diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..168addfbc --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,3 @@ +e8424f2000222490850d2a5227b6b6b0c0a5d6ce +33d0737d1d4a6d8a7f0fa3bf2af2b242b545dc69 +631873465238400f8ed8113ac87d63c3d6edf617 \ No newline at end of file diff --git a/4J.Input/4J_Input.cpp b/4J.Input/4J_Input.cpp index 2d8486e2b..499b5f742 100644 --- a/4J.Input/4J_Input.cpp +++ b/4J.Input/4J_Input.cpp @@ -8,52 +8,69 @@ C_4JInput InputManager; -static const int KEY_COUNT = SDL_NUM_SCANCODES; +static const int KEY_COUNT = SDL_NUM_SCANCODES; static const float MOUSE_SCALE = 0.015f; // Vars static bool s_sdlInitialized = false; static bool s_keysCurrent[KEY_COUNT] = {}; -static bool s_keysPrev [KEY_COUNT] = {}; -static bool s_mouseLeftCurrent = false, s_mouseLeftPrev = false; +static bool s_keysPrev[KEY_COUNT] = {}; +static bool s_mouseLeftCurrent = false, s_mouseLeftPrev = false; static bool s_mouseRightCurrent = false, s_mouseRightPrev = false; -static bool s_menuDisplayed[4] = {}; +static bool s_menuDisplayed[4] = {}; static bool s_prevMenuDisplayed = false; static bool s_snapTaken = false; static float s_accumRelX = 0, s_accumRelY = 0; -static float s_snapRelX = 0, s_snapRelY = 0; +static float s_snapRelX = 0, s_snapRelY = 0; -static int s_scrollTicksForButtonPressed = 0; -static int s_scrollTicksForGetValue = 0; -static int s_scrollTicksSnap = 0; -static bool s_scrollSnapTaken = false; +static int s_scrollTicksForButtonPressed = 0; +static int s_scrollTicksForGetValue = 0; +static int s_scrollTicksSnap = 0; +static bool s_scrollSnapTaken = false; // We set all the watched keys // I don't know if I'll need to change this if we add chat support soon. static const int s_watchedKeys[] = { - SDL_SCANCODE_W, SDL_SCANCODE_A, SDL_SCANCODE_S, SDL_SCANCODE_D, - SDL_SCANCODE_SPACE, SDL_SCANCODE_LSHIFT, SDL_SCANCODE_RSHIFT, - SDL_SCANCODE_E, SDL_SCANCODE_Q, SDL_SCANCODE_F, - SDL_SCANCODE_C, SDL_SCANCODE_ESCAPE, SDL_SCANCODE_RETURN, - SDL_SCANCODE_F3, SDL_SCANCODE_F5, - SDL_SCANCODE_UP, SDL_SCANCODE_DOWN, SDL_SCANCODE_LEFT, SDL_SCANCODE_RIGHT, - SDL_SCANCODE_PAGEUP, SDL_SCANCODE_PAGEDOWN, - SDL_SCANCODE_TAB, SDL_SCANCODE_LCTRL, SDL_SCANCODE_RCTRL, - SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_3, SDL_SCANCODE_4, - SDL_SCANCODE_5, SDL_SCANCODE_6, SDL_SCANCODE_7, SDL_SCANCODE_8, - SDL_SCANCODE_9, + SDL_SCANCODE_W, SDL_SCANCODE_A, SDL_SCANCODE_S, + SDL_SCANCODE_D, SDL_SCANCODE_SPACE, SDL_SCANCODE_LSHIFT, + SDL_SCANCODE_RSHIFT, SDL_SCANCODE_E, SDL_SCANCODE_Q, + SDL_SCANCODE_F, SDL_SCANCODE_C, SDL_SCANCODE_ESCAPE, + SDL_SCANCODE_RETURN, SDL_SCANCODE_F3, SDL_SCANCODE_F5, + SDL_SCANCODE_UP, SDL_SCANCODE_DOWN, SDL_SCANCODE_LEFT, + SDL_SCANCODE_RIGHT, SDL_SCANCODE_PAGEUP, SDL_SCANCODE_PAGEDOWN, + SDL_SCANCODE_TAB, SDL_SCANCODE_LCTRL, SDL_SCANCODE_RCTRL, + SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_3, + SDL_SCANCODE_4, SDL_SCANCODE_5, SDL_SCANCODE_6, + SDL_SCANCODE_7, SDL_SCANCODE_8, SDL_SCANCODE_9, }; -static const int s_watchedKeyCount = (int)(sizeof(s_watchedKeys) / sizeof(s_watchedKeys[0])); +static const int s_watchedKeyCount = + (int)(sizeof(s_watchedKeys) / sizeof(s_watchedKeys[0])); -static inline bool KDown (int sc) { return (sc > 0 && sc < KEY_COUNT) ? s_keysCurrent[sc] : false; } -static inline bool KPressed (int sc) { return (sc > 0 && sc < KEY_COUNT) ? !s_keysPrev[sc] && s_keysCurrent[sc] : false; } -static inline bool KReleased(int sc) { return (sc > 0 && sc < KEY_COUNT) ? s_keysPrev[sc] && !s_keysCurrent[sc] : false; } +static inline bool KDown(int sc) { + return (sc > 0 && sc < KEY_COUNT) ? s_keysCurrent[sc] : false; +} +static inline bool KPressed(int sc) { + return (sc > 0 && sc < KEY_COUNT) ? !s_keysPrev[sc] && s_keysCurrent[sc] + : false; +} +static inline bool KReleased(int sc) { + return (sc > 0 && sc < KEY_COUNT) ? s_keysPrev[sc] && !s_keysCurrent[sc] + : false; +} -static inline bool MouseLDown () { return s_mouseLeftCurrent; } -static inline bool MouseLPressed () { return s_mouseLeftCurrent && !s_mouseLeftPrev; } -static inline bool MouseLReleased() { return !s_mouseLeftCurrent && s_mouseLeftPrev; } -static inline bool MouseRDown () { return s_mouseRightCurrent; } -static inline bool MouseRPressed () { return s_mouseRightCurrent && !s_mouseRightPrev; } -static inline bool MouseRReleased() { return !s_mouseRightCurrent && s_mouseRightPrev; } +static inline bool MouseLDown() { return s_mouseLeftCurrent; } +static inline bool MouseLPressed() { + return s_mouseLeftCurrent && !s_mouseLeftPrev; +} +static inline bool MouseLReleased() { + return !s_mouseLeftCurrent && s_mouseLeftPrev; +} +static inline bool MouseRDown() { return s_mouseRightCurrent; } +static inline bool MouseRPressed() { + return s_mouseRightCurrent && !s_mouseRightPrev; +} +static inline bool MouseRReleased() { + return !s_mouseRightCurrent && s_mouseRightPrev; +} // get directly into SDL events before the game queue can steal them. // this took me a while. @@ -91,8 +108,10 @@ static int ScrollSnap() { static void TakeSnapIfNeeded() { if (!s_snapTaken) { - s_snapRelX = s_accumRelX; s_accumRelX = 0; - s_snapRelY = s_accumRelY; s_accumRelY = 0; + s_snapRelX = s_accumRelX; + s_accumRelX = 0; + s_snapRelY = s_accumRelY; + s_accumRelY = 0; s_snapTaken = true; } } @@ -106,27 +125,29 @@ void C_4JInput::Initialise(int, unsigned char, unsigned char, unsigned char) { s_sdlInitialized = true; } - memset(s_keysCurrent, 0, sizeof(s_keysCurrent)); - memset(s_keysPrev, 0, sizeof(s_keysPrev)); + memset(s_keysCurrent, 0, sizeof(s_keysCurrent)); + memset(s_keysPrev, 0, sizeof(s_keysPrev)); memset(s_menuDisplayed, 0, sizeof(s_menuDisplayed)); - s_mouseLeftCurrent = s_mouseLeftPrev = s_mouseRightCurrent = s_mouseRightPrev = false; + s_mouseLeftCurrent = s_mouseLeftPrev = s_mouseRightCurrent = + s_mouseRightPrev = false; s_accumRelX = s_accumRelY = s_snapRelX = s_snapRelY = 0; // i really gotta name these vars better.. - s_scrollTicksForButtonPressed = s_scrollTicksForGetValue = s_scrollTicksSnap = 0; + s_scrollTicksForButtonPressed = s_scrollTicksForGetValue = + s_scrollTicksSnap = 0; s_snapTaken = s_scrollSnapTaken = s_prevMenuDisplayed = false; - if (s_sdlInitialized) - SDL_SetRelativeMouseMode(SDL_TRUE); + if (s_sdlInitialized) SDL_SetRelativeMouseMode(SDL_TRUE); } -// Each tick we update the input state by polling SDL, this is where we get the kbd and mouse state. +// Each tick we update the input state by polling SDL, this is where we get the +// kbd and mouse state. void C_4JInput::Tick() { if (!s_sdlInitialized) return; memcpy(s_keysPrev, s_keysCurrent, sizeof(s_keysCurrent)); - s_mouseLeftPrev = s_mouseLeftCurrent; + s_mouseLeftPrev = s_mouseLeftCurrent; s_mouseRightPrev = s_mouseRightCurrent; - s_snapTaken = false; + s_snapTaken = false; s_scrollSnapTaken = false; s_snapRelX = s_snapRelY = 0; s_scrollTicksSnap = 0; @@ -137,14 +158,14 @@ void C_4JInput::Tick() { s_scrollTicksForGetValue = 0; } - const Uint8 *state = SDL_GetKeyboardState(NULL); + const Uint8* state = SDL_GetKeyboardState(NULL); for (int i = 0; i < s_watchedKeyCount; ++i) { int sc = s_watchedKeys[i]; if (sc > 0 && sc < KEY_COUNT) s_keysCurrent[sc] = state[sc] != 0; } Uint32 btns = SDL_GetMouseState(NULL, NULL); - s_mouseLeftCurrent = (btns & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; + s_mouseLeftCurrent = (btns & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; s_mouseRightCurrent = (btns & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; if (!SDL_GetRelativeMouseMode()) { @@ -153,8 +174,11 @@ void C_4JInput::Tick() { } if (!SDL_GetKeyboardFocus()) { - SDL_Window *mf = SDL_GetMouseFocus(); - if (mf) { SDL_RaiseWindow(mf); SDL_SetWindowGrab(mf, SDL_TRUE); } + SDL_Window* mf = SDL_GetMouseFocus(); + if (mf) { + SDL_RaiseWindow(mf); + SDL_SetWindowGrab(mf, SDL_TRUE); + } } } @@ -164,9 +188,9 @@ int C_4JInput::GetHotbarSlotPressed(int iPad) { constexpr size_t NUM_HOTBAR_SLOTS = 9; static const int sc[NUM_HOTBAR_SLOTS] = { - SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_3, SDL_SCANCODE_4, - SDL_SCANCODE_5, SDL_SCANCODE_6, SDL_SCANCODE_7, SDL_SCANCODE_8, - SDL_SCANCODE_9, + SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_3, + SDL_SCANCODE_4, SDL_SCANCODE_5, SDL_SCANCODE_6, + SDL_SCANCODE_7, SDL_SCANCODE_8, SDL_SCANCODE_9, }; static bool s_wasDown[NUM_HOTBAR_SLOTS] = {}; @@ -179,31 +203,55 @@ int C_4JInput::GetHotbarSlotPressed(int iPad) { return -1; } -#define ACTION_CASES(FN) \ -case ACTION_MENU_UP: return FN(SDL_SCANCODE_UP); \ -case ACTION_MENU_DOWN: return FN(SDL_SCANCODE_DOWN); \ -case ACTION_MENU_LEFT: return FN(SDL_SCANCODE_LEFT); \ -case ACTION_MENU_RIGHT: return FN(SDL_SCANCODE_RIGHT); \ -case ACTION_MENU_PAGEUP: return FN(SDL_SCANCODE_PAGEUP); \ -case ACTION_MENU_PAGEDOWN: return FN(SDL_SCANCODE_PAGEDOWN); \ -case ACTION_MENU_OK: return FN(SDL_SCANCODE_RETURN); \ -case ACTION_MENU_CANCEL: return FN(SDL_SCANCODE_ESCAPE); \ -case MINECRAFT_ACTION_JUMP: return FN(SDL_SCANCODE_SPACE); \ -case MINECRAFT_ACTION_FORWARD: return FN(SDL_SCANCODE_W); \ -case MINECRAFT_ACTION_BACKWARD: return FN(SDL_SCANCODE_S); \ -case MINECRAFT_ACTION_LEFT: return FN(SDL_SCANCODE_A); \ -case MINECRAFT_ACTION_RIGHT: return FN(SDL_SCANCODE_D); \ -case MINECRAFT_ACTION_INVENTORY: return FN(SDL_SCANCODE_E); \ -case MINECRAFT_ACTION_PAUSEMENU: return FN(SDL_SCANCODE_ESCAPE); \ -case MINECRAFT_ACTION_DROP: return FN(SDL_SCANCODE_Q); \ -case MINECRAFT_ACTION_CRAFTING: return FN(SDL_SCANCODE_C); \ -case MINECRAFT_ACTION_RENDER_THIRD_PERSON:return FN(SDL_SCANCODE_F5); \ -case MINECRAFT_ACTION_GAME_INFO: return FN(SDL_SCANCODE_F3); \ -case MINECRAFT_ACTION_DPAD_LEFT: return FN(SDL_SCANCODE_LEFT); \ -case MINECRAFT_ACTION_DPAD_RIGHT: return FN(SDL_SCANCODE_RIGHT); \ -case MINECRAFT_ACTION_DPAD_UP: return FN(SDL_SCANCODE_UP); \ -case MINECRAFT_ACTION_DPAD_DOWN: return FN(SDL_SCANCODE_DOWN); \ -default: return false; +#define ACTION_CASES(FN) \ + case ACTION_MENU_UP: \ + return FN(SDL_SCANCODE_UP); \ + case ACTION_MENU_DOWN: \ + return FN(SDL_SCANCODE_DOWN); \ + case ACTION_MENU_LEFT: \ + return FN(SDL_SCANCODE_LEFT); \ + case ACTION_MENU_RIGHT: \ + return FN(SDL_SCANCODE_RIGHT); \ + case ACTION_MENU_PAGEUP: \ + return FN(SDL_SCANCODE_PAGEUP); \ + case ACTION_MENU_PAGEDOWN: \ + return FN(SDL_SCANCODE_PAGEDOWN); \ + case ACTION_MENU_OK: \ + return FN(SDL_SCANCODE_RETURN); \ + case ACTION_MENU_CANCEL: \ + return FN(SDL_SCANCODE_ESCAPE); \ + case MINECRAFT_ACTION_JUMP: \ + return FN(SDL_SCANCODE_SPACE); \ + case MINECRAFT_ACTION_FORWARD: \ + return FN(SDL_SCANCODE_W); \ + case MINECRAFT_ACTION_BACKWARD: \ + return FN(SDL_SCANCODE_S); \ + case MINECRAFT_ACTION_LEFT: \ + return FN(SDL_SCANCODE_A); \ + case MINECRAFT_ACTION_RIGHT: \ + return FN(SDL_SCANCODE_D); \ + case MINECRAFT_ACTION_INVENTORY: \ + return FN(SDL_SCANCODE_E); \ + case MINECRAFT_ACTION_PAUSEMENU: \ + return FN(SDL_SCANCODE_ESCAPE); \ + case MINECRAFT_ACTION_DROP: \ + return FN(SDL_SCANCODE_Q); \ + case MINECRAFT_ACTION_CRAFTING: \ + return FN(SDL_SCANCODE_C); \ + case MINECRAFT_ACTION_RENDER_THIRD_PERSON: \ + return FN(SDL_SCANCODE_F5); \ + case MINECRAFT_ACTION_GAME_INFO: \ + return FN(SDL_SCANCODE_F3); \ + case MINECRAFT_ACTION_DPAD_LEFT: \ + return FN(SDL_SCANCODE_LEFT); \ + case MINECRAFT_ACTION_DPAD_RIGHT: \ + return FN(SDL_SCANCODE_RIGHT); \ + case MINECRAFT_ACTION_DPAD_UP: \ + return FN(SDL_SCANCODE_UP); \ + case MINECRAFT_ACTION_DPAD_DOWN: \ + return FN(SDL_SCANCODE_DOWN); \ + default: \ + return false; bool C_4JInput::ButtonDown(int iPad, unsigned char ucAction) { if (iPad != 0) return false; @@ -213,45 +261,64 @@ bool C_4JInput::ButtonDown(int iPad, unsigned char ucAction) { return s_mouseLeftCurrent || s_mouseRightCurrent; } switch (ucAction) { - case MINECRAFT_ACTION_ACTION: return MouseLDown() || KDown(SDL_SCANCODE_RETURN); - case MINECRAFT_ACTION_USE: return MouseRDown() || KDown(SDL_SCANCODE_F); - case MINECRAFT_ACTION_SNEAK_TOGGLE: return KDown(SDL_SCANCODE_LSHIFT) || KDown(SDL_SCANCODE_RSHIFT); - case MINECRAFT_ACTION_SPRINT: return KDown(SDL_SCANCODE_LCTRL) || KDown(SDL_SCANCODE_RCTRL); + case MINECRAFT_ACTION_ACTION: + return MouseLDown() || KDown(SDL_SCANCODE_RETURN); + case MINECRAFT_ACTION_USE: + return MouseRDown() || KDown(SDL_SCANCODE_F); + case MINECRAFT_ACTION_SNEAK_TOGGLE: + return KDown(SDL_SCANCODE_LSHIFT) || KDown(SDL_SCANCODE_RSHIFT); + case MINECRAFT_ACTION_SPRINT: + return KDown(SDL_SCANCODE_LCTRL) || KDown(SDL_SCANCODE_RCTRL); case MINECRAFT_ACTION_LEFT_SCROLL: - case ACTION_MENU_LEFT_SCROLL: return ScrollSnap() > 0; + case ACTION_MENU_LEFT_SCROLL: + return ScrollSnap() > 0; case MINECRAFT_ACTION_RIGHT_SCROLL: - case ACTION_MENU_RIGHT_SCROLL: return ScrollSnap() < 0; - ACTION_CASES(KDown) + case ACTION_MENU_RIGHT_SCROLL: + return ScrollSnap() < 0; + ACTION_CASES(KDown) } } // The part that handles completing the action of pressing a button. bool C_4JInput::ButtonPressed(int iPad, unsigned char ucAction) { if (iPad != 0 || ucAction == 255) return false; switch (ucAction) { - case MINECRAFT_ACTION_ACTION: return MouseLPressed() || KPressed(SDL_SCANCODE_RETURN); - case MINECRAFT_ACTION_USE: return MouseRPressed() || KPressed(SDL_SCANCODE_F); - case MINECRAFT_ACTION_SNEAK_TOGGLE: return KPressed(SDL_SCANCODE_LSHIFT) || KPressed(SDL_SCANCODE_RSHIFT); - case MINECRAFT_ACTION_SPRINT: return KPressed(SDL_SCANCODE_LCTRL) || KPressed(SDL_SCANCODE_RCTRL); + case MINECRAFT_ACTION_ACTION: + return MouseLPressed() || KPressed(SDL_SCANCODE_RETURN); + case MINECRAFT_ACTION_USE: + return MouseRPressed() || KPressed(SDL_SCANCODE_F); + case MINECRAFT_ACTION_SNEAK_TOGGLE: + return KPressed(SDL_SCANCODE_LSHIFT) || + KPressed(SDL_SCANCODE_RSHIFT); + case MINECRAFT_ACTION_SPRINT: + return KPressed(SDL_SCANCODE_LCTRL) || KPressed(SDL_SCANCODE_RCTRL); case MINECRAFT_ACTION_LEFT_SCROLL: - case ACTION_MENU_LEFT_SCROLL: return ScrollSnap() > 0; + case ACTION_MENU_LEFT_SCROLL: + return ScrollSnap() > 0; case MINECRAFT_ACTION_RIGHT_SCROLL: - case ACTION_MENU_RIGHT_SCROLL: return ScrollSnap() < 0; - ACTION_CASES(KPressed) + case ACTION_MENU_RIGHT_SCROLL: + return ScrollSnap() < 0; + ACTION_CASES(KPressed) } } // The part that handles Releasing a button. bool C_4JInput::ButtonReleased(int iPad, unsigned char ucAction) { if (iPad != 0 || ucAction == 255) return false; switch (ucAction) { - case MINECRAFT_ACTION_ACTION: return MouseLReleased() || KReleased(SDL_SCANCODE_RETURN); - case MINECRAFT_ACTION_USE: return MouseRReleased() || KReleased(SDL_SCANCODE_F); - case MINECRAFT_ACTION_SNEAK_TOGGLE: return KReleased(SDL_SCANCODE_LSHIFT) || KReleased(SDL_SCANCODE_RSHIFT); - case MINECRAFT_ACTION_SPRINT: KReleased(SDL_SCANCODE_LCTRL) || KReleased(SDL_SCANCODE_RCTRL); + case MINECRAFT_ACTION_ACTION: + return MouseLReleased() || KReleased(SDL_SCANCODE_RETURN); + case MINECRAFT_ACTION_USE: + return MouseRReleased() || KReleased(SDL_SCANCODE_F); + case MINECRAFT_ACTION_SNEAK_TOGGLE: + return KReleased(SDL_SCANCODE_LSHIFT) || + KReleased(SDL_SCANCODE_RSHIFT); + case MINECRAFT_ACTION_SPRINT: + KReleased(SDL_SCANCODE_LCTRL) || KReleased(SDL_SCANCODE_RCTRL); case MINECRAFT_ACTION_LEFT_SCROLL: case ACTION_MENU_LEFT_SCROLL: case MINECRAFT_ACTION_RIGHT_SCROLL: - case ACTION_MENU_RIGHT_SCROLL: return false; - ACTION_CASES(KReleased) + case ACTION_MENU_RIGHT_SCROLL: + return false; + ACTION_CASES(KReleased) } } @@ -275,17 +342,20 @@ unsigned int C_4JInput::GetValue(int iPad, unsigned char ucAction, bool) { } return ButtonDown(iPad, ucAction) ? 1u : 0u; } -// Left stick movement, the one that moves the player around or selects menu options. (Soon be tested.) +// Left stick movement, the one that moves the player around or selects menu +// options. (Soon be tested.) float C_4JInput::GetJoypadStick_LX(int, bool) { - return (KDown(SDL_SCANCODE_D) ? 1.f : 0.f) - (KDown(SDL_SCANCODE_A) ? 1.f : 0.f); + return (KDown(SDL_SCANCODE_D) ? 1.f : 0.f) - + (KDown(SDL_SCANCODE_A) ? 1.f : 0.f); } float C_4JInput::GetJoypadStick_LY(int, bool) { - return (KDown(SDL_SCANCODE_W) ? 1.f : 0.f) - (KDown(SDL_SCANCODE_S) ? 1.f : 0.f); + return (KDown(SDL_SCANCODE_W) ? 1.f : 0.f) - + (KDown(SDL_SCANCODE_S) ? 1.f : 0.f); } -// We use mouse movement and convert it into a Right Stick output using logarithmic scaling -// This is the most important mouse part. Yet it's so small. +// We use mouse movement and convert it into a Right Stick output using +// logarithmic scaling This is the most important mouse part. Yet it's so small. static float MouseAxis(float raw) { - if (fabsf(raw) < 0.0001f) return 0.f; // from 4j previous code + if (fabsf(raw) < 0.0001f) return 0.f; // from 4j previous code return (raw >= 0.f ? 1.f : -1.f) * sqrtf(fabsf(raw)); } // We apply the Stick movement on the R(Right) X(2D Position) @@ -301,9 +371,14 @@ float C_4JInput::GetJoypadStick_RY(int, bool) { return MouseAxis(-s_snapRelY * MOUSE_SCALE); } -unsigned char C_4JInput::GetJoypadLTrigger(int, bool) { return s_mouseRightCurrent ? 255 : 0; } -unsigned char C_4JInput::GetJoypadRTrigger(int, bool) { return s_mouseLeftCurrent ? 255 : 0; } -// We detect if a Menu is visible on the player's screen to the mouse being stuck. +unsigned char C_4JInput::GetJoypadLTrigger(int, bool) { + return s_mouseRightCurrent ? 255 : 0; +} +unsigned char C_4JInput::GetJoypadRTrigger(int, bool) { + return s_mouseLeftCurrent ? 255 : 0; +} +// We detect if a Menu is visible on the player's screen to the mouse being +// stuck. void C_4JInput::SetMenuDisplayed(int iPad, bool bVal) { if (iPad >= 0 && iPad < 4) s_menuDisplayed[iPad] = bVal; if (!s_sdlInitialized || bVal == s_prevMenuDisplayed) return; @@ -311,31 +386,43 @@ void C_4JInput::SetMenuDisplayed(int iPad, bool bVal) { s_prevMenuDisplayed = bVal; } -int C_4JInput::GetScrollDelta() { +int C_4JInput::GetScrollDelta() { int v = s_scrollTicksForButtonPressed; s_scrollTicksForButtonPressed = 0; return v; } -void C_4JInput::SetDeadzoneAndMovementRange(unsigned int, unsigned int){} -void C_4JInput::SetGameJoypadMaps(unsigned char, unsigned char, unsigned int){} -unsigned int C_4JInput::GetGameJoypadMaps(unsigned char, unsigned char){ return 0; } -void C_4JInput::SetJoypadMapVal(int, unsigned char){} -unsigned char C_4JInput::GetJoypadMapVal(int){ return 0; } -void C_4JInput::SetJoypadSensitivity(int, float){} -void C_4JInput::SetJoypadStickAxisMap(int, unsigned int, unsigned int){} -void C_4JInput::SetJoypadStickTriggerMap(int, unsigned int, unsigned int){} -void C_4JInput::SetKeyRepeatRate(float, float){} -void C_4JInput::SetDebugSequence(const char*, int(*)(void *), void *){} -FLOAT C_4JInput::GetIdleSeconds(int){ return 0.f; } -bool C_4JInput::IsPadConnected(int iPad){ return iPad == 0; } +void C_4JInput::SetDeadzoneAndMovementRange(unsigned int, unsigned int) {} +void C_4JInput::SetGameJoypadMaps(unsigned char, unsigned char, unsigned int) {} +unsigned int C_4JInput::GetGameJoypadMaps(unsigned char, unsigned char) { + return 0; +} +void C_4JInput::SetJoypadMapVal(int, unsigned char) {} +unsigned char C_4JInput::GetJoypadMapVal(int) { return 0; } +void C_4JInput::SetJoypadSensitivity(int, float) {} +void C_4JInput::SetJoypadStickAxisMap(int, unsigned int, unsigned int) {} +void C_4JInput::SetJoypadStickTriggerMap(int, unsigned int, unsigned int) {} +void C_4JInput::SetKeyRepeatRate(float, float) {} +void C_4JInput::SetDebugSequence(const char*, int (*)(void*), void*) {} +FLOAT C_4JInput::GetIdleSeconds(int) { return 0.f; } +bool C_4JInput::IsPadConnected(int iPad) { return iPad == 0; } // Silly check, we check if we have a keyboard. -EKeyboardResult C_4JInput::RequestKeyboard(const wchar_t *, const wchar_t *, int, unsigned int, - int(*)(void *, const bool), void *, C_4JInput::EKeyboardMode) -{ return EKeyboard_Cancelled; } +EKeyboardResult C_4JInput::RequestKeyboard(const wchar_t*, const wchar_t*, int, + unsigned int, + int (*)(void*, const bool), void*, + C_4JInput::EKeyboardMode) { + return EKeyboard_Cancelled; +} -void C_4JInput::GetText(uint16_t *s){ if (s) s[0] = 0; } -bool C_4JInput::VerifyStrings(wchar_t **, int, int(*)(void *, STRING_VERIFY_RESPONSE *), void *){ return true; } -void C_4JInput::CancelQueuedVerifyStrings(int(*)(void *, STRING_VERIFY_RESPONSE *), void *){} -void C_4JInput::CancelAllVerifyInProgress(){} +void C_4JInput::GetText(uint16_t* s) { + if (s) s[0] = 0; +} +bool C_4JInput::VerifyStrings(wchar_t**, int, + int (*)(void*, STRING_VERIFY_RESPONSE*), void*) { + return true; +} +void C_4JInput::CancelQueuedVerifyStrings(int (*)(void*, + STRING_VERIFY_RESPONSE*), + void*) {} +void C_4JInput::CancelAllVerifyInProgress() {} diff --git a/4J.Input/4J_Input.h b/4J.Input/4J_Input.h index 511a92ee6..85ee8b5bd 100644 --- a/4J.Input/4J_Input.h +++ b/4J.Input/4J_Input.h @@ -1,138 +1,163 @@ #pragma once -#define MAP_STYLE_0 0 -#define MAP_STYLE_1 1 -#define MAP_STYLE_2 2 +#define MAP_STYLE_0 0 +#define MAP_STYLE_1 1 +#define MAP_STYLE_2 2 -#define _360_JOY_BUTTON_A 0x00000001 -#define _360_JOY_BUTTON_B 0x00000002 -#define _360_JOY_BUTTON_X 0x00000004 -#define _360_JOY_BUTTON_Y 0x00000008 +#define _360_JOY_BUTTON_A 0x00000001 +#define _360_JOY_BUTTON_B 0x00000002 +#define _360_JOY_BUTTON_X 0x00000004 +#define _360_JOY_BUTTON_Y 0x00000008 -#define _360_JOY_BUTTON_START 0x00000010 -#define _360_JOY_BUTTON_BACK 0x00000020 -#define _360_JOY_BUTTON_RB 0x00000040 -#define _360_JOY_BUTTON_LB 0x00000080 +#define _360_JOY_BUTTON_START 0x00000010 +#define _360_JOY_BUTTON_BACK 0x00000020 +#define _360_JOY_BUTTON_RB 0x00000040 +#define _360_JOY_BUTTON_LB 0x00000080 -#define _360_JOY_BUTTON_RTHUMB 0x00000100 -#define _360_JOY_BUTTON_LTHUMB 0x00000200 -#define _360_JOY_BUTTON_DPAD_UP 0x00000400 -#define _360_JOY_BUTTON_DPAD_DOWN 0x00000800 +#define _360_JOY_BUTTON_RTHUMB 0x00000100 +#define _360_JOY_BUTTON_LTHUMB 0x00000200 +#define _360_JOY_BUTTON_DPAD_UP 0x00000400 +#define _360_JOY_BUTTON_DPAD_DOWN 0x00000800 -#define _360_JOY_BUTTON_DPAD_LEFT 0x00001000 -#define _360_JOY_BUTTON_DPAD_RIGHT 0x00002000 -// fake digital versions of analog values -#define _360_JOY_BUTTON_LSTICK_RIGHT 0x00004000 -#define _360_JOY_BUTTON_LSTICK_LEFT 0x00008000 +#define _360_JOY_BUTTON_DPAD_LEFT 0x00001000 +#define _360_JOY_BUTTON_DPAD_RIGHT 0x00002000 +// fake digital versions of analog values +#define _360_JOY_BUTTON_LSTICK_RIGHT 0x00004000 +#define _360_JOY_BUTTON_LSTICK_LEFT 0x00008000 -#define _360_JOY_BUTTON_RSTICK_DOWN 0x00010000 -#define _360_JOY_BUTTON_RSTICK_UP 0x00020000 -#define _360_JOY_BUTTON_RSTICK_RIGHT 0x00040000 -#define _360_JOY_BUTTON_RSTICK_LEFT 0x00080000 +#define _360_JOY_BUTTON_RSTICK_DOWN 0x00010000 +#define _360_JOY_BUTTON_RSTICK_UP 0x00020000 +#define _360_JOY_BUTTON_RSTICK_RIGHT 0x00040000 +#define _360_JOY_BUTTON_RSTICK_LEFT 0x00080000 -#define _360_JOY_BUTTON_LSTICK_DOWN 0x00100000 -#define _360_JOY_BUTTON_LSTICK_UP 0x00200000 -#define _360_JOY_BUTTON_RT 0x00400000 -#define _360_JOY_BUTTON_LT 0x00800000 +#define _360_JOY_BUTTON_LSTICK_DOWN 0x00100000 +#define _360_JOY_BUTTON_LSTICK_UP 0x00200000 +#define _360_JOY_BUTTON_RT 0x00400000 +#define _360_JOY_BUTTON_LT 0x00800000 // Stick axis maps - to allow changes for SouthPaw in-game axis mapping -#define AXIS_MAP_LX 0 -#define AXIS_MAP_LY 1 -#define AXIS_MAP_RX 2 -#define AXIS_MAP_RY 3 +#define AXIS_MAP_LX 0 +#define AXIS_MAP_LY 1 +#define AXIS_MAP_RX 2 +#define AXIS_MAP_RY 3 // Trigger map - to allow for swap triggers in-game -#define TRIGGER_MAP_0 0 -#define TRIGGER_MAP_1 1 +#define TRIGGER_MAP_0 0 +#define TRIGGER_MAP_1 1 -enum EKeyboardResult -{ - EKeyboard_Pending, - EKeyboard_Cancelled, - EKeyboard_ResultAccept, - EKeyboard_ResultDecline, +enum EKeyboardResult { + EKeyboard_Pending, + EKeyboard_Cancelled, + EKeyboard_ResultAccept, + EKeyboard_ResultDecline, }; -typedef struct _STRING_VERIFY_RESPONSE -{ - WORD wNumStrings; - HRESULT *pStringResult; -} -STRING_VERIFY_RESPONSE; +typedef struct _STRING_VERIFY_RESPONSE { + WORD wNumStrings; + HRESULT* pStringResult; +} STRING_VERIFY_RESPONSE; -class C_4JInput -{ +class C_4JInput { public: + enum EKeyboardMode { + EKeyboardMode_Default, + EKeyboardMode_Numeric, + EKeyboardMode_Password, + EKeyboardMode_Alphabet, + EKeyboardMode_Full, + EKeyboardMode_Alphabet_Extended, + EKeyboardMode_IP_Address, + EKeyboardMode_Phone + }; + void Initialise(int iInputStateC, unsigned char ucMapC, + unsigned char ucActionC, unsigned char ucMenuActionC); + void Tick(void); + void SetDeadzoneAndMovementRange(unsigned int uiDeadzone, + unsigned int uiMovementRangeMax); + void SetGameJoypadMaps(unsigned char ucMap, unsigned char ucAction, + unsigned int uiActionVal); + unsigned int GetGameJoypadMaps(unsigned char ucMap, unsigned char ucAction); + void SetJoypadMapVal(int iPad, unsigned char ucMap); + unsigned char GetJoypadMapVal(int iPad); + void SetJoypadSensitivity(int iPad, float fSensitivity); + unsigned int GetValue(int iPad, unsigned char ucAction, + bool bRepeat = false); + bool ButtonPressed(int iPad, unsigned char ucAction = 255); // toggled + bool ButtonReleased(int iPad, unsigned char ucAction); // toggled + bool ButtonDown(int iPad, + unsigned char ucAction = 255); // button held down + // Functions to remap the axis and triggers for in-game (not menus) - + // SouthPaw, etc + void SetJoypadStickAxisMap(int iPad, unsigned int uiFrom, + unsigned int uiTo); + void SetJoypadStickTriggerMap(int iPad, unsigned int uiFrom, + unsigned int uiTo); + void SetKeyRepeatRate(float fRepeatDelaySecs, float fRepeatRateSecs); + void SetDebugSequence(const char* chSequenceA, int (*Func)(void*), + void* lpParam); + FLOAT GetIdleSeconds(int iPad); + bool IsPadConnected(int iPad); - enum EKeyboardMode - { - EKeyboardMode_Default, - EKeyboardMode_Numeric, - EKeyboardMode_Password, - EKeyboardMode_Alphabet, - EKeyboardMode_Full, - EKeyboardMode_Alphabet_Extended, - EKeyboardMode_IP_Address, - EKeyboardMode_Phone - }; + // In-Game values which may have been remapped due to Southpaw, swap + // triggers, etc + float GetJoypadStick_LX(int iPad, bool bCheckMenuDisplay = true); + float GetJoypadStick_LY(int iPad, bool bCheckMenuDisplay = true); + float GetJoypadStick_RX(int iPad, bool bCheckMenuDisplay = true); + float GetJoypadStick_RY(int iPad, bool bCheckMenuDisplay = true); + unsigned char GetJoypadLTrigger(int iPad, bool bCheckMenuDisplay = true); + unsigned char GetJoypadRTrigger(int iPad, bool bCheckMenuDisplay = true); - void Initialise( int iInputStateC, unsigned char ucMapC,unsigned char ucActionC, unsigned char ucMenuActionC ); - void Tick(void); - void SetDeadzoneAndMovementRange(unsigned int uiDeadzone, unsigned int uiMovementRangeMax ); - void SetGameJoypadMaps(unsigned char ucMap,unsigned char ucAction,unsigned int uiActionVal); - unsigned int GetGameJoypadMaps(unsigned char ucMap,unsigned char ucAction); - void SetJoypadMapVal(int iPad,unsigned char ucMap); - unsigned char GetJoypadMapVal(int iPad); - void SetJoypadSensitivity(int iPad, float fSensitivity); - unsigned int GetValue(int iPad,unsigned char ucAction, bool bRepeat=false); - bool ButtonPressed(int iPad,unsigned char ucAction=255); // toggled - bool ButtonReleased(int iPad,unsigned char ucAction); //toggled - bool ButtonDown(int iPad,unsigned char ucAction=255); // button held down - // Functions to remap the axis and triggers for in-game (not menus) - SouthPaw, etc - void SetJoypadStickAxisMap(int iPad,unsigned int uiFrom, unsigned int uiTo); - void SetJoypadStickTriggerMap(int iPad,unsigned int uiFrom, unsigned int uiTo); - void SetKeyRepeatRate(float fRepeatDelaySecs,float fRepeatRateSecs); - void SetDebugSequence( const char *chSequenceA,int( *Func)(void *),void *lpParam ); - FLOAT GetIdleSeconds(int iPad); - bool IsPadConnected(int iPad); + void SetMenuDisplayed(int iPad, bool bVal); + int GetHotbarSlotPressed(int iPad); + int GetScrollDelta(); - // In-Game values which may have been remapped due to Southpaw, swap triggers, etc - float GetJoypadStick_LX(int iPad, bool bCheckMenuDisplay=true); - float GetJoypadStick_LY(int iPad, bool bCheckMenuDisplay=true); - float GetJoypadStick_RX(int iPad, bool bCheckMenuDisplay=true); - float GetJoypadStick_RY(int iPad, bool bCheckMenuDisplay=true); - unsigned char GetJoypadLTrigger(int iPad, bool bCheckMenuDisplay=true); - unsigned char GetJoypadRTrigger(int iPad, bool bCheckMenuDisplay=true); + // EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT + // uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( + // *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode + // eMode,C4JStringTable *pStringTable=NULL); EKeyboardResult + // RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD + // dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const + // bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable + // *pStringTable=NULL); + EKeyboardResult RequestKeyboard(const wchar_t* Title, const wchar_t* Text, + int iPad, unsigned int uiMaxChars, + int (*Func)(void*, const bool), + void* lpParam, + C_4JInput::EKeyboardMode eMode); + void GetText(uint16_t* UTF16String); - void SetMenuDisplayed(int iPad, bool bVal); - int GetHotbarSlotPressed(int iPad); - int GetScrollDelta(); + // Online check strings against offensive list - TCR 92 + // TCR # 092 CMTV Player Text String Verification + // Requirement Any player-entered text visible to another player on + // Xbox LIVE must be verified using the Xbox LIVE service before being + // transmitted. Text that is rejected by the Xbox LIVE service must not be + // displayed. + // + // Remarks + // This requirement applies to any player-entered string that can + // be exposed to other players on Xbox LIVE. It includes session names, + // content descriptions, text messages, tags, team names, mottos, comments, + // and so on. + // + // Games may decide to not send the text, blank it out, or use + // generic text if the text was rejected by the Xbox LIVE service. + // + // Games verify the text by calling the XStringVerify function. + // + // Exemption It is not required to use the Xbox LIVE service to + // verify real-time text communication. An example of real-time text + // communication is in-game text chat. + // + // Intent Protect players from inappropriate language. + bool VerifyStrings(wchar_t** pwStringA, int iStringC, + int (*Func)(void*, STRING_VERIFY_RESPONSE*), + void* lpParam); + void CancelQueuedVerifyStrings(int (*Func)(void*, STRING_VERIFY_RESPONSE*), + void* lpParam); + void CancelAllVerifyInProgress(void); -// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); -// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); - EKeyboardResult RequestKeyboard(const wchar_t *Title, const wchar_t *Text, int iPad, unsigned int uiMaxChars, int( *Func)(void *,const bool), void *lpParam, C_4JInput::EKeyboardMode eMode); - void GetText(uint16_t *UTF16String); - - // Online check strings against offensive list - TCR 92 - // TCR # 092 CMTV Player Text String Verification - // Requirement Any player-entered text visible to another player on Xbox LIVE must be verified using the Xbox LIVE service before being transmitted. Text that is rejected by the Xbox LIVE service must not be displayed. - // - // Remarks - // This requirement applies to any player-entered string that can be exposed to other players on Xbox LIVE. It includes session names, content descriptions, text messages, tags, team names, mottos, comments, and so on. - // - // Games may decide to not send the text, blank it out, or use generic text if the text was rejected by the Xbox LIVE service. - // - // Games verify the text by calling the XStringVerify function. - // - // Exemption It is not required to use the Xbox LIVE service to verify real-time text communication. An example of real-time text communication is in-game text chat. - // - // Intent Protect players from inappropriate language. - bool VerifyStrings(wchar_t **pwStringA,int iStringC,int( *Func)(void *,STRING_VERIFY_RESPONSE *),void *lpParam); - void CancelQueuedVerifyStrings(int( *Func)(void *,STRING_VERIFY_RESPONSE *),void *lpParam); - void CancelAllVerifyInProgress(void); - - //bool InputDetected(DWORD dwUserIndex,WCHAR *pwchInput); + // bool InputDetected(DWORD dwUserIndex,WCHAR *pwchInput); }; // Singleton diff --git a/4J.Input/stdafx.h b/4J.Input/stdafx.h index c5d7fda89..70c4cc13e 100644 --- a/4J.Input/stdafx.h +++ b/4J.Input/stdafx.h @@ -5,4 +5,4 @@ #include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h" #endif -#endif //_4J_INPUT_STADAFX_H \ No newline at end of file +#endif //_4J_INPUT_STADAFX_H \ No newline at end of file diff --git a/4J.Profile/4J_Profile.cpp b/4J.Profile/4J_Profile.cpp index 5a7cf8baf..d71426de2 100644 --- a/4J.Profile/4J_Profile.cpp +++ b/4J.Profile/4J_Profile.cpp @@ -3,48 +3,85 @@ C_4JProfile ProfileManager; -static void *s_profileData[4] = {}; +static void* s_profileData[4] = {}; -void C_4JProfile::Initialise(DWORD dwTitleID, DWORD dwOfferID, unsigned short usProfileVersion, - UINT uiProfileValuesC, UINT uiProfileSettingsC, DWORD *pdwProfileSettingsA, - int iGameDefinedDataSizeX4, unsigned int *puiGameDefinedDataChangedBitmask) -{ - for (int i = 0; i < 4; i++) - { +void C_4JProfile::Initialise(DWORD dwTitleID, DWORD dwOfferID, + unsigned short usProfileVersion, + UINT uiProfileValuesC, UINT uiProfileSettingsC, + DWORD* pdwProfileSettingsA, + int iGameDefinedDataSizeX4, + unsigned int* puiGameDefinedDataChangedBitmask) { + for (int i = 0; i < 4; i++) { s_profileData[i] = new unsigned char[iGameDefinedDataSizeX4 / 4]; memset(s_profileData[i], 0, iGameDefinedDataSizeX4 / 4); } } -void C_4JProfile::SetTrialTextStringTable(CXuiStringTable *pStringTable, int iAccept, int iReject) {} -void C_4JProfile::SetTrialAwardText(eAwardType AwardType, int iTitle, int iText) {} +void C_4JProfile::SetTrialTextStringTable(CXuiStringTable* pStringTable, + int iAccept, int iReject) {} +void C_4JProfile::SetTrialAwardText(eAwardType AwardType, int iTitle, + int iText) {} int C_4JProfile::GetLockedProfile() { return -1; } void C_4JProfile::SetLockedProfile(int iProf) {} bool C_4JProfile::IsSignedIn(int iQuadrant) { return iQuadrant == 0; } bool C_4JProfile::IsSignedInLive(int iProf) { return false; } bool C_4JProfile::IsGuest(int iQuadrant) { return false; } -UINT C_4JProfile::RequestSignInUI(bool bFromInvite, bool bLocalGame, bool bNoGuestsAllowed, bool bMultiplayerSignIn, bool bAddUser, int(*Func)(void *, const bool, const int iPad), void *lpParam, int iQuadrant) { return 0; } -UINT C_4JProfile::DisplayOfflineProfile(int(*Func)(void *, const bool, const int iPad), void *lpParam, int iQuadrant) { return 0; } -UINT C_4JProfile::RequestConvertOfflineToGuestUI(int(*Func)(void *, const bool, const int iPad), void *lpParam, int iQuadrant) { return 0; } +UINT C_4JProfile::RequestSignInUI(bool bFromInvite, bool bLocalGame, + bool bNoGuestsAllowed, + bool bMultiplayerSignIn, bool bAddUser, + int (*Func)(void*, const bool, + const int iPad), + void* lpParam, int iQuadrant) { + return 0; +} +UINT C_4JProfile::DisplayOfflineProfile(int (*Func)(void*, const bool, + const int iPad), + void* lpParam, int iQuadrant) { + return 0; +} +UINT C_4JProfile::RequestConvertOfflineToGuestUI(int (*Func)(void*, const bool, + const int iPad), + void* lpParam, int iQuadrant) { + return 0; +} void C_4JProfile::SetPrimaryPlayerChanged(bool bVal) {} bool C_4JProfile::QuerySigninStatus(void) { return true; } -void C_4JProfile::GetXUID(int iPad, PlayerUID *pXuid, bool bOnlineXuid) { if (pXuid) *pXuid = 0; } -bool C_4JProfile::AreXUIDSEqual(PlayerUID xuid1, PlayerUID xuid2) { return xuid1 == xuid2; } +void C_4JProfile::GetXUID(int iPad, PlayerUID* pXuid, bool bOnlineXuid) { + if (pXuid) *pXuid = 0; +} +bool C_4JProfile::AreXUIDSEqual(PlayerUID xuid1, PlayerUID xuid2) { + return xuid1 == xuid2; +} bool C_4JProfile::XUIDIsGuest(PlayerUID xuid) { return false; } bool C_4JProfile::AllowedToPlayMultiplayer(int iProf) { return true; } -bool C_4JProfile::GetChatAndContentRestrictions(int iPad, bool *pbChatRestricted, bool *pbContentRestricted, int *piAge) { +bool C_4JProfile::GetChatAndContentRestrictions(int iPad, + bool* pbChatRestricted, + bool* pbContentRestricted, + int* piAge) { if (pbChatRestricted) *pbChatRestricted = false; if (pbContentRestricted) *pbContentRestricted = false; if (piAge) *piAge = 18; return true; } void C_4JProfile::StartTrialGame() {} -void C_4JProfile::AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, bool *allAllowed, bool *friendsAllowed) { +void C_4JProfile::AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, + bool* allAllowed, + bool* friendsAllowed) { if (allAllowed) *allAllowed = true; if (friendsAllowed) *friendsAllowed = true; } -bool C_4JProfile::CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, PPlayerUID pXuids, unsigned int xuidCount) { return true; } +bool C_4JProfile::CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, + PPlayerUID pXuids, + unsigned int xuidCount) { + return true; +} void C_4JProfile::ShowProfileCard(int iPad, PlayerUID targetUid) {} -bool C_4JProfile::GetProfileAvatar(int iPad, int(*Func)(void *lpParam, std::uint8_t *thumbnailData, unsigned int thumbnailBytes), void *lpParam) { return false; } +bool C_4JProfile::GetProfileAvatar(int iPad, + int (*Func)(void* lpParam, + std::uint8_t* thumbnailData, + unsigned int thumbnailBytes), + void* lpParam) { + return false; +} void C_4JProfile::CancelProfileAvatarRequest() {} int C_4JProfile::GetPrimaryPad() { return 0; } void C_4JProfile::SetPrimaryPad(int iPad) {} @@ -53,34 +90,68 @@ static char s_gamertag[64] = "Player"; char* C_4JProfile::GetGamertag(int iPad) { return s_gamertag; } std::wstring C_4JProfile::GetDisplayName(int iPad) { return L"Player"; } bool C_4JProfile::IsFullVersion() { return true; } -void C_4JProfile::SetSignInChangeCallback(void(*Func)(void *, bool, unsigned int), void *lpParam) {} -void C_4JProfile::SetNotificationsCallback(void(*Func)(void *, std::uint32_t, unsigned int), void *lpParam) {} +void C_4JProfile::SetSignInChangeCallback(void (*Func)(void*, bool, + unsigned int), + void* lpParam) {} +void C_4JProfile::SetNotificationsCallback(void (*Func)(void*, std::uint32_t, + unsigned int), + void* lpParam) {} bool C_4JProfile::RegionIsNorthAmerica(void) { return true; } bool C_4JProfile::LocaleIsUSorCanada(void) { return true; } HRESULT C_4JProfile::GetLiveConnectionStatus() { return S_OK; } bool C_4JProfile::IsSystemUIDisplayed() { return false; } -void C_4JProfile::SetProfileReadErrorCallback(void(*Func)(void *), void *lpParam) {} -int C_4JProfile::SetDefaultOptionsCallback(int(*Func)(void *, PROFILESETTINGS *, const int iPad), void *lpParam) { return 0; } -int C_4JProfile::SetOldProfileVersionCallback(int(*Func)(void *, unsigned char *, const unsigned short, const int), void *lpParam) { return 0; } +void C_4JProfile::SetProfileReadErrorCallback(void (*Func)(void*), + void* lpParam) {} +int C_4JProfile::SetDefaultOptionsCallback(int (*Func)(void*, PROFILESETTINGS*, + const int iPad), + void* lpParam) { + return 0; +} +int C_4JProfile::SetOldProfileVersionCallback(int (*Func)(void*, unsigned char*, + const unsigned short, + const int), + void* lpParam) { + return 0; +} static C_4JProfile::PROFILESETTINGS s_defaultSettings = {}; -C_4JProfile::PROFILESETTINGS* C_4JProfile::GetDashboardProfileSettings(int iPad) { return &s_defaultSettings; } -void C_4JProfile::WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged, bool bOverride5MinuteLimitOnProfileWrites) {} +C_4JProfile::PROFILESETTINGS* C_4JProfile::GetDashboardProfileSettings( + int iPad) { + return &s_defaultSettings; +} +void C_4JProfile::WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged, + bool bOverride5MinuteLimitOnProfileWrites) {} void C_4JProfile::ForceQueuedProfileWrites(int iPad) {} -void* C_4JProfile::GetGameDefinedProfileData(int iQuadrant) { return s_profileData[iQuadrant]; } +void* C_4JProfile::GetGameDefinedProfileData(int iQuadrant) { + return s_profileData[iQuadrant]; +} void C_4JProfile::ResetProfileProcessState() {} void C_4JProfile::Tick(void) {} -void C_4JProfile::RegisterAward(int iAwardNumber, int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected, - CXuiStringTable *pStringTable, int iTitleStr, int iTextStr, int iAcceptStr, char *pszThemeName, unsigned int uiThemeSize) {} +void C_4JProfile::RegisterAward(int iAwardNumber, int iGamerconfigID, + eAwardType eType, bool bLeaderboardAffected, + CXuiStringTable* pStringTable, int iTitleStr, + int iTextStr, int iAcceptStr, + char* pszThemeName, unsigned int uiThemeSize) {} int C_4JProfile::GetAwardId(int iAwardNumber) { return 0; } -eAwardType C_4JProfile::GetAwardType(int iAwardNumber) { return eAwardType_Achievement; } -bool C_4JProfile::CanBeAwarded(int iQuadrant, int iAwardNumber) { return false; } +eAwardType C_4JProfile::GetAwardType(int iAwardNumber) { + return eAwardType_Achievement; +} +bool C_4JProfile::CanBeAwarded(int iQuadrant, int iAwardNumber) { + return false; +} void C_4JProfile::Award(int iQuadrant, int iAwardNumber, bool bForce) {} bool C_4JProfile::IsAwardsFlagSet(int iQuadrant, int iAward) { return false; } void C_4JProfile::RichPresenceInit(int iPresenceCount, int iContextCount) {} void C_4JProfile::RegisterRichPresenceContext(int iGameConfigContextID) {} -void C_4JProfile::SetRichPresenceContextValue(int iPad, int iContextID, int iVal) {} -void C_4JProfile::SetCurrentGameActivity(int iPad, int iNewPresence, bool bSetOthersToIdle) {} -void C_4JProfile::DisplayFullVersionPurchase(bool bRequired, int iQuadrant, int iUpsellParam) {} -void C_4JProfile::SetUpsellCallback(void(*Func)(void *lpParam, eUpsellType type, eUpsellResponse response, int iUserData), void *lpParam) {} +void C_4JProfile::SetRichPresenceContextValue(int iPad, int iContextID, + int iVal) {} +void C_4JProfile::SetCurrentGameActivity(int iPad, int iNewPresence, + bool bSetOthersToIdle) {} +void C_4JProfile::DisplayFullVersionPurchase(bool bRequired, int iQuadrant, + int iUpsellParam) {} +void C_4JProfile::SetUpsellCallback(void (*Func)(void* lpParam, + eUpsellType type, + eUpsellResponse response, + int iUserData), + void* lpParam) {} void C_4JProfile::SetDebugFullOverride(bool bVal) {} diff --git a/4J.Profile/4J_Profile.h b/4J.Profile/4J_Profile.h index 881480b03..0bd8a4b9e 100644 --- a/4J.Profile/4J_Profile.h +++ b/4J.Profile/4J_Profile.h @@ -2,129 +2,156 @@ #include -enum eAwardType -{ - eAwardType_Achievement = 0, - eAwardType_GamerPic, - eAwardType_Theme, - eAwardType_AvatarItem, +enum eAwardType { + eAwardType_Achievement = 0, + eAwardType_GamerPic, + eAwardType_Theme, + eAwardType_AvatarItem, }; -enum eUpsellType -{ - eUpsellType_Custom = 0, // This is the default, and means that the upsell dialog was initiated in the app code - eUpsellType_Achievement, - eUpsellType_GamerPic, - eUpsellType_Theme, - eUpsellType_AvatarItem, +enum eUpsellType { + eUpsellType_Custom = 0, // This is the default, and means that the upsell + // dialog was initiated in the app code + eUpsellType_Achievement, + eUpsellType_GamerPic, + eUpsellType_Theme, + eUpsellType_AvatarItem, }; -enum eUpsellResponse -{ - eUpsellResponse_Declined, - eUpsellResponse_Accepted_NoPurchase, - eUpsellResponse_Accepted_Purchase, +enum eUpsellResponse { + eUpsellResponse_Declined, + eUpsellResponse_Accepted_NoPurchase, + eUpsellResponse_Accepted_Purchase, }; - - -class C_4JProfile -{ +class C_4JProfile { public: - struct PROFILESETTINGS - { - int iYAxisInversion; - int iControllerSensitivity; - int iVibration; - bool bSwapSticks; - }; + struct PROFILESETTINGS { + int iYAxisInversion; + int iControllerSensitivity; + int iVibration; + bool bSwapSticks; + }; + // 4 players have game defined data, puiGameDefinedDataChangedBitmask needs + // to be checked by the game side to see if there's an update needed - it'll + // have the bits set for players to be updated + void Initialise(DWORD dwTitleID, DWORD dwOfferID, + unsigned short usProfileVersion, UINT uiProfileValuesC, + UINT uiProfileSettingsC, DWORD* pdwProfileSettingsA, + int iGameDefinedDataSizeX4, + unsigned int* puiGameDefinedDataChangedBitmask); + void SetTrialTextStringTable(CXuiStringTable* pStringTable, int iAccept, + int iReject); + void SetTrialAwardText(eAwardType AwardType, int iTitle, + int iText); // achievement popup in the trial game + int GetLockedProfile(); + void SetLockedProfile(int iProf); + bool IsSignedIn(int iQuadrant); + bool IsSignedInLive(int iProf); + bool IsGuest(int iQuadrant); + UINT RequestSignInUI(bool bFromInvite, bool bLocalGame, + bool bNoGuestsAllowed, bool bMultiplayerSignIn, + bool bAddUser, + int (*Func)(void*, const bool, const int iPad), + void* lpParam, int iQuadrant = XUSER_INDEX_ANY); + UINT DisplayOfflineProfile(int (*Func)(void*, const bool, const int iPad), + void* lpParam, int iQuadrant = XUSER_INDEX_ANY); + UINT RequestConvertOfflineToGuestUI(int (*Func)(void*, const bool, + const int iPad), + void* lpParam, + int iQuadrant = XUSER_INDEX_ANY); + void SetPrimaryPlayerChanged(bool bVal); + bool QuerySigninStatus(void); + void GetXUID(int iPad, PlayerUID* pXuid, bool bOnlineXuid); + bool AreXUIDSEqual(PlayerUID xuid1, PlayerUID xuid2); + bool XUIDIsGuest(PlayerUID xuid); + bool AllowedToPlayMultiplayer(int iProf); + bool GetChatAndContentRestrictions(int iPad, bool* pbChatRestricted, + bool* pbContentRestricted, int* piAge); + void StartTrialGame(); // disables saves and leaderboard, and change state + // to readyforgame from pregame + void AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, + bool* allAllowed, bool* friendsAllowed); + bool CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, + PPlayerUID pXuids, unsigned int xuidCount); + void ShowProfileCard(int iPad, PlayerUID targetUid); + bool GetProfileAvatar(int iPad, + int (*Func)(void* lpParam, + std::uint8_t* thumbnailData, + unsigned int thumbnailBytes), + void* lpParam); + void CancelProfileAvatarRequest(); - // 4 players have game defined data, puiGameDefinedDataChangedBitmask needs to be checked by the game side to see if there's an update needed - it'll have the bits set for players to be updated - void Initialise( DWORD dwTitleID, - DWORD dwOfferID, - unsigned short usProfileVersion, - UINT uiProfileValuesC, - UINT uiProfileSettingsC, - DWORD *pdwProfileSettingsA, - int iGameDefinedDataSizeX4, - unsigned int *puiGameDefinedDataChangedBitmask); - void SetTrialTextStringTable(CXuiStringTable *pStringTable,int iAccept,int iReject); - void SetTrialAwardText(eAwardType AwardType,int iTitle,int iText); // achievement popup in the trial game - int GetLockedProfile(); - void SetLockedProfile(int iProf); - bool IsSignedIn(int iQuadrant); - bool IsSignedInLive(int iProf); - bool IsGuest(int iQuadrant); - UINT RequestSignInUI(bool bFromInvite,bool bLocalGame,bool bNoGuestsAllowed,bool bMultiplayerSignIn,bool bAddUser, int( *Func)(void *,const bool, const int iPad),void *lpParam,int iQuadrant=XUSER_INDEX_ANY); - UINT DisplayOfflineProfile(int( *Func)(void *,const bool, const int iPad),void *lpParam,int iQuadrant=XUSER_INDEX_ANY); - UINT RequestConvertOfflineToGuestUI(int( *Func)(void *,const bool, const int iPad),void *lpParam,int iQuadrant=XUSER_INDEX_ANY); - void SetPrimaryPlayerChanged(bool bVal); - bool QuerySigninStatus(void); - void GetXUID(int iPad, PlayerUID *pXuid,bool bOnlineXuid); - bool AreXUIDSEqual(PlayerUID xuid1,PlayerUID xuid2); - bool XUIDIsGuest(PlayerUID xuid); - bool AllowedToPlayMultiplayer(int iProf); - bool GetChatAndContentRestrictions(int iPad,bool *pbChatRestricted,bool *pbContentRestricted,int *piAge); - void StartTrialGame(); // disables saves and leaderboard, and change state to readyforgame from pregame - void AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, bool *allAllowed, bool *friendsAllowed); - bool CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, PPlayerUID pXuids, unsigned int xuidCount); - void ShowProfileCard(int iPad, PlayerUID targetUid); - bool GetProfileAvatar(int iPad,int( *Func)(void *lpParam,std::uint8_t *thumbnailData,unsigned int thumbnailBytes), void *lpParam); - void CancelProfileAvatarRequest(); + // SYS + int GetPrimaryPad(); + void SetPrimaryPad(int iPad); + char* GetGamertag(int iPad); + std::wstring GetDisplayName(int iPad); + bool IsFullVersion(); + void SetSignInChangeCallback(void (*Func)(void*, bool, unsigned int), + void* lpParam); + void SetNotificationsCallback(void (*Func)(void*, std::uint32_t, + unsigned int), + void* lpParam); + bool RegionIsNorthAmerica(void); + bool LocaleIsUSorCanada(void); + HRESULT GetLiveConnectionStatus(); + bool IsSystemUIDisplayed(); + void SetProfileReadErrorCallback(void (*Func)(void*), void* lpParam); - - // SYS - int GetPrimaryPad(); - void SetPrimaryPad(int iPad); - char* GetGamertag(int iPad); - std::wstring GetDisplayName(int iPad); - bool IsFullVersion(); - void SetSignInChangeCallback(void ( *Func)(void *, bool, unsigned int),void *lpParam); - void SetNotificationsCallback(void ( *Func)(void *, std::uint32_t, unsigned int),void *lpParam); - bool RegionIsNorthAmerica(void); - bool LocaleIsUSorCanada(void); - HRESULT GetLiveConnectionStatus(); - bool IsSystemUIDisplayed(); - void SetProfileReadErrorCallback(void ( *Func)(void *), void *lpParam); + // PROFILE DATA + int SetDefaultOptionsCallback(int (*Func)(void*, PROFILESETTINGS*, + const int iPad), + void* lpParam); + int SetOldProfileVersionCallback(int (*Func)(void*, unsigned char*, + const unsigned short, + const int), + void* lpParam); + PROFILESETTINGS* GetDashboardProfileSettings(int iPad); + void WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged = false, + bool bOverride5MinuteLimitOnProfileWrites = false); + void ForceQueuedProfileWrites(int iPad = XUSER_INDEX_ANY); + void* GetGameDefinedProfileData(int iQuadrant); + void ResetProfileProcessState(); // after a sign out from the primary + // player, call this + void Tick(void); + // ACHIEVEMENTS & AWARDS - // PROFILE DATA - int SetDefaultOptionsCallback(int( *Func)(void *,PROFILESETTINGS *, const int iPad),void *lpParam); - int SetOldProfileVersionCallback(int( *Func)(void *,unsigned char *, const unsigned short,const int),void *lpParam); - PROFILESETTINGS * GetDashboardProfileSettings(int iPad); - void WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged=false, bool bOverride5MinuteLimitOnProfileWrites=false); - void ForceQueuedProfileWrites(int iPad=XUSER_INDEX_ANY); - void *GetGameDefinedProfileData(int iQuadrant); - void ResetProfileProcessState(); // after a sign out from the primary player, call this - void Tick( void ); + void RegisterAward(int iAwardNumber, int iGamerconfigID, eAwardType eType, + bool bLeaderboardAffected = false, + CXuiStringTable* pStringTable = NULL, int iTitleStr = -1, + int iTextStr = -1, int iAcceptStr = -1, + char* pszThemeName = NULL, + unsigned int uiThemeSize = 0L); + int GetAwardId(int iAwardNumber); + eAwardType GetAwardType(int iAwardNumber); + bool CanBeAwarded(int iQuadrant, int iAwardNumber); + void Award(int iQuadrant, int iAwardNumber, bool bForce = false); + bool IsAwardsFlagSet(int iQuadrant, int iAward); - // ACHIEVEMENTS & AWARDS + // RICH PRESENCE - void RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected=false, - CXuiStringTable*pStringTable=NULL, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=NULL, unsigned int uiThemeSize=0L); - int GetAwardId(int iAwardNumber); - eAwardType GetAwardType(int iAwardNumber); - bool CanBeAwarded(int iQuadrant, int iAwardNumber); - void Award(int iQuadrant, int iAwardNumber, bool bForce=false); - bool IsAwardsFlagSet(int iQuadrant, int iAward); + void RichPresenceInit(int iPresenceCount, int iContextCount); + void RegisterRichPresenceContext(int iGameConfigContextID); + void SetRichPresenceContextValue(int iPad, int iContextID, int iVal); + void SetCurrentGameActivity(int iPad, int iNewPresence, + bool bSetOthersToIdle = false); - // RICH PRESENCE - - void RichPresenceInit(int iPresenceCount, int iContextCount); - void RegisterRichPresenceContext(int iGameConfigContextID); - void SetRichPresenceContextValue(int iPad,int iContextID, int iVal); - void SetCurrentGameActivity(int iPad,int iNewPresence, bool bSetOthersToIdle=false); - - // PURCHASE - void DisplayFullVersionPurchase(bool bRequired, int iQuadrant, int iUpsellParam = -1); - void SetUpsellCallback(void ( *Func)(void *lpParam, eUpsellType type, eUpsellResponse response, int iUserData),void *lpParam); - - // Debug - void SetDebugFullOverride(bool bVal); // To override the license version (trail/full). Only in debug/release, not ContentPackage + // PURCHASE + void DisplayFullVersionPurchase(bool bRequired, int iQuadrant, + int iUpsellParam = -1); + void SetUpsellCallback(void (*Func)(void* lpParam, eUpsellType type, + eUpsellResponse response, + int iUserData), + void* lpParam); + // Debug + void SetDebugFullOverride( + bool bVal); // To override the license version (trail/full). Only in + // debug/release, not ContentPackage }; // Singleton extern C_4JProfile ProfileManager; - diff --git a/4J.Profile/stdafx.h b/4J.Profile/stdafx.h index a728eb598..85d4b05ba 100644 --- a/4J.Profile/stdafx.h +++ b/4J.Profile/stdafx.h @@ -1,11 +1,10 @@ #ifndef _4J_PROFILE_STADAFX_H #define _4J_PROFILE_STADAFX_H - #ifdef __linux__ #include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h" #endif #include "../Minecraft.World/Platform/x64headers/extraX64.h" -#endif //_4J_PROFILE_STADAFX_H \ No newline at end of file +#endif //_4J_PROFILE_STADAFX_H \ No newline at end of file diff --git a/4J.Render/4J_Render.cpp b/4J.Render/4J_Render.cpp index b92fe8220..8bd80daa5 100644 --- a/4J.Render/4J_Render.cpp +++ b/4J.Render/4J_Render.cpp @@ -16,16 +16,16 @@ C4JRender RenderManager; // Hello SDL! -static SDL_Window *s_window = nullptr; +static SDL_Window* s_window = nullptr; static SDL_GLContext s_glContext = nullptr; static bool s_shouldClose = false; static int s_textureLevels = 1; -static int s_windowWidth = 0; +static int s_windowWidth = 0; static int s_windowHeight = 0; -// We set Window size with the monitor's res, so that I can get rid of ugly values. -static void SetInitialWindowSize() -{ +// We set Window size with the monitor's res, so that I can get rid of ugly +// values. +static void SetInitialWindowSize() { int w = 0, h = 0; if (SDL_Init(SDL_INIT_VIDEO) == 0) { SDL_DisplayMode mode; @@ -34,21 +34,27 @@ static void SetInitialWindowSize() h = (int)(mode.h * 0.4f); } } - if (w > 0 && h > 0) { s_windowWidth = w; s_windowHeight = h; } - else { s_windowWidth = 1280; s_windowHeight = 720; } + if (w > 0 && h > 0) { + s_windowWidth = w; + s_windowHeight = h; + } else { + s_windowWidth = 1280; + s_windowHeight = 720; + } } // (can't believe i had to rewrite this, i literally did it TODAY.) -static int s_reqWidth = 0; -static int s_reqHeight = 0; -// When we'll have a settings system in order, we'll set bool to that value, right now it's hardcoded. -static bool s_fullscreen = false; +static int s_reqWidth = 0; +static int s_reqHeight = 0; +// When we'll have a settings system in order, we'll set bool to that value, +// right now it's hardcoded. +static bool s_fullscreen = false; static pthread_key_t s_glCtxKey; static pthread_once_t s_glCtxKeyOnce = PTHREAD_ONCE_INIT; static void makeGLCtxKey() { pthread_key_create(&s_glCtxKey, nullptr); } // Do not touch exactly this number | -static const int MAX_SHARED_CONTEXTS = 6; // <- this one, do not touch -static SDL_Window *s_sharedContextWindows[MAX_SHARED_CONTEXTS] = {}; +static const int MAX_SHARED_CONTEXTS = 6; // <- this one, do not touch +static SDL_Window* s_sharedContextWindows[MAX_SHARED_CONTEXTS] = {}; static SDL_GLContext s_sharedContexts[MAX_SHARED_CONTEXTS] = {}; static int s_sharedContextCount = 0; static int s_nextSharedContext = 0; @@ -61,37 +67,35 @@ static pthread_t s_mainThread; static bool s_mainThreadSet = false; // viewport go brr -static void onFramebufferResize(int w, int h) -{ +static void onFramebufferResize(int w, int h) { if (w < 1) w = 1; if (h < 1) h = 1; - s_windowWidth = w; + s_windowWidth = w; s_windowHeight = h; ::glViewport(0, 0, w, h); } -// V-Sync - +// V-Sync // Initialize OpenGL & The SDL window. -void C4JRender::Initialise() -{ +void C4JRender::Initialise() { if (SDL_Init(SDL_INIT_VIDEO) != 0) { - fprintf(stderr, "[4J_Render] Failed to initialise SDL: %s\n", SDL_GetError()); + fprintf(stderr, "[4J_Render] Failed to initialise SDL: %s\n", + SDL_GetError()); return; } SDL_DisplayMode mode; int haveMode = (SDL_GetCurrentDisplayMode(0, &mode) == 0); if (s_reqWidth > 0 && s_reqHeight > 0) { - s_windowWidth = s_reqWidth; + s_windowWidth = s_reqWidth; s_windowHeight = s_reqHeight; } else if (haveMode) { - s_windowWidth = mode.w; + s_windowWidth = mode.w; s_windowHeight = mode.h; } - fprintf(stderr, "[4J_Render] Window %dx%d fullscreen=%s\n", - s_windowWidth, s_windowHeight, s_fullscreen ? "yes" : "no"); + fprintf(stderr, "[4J_Render] Window %dx%d fullscreen=%s\n", s_windowWidth, + s_windowHeight, s_fullscreen ? "yes" : "no"); fflush(stderr); // Setting the sdl_gl ver. Change in future incase we want to use shaders @@ -108,33 +112,37 @@ void C4JRender::Initialise() if (s_fullscreen) winFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; s_window = SDL_CreateWindow("Minecraft Console Edition", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, - s_windowWidth, s_windowHeight, - winFlags); + s_windowWidth, s_windowHeight, winFlags); if (!s_window) { - fprintf(stderr, "[4J_Render] Failed to create SDL window: %s\n", SDL_GetError()); + fprintf(stderr, "[4J_Render] Failed to create SDL window: %s\n", + SDL_GetError()); SDL_Quit(); return; } s_glContext = SDL_GL_CreateContext(s_window); if (!s_glContext) { - fprintf(stderr, "[4J_Render] Failed to create GL context: %s\n", SDL_GetError()); + fprintf(stderr, "[4J_Render] Failed to create GL context: %s\n", + SDL_GetError()); SDL_DestroyWindow(s_window); s_window = nullptr; SDL_Quit(); return; } - // 4JCraft VSync/V-Sync - #ifdef ENABLE_VSYNC - SDL_GL_SetSwapInterval(1); // V-Sync On Please. - #else - SDL_GL_SetSwapInterval(0); // V-Sync Off Please. - #endif - - int fw, fh; SDL_GetWindowSize(s_window, &fw, &fh); onFramebufferResize(fw, fh); +// 4JCraft VSync/V-Sync +#ifdef ENABLE_VSYNC + SDL_GL_SetSwapInterval(1); // V-Sync On Please. +#else + SDL_GL_SetSwapInterval(0); // V-Sync Off Please. +#endif - // We initialize the OpenGL states. Touching those values makes some funny artifacts appear. + int fw, fh; + SDL_GetWindowSize(s_window, &fw, &fh); + onFramebufferResize(fw, fh); + + // We initialize the OpenGL states. Touching those values makes some funny + // artifacts appear. ::glEnable(GL_TEXTURE_2D); ::glEnable(GL_DEPTH_TEST); ::glDepthFunc(GL_LEQUAL); @@ -164,14 +172,15 @@ void C4JRender::Initialise() pthread_setspecific(s_glCtxKey, (void*)s_window); // Pre-create shared GL contexts for worker threads (chunk builders etc.) - // Ensure they are invisible so they don't interfere with the window manager. + // Ensure they are invisible so they don't interfere with the window + // manager. - // Pre-create shared GL contexts for worker threads (chunk builders & other shit etc.) - // SDL_GL_SHARE_WITH_CURRENT_CONTEXT my saviour. + // Pre-create shared GL contexts for worker threads (chunk builders & other + // shit etc.) SDL_GL_SHARE_WITH_CURRENT_CONTEXT my saviour. for (int i = 0; i < MAX_SHARED_CONTEXTS; i++) { - SDL_Window *w = SDL_CreateWindow("", - SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - 1, 1, SDL_WINDOW_HIDDEN | SDL_WINDOW_OPENGL); + SDL_Window* w = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, + SDL_WINDOWPOS_UNDEFINED, 1, 1, + SDL_WINDOW_HIDDEN | SDL_WINDOW_OPENGL); if (!w) break; // Ensure sharing // I've been stuck on this for a while. Im stupid.. @@ -189,12 +198,13 @@ void C4JRender::Initialise() // Ensure main thread still has the context SDL_GL_MakeCurrent(s_window, s_glContext); - fprintf(stderr, "[4J_Render] Created %d shared GL contexts for worker threads\n", s_sharedContextCount); + fprintf(stderr, + "[4J_Render] Created %d shared GL contexts for worker threads\n", + s_sharedContextCount); fflush(stderr); } -void C4JRender::InitialiseContext() -{ +void C4JRender::InitialiseContext() { if (!s_window) return; pthread_once(&s_glCtxKeyOnce, makeGLCtxKey); @@ -205,14 +215,20 @@ void C4JRender::InitialiseContext() return; } - // Worker thread checks if there's a context, we don't want to have multiple contexts. - void *ctxPtr = pthread_getspecific(s_glCtxKey); + // Worker thread checks if there's a context, we don't want to have multiple + // contexts. + void* ctxPtr = pthread_getspecific(s_glCtxKey); if (ctxPtr) { // ctxPtr -> SDL_GLContext pointer SDL_GLContext ctx = (SDL_GLContext)ctxPtr; int idx = -1; - for (int i = 0; i < s_sharedContextCount; ++i) if (s_sharedContexts[i] == ctx) { idx = i; break; } - if (idx >= 0 && s_sharedContextWindows[idx]) SDL_GL_MakeCurrent(s_sharedContextWindows[idx], ctx); + for (int i = 0; i < s_sharedContextCount; ++i) + if (s_sharedContexts[i] == ctx) { + idx = i; + break; + } + if (idx >= 0 && s_sharedContextWindows[idx]) + SDL_GL_MakeCurrent(s_sharedContextWindows[idx], ctx); return; } @@ -225,16 +241,25 @@ void C4JRender::InitialiseContext() pthread_mutex_unlock(&s_sharedCtxMutex); if (!shared) { - fprintf(stderr, "[4J_Render] ERROR: no shared GL contexts left for worker thread %lu!\n", (unsigned long)pthread_self()); + fprintf(stderr, + "[4J_Render] ERROR: no shared GL contexts left for worker " + "thread %lu!\n", + (unsigned long)pthread_self()); fflush(stderr); return; } // ewww..... look at line 201-203, we gotta make a function for that.... int idx = -1; - for (int i = 0; i < s_sharedContextCount; ++i) if (s_sharedContexts[i] == shared) { idx = i; break; } - if (idx >= 0 && s_sharedContextWindows[idx]) SDL_GL_MakeCurrent(s_sharedContextWindows[idx], shared); + for (int i = 0; i < s_sharedContextCount; ++i) + if (s_sharedContexts[i] == shared) { + idx = i; + break; + } + if (idx >= 0 && s_sharedContextWindows[idx]) + SDL_GL_MakeCurrent(s_sharedContextWindows[idx], shared); - // Initialize some basic state for this context to ensure consistent display list recording + // Initialize some basic state for this context to ensure consistent display + // list recording ::glEnable(GL_TEXTURE_2D); ::glEnable(GL_DEPTH_TEST); ::glDepthFunc(GL_LEQUAL); @@ -246,59 +271,56 @@ void C4JRender::InitialiseContext() ::glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); pthread_setspecific(s_glCtxKey, (void*)shared); - fprintf(stderr, "[4J_Render] Assigned shared GL context %p to worker thread %lu\n", (void*)shared, (unsigned long)pthread_self()); + fprintf(stderr, + "[4J_Render] Assigned shared GL context %p to worker thread %lu\n", + (void*)shared, (unsigned long)pthread_self()); fflush(stderr); } -void C4JRender::StartFrame() -{ +void C4JRender::StartFrame() { if (!s_window) return; - int w,h; SDL_GetWindowSize(s_window, &w, &h); + int w, h; + SDL_GetWindowSize(s_window, &w, &h); s_windowWidth = w > 0 ? w : 1; s_windowHeight = h > 0 ? h : 1; ::glViewport(0, 0, s_windowWidth, s_windowHeight); } -void C4JRender::Present() -{ +void C4JRender::Present() { if (!s_window) return; SDL_Event ev; while (SDL_PollEvent(&ev)) { - if (ev.type == SDL_QUIT) s_shouldClose = true; + if (ev.type == SDL_QUIT) + s_shouldClose = true; else if (ev.type == SDL_WINDOWEVENT) { - if (ev.window.event == SDL_WINDOWEVENT_CLOSE) s_shouldClose = true; - else if (ev.window.event == SDL_WINDOWEVENT_RESIZED) onFramebufferResize(ev.window.data1, ev.window.data2); + if (ev.window.event == SDL_WINDOWEVENT_CLOSE) + s_shouldClose = true; + else if (ev.window.event == SDL_WINDOWEVENT_RESIZED) + onFramebufferResize(ev.window.data1, ev.window.data2); } } - // Present the rendered frame after processing input/events to avoid input timing issues + // Present the rendered frame after processing input/events to avoid input + // timing issues ::glFlush(); // debug log to help diagnose mouse issues - // printf("[4J_Render] Presenting frame (mouse lock=%d)\n", s_mouseLocked); fflush(stdout); + // printf("[4J_Render] Presenting frame (mouse lock=%d)\n", s_mouseLocked); + // fflush(stdout); SDL_GL_SwapWindow(s_window); } -void C4JRender::SetWindowSize(int w, int h) -{ - s_reqWidth = (w > 0) ? w : 0; +void C4JRender::SetWindowSize(int w, int h) { + s_reqWidth = (w > 0) ? w : 0; s_reqHeight = (h > 0) ? h : 0; } -void C4JRender::SetFullscreen(bool fs) -{ - s_fullscreen = fs; -} +void C4JRender::SetFullscreen(bool fs) { s_fullscreen = fs; } -bool C4JRender::ShouldClose() -{ - return !s_window || s_shouldClose; -} +bool C4JRender::ShouldClose() { return !s_window || s_shouldClose; } -void C4JRender::Shutdown() -{ +void C4JRender::Shutdown() { // Destroy the main window and clean up SDL resources so that // destructors running after the game loop don't touch a dead context. - if (s_window) - { + if (s_window) { if (s_glContext) { SDL_GL_DeleteContext(s_glContext); s_glContext = nullptr; @@ -324,64 +346,61 @@ void C4JRender::Shutdown() // rip glfw. you won't be missed. (i hope) void C4JRender::DoScreenGrabOnNextPresent() {} -void C4JRender::Clear(int flags) -{ - ::glClear(flags); -} +void C4JRender::Clear(int flags) { ::glClear(flags); } -void C4JRender::SetClearColour(const float colourRGBA[4]) -{ +void C4JRender::SetClearColour(const float colourRGBA[4]) { ::glClearColor(colourRGBA[0], colourRGBA[1], colourRGBA[2], colourRGBA[3]); } bool C4JRender::IsWidescreen() { return true; } -bool C4JRender::IsHiDef() { return true; } -void C4JRender::GetFramebufferSize(int &width, int &height) { width = s_windowWidth; height = s_windowHeight; } -void C4JRender::CaptureThumbnail(ImageFileBuffer *) {} -void C4JRender::CaptureScreen(ImageFileBuffer *, XSOCIAL_PREVIEWIMAGE *) {} -void C4JRender::BeginConditionalSurvey(int) {} -void C4JRender::EndConditionalSurvey() {} -void C4JRender::BeginConditionalRendering(int){} -void C4JRender::EndConditionalRendering() {} +bool C4JRender::IsHiDef() { return true; } +void C4JRender::GetFramebufferSize(int& width, int& height) { + width = s_windowWidth; + height = s_windowHeight; +} +void C4JRender::CaptureThumbnail(ImageFileBuffer*) {} +void C4JRender::CaptureScreen(ImageFileBuffer*, XSOCIAL_PREVIEWIMAGE*) {} +void C4JRender::BeginConditionalSurvey(int) {} +void C4JRender::EndConditionalSurvey() {} +void C4JRender::BeginConditionalRendering(int) {} +void C4JRender::EndConditionalRendering() {} -void C4JRender::MatrixMode(int type) { ::glMatrixMode(type); } -void C4JRender::MatrixSetIdentity() { ::glLoadIdentity(); } -void C4JRender::MatrixTranslate(float x, float y, float z) { ::glTranslatef(x, y, z); } +void C4JRender::MatrixMode(int type) { ::glMatrixMode(type); } +void C4JRender::MatrixSetIdentity() { ::glLoadIdentity(); } +void C4JRender::MatrixTranslate(float x, float y, float z) { + ::glTranslatef(x, y, z); +} -void C4JRender::MatrixRotate(float angle, float x, float y, float z) -{ +void C4JRender::MatrixRotate(float angle, float x, float y, float z) { // We use math from the math lib instead of hardcoding it. How Ugly. ::glRotatef(angle * (180.0f / static_cast(M_PI)), x, y, z); } void C4JRender::MatrixScale(float x, float y, float z) { ::glScalef(x, y, z); } -void C4JRender::MatrixPerspective(float fovy, float aspect, float zNear, float zFar) -{ +void C4JRender::MatrixPerspective(float fovy, float aspect, float zNear, + float zFar) { ::gluPerspective((double)fovy, (double)aspect, (double)zNear, (double)zFar); } -void C4JRender::MatrixOrthogonal(float left, float right, float bottom, float top, - float zNear, float zFar) -{ +void C4JRender::MatrixOrthogonal(float left, float right, float bottom, + float top, float zNear, float zFar) { ::glOrtho(left, right, bottom, top, zNear, zFar); } -void C4JRender::MatrixPop() { ::glPopMatrix(); } -void C4JRender::MatrixPush() { ::glPushMatrix(); } -void C4JRender::MatrixMult(float *mat) { ::glMultMatrixf(mat); } +void C4JRender::MatrixPop() { ::glPopMatrix(); } +void C4JRender::MatrixPush() { ::glPushMatrix(); } +void C4JRender::MatrixMult(float* mat) { ::glMultMatrixf(mat); } -const float* C4JRender::MatrixGet(int type) -{ +const float* C4JRender::MatrixGet(int type) { static float mat[16]; ::glGetFloatv(type, mat); return mat; } -void C4JRender::Set_matrixDirty() {} // immediate-mode +void C4JRender::Set_matrixDirty() {} // immediate-mode -static GLenum mapPrimType(int pt) -{ +static GLenum mapPrimType(int pt) { // Handle GL constants first if (pt == GL_QUADS) return GL_QUADS; if (pt == GL_TRIANGLES) return GL_TRIANGLES; @@ -392,21 +411,27 @@ static GLenum mapPrimType(int pt) // Map from ePrimitiveType enum switch (pt) { - case C4JRender::PRIMITIVE_TYPE_TRIANGLE_LIST: return GL_TRIANGLES; - case C4JRender::PRIMITIVE_TYPE_TRIANGLE_STRIP: return GL_TRIANGLE_STRIP; - case C4JRender::PRIMITIVE_TYPE_TRIANGLE_FAN: return GL_TRIANGLE_FAN; - case C4JRender::PRIMITIVE_TYPE_QUAD_LIST: return GL_QUADS; - case C4JRender::PRIMITIVE_TYPE_LINE_LIST: return GL_LINES; - case C4JRender::PRIMITIVE_TYPE_LINE_STRIP: return GL_LINE_STRIP; - default: return GL_TRIANGLES; + case C4JRender::PRIMITIVE_TYPE_TRIANGLE_LIST: + return GL_TRIANGLES; + case C4JRender::PRIMITIVE_TYPE_TRIANGLE_STRIP: + return GL_TRIANGLE_STRIP; + case C4JRender::PRIMITIVE_TYPE_TRIANGLE_FAN: + return GL_TRIANGLE_FAN; + case C4JRender::PRIMITIVE_TYPE_QUAD_LIST: + return GL_QUADS; + case C4JRender::PRIMITIVE_TYPE_LINE_LIST: + return GL_LINES; + case C4JRender::PRIMITIVE_TYPE_LINE_STRIP: + return GL_LINE_STRIP; + default: + return GL_TRIANGLES; } } // This is the clientside vertex processing. void C4JRender::DrawVertices(ePrimitiveType PrimitiveType, int count, - void *dataIn, eVertexType vType, - C4JRender::ePixelShaderType psType) -{ + void* dataIn, eVertexType vType, + C4JRender::ePixelShaderType psType) { if (count <= 0 || !dataIn) return; // trash trash trash trash @@ -415,20 +440,21 @@ void C4JRender::DrawVertices(ePrimitiveType PrimitiveType, int count, GLenum mode = mapPrimType((int)PrimitiveType); if (vType == VERTEX_TYPE_COMPRESSED) { - int16_t *sdata = (int16_t *)dataIn; + int16_t* sdata = (int16_t*)dataIn; ::glBegin(mode); for (int i = 0; i < count; i++) { - int16_t *vert = sdata + i * 8; + int16_t* vert = sdata + i * 8; float x = vert[0] / 1024.0f; float y = vert[1] / 1024.0f; float z = vert[2] / 1024.0f; - // Unpack RGB565 colour (Tesselator stores as packedcol - 32768 to fit in int16) + // Unpack RGB565 colour (Tesselator stores as packedcol - 32768 to + // fit in int16) unsigned short packedColor = (unsigned short)((int)vert[3] + 32768); float r = ((packedColor >> 11) & 0x1f) / 31.0f; - float g = ((packedColor >> 5) & 0x3f) / 63.0f; - float b = ( packedColor & 0x1f) / 31.0f; + float g = ((packedColor >> 5) & 0x3f) / 63.0f; + float b = (packedColor & 0x1f) / 31.0f; float fu = vert[4] / 8192.0f; float fv = vert[5] / 8192.0f; @@ -446,20 +472,20 @@ void C4JRender::DrawVertices(ePrimitiveType PrimitiveType, int count, } ::glEnd(); } else { - unsigned int *idata = (unsigned int *)dataIn; + unsigned int* idata = (unsigned int*)dataIn; ::glBegin(mode); for (int i = 0; i < count; i++) { - float *fdata = (float *)(idata + i * 8); + float* fdata = (float*)(idata + i * 8); unsigned int colorInt = idata[i * 8 + 5]; unsigned char cr = (colorInt >> 24) & 0xFF; unsigned char cg = (colorInt >> 16) & 0xFF; - unsigned char cb = (colorInt >> 8) & 0xFF; - unsigned char ca = colorInt & 0xFF; + unsigned char cb = (colorInt >> 8) & 0xFF; + unsigned char ca = colorInt & 0xFF; unsigned int normalInt = idata[i * 8 + 6]; - int8_t nx = (int8_t)( normalInt & 0xFF); - int8_t ny = (int8_t)((normalInt >> 8) & 0xFF); + int8_t nx = (int8_t)(normalInt & 0xFF); + int8_t ny = (int8_t)((normalInt >> 8) & 0xFF); int8_t nz = (int8_t)((normalInt >> 16) & 0xFF); unsigned int tex2Int = idata[i * 8 + 7]; @@ -475,8 +501,8 @@ void C4JRender::DrawVertices(ePrimitiveType PrimitiveType, int count, ::glTexCoord2f(fdata[3], fdata[4]); - // Unit 1 (lightmap) UVs - 0xfe00fe00 is sentinel for "no Unit 1 UVs" - // Ugly hack, replace soon. + // Unit 1 (lightmap) UVs - 0xfe00fe00 is sentinel for "no Unit 1 + // UVs" Ugly hack, replace soon. if (tex2Int != 0xfe00fe00) { float u2 = (float)(short)(tex2Int & 0xFFFF) / 256.0f; float v2 = (float)(short)((tex2Int >> 16) & 0xFFFF) / 256.0f; @@ -492,34 +518,29 @@ void C4JRender::DrawVertices(ePrimitiveType PrimitiveType, int count, pthread_mutex_unlock(&s_glCallMutex); } - void C4JRender::CBuffLockStaticCreations() {} -int C4JRender::CBuffCreate(int count) -{ +int C4JRender::CBuffCreate(int count) { int id = (int)::glGenLists(count); ::glFlush(); return id; } -void C4JRender::CBuffDelete(int first, int count) -{ +void C4JRender::CBuffDelete(int first, int count) { if (first > 0 && count > 0) { ::glDeleteLists(first, count); ::glFlush(); } } -void C4JRender::CBuffStart(int index, bool /*full*/) -{ +void C4JRender::CBuffStart(int index, bool /*full*/) { if (index > 0) { ::glNewList(index, GL_COMPILE); ::glFlush(); } } -void C4JRender::CBuffClear(int index) -{ +void C4JRender::CBuffClear(int index) { if (index > 0) { ::glNewList(index, GL_COMPILE); ::glEndList(); @@ -527,41 +548,38 @@ void C4JRender::CBuffClear(int index) } } -int C4JRender::CBuffSize(int /*index*/) { return 0; } +int C4JRender::CBuffSize(int /*index*/) { return 0; } -void C4JRender::CBuffEnd() -{ +void C4JRender::CBuffEnd() { ::glEndList(); ::glFlush(); } -bool C4JRender::CBuffCall(int index, bool /*full*/) -{ +bool C4JRender::CBuffCall(int index, bool /*full*/) { if (index <= 0) return false; - if (::glIsList(index)) { ::glCallList(index); return true; } + if (::glIsList(index)) { + ::glCallList(index); + return true; + } return false; } -void C4JRender::CBuffTick() {} +void C4JRender::CBuffTick() {} void C4JRender::CBuffDeferredModeStart() {} -void C4JRender::CBuffDeferredModeEnd() {} +void C4JRender::CBuffDeferredModeEnd() {} - -int C4JRender::TextureCreate() -{ +int C4JRender::TextureCreate() { GLuint id = 0; ::glGenTextures(1, &id); return (int)id; } -void C4JRender::TextureFree(int idx) -{ +void C4JRender::TextureFree(int idx) { GLuint id = (GLuint)idx; ::glDeleteTextures(1, &id); } -void C4JRender::TextureBind(int idx) -{ +void C4JRender::TextureBind(int idx) { if (idx < 0) { ::glBindTexture(GL_TEXTURE_2D, 0); } else { @@ -569,8 +587,7 @@ void C4JRender::TextureBind(int idx) } } -void C4JRender::TextureBindVertex(int idx, bool scaleLight) -{ +void C4JRender::TextureBindVertex(int idx, bool scaleLight) { // Unit 1 used for lightmapping in fixed-function or standard shaders ::glActiveTexture(GL_TEXTURE1); if (idx < 0) { @@ -586,8 +603,7 @@ void C4JRender::TextureBindVertex(int idx, bool scaleLight) // 4jcraft: jank workaround for entities // referenced from the disabled code in GameRenderer::turnOnLightLayer - if (scaleLight) - { + if (scaleLight) { ::glMatrixMode(GL_TEXTURE); ::glLoadIdentity(); float s = 1 / 16.0f / 15.0f * 15 / 16; @@ -596,26 +612,24 @@ void C4JRender::TextureBindVertex(int idx, bool scaleLight) ::glMatrixMode(GL_MODELVIEW); } } - + ::glActiveTexture(GL_TEXTURE0); ::glFlush(); } -void C4JRender::TextureSetTextureLevels(int levels) -{ +void C4JRender::TextureSetTextureLevels(int levels) { // base level is always 0, no mipmaps sadly. I'll add them later. - ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, levels > 0 ? levels - 1 : 0); + ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, + levels > 0 ? levels - 1 : 0); s_textureLevels = levels; } -int C4JRender::TextureGetTextureLevels() { return s_textureLevels; } +int C4JRender::TextureGetTextureLevels() { return s_textureLevels; } -void C4JRender::TextureData(int width, int height, void *data, int level, - eTextureFormat /*format*/) -{ +void C4JRender::TextureData(int width, int height, void* data, int level, + eTextureFormat /*format*/) { // TODO: Check if correct format. - ::glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, - width, height, 0, - GL_RGBA, GL_UNSIGNED_BYTE, data); + ::glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, width, height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, data); ::glFlush(); @@ -626,45 +640,40 @@ void C4JRender::TextureData(int width, int height, void *data, int level, } } -void C4JRender::TextureDataUpdate(int xoffset, int yoffset, - int width, int height, - void *data, int level) -{ - ::glTexSubImage2D(GL_TEXTURE_2D, level, xoffset, yoffset, - width, height, GL_RGBA, GL_UNSIGNED_BYTE, data); +void C4JRender::TextureDataUpdate(int xoffset, int yoffset, int width, + int height, void* data, int level) { + ::glTexSubImage2D(GL_TEXTURE_2D, level, xoffset, yoffset, width, height, + GL_RGBA, GL_UNSIGNED_BYTE, data); ::glFlush(); } -void C4JRender::TextureSetParam(int param, int value) -{ +void C4JRender::TextureSetParam(int param, int value) { ::glTexParameteri(GL_TEXTURE_2D, param, value); } void C4JRender::TextureDynamicUpdateStart() {} -void C4JRender::TextureDynamicUpdateEnd() {} +void C4JRender::TextureDynamicUpdateEnd() {} void C4JRender::Tick() {} void C4JRender::UpdateGamma(unsigned short) {} // Converts RGBA data to the format expected by the texture loader. -static HRESULT LoadFromSTB(unsigned char* data, int width, int height, D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut) -{ +static HRESULT LoadFromSTB(unsigned char* data, int width, int height, + D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut) { int pixelCount = width * height; int* pixels = new int[pixelCount]; - for (int i = 0; i < pixelCount; i++) - { + for (int i = 0; i < pixelCount; i++) { unsigned char r = data[i * 4 + 0]; unsigned char g = data[i * 4 + 1]; unsigned char b = data[i * 4 + 2]; unsigned char a = data[i * 4 + 3]; - //pixels[i] = (a << 24) | (b << 16) | (g << 8) | r; + // pixels[i] = (a << 24) | (b << 16) | (g << 8) | r; pixels[i] = (a << 24) | (r << 16) | (g << 8) | b; } - if (pSrcInfo) - { + if (pSrcInfo) { pSrcInfo->Width = width; pSrcInfo->Height = height; } @@ -673,13 +682,12 @@ static HRESULT LoadFromSTB(unsigned char* data, int width, int height, D3DXIMAGE return S_OK; } -HRESULT C4JRender::LoadTextureData(const char* szFilename, D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut) -{ +HRESULT C4JRender::LoadTextureData(const char* szFilename, + D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut) { int width, height, channels; unsigned char* data = stbi_load(szFilename, &width, &height, &channels, 4); - if (!data) - return E_FAIL; + if (!data) return E_FAIL; HRESULT hr = LoadFromSTB(data, width, height, pSrcInfo, ppDataOut); @@ -687,13 +695,13 @@ HRESULT C4JRender::LoadTextureData(const char* szFilename, D3DXIMAGE_INFO* pSrcI return hr; } -HRESULT C4JRender::LoadTextureData(BYTE* pbData, DWORD dwBytes, D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut) -{ +HRESULT C4JRender::LoadTextureData(BYTE* pbData, DWORD dwBytes, + D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut) { int width, height, channels; - unsigned char* data = stbi_load_from_memory(pbData, dwBytes, &width, &height, &channels, 4); - if (!data) - return E_FAIL; + unsigned char* data = + stbi_load_from_memory(pbData, dwBytes, &width, &height, &channels, 4); + if (!data) return E_FAIL; HRESULT hr = LoadFromSTB(data, width, height, pSrcInfo, ppDataOut); @@ -701,83 +709,83 @@ HRESULT C4JRender::LoadTextureData(BYTE* pbData, DWORD dwBytes, D3DXIMAGE_INFO* return hr; } -HRESULT C4JRender::SaveTextureData(const char *szFilename, D3DXIMAGE_INFO *pSrcInfo, int *ppDataOut) { return S_OK; } -HRESULT C4JRender::SaveTextureDataToMemory(void *pOutput, int outputCapacity, int *outputLength, int width, int height, int *ppDataIn) { return S_OK; } +HRESULT C4JRender::SaveTextureData(const char* szFilename, + D3DXIMAGE_INFO* pSrcInfo, int* ppDataOut) { + return S_OK; +} +HRESULT C4JRender::SaveTextureDataToMemory(void* pOutput, int outputCapacity, + int* outputLength, int width, + int height, int* ppDataIn) { + return S_OK; +} void C4JRender::TextureGetStats() {} void* C4JRender::TextureGetTexture(int idx) { return nullptr; } -void C4JRender::StateSetColour(float r, float g, float b, float a) -{ +void C4JRender::StateSetColour(float r, float g, float b, float a) { ::glColor4f(r, g, b, a); } -void C4JRender::StateSetDepthMask(bool enable) -{ +void C4JRender::StateSetDepthMask(bool enable) { ::glDepthMask(enable ? GL_TRUE : GL_FALSE); } -void C4JRender::StateSetBlendEnable(bool enable) -{ - if (enable) ::glEnable(GL_BLEND); else ::glDisable(GL_BLEND); +void C4JRender::StateSetBlendEnable(bool enable) { + if (enable) + ::glEnable(GL_BLEND); + else + ::glDisable(GL_BLEND); } -void C4JRender::StateSetBlendFunc(int src, int dst) -{ - ::glBlendFunc(src, dst); -} +void C4JRender::StateSetBlendFunc(int src, int dst) { ::glBlendFunc(src, dst); } -void C4JRender::StateSetBlendFactor(unsigned int colour) -{ +void C4JRender::StateSetBlendFactor(unsigned int colour) { // colour is 0xAARRGGBB packed float a = ((colour >> 24) & 0xFF) / 255.0f; float r = ((colour >> 16) & 0xFF) / 255.0f; - float g = ((colour >> 8) & 0xFF) / 255.0f; - float b = ( colour & 0xFF) / 255.0f; + float g = ((colour >> 8) & 0xFF) / 255.0f; + float b = (colour & 0xFF) / 255.0f; ::glBlendColor(r, g, b, a); } -void C4JRender::StateSetAlphaFunc(int func, float param) -{ +void C4JRender::StateSetAlphaFunc(int func, float param) { ::glAlphaFunc(func, param); } -void C4JRender::StateSetDepthFunc(int func) -{ - ::glDepthFunc(func); +void C4JRender::StateSetDepthFunc(int func) { ::glDepthFunc(func); } + +void C4JRender::StateSetFaceCull(bool enable) { + if (enable) + ::glEnable(GL_CULL_FACE); + else + ::glDisable(GL_CULL_FACE); } -void C4JRender::StateSetFaceCull(bool enable) -{ - if (enable) ::glEnable(GL_CULL_FACE); else ::glDisable(GL_CULL_FACE); -} - -void C4JRender::StateSetFaceCullCW(bool enable) -{ +void C4JRender::StateSetFaceCullCW(bool enable) { ::glFrontFace(enable ? GL_CW : GL_CCW); } -void C4JRender::StateSetLineWidth(float width) -{ - ::glLineWidth(width); -} +void C4JRender::StateSetLineWidth(float width) { ::glLineWidth(width); } -void C4JRender::StateSetWriteEnable(bool red, bool green, bool blue, bool alpha) -{ +void C4JRender::StateSetWriteEnable(bool red, bool green, bool blue, + bool alpha) { ::glColorMask(red, green, blue, alpha); } -void C4JRender::StateSetDepthTestEnable(bool enable) -{ - if (enable) ::glEnable(GL_DEPTH_TEST); else ::glDisable(GL_DEPTH_TEST); +void C4JRender::StateSetDepthTestEnable(bool enable) { + if (enable) + ::glEnable(GL_DEPTH_TEST); + else + ::glDisable(GL_DEPTH_TEST); } -void C4JRender::StateSetAlphaTestEnable(bool enable) -{ - if (enable) ::glEnable(GL_ALPHA_TEST); else ::glDisable(GL_ALPHA_TEST); +void C4JRender::StateSetAlphaTestEnable(bool enable) { + if (enable) + ::glEnable(GL_ALPHA_TEST); + else + ::glDisable(GL_ALPHA_TEST); } -void C4JRender::StateSetDepthSlopeAndBias(float slope, float bias) -{ +void C4JRender::StateSetDepthSlopeAndBias(float slope, float bias) { if (slope != 0.0f || bias != 0.0f) { ::glEnable(GL_POLYGON_OFFSET_FILL); ::glPolygonOffset(slope, bias); @@ -786,39 +794,33 @@ void C4JRender::StateSetDepthSlopeAndBias(float slope, float bias) } } -void C4JRender::StateSetFogEnable(bool enable) -{ - if (enable) ::glEnable(GL_FOG); else ::glDisable(GL_FOG); +void C4JRender::StateSetFogEnable(bool enable) { + if (enable) + ::glEnable(GL_FOG); + else + ::glDisable(GL_FOG); } -void C4JRender::StateSetFogMode(int mode) -{ - ::glFogi(GL_FOG_MODE, mode); -} +void C4JRender::StateSetFogMode(int mode) { ::glFogi(GL_FOG_MODE, mode); } -void C4JRender::StateSetFogNearDistance(float dist) -{ +void C4JRender::StateSetFogNearDistance(float dist) { ::glFogf(GL_FOG_START, dist); } -void C4JRender::StateSetFogFarDistance(float dist) -{ +void C4JRender::StateSetFogFarDistance(float dist) { ::glFogf(GL_FOG_END, dist); } -void C4JRender::StateSetFogDensity(float density) -{ +void C4JRender::StateSetFogDensity(float density) { ::glFogf(GL_FOG_DENSITY, density); } -void C4JRender::StateSetFogColour(float red, float green, float blue) -{ +void C4JRender::StateSetFogColour(float red, float green, float blue) { float c[4] = {red, green, blue, 1.0f}; ::glFogfv(GL_FOG_COLOR, c); } -void C4JRender::StateSetLightingEnable(bool enable) -{ +void C4JRender::StateSetLightingEnable(bool enable) { if (enable) { ::glEnable(GL_LIGHTING); // Enable color material so glColor calls set material ambient+diffuse @@ -830,58 +832,69 @@ void C4JRender::StateSetLightingEnable(bool enable) } } -void C4JRender::StateSetVertexTextureUV(float u, float v) -{ +void C4JRender::StateSetVertexTextureUV(float u, float v) { ::glMultiTexCoord2f(GL_TEXTURE1, u, v); } -void C4JRender::StateSetLightColour(int light, float red, float green, float blue) -{ +void C4JRender::StateSetLightColour(int light, float red, float green, + float blue) { float diffuse[4] = {red, green, blue, 1.0f}; ::glLightfv(GL_LIGHT0 + light, GL_DIFFUSE, diffuse); } -void C4JRender::StateSetLightAmbientColour(float red, float green, float blue) -{ +void C4JRender::StateSetLightAmbientColour(float red, float green, float blue) { float ambient[4] = {red, green, blue, 1.0f}; float model[4] = {red, green, blue, 1.0f}; ::glLightModelfv(GL_LIGHT_MODEL_AMBIENT, model); ::glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); } -void C4JRender::StateSetLightDirection(int light, float x, float y, float z) -{ - float dir[4] = {x, y, z, 0.0f}; // TODO: Java seems to do the reverse, gotta check. +void C4JRender::StateSetLightDirection(int light, float x, float y, float z) { + float dir[4] = {x, y, z, + 0.0f}; // TODO: Java seems to do the reverse, gotta check. ::glLightfv(GL_LIGHT0 + light, GL_POSITION, dir); } -void C4JRender::StateSetLightEnable(int light, bool enable) -{ +void C4JRender::StateSetLightEnable(int light, bool enable) { GLenum l = GL_LIGHT0 + light; - if (enable) ::glEnable(l); else ::glDisable(l); + if (enable) + ::glEnable(l); + else + ::glDisable(l); } -void C4JRender::StateSetViewport(eViewportType viewportType) -{ +void C4JRender::StateSetViewport(eViewportType viewportType) { // Use the full framebuffer for all viewport types ::glViewport(0, 0, s_windowWidth, s_windowHeight); } -void C4JRender::StateSetEnableViewportClipPlanes(bool enable) -{ +void C4JRender::StateSetEnableViewportClipPlanes(bool enable) { // Clip planes not commonly used in the legacy path - if (enable) ::glEnable(GL_CLIP_PLANE0); else ::glDisable(GL_CLIP_PLANE0); + if (enable) + ::glEnable(GL_CLIP_PLANE0); + else + ::glDisable(GL_CLIP_PLANE0); } -void C4JRender::StateSetTexGenCol(int col, float x, float y, float z, float w, bool eyeSpace) -{ +void C4JRender::StateSetTexGenCol(int col, float x, float y, float z, float w, + bool eyeSpace) { GLenum coord; switch (col) { - case 0: coord = GL_S; break; - case 1: coord = GL_T; break; - case 2: coord = GL_R; break; - case 3: coord = GL_Q; break; - default: coord = GL_S; break; + case 0: + coord = GL_S; + break; + case 1: + coord = GL_T; + break; + case 2: + coord = GL_R; + break; + case 3: + coord = GL_Q; + break; + default: + coord = GL_S; + break; } float plane[4] = {x, y, z, w}; GLenum planeMode = eyeSpace ? GL_EYE_PLANE : GL_OBJECT_PLANE; @@ -892,14 +905,13 @@ void C4JRender::StateSetTexGenCol(int col, float x, float y, float z, float w, b void C4JRender::StateSetStencil(int Function, uint8_t stencil_ref, uint8_t stencil_func_mask, - uint8_t stencil_write_mask) -{ + uint8_t stencil_write_mask) { ::glEnable(GL_STENCIL_TEST); ::glStencilFunc(Function, stencil_ref, stencil_func_mask); ::glStencilMask(stencil_write_mask); } -void C4JRender::StateSetForceLOD(int LOD) {} // No LOD bias in legacy GL path +void C4JRender::StateSetForceLOD(int LOD) {} // No LOD bias in legacy GL path void C4JRender::BeginEvent(LPCWSTR eventName) {} void C4JRender::EndEvent() {} diff --git a/4J.Render/4J_Render.h b/4J.Render/4J_Render.h index aa69717bc..bf8a4c6c1 100644 --- a/4J.Render/4J_Render.h +++ b/4J.Render/4J_Render.h @@ -6,218 +6,230 @@ #include -class ImageFileBuffer -{ +class ImageFileBuffer { public: - enum EImageType - { - e_typePNG, - e_typeJPG - }; + enum EImageType { e_typePNG, e_typeJPG }; - EImageType m_type; - void* m_pBuffer; - int m_bufferSize; + EImageType m_type; + void* m_pBuffer; + int m_bufferSize; - int GetType() { return m_type; } - void *GetBufferPointer() { return m_pBuffer; } - int GetBufferSize() { return m_bufferSize; } - void Release() { free(m_pBuffer); m_pBuffer = NULL; } - bool Allocated() { return m_pBuffer != NULL; } + int GetType() { return m_type; } + void* GetBufferPointer() { return m_pBuffer; } + int GetBufferSize() { return m_bufferSize; } + void Release() { + free(m_pBuffer); + m_pBuffer = NULL; + } + bool Allocated() { return m_pBuffer != NULL; } }; -typedef struct -{ - int Width; - int Height; -}D3DXIMAGE_INFO; +typedef struct { + int Width; + int Height; +} D3DXIMAGE_INFO; typedef struct _XSOCIAL_PREVIEWIMAGE { - BYTE *pBytes; + BYTE* pBytes; DWORD Pitch; DWORD Width; DWORD Height; -// D3DFORMAT Format; + // D3DFORMAT Format; } XSOCIAL_PREVIEWIMAGE, *PXSOCIAL_PREVIEWIMAGE; -class C4JRender -{ +class C4JRender { public: - void Tick(); - void UpdateGamma(unsigned short usGamma); + void Tick(); + void UpdateGamma(unsigned short usGamma); - // Matrix stack - void MatrixMode(int type); - void MatrixSetIdentity(); - void MatrixTranslate(float x,float y,float z); - void MatrixRotate(float angle, float x, float y, float z); - void MatrixScale(float x, float y, float z); - void MatrixPerspective(float fovy, float aspect, float zNear, float zFar); - void MatrixOrthogonal(float left,float right,float bottom,float top,float zNear,float zFar); - void MatrixPop(); - void MatrixPush(); - void MatrixMult(float *mat); - const float *MatrixGet(int type); - void Set_matrixDirty(); + // Matrix stack + void MatrixMode(int type); + void MatrixSetIdentity(); + void MatrixTranslate(float x, float y, float z); + void MatrixRotate(float angle, float x, float y, float z); + void MatrixScale(float x, float y, float z); + void MatrixPerspective(float fovy, float aspect, float zNear, float zFar); + void MatrixOrthogonal(float left, float right, float bottom, float top, + float zNear, float zFar); + void MatrixPop(); + void MatrixPush(); + void MatrixMult(float* mat); + const float* MatrixGet(int type); + void Set_matrixDirty(); - // Core - void Initialise(); - void InitialiseContext(); - // Call before Initialise() to override window size and/or fullscreen mode. - // If not called, the primary monitor's native resolution is used. - void SetWindowSize(int w, int h); - void SetFullscreen(bool fs); - void StartFrame(); - void DoScreenGrabOnNextPresent(); - void Present(); - void Clear(int flags); - void SetClearColour(const float colourRGBA[4]); - bool IsWidescreen(); - bool IsHiDef(); - void GetFramebufferSize(int &width, int &height); - void CaptureThumbnail(ImageFileBuffer *pngOut); - void CaptureScreen(ImageFileBuffer *jpgOut, XSOCIAL_PREVIEWIMAGE *previewOut); - void BeginConditionalSurvey(int identifier); - void EndConditionalSurvey(); - void BeginConditionalRendering(int identifier); - void EndConditionalRendering(); + // Core + void Initialise(); + void InitialiseContext(); + // Call before Initialise() to override window size and/or fullscreen mode. + // If not called, the primary monitor's native resolution is used. + void SetWindowSize(int w, int h); + void SetFullscreen(bool fs); + void StartFrame(); + void DoScreenGrabOnNextPresent(); + void Present(); + void Clear(int flags); + void SetClearColour(const float colourRGBA[4]); + bool IsWidescreen(); + bool IsHiDef(); + void GetFramebufferSize(int& width, int& height); + void CaptureThumbnail(ImageFileBuffer* pngOut); + void CaptureScreen(ImageFileBuffer* jpgOut, + XSOCIAL_PREVIEWIMAGE* previewOut); + void BeginConditionalSurvey(int identifier); + void EndConditionalSurvey(); + void BeginConditionalRendering(int identifier); + void EndConditionalRendering(); - // Vertex data handling - typedef enum - { - VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, // Position 3 x float, texture 2 x float, colour 4 x byte, normal 4 x byte, padding 1 DWORD - VERTEX_TYPE_COMPRESSED, // Compressed format - see comment at top of VS_PS3_TS2_CS1.hlsl for description of layout - VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_LIT, // as VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1 with lighting applied, - VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, // as VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1 with tex gen - VERTEX_TYPE_COUNT - } eVertexType; + // Vertex data handling + typedef enum { + VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, // Position 3 x float, texture 2 x + // float, colour 4 x byte, normal 4 x + // byte, padding 1 DWORD + VERTEX_TYPE_COMPRESSED, // Compressed format - see comment at top of + // VS_PS3_TS2_CS1.hlsl for description of + // layout + VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_LIT, // as + // VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1 + // with lighting applied, + VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, // as + // VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1 + // with tex gen + VERTEX_TYPE_COUNT + } eVertexType; - // Pixel shader - typedef enum - { - PIXEL_SHADER_TYPE_STANDARD, - PIXEL_SHADER_TYPE_PROJECTION, - PIXEL_SHADER_TYPE_FORCELOD, - PIXEL_SHADER_COUNT - } ePixelShaderType; + // Pixel shader + typedef enum { + PIXEL_SHADER_TYPE_STANDARD, + PIXEL_SHADER_TYPE_PROJECTION, + PIXEL_SHADER_TYPE_FORCELOD, + PIXEL_SHADER_COUNT + } ePixelShaderType; - typedef enum - { - VIEWPORT_TYPE_FULLSCREEN, - VIEWPORT_TYPE_SPLIT_TOP, - VIEWPORT_TYPE_SPLIT_BOTTOM, - VIEWPORT_TYPE_SPLIT_LEFT, - VIEWPORT_TYPE_SPLIT_RIGHT, - VIEWPORT_TYPE_QUADRANT_TOP_LEFT, - VIEWPORT_TYPE_QUADRANT_TOP_RIGHT, - VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT, - VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT, - } eViewportType; + typedef enum { + VIEWPORT_TYPE_FULLSCREEN, + VIEWPORT_TYPE_SPLIT_TOP, + VIEWPORT_TYPE_SPLIT_BOTTOM, + VIEWPORT_TYPE_SPLIT_LEFT, + VIEWPORT_TYPE_SPLIT_RIGHT, + VIEWPORT_TYPE_QUADRANT_TOP_LEFT, + VIEWPORT_TYPE_QUADRANT_TOP_RIGHT, + VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT, + VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT, + } eViewportType; - typedef enum - { - PRIMITIVE_TYPE_TRIANGLE_LIST, - PRIMITIVE_TYPE_TRIANGLE_STRIP, - PRIMITIVE_TYPE_TRIANGLE_FAN, - PRIMITIVE_TYPE_QUAD_LIST, - PRIMITIVE_TYPE_LINE_LIST, - PRIMITIVE_TYPE_LINE_STRIP, - PRIMITIVE_TYPE_COUNT - } ePrimitiveType; + typedef enum { + PRIMITIVE_TYPE_TRIANGLE_LIST, + PRIMITIVE_TYPE_TRIANGLE_STRIP, + PRIMITIVE_TYPE_TRIANGLE_FAN, + PRIMITIVE_TYPE_QUAD_LIST, + PRIMITIVE_TYPE_LINE_LIST, + PRIMITIVE_TYPE_LINE_STRIP, + PRIMITIVE_TYPE_COUNT + } ePrimitiveType; - void DrawVertices(ePrimitiveType PrimitiveType, int count, void *dataIn, eVertexType vType, C4JRender::ePixelShaderType psType); + void DrawVertices(ePrimitiveType PrimitiveType, int count, void* dataIn, + eVertexType vType, C4JRender::ePixelShaderType psType); - // Command buffers - void CBuffLockStaticCreations(); - int CBuffCreate(int count); - void CBuffDelete(int first, int count); - void CBuffStart(int index, bool full = false); - void CBuffClear(int index); - int CBuffSize(int index); - void CBuffEnd(); - bool CBuffCall(int index, bool full = true); - void CBuffTick(); - void CBuffDeferredModeStart(); - void CBuffDeferredModeEnd(); + // Command buffers + void CBuffLockStaticCreations(); + int CBuffCreate(int count); + void CBuffDelete(int first, int count); + void CBuffStart(int index, bool full = false); + void CBuffClear(int index); + int CBuffSize(int index); + void CBuffEnd(); + bool CBuffCall(int index, bool full = true); + void CBuffTick(); + void CBuffDeferredModeStart(); + void CBuffDeferredModeEnd(); - typedef enum - { - TEXTURE_FORMAT_RxGyBzAw, // Normal 32-bit RGBA texture, 8 bits per component - /* Don't think these are all directly available on D3D 11 - leaving for now - TEXTURE_FORMAT_R0G0B0Ax, // One 8-bit component mapped to alpha channel, R=G=B=0 - TEXTURE_FORMAT_R1G1B1Ax, // One 8-bit component mapped to alpha channel, R=G=B=1 - TEXTURE_FORMAT_RxGxBxAx, // One 8-bit component mapped to all channels - */ - MAX_TEXTURE_FORMATS - } eTextureFormat; + typedef enum { + TEXTURE_FORMAT_RxGyBzAw, // Normal 32-bit RGBA texture, 8 bits per + // component + /* Don't think these are all directly available on D3D 11 - leaving for + now TEXTURE_FORMAT_R0G0B0Ax, // One 8-bit component mapped to + alpha channel, R=G=B=0 TEXTURE_FORMAT_R1G1B1Ax, // One 8-bit + component mapped to alpha channel, R=G=B=1 TEXTURE_FORMAT_RxGxBxAx, + // One 8-bit component mapped to all channels + */ + MAX_TEXTURE_FORMATS + } eTextureFormat; - // Textures - int TextureCreate(); - void TextureFree(int idx); - void TextureBind(int idx); - void TextureBindVertex(int idx, bool scaleLight = false); - void TextureSetTextureLevels(int levels); - int TextureGetTextureLevels(); - void TextureData(int width, int height, void *data, int level, eTextureFormat format = TEXTURE_FORMAT_RxGyBzAw); - void TextureDataUpdate(int xoffset, int yoffset, int width, int height, void *data, int level); - void TextureSetParam(int param, int value); - void TextureDynamicUpdateStart(); - void TextureDynamicUpdateEnd(); - HRESULT LoadTextureData(const char *szFilename,D3DXIMAGE_INFO *pSrcInfo, int **ppDataOut); - HRESULT LoadTextureData(BYTE *pbData, DWORD dwBytes,D3DXIMAGE_INFO *pSrcInfo, int **ppDataOut); - HRESULT SaveTextureData(const char *szFilename, D3DXIMAGE_INFO *pSrcInfo, int *ppDataOut); - HRESULT SaveTextureDataToMemory(void *pOutput, int outputCapacity, int *outputLength, int width, int height, int *ppDataIn); - void TextureGetStats(); - void *TextureGetTexture(int idx); + // Textures + int TextureCreate(); + void TextureFree(int idx); + void TextureBind(int idx); + void TextureBindVertex(int idx, bool scaleLight = false); + void TextureSetTextureLevels(int levels); + int TextureGetTextureLevels(); + void TextureData(int width, int height, void* data, int level, + eTextureFormat format = TEXTURE_FORMAT_RxGyBzAw); + void TextureDataUpdate(int xoffset, int yoffset, int width, int height, + void* data, int level); + void TextureSetParam(int param, int value); + void TextureDynamicUpdateStart(); + void TextureDynamicUpdateEnd(); + HRESULT LoadTextureData(const char* szFilename, D3DXIMAGE_INFO* pSrcInfo, + int** ppDataOut); + HRESULT LoadTextureData(BYTE* pbData, DWORD dwBytes, + D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut); + HRESULT SaveTextureData(const char* szFilename, D3DXIMAGE_INFO* pSrcInfo, + int* ppDataOut); + HRESULT SaveTextureDataToMemory(void* pOutput, int outputCapacity, + int* outputLength, int width, int height, + int* ppDataIn); + void TextureGetStats(); + void* TextureGetTexture(int idx); - // State control - void StateSetColour(float r, float g, float b, float a); - void StateSetDepthMask(bool enable); - void StateSetBlendEnable(bool enable); - void StateSetBlendFunc(int src, int dst); - void StateSetBlendFactor(unsigned int colour); - void StateSetAlphaFunc(int func, float param); - void StateSetDepthFunc(int func); - void StateSetFaceCull(bool enable); - void StateSetFaceCullCW(bool enable); - void StateSetLineWidth(float width); - void StateSetWriteEnable(bool red, bool green, bool blue, bool alpha); - void StateSetDepthTestEnable(bool enable); - void StateSetAlphaTestEnable(bool enable); - void StateSetDepthSlopeAndBias(float slope, float bias); - void StateSetFogEnable(bool enable); - void StateSetFogMode(int mode); - void StateSetFogNearDistance(float dist); - void StateSetFogFarDistance(float dist); - void StateSetFogDensity(float density); - void StateSetFogColour(float red, float green, float blue); - void StateSetLightingEnable(bool enable); - void StateSetVertexTextureUV( float u, float v); - void StateSetLightColour(int light, float red, float green, float blue); - void StateSetLightAmbientColour(float red, float green, float blue); - void StateSetLightDirection(int light, float x, float y, float z); - void StateSetLightEnable(int light, bool enable); - void StateSetViewport(eViewportType viewportType); - void StateSetEnableViewportClipPlanes(bool enable); - void StateSetTexGenCol(int col, float x, float y, float z, float w, bool eyeSpace); - void StateSetStencil(int Function, uint8_t stencil_ref, uint8_t stencil_func_mask, uint8_t stencil_write_mask); - void StateSetForceLOD(int LOD); + // State control + void StateSetColour(float r, float g, float b, float a); + void StateSetDepthMask(bool enable); + void StateSetBlendEnable(bool enable); + void StateSetBlendFunc(int src, int dst); + void StateSetBlendFactor(unsigned int colour); + void StateSetAlphaFunc(int func, float param); + void StateSetDepthFunc(int func); + void StateSetFaceCull(bool enable); + void StateSetFaceCullCW(bool enable); + void StateSetLineWidth(float width); + void StateSetWriteEnable(bool red, bool green, bool blue, bool alpha); + void StateSetDepthTestEnable(bool enable); + void StateSetAlphaTestEnable(bool enable); + void StateSetDepthSlopeAndBias(float slope, float bias); + void StateSetFogEnable(bool enable); + void StateSetFogMode(int mode); + void StateSetFogNearDistance(float dist); + void StateSetFogFarDistance(float dist); + void StateSetFogDensity(float density); + void StateSetFogColour(float red, float green, float blue); + void StateSetLightingEnable(bool enable); + void StateSetVertexTextureUV(float u, float v); + void StateSetLightColour(int light, float red, float green, float blue); + void StateSetLightAmbientColour(float red, float green, float blue); + void StateSetLightDirection(int light, float x, float y, float z); + void StateSetLightEnable(int light, bool enable); + void StateSetViewport(eViewportType viewportType); + void StateSetEnableViewportClipPlanes(bool enable); + void StateSetTexGenCol(int col, float x, float y, float z, float w, + bool eyeSpace); + void StateSetStencil(int Function, uint8_t stencil_ref, + uint8_t stencil_func_mask, uint8_t stencil_write_mask); + void StateSetForceLOD(int LOD); - // Event tracking - void BeginEvent(LPCWSTR eventName); - void EndEvent(); + // Event tracking + void BeginEvent(LPCWSTR eventName); + void EndEvent(); - // PLM event handling - void Suspend(); - bool Suspended(); - void Resume(); + // PLM event handling + void Suspend(); + bool Suspended(); + void Resume(); - // Linux window management - bool ShouldClose(); - void Shutdown(); + // Linux window management + bool ShouldClose(); + void Shutdown(); }; - const int GL_MODELVIEW_MATRIX = 0x0BA6; const int GL_PROJECTION_MATRIX = 0x0BA7; const int GL_MODELVIEW = 0x1700; @@ -242,8 +254,8 @@ const int GL_EYE_LINEAR = 0x2400; const int GL_OBJECT_PLANE = 0x2501; const int GL_EYE_PLANE = 0x2502; - -// These things are used by glEnable/glDisable so must be different and non-zero (zero is used by things we haven't assigned yet) +// These things are used by glEnable/glDisable so must be different and non-zero +// (zero is used by things we haven't assigned yet) const int GL_TEXTURE_2D = 0x0DE1; const int GL_BLEND = 0x0BE2; const int GL_CULL_FACE = 0x0B44; @@ -286,7 +298,7 @@ const int GL_TEXTURE_WRAP_T = 0x2803; const int GL_NEAREST = 0x2600; const int GL_LINEAR = 0x2601; const int GL_EXP = 0x0800; -const int GL_NEAREST_MIPMAP_LINEAR = 0x2702; // TODO - mipmapping bit of this +const int GL_NEAREST_MIPMAP_LINEAR = 0x2702; // TODO - mipmapping bit of this const int GL_CLAMP = 0x2900; const int GL_REPEAT = 0x2901; @@ -312,5 +324,3 @@ const int GL_TRIANGLE_STRIP = 0x0005; // Singleton extern C4JRender RenderManager; - - diff --git a/4J.Render/stb_image.h b/4J.Render/stb_image.h index 9eedabedc..401a2d65e 100644 --- a/4J.Render/stb_image.h +++ b/4J.Render/stb_image.h @@ -3,7 +3,8 @@ Do this: #define STB_IMAGE_IMPLEMENTATION - before you include this file in *one* C or C++ file to create the implementation. + before you include this file in *one* C or C++ file to create the +implementation. // i.e. it should look like this: #include ... @@ -13,15 +14,16 @@ #include "stb_image.h" You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. - And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using +malloc,realloc,free QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface - JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) - PNG 1/2/4/8/16-bit-per-channel + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as +stock IJG lib) PNG 1/2/4/8/16-bit-per-channel TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE @@ -51,23 +53,19 @@ RECENT REVISION HISTORY: 2.30 (2024-05-31) avoid erroneous gcc warning 2.29 (2023-05-xx) optimizations 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff - 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes - 2.26 (2020-07-13) many minor fixes - 2.25 (2020-02-02) fix warnings - 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically - 2.23 (2019-08-11) fix clang static analysis warning - 2.22 (2019-03-04) gif fixes, fix warnings - 2.21 (2019-02-25) fix typo in comment - 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs - 2.19 (2018-02-11) fix warning - 2.18 (2018-01-30) fix warnings - 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings - 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes - 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC - 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs - 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes - 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes - 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug +fixes 2.26 (2020-07-13) many minor fixes 2.25 (2020-02-02) fix warnings 2.24 +(2020-02-02) fix warnings; thread-local failure_reason and flip_vertically 2.23 +(2019-08-11) fix clang static analysis warning 2.22 (2019-03-04) gif fixes, fix +warnings 2.21 (2019-02-25) fix typo in comment 2.20 (2019-02-07) support utf8 +filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix +warning 2.18 (2018-01-30) fix warnings 2.17 (2018-01-29) bugfix, 1-bit BMP, +16-bitness query, fix warnings 2.16 (2017-07-23) all functions have 16-bit +variants; optimizations; bugfixes 2.15 (2017-03-18) fix png-1,2,4; all Imagenet +JPGs; no runtime SSE detection on GCC 2.14 (2017-03-03) remove deprecated +STBI_JPEG_OLD; fixes for Imagenet JPGs 2.13 (2016-12-04) experimental 16-bit +API, only for PNG so far; fixes 2.12 (2016-04-02) fix typo in 2.11 PSD fix that +caused crashes 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 RGB-format JPEG; remove white matting in PSD; allocate large structures on the stack; correct channel count for PNG & BMP @@ -90,40 +88,39 @@ RECENT REVISION HISTORY: github:urraka (animated gif) Junggon Kim (PNM comments) Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) socks-the-fox (16-bit PNG) - Jeremy Sawicki (handle all ImageNet JPGs) - Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Jeremy Sawicki (handle all ImageNet +JPGs) Optimizations & bugfixes Mikhail Morozov (1-bit BMP) Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) Arseny Kapoulkine Simon Breuss (16-bit PNM) John-Mark Allen Carmelo J Fdez-Aguera Bug & warning fixes - Marc LeBlanc David Woo Guillaume George Martins Mozeiko - Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski - Phil Jordan Dave Moore Roy Eltham - Hayaki Saito Nathan Reed Won Chun - Luke Graham Johan Duparc Nick Verigakis the Horde3D community - Thomas Ruf Ronny Chevalier github:rlyeh - Janez Zemva John Bartholomew Michal Cichon github:romigrou - Jonathan Blow Ken Hamada Tero Hanninen github:svdijk - Eugene Golushkov Laurent Gomila Cort Stratton github:snagar - Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex - Cass Everitt Ryamond Barbiero github:grim210 - Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw - Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus - Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo - Julian Raschke Gregory Mullen Christian Floisand github:darealshinji - Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 - Brad Weinberger Matvey Cherevko github:mosra - Luca Sas Alexander Veselov Zack Middleton [reserved] - Ryan C. Gordon [reserved] [reserved] - DO NOT ADD YOUR NAME HERE + Marc LeBlanc David Woo Guillaume George Martins +Mozeiko Christpher Lloyd Jerry Jansson Joseph Thomson Blazej +Dariusz Roszkowski Phil Jordan Dave Moore Roy +Eltham Hayaki Saito Nathan Reed Won Chun Luke Graham Johan +Duparc Nick Verigakis the Horde3D community Thomas Ruf Ronny +Chevalier github:rlyeh Janez Zemva John +Bartholomew Michal Cichon github:romigrou Jonathan Blow Ken +Hamada Tero Hanninen github:svdijk Eugene Golushkov Laurent +Gomila Cort Stratton github:snagar Aruelien Pocheville Sergio +Gonzalez Thibault Reuille github:Zelex Cass Everitt Ryamond +Barbiero github:grim210 Paul Du Bois Engin +Manap Aldo Culquicondor github:sammyhw Philipp Wiesemann Dale +Weiler Oriol Ferrer Mesia github:phprus Josh Tobin Neil +Bickford Matthew Gregan github:poppolopoppo Julian Raschke Gregory +Mullen Christian Floisand github:darealshinji Baldur Karlsson Kevin +Schmidt JR Smith github:Michaelangel007 Brad Weinberger Matvey +Cherevko github:mosra Luca Sas Alexander Veselov Zack +Middleton [reserved] Ryan C. Gordon [reserved] [reserved] DO NOT +ADD YOUR NAME HERE Jacko Dirks - To add your name to the credits, pick a random blank space in the middle and fill it. - 80% of merge conflicts on stb PRs are due to people adding their name at the end - of the credits. + To add your name to the credits, pick a random blank space in the middle and +fill it. 80% of merge conflicts on stb PRs are due to people adding their name +at the end of the credits. */ #ifndef STBI_INCLUDE_STB_IMAGE_H @@ -142,14 +139,15 @@ RECENT REVISION HISTORY: // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel -// // ... but 'n' will always be the number that it would have been if you said 0 -// stbi_image_free(data); +// // ... but 'n' will always be the number that it would have been if you +// said 0 stbi_image_free(data); // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *channels_in_file -- outputs # of image components in image file -// int desired_channels -- if non-zero, # of image components requested in result +// int desired_channels -- if non-zero, # of image components requested in +// result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is @@ -177,8 +175,8 @@ RECENT REVISION HISTORY: // and *x, *y, *channels_in_file will be unchanged. The function // stbi_failure_reason() can be queried for an extremely brief, end-user // unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS -// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly -// more user-friendly ones. +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get +// slightly more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // @@ -228,11 +226,12 @@ RECENT REVISION HISTORY: // 2. easy to maintain // 3. good performance // -// Sometimes I let "good performance" creep up in priority over "easy to maintain", -// and for best performance I may provide less-easy-to-use APIs that give higher -// performance, in addition to the easy-to-use ones. Nevertheless, it's important -// to keep in mind that from the standpoint of you, a client of this library, -// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// Sometimes I let "good performance" creep up in priority over "easy to +// maintain", and for best performance I may provide less-easy-to-use APIs that +// give higher performance, in addition to the easy-to-use ones. Nevertheless, +// it's important to keep in mind that from the standpoint of you, a client of +// this library, all you care about is #1 and #3, and stb libraries DO NOT +// emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which // provide more explicit reasons why performance can't be emphasized. @@ -251,7 +250,8 @@ RECENT REVISION HISTORY: // overhead. // // The three functions you must define are "read" (reads some bytes of data), -// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the +// end). // // =========================================================================== // @@ -279,10 +279,11 @@ RECENT REVISION HISTORY: // HDR image support (disable by defining STBI_NO_HDR) // // stb_image supports loading HDR images in general, and currently the Radiance -// .HDR file format specifically. You can still load any file through the existing -// interface; if you attempt to load an HDR file, it will be automatically remapped -// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; -// both of these constants can be reconfigured through this interface: +// .HDR file format specifically. You can still load any file through the +// existing interface; if you attempt to load an HDR file, it will be +// automatically remapped to LDR, assuming gamma 2.2 and an arbitrary scale +// factor defaulting to 1; both of these constants can be reconfigured through +// this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); @@ -369,18 +370,17 @@ RECENT REVISION HISTORY: #ifndef STBI_NO_STDIO #include -#endif // STBI_NO_STDIO +#endif // STBI_NO_STDIO #define STBI_VERSION 1 -enum -{ - STBI_default = 0, // only used for desired_channels +enum { + STBI_default = 0, // only used for desired_channels - STBI_grey = 1, - STBI_grey_alpha = 2, - STBI_rgb = 3, - STBI_rgb_alpha = 4 + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 }; #include @@ -408,11 +408,13 @@ extern "C" { // load image by filename, open file, or memory buffer // -typedef struct -{ - int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read - void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative - int (*eof) (void *user); // returns nonzero if we are at end of file/data +typedef struct { + int (*read)(void* user, char* data, + int size); // fill 'data' with 'size' bytes. return number of + // bytes actually read + void (*skip)(void* user, int n); // skip the next 'n' bytes, or 'unget' the + // last -n bytes if negative + int (*eof)(void* user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; //////////////////////////////////// @@ -420,21 +422,33 @@ typedef struct // 8-bits-per-channel interface // -STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc* stbi_load_from_memory(stbi_uc const* buffer, int len, int* x, + int* y, int* channels_in_file, + int desired_channels); +STBIDEF stbi_uc* stbi_load_from_callbacks(stbi_io_callbacks const* clbk, + void* user, int* x, int* y, + int* channels_in_file, + int desired_channels); #ifndef STBI_NO_STDIO -STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); -// for stbi_load_from_file, file pointer is left pointing immediately after image +STBIDEF stbi_uc* stbi_load(char const* filename, int* x, int* y, + int* channels_in_file, int desired_channels); +STBIDEF stbi_uc* stbi_load_from_file(FILE* f, int* x, int* y, + int* channels_in_file, + int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after +// image #endif #ifndef STBI_NO_GIF -STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +STBIDEF stbi_uc* stbi_load_gif_from_memory(stbi_uc const* buffer, int len, + int** delays, int* x, int* y, int* z, + int* comp, int req_comp); #endif #ifdef STBI_WINDOWS_UTF8 -STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, + const wchar_t* input); #endif //////////////////////////////////// @@ -442,12 +456,20 @@ STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wch // 16-bits-per-channel interface // -STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us* stbi_load_16_from_memory(stbi_uc const* buffer, int len, + int* x, int* y, int* channels_in_file, + int desired_channels); +STBIDEF stbi_us* stbi_load_16_from_callbacks(stbi_io_callbacks const* clbk, + void* user, int* x, int* y, + int* channels_in_file, + int desired_channels); #ifndef STBI_NO_STDIO -STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us* stbi_load_16(char const* filename, int* x, int* y, + int* channels_in_file, int desired_channels); +STBIDEF stbi_us* stbi_load_from_file_16(FILE* f, int* x, int* y, + int* channels_in_file, + int desired_channels); #endif //////////////////////////////////// @@ -455,85 +477,106 @@ STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_i // float-per-channel interface // #ifndef STBI_NO_LINEAR - STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); - STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF float* stbi_loadf_from_memory(stbi_uc const* buffer, int len, int* x, + int* y, int* channels_in_file, + int desired_channels); +STBIDEF float* stbi_loadf_from_callbacks(stbi_io_callbacks const* clbk, + void* user, int* x, int* y, + int* channels_in_file, + int desired_channels); - #ifndef STBI_NO_STDIO - STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); - STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); - #endif +#ifndef STBI_NO_STDIO +STBIDEF float* stbi_loadf(char const* filename, int* x, int* y, + int* channels_in_file, int desired_channels); +STBIDEF float* stbi_loadf_from_file(FILE* f, int* x, int* y, + int* channels_in_file, + int desired_channels); +#endif #endif #ifndef STBI_NO_HDR - STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); - STBIDEF void stbi_hdr_to_ldr_scale(float scale); -#endif // STBI_NO_HDR +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); +STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR - STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); - STBIDEF void stbi_ldr_to_hdr_scale(float scale); -#endif // STBI_NO_LINEAR +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); +STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); -STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const* clbk, + void* user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const* buffer, int len); #ifndef STBI_NO_STDIO -STBIDEF int stbi_is_hdr (char const *filename); -STBIDEF int stbi_is_hdr_from_file(FILE *f); -#endif // STBI_NO_STDIO - +STBIDEF int stbi_is_hdr(char const* filename); +STBIDEF int stbi_is_hdr_from_file(FILE* f); +#endif // STBI_NO_STDIO // get a VERY brief reason for failure // on most compilers (and ALL modern mainstream compilers) this is threadsafe -STBIDEF const char *stbi_failure_reason (void); +STBIDEF const char* stbi_failure_reason(void); // free the loaded image -- this is just free() -STBIDEF void stbi_image_free (void *retval_from_stbi_load); +STBIDEF void stbi_image_free(void* retval_from_stbi_load); // get image dimensions & components without fully decoding -STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); -STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_info_from_memory(stbi_uc const* buffer, int len, int* x, + int* y, int* comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const* clbk, void* user, + int* x, int* y, int* comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const* buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const* clbk, + void* user); #ifndef STBI_NO_STDIO -STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); -STBIDEF int stbi_is_16_bit (char const *filename); -STBIDEF int stbi_is_16_bit_from_file(FILE *f); +STBIDEF int stbi_info(char const* filename, int* x, int* y, int* comp); +STBIDEF int stbi_info_from_file(FILE* f, int* x, int* y, int* comp); +STBIDEF int stbi_is_16_bit(char const* filename); +STBIDEF int stbi_is_16_bit_from_file(FILE* f); #endif - - // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. -STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_set_unpremultiply_on_load( + int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); -// flip the image vertically, so the first pixel in the output array is the bottom left +// flip the image vertically, so the first pixel in the output array is the +// bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); -// as above, but only applies to images loaded on the thread that calls the function -// this function is only available if your compiler supports thread-local variables; -// calling it will fail to link if your compiler doesn't -STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); -STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); -STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); +// as above, but only applies to images loaded on the thread that calls the +// function this function is only available if your compiler supports +// thread-local variables; calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread( + int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread( + int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread( + int flag_true_if_should_flip); // ZLIB client - used by PNG, available for other purposes -STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); -STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); -STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); -STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); - -STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); -STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); +STBIDEF char* stbi_zlib_decode_malloc_guesssize(const char* buffer, int len, + int initial_size, int* outlen); +STBIDEF char* stbi_zlib_decode_malloc_guesssize_headerflag(const char* buffer, + int len, + int initial_size, + int* outlen, + int parse_header); +STBIDEF char* stbi_zlib_decode_malloc(const char* buffer, int len, int* outlen); +STBIDEF int stbi_zlib_decode_buffer(char* obuffer, int olen, + const char* ibuffer, int ilen); +STBIDEF char* stbi_zlib_decode_noheader_malloc(const char* buffer, int len, + int* outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char* obuffer, int olen, + const char* ibuffer, int ilen); #ifdef __cplusplus } @@ -542,50 +585,51 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch // // //// end header file ///////////////////////////////////////////////////// -#endif // STBI_INCLUDE_STB_IMAGE_H +#endif // STBI_INCLUDE_STB_IMAGE_H #ifdef STB_IMAGE_IMPLEMENTATION -#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ - || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ - || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ - || defined(STBI_ONLY_ZLIB) - #ifndef STBI_ONLY_JPEG - #define STBI_NO_JPEG - #endif - #ifndef STBI_ONLY_PNG - #define STBI_NO_PNG - #endif - #ifndef STBI_ONLY_BMP - #define STBI_NO_BMP - #endif - #ifndef STBI_ONLY_PSD - #define STBI_NO_PSD - #endif - #ifndef STBI_ONLY_TGA - #define STBI_NO_TGA - #endif - #ifndef STBI_ONLY_GIF - #define STBI_NO_GIF - #endif - #ifndef STBI_ONLY_HDR - #define STBI_NO_HDR - #endif - #ifndef STBI_ONLY_PIC - #define STBI_NO_PIC - #endif - #ifndef STBI_ONLY_PNM - #define STBI_NO_PNM - #endif +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || \ + defined(STBI_ONLY_BMP) || defined(STBI_ONLY_TGA) || \ + defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) || \ + defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || \ + defined(STBI_ONLY_PNM) || defined(STBI_ONLY_ZLIB) +#ifndef STBI_ONLY_JPEG +#define STBI_NO_JPEG +#endif +#ifndef STBI_ONLY_PNG +#define STBI_NO_PNG +#endif +#ifndef STBI_ONLY_BMP +#define STBI_NO_BMP +#endif +#ifndef STBI_ONLY_PSD +#define STBI_NO_PSD +#endif +#ifndef STBI_ONLY_TGA +#define STBI_NO_TGA +#endif +#ifndef STBI_ONLY_GIF +#define STBI_NO_GIF +#endif +#ifndef STBI_ONLY_HDR +#define STBI_NO_HDR +#endif +#ifndef STBI_ONLY_PIC +#define STBI_NO_PIC +#endif +#ifndef STBI_ONLY_PNM +#define STBI_NO_PNM +#endif #endif -#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && \ + !defined(STBI_NO_ZLIB) #define STBI_NO_ZLIB #endif - #include -#include // ptrdiff_t on osx +#include // ptrdiff_t on osx #include #include #include @@ -609,55 +653,55 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch #define STBI_EXTERN extern #endif - #ifndef _MSC_VER - #ifdef __cplusplus - #define stbi_inline inline - #else - #define stbi_inline - #endif +#ifdef __cplusplus +#define stbi_inline inline #else - #define stbi_inline __forceinline +#define stbi_inline +#endif +#else +#define stbi_inline __forceinline #endif #ifndef STBI_NO_THREAD_LOCALS - #if defined(__cplusplus) && __cplusplus >= 201103L - #define STBI_THREAD_LOCAL thread_local - #elif defined(__GNUC__) && __GNUC__ < 5 - #define STBI_THREAD_LOCAL __thread - #elif defined(_MSC_VER) - #define STBI_THREAD_LOCAL __declspec(thread) - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) - #define STBI_THREAD_LOCAL _Thread_local - #endif +#if defined(__cplusplus) && __cplusplus >= 201103L +#define STBI_THREAD_LOCAL thread_local +#elif defined(__GNUC__) && __GNUC__ < 5 +#define STBI_THREAD_LOCAL __thread +#elif defined(_MSC_VER) +#define STBI_THREAD_LOCAL __declspec(thread) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && \ + !defined(__STDC_NO_THREADS__) +#define STBI_THREAD_LOCAL _Thread_local +#endif - #ifndef STBI_THREAD_LOCAL - #if defined(__GNUC__) - #define STBI_THREAD_LOCAL __thread - #endif - #endif +#ifndef STBI_THREAD_LOCAL +#if defined(__GNUC__) +#define STBI_THREAD_LOCAL __thread +#endif +#endif #endif #if defined(_MSC_VER) || defined(__SYMBIAN32__) typedef unsigned short stbi__uint16; -typedef signed short stbi__int16; -typedef unsigned int stbi__uint32; -typedef signed int stbi__int32; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; #else #include typedef uint16_t stbi__uint16; -typedef int16_t stbi__int16; +typedef int16_t stbi__int16; typedef uint32_t stbi__uint32; -typedef int32_t stbi__int32; +typedef int32_t stbi__int32; #endif // should produce compiler error if size is wrong -typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; +typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1]; #ifdef _MSC_VER -#define STBI_NOTUSED(v) (void)(v) +#define STBI_NOTUSED(v) (void)(v) #else -#define STBI_NOTUSED(v) (void)sizeof(v) +#define STBI_NOTUSED(v) (void)sizeof(v) #endif #ifdef _MSC_VER @@ -665,27 +709,30 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #endif #ifdef STBI_HAS_LROTL - #define stbi_lrot(x,y) _lrotl(x,y) +#define stbi_lrot(x, y) _lrotl(x, y) #else - #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) +#define stbi_lrot(x, y) (((x) << (y)) | ((x) >> (-(y) & 31))) #endif -#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +#if defined(STBI_MALLOC) && defined(STBI_FREE) && \ + (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok -#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && \ + !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else -#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#error \ + "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC -#define STBI_MALLOC(sz) malloc(sz) -#define STBI_REALLOC(p,newsz) realloc(p,newsz) -#define STBI_FREE(p) free(p) +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p, newsz) realloc(p, newsz) +#define STBI_FREE(p) free(p) #endif #ifndef STBI_REALLOC_SIZED -#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#define STBI_REALLOC_SIZED(p, oldsz, newsz) STBI_REALLOC(p, newsz) #endif // x86/x64 detection @@ -695,7 +742,8 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #define STBI__X86_TARGET #endif -#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && \ + !defined(STBI_NO_SIMD) // gcc doesn't support sse2 intrinsics unless you compile with -msse2, // which in turn means it gets to use SSE2 everywhere. This is unfortunate, // but previous attempts to provide the SSE2 functions with runtime @@ -706,8 +754,10 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #define STBI_NO_SIMD #endif -#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) -// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && \ + !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid +// STBI__X64_TARGET // // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. @@ -717,57 +767,55 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; // See https://github.com/nothings/stb/issues/81 for more information. // // So default to no SSE2 on 32-bit MinGW. If you've read this far and added -// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +// -mstackrealign to your build settings, feel free to #define +// STBI_MINGW_ENABLE_SSE2. #define STBI_NO_SIMD #endif -#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#if !defined(STBI_NO_SIMD) && \ + (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include #ifdef _MSC_VER #if _MSC_VER >= 1400 // not VC6 -#include // __cpuid -static int stbi__cpuid3(void) -{ - int info[4]; - __cpuid(info,1); - return info[3]; +#include // __cpuid +static int stbi__cpuid3(void) { + int info[4]; + __cpuid(info, 1); + return info[3]; } #else -static int stbi__cpuid3(void) -{ - int res; - __asm { +static int stbi__cpuid3(void) { + int res; + __asm { mov eax,1 cpuid mov res,edx - } - return res; + } + return res; } #endif #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) -static int stbi__sse2_available(void) -{ - int info3 = stbi__cpuid3(); - return ((info3 >> 26) & 1) != 0; +static int stbi__sse2_available(void) { + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; } #endif -#else // assume GCC-style if not VC++ +#else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) -static int stbi__sse2_available(void) -{ - // If we're even attempting to compile this on GCC/Clang, that means - // -msse2 is on, which means the compiler is allowed to use SSE2 - // instructions at will, and so are we. - return 1; +static int stbi__sse2_available(void) { + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; } #endif @@ -802,190 +850,180 @@ static int stbi__sse2_available(void) // stbi__context structure is our basic context used by all images, so it // contains all the IO context, plus some basic image information -typedef struct -{ - stbi__uint32 img_x, img_y; - int img_n, img_out_n; +typedef struct { + stbi__uint32 img_x, img_y; + int img_n, img_out_n; - stbi_io_callbacks io; - void *io_user_data; + stbi_io_callbacks io; + void* io_user_data; - int read_from_callbacks; - int buflen; - stbi_uc buffer_start[128]; - int callback_already_read; + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; - stbi_uc *img_buffer, *img_buffer_end; - stbi_uc *img_buffer_original, *img_buffer_original_end; + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; } stbi__context; - -static void stbi__refill_buffer(stbi__context *s); +static void stbi__refill_buffer(stbi__context* s); // initialize a memory-decode context -static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) -{ - s->io.read = NULL; - s->read_from_callbacks = 0; - s->callback_already_read = 0; - s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; - s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +static void stbi__start_mem(stbi__context* s, stbi_uc const* buffer, int len) { + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc*)buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc*)buffer + len; } // initialize a callback-based context -static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) -{ - s->io = *c; - s->io_user_data = user; - s->buflen = sizeof(s->buffer_start); - s->read_from_callbacks = 1; - s->callback_already_read = 0; - s->img_buffer = s->img_buffer_original = s->buffer_start; - stbi__refill_buffer(s); - s->img_buffer_original_end = s->img_buffer_end; +static void stbi__start_callbacks(stbi__context* s, stbi_io_callbacks* c, + void* user) { + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; } #ifndef STBI_NO_STDIO -static int stbi__stdio_read(void *user, char *data, int size) -{ - return (int) fread(data,1,size,(FILE*) user); +static int stbi__stdio_read(void* user, char* data, int size) { + return (int)fread(data, 1, size, (FILE*)user); } -static void stbi__stdio_skip(void *user, int n) -{ - int ch; - fseek((FILE*) user, n, SEEK_CUR); - ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ - if (ch != EOF) { - ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ - } +static void stbi__stdio_skip(void* user, int n) { + int ch; + fseek((FILE*)user, n, SEEK_CUR); + ch = fgetc((FILE*)user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE*)user); /* push byte back onto stream if valid. */ + } } -static int stbi__stdio_eof(void *user) -{ - return feof((FILE*) user) || ferror((FILE *) user); +static int stbi__stdio_eof(void* user) { + return feof((FILE*)user) || ferror((FILE*)user); } -static stbi_io_callbacks stbi__stdio_callbacks = -{ - stbi__stdio_read, - stbi__stdio_skip, - stbi__stdio_eof, +static stbi_io_callbacks stbi__stdio_callbacks = { + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, }; -static void stbi__start_file(stbi__context *s, FILE *f) -{ - stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +static void stbi__start_file(stbi__context* s, FILE* f) { + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void*)f); } -//static void stop_file(stbi__context *s) { } +// static void stop_file(stbi__context *s) { } -#endif // !STBI_NO_STDIO +#endif // !STBI_NO_STDIO -static void stbi__rewind(stbi__context *s) -{ - // conceptually rewind SHOULD rewind to the beginning of the stream, - // but we just rewind to the beginning of the initial buffer, because - // we only use it after doing 'test', which only ever looks at at most 92 bytes - s->img_buffer = s->img_buffer_original; - s->img_buffer_end = s->img_buffer_original_end; +static void stbi__rewind(stbi__context* s) { + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 + // bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; } -enum -{ - STBI_ORDER_RGB, - STBI_ORDER_BGR -}; +enum { STBI_ORDER_RGB, STBI_ORDER_BGR }; -typedef struct -{ - int bits_per_channel; - int num_channels; - int channel_order; +typedef struct { + int bits_per_channel; + int num_channels; + int channel_order; } stbi__result_info; #ifndef STBI_NO_JPEG -static int stbi__jpeg_test(stbi__context *s); -static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__jpeg_test(stbi__context* s); +static void* stbi__jpeg_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static int stbi__jpeg_info(stbi__context* s, int* x, int* y, int* comp); #endif #ifndef STBI_NO_PNG -static int stbi__png_test(stbi__context *s); -static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__png_is16(stbi__context *s); +static int stbi__png_test(stbi__context* s); +static void* stbi__png_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static int stbi__png_info(stbi__context* s, int* x, int* y, int* comp); +static int stbi__png_is16(stbi__context* s); #endif #ifndef STBI_NO_BMP -static int stbi__bmp_test(stbi__context *s); -static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__bmp_test(stbi__context* s); +static void* stbi__bmp_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static int stbi__bmp_info(stbi__context* s, int* x, int* y, int* comp); #endif #ifndef STBI_NO_TGA -static int stbi__tga_test(stbi__context *s); -static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__tga_test(stbi__context* s); +static void* stbi__tga_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static int stbi__tga_info(stbi__context* s, int* x, int* y, int* comp); #endif #ifndef STBI_NO_PSD -static int stbi__psd_test(stbi__context *s); -static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); -static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__psd_is16(stbi__context *s); +static int stbi__psd_test(stbi__context* s); +static void* stbi__psd_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri, int bpc); +static int stbi__psd_info(stbi__context* s, int* x, int* y, int* comp); +static int stbi__psd_is16(stbi__context* s); #endif #ifndef STBI_NO_HDR -static int stbi__hdr_test(stbi__context *s); -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__hdr_test(stbi__context* s); +static float* stbi__hdr_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static int stbi__hdr_info(stbi__context* s, int* x, int* y, int* comp); #endif #ifndef STBI_NO_PIC -static int stbi__pic_test(stbi__context *s); -static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pic_test(stbi__context* s); +static void* stbi__pic_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static int stbi__pic_info(stbi__context* s, int* x, int* y, int* comp); #endif #ifndef STBI_NO_GIF -static int stbi__gif_test(stbi__context *s); -static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); -static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__gif_test(stbi__context* s); +static void* stbi__gif_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static void* stbi__load_gif_main(stbi__context* s, int** delays, int* x, int* y, + int* z, int* comp, int req_comp); +static int stbi__gif_info(stbi__context* s, int* x, int* y, int* comp); #endif #ifndef STBI_NO_PNM -static int stbi__pnm_test(stbi__context *s); -static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__pnm_is16(stbi__context *s); +static int stbi__pnm_test(stbi__context* s); +static void* stbi__pnm_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri); +static int stbi__pnm_info(stbi__context* s, int* x, int* y, int* comp); +static int stbi__pnm_is16(stbi__context* s); #endif static #ifdef STBI_THREAD_LOCAL -STBI_THREAD_LOCAL + STBI_THREAD_LOCAL #endif -const char *stbi__g_failure_reason; + const char* stbi__g_failure_reason; -STBIDEF const char *stbi_failure_reason(void) -{ - return stbi__g_failure_reason; -} +STBIDEF const char* stbi_failure_reason(void) { return stbi__g_failure_reason; } #ifndef STBI_NO_FAILURE_STRINGS -static int stbi__err(const char *str) -{ - stbi__g_failure_reason = str; - return 0; +static int stbi__err(const char* str) { + stbi__g_failure_reason = str; + return 0; } #endif -static void *stbi__malloc(size_t size) -{ - return STBI_MALLOC(size); -} +static void* stbi__malloc(size_t size) { return STBI_MALLOC(size); } // stb_image uses ints pervasively, including for offset calculations. // therefore the largest decoded image size we can support with the @@ -999,88 +1037,91 @@ static void *stbi__malloc(size_t size) // return 1 if the sum is valid, 0 on overflow. // negative terms are considered invalid. -static int stbi__addsizes_valid(int a, int b) -{ - if (b < 0) return 0; - // now 0 <= b <= INT_MAX, hence also - // 0 <= INT_MAX - b <= INTMAX. - // And "a + b <= INT_MAX" (which might overflow) is the - // same as a <= INT_MAX - b (no overflow) - return a <= INT_MAX - b; +static int stbi__addsizes_valid(int a, int b) { + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; } // returns 1 if the product is valid, 0 on overflow. // negative factors are considered invalid. -static int stbi__mul2sizes_valid(int a, int b) -{ - if (a < 0 || b < 0) return 0; - if (b == 0) return 1; // mul-by-0 is always safe - // portable way to check for no overflows in a*b - return a <= INT_MAX/b; +static int stbi__mul2sizes_valid(int a, int b) { + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX / b; } -#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || \ + !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow -static int stbi__mad2sizes_valid(int a, int b, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +static int stbi__mad2sizes_valid(int a, int b, int add) { + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a * b, add); } #endif // returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow -static int stbi__mad3sizes_valid(int a, int b, int c, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && - stbi__addsizes_valid(a*b*c, add); +static int stbi__mad3sizes_valid(int a, int b, int c, int add) { + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) && + stbi__addsizes_valid(a * b * c, add); } -// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't +// overflow #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) -static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && - stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) { + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c) && + stbi__mul2sizes_valid(a * b * c, d) && + stbi__addsizes_valid(a * b * c * d, add); } #endif -#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || \ + !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // mallocs with size overflow checking -static void *stbi__malloc_mad2(int a, int b, int add) -{ - if (!stbi__mad2sizes_valid(a, b, add)) return NULL; - return stbi__malloc(a*b + add); +static void* stbi__malloc_mad2(int a, int b, int add) { + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a * b + add); } #endif -static void *stbi__malloc_mad3(int a, int b, int c, int add) -{ - if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; - return stbi__malloc(a*b*c + add); +static void* stbi__malloc_mad3(int a, int b, int c, int add) { + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a * b * c + add); } #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) -static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) -{ - if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; - return stbi__malloc(a*b*c*d + add); +static void* stbi__malloc_mad4(int a, int b, int c, int d, int add) { + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a * b * c * d + add); } #endif -// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. -static int stbi__addints_valid(int a, int b) -{ - if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow - if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. - return a <= INT_MAX - b; +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 +// inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) { + if ((a >= 0) != (b >= 0)) + return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) + return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b + // cannot overflow since b < 0. + return a <= INT_MAX - b; } // returns 1 if the product of two ints fits in a signed short, 0 on overflow. -static int stbi__mul2shorts_valid(int a, int b) -{ - if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow - if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid - if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN - return a >= SHRT_MIN / b; +static int stbi__mul2shorts_valid(int a, int b) { + if (b == 0 || b == -1) + return 1; // multiplication by 0 is always 0; check for -1 so + // SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) + return a <= + SHRT_MAX / + b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; } // stbi__err - error @@ -1088,648 +1129,669 @@ static int stbi__mul2shorts_valid(int a, int b) // stbi__errpuc - error returning pointer to unsigned char #ifdef STBI_NO_FAILURE_STRINGS - #define stbi__err(x,y) 0 +#define stbi__err(x, y) 0 #elif defined(STBI_FAILURE_USERMSG) - #define stbi__err(x,y) stbi__err(y) +#define stbi__err(x, y) stbi__err(y) #else - #define stbi__err(x,y) stbi__err(x) +#define stbi__err(x, y) stbi__err(x) #endif -#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) -#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpf(x, y) ((float*)(size_t)(stbi__err(x, y) ? NULL : NULL)) +#define stbi__errpuc(x, y) \ + ((unsigned char*)(size_t)(stbi__err(x, y) ? NULL : NULL)) -STBIDEF void stbi_image_free(void *retval_from_stbi_load) -{ - STBI_FREE(retval_from_stbi_load); +STBIDEF void stbi_image_free(void* retval_from_stbi_load) { + STBI_FREE(retval_from_stbi_load); } #ifndef STBI_NO_LINEAR -static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +static float* stbi__ldr_to_hdr(stbi_uc* data, int x, int y, int comp); #endif #ifndef STBI_NO_HDR -static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +static stbi_uc* stbi__hdr_to_ldr(float* data, int x, int y, int comp); #endif static int stbi__vertically_flip_on_load_global = 0; -STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) -{ - stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; } #ifndef STBI_THREAD_LOCAL -#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global #else -static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, + stbi__vertically_flip_on_load_set; -STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) -{ - stbi__vertically_flip_on_load_local = flag_true_if_should_flip; - stbi__vertically_flip_on_load_set = 1; +STBIDEF void stbi_set_flip_vertically_on_load_thread( + int flag_true_if_should_flip) { + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; } -#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ - ? stbi__vertically_flip_on_load_local \ - : stbi__vertically_flip_on_load_global) -#endif // STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load \ + (stbi__vertically_flip_on_load_set ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL -static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) -{ - memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields - ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed - ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order - ri->num_channels = 0; +static void* stbi__load_main(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri, int bpc) { + memset(ri, 0, + sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = + 8; // default is 8 so most paths don't have to be changed + ri->channel_order = + STBI_ORDER_RGB; // all current input & output are this, but this is + // here so we can add BGR order + ri->num_channels = 0; - // test the formats with a very explicit header first (at least a FOURCC - // or distinctive magic number first) - #ifndef STBI_NO_PNG - if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_BMP - if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_GIF - if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_PSD - if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); - #else - STBI_NOTUSED(bpc); - #endif - #ifndef STBI_NO_PIC - if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); - #endif +// test the formats with a very explicit header first (at least a FOURCC +// or distinctive magic number first) +#ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_PSD + if (stbi__psd_test(s)) + return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc); +#else + STBI_NOTUSED(bpc); +#endif +#ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s, x, y, comp, req_comp, ri); +#endif - // then the formats that can end up attempting to load with just 1 or 2 - // bytes matching expectations; these are prone to false positives, so - // try them later - #ifndef STBI_NO_JPEG - if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_PNM - if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); - #endif +// then the formats that can end up attempting to load with just 1 or 2 +// bytes matching expectations; these are prone to false positives, so +// try them later +#ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s, x, y, comp, req_comp, ri); +#endif - #ifndef STBI_NO_HDR - if (stbi__hdr_test(s)) { - float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); - return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); - } - #endif +#ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float* hdr = stbi__hdr_load(s, x, y, comp, req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } +#endif - #ifndef STBI_NO_TGA - // test tga last because it's a crappy test! - if (stbi__tga_test(s)) - return stbi__tga_load(s,x,y,comp,req_comp, ri); - #endif +#ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) return stbi__tga_load(s, x, y, comp, req_comp, ri); +#endif - return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); + return stbi__errpuc("unknown image type", + "Image not of any known type, or corrupt"); } -static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) -{ - int i; - int img_len = w * h * channels; - stbi_uc *reduced; +static stbi_uc* stbi__convert_16_to_8(stbi__uint16* orig, int w, int h, + int channels) { + int i; + int img_len = w * h * channels; + stbi_uc* reduced; - reduced = (stbi_uc *) stbi__malloc(img_len); - if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + reduced = (stbi_uc*)stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); - for (i = 0; i < img_len; ++i) - reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & + 0xFF); // top half of each byte is sufficient + // approx of 16->8 bit scaling - STBI_FREE(orig); - return reduced; + STBI_FREE(orig); + return reduced; } -static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) -{ - int i; - int img_len = w * h * channels; - stbi__uint16 *enlarged; +static stbi__uint16* stbi__convert_8_to_16(stbi_uc* orig, int w, int h, + int channels) { + int i; + int img_len = w * h * channels; + stbi__uint16* enlarged; - enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); - if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + enlarged = (stbi__uint16*)stbi__malloc(img_len * 2); + if (enlarged == NULL) + return (stbi__uint16*)stbi__errpuc("outofmem", "Out of memory"); - for (i = 0; i < img_len; ++i) - enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + + orig[i]); // replicate to high and low + // byte, maps 0->0, 255->0xffff - STBI_FREE(orig); - return enlarged; + STBI_FREE(orig); + return enlarged; } -static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) -{ - int row; - size_t bytes_per_row = (size_t)w * bytes_per_pixel; - stbi_uc temp[2048]; - stbi_uc *bytes = (stbi_uc *)image; +static void stbi__vertical_flip(void* image, int w, int h, + int bytes_per_pixel) { + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc* bytes = (stbi_uc*)image; - for (row = 0; row < (h>>1); row++) { - stbi_uc *row0 = bytes + row*bytes_per_row; - stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; - // swap row0 with row1 - size_t bytes_left = bytes_per_row; - while (bytes_left) { - size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); - memcpy(temp, row0, bytes_copy); - memcpy(row0, row1, bytes_copy); - memcpy(row1, temp, bytes_copy); - row0 += bytes_copy; - row1 += bytes_copy; - bytes_left -= bytes_copy; - } - } + for (row = 0; row < (h >> 1); row++) { + stbi_uc* row0 = bytes + row * bytes_per_row; + stbi_uc* row1 = bytes + (h - row - 1) * bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = + (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } } #ifndef STBI_NO_GIF -static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) -{ - int slice; - int slice_size = w * h * bytes_per_pixel; +static void stbi__vertical_flip_slices(void* image, int w, int h, int z, + int bytes_per_pixel) { + int slice; + int slice_size = w * h * bytes_per_pixel; - stbi_uc *bytes = (stbi_uc *)image; - for (slice = 0; slice < z; ++slice) { - stbi__vertical_flip(bytes, w, h, bytes_per_pixel); - bytes += slice_size; - } + stbi_uc* bytes = (stbi_uc*)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } } #endif -static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - stbi__result_info ri; - void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); +static unsigned char* stbi__load_and_postprocess_8bit(stbi__context* s, int* x, + int* y, int* comp, + int req_comp) { + stbi__result_info ri; + void* result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); - if (result == NULL) - return NULL; + if (result == NULL) return NULL; - // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. - STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + // it is the responsibility of the loaders to make sure we get either 8 or + // 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); - if (ri.bits_per_channel != 8) { - result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); - ri.bits_per_channel = 8; - } + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16*)result, *x, *y, + req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } - // @TODO: move stbi__convert_format to here + // @TODO: move stbi__convert_format to here - if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); - } + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } - return (unsigned char *) result; + return (unsigned char*)result; } -static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - stbi__result_info ri; - void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); +static stbi__uint16* stbi__load_and_postprocess_16bit(stbi__context* s, int* x, + int* y, int* comp, + int req_comp) { + stbi__result_info ri; + void* result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); - if (result == NULL) - return NULL; + if (result == NULL) return NULL; - // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. - STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + // it is the responsibility of the loaders to make sure we get either 8 or + // 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); - if (ri.bits_per_channel != 16) { - result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); - ri.bits_per_channel = 16; - } + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc*)result, *x, *y, + req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } - // @TODO: move stbi__convert_format16 to here - // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to + // keep more precision - if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); - } + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } - return (stbi__uint16 *) result; + return (stbi__uint16*)result; } #if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) -static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) -{ - if (stbi__vertically_flip_on_load && result != NULL) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); - } +static void stbi__float_postprocess(float* result, int* x, int* y, int* comp, + int req_comp) { + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } } #endif #ifndef STBI_NO_STDIO #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) -STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); -STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar( + unsigned int cp, unsigned long flags, const char* str, int cbmb, + wchar_t* widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte( + unsigned int cp, unsigned long flags, const wchar_t* widestr, int cchwide, + char* str, int cbmb, const char* defchar, int* used_default); #endif #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) -STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) -{ - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, + const wchar_t* input) { + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, + (int)bufferlen, NULL, NULL); } #endif -static FILE *stbi__fopen(char const *filename, char const *mode) -{ - FILE *f; +static FILE* stbi__fopen(char const* filename, char const* mode) { + FILE* f; #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) - wchar_t wMode[64]; - wchar_t wFilename[1024]; - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) - return 0; + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, + sizeof(wFilename) / sizeof(*wFilename))) + return 0; - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) - return 0; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, + sizeof(wMode) / sizeof(*wMode))) + return 0; #if defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != _wfopen_s(&f, wFilename, wMode)) - f = 0; + if (0 != _wfopen_s(&f, wFilename, wMode)) f = 0; #else - f = _wfopen(wFilename, wMode); + f = _wfopen(wFilename, wMode); #endif #elif defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != fopen_s(&f, filename, mode)) - f=0; + if (0 != fopen_s(&f, filename, mode)) f = 0; #else - f = fopen(filename, mode); + f = fopen(filename, mode); #endif - return f; + return f; } - -STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - unsigned char *result; - if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); - result = stbi_load_from_file(f,x,y,comp,req_comp); - fclose(f); - return result; +STBIDEF stbi_uc* stbi_load(char const* filename, int* x, int* y, int* comp, + int req_comp) { + FILE* f = stbi__fopen(filename, "rb"); + unsigned char* result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f, x, y, comp, req_comp); + fclose(f); + return result; } -STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - unsigned char *result; - stbi__context s; - stbi__start_file(&s,f); - result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); - if (result) { - // need to 'unget' all the characters in the IO buffer - fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); - } - return result; +STBIDEF stbi_uc* stbi_load_from_file(FILE* f, int* x, int* y, int* comp, + int req_comp) { + unsigned char* result; + stbi__context s; + stbi__start_file(&s, f); + result = stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; } -STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - stbi__uint16 *result; - stbi__context s; - stbi__start_file(&s,f); - result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); - if (result) { - // need to 'unget' all the characters in the IO buffer - fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); - } - return result; +STBIDEF stbi__uint16* stbi_load_from_file_16(FILE* f, int* x, int* y, int* comp, + int req_comp) { + stbi__uint16* result; + stbi__context s; + stbi__start_file(&s, f); + result = stbi__load_and_postprocess_16bit(&s, x, y, comp, req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; } -STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - stbi__uint16 *result; - if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); - result = stbi_load_from_file_16(f,x,y,comp,req_comp); - fclose(f); - return result; +STBIDEF stbi_us* stbi_load_16(char const* filename, int* x, int* y, int* comp, + int req_comp) { + FILE* f = stbi__fopen(filename, "rb"); + stbi__uint16* result; + if (!f) return (stbi_us*)stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f, x, y, comp, req_comp); + fclose(f); + return result; } +#endif //! STBI_NO_STDIO -#endif //!STBI_NO_STDIO - -STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +STBIDEF stbi_us* stbi_load_16_from_memory(stbi_uc const* buffer, int len, + int* x, int* y, int* channels_in_file, + int desired_channels) { + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, + desired_channels); } -STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); - return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +STBIDEF stbi_us* stbi_load_16_from_callbacks(stbi_io_callbacks const* clbk, + void* user, int* x, int* y, + int* channels_in_file, + int desired_channels) { + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, + desired_channels); } -STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +STBIDEF stbi_uc* stbi_load_from_memory(stbi_uc const* buffer, int len, int* x, + int* y, int* comp, int req_comp) { + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +STBIDEF stbi_uc* stbi_load_from_callbacks(stbi_io_callbacks const* clbk, + void* user, int* x, int* y, int* comp, + int req_comp) { + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); } #ifndef STBI_NO_GIF -STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) -{ - unsigned char *result; - stbi__context s; - stbi__start_mem(&s,buffer,len); +STBIDEF stbi_uc* stbi_load_gif_from_memory(stbi_uc const* buffer, int len, + int** delays, int* x, int* y, int* z, + int* comp, int req_comp) { + unsigned char* result; + stbi__context s; + stbi__start_mem(&s, buffer, len); - result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); - if (stbi__vertically_flip_on_load) { - stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); - } + result = (unsigned char*)stbi__load_gif_main(&s, delays, x, y, z, comp, + req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices(result, *x, *y, *z, *comp); + } - return result; + return result; } #endif #ifndef STBI_NO_LINEAR -static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - unsigned char *data; - #ifndef STBI_NO_HDR - if (stbi__hdr_test(s)) { - stbi__result_info ri; - float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); - if (hdr_data) - stbi__float_postprocess(hdr_data,x,y,comp,req_comp); - return hdr_data; - } - #endif - data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); - if (data) - return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); - return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +static float* stbi__loadf_main(stbi__context* s, int* x, int* y, int* comp, + int req_comp) { + unsigned char* data; +#ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float* hdr_data = stbi__hdr_load(s, x, y, comp, req_comp, &ri); + if (hdr_data) stbi__float_postprocess(hdr_data, x, y, comp, req_comp); + return hdr_data; + } +#endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", + "Image not of any known type, or corrupt"); } -STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__loadf_main(&s,x,y,comp,req_comp); +STBIDEF float* stbi_loadf_from_memory(stbi_uc const* buffer, int len, int* x, + int* y, int* comp, int req_comp) { + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__loadf_main(&s, x, y, comp, req_comp); } -STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__loadf_main(&s,x,y,comp,req_comp); +STBIDEF float* stbi_loadf_from_callbacks(stbi_io_callbacks const* clbk, + void* user, int* x, int* y, int* comp, + int req_comp) { + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__loadf_main(&s, x, y, comp, req_comp); } #ifndef STBI_NO_STDIO -STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - float *result; - FILE *f = stbi__fopen(filename, "rb"); - if (!f) return stbi__errpf("can't fopen", "Unable to open file"); - result = stbi_loadf_from_file(f,x,y,comp,req_comp); - fclose(f); - return result; +STBIDEF float* stbi_loadf(char const* filename, int* x, int* y, int* comp, + int req_comp) { + float* result; + FILE* f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f, x, y, comp, req_comp); + fclose(f); + return result; } -STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_file(&s,f); - return stbi__loadf_main(&s,x,y,comp,req_comp); +STBIDEF float* stbi_loadf_from_file(FILE* f, int* x, int* y, int* comp, + int req_comp) { + stbi__context s; + stbi__start_file(&s, f); + return stbi__loadf_main(&s, x, y, comp, req_comp); } -#endif // !STBI_NO_STDIO +#endif // !STBI_NO_STDIO -#endif // !STBI_NO_LINEAR +#endif // !STBI_NO_LINEAR // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always // reports false! -STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) -{ - #ifndef STBI_NO_HDR - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__hdr_test(&s); - #else - STBI_NOTUSED(buffer); - STBI_NOTUSED(len); - return 0; - #endif +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const* buffer, int len) { +#ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__hdr_test(&s); +#else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; +#endif } #ifndef STBI_NO_STDIO -STBIDEF int stbi_is_hdr (char const *filename) -{ - FILE *f = stbi__fopen(filename, "rb"); - int result=0; - if (f) { - result = stbi_is_hdr_from_file(f); - fclose(f); - } - return result; +STBIDEF int stbi_is_hdr(char const* filename) { + FILE* f = stbi__fopen(filename, "rb"); + int result = 0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; } -STBIDEF int stbi_is_hdr_from_file(FILE *f) -{ - #ifndef STBI_NO_HDR - long pos = ftell(f); - int res; - stbi__context s; - stbi__start_file(&s,f); - res = stbi__hdr_test(&s); - fseek(f, pos, SEEK_SET); - return res; - #else - STBI_NOTUSED(f); - return 0; - #endif +STBIDEF int stbi_is_hdr_from_file(FILE* f) { +#ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s, f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; +#else + STBI_NOTUSED(f); + return 0; +#endif } -#endif // !STBI_NO_STDIO +#endif // !STBI_NO_STDIO -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) -{ - #ifndef STBI_NO_HDR - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__hdr_test(&s); - #else - STBI_NOTUSED(clbk); - STBI_NOTUSED(user); - return 0; - #endif +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const* clbk, + void* user) { +#ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)clbk, user); + return stbi__hdr_test(&s); +#else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; +#endif } #ifndef STBI_NO_LINEAR -static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; +static float stbi__l2h_gamma = 2.2f, stbi__l2h_scale = 1.0f; -STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } -STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif -static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; - -STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } -STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } +static float stbi__h2l_gamma_i = 1.0f / 2.2f, stbi__h2l_scale_i = 1.0f; +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { + stbi__h2l_gamma_i = 1 / gamma; +} +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { + stbi__h2l_scale_i = 1 / scale; +} ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // -enum -{ - STBI__SCAN_load=0, - STBI__SCAN_type, - STBI__SCAN_header -}; +enum { STBI__SCAN_load = 0, STBI__SCAN_type, STBI__SCAN_header }; -static void stbi__refill_buffer(stbi__context *s) -{ - int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); - s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); - if (n == 0) { - // at end of file, treat same as if from memory, but need to handle case - // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file - s->read_from_callbacks = 0; - s->img_buffer = s->buffer_start; - s->img_buffer_end = s->buffer_start+1; - *s->img_buffer = 0; - } else { - s->img_buffer = s->buffer_start; - s->img_buffer_end = s->buffer_start + n; - } +static void stbi__refill_buffer(stbi__context* s) { + int n = (s->io.read)(s->io_user_data, (char*)s->buffer_start, s->buflen); + s->callback_already_read += (int)(s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + 1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } } -stbi_inline static stbi_uc stbi__get8(stbi__context *s) -{ - if (s->img_buffer < s->img_buffer_end) - return *s->img_buffer++; - if (s->read_from_callbacks) { - stbi__refill_buffer(s); - return *s->img_buffer++; - } - return 0; +stbi_inline static stbi_uc stbi__get8(stbi__context* s) { + if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; } -#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && \ + defined(STBI_NO_PNM) // nothing #else -stbi_inline static int stbi__at_eof(stbi__context *s) -{ - if (s->io.read) { - if (!(s->io.eof)(s->io_user_data)) return 0; - // if feof() is true, check if buffer = end - // special case: we've only got the special 0 character at the end - if (s->read_from_callbacks == 0) return 1; - } +stbi_inline static int stbi__at_eof(stbi__context* s) { + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } - return s->img_buffer >= s->img_buffer_end; + return s->img_buffer >= s->img_buffer_end; } #endif -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && \ + defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && \ + defined(STBI_NO_PIC) // nothing #else -static void stbi__skip(stbi__context *s, int n) -{ - if (n == 0) return; // already there! - if (n < 0) { - s->img_buffer = s->img_buffer_end; - return; - } - if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); - if (blen < n) { - s->img_buffer = s->img_buffer_end; - (s->io.skip)(s->io_user_data, n - blen); - return; - } - } - s->img_buffer += n; +static void stbi__skip(stbi__context* s, int n) { + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int)(s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; } #endif -#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && \ + defined(STBI_NO_PNM) // nothing #else -static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) -{ - if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); - if (blen < n) { - int res, count; +static int stbi__getn(stbi__context* s, stbi_uc* buffer, int n) { + if (s->io.read) { + int blen = (int)(s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; - memcpy(buffer, s->img_buffer, blen); + memcpy(buffer, s->img_buffer, blen); - count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); - res = (count == (n-blen)); - s->img_buffer = s->img_buffer_end; - return res; - } - } + count = + (s->io.read)(s->io_user_data, (char*)buffer + blen, n - blen); + res = (count == (n - blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } - if (s->img_buffer+n <= s->img_buffer_end) { - memcpy(buffer, s->img_buffer, n); - s->img_buffer += n; - return 1; - } else - return 0; + if (s->img_buffer + n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; } #endif -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && \ + defined(STBI_NO_PIC) // nothing #else -static int stbi__get16be(stbi__context *s) -{ - int z = stbi__get8(s); - return (z << 8) + stbi__get8(s); +static int stbi__get16be(stbi__context* s) { + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) // nothing #else -static stbi__uint32 stbi__get32be(stbi__context *s) -{ - stbi__uint32 z = stbi__get16be(s); - return (z << 16) + stbi__get16be(s); +static stbi__uint32 stbi__get32be(stbi__context* s) { + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); } #endif #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing #else -static int stbi__get16le(stbi__context *s) -{ - int z = stbi__get8(s); - return z + (stbi__get8(s) << 8); +static int stbi__get16le(stbi__context* s) { + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); } #endif #ifndef STBI_NO_BMP -static stbi__uint32 stbi__get32le(stbi__context *s) -{ - stbi__uint32 z = stbi__get16le(s); - z += (stbi__uint32)stbi__get16le(s) << 16; - return z; +static stbi__uint32 stbi__get32le(stbi__context* s) { + stbi__uint32 z = stbi__get16le(s); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; } #endif -#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings +#define STBI__BYTECAST(x) \ + ((stbi_uc)((x) & 255)) // truncate int to byte without warnings -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && \ + defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && \ + defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else ////////////////////////////////////////////////////////////////////////////// @@ -1743,169 +1805,282 @@ static stbi__uint32 stbi__get32le(stbi__context *s) // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing -static stbi_uc stbi__compute_y(int r, int g, int b) -{ - return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +static stbi_uc stbi__compute_y(int r, int g, int b) { + return (stbi_uc)(((r * 77) + (g * 150) + (29 * b)) >> 8); } #endif -#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && \ + defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && \ + defined(STBI_NO_PNM) // nothing #else -static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) -{ - int i,j; - unsigned char *good; +static unsigned char* stbi__convert_format(unsigned char* data, int img_n, + int req_comp, unsigned int x, + unsigned int y) { + int i, j; + unsigned char* good; - if (req_comp == img_n) return data; - STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); - if (good == NULL) { - STBI_FREE(data); - return stbi__errpuc("outofmem", "Out of memory"); - } + good = (unsigned char*)stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } - for (j=0; j < (int) y; ++j) { - unsigned char *src = data + j * x * img_n ; - unsigned char *dest = good + j * x * req_comp; + for (j = 0; j < (int)y; ++j) { + unsigned char* src = data + j * x * img_n; + unsigned char* dest = good + j * x * req_comp; - #define STBI__COMBO(a,b) ((a)*8+(b)) - #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) - // convert source image with img_n components to one with req_comp components; - // avoid switch per pixel, so use switch per scanline and massive macros - switch (STBI__COMBO(img_n, req_comp)) { - STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; - STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; - STBI__CASE(2,1) { dest[0]=src[0]; } break; - STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; - STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; - STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; - STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; - STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; - STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; - STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; - default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); - } - #undef STBI__CASE - } +#define STBI__COMBO(a, b) ((a) * 8 + (b)) +#define STBI__CASE(a, b) \ + case STBI__COMBO(a, b): \ + for (i = x - 1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp + // components; avoid switch per pixel, so use switch per scanline and + // massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1, 2) { + dest[0] = src[0]; + dest[1] = 255; + } + break; + STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } + break; + STBI__CASE(1, 4) { + dest[0] = dest[1] = dest[2] = src[0]; + dest[3] = 255; + } + break; + STBI__CASE(2, 1) { dest[0] = src[0]; } + break; + STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } + break; + STBI__CASE(2, 4) { + dest[0] = dest[1] = dest[2] = src[0]; + dest[3] = src[1]; + } + break; + STBI__CASE(3, 4) { + dest[0] = src[0]; + dest[1] = src[1]; + dest[2] = src[2]; + dest[3] = 255; + } + break; + STBI__CASE(3, 1) { + dest[0] = stbi__compute_y(src[0], src[1], src[2]); + } + break; + STBI__CASE(3, 2) { + dest[0] = stbi__compute_y(src[0], src[1], src[2]); + dest[1] = 255; + } + break; + STBI__CASE(4, 1) { + dest[0] = stbi__compute_y(src[0], src[1], src[2]); + } + break; + STBI__CASE(4, 2) { + dest[0] = stbi__compute_y(src[0], src[1], src[2]); + dest[1] = src[3]; + } + break; + STBI__CASE(4, 3) { + dest[0] = src[0]; + dest[1] = src[1]; + dest[2] = src[2]; + } + break; + default: + STBI_ASSERT(0); + STBI_FREE(data); + STBI_FREE(good); + return stbi__errpuc("unsupported", + "Unsupported format conversion"); + } +#undef STBI__CASE + } - STBI_FREE(data); - return good; + STBI_FREE(data); + return good; } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else -static stbi__uint16 stbi__compute_y_16(int r, int g, int b) -{ - return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) { + return (stbi__uint16)(((r * 77) + (g * 150) + (29 * b)) >> 8); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else -static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) -{ - int i,j; - stbi__uint16 *good; +static stbi__uint16* stbi__convert_format16(stbi__uint16* data, int img_n, + int req_comp, unsigned int x, + unsigned int y) { + int i, j; + stbi__uint16* good; - if (req_comp == img_n) return data; - STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); - if (good == NULL) { - STBI_FREE(data); - return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); - } + good = (stbi__uint16*)stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16*)stbi__errpuc("outofmem", "Out of memory"); + } - for (j=0; j < (int) y; ++j) { - stbi__uint16 *src = data + j * x * img_n ; - stbi__uint16 *dest = good + j * x * req_comp; + for (j = 0; j < (int)y; ++j) { + stbi__uint16* src = data + j * x * img_n; + stbi__uint16* dest = good + j * x * req_comp; - #define STBI__COMBO(a,b) ((a)*8+(b)) - #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) - // convert source image with img_n components to one with req_comp components; - // avoid switch per pixel, so use switch per scanline and massive macros - switch (STBI__COMBO(img_n, req_comp)) { - STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; - STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; - STBI__CASE(2,1) { dest[0]=src[0]; } break; - STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; - STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; - STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; - STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; - STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; - STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; - STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; - default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); - } - #undef STBI__CASE - } +#define STBI__COMBO(a, b) ((a) * 8 + (b)) +#define STBI__CASE(a, b) \ + case STBI__COMBO(a, b): \ + for (i = x - 1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp + // components; avoid switch per pixel, so use switch per scanline and + // massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1, 2) { + dest[0] = src[0]; + dest[1] = 0xffff; + } + break; + STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } + break; + STBI__CASE(1, 4) { + dest[0] = dest[1] = dest[2] = src[0]; + dest[3] = 0xffff; + } + break; + STBI__CASE(2, 1) { dest[0] = src[0]; } + break; + STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } + break; + STBI__CASE(2, 4) { + dest[0] = dest[1] = dest[2] = src[0]; + dest[3] = src[1]; + } + break; + STBI__CASE(3, 4) { + dest[0] = src[0]; + dest[1] = src[1]; + dest[2] = src[2]; + dest[3] = 0xffff; + } + break; + STBI__CASE(3, 1) { + dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); + } + break; + STBI__CASE(3, 2) { + dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); + dest[1] = 0xffff; + } + break; + STBI__CASE(4, 1) { + dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); + } + break; + STBI__CASE(4, 2) { + dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); + dest[1] = src[3]; + } + break; + STBI__CASE(4, 3) { + dest[0] = src[0]; + dest[1] = src[1]; + dest[2] = src[2]; + } + break; + default: + STBI_ASSERT(0); + STBI_FREE(data); + STBI_FREE(good); + return (stbi__uint16*)stbi__errpuc( + "unsupported", "Unsupported format conversion"); + } +#undef STBI__CASE + } - STBI_FREE(data); - return good; + STBI_FREE(data); + return good; } #endif #ifndef STBI_NO_LINEAR -static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) -{ - int i,k,n; - float *output; - if (!data) return NULL; - output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); - if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } - // compute number of non-alpha components - if (comp & 1) n = comp; else n = comp-1; - for (i=0; i < x*y; ++i) { - for (k=0; k < n; ++k) { - output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); - } - } - if (n < comp) { - for (i=0; i < x*y; ++i) { - output[i*comp + n] = data[i*comp + n]/255.0f; - } - } - STBI_FREE(data); - return output; +static float* stbi__ldr_to_hdr(stbi_uc* data, int x, int y, int comp) { + int i, k, n; + float* output; + if (!data) return NULL; + output = (float*)stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { + STBI_FREE(data); + return stbi__errpf("outofmem", "Out of memory"); + } + // compute number of non-alpha components + if (comp & 1) + n = comp; + else + n = comp - 1; + for (i = 0; i < x * y; ++i) { + for (k = 0; k < n; ++k) { + output[i * comp + k] = + (float)(pow(data[i * comp + k] / 255.0f, stbi__l2h_gamma) * + stbi__l2h_scale); + } + } + if (n < comp) { + for (i = 0; i < x * y; ++i) { + output[i * comp + n] = data[i * comp + n] / 255.0f; + } + } + STBI_FREE(data); + return output; } #endif #ifndef STBI_NO_HDR -#define stbi__float2int(x) ((int) (x)) -static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) -{ - int i,k,n; - stbi_uc *output; - if (!data) return NULL; - output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); - if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } - // compute number of non-alpha components - if (comp & 1) n = comp; else n = comp-1; - for (i=0; i < x*y; ++i) { - for (k=0; k < n; ++k) { - float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; - if (z < 0) z = 0; - if (z > 255) z = 255; - output[i*comp + k] = (stbi_uc) stbi__float2int(z); - } - if (k < comp) { - float z = data[i*comp+k] * 255 + 0.5f; - if (z < 0) z = 0; - if (z > 255) z = 255; - output[i*comp + k] = (stbi_uc) stbi__float2int(z); - } - } - STBI_FREE(data); - return output; +#define stbi__float2int(x) ((int)(x)) +static stbi_uc* stbi__hdr_to_ldr(float* data, int x, int y, int comp) { + int i, k, n; + stbi_uc* output; + if (!data) return NULL; + output = (stbi_uc*)stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + // compute number of non-alpha components + if (comp & 1) + n = comp; + else + n = comp - 1; + for (i = 0; i < x * y; ++i) { + for (k = 0; k < n; ++k) { + float z = (float)pow(data[i * comp + k] * stbi__h2l_scale_i, + stbi__h2l_gamma_i) * + 255 + + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i * comp + k] = (stbi_uc)stbi__float2int(z); + } + if (k < comp) { + float z = data[i * comp + k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i * comp + k] = (stbi_uc)stbi__float2int(z); + } + } + STBI_FREE(data); + return output; } #endif @@ -1933,763 +2108,808 @@ static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) #ifndef STBI_NO_JPEG // huffman decoding acceleration -#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache -typedef struct -{ - stbi_uc fast[1 << FAST_BITS]; - // weirdly, repacking this into AoS is a 10% speed loss, instead of a win - stbi__uint16 code[256]; - stbi_uc values[256]; - stbi_uc size[257]; - unsigned int maxcode[18]; - int delta[17]; // old 'firstsymbol' - old 'firstcode' +typedef struct { + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' } stbi__huffman; -typedef struct -{ - stbi__context *s; - stbi__huffman huff_dc[4]; - stbi__huffman huff_ac[4]; - stbi__uint16 dequant[4][64]; - stbi__int16 fast_ac[4][1 << FAST_BITS]; +typedef struct { + stbi__context* s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; -// sizes for components, interleaved MCUs - int img_h_max, img_v_max; - int img_mcu_x, img_mcu_y; - int img_mcu_w, img_mcu_h; + // sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; -// definition of jpeg image component - struct - { - int id; - int h,v; - int tq; - int hd,ha; - int dc_pred; + // definition of jpeg image component + struct { + int id; + int h, v; + int tq; + int hd, ha; + int dc_pred; - int x,y,w2,h2; - stbi_uc *data; - void *raw_data, *raw_coeff; - stbi_uc *linebuf; - short *coeff; // progressive only - int coeff_w, coeff_h; // number of 8x8 coefficient blocks - } img_comp[4]; + int x, y, w2, h2; + stbi_uc* data; + void *raw_data, *raw_coeff; + stbi_uc* linebuf; + short* coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; - stbi__uint32 code_buffer; // jpeg entropy-coded buffer - int code_bits; // number of valid bits - unsigned char marker; // marker seen while filling entropy buffer - int nomore; // flag if we saw a marker so must stop + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop - int progressive; - int spec_start; - int spec_end; - int succ_high; - int succ_low; - int eob_run; - int jfif; - int app14_color_transform; // Adobe APP14 tag - int rgb; + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; - int scan_n, order[4]; - int restart_interval, todo; + int scan_n, order[4]; + int restart_interval, todo; -// kernels - void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); - void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); - stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); + // kernels + void (*idct_block_kernel)(stbi_uc* out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc* out, const stbi_uc* y, + const stbi_uc* pcb, const stbi_uc* pcr, + int count, int step); + stbi_uc* (*resample_row_hv_2_kernel)(stbi_uc* out, stbi_uc* in_near, + stbi_uc* in_far, int w, int hs); } stbi__jpeg; -static int stbi__build_huffman(stbi__huffman *h, int *count) -{ - int i,j,k=0; - unsigned int code; - // build size list for each symbol (from JPEG spec) - for (i=0; i < 16; ++i) { - for (j=0; j < count[i]; ++j) { - h->size[k++] = (stbi_uc) (i+1); - if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); - } - } - h->size[k] = 0; +static int stbi__build_huffman(stbi__huffman* h, int* count) { + int i, j, k = 0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i = 0; i < 16; ++i) { + for (j = 0; j < count[i]; ++j) { + h->size[k++] = (stbi_uc)(i + 1); + if (k >= 257) return stbi__err("bad size list", "Corrupt JPEG"); + } + } + h->size[k] = 0; - // compute actual symbols (from jpeg spec) - code = 0; - k = 0; - for(j=1; j <= 16; ++j) { - // compute delta to add to code to compute symbol id - h->delta[j] = k - code; - if (h->size[k] == j) { - while (h->size[k] == j) - h->code[k++] = (stbi__uint16) (code++); - if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); - } - // compute largest code + 1 for this size, preshifted as needed later - h->maxcode[j] = code << (16-j); - code <<= 1; - } - h->maxcode[j] = 0xffffffff; + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for (j = 1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) h->code[k++] = (stbi__uint16)(code++); + if (code - 1 >= (1u << j)) + return stbi__err("bad code lengths", "Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16 - j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; - // build non-spec acceleration table; 255 is flag for not-accelerated - memset(h->fast, 255, 1 << FAST_BITS); - for (i=0; i < k; ++i) { - int s = h->size[i]; - if (s <= FAST_BITS) { - int c = h->code[i] << (FAST_BITS-s); - int m = 1 << (FAST_BITS-s); - for (j=0; j < m; ++j) { - h->fast[c+j] = (stbi_uc) i; - } - } - } - return 1; + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i = 0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS - s); + int m = 1 << (FAST_BITS - s); + for (j = 0; j < m; ++j) { + h->fast[c + j] = (stbi_uc)i; + } + } + } + return 1; } // build a table that decodes both magnitude and value of small ACs in // one go. -static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) -{ - int i; - for (i=0; i < (1 << FAST_BITS); ++i) { - stbi_uc fast = h->fast[i]; - fast_ac[i] = 0; - if (fast < 255) { - int rs = h->values[fast]; - int run = (rs >> 4) & 15; - int magbits = rs & 15; - int len = h->size[fast]; +static void stbi__build_fast_ac(stbi__int16* fast_ac, stbi__huffman* h) { + int i; + for (i = 0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; - if (magbits && len + magbits <= FAST_BITS) { - // magnitude code followed by receive_extend code - int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); - int m = 1 << (magbits - 1); - if (k < m) k += (~0U << magbits) + 1; - // if the result is small enough, we can fit it in fast_ac table - if (k >= -128 && k <= 127) - fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); - } - } - } + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> + (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = + (stbi__int16)((k * 256) + (run * 16) + (len + magbits)); + } + } + } } -static void stbi__grow_buffer_unsafe(stbi__jpeg *j) -{ - do { - unsigned int b = j->nomore ? 0 : stbi__get8(j->s); - if (b == 0xff) { - int c = stbi__get8(j->s); - while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes - if (c != 0) { - j->marker = (unsigned char) c; - j->nomore = 1; - return; - } - } - j->code_buffer |= b << (24 - j->code_bits); - j->code_bits += 8; - } while (j->code_bits <= 24); +static void stbi__grow_buffer_unsafe(stbi__jpeg* j) { + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char)c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); } // (1 << n) - 1 -static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; +static const stbi__uint32 stbi__bmask[17] = { + 0, 1, 3, 7, 15, 31, 63, 127, 255, + 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535}; // decode a jpeg huffman value from the bitstream -stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) -{ - unsigned int temp; - int c,k; +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg* j, stbi__huffman* h) { + unsigned int temp; + int c, k; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - // look at the top FAST_BITS and determine what symbol ID it is, - // if the code is <= FAST_BITS - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - k = h->fast[c]; - if (k < 255) { - int s = h->size[k]; - if (s > j->code_bits) - return -1; - j->code_buffer <<= s; - j->code_bits -= s; - return h->values[k]; - } + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } - // naive test is to shift the code_buffer down so k bits are - // valid, then test against maxcode. To speed this up, we've - // preshifted maxcode left so that it has (16-k) 0s at the - // end; in other words, regardless of the number of bits, it - // wants to be compared against something shifted to have 16; - // that way we don't need to shift inside the loop. - temp = j->code_buffer >> 16; - for (k=FAST_BITS+1 ; ; ++k) - if (temp < h->maxcode[k]) - break; - if (k == 17) { - // error! code not found - j->code_bits -= 16; - return -1; - } + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k = FAST_BITS + 1;; ++k) + if (temp < h->maxcode[k]) break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } - if (k > j->code_bits) - return -1; + if (k > j->code_bits) return -1; - // convert the huffman code to the symbol id - c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; - if(c < 0 || c >= 256) // symbol id out of bounds! - return -1; - STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if (c < 0 || c >= 256) // symbol id out of bounds! + return -1; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & + stbi__bmask[h->size[c]]) == h->code[c]); - // convert the id to a symbol - j->code_bits -= k; - j->code_buffer <<= k; - return h->values[c]; + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; } // bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); - if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing +stbi_inline static int stbi__extend_receive(stbi__jpeg* j, int n) { + unsigned int k; + int sgn; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) + return 0; // ran out of bits from stream, return 0s intead of + // continuing - sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) - k = stbi_lrot(j->code_buffer, n); - j->code_buffer = k & ~stbi__bmask[n]; - k &= stbi__bmask[n]; - j->code_bits -= n; - return k + (stbi__jbias[n] & (sgn - 1)); + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear + // (positive), 1 if MSB set (negative) + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & (sgn - 1)); } // get some unsigned bits -stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) -{ - unsigned int k; - if (j->code_bits < n) stbi__grow_buffer_unsafe(j); - if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing - k = stbi_lrot(j->code_buffer, n); - j->code_buffer = k & ~stbi__bmask[n]; - k &= stbi__bmask[n]; - j->code_bits -= n; - return k; +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg* j, int n) { + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) + return 0; // ran out of bits from stream, return 0s intead of + // continuing + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; } -stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) -{ - unsigned int k; - if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); - if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing - k = j->code_buffer; - j->code_buffer <<= 1; - --j->code_bits; - return k & 0x80000000; +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg* j) { + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) + return 0; // ran out of bits from stream, return 0s intead of + // continuing + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? -static const stbi_uc stbi__jpeg_dezigzag[64+15] = -{ - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63, - // let corrupt input sample past end - 63, 63, 63, 63, 63, 63, 63, 63, - 63, 63, 63, 63, 63, 63, 63 -}; +static const stbi_uc stbi__jpeg_dezigzag[64 + 15] = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, + 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, + 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; // decode one 64-entry block-- -static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) -{ - int diff,dc,k; - int t; +static int stbi__jpeg_decode_block(stbi__jpeg* j, short data[64], + stbi__huffman* hdc, stbi__huffman* hac, + stbi__int16* fac, int b, + stbi__uint16* dequant) { + int diff, dc, k; + int t; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("bad huffman code", "Corrupt JPEG"); - // 0 all the ac values now so we can do it 32-bits at a time - memset(data,0,64*sizeof(data[0])); + // 0 all the ac values now so we can do it 32-bits at a time + memset(data, 0, 64 * sizeof(data[0])); - diff = t ? stbi__extend_receive(j, t) : 0; - if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); - dc = j->img_comp[b].dc_pred + diff; - j->img_comp[b].dc_pred = dc; - if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - data[0] = (short) (dc * dequant[0]); + diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) + return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) + return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short)(dc * dequant[0]); - // decode AC components, see JPEG spec - k = 1; - do { - unsigned int zig; - int c,r,s; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - r = fac[c]; - if (r) { // fast-AC path - k += (r >> 4) & 15; // run - s = r & 15; // combined length - if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); - j->code_buffer <<= s; - j->code_bits -= s; - // decode into unzigzag'd location - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) * dequant[zig]); - } else { - int rs = stbi__jpeg_huff_decode(j, hac); - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (rs != 0xf0) break; // end block - k += 16; - } else { - k += r; + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c, r, s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) + return stbi__err( + "bad huffman code", + "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); - } - } - } while (k < 64); - return 1; + data[zig] = (short)((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)(stbi__extend_receive(j, s) * dequant[zig]); + } + } + } while (k < 64); + return 1; } -static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) -{ - int diff,dc; - int t; - if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg* j, short data[64], + stbi__huffman* hdc, int b) { + int diff, dc; + int t; + if (j->spec_end != 0) + return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - if (j->succ_high == 0) { - // first scan for DC coefficient, must be first - memset(data,0,64*sizeof(data[0])); // 0 all the ac values now - t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - diff = t ? stbi__extend_receive(j, t) : 0; + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data, 0, 64 * sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) + return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; - if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); - dc = j->img_comp[b].dc_pred + diff; - j->img_comp[b].dc_pred = dc; - if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - data[0] = (short) (dc * (1 << j->succ_low)); - } else { - // refinement scan for DC coefficient - if (stbi__jpeg_get_bit(j)) - data[0] += (short) (1 << j->succ_low); - } - return 1; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) + return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) + return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short)(dc * (1 << j->succ_low)); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) data[0] += (short)(1 << j->succ_low); + } + return 1; } // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing -static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) -{ - int k; - if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg* j, short data[64], + stbi__huffman* hac, + stbi__int16* fac) { + int k; + if (j->spec_start == 0) + return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - if (j->succ_high == 0) { - int shift = j->succ_low; + if (j->succ_high == 0) { + int shift = j->succ_low; - if (j->eob_run) { - --j->eob_run; - return 1; - } + if (j->eob_run) { + --j->eob_run; + return 1; + } - k = j->spec_start; - do { - unsigned int zig; - int c,r,s; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - r = fac[c]; - if (r) { // fast-AC path - k += (r >> 4) & 15; // run - s = r & 15; // combined length - if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); - j->code_buffer <<= s; - j->code_bits -= s; - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) * (1 << shift)); - } else { - int rs = stbi__jpeg_huff_decode(j, hac); - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (r < 15) { - j->eob_run = (1 << r); - if (r) - j->eob_run += stbi__jpeg_get_bits(j, r); - --j->eob_run; - break; - } - k += 16; + k = j->spec_start; + do { + unsigned int zig; + int c, r, s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) + return stbi__err( + "bad huffman code", + "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)((r >> 8) * (1 << shift)); } else { - k += r; - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) + return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = + (short)(stbi__extend_receive(j, s) * (1 << shift)); + } } - } - } while (k <= j->spec_end); - } else { - // refinement scan for these AC coefficients + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients - short bit = (short) (1 << j->succ_low); + short bit = (short)(1 << j->succ_low); - if (j->eob_run) { - --j->eob_run; - for (k = j->spec_start; k <= j->spec_end; ++k) { - short *p = &data[stbi__jpeg_dezigzag[k]]; - if (*p != 0) - if (stbi__jpeg_get_bit(j)) - if ((*p & bit)==0) { - if (*p > 0) - *p += bit; - else - *p -= bit; - } - } - } else { - k = j->spec_start; - do { - int r,s; - int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (r < 15) { - j->eob_run = (1 << r) - 1; - if (r) - j->eob_run += stbi__jpeg_get_bits(j, r); - r = 64; // force end of block - } else { - // r=15 s=0 should write 16 0s, so we just do - // a run of 15 0s and then write s (which is 0), - // so we don't have to do anything special here - } - } else { - if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); - // sign bit - if (stbi__jpeg_get_bit(j)) - s = bit; - else - s = -bit; + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short* p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit) == 0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } } + } else { + k = j->spec_start; + do { + int r, s; + int rs = stbi__jpeg_huff_decode( + j, hac); // @OPTIMIZE see if we can use the fast path here, + // advance-by-r is so slow, eh + if (rs < 0) + return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) + return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } - // advance by r - while (k <= j->spec_end) { - short *p = &data[stbi__jpeg_dezigzag[k++]]; - if (*p != 0) { - if (stbi__jpeg_get_bit(j)) - if ((*p & bit)==0) { - if (*p > 0) - *p += bit; - else - *p -= bit; - } - } else { - if (r == 0) { - *p = (short) s; - break; - } - --r; - } - } - } while (k <= j->spec_end); - } - } - return 1; + // advance by r + while (k <= j->spec_end) { + short* p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit) == 0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short)s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; } // take a -128..127 value and stbi__clamp it and convert to 0..255 -stbi_inline static stbi_uc stbi__clamp(int x) -{ - // trick to use a single test to catch both cases - if ((unsigned int) x > 255) { - if (x < 0) return 0; - if (x > 255) return 255; - } - return (stbi_uc) x; +stbi_inline static stbi_uc stbi__clamp(int x) { + // trick to use a single test to catch both cases + if ((unsigned int)x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc)x; } -#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) -#define stbi__fsh(x) ((x) * 4096) +#define stbi__f2f(x) ((int)(((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) // derived from jidctint -- DCT_ISLOW -#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ - int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ - p2 = s2; \ - p3 = s6; \ - p1 = (p2+p3) * stbi__f2f(0.5411961f); \ - t2 = p1 + p3*stbi__f2f(-1.847759065f); \ - t3 = p1 + p2*stbi__f2f( 0.765366865f); \ - p2 = s0; \ - p3 = s4; \ - t0 = stbi__fsh(p2+p3); \ - t1 = stbi__fsh(p2-p3); \ - x0 = t0+t3; \ - x3 = t0-t3; \ - x1 = t1+t2; \ - x2 = t1-t2; \ - t0 = s7; \ - t1 = s5; \ - t2 = s3; \ - t3 = s1; \ - p3 = t0+t2; \ - p4 = t1+t3; \ - p1 = t0+t3; \ - p2 = t1+t2; \ - p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ - t0 = t0*stbi__f2f( 0.298631336f); \ - t1 = t1*stbi__f2f( 2.053119869f); \ - t2 = t2*stbi__f2f( 3.072711026f); \ - t3 = t3*stbi__f2f( 1.501321110f); \ - p1 = p5 + p1*stbi__f2f(-0.899976223f); \ - p2 = p5 + p2*stbi__f2f(-2.562915447f); \ - p3 = p3*stbi__f2f(-1.961570560f); \ - p4 = p4*stbi__f2f(-0.390180644f); \ - t3 += p1+p4; \ - t2 += p2+p3; \ - t1 += p2+p4; \ - t0 += p1+p3; +#define STBI__IDCT_1D(s0, s1, s2, s3, s4, s5, s6, s7) \ + int t0, t1, t2, t3, p1, p2, p3, p4, p5, x0, x1, x2, x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2 + p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3 * stbi__f2f(-1.847759065f); \ + t3 = p1 + p2 * stbi__f2f(0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2 + p3); \ + t1 = stbi__fsh(p2 - p3); \ + x0 = t0 + t3; \ + x3 = t0 - t3; \ + x1 = t1 + t2; \ + x2 = t1 - t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0 + t2; \ + p4 = t1 + t3; \ + p1 = t0 + t3; \ + p2 = t1 + t2; \ + p5 = (p3 + p4) * stbi__f2f(1.175875602f); \ + t0 = t0 * stbi__f2f(0.298631336f); \ + t1 = t1 * stbi__f2f(2.053119869f); \ + t2 = t2 * stbi__f2f(3.072711026f); \ + t3 = t3 * stbi__f2f(1.501321110f); \ + p1 = p5 + p1 * stbi__f2f(-0.899976223f); \ + p2 = p5 + p2 * stbi__f2f(-2.562915447f); \ + p3 = p3 * stbi__f2f(-1.961570560f); \ + p4 = p4 * stbi__f2f(-0.390180644f); \ + t3 += p1 + p4; \ + t2 += p2 + p3; \ + t1 += p2 + p4; \ + t0 += p1 + p3; -static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) -{ - int i,val[64],*v=val; - stbi_uc *o; - short *d = data; +static void stbi__idct_block(stbi_uc* out, int out_stride, short data[64]) { + int i, val[64], *v = val; + stbi_uc* o; + short* d = data; - // columns - for (i=0; i < 8; ++i,++d, ++v) { - // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing - if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 - && d[40]==0 && d[48]==0 && d[56]==0) { - // no shortcut 0 seconds - // (1|2|3|4|5|6|7)==0 0 seconds - // all separate -0.047 seconds - // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds - int dcterm = d[0]*4; - v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; - } else { - STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) - // constants scaled things up by 1<<12; let's bring them back - // down, but keep 2 extra bits of precision - x0 += 512; x1 += 512; x2 += 512; x3 += 512; - v[ 0] = (x0+t3) >> 10; - v[56] = (x0-t3) >> 10; - v[ 8] = (x1+t2) >> 10; - v[48] = (x1-t2) >> 10; - v[16] = (x2+t1) >> 10; - v[40] = (x2-t1) >> 10; - v[24] = (x3+t0) >> 10; - v[32] = (x3-t0) >> 10; - } - } + // columns + for (i = 0; i < 8; ++i, ++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0 && + d[48] == 0 && d[56] == 0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0] * 4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = + dcterm; + } else { + STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; + x1 += 512; + x2 += 512; + x3 += 512; + v[0] = (x0 + t3) >> 10; + v[56] = (x0 - t3) >> 10; + v[8] = (x1 + t2) >> 10; + v[48] = (x1 - t2) >> 10; + v[16] = (x2 + t1) >> 10; + v[40] = (x2 - t1) >> 10; + v[24] = (x3 + t0) >> 10; + v[32] = (x3 - t0) >> 10; + } + } - for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { - // no fast case since the first 1D IDCT spread components out - STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) - // constants scaled things up by 1<<12, plus we had 1<<2 from first - // loop, plus horizontal and vertical each scale by sqrt(8) so together - // we've got an extra 1<<3, so 1<<17 total we need to remove. - // so we want to round that, which means adding 0.5 * 1<<17, - // aka 65536. Also, we'll end up with -128 to 127 that we want - // to encode as 0..255 by adding 128, so we'll add that before the shift - x0 += 65536 + (128<<17); - x1 += 65536 + (128<<17); - x2 += 65536 + (128<<17); - x3 += 65536 + (128<<17); - // tried computing the shifts into temps, or'ing the temps to see - // if any were out of range, but that was slower - o[0] = stbi__clamp((x0+t3) >> 17); - o[7] = stbi__clamp((x0-t3) >> 17); - o[1] = stbi__clamp((x1+t2) >> 17); - o[6] = stbi__clamp((x1-t2) >> 17); - o[2] = stbi__clamp((x2+t1) >> 17); - o[5] = stbi__clamp((x2-t1) >> 17); - o[3] = stbi__clamp((x3+t0) >> 17); - o[4] = stbi__clamp((x3-t0) >> 17); - } + for (i = 0, v = val, o = out; i < 8; ++i, v += 8, o += out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128 << 17); + x1 += 65536 + (128 << 17); + x2 += 65536 + (128 << 17); + x3 += 65536 + (128 << 17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0 + t3) >> 17); + o[7] = stbi__clamp((x0 - t3) >> 17); + o[1] = stbi__clamp((x1 + t2) >> 17); + o[6] = stbi__clamp((x1 - t2) >> 17); + o[2] = stbi__clamp((x2 + t1) >> 17); + o[5] = stbi__clamp((x2 - t1) >> 17); + o[3] = stbi__clamp((x3 + t0) >> 17); + o[4] = stbi__clamp((x3 - t0) >> 17); + } } #ifdef STBI_SSE2 // sse2 integer IDCT. not the fastest possible implementation but it // produces bit-identical results to the generic C version so it's // fully "transparent". -static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) -{ - // This is constructed to match our regular (generic) integer IDCT exactly. - __m128i row0, row1, row2, row3, row4, row5, row6, row7; - __m128i tmp; +static void stbi__idct_simd(stbi_uc* out, int out_stride, short data[64]) { + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; - // dot product constant: even elems=x, odd elems=y - #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) +// dot product constant: even elems=x, odd elems=y +#define dct_const(x, y) _mm_setr_epi16((x), (y), (x), (y), (x), (y), (x), (y)) - // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) - // out(1) = c1[even]*x + c1[odd]*y - #define dct_rot(out0,out1, x,y,c0,c1) \ - __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ - __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ - __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ - __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ - __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ - __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) +// out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) +// out(1) = c1[even]*x + c1[odd]*y +#define dct_rot(out0, out1, x, y, c0, c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x), (y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x), (y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) - // out = in << 12 (in 16-bit, out 32-bit) - #define dct_widen(out, in) \ - __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ - __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) +// out = in << 12 (in 16-bit, out 32-bit) +#define dct_widen(out, in) \ + __m128i out##_l = \ + _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = \ + _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) - // wide add - #define dct_wadd(out, a, b) \ - __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ - __m128i out##_h = _mm_add_epi32(a##_h, b##_h) +// wide add +#define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) - // wide sub - #define dct_wsub(out, a, b) \ - __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ - __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) +// wide sub +#define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) - // butterfly a/b, add bias, then shift by "s" and pack - #define dct_bfly32o(out0, out1, a,b,bias,s) \ - { \ - __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ - __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ - dct_wadd(sum, abiased, b); \ - dct_wsub(dif, abiased, b); \ - out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ - out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ - } +// butterfly a/b, add bias, then shift by "s" and pack +#define dct_bfly32o(out0, out1, a, b, bias, s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), \ + _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), \ + _mm_srai_epi32(dif_h, s)); \ + } - // 8-bit interleave step (for transposes) - #define dct_interleave8(a, b) \ - tmp = a; \ - a = _mm_unpacklo_epi8(a, b); \ - b = _mm_unpackhi_epi8(tmp, b) +// 8-bit interleave step (for transposes) +#define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) - // 16-bit interleave step (for transposes) - #define dct_interleave16(a, b) \ - tmp = a; \ - a = _mm_unpacklo_epi16(a, b); \ - b = _mm_unpackhi_epi16(tmp, b) +// 16-bit interleave step (for transposes) +#define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) - #define dct_pass(bias,shift) \ - { \ - /* even part */ \ - dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ - __m128i sum04 = _mm_add_epi16(row0, row4); \ - __m128i dif04 = _mm_sub_epi16(row0, row4); \ - dct_widen(t0e, sum04); \ - dct_widen(t1e, dif04); \ - dct_wadd(x0, t0e, t3e); \ - dct_wsub(x3, t0e, t3e); \ - dct_wadd(x1, t1e, t2e); \ - dct_wsub(x2, t1e, t2e); \ - /* odd part */ \ - dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ - dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ - __m128i sum17 = _mm_add_epi16(row1, row7); \ - __m128i sum35 = _mm_add_epi16(row3, row5); \ - dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ - dct_wadd(x4, y0o, y4o); \ - dct_wadd(x5, y1o, y5o); \ - dct_wadd(x6, y2o, y5o); \ - dct_wadd(x7, y3o, y4o); \ - dct_bfly32o(row0,row7, x0,x7,bias,shift); \ - dct_bfly32o(row1,row6, x1,x6,bias,shift); \ - dct_bfly32o(row2,row5, x2,x5,bias,shift); \ - dct_bfly32o(row3,row4, x3,x4,bias,shift); \ - } +#define dct_pass(bias, shift) \ + { \ + /* even part */ \ + dct_rot(t2e, t3e, row2, row6, rot0_0, rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o, y2o, row7, row3, rot2_0, rot2_1); \ + dct_rot(y1o, y3o, row5, row1, rot3_0, rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o, y5o, sum17, sum35, rot1_0, rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0, row7, x0, x7, bias, shift); \ + dct_bfly32o(row1, row6, x1, x6, bias, shift); \ + dct_bfly32o(row2, row5, x2, x5, bias, shift); \ + dct_bfly32o(row3, row4, x3, x4, bias, shift); \ + } - __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); - __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); - __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); - __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); - __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); - __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); - __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); - __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + __m128i rot0_0 = + dct_const(stbi__f2f(0.5411961f), + stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), + stbi__f2f(0.5411961f)); + __m128i rot1_0 = + dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), + stbi__f2f(1.175875602f)); + __m128i rot1_1 = + dct_const(stbi__f2f(1.175875602f), + stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = + dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), + stbi__f2f(-1.961570560f)); + __m128i rot2_1 = + dct_const(stbi__f2f(-1.961570560f), + stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f)); + __m128i rot3_0 = + dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), + stbi__f2f(-0.390180644f)); + __m128i rot3_1 = + dct_const(stbi__f2f(-0.390180644f), + stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f)); - // rounding biases in column/row passes, see stbi__idct_block for explanation. - __m128i bias_0 = _mm_set1_epi32(512); - __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + // rounding biases in column/row passes, see stbi__idct_block for + // explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128 << 17)); - // load - row0 = _mm_load_si128((const __m128i *) (data + 0*8)); - row1 = _mm_load_si128((const __m128i *) (data + 1*8)); - row2 = _mm_load_si128((const __m128i *) (data + 2*8)); - row3 = _mm_load_si128((const __m128i *) (data + 3*8)); - row4 = _mm_load_si128((const __m128i *) (data + 4*8)); - row5 = _mm_load_si128((const __m128i *) (data + 5*8)); - row6 = _mm_load_si128((const __m128i *) (data + 6*8)); - row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + // load + row0 = _mm_load_si128((const __m128i*)(data + 0 * 8)); + row1 = _mm_load_si128((const __m128i*)(data + 1 * 8)); + row2 = _mm_load_si128((const __m128i*)(data + 2 * 8)); + row3 = _mm_load_si128((const __m128i*)(data + 3 * 8)); + row4 = _mm_load_si128((const __m128i*)(data + 4 * 8)); + row5 = _mm_load_si128((const __m128i*)(data + 5 * 8)); + row6 = _mm_load_si128((const __m128i*)(data + 6 * 8)); + row7 = _mm_load_si128((const __m128i*)(data + 7 * 8)); - // column pass - dct_pass(bias_0, 10); + // column pass + dct_pass(bias_0, 10); - { - // 16bit 8x8 transpose pass 1 - dct_interleave16(row0, row4); - dct_interleave16(row1, row5); - dct_interleave16(row2, row6); - dct_interleave16(row3, row7); + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); - // transpose pass 2 - dct_interleave16(row0, row2); - dct_interleave16(row1, row3); - dct_interleave16(row4, row6); - dct_interleave16(row5, row7); + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); - // transpose pass 3 - dct_interleave16(row0, row1); - dct_interleave16(row2, row3); - dct_interleave16(row4, row5); - dct_interleave16(row6, row7); - } + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } - // row pass - dct_pass(bias_1, 17); + // row pass + dct_pass(bias_1, 17); - { - // pack - __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 - __m128i p1 = _mm_packus_epi16(row2, row3); - __m128i p2 = _mm_packus_epi16(row4, row5); - __m128i p3 = _mm_packus_epi16(row6, row7); + { + // pack + __m128i p0 = + _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); - // 8bit 8x8 transpose pass 1 - dct_interleave8(p0, p2); // a0e0a1e1... - dct_interleave8(p1, p3); // c0g0c1g1... + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... - // transpose pass 2 - dct_interleave8(p0, p1); // a0c0e0g0... - dct_interleave8(p2, p3); // b0d0f0h0... + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... - // transpose pass 3 - dct_interleave8(p0, p2); // a0b0c0d0... - dct_interleave8(p1, p3); // a4b4c4d4... + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... - // store - _mm_storel_epi64((__m128i *) out, p0); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p2); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p1); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p3); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); - } + // store + _mm_storel_epi64((__m128i*)out, p0); + out += out_stride; + _mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p0, 0x4e)); + out += out_stride; + _mm_storel_epi64((__m128i*)out, p2); + out += out_stride; + _mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p2, 0x4e)); + out += out_stride; + _mm_storel_epi64((__m128i*)out, p1); + out += out_stride; + _mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p1, 0x4e)); + out += out_stride; + _mm_storel_epi64((__m128i*)out, p3); + out += out_stride; + _mm_storel_epi64((__m128i*)out, _mm_shuffle_epi32(p3, 0x4e)); + } #undef dct_const #undef dct_rot @@ -2702,204 +2922,244 @@ static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) #undef dct_pass } -#endif // STBI_SSE2 +#endif // STBI_SSE2 #ifdef STBI_NEON // NEON integer IDCT. should produce bit-identical // results to the generic C version. -static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) -{ - int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; +static void stbi__idct_simd(stbi_uc* out, int out_stride, short data[64]) { + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; - int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); - int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); - int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); - int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); - int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); - int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); - int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); - int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); - int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); - int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); - int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); - int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f(0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f(1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f(0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f(2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f(3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f(1.501321110f)); -#define dct_long_mul(out, inq, coeff) \ - int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ - int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) -#define dct_long_mac(out, acc, inq, coeff) \ - int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ - int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) -#define dct_widen(out, inq) \ - int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ - int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) // wide add -#define dct_wadd(out, a, b) \ - int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ - int32x4_t out##_h = vaddq_s32(a##_h, b##_h) +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) // wide sub -#define dct_wsub(out, a, b) \ - int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ - int32x4_t out##_h = vsubq_s32(a##_h, b##_h) +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) // butterfly a/b, then shift using "shiftop" by "s" and pack -#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ - { \ - dct_wadd(sum, a, b); \ - dct_wsub(dif, a, b); \ - out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ - out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ - } +#define dct_bfly32o(out0, out1, a, b, shiftop, s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } -#define dct_pass(shiftop, shift) \ - { \ - /* even part */ \ - int16x8_t sum26 = vaddq_s16(row2, row6); \ - dct_long_mul(p1e, sum26, rot0_0); \ - dct_long_mac(t2e, p1e, row6, rot0_1); \ - dct_long_mac(t3e, p1e, row2, rot0_2); \ - int16x8_t sum04 = vaddq_s16(row0, row4); \ - int16x8_t dif04 = vsubq_s16(row0, row4); \ - dct_widen(t0e, sum04); \ - dct_widen(t1e, dif04); \ - dct_wadd(x0, t0e, t3e); \ - dct_wsub(x3, t0e, t3e); \ - dct_wadd(x1, t1e, t2e); \ - dct_wsub(x2, t1e, t2e); \ - /* odd part */ \ - int16x8_t sum15 = vaddq_s16(row1, row5); \ - int16x8_t sum17 = vaddq_s16(row1, row7); \ - int16x8_t sum35 = vaddq_s16(row3, row5); \ - int16x8_t sum37 = vaddq_s16(row3, row7); \ - int16x8_t sumodd = vaddq_s16(sum17, sum35); \ - dct_long_mul(p5o, sumodd, rot1_0); \ - dct_long_mac(p1o, p5o, sum17, rot1_1); \ - dct_long_mac(p2o, p5o, sum35, rot1_2); \ - dct_long_mul(p3o, sum37, rot2_0); \ - dct_long_mul(p4o, sum15, rot2_1); \ - dct_wadd(sump13o, p1o, p3o); \ - dct_wadd(sump24o, p2o, p4o); \ - dct_wadd(sump23o, p2o, p3o); \ - dct_wadd(sump14o, p1o, p4o); \ - dct_long_mac(x4, sump13o, row7, rot3_0); \ - dct_long_mac(x5, sump24o, row5, rot3_1); \ - dct_long_mac(x6, sump23o, row3, rot3_2); \ - dct_long_mac(x7, sump14o, row1, rot3_3); \ - dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ - dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ - dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ - dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ - } +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0, row7, x0, x7, shiftop, shift); \ + dct_bfly32o(row1, row6, x1, x6, shiftop, shift); \ + dct_bfly32o(row2, row5, x2, x5, shiftop, shift); \ + dct_bfly32o(row3, row4, x3, x4, shiftop, shift); \ + } - // load - row0 = vld1q_s16(data + 0*8); - row1 = vld1q_s16(data + 1*8); - row2 = vld1q_s16(data + 2*8); - row3 = vld1q_s16(data + 3*8); - row4 = vld1q_s16(data + 4*8); - row5 = vld1q_s16(data + 5*8); - row6 = vld1q_s16(data + 6*8); - row7 = vld1q_s16(data + 7*8); + // load + row0 = vld1q_s16(data + 0 * 8); + row1 = vld1q_s16(data + 1 * 8); + row2 = vld1q_s16(data + 2 * 8); + row3 = vld1q_s16(data + 3 * 8); + row4 = vld1q_s16(data + 4 * 8); + row5 = vld1q_s16(data + 5 * 8); + row6 = vld1q_s16(data + 6 * 8); + row7 = vld1q_s16(data + 7 * 8); - // add DC bias - row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); - // column pass - dct_pass(vrshrn_n_s32, 10); + // column pass + dct_pass(vrshrn_n_s32, 10); - // 16bit 8x8 transpose - { + // 16bit 8x8 transpose + { // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. // whether compilers actually get this is another story, sadly. -#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } -#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } -#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } +#define dct_trn16(x, y) \ + { \ + int16x8x2_t t = vtrnq_s16(x, y); \ + x = t.val[0]; \ + y = t.val[1]; \ + } +#define dct_trn32(x, y) \ + { \ + int32x4x2_t t = \ + vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); \ + x = vreinterpretq_s16_s32(t.val[0]); \ + y = vreinterpretq_s16_s32(t.val[1]); \ + } +#define dct_trn64(x, y) \ + { \ + int16x8_t x0 = x; \ + int16x8_t y0 = y; \ + x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); \ + y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); \ + } - // pass 1 - dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 - dct_trn16(row2, row3); - dct_trn16(row4, row5); - dct_trn16(row6, row7); + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); - // pass 2 - dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 - dct_trn32(row1, row3); - dct_trn32(row4, row6); - dct_trn32(row5, row7); + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); - // pass 3 - dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 - dct_trn64(row1, row5); - dct_trn64(row2, row6); - dct_trn64(row3, row7); + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); #undef dct_trn16 #undef dct_trn32 #undef dct_trn64 - } + } - // row pass - // vrshrn_n_s32 only supports shifts up to 16, we need - // 17. so do a non-rounding shift of 16 first then follow - // up with a rounding shift by 1. - dct_pass(vshrn_n_s32, 16); + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); - { - // pack and round - uint8x8_t p0 = vqrshrun_n_s16(row0, 1); - uint8x8_t p1 = vqrshrun_n_s16(row1, 1); - uint8x8_t p2 = vqrshrun_n_s16(row2, 1); - uint8x8_t p3 = vqrshrun_n_s16(row3, 1); - uint8x8_t p4 = vqrshrun_n_s16(row4, 1); - uint8x8_t p5 = vqrshrun_n_s16(row5, 1); - uint8x8_t p6 = vqrshrun_n_s16(row6, 1); - uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); - // again, these can translate into one instruction, but often don't. -#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } -#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } -#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) \ + { \ + uint8x8x2_t t = vtrn_u8(x, y); \ + x = t.val[0]; \ + y = t.val[1]; \ + } +#define dct_trn8_16(x, y) \ + { \ + uint16x4x2_t t = \ + vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); \ + x = vreinterpret_u8_u16(t.val[0]); \ + y = vreinterpret_u8_u16(t.val[1]); \ + } +#define dct_trn8_32(x, y) \ + { \ + uint32x2x2_t t = \ + vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); \ + x = vreinterpret_u8_u32(t.val[0]); \ + y = vreinterpret_u8_u32(t.val[1]); \ + } - // sadly can't use interleaved stores here since we only write - // 8 bytes to each scan line! + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! - // 8x8 8-bit transpose pass 1 - dct_trn8_8(p0, p1); - dct_trn8_8(p2, p3); - dct_trn8_8(p4, p5); - dct_trn8_8(p6, p7); + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); - // pass 2 - dct_trn8_16(p0, p2); - dct_trn8_16(p1, p3); - dct_trn8_16(p4, p6); - dct_trn8_16(p5, p7); + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); - // pass 3 - dct_trn8_32(p0, p4); - dct_trn8_32(p1, p5); - dct_trn8_32(p2, p6); - dct_trn8_32(p3, p7); + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); - // store - vst1_u8(out, p0); out += out_stride; - vst1_u8(out, p1); out += out_stride; - vst1_u8(out, p2); out += out_stride; - vst1_u8(out, p3); out += out_stride; - vst1_u8(out, p4); out += out_stride; - vst1_u8(out, p5); out += out_stride; - vst1_u8(out, p6); out += out_stride; - vst1_u8(out, p7); + // store + vst1_u8(out, p0); + out += out_stride; + vst1_u8(out, p1); + out += out_stride; + vst1_u8(out, p2); + out += out_stride; + vst1_u8(out, p3); + out += out_stride; + vst1_u8(out, p4); + out += out_stride; + vst1_u8(out, p5); + out += out_stride; + vst1_u8(out, p6); + out += out_stride; + vst1_u8(out, p7); #undef dct_trn8_8 #undef dct_trn8_16 #undef dct_trn8_32 - } + } #undef dct_long_mul #undef dct_long_mac @@ -2910,1171 +3170,1300 @@ static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) #undef dct_pass } -#endif // STBI_NEON +#endif // STBI_NEON -#define STBI__MARKER_none 0xff +#define STBI__MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value -static stbi_uc stbi__get_marker(stbi__jpeg *j) -{ - stbi_uc x; - if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } - x = stbi__get8(j->s); - if (x != 0xff) return STBI__MARKER_none; - while (x == 0xff) - x = stbi__get8(j->s); // consume repeated 0xff fill bytes - return x; +static stbi_uc stbi__get_marker(stbi__jpeg* j) { + stbi_uc x; + if (j->marker != STBI__MARKER_none) { + x = j->marker; + j->marker = STBI__MARKER_none; + return x; + } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] -#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, stbi__jpeg_reset the entropy decoder and // the dc prediction -static void stbi__jpeg_reset(stbi__jpeg *j) -{ - j->code_bits = 0; - j->code_buffer = 0; - j->nomore = 0; - j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; - j->marker = STBI__MARKER_none; - j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; - j->eob_run = 0; - // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, - // since we don't even allow 1<<30 pixels +static void stbi__jpeg_reset(stbi__jpeg* j) { + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = + j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels } -static int stbi__parse_entropy_coded_data(stbi__jpeg *z) -{ - stbi__jpeg_reset(z); - if (!z->progressive) { - if (z->scan_n == 1) { - int i,j; - STBI_SIMD_ALIGN(short, data[64]); - int n = z->order[0]; - // non-interleaved data, we just need to process one block at a time, - // in trivial scanline order - // number of blocks to do just depends on how many actual "pixels" this - // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); - // every data block is an MCU, so countdown the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - // if it's NOT a restart, then just bail, so we get corrupt data - // rather than no data - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } +static int stbi__parse_entropy_coded_data(stbi__jpeg* z) { + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i, j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a + // time, in trivial scanline order number of blocks to do just + // depends on how many actual "pixels" this component has, + // independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block( + z, data, z->huff_dc + z->img_comp[n].hd, + z->huff_ac + ha, z->fast_ac[ha], n, + z->dequant[z->img_comp[n].tq])) + return 0; + z->idct_block_kernel( + z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, + z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart + // interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get + // corrupt data rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } } - } - return 1; - } else { // interleaved - int i,j,k,x,y; - STBI_SIMD_ALIGN(short, data[64]); - for (j=0; j < z->img_mcu_y; ++j) { - for (i=0; i < z->img_mcu_x; ++i) { - // scan an interleaved mcu... process scan_n components in order - for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; - // scan out an mcu's worth of this component; that's just determined - // by the basic H and V specified for the component - for (y=0; y < z->img_comp[n].v; ++y) { - for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x)*8; - int y2 = (j*z->img_comp[n].v + y)*8; + return 1; + } else { // interleaved + int i, j, k, x, y; + STBI_SIMD_ALIGN(short, data[64]); + for (j = 0; j < z->img_mcu_y; ++j) { + for (i = 0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in + // order + for (k = 0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's + // just determined by the basic H and V specified for + // the component + for (y = 0; y < z->img_comp[n].v; ++y) { + for (x = 0; x < z->img_comp[n].h; ++x) { + int x2 = (i * z->img_comp[n].h + x) * 8; + int y2 = (j * z->img_comp[n].v + y) * 8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block( + z, data, z->huff_dc + z->img_comp[n].hd, + z->huff_ac + ha, z->fast_ac[ha], n, + z->dequant[z->img_comp[n].tq])) + return 0; + z->idct_block_kernel( + z->img_comp[n].data + + z->img_comp[n].w2 * y2 + x2, + z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved + // MCU, so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i, j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a + // time, in trivial scanline order number of blocks to do just + // depends on how many actual "pixels" this component has, + // independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + short* data = z->img_comp[n].coeff + + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc( + z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); - } - } - } - // after all interleaved components, that's an interleaved MCU, - // so now count down the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } + if (!stbi__jpeg_decode_block_prog_ac( + z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart + // interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } } - } - return 1; - } - } else { - if (z->scan_n == 1) { - int i,j; - int n = z->order[0]; - // non-interleaved data, we just need to process one block at a time, - // in trivial scanline order - // number of blocks to do just depends on how many actual "pixels" this - // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); - if (z->spec_start == 0) { - if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) - return 0; - } else { - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) - return 0; - } - // every data block is an MCU, so countdown the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } + return 1; + } else { // interleaved + int i, j, k, x, y; + for (j = 0; j < z->img_mcu_y; ++j) { + for (i = 0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in + // order + for (k = 0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's + // just determined by the basic H and V specified for + // the component + for (y = 0; y < z->img_comp[n].v; ++y) { + for (x = 0; x < z->img_comp[n].h; ++x) { + int x2 = (i * z->img_comp[n].h + x); + int y2 = (j * z->img_comp[n].v + y); + short* data = + z->img_comp[n].coeff + + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc( + z, data, &z->huff_dc[z->img_comp[n].hd], + n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved + // MCU, so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } } - } - return 1; - } else { // interleaved - int i,j,k,x,y; - for (j=0; j < z->img_mcu_y; ++j) { - for (i=0; i < z->img_mcu_x; ++i) { - // scan an interleaved mcu... process scan_n components in order - for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; - // scan out an mcu's worth of this component; that's just determined - // by the basic H and V specified for the component - for (y=0; y < z->img_comp[n].v; ++y) { - for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x); - int y2 = (j*z->img_comp[n].v + y); - short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); - if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) - return 0; - } - } - } - // after all interleaved components, that's an interleaved MCU, - // so now count down the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } - } + return 1; + } + } } -static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) -{ - int i; - for (i=0; i < 64; ++i) - data[i] *= dequant[i]; +static void stbi__jpeg_dequantize(short* data, stbi__uint16* dequant) { + int i; + for (i = 0; i < 64; ++i) data[i] *= dequant[i]; } -static void stbi__jpeg_finish(stbi__jpeg *z) -{ - if (z->progressive) { - // dequantize and idct the data - int i,j,n; - for (n=0; n < z->s->img_n; ++n) { - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); - stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); +static void stbi__jpeg_finish(stbi__jpeg* z) { + if (z->progressive) { + // dequantize and idct the data + int i, j, n; + for (n = 0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + short* data = z->img_comp[n].coeff + + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel( + z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8, + z->img_comp[n].w2, data); + } } - } - } - } + } + } } -static int stbi__process_marker(stbi__jpeg *z, int m) -{ - int L; - switch (m) { - case STBI__MARKER_none: // no marker found - return stbi__err("expected marker","Corrupt JPEG"); +static int stbi__process_marker(stbi__jpeg* z, int m) { + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker", "Corrupt JPEG"); - case 0xDD: // DRI - specify restart interval - if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); - z->restart_interval = stbi__get16be(z->s); - return 1; + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) + return stbi__err("bad DRI len", "Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; - case 0xDB: // DQT - define quantization table - L = stbi__get16be(z->s)-2; - while (L > 0) { - int q = stbi__get8(z->s); - int p = q >> 4, sixteen = (p != 0); - int t = q & 15,i; - if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); - if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s) - 2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15, i; + if (p != 0 && p != 1) + return stbi__err("bad DQT type", "Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table", "Corrupt JPEG"); - for (i=0; i < 64; ++i) - z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); - L -= (sixteen ? 129 : 65); - } - return L==0; - - case 0xC4: // DHT - define huffman table - L = stbi__get16be(z->s)-2; - while (L > 0) { - stbi_uc *v; - int sizes[16],i,n=0; - int q = stbi__get8(z->s); - int tc = q >> 4; - int th = q & 15; - if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); - for (i=0; i < 16; ++i) { - sizes[i] = stbi__get8(z->s); - n += sizes[i]; + for (i = 0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = + (stbi__uint16)(sixteen ? stbi__get16be(z->s) + : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); } - if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! - L -= 17; - if (tc == 0) { - if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; - v = z->huff_dc[th].values; - } else { - if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; - v = z->huff_ac[th].values; + return L == 0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s) - 2; + while (L > 0) { + stbi_uc* v; + int sizes[16], i, n = 0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) + return stbi__err("bad DHT header", "Corrupt JPEG"); + for (i = 0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + if (n > 256) + return stbi__err( + "bad DHT header", + "Corrupt JPEG"); // Loop over i < n would write past + // end of values! + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc + th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac + th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i = 0; i < n; ++i) v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; } - for (i=0; i < n; ++i) - v[i] = stbi__get8(z->s); - if (tc != 0) - stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); - L -= n; - } - return L==0; - } + return L == 0; + } - // check for comment block or APP blocks - if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { - L = stbi__get16be(z->s); - if (L < 2) { - if (m == 0xFE) - return stbi__err("bad COM len","Corrupt JPEG"); - else - return stbi__err("bad APP len","Corrupt JPEG"); - } - L -= 2; + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len", "Corrupt JPEG"); + else + return stbi__err("bad APP len", "Corrupt JPEG"); + } + L -= 2; - if (m == 0xE0 && L >= 5) { // JFIF APP0 segment - static const unsigned char tag[5] = {'J','F','I','F','\0'}; - int ok = 1; - int i; - for (i=0; i < 5; ++i) - if (stbi__get8(z->s) != tag[i]) - ok = 0; - L -= 5; - if (ok) - z->jfif = 1; - } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment - static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; - int ok = 1; - int i; - for (i=0; i < 6; ++i) - if (stbi__get8(z->s) != tag[i]) - ok = 0; - L -= 6; - if (ok) { - stbi__get8(z->s); // version - stbi__get16be(z->s); // flags0 - stbi__get16be(z->s); // flags1 - z->app14_color_transform = stbi__get8(z->s); // color transform + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J', 'F', 'I', 'F', '\0'}; + int ok = 1; + int i; + for (i = 0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) ok = 0; + L -= 5; + if (ok) z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A', 'd', 'o', 'b', 'e', '\0'}; + int ok = 1; + int i; + for (i = 0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) ok = 0; L -= 6; - } - } + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } - stbi__skip(z->s, L); - return 1; - } + stbi__skip(z->s, L); + return 1; + } - return stbi__err("unknown marker","Corrupt JPEG"); + return stbi__err("unknown marker", "Corrupt JPEG"); } // after we see SOS -static int stbi__process_scan_header(stbi__jpeg *z) -{ - int i; - int Ls = stbi__get16be(z->s); - z->scan_n = stbi__get8(z->s); - if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); - if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); - for (i=0; i < z->scan_n; ++i) { - int id = stbi__get8(z->s), which; - int q = stbi__get8(z->s); - for (which = 0; which < z->s->img_n; ++which) - if (z->img_comp[which].id == id) - break; - if (which == z->s->img_n) return 0; // no match - z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); - z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); - z->order[i] = which; - } +static int stbi__process_scan_header(stbi__jpeg* z) { + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int)z->s->img_n) + return stbi__err("bad SOS component count", "Corrupt JPEG"); + if (Ls != 6 + 2 * z->scan_n) + return stbi__err("bad SOS len", "Corrupt JPEG"); + for (i = 0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; + if (z->img_comp[which].hd > 3) + return stbi__err("bad DC huff", "Corrupt JPEG"); + z->img_comp[which].ha = q & 15; + if (z->img_comp[which].ha > 3) + return stbi__err("bad AC huff", "Corrupt JPEG"); + z->order[i] = which; + } - { - int aa; - z->spec_start = stbi__get8(z->s); - z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 - aa = stbi__get8(z->s); - z->succ_high = (aa >> 4); - z->succ_low = (aa & 15); - if (z->progressive) { - if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) - return stbi__err("bad SOS", "Corrupt JPEG"); - } else { - if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); - if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); - z->spec_end = 63; - } - } + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || + z->spec_start > z->spec_end || z->succ_high > 13 || + z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS", "Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) + return stbi__err("bad SOS", "Corrupt JPEG"); + z->spec_end = 63; + } + } - return 1; + return 1; } -static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) -{ - int i; - for (i=0; i < ncomp; ++i) { - if (z->img_comp[i].raw_data) { - STBI_FREE(z->img_comp[i].raw_data); - z->img_comp[i].raw_data = NULL; - z->img_comp[i].data = NULL; - } - if (z->img_comp[i].raw_coeff) { - STBI_FREE(z->img_comp[i].raw_coeff); - z->img_comp[i].raw_coeff = 0; - z->img_comp[i].coeff = 0; - } - if (z->img_comp[i].linebuf) { - STBI_FREE(z->img_comp[i].linebuf); - z->img_comp[i].linebuf = NULL; - } - } - return why; +static int stbi__free_jpeg_components(stbi__jpeg* z, int ncomp, int why) { + int i; + for (i = 0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; } -static int stbi__process_frame_header(stbi__jpeg *z, int scan) -{ - stbi__context *s = z->s; - int Lf,p,i,q, h_max=1,v_max=1,c; - Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG - p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline - s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG - s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - c = stbi__get8(s); - if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); - s->img_n = c; - for (i=0; i < c; ++i) { - z->img_comp[i].data = NULL; - z->img_comp[i].linebuf = NULL; - } +static int stbi__process_frame_header(stbi__jpeg* z, int scan) { + stbi__context* s = z->s; + int Lf, p, i, q, h_max = 1, v_max = 1, c; + Lf = stbi__get16be(s); + if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG + p = stbi__get8(s); + if (p != 8) + return stbi__err( + "only 8-bit", + "JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); + if (s->img_y == 0) + return stbi__err( + "no header height", + "JPEG format not supported: delayed height"); // Legal, but we + // don't handle + // it--but neither + // does IJG + s->img_x = stbi__get16be(s); + if (s->img_x == 0) + return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) + return stbi__err("too large", "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) + return stbi__err("too large", "Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) + return stbi__err("bad component count", "Corrupt JPEG"); + s->img_n = c; + for (i = 0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } - if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + if (Lf != 8 + 3 * s->img_n) return stbi__err("bad SOF len", "Corrupt JPEG"); - z->rgb = 0; - for (i=0; i < s->img_n; ++i) { - static const unsigned char rgb[3] = { 'R', 'G', 'B' }; - z->img_comp[i].id = stbi__get8(s); - if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) - ++z->rgb; - q = stbi__get8(s); - z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); - z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); - z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); - } + z->rgb = 0; + for (i = 0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = {'R', 'G', 'B'}; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); + if (!z->img_comp[i].h || z->img_comp[i].h > 4) + return stbi__err("bad H", "Corrupt JPEG"); + z->img_comp[i].v = q & 15; + if (!z->img_comp[i].v || z->img_comp[i].v > 4) + return stbi__err("bad V", "Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); + if (z->img_comp[i].tq > 3) return stbi__err("bad TQ", "Corrupt JPEG"); + } - if (scan != STBI__SCAN_load) return 1; + if (scan != STBI__SCAN_load) return 1; - if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) + return stbi__err("too large", "Image too large to decode"); - for (i=0; i < s->img_n; ++i) { - if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; - if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; - } + for (i = 0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } - // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios - // and I've never seen a non-corrupted JPEG file actually use them - for (i=0; i < s->img_n; ++i) { - if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); - if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); - } + // check that plane subsampling factors are integer ratios; our resamplers + // can't deal with fractional ratios and I've never seen a non-corrupted + // JPEG file actually use them + for (i = 0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) + return stbi__err("bad H", "Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) + return stbi__err("bad V", "Corrupt JPEG"); + } - // compute interleaved mcu info - z->img_h_max = h_max; - z->img_v_max = v_max; - z->img_mcu_w = h_max * 8; - z->img_mcu_h = v_max * 8; - // these sizes can't be more than 17 bits - z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; - z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w - 1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h - 1) / z->img_mcu_h; - for (i=0; i < s->img_n; ++i) { - // number of effective pixels (e.g. for non-interleaved MCU) - z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; - z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; - // to simplify generation, we'll allocate enough memory to decode - // the bogus oversized data from using interleaved MCUs and their - // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't - // discard the extra data until colorspace conversion - // - // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) - // so these muls can't overflow with 32-bit ints (which we require) - z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; - z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; - z->img_comp[i].coeff = 0; - z->img_comp[i].raw_coeff = 0; - z->img_comp[i].linebuf = NULL; - z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); - if (z->img_comp[i].raw_data == NULL) - return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); - // align blocks for idct using mmx/sse - z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); - if (z->progressive) { - // w2, h2 are multiples of 8 (see above) - z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; - z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; - z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); - if (z->img_comp[i].raw_coeff == NULL) - return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); - z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); - } - } + for (i = 0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max - 1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max - 1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked + // earlier) so these muls can't overflow with 32-bit ints (which we + // require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = + stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components( + z, i + 1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = + (stbi_uc*)(((size_t)z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3( + z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components( + z, i + 1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = + (short*)(((size_t)z->img_comp[i].raw_coeff + 15) & ~15); + } + } - return 1; + return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) -#define stbi__DNL(x) ((x) == 0xdc) -#define stbi__SOI(x) ((x) == 0xd8) -#define stbi__EOI(x) ((x) == 0xd9) -#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) -#define stbi__SOS(x) ((x) == 0xda) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) -#define stbi__SOF_progressive(x) ((x) == 0xc2) +#define stbi__SOF_progressive(x) ((x) == 0xc2) -static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) -{ - int m; - z->jfif = 0; - z->app14_color_transform = -1; // valid values are 0,1,2 - z->marker = STBI__MARKER_none; // initialize cached marker to empty - m = stbi__get_marker(z); - if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); - if (scan == STBI__SCAN_type) return 1; - m = stbi__get_marker(z); - while (!stbi__SOF(m)) { - if (!stbi__process_marker(z,m)) return 0; - m = stbi__get_marker(z); - while (m == STBI__MARKER_none) { - // some files have extra padding after their blocks, so ok, we'll scan - if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); - m = stbi__get_marker(z); - } - } - z->progressive = stbi__SOF_progressive(m); - if (!stbi__process_frame_header(z, scan)) return 0; - return 1; +static int stbi__decode_jpeg_header(stbi__jpeg* z, int scan) { + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI", "Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z, m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll + // scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; } -static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) -{ - // some JPEGs have junk at end, skip over it but if we find what looks - // like a valid marker, resume there - while (!stbi__at_eof(j->s)) { - stbi_uc x = stbi__get8(j->s); - while (x == 0xff) { // might be a marker - if (stbi__at_eof(j->s)) return STBI__MARKER_none; - x = stbi__get8(j->s); - if (x != 0x00 && x != 0xff) { - // not a stuffed zero or lead-in to another marker, looks - // like an actual marker, return it - return x; - } - // stuffed zero has x=0 now which ends the loop, meaning we go - // back to regular scan loop. - // repeated 0xff keeps trying to read the next byte of the marker. - } - } - return STBI__MARKER_none; +static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg* j) { + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + stbi_uc x = stbi__get8(j->s); + while (x == 0xff) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; } // decode image to YCbCr format -static int stbi__decode_jpeg_image(stbi__jpeg *j) -{ - int m; - for (m = 0; m < 4; m++) { - j->img_comp[m].raw_data = NULL; - j->img_comp[m].raw_coeff = NULL; - } - j->restart_interval = 0; - if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; - m = stbi__get_marker(j); - while (!stbi__EOI(m)) { - if (stbi__SOS(m)) { - if (!stbi__process_scan_header(j)) return 0; - if (!stbi__parse_entropy_coded_data(j)) return 0; - if (j->marker == STBI__MARKER_none ) { - j->marker = stbi__skip_jpeg_junk_at_end(j); - // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 - } - m = stbi__get_marker(j); - if (STBI__RESTART(m)) +static int stbi__decode_jpeg_image(stbi__jpeg* j) { + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none) { + j->marker = stbi__skip_jpeg_junk_at_end(j); + // if we reach eof without hitting a marker, stbi__get_marker() + // below will fail and we'll eventually return 0 + } m = stbi__get_marker(j); - } else if (stbi__DNL(m)) { - int Ld = stbi__get16be(j->s); - stbi__uint32 NL = stbi__get16be(j->s); - if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); - if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); - m = stbi__get_marker(j); - } else { - if (!stbi__process_marker(j, m)) return 1; - m = stbi__get_marker(j); - } - } - if (j->progressive) - stbi__jpeg_finish(j); - return 1; + if (STBI__RESTART(m)) m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) + return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); + } else { + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); + } + } + if (j->progressive) stbi__jpeg_finish(j); + return 1; } // static jfif-centered resampling (across block boundaries) -typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, - int w, int hs); +typedef stbi_uc* (*resample_row_func)(stbi_uc* out, stbi_uc* in0, stbi_uc* in1, + int w, int hs); -#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) +#define stbi__div4(x) ((stbi_uc)((x) >> 2)) -static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - STBI_NOTUSED(out); - STBI_NOTUSED(in_far); - STBI_NOTUSED(w); - STBI_NOTUSED(hs); - return in_near; +static stbi_uc* resample_row_1(stbi_uc* out, stbi_uc* in_near, stbi_uc* in_far, + int w, int hs) { + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; } -static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate two samples vertically for every one in input - int i; - STBI_NOTUSED(hs); - for (i=0; i < w; ++i) - out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); - return out; +static stbi_uc* stbi__resample_row_v_2(stbi_uc* out, stbi_uc* in_near, + stbi_uc* in_far, int w, int hs) { + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i = 0; i < w; ++i) out[i] = stbi__div4(3 * in_near[i] + in_far[i] + 2); + return out; } -static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate two samples horizontally for every one in input - int i; - stbi_uc *input = in_near; +static stbi_uc* stbi__resample_row_h_2(stbi_uc* out, stbi_uc* in_near, + stbi_uc* in_far, int w, int hs) { + // need to generate two samples horizontally for every one in input + int i; + stbi_uc* input = in_near; - if (w == 1) { - // if only one sample, can't do any interpolation - out[0] = out[1] = input[0]; - return out; - } + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } - out[0] = input[0]; - out[1] = stbi__div4(input[0]*3 + input[1] + 2); - for (i=1; i < w-1; ++i) { - int n = 3*input[i]+2; - out[i*2+0] = stbi__div4(n+input[i-1]); - out[i*2+1] = stbi__div4(n+input[i+1]); - } - out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); - out[i*2+1] = input[w-1]; + out[0] = input[0]; + out[1] = stbi__div4(input[0] * 3 + input[1] + 2); + for (i = 1; i < w - 1; ++i) { + int n = 3 * input[i] + 2; + out[i * 2 + 0] = stbi__div4(n + input[i - 1]); + out[i * 2 + 1] = stbi__div4(n + input[i + 1]); + } + out[i * 2 + 0] = stbi__div4(input[w - 2] * 3 + input[w - 1] + 2); + out[i * 2 + 1] = input[w - 1]; - STBI_NOTUSED(in_far); - STBI_NOTUSED(hs); + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); - return out; + return out; } -#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) +#define stbi__div16(x) ((stbi_uc)((x) >> 4)) -static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate 2x2 samples for every one in input - int i,t0,t1; - if (w == 1) { - out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); - return out; - } +static stbi_uc* stbi__resample_row_hv_2(stbi_uc* out, stbi_uc* in_near, + stbi_uc* in_far, int w, int hs) { + // need to generate 2x2 samples for every one in input + int i, t0, t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); + return out; + } - t1 = 3*in_near[0] + in_far[0]; - out[0] = stbi__div4(t1+2); - for (i=1; i < w; ++i) { - t0 = t1; - t1 = 3*in_near[i]+in_far[i]; - out[i*2-1] = stbi__div16(3*t0 + t1 + 8); - out[i*2 ] = stbi__div16(3*t1 + t0 + 8); - } - out[w*2-1] = stbi__div4(t1+2); + t1 = 3 * in_near[0] + in_far[0]; + out[0] = stbi__div4(t1 + 2); + for (i = 1; i < w; ++i) { + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + } + out[w * 2 - 1] = stbi__div4(t1 + 2); - STBI_NOTUSED(hs); + STBI_NOTUSED(hs); - return out; + return out; } #if defined(STBI_SSE2) || defined(STBI_NEON) -static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate 2x2 samples for every one in input - int i=0,t0,t1; +static stbi_uc* stbi__resample_row_hv_2_simd(stbi_uc* out, stbi_uc* in_near, + stbi_uc* in_far, int w, int hs) { + // need to generate 2x2 samples for every one in input + int i = 0, t0, t1; - if (w == 1) { - out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); - return out; - } + if (w == 1) { + out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); + return out; + } - t1 = 3*in_near[0] + in_far[0]; - // process groups of 8 pixels for as long as we can. - // note we can't handle the last pixel in a row in this loop - // because we need to handle the filter boundary conditions. - for (; i < ((w-1) & ~7); i += 8) { + t1 = 3 * in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w - 1) & ~7); i += 8) { #if defined(STBI_SSE2) - // load and perform the vertical filtering pass - // this uses 3*x + y = 4*x + (y - x) - __m128i zero = _mm_setzero_si128(); - __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); - __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); - __m128i farw = _mm_unpacklo_epi8(farb, zero); - __m128i nearw = _mm_unpacklo_epi8(nearb, zero); - __m128i diff = _mm_sub_epi16(farw, nearw); - __m128i nears = _mm_slli_epi16(nearw, 2); - __m128i curr = _mm_add_epi16(nears, diff); // current row + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i*)(in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i*)(in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row - // horizontal filter works the same based on shifted vers of current - // row. "prev" is current row shifted right by 1 pixel; we need to - // insert the previous pixel value (from t1). - // "next" is current row shifted left by 1 pixel, with first pixel - // of next block of 8 pixels added in. - __m128i prv0 = _mm_slli_si128(curr, 2); - __m128i nxt0 = _mm_srli_si128(curr, 2); - __m128i prev = _mm_insert_epi16(prv0, t1, 0); - __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = + _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7); - // horizontal filter, polyphase implementation since it's convenient: - // even pixels = 3*cur + prev = cur*4 + (prev - cur) - // odd pixels = 3*cur + next = cur*4 + (next - cur) - // note the shared term. - __m128i bias = _mm_set1_epi16(8); - __m128i curs = _mm_slli_epi16(curr, 2); - __m128i prvd = _mm_sub_epi16(prev, curr); - __m128i nxtd = _mm_sub_epi16(next, curr); - __m128i curb = _mm_add_epi16(curs, bias); - __m128i even = _mm_add_epi16(prvd, curb); - __m128i odd = _mm_add_epi16(nxtd, curb); + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); - // interleave even and odd pixels, then undo scaling. - __m128i int0 = _mm_unpacklo_epi16(even, odd); - __m128i int1 = _mm_unpackhi_epi16(even, odd); - __m128i de0 = _mm_srli_epi16(int0, 4); - __m128i de1 = _mm_srli_epi16(int1, 4); + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); - // pack and write output - __m128i outv = _mm_packus_epi16(de0, de1); - _mm_storeu_si128((__m128i *) (out + i*2), outv); + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i*)(out + i * 2), outv); #elif defined(STBI_NEON) - // load and perform the vertical filtering pass - // this uses 3*x + y = 4*x + (y - x) - uint8x8_t farb = vld1_u8(in_far + i); - uint8x8_t nearb = vld1_u8(in_near + i); - int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); - int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); - int16x8_t curr = vaddq_s16(nears, diff); // current row + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row - // horizontal filter works the same based on shifted vers of current - // row. "prev" is current row shifted right by 1 pixel; we need to - // insert the previous pixel value (from t1). - // "next" is current row shifted left by 1 pixel, with first pixel - // of next block of 8 pixels added in. - int16x8_t prv0 = vextq_s16(curr, curr, 7); - int16x8_t nxt0 = vextq_s16(curr, curr, 1); - int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); - int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = + vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7); - // horizontal filter, polyphase implementation since it's convenient: - // even pixels = 3*cur + prev = cur*4 + (prev - cur) - // odd pixels = 3*cur + next = cur*4 + (next - cur) - // note the shared term. - int16x8_t curs = vshlq_n_s16(curr, 2); - int16x8_t prvd = vsubq_s16(prev, curr); - int16x8_t nxtd = vsubq_s16(next, curr); - int16x8_t even = vaddq_s16(curs, prvd); - int16x8_t odd = vaddq_s16(curs, nxtd); + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); - // undo scaling and round, then store with even/odd phases interleaved - uint8x8x2_t o; - o.val[0] = vqrshrun_n_s16(even, 4); - o.val[1] = vqrshrun_n_s16(odd, 4); - vst2_u8(out + i*2, o); + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i * 2, o); #endif - // "previous" value for next iter - t1 = 3*in_near[i+7] + in_far[i+7]; - } + // "previous" value for next iter + t1 = 3 * in_near[i + 7] + in_far[i + 7]; + } - t0 = t1; - t1 = 3*in_near[i] + in_far[i]; - out[i*2] = stbi__div16(3*t1 + t0 + 8); + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); - for (++i; i < w; ++i) { - t0 = t1; - t1 = 3*in_near[i]+in_far[i]; - out[i*2-1] = stbi__div16(3*t0 + t1 + 8); - out[i*2 ] = stbi__div16(3*t1 + t0 + 8); - } - out[w*2-1] = stbi__div4(t1+2); + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + } + out[w * 2 - 1] = stbi__div4(t1 + 2); - STBI_NOTUSED(hs); + STBI_NOTUSED(hs); - return out; + return out; } #endif -static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // resample with nearest-neighbor - int i,j; - STBI_NOTUSED(in_far); - for (i=0; i < w; ++i) - for (j=0; j < hs; ++j) - out[i*hs+j] = in_near[i]; - return out; +static stbi_uc* stbi__resample_row_generic(stbi_uc* out, stbi_uc* in_near, + stbi_uc* in_far, int w, int hs) { + // resample with nearest-neighbor + int i, j; + STBI_NOTUSED(in_far); + for (i = 0; i < w; ++i) + for (j = 0; j < hs; ++j) out[i * hs + j] = in_near[i]; + return out; } // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar -#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) -static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) -{ - int i; - for (i=0; i < count; ++i) { - int y_fixed = (y[i] << 20) + (1<<19); // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr* stbi__float2fixed(1.40200f); - g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* stbi__float2fixed(1.77200f); - r >>= 20; - g >>= 20; - b >>= 20; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } +#define stbi__float2fixed(x) (((int)((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc* out, const stbi_uc* y, + const stbi_uc* pcb, const stbi_uc* pcr, + int count, int step) { + int i; + for (i = 0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1 << 19); // rounding + int r, g, b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr * stbi__float2fixed(1.40200f); + g = y_fixed + (cr * -stbi__float2fixed(0.71414f)) + + ((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb * stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned)r > 255) { + if (r < 0) + r = 0; + else + r = 255; + } + if ((unsigned)g > 255) { + if (g < 0) + g = 0; + else + g = 255; + } + if ((unsigned)b > 255) { + if (b < 0) + b = 0; + else + b = 255; + } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } } #if defined(STBI_SSE2) || defined(STBI_NEON) -static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) -{ - int i = 0; +static void stbi__YCbCr_to_RGB_simd(stbi_uc* out, stbi_uc const* y, + stbi_uc const* pcb, stbi_uc const* pcr, + int count, int step) { + int i = 0; #ifdef STBI_SSE2 - // step == 3 is pretty ugly on the final interleave, and i'm not convinced - // it's useful in practice (you wouldn't use it for textures, for example). - // so just accelerate step == 4 case. - if (step == 4) { - // this is a fairly straightforward implementation and not super-optimized. - __m128i signflip = _mm_set1_epi8(-0x80); - __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); - __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); - __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); - __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); - __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); - __m128i xw = _mm_set1_epi16(255); // alpha channel + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not + // super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16((short)(1.40200f * 4096.0f + 0.5f)); + __m128i cr_const1 = _mm_set1_epi16(-(short)(0.71414f * 4096.0f + 0.5f)); + __m128i cb_const0 = _mm_set1_epi16(-(short)(0.34414f * 4096.0f + 0.5f)); + __m128i cb_const1 = _mm_set1_epi16((short)(1.77200f * 4096.0f + 0.5f)); + __m128i y_bias = _mm_set1_epi8((char)(unsigned char)128); + __m128i xw = _mm_set1_epi16(255); // alpha channel - for (; i+7 < count; i += 8) { - // load - __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); - __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); - __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); - __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 - __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + for (; i + 7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i*)(y + i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i*)(pcr + i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i*)(pcb + i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 - // unpack to short (and left-shift cr, cb by 8) - __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); - __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); - __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); - // color transform - __m128i yws = _mm_srli_epi16(yw, 4); - __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); - __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); - __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); - __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); - __m128i rws = _mm_add_epi16(cr0, yws); - __m128i gwt = _mm_add_epi16(cb0, yws); - __m128i bws = _mm_add_epi16(yws, cb1); - __m128i gws = _mm_add_epi16(gwt, cr1); + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); - // descale - __m128i rw = _mm_srai_epi16(rws, 4); - __m128i bw = _mm_srai_epi16(bws, 4); - __m128i gw = _mm_srai_epi16(gws, 4); + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); - // back to byte, set up for transpose - __m128i brb = _mm_packus_epi16(rw, bw); - __m128i gxb = _mm_packus_epi16(gw, xw); + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); - // transpose to interleave channels - __m128i t0 = _mm_unpacklo_epi8(brb, gxb); - __m128i t1 = _mm_unpackhi_epi8(brb, gxb); - __m128i o0 = _mm_unpacklo_epi16(t0, t1); - __m128i o1 = _mm_unpackhi_epi16(t0, t1); + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); - // store - _mm_storeu_si128((__m128i *) (out + 0), o0); - _mm_storeu_si128((__m128i *) (out + 16), o1); - out += 32; - } - } + // store + _mm_storeu_si128((__m128i*)(out + 0), o0); + _mm_storeu_si128((__m128i*)(out + 16), o1); + out += 32; + } + } #endif #ifdef STBI_NEON - // in this version, step=3 support would be easy to add. but is there demand? - if (step == 4) { - // this is a fairly straightforward implementation and not super-optimized. - uint8x8_t signflip = vdup_n_u8(0x80); - int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); - int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); - int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); - int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + // in this version, step=3 support would be easy to add. but is there + // demand? + if (step == 4) { + // this is a fairly straightforward implementation and not + // super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16((short)(1.40200f * 4096.0f + 0.5f)); + int16x8_t cr_const1 = vdupq_n_s16(-(short)(0.71414f * 4096.0f + 0.5f)); + int16x8_t cb_const0 = vdupq_n_s16(-(short)(0.34414f * 4096.0f + 0.5f)); + int16x8_t cb_const1 = vdupq_n_s16((short)(1.77200f * 4096.0f + 0.5f)); - for (; i+7 < count; i += 8) { - // load - uint8x8_t y_bytes = vld1_u8(y + i); - uint8x8_t cr_bytes = vld1_u8(pcr + i); - uint8x8_t cb_bytes = vld1_u8(pcb + i); - int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); - int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + for (; i + 7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = + vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = + vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); - // expand to s16 - int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); - int16x8_t crw = vshll_n_s8(cr_biased, 7); - int16x8_t cbw = vshll_n_s8(cb_biased, 7); + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); - // color transform - int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); - int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); - int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); - int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); - int16x8_t rws = vaddq_s16(yws, cr0); - int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); - int16x8_t bws = vaddq_s16(yws, cb1); + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); - // undo scaling, round, convert to byte - uint8x8x4_t o; - o.val[0] = vqrshrun_n_s16(rws, 4); - o.val[1] = vqrshrun_n_s16(gws, 4); - o.val[2] = vqrshrun_n_s16(bws, 4); - o.val[3] = vdup_n_u8(255); + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); - // store, interleaving r/g/b/a - vst4_u8(out, o); - out += 8*4; - } - } + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8 * 4; + } + } #endif - for (; i < count; ++i) { - int y_fixed = (y[i] << 20) + (1<<19); // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr* stbi__float2fixed(1.40200f); - g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* stbi__float2fixed(1.77200f); - r >>= 20; - g >>= 20; - b >>= 20; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1 << 19); // rounding + int r, g, b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr * stbi__float2fixed(1.40200f); + g = y_fixed + cr * -stbi__float2fixed(0.71414f) + + ((cb * -stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb * stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned)r > 255) { + if (r < 0) + r = 0; + else + r = 255; + } + if ((unsigned)g > 255) { + if (g < 0) + g = 0; + else + g = 255; + } + if ((unsigned)b > 255) { + if (b < 0) + b = 0; + else + b = 255; + } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } } #endif // set up the kernels -static void stbi__setup_jpeg(stbi__jpeg *j) -{ - j->idct_block_kernel = stbi__idct_block; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; +static void stbi__setup_jpeg(stbi__jpeg* j) { + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; #ifdef STBI_SSE2 - if (stbi__sse2_available()) { - j->idct_block_kernel = stbi__idct_simd; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; - } + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } #endif #ifdef STBI_NEON - j->idct_block_kernel = stbi__idct_simd; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } // clean up the temporary component buffers -static void stbi__cleanup_jpeg(stbi__jpeg *j) -{ - stbi__free_jpeg_components(j, j->s->img_n, 0); +static void stbi__cleanup_jpeg(stbi__jpeg* j) { + stbi__free_jpeg_components(j, j->s->img_n, 0); } -typedef struct -{ - resample_row_func resample; - stbi_uc *line0,*line1; - int hs,vs; // expansion factor in each axis - int w_lores; // horizontal pixels pre-expansion - int ystep; // how far through vertical expansion we are - int ypos; // which pre-expansion row we're on +typedef struct { + resample_row_func resample; + stbi_uc *line0, *line1; + int hs, vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on } stbi__resample; // fast 0..255 * 0..255 => 0..255 rounded multiplication -static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) -{ - unsigned int t = x*y + 128; - return (stbi_uc) ((t + (t >>8)) >> 8); +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) { + unsigned int t = x * y + 128; + return (stbi_uc)((t + (t >> 8)) >> 8); } -static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) -{ - int n, decode_n, is_rgb; - z->s->img_n = 0; // make stbi__cleanup_jpeg safe +static stbi_uc* load_jpeg_image(stbi__jpeg* z, int* out_x, int* out_y, + int* comp, int req_comp) { + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe - // validate req_comp - if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + // validate req_comp + if (req_comp < 0 || req_comp > 4) + return stbi__errpuc("bad req_comp", "Internal error"); - // load a jpeg image from whichever source, but leave in YCbCr format - if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { + stbi__cleanup_jpeg(z); + return NULL; + } - // determine actual number of components to generate - n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; - is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + is_rgb = z->s->img_n == 3 && + (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); - if (z->s->img_n == 3 && n < 3 && !is_rgb) - decode_n = 1; - else - decode_n = z->s->img_n; + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; - // nothing to do if no components requested; check this now to avoid - // accessing uninitialized coutput[0] later - if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { + stbi__cleanup_jpeg(z); + return NULL; + } - // resample and color-convert - { - int k; - unsigned int i,j; - stbi_uc *output; - stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + // resample and color-convert + { + int k; + unsigned int i, j; + stbi_uc* output; + stbi_uc* coutput[4] = {NULL, NULL, NULL, NULL}; - stbi__resample res_comp[4]; + stbi__resample res_comp[4]; - for (k=0; k < decode_n; ++k) { - stbi__resample *r = &res_comp[k]; + for (k = 0; k < decode_n; ++k) { + stbi__resample* r = &res_comp[k]; - // allocate line buffer big enough for upsampling off the edges - // with upsample factor of 4 - z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); - if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } - - r->hs = z->img_h_max / z->img_comp[k].h; - r->vs = z->img_v_max / z->img_comp[k].v; - r->ystep = r->vs >> 1; - r->w_lores = (z->s->img_x + r->hs-1) / r->hs; - r->ypos = 0; - r->line0 = r->line1 = z->img_comp[k].data; - - if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; - else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; - else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; - else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; - else r->resample = stbi__resample_row_generic; - } - - // can't error after this so, this is safe - output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); - if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } - - // now go ahead and resample - for (j=0; j < z->s->img_y; ++j) { - stbi_uc *out = output + n * z->s->img_x * j; - for (k=0; k < decode_n; ++k) { - stbi__resample *r = &res_comp[k]; - int y_bot = r->ystep >= (r->vs >> 1); - coutput[k] = r->resample(z->img_comp[k].linebuf, - y_bot ? r->line1 : r->line0, - y_bot ? r->line0 : r->line1, - r->w_lores, r->hs); - if (++r->ystep >= r->vs) { - r->ystep = 0; - r->line0 = r->line1; - if (++r->ypos < z->img_comp[k].y) - r->line1 += z->img_comp[k].w2; + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc*)stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { + stbi__cleanup_jpeg(z); + return stbi__errpuc("outofmem", "Out of memory"); } - } - if (n >= 3) { - stbi_uc *y = coutput[0]; - if (z->s->img_n == 3) { - if (is_rgb) { - for (i=0; i < z->s->img_x; ++i) { - out[0] = y[i]; - out[1] = coutput[1][i]; - out[2] = coutput[2][i]; - out[3] = 255; - out += n; - } - } else { - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - } - } else if (z->s->img_n == 4) { - if (z->app14_color_transform == 0) { // CMYK - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - out[0] = stbi__blinn_8x8(coutput[0][i], m); - out[1] = stbi__blinn_8x8(coutput[1][i], m); - out[2] = stbi__blinn_8x8(coutput[2][i], m); - out[3] = 255; - out += n; - } - } else if (z->app14_color_transform == 2) { // YCCK - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - out[0] = stbi__blinn_8x8(255 - out[0], m); - out[1] = stbi__blinn_8x8(255 - out[1], m); - out[2] = stbi__blinn_8x8(255 - out[2], m); - out += n; - } - } else { // YCbCr + alpha? Ignore the fourth channel for now - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - } - } else - for (i=0; i < z->s->img_x; ++i) { - out[0] = out[1] = out[2] = y[i]; - out[3] = 255; // not used if n==3 - out += n; - } - } else { - if (is_rgb) { - if (n == 1) - for (i=0; i < z->s->img_x; ++i) - *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); - else { - for (i=0; i < z->s->img_x; ++i, out += 2) { - out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); - out[1] = 255; - } - } - } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); - stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); - stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); - out[0] = stbi__compute_y(r, g, b); - out[1] = 255; - out += n; - } - } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { - for (i=0; i < z->s->img_x; ++i) { - out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); - out[1] = 255; - out += n; - } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs - 1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) + r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) + r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) + r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) + r->resample = z->resample_row_hv_2_kernel; + else + r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc*)stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { + stbi__cleanup_jpeg(z); + return stbi__errpuc("outofmem", "Out of memory"); + } + + // now go ahead and resample + for (j = 0; j < z->s->img_y; ++j) { + stbi_uc* out = output + n * z->s->img_x * j; + for (k = 0; k < decode_n; ++k) { + stbi__resample* r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample( + z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc* y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i = 0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], + z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], + z->s->img_x, n); + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for + // now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], + z->s->img_x, n); + } + } else + for (i = 0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } } else { - stbi_uc *y = coutput[0]; - if (n == 1) - for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; - else - for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + if (is_rgb) { + if (n == 1) + for (i = 0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y( + coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i = 0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y( + coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i = 0; i < z->s->img_x; ++i) { + out[0] = + stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc* y = coutput[0]; + if (n == 1) + for (i = 0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i = 0; i < z->s->img_x; ++i) { + *out++ = y[i]; + *out++ = 255; + } + } } - } - } - stbi__cleanup_jpeg(z); - *out_x = z->s->img_x; - *out_y = z->s->img_y; - if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output - return output; - } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) + *comp = z->s->img_n >= 3 + ? 3 + : 1; // report original components, not output + return output; + } } -static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - unsigned char* result; - stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); - if (!j) return stbi__errpuc("outofmem", "Out of memory"); - memset(j, 0, sizeof(stbi__jpeg)); - STBI_NOTUSED(ri); - j->s = s; - stbi__setup_jpeg(j); - result = load_jpeg_image(j, x,y,comp,req_comp); - STBI_FREE(j); - return result; +static void* stbi__jpeg_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri) { + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x, y, comp, req_comp); + STBI_FREE(j); + return result; } -static int stbi__jpeg_test(stbi__context *s) -{ - int r; - stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); - if (!j) return stbi__err("outofmem", "Out of memory"); - memset(j, 0, sizeof(stbi__jpeg)); - j->s = s; - stbi__setup_jpeg(j); - r = stbi__decode_jpeg_header(j, STBI__SCAN_type); - stbi__rewind(s); - STBI_FREE(j); - return r; +static int stbi__jpeg_test(stbi__context* s) { + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; } -static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) -{ - if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { - stbi__rewind( j->s ); - return 0; - } - if (x) *x = j->s->img_x; - if (y) *y = j->s->img_y; - if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; - return 1; +static int stbi__jpeg_info_raw(stbi__jpeg* j, int* x, int* y, int* comp) { + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind(j->s); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; } -static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) -{ - int result; - stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); - if (!j) return stbi__err("outofmem", "Out of memory"); - memset(j, 0, sizeof(stbi__jpeg)); - j->s = s; - result = stbi__jpeg_info_raw(j, x, y, comp); - STBI_FREE(j); - return result; +static int stbi__jpeg_info(stbi__context* s, int* x, int* y, int* comp) { + int result; + stbi__jpeg* j = (stbi__jpeg*)(stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; } #endif @@ -4088,84 +4477,80 @@ static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) #ifndef STBI_NO_ZLIB // fast-way is faster to check than jpeg huffman, but slow way is slower -#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables -#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) -#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) -typedef struct -{ - stbi__uint16 fast[1 << STBI__ZFAST_BITS]; - stbi__uint16 firstcode[16]; - int maxcode[17]; - stbi__uint16 firstsymbol[16]; - stbi_uc size[STBI__ZNSYMS]; - stbi__uint16 value[STBI__ZNSYMS]; +typedef struct { + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; } stbi__zhuffman; -stbi_inline static int stbi__bitreverse16(int n) -{ - n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); - n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); - n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); - n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); - return n; +stbi_inline static int stbi__bitreverse16(int n) { + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; } -stbi_inline static int stbi__bit_reverse(int v, int bits) -{ - STBI_ASSERT(bits <= 16); - // to bit reverse n bits, reverse 16 and shift - // e.g. 11 bits, bit reverse and shift away 5 - return stbi__bitreverse16(v) >> (16-bits); +stbi_inline static int stbi__bit_reverse(int v, int bits) { + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16 - bits); } -static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) -{ - int i,k=0; - int code, next_code[16], sizes[17]; +static int stbi__zbuild_huffman(stbi__zhuffman* z, const stbi_uc* sizelist, + int num) { + int i, k = 0; + int code, next_code[16], sizes[17]; - // DEFLATE spec for generating codes - memset(sizes, 0, sizeof(sizes)); - memset(z->fast, 0, sizeof(z->fast)); - for (i=0; i < num; ++i) - ++sizes[sizelist[i]]; - sizes[0] = 0; - for (i=1; i < 16; ++i) - if (sizes[i] > (1 << i)) - return stbi__err("bad sizes", "Corrupt PNG"); - code = 0; - for (i=1; i < 16; ++i) { - next_code[i] = code; - z->firstcode[i] = (stbi__uint16) code; - z->firstsymbol[i] = (stbi__uint16) k; - code = (code + sizes[i]); - if (sizes[i]) - if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); - z->maxcode[i] = code << (16-i); // preshift for inner loop - code <<= 1; - k += sizes[i]; - } - z->maxcode[16] = 0x10000; // sentinel - for (i=0; i < num; ++i) { - int s = sizelist[i]; - if (s) { - int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; - stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); - z->size [c] = (stbi_uc ) s; - z->value[c] = (stbi__uint16) i; - if (s <= STBI__ZFAST_BITS) { - int j = stbi__bit_reverse(next_code[s],s); - while (j < (1 << STBI__ZFAST_BITS)) { - z->fast[j] = fastv; - j += (1 << s); + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i = 0; i < num; ++i) ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i = 1; i < 16; ++i) + if (sizes[i] > (1 << i)) return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i = 1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16)code; + z->firstsymbol[i] = (stbi__uint16)k; + code = (code + sizes[i]); + if (sizes[i]) + if (code - 1 >= (1 << i)) + return stbi__err("bad codelengths", "Corrupt PNG"); + z->maxcode[i] = code << (16 - i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i = 0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16)((s << 9) | i); + z->size[c] = (stbi_uc)s; + z->value[c] = (stbi__uint16)i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s], s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } } - } - ++next_code[s]; - } - } - return 1; + ++next_code[s]; + } + } + return 1; } // zlib-from-memory implementation for PNG reading @@ -4174,297 +4559,322 @@ static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int // we require PNG read all the IDATs and combine them into a single // memory buffer -typedef struct -{ - stbi_uc *zbuffer, *zbuffer_end; - int num_bits; - int hit_zeof_once; - stbi__uint32 code_buffer; +typedef struct { + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + int hit_zeof_once; + stbi__uint32 code_buffer; - char *zout; - char *zout_start; - char *zout_end; - int z_expandable; + char* zout; + char* zout_start; + char* zout_end; + int z_expandable; - stbi__zhuffman z_length, z_distance; + stbi__zhuffman z_length, z_distance; } stbi__zbuf; -stbi_inline static int stbi__zeof(stbi__zbuf *z) -{ - return (z->zbuffer >= z->zbuffer_end); +stbi_inline static int stbi__zeof(stbi__zbuf* z) { + return (z->zbuffer >= z->zbuffer_end); } -stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) -{ - return stbi__zeof(z) ? 0 : *z->zbuffer++; +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf* z) { + return stbi__zeof(z) ? 0 : *z->zbuffer++; } -static void stbi__fill_bits(stbi__zbuf *z) -{ - do { - if (z->code_buffer >= (1U << z->num_bits)) { - z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ - return; - } - z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; - z->num_bits += 8; - } while (z->num_bits <= 24); +static void stbi__fill_bits(stbi__zbuf* z) { + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int)stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); } -stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) -{ - unsigned int k; - if (z->num_bits < n) stbi__fill_bits(z); - k = z->code_buffer & ((1 << n) - 1); - z->code_buffer >>= n; - z->num_bits -= n; - return k; +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf* z, int n) { + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; } -static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) -{ - int b,s,k; - // not resolved by fast table, so compute it the slow way - // use jpeg approach, which requires MSbits at top - k = stbi__bit_reverse(a->code_buffer, 16); - for (s=STBI__ZFAST_BITS+1; ; ++s) - if (k < z->maxcode[s]) - break; - if (s >= 16) return -1; // invalid code! - // code size is s, so: - b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; - if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! - if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. - a->code_buffer >>= s; - a->num_bits -= s; - return z->value[b]; +static int stbi__zhuffman_decode_slowpath(stbi__zbuf* a, stbi__zhuffman* z) { + int b, s, k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s = STBI__ZFAST_BITS + 1;; ++s) + if (k < z->maxcode[s]) break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) + return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; } -stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) -{ - int b,s; - if (a->num_bits < 16) { - if (stbi__zeof(a)) { - if (!a->hit_zeof_once) { - // This is the first time we hit eof, insert 16 extra padding btis - // to allow us to keep going; if we actually consume any of them - // though, that is invalid data. This is caught later. - a->hit_zeof_once = 1; - a->num_bits += 16; // add 16 implicit zero bits - } else { - // We already inserted our extra 16 padding bits and are again - // out, this stream is actually prematurely terminated. - return -1; - } - } else { - stbi__fill_bits(a); - } - } - b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; - if (b) { - s = b >> 9; - a->code_buffer >>= s; - a->num_bits -= s; - return b & 511; - } - return stbi__zhuffman_decode_slowpath(a, z); +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf* a, stbi__zhuffman* z) { + int b, s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + if (!a->hit_zeof_once) { + // This is the first time we hit eof, insert 16 extra padding + // btis to allow us to keep going; if we actually consume any of + // them though, that is invalid data. This is caught later. + a->hit_zeof_once = 1; + a->num_bits += 16; // add 16 implicit zero bits + } else { + // We already inserted our extra 16 padding bits and are again + // out, this stream is actually prematurely terminated. + return -1; + } + } else { + stbi__fill_bits(a); + } + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); } -static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +static int stbi__zexpand(stbi__zbuf* z, char* zout, + int n) // need to make room for n bytes { - char *q; - unsigned int cur, limit, old_limit; - z->zout = zout; - if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); - cur = (unsigned int) (z->zout - z->zout_start); - limit = old_limit = (unsigned) (z->zout_end - z->zout_start); - if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); - while (cur + n > limit) { - if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); - limit *= 2; - } - q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); - STBI_NOTUSED(old_limit); - if (q == NULL) return stbi__err("outofmem", "Out of memory"); - z->zout_start = q; - z->zout = q + cur; - z->zout_end = q + limit; - return 1; + char* q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) + return stbi__err("output buffer limit", "Corrupt PNG"); + cur = (unsigned int)(z->zout - z->zout_start); + limit = old_limit = (unsigned)(z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned)n) + return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if (limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char*)STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; } static const int stbi__zlength_base[31] = { - 3,4,5,6,7,8,9,10,11,13, - 15,17,19,23,27,31,35,43,51,59, - 67,83,99,115,131,163,195,227,258,0,0 }; + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; -static const int stbi__zlength_extra[31]= -{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; +static const int stbi__zlength_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, + 4, 4, 5, 5, 5, 5, 0, 0, 0}; -static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, -257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; +static const int stbi__zdist_base[32] = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, + 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, + 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; -static const int stbi__zdist_extra[32] = -{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; +static const int stbi__zdist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, + 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, + 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; -static int stbi__parse_huffman_block(stbi__zbuf *a) -{ - char *zout = a->zout; - for(;;) { - int z = stbi__zhuffman_decode(a, &a->z_length); - if (z < 256) { - if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes - if (zout >= a->zout_end) { - if (!stbi__zexpand(a, zout, 1)) return 0; - zout = a->zout; - } - *zout++ = (char) z; - } else { - stbi_uc *p; - int len,dist; - if (z == 256) { - a->zout = zout; - if (a->hit_zeof_once && a->num_bits < 16) { - // The first time we hit zeof, we inserted 16 extra zero bits into our bit - // buffer so the decoder can just do its speculative decoding. But if we - // actually consumed any of those bits (which is the case when num_bits < 16), - // the stream actually read past the end so it is malformed. - return stbi__err("unexpected end","Corrupt PNG"); +static int stbi__parse_huffman_block(stbi__zbuf* a) { + char* zout = a->zout; + for (;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) + return stbi__err("bad huffman code", + "Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; } - return 1; - } - if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data - z -= 257; - len = stbi__zlength_base[z]; - if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); - z = stbi__zhuffman_decode(a, &a->z_distance); - if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data - dist = stbi__zdist_base[z]; - if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); - if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); - if (len > a->zout_end - zout) { - if (!stbi__zexpand(a, zout, len)) return 0; - zout = a->zout; - } - p = (stbi_uc *) (zout - dist); - if (dist == 1) { // run of one byte; common in images. - stbi_uc v = *p; - if (len) { do *zout++ = v; while (--len); } - } else { - if (len) { do *zout++ = *p++; while (--len); } - } - } - } + *zout++ = (char)z; + } else { + stbi_uc* p; + int len, dist; + if (z == 256) { + a->zout = zout; + if (a->hit_zeof_once && a->num_bits < 16) { + // The first time we hit zeof, we inserted 16 extra zero + // bits into our bit buffer so the decoder can just do its + // speculative decoding. But if we actually consumed any of + // those bits (which is the case when num_bits < 16), the + // stream actually read past the end so it is malformed. + return stbi__err("unexpected end", "Corrupt PNG"); + } + return 1; + } + if (z >= 286) + return stbi__err( + "bad huffman code", + "Corrupt PNG"); // per DEFLATE, length codes 286 and 287 + // must not appear in compressed data + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) + len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0 || z >= 30) + return stbi__err( + "bad huffman code", + "Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 + // must not appear in compressed data + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) + dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) + return stbi__err("bad dist", "Corrupt PNG"); + if (len > a->zout_end - zout) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc*)(zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { + do *zout++ = v; + while (--len); + } + } else { + if (len) { + do *zout++ = *p++; + while (--len); + } + } + } + } } -static int stbi__compute_huffman_codes(stbi__zbuf *a) -{ - static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; - stbi__zhuffman z_codelength; - stbi_uc lencodes[286+32+137];//padding for maximum single op - stbi_uc codelength_sizes[19]; - int i,n; +static int stbi__compute_huffman_codes(stbi__zbuf* a) { + static const stbi_uc length_dezigzag[19] = { + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286 + 32 + 137]; // padding for maximum single op + stbi_uc codelength_sizes[19]; + int i, n; - int hlit = stbi__zreceive(a,5) + 257; - int hdist = stbi__zreceive(a,5) + 1; - int hclen = stbi__zreceive(a,4) + 4; - int ntot = hlit + hdist; + int hlit = stbi__zreceive(a, 5) + 257; + int hdist = stbi__zreceive(a, 5) + 1; + int hclen = stbi__zreceive(a, 4) + 4; + int ntot = hlit + hdist; - memset(codelength_sizes, 0, sizeof(codelength_sizes)); - for (i=0; i < hclen; ++i) { - int s = stbi__zreceive(a,3); - codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; - } - if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i = 0; i < hclen; ++i) { + int s = stbi__zreceive(a, 3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc)s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; - n = 0; - while (n < ntot) { - int c = stbi__zhuffman_decode(a, &z_codelength); - if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); - if (c < 16) - lencodes[n++] = (stbi_uc) c; - else { - stbi_uc fill = 0; - if (c == 16) { - c = stbi__zreceive(a,2)+3; - if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); - fill = lencodes[n-1]; - } else if (c == 17) { - c = stbi__zreceive(a,3)+3; - } else if (c == 18) { - c = stbi__zreceive(a,7)+11; - } else { + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); - } - if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); - memset(lencodes+n, fill, c); - n += c; - } - } - if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); - if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; - if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; - return 1; + if (c < 16) + lencodes[n++] = (stbi_uc)c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a, 2) + 3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n - 1]; + } else if (c == 17) { + c = stbi__zreceive(a, 3) + 3; + } else if (c == 18) { + c = stbi__zreceive(a, 7) + 11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) + return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes + n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths", "Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes + hlit, hdist)) return 0; + return 1; } -static int stbi__parse_uncompressed_block(stbi__zbuf *a) -{ - stbi_uc header[4]; - int len,nlen,k; - if (a->num_bits & 7) - stbi__zreceive(a, a->num_bits & 7); // discard - // drain the bit-packed data into header - k = 0; - while (a->num_bits > 0) { - header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check - a->code_buffer >>= 8; - a->num_bits -= 8; - } - if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); - // now fill header the normal way - while (k < 4) - header[k++] = stbi__zget8(a); - len = header[1] * 256 + header[0]; - nlen = header[3] * 256 + header[2]; - if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); - if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); - if (a->zout + len > a->zout_end) - if (!stbi__zexpand(a, a->zout, len)) return 0; - memcpy(a->zout, a->zbuffer, len); - a->zbuffer += len; - a->zout += len; - return 1; +static int stbi__parse_uncompressed_block(stbi__zbuf* a) { + stbi_uc header[4]; + int len, nlen, k; + if (a->num_bits & 7) stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = + (stbi_uc)(a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt", "Corrupt PNG"); + // now fill header the normal way + while (k < 4) header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt", "Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) + return stbi__err("read past buffer", "Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; } -static int stbi__parse_zlib_header(stbi__zbuf *a) -{ - int cmf = stbi__zget8(a); - int cm = cmf & 15; - /* int cinfo = cmf >> 4; */ - int flg = stbi__zget8(a); - if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec - if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec - if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png - if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png - // window = 1 << (8 + cinfo)... but who cares, we fully buffer output - return 1; +static int stbi__parse_zlib_header(stbi__zbuf* a) { + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) + return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec + if ((cmf * 256 + flg) % 31 != 0) + return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec + if (flg & 32) + return stbi__err( + "no preset dict", + "Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) + return stbi__err("bad compression", + "Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; } -static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = -{ - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 -}; -static const stbi_uc stbi__zdefault_distance[32] = -{ - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 -}; +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = { + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8}; +static const stbi_uc stbi__zdefault_distance[32] = { + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; /* Init algorithm: { @@ -4478,118 +4888,124 @@ Init algorithm: } */ -static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) -{ - int final, type; - if (parse_header) - if (!stbi__parse_zlib_header(a)) return 0; - a->num_bits = 0; - a->code_buffer = 0; - a->hit_zeof_once = 0; - do { - final = stbi__zreceive(a,1); - type = stbi__zreceive(a,2); - if (type == 0) { - if (!stbi__parse_uncompressed_block(a)) return 0; - } else if (type == 3) { - return 0; - } else { - if (type == 1) { - // use fixed code lengths - if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; - if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; - } else { - if (!stbi__compute_huffman_codes(a)) return 0; - } - if (!stbi__parse_huffman_block(a)) return 0; - } - } while (!final); - return 1; +static int stbi__parse_zlib(stbi__zbuf* a, int parse_header) { + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + a->hit_zeof_once = 0; + do { + final = stbi__zreceive(a, 1); + type = stbi__zreceive(a, 2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, + STBI__ZNSYMS)) + return 0; + if (!stbi__zbuild_huffman(&a->z_distance, + stbi__zdefault_distance, 32)) + return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; } -static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) -{ - a->zout_start = obuf; - a->zout = obuf; - a->zout_end = obuf + olen; - a->z_expandable = exp; +static int stbi__do_zlib(stbi__zbuf* a, char* obuf, int olen, int exp, + int parse_header) { + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; - return stbi__parse_zlib(a, parse_header); + return stbi__parse_zlib(a, parse_header); } -STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(initial_size); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer + len; - if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } +STBIDEF char* stbi_zlib_decode_malloc_guesssize(const char* buffer, int len, + int initial_size, int* outlen) { + stbi__zbuf a; + char* p = (char*)stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc*)buffer; + a.zbuffer_end = (stbi_uc*)buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } } -STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) -{ - return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +STBIDEF char* stbi_zlib_decode_malloc(char const* buffer, int len, + int* outlen) { + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } -STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(initial_size); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer + len; - if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } +STBIDEF char* stbi_zlib_decode_malloc_guesssize_headerflag(const char* buffer, + int len, + int initial_size, + int* outlen, + int parse_header) { + stbi__zbuf a; + char* p = (char*)stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc*)buffer; + a.zbuffer_end = (stbi_uc*)buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } } -STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) -{ - stbi__zbuf a; - a.zbuffer = (stbi_uc *) ibuffer; - a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) - return (int) (a.zout - a.zout_start); - else - return -1; +STBIDEF int stbi_zlib_decode_buffer(char* obuffer, int olen, + char const* ibuffer, int ilen) { + stbi__zbuf a; + a.zbuffer = (stbi_uc*)ibuffer; + a.zbuffer_end = (stbi_uc*)ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int)(a.zout - a.zout_start); + else + return -1; } -STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(16384); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer+len; - if (stbi__do_zlib(&a, p, 16384, 1, 0)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } +STBIDEF char* stbi_zlib_decode_noheader_malloc(char const* buffer, int len, + int* outlen) { + stbi__zbuf a; + char* p = (char*)stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc*)buffer; + a.zbuffer_end = (stbi_uc*)buffer + len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } } -STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) -{ - stbi__zbuf a; - a.zbuffer = (stbi_uc *) ibuffer; - a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) - return (int) (a.zout - a.zout_start); - else - return -1; +STBIDEF int stbi_zlib_decode_noheader_buffer(char* obuffer, int olen, + const char* ibuffer, int ilen) { + stbi__zbuf a; + a.zbuffer = (stbi_uc*)ibuffer; + a.zbuffer_end = (stbi_uc*)ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int)(a.zout - a.zout_start); + else + return -1; } #endif @@ -4604,1131 +5020,1280 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char // - uses stb_zlib, a PD zlib implementation with fast huffman decoding #ifndef STBI_NO_PNG -typedef struct -{ - stbi__uint32 length; - stbi__uint32 type; +typedef struct { + stbi__uint32 length; + stbi__uint32 type; } stbi__pngchunk; -static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) -{ - stbi__pngchunk c; - c.length = stbi__get32be(s); - c.type = stbi__get32be(s); - return c; +static stbi__pngchunk stbi__get_chunk_header(stbi__context* s) { + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; } -static int stbi__check_png_header(stbi__context *s) -{ - static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; - int i; - for (i=0; i < 8; ++i) - if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); - return 1; +static int stbi__check_png_header(stbi__context* s) { + static const stbi_uc png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10}; + int i; + for (i = 0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) + return stbi__err("bad png sig", "Not a PNG"); + return 1; } -typedef struct -{ - stbi__context *s; - stbi_uc *idata, *expanded, *out; - int depth; +typedef struct { + stbi__context* s; + stbi_uc *idata, *expanded, *out; + int depth; } stbi__png; - enum { - STBI__F_none=0, - STBI__F_sub=1, - STBI__F_up=2, - STBI__F_avg=3, - STBI__F_paeth=4, - // synthetic filter used for first scanline to avoid needing a dummy row of 0s - STBI__F_avg_first + STBI__F_none = 0, + STBI__F_sub = 1, + STBI__F_up = 2, + STBI__F_avg = 3, + STBI__F_paeth = 4, + // synthetic filter used for first scanline to avoid needing a dummy row of + // 0s + STBI__F_avg_first }; -static stbi_uc first_row_filter[5] = -{ - STBI__F_none, - STBI__F_sub, - STBI__F_none, - STBI__F_avg_first, - STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub +static stbi_uc first_row_filter[5] = { + STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, + STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub }; -static int stbi__paeth(int a, int b, int c) -{ - // This formulation looks very different from the reference in the PNG spec, but is - // actually equivalent and has favorable data dependencies and admits straightforward - // generation of branch-free code, which helps performance significantly. - int thresh = c*3 - (a + b); - int lo = a < b ? a : b; - int hi = a < b ? b : a; - int t0 = (hi <= thresh) ? lo : c; - int t1 = (thresh <= lo) ? hi : t0; - return t1; +static int stbi__paeth(int a, int b, int c) { + // This formulation looks very different from the reference in the PNG spec, + // but is actually equivalent and has favorable data dependencies and admits + // straightforward generation of branch-free code, which helps performance + // significantly. + int thresh = c * 3 - (a + b); + int lo = a < b ? a : b; + int hi = a < b ? b : a; + int t0 = (hi <= thresh) ? lo : c; + int t1 = (thresh <= lo) ? hi : t0; + return t1; } -static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; +static const stbi_uc stbi__depth_scale_table[9] = {0, 0xff, 0x55, 0, 0x11, + 0, 0, 0, 0x01}; // adds an extra all-255 alpha channel // dest == src is legal // img_n must be 1 or 3 -static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n) -{ - int i; - // must process data backwards since we allow dest==src - if (img_n == 1) { - for (i=x-1; i >= 0; --i) { - dest[i*2+1] = 255; - dest[i*2+0] = src[i]; - } - } else { - STBI_ASSERT(img_n == 3); - for (i=x-1; i >= 0; --i) { - dest[i*4+3] = 255; - dest[i*4+2] = src[i*3+2]; - dest[i*4+1] = src[i*3+1]; - dest[i*4+0] = src[i*3+0]; - } - } +static void stbi__create_png_alpha_expand8(stbi_uc* dest, stbi_uc* src, + stbi__uint32 x, int img_n) { + int i; + // must process data backwards since we allow dest==src + if (img_n == 1) { + for (i = x - 1; i >= 0; --i) { + dest[i * 2 + 1] = 255; + dest[i * 2 + 0] = src[i]; + } + } else { + STBI_ASSERT(img_n == 3); + for (i = x - 1; i >= 0; --i) { + dest[i * 4 + 3] = 255; + dest[i * 4 + 2] = src[i * 3 + 2]; + dest[i * 4 + 1] = src[i * 3 + 1]; + dest[i * 4 + 0] = src[i * 3 + 0]; + } + } } // create the png data from post-deflated data -static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) -{ - int bytes = (depth == 16 ? 2 : 1); - stbi__context *s = a->s; - stbi__uint32 i,j,stride = x*out_n*bytes; - stbi__uint32 img_len, img_width_bytes; - stbi_uc *filter_buf; - int all_ok = 1; - int k; - int img_n = s->img_n; // copy it into a local for later +static int stbi__create_png_image_raw(stbi__png* a, stbi_uc* raw, + stbi__uint32 raw_len, int out_n, + stbi__uint32 x, stbi__uint32 y, int depth, + int color) { + int bytes = (depth == 16 ? 2 : 1); + stbi__context* s = a->s; + stbi__uint32 i, j, stride = x * out_n * bytes; + stbi__uint32 img_len, img_width_bytes; + stbi_uc* filter_buf; + int all_ok = 1; + int k; + int img_n = s->img_n; // copy it into a local for later - int output_bytes = out_n*bytes; - int filter_bytes = img_n*bytes; - int width = x; + int output_bytes = out_n * bytes; + int filter_bytes = img_n * bytes; + int width = x; - STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); - a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into - if (!a->out) return stbi__err("outofmem", "Out of memory"); + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1); + a->out = (stbi_uc*)stbi__malloc_mad3( + x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); - // note: error exits here don't need to clean up a->out individually, - // stbi__do_png always does on error. - if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); - img_width_bytes = (((img_n * x * depth) + 7) >> 3); - if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG"); - img_len = (img_width_bytes + 1) * y; + // note: error exits here don't need to clean up a->out individually, + // stbi__do_png always does on error. + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) + return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) + return stbi__err("too large", "Corrupt PNG"); + img_len = (img_width_bytes + 1) * y; - // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, - // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), - // so just check for raw_len < img_len always. - if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + // we used to check for exact match between raw_len and img_len on + // non-interlaced PNGs, but issue #276 reported a PNG in the wild that had + // extra data at the end (all zeros), so just check for raw_len < img_len + // always. + if (raw_len < img_len) return stbi__err("not enough pixels", "Corrupt PNG"); - // Allocate two scan lines worth of filter workspace buffer. - filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0); - if (!filter_buf) return stbi__err("outofmem", "Out of memory"); + // Allocate two scan lines worth of filter workspace buffer. + filter_buf = (stbi_uc*)stbi__malloc_mad2(img_width_bytes, 2, 0); + if (!filter_buf) return stbi__err("outofmem", "Out of memory"); - // Filtering for low-bit-depth images - if (depth < 8) { - filter_bytes = 1; - width = img_width_bytes; - } + // Filtering for low-bit-depth images + if (depth < 8) { + filter_bytes = 1; + width = img_width_bytes; + } - for (j=0; j < y; ++j) { - // cur/prior filter buffers alternate - stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes; - stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes; - stbi_uc *dest = a->out + stride*j; - int nk = width * filter_bytes; - int filter = *raw++; + for (j = 0; j < y; ++j) { + // cur/prior filter buffers alternate + stbi_uc* cur = filter_buf + (j & 1) * img_width_bytes; + stbi_uc* prior = filter_buf + (~j & 1) * img_width_bytes; + stbi_uc* dest = a->out + stride * j; + int nk = width * filter_bytes; + int filter = *raw++; - // check filter type - if (filter > 4) { - all_ok = stbi__err("invalid filter","Corrupt PNG"); - break; - } + // check filter type + if (filter > 4) { + all_ok = stbi__err("invalid filter", "Corrupt PNG"); + break; + } - // if first row, use special filter that doesn't sample previous row - if (j == 0) filter = first_row_filter[filter]; + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; - // perform actual filtering - switch (filter) { - case STBI__F_none: - memcpy(cur, raw, nk); - break; - case STBI__F_sub: - memcpy(cur, raw, filter_bytes); - for (k = filter_bytes; k < nk; ++k) - cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); - break; - case STBI__F_up: - for (k = 0; k < nk; ++k) - cur[k] = STBI__BYTECAST(raw[k] + prior[k]); - break; - case STBI__F_avg: - for (k = 0; k < filter_bytes; ++k) - cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); - for (k = filter_bytes; k < nk; ++k) - cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); - break; - case STBI__F_paeth: - for (k = 0; k < filter_bytes; ++k) - cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) - for (k = filter_bytes; k < nk; ++k) - cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes])); - break; - case STBI__F_avg_first: - memcpy(cur, raw, filter_bytes); - for (k = filter_bytes; k < nk; ++k) - cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); - break; - } + // perform actual filtering + switch (filter) { + case STBI__F_none: + memcpy(cur, raw, nk); + break; + case STBI__F_sub: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]); + break; + case STBI__F_up: + for (k = 0; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); + break; + case STBI__F_avg: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1)); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST( + raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1)); + break; + case STBI__F_paeth: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST( + raw[k] + + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST( + raw[k] + stbi__paeth(cur[k - filter_bytes], prior[k], + prior[k - filter_bytes])); + break; + case STBI__F_avg_first: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = + STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1)); + break; + } - raw += nk; + raw += nk; - // expand decoded bits in cur to dest, also adding an extra alpha channel if desired - if (depth < 8) { - stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range - stbi_uc *in = cur; - stbi_uc *out = dest; - stbi_uc inb = 0; - stbi__uint32 nsmp = x*img_n; + // expand decoded bits in cur to dest, also adding an extra alpha + // channel if desired + if (depth < 8) { + stbi_uc scale = (color == 0) + ? stbi__depth_scale_table[depth] + : 1; // scale grayscale values to 0..255 range + stbi_uc* in = cur; + stbi_uc* out = dest; + stbi_uc inb = 0; + stbi__uint32 nsmp = x * img_n; - // expand bits to bytes first - if (depth == 4) { - for (i=0; i < nsmp; ++i) { - if ((i & 1) == 0) inb = *in++; - *out++ = scale * (inb >> 4); - inb <<= 4; - } - } else if (depth == 2) { - for (i=0; i < nsmp; ++i) { - if ((i & 3) == 0) inb = *in++; - *out++ = scale * (inb >> 6); - inb <<= 2; - } - } else { - STBI_ASSERT(depth == 1); - for (i=0; i < nsmp; ++i) { - if ((i & 7) == 0) inb = *in++; - *out++ = scale * (inb >> 7); - inb <<= 1; - } - } - - // insert alpha=255 values if desired - if (img_n != out_n) - stbi__create_png_alpha_expand8(dest, dest, x, img_n); - } else if (depth == 8) { - if (img_n == out_n) - memcpy(dest, cur, x*img_n); - else - stbi__create_png_alpha_expand8(dest, cur, x, img_n); - } else if (depth == 16) { - // convert the image data from big-endian to platform-native - stbi__uint16 *dest16 = (stbi__uint16*)dest; - stbi__uint32 nsmp = x*img_n; - - if (img_n == out_n) { - for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) - *dest16 = (cur[0] << 8) | cur[1]; - } else { - STBI_ASSERT(img_n+1 == out_n); - if (img_n == 1) { - for (i = 0; i < x; ++i, dest16 += 2, cur += 2) { - dest16[0] = (cur[0] << 8) | cur[1]; - dest16[1] = 0xffff; - } + // expand bits to bytes first + if (depth == 4) { + for (i = 0; i < nsmp; ++i) { + if ((i & 1) == 0) inb = *in++; + *out++ = scale * (inb >> 4); + inb <<= 4; + } + } else if (depth == 2) { + for (i = 0; i < nsmp; ++i) { + if ((i & 3) == 0) inb = *in++; + *out++ = scale * (inb >> 6); + inb <<= 2; + } } else { - STBI_ASSERT(img_n == 3); - for (i = 0; i < x; ++i, dest16 += 4, cur += 6) { - dest16[0] = (cur[0] << 8) | cur[1]; - dest16[1] = (cur[2] << 8) | cur[3]; - dest16[2] = (cur[4] << 8) | cur[5]; - dest16[3] = 0xffff; - } + STBI_ASSERT(depth == 1); + for (i = 0; i < nsmp; ++i) { + if ((i & 7) == 0) inb = *in++; + *out++ = scale * (inb >> 7); + inb <<= 1; + } } - } - } - } - STBI_FREE(filter_buf); - if (!all_ok) return 0; + // insert alpha=255 values if desired + if (img_n != out_n) + stbi__create_png_alpha_expand8(dest, dest, x, img_n); + } else if (depth == 8) { + if (img_n == out_n) + memcpy(dest, cur, x * img_n); + else + stbi__create_png_alpha_expand8(dest, cur, x, img_n); + } else if (depth == 16) { + // convert the image data from big-endian to platform-native + stbi__uint16* dest16 = (stbi__uint16*)dest; + stbi__uint32 nsmp = x * img_n; - return 1; -} - -static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) -{ - int bytes = (depth == 16 ? 2 : 1); - int out_bytes = out_n * bytes; - stbi_uc *final; - int p; - if (!interlaced) - return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); - - // de-interlacing - final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); - if (!final) return stbi__err("outofmem", "Out of memory"); - for (p=0; p < 7; ++p) { - int xorig[] = { 0,4,0,2,0,1,0 }; - int yorig[] = { 0,0,4,0,2,0,1 }; - int xspc[] = { 8,8,4,4,2,2,1 }; - int yspc[] = { 8,8,8,4,4,2,2 }; - int i,j,x,y; - // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 - x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; - y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; - if (x && y) { - stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; - if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { - STBI_FREE(final); - return 0; - } - for (j=0; j < y; ++j) { - for (i=0; i < x; ++i) { - int out_y = j*yspc[p]+yorig[p]; - int out_x = i*xspc[p]+xorig[p]; - memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, - a->out + (j*x+i)*out_bytes, out_bytes); + if (img_n == out_n) { + for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) + *dest16 = (cur[0] << 8) | cur[1]; + } else { + STBI_ASSERT(img_n + 1 == out_n); + if (img_n == 1) { + for (i = 0; i < x; ++i, dest16 += 2, cur += 2) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = 0xffff; + } + } else { + STBI_ASSERT(img_n == 3); + for (i = 0; i < x; ++i, dest16 += 4, cur += 6) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = (cur[2] << 8) | cur[3]; + dest16[2] = (cur[4] << 8) | cur[5]; + dest16[3] = 0xffff; + } + } } - } - STBI_FREE(a->out); - image_data += img_len; - image_data_len -= img_len; - } - } - a->out = final; + } + } - return 1; + STBI_FREE(filter_buf); + if (!all_ok) return 0; + + return 1; } -static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi_uc *p = z->out; +static int stbi__create_png_image(stbi__png* a, stbi_uc* image_data, + stbi__uint32 image_data_len, int out_n, + int depth, int color, int interlaced) { + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc* final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, + a->s->img_x, a->s->img_y, depth, + color); - // compute color-based transparency, assuming we've - // already got 255 as the alpha value in the output - STBI_ASSERT(out_n == 2 || out_n == 4); + // de-interlacing + final = (stbi_uc*)stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); + for (p = 0; p < 7; ++p) { + int xorig[] = {0, 4, 0, 2, 0, 1, 0}; + int yorig[] = {0, 0, 4, 0, 2, 0, 1}; + int xspc[] = {8, 8, 4, 4, 2, 2, 1}; + int yspc[] = {8, 8, 8, 4, 4, 2, 2}; + int i, j, x, y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = + ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, + out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j = 0; j < y; ++j) { + for (i = 0; i < x; ++i) { + int out_y = j * yspc[p] + yorig[p]; + int out_x = i * xspc[p] + xorig[p]; + memcpy(final + out_y * a->s->img_x * out_bytes + + out_x * out_bytes, + a->out + (j * x + i) * out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; - if (out_n == 2) { - for (i=0; i < pixel_count; ++i) { - p[1] = (p[0] == tc[0] ? 0 : 255); - p += 2; - } - } else { - for (i=0; i < pixel_count; ++i) { - if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) - p[3] = 0; - p += 4; - } - } - return 1; + return 1; } -static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi__uint16 *p = (stbi__uint16*) z->out; +static int stbi__compute_transparency(stbi__png* z, stbi_uc tc[3], int out_n) { + stbi__context* s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc* p = z->out; - // compute color-based transparency, assuming we've - // already got 65535 as the alpha value in the output - STBI_ASSERT(out_n == 2 || out_n == 4); + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); - if (out_n == 2) { - for (i = 0; i < pixel_count; ++i) { - p[1] = (p[0] == tc[0] ? 0 : 65535); - p += 2; - } - } else { - for (i = 0; i < pixel_count; ++i) { - if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) - p[3] = 0; - p += 4; - } - } - return 1; + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; + p += 4; + } + } + return 1; } -static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) -{ - stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; - stbi_uc *p, *temp_out, *orig = a->out; +static int stbi__compute_transparency16(stbi__png* z, stbi__uint16 tc[3], + int out_n) { + stbi__context* s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16* p = (stbi__uint16*)z->out; - p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); - if (p == NULL) return stbi__err("outofmem", "Out of memory"); + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); - // between here and free(out) below, exitting would leak - temp_out = p; + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; + p += 4; + } + } + return 1; +} - if (pal_img_n == 3) { - for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; - p[0] = palette[n ]; - p[1] = palette[n+1]; - p[2] = palette[n+2]; - p += 3; - } - } else { - for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; - p[0] = palette[n ]; - p[1] = palette[n+1]; - p[2] = palette[n+2]; - p[3] = palette[n+3]; - p += 4; - } - } - STBI_FREE(a->out); - a->out = temp_out; +static int stbi__expand_png_palette(stbi__png* a, stbi_uc* palette, int len, + int pal_img_n) { + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; - STBI_NOTUSED(len); + p = (stbi_uc*)stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); - return 1; + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i = 0; i < pixel_count; ++i) { + int n = orig[i] * 4; + p[0] = palette[n]; + p[1] = palette[n + 1]; + p[2] = palette[n + 2]; + p += 3; + } + } else { + for (i = 0; i < pixel_count; ++i) { + int n = orig[i] * 4; + p[0] = palette[n]; + p[1] = palette[n + 1]; + p[2] = palette[n + 2]; + p[3] = palette[n + 3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; } static int stbi__unpremultiply_on_load_global = 0; static int stbi__de_iphone_flag_global = 0; -STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) -{ - stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; +STBIDEF void stbi_set_unpremultiply_on_load( + int flag_true_if_should_unpremultiply) { + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; } -STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) -{ - stbi__de_iphone_flag_global = flag_true_if_should_convert; +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { + stbi__de_iphone_flag_global = flag_true_if_should_convert; } #ifndef STBI_THREAD_LOCAL -#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global -#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global #else -static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; -static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, + stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, + stbi__de_iphone_flag_set; -STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) -{ - stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; - stbi__unpremultiply_on_load_set = 1; +STBIDEF void stbi_set_unpremultiply_on_load_thread( + int flag_true_if_should_unpremultiply) { + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; } -STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) -{ - stbi__de_iphone_flag_local = flag_true_if_should_convert; - stbi__de_iphone_flag_set = 1; +STBIDEF void stbi_convert_iphone_png_to_rgb_thread( + int flag_true_if_should_convert) { + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; } -#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ - ? stbi__unpremultiply_on_load_local \ - : stbi__unpremultiply_on_load_global) -#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ - ? stbi__de_iphone_flag_local \ - : stbi__de_iphone_flag_global) -#endif // STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load \ + (stbi__unpremultiply_on_load_set ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag \ + (stbi__de_iphone_flag_set ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL -static void stbi__de_iphone(stbi__png *z) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi_uc *p = z->out; +static void stbi__de_iphone(stbi__png* z) { + stbi__context* s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc* p = z->out; - if (s->img_out_n == 3) { // convert bgr to rgb - for (i=0; i < pixel_count; ++i) { - stbi_uc t = p[0]; - p[0] = p[2]; - p[2] = t; - p += 3; - } - } else { - STBI_ASSERT(s->img_out_n == 4); - if (stbi__unpremultiply_on_load) { - // convert bgr to rgb and unpremultiply - for (i=0; i < pixel_count; ++i) { - stbi_uc a = p[3]; - stbi_uc t = p[0]; - if (a) { - stbi_uc half = a / 2; - p[0] = (p[2] * 255 + half) / a; - p[1] = (p[1] * 255 + half) / a; - p[2] = ( t * 255 + half) / a; - } else { - p[0] = p[2]; - p[2] = t; - } - p += 4; - } - } else { - // convert bgr to rgb - for (i=0; i < pixel_count; ++i) { + if (s->img_out_n == 3) { // convert bgr to rgb + for (i = 0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; - p += 4; - } - } - } + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i = 0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = (t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i = 0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } } -#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) +#define STBI__PNG_TYPE(a, b, c, d) \ + (((unsigned)(a) << 24) + ((unsigned)(b) << 16) + ((unsigned)(c) << 8) + \ + (unsigned)(d)) -static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) -{ - stbi_uc palette[1024], pal_img_n=0; - stbi_uc has_trans=0, tc[3]={0}; - stbi__uint16 tc16[3]; - stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; - int first=1,k,interlace=0, color=0, is_iphone=0; - stbi__context *s = z->s; +static int stbi__parse_png_file(stbi__png* z, int scan, int req_comp) { + stbi_uc palette[1024], pal_img_n = 0; + stbi_uc has_trans = 0, tc[3] = {0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff = 0, idata_limit = 0, i, pal_len = 0; + int first = 1, k, interlace = 0, color = 0, is_iphone = 0; + stbi__context* s = z->s; - z->expanded = NULL; - z->idata = NULL; - z->out = NULL; + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; - if (!stbi__check_png_header(s)) return 0; + if (!stbi__check_png_header(s)) return 0; - if (scan == STBI__SCAN_type) return 1; + if (scan == STBI__SCAN_type) return 1; - for (;;) { - stbi__pngchunk c = stbi__get_chunk_header(s); - switch (c.type) { - case STBI__PNG_TYPE('C','g','B','I'): - is_iphone = 1; - stbi__skip(s, c.length); - break; - case STBI__PNG_TYPE('I','H','D','R'): { - int comp,filter; - if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); - first = 0; - if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); - s->img_x = stbi__get32be(s); - s->img_y = stbi__get32be(s); - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); - color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); - if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); - if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); - comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); - filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); - interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); - if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); - if (!pal_img_n) { - s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); - if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); - } else { - // if paletted, then pal_n is our final components, and - // img_n is # components to decompress/filter. - s->img_n = 1; - if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C', 'g', 'B', 'I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I', 'H', 'D', 'R'): { + int comp, filter; + if (!first) return stbi__err("multiple IHDR", "Corrupt PNG"); + first = 0; + if (c.length != 13) + return stbi__err("bad IHDR len", "Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) + return stbi__err("too large", + "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) + return stbi__err("too large", + "Very large image (corrupt?)"); + z->depth = stbi__get8(s); + if (z->depth != 1 && z->depth != 2 && z->depth != 4 && + z->depth != 8 && z->depth != 16) + return stbi__err("1/2/4/8/16-bit only", + "PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); + if (color > 6) return stbi__err("bad ctype", "Corrupt PNG"); + if (color == 3 && z->depth == 16) + return stbi__err("bad ctype", "Corrupt PNG"); + if (color == 3) + pal_img_n = 3; + else if (color & 1) + return stbi__err("bad ctype", "Corrupt PNG"); + comp = stbi__get8(s); + if (comp) return stbi__err("bad comp method", "Corrupt PNG"); + filter = stbi__get8(s); + if (filter) + return stbi__err("bad filter method", "Corrupt PNG"); + interlace = stbi__get8(s); + if (interlace > 1) + return stbi__err("bad interlace method", "Corrupt PNG"); + if (!s->img_x || !s->img_y) + return stbi__err("0-pixel image", "Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) + return stbi__err("too large", + "Image too large to decode"); + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) + return stbi__err("too large", "Corrupt PNG"); + } + // even with SCAN_header, have to scan to see if we have a tRNS + break; } - // even with SCAN_header, have to scan to see if we have a tRNS - break; - } - case STBI__PNG_TYPE('P','L','T','E'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); - pal_len = c.length / 3; - if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); - for (i=0; i < pal_len; ++i) { - palette[i*4+0] = stbi__get8(s); - palette[i*4+1] = stbi__get8(s); - palette[i*4+2] = stbi__get8(s); - palette[i*4+3] = 255; + case STBI__PNG_TYPE('P', 'L', 'T', 'E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256 * 3) + return stbi__err("invalid PLTE", "Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) + return stbi__err("invalid PLTE", "Corrupt PNG"); + for (i = 0; i < pal_len; ++i) { + palette[i * 4 + 0] = stbi__get8(s); + palette[i * 4 + 1] = stbi__get8(s); + palette[i * 4 + 2] = stbi__get8(s); + palette[i * 4 + 3] = 255; + } + break; } - break; - } - case STBI__PNG_TYPE('t','R','N','S'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); - if (pal_img_n) { - if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } - if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); - if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); - pal_img_n = 4; - for (i=0; i < c.length; ++i) - palette[i*4+3] = stbi__get8(s); - } else { - if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); - if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); - has_trans = 1; - // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. - if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } - if (z->depth == 16) { - for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning - tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is - } else { - for (k = 0; k < s->img_n && k < 3; ++k) - tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger - } + case STBI__PNG_TYPE('t', 'R', 'N', 'S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) + return stbi__err("tRNS after IDAT", "Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { + s->img_n = 4; + return 1; + } + if (pal_len == 0) + return stbi__err("tRNS before PLTE", "Corrupt PNG"); + if (c.length > pal_len) + return stbi__err("bad tRNS len", "Corrupt PNG"); + pal_img_n = 4; + for (i = 0; i < c.length; ++i) + palette[i * 4 + 3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) + return stbi__err("tRNS with alpha", "Corrupt PNG"); + if (c.length != (stbi__uint32)s->img_n * 2) + return stbi__err("bad tRNS len", "Corrupt PNG"); + has_trans = 1; + // non-paletted with tRNS = constant alpha. if + // header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { + ++s->img_n; + return 1; + } + if (z->depth == 16) { + for (k = 0; k < s->img_n && k < 3; + ++k) // extra loop test to suppress false GCC + // warning + tc16[k] = (stbi__uint16)stbi__get16be( + s); // copy the values as-is + } else { + for (k = 0; k < s->img_n && k < 3; ++k) + tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * + stbi__depth_scale_table + [z->depth]; // non 8-bit images will be + // larger + } + } + break; } - break; - } - case STBI__PNG_TYPE('I','D','A','T'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); - if (scan == STBI__SCAN_header) { - // header scan definitely stops at first IDAT - if (pal_img_n) - s->img_n = pal_img_n; - return 1; + case STBI__PNG_TYPE('I', 'D', 'A', 'T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) + return stbi__err("no PLTE", "Corrupt PNG"); + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) + return stbi__err("IDAT size limit", + "IDAT section larger than 2^30 bytes"); + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc* p; + if (idata_limit == 0) + idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc*)STBI_REALLOC_SIZED(z->idata, idata_limit_old, + idata_limit); + if (p == NULL) + return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata + ioff, c.length)) + return stbi__err("outofdata", "Corrupt PNG"); + ioff += c.length; + break; } - if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); - if ((int)(ioff + c.length) < (int)ioff) return 0; - if (ioff + c.length > idata_limit) { - stbi__uint32 idata_limit_old = idata_limit; - stbi_uc *p; - if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; - while (ioff + c.length > idata_limit) - idata_limit *= 2; - STBI_NOTUSED(idata_limit_old); - p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); - z->idata = p; - } - if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); - ioff += c.length; - break; - } - case STBI__PNG_TYPE('I','E','N','D'): { - stbi__uint32 raw_len, bpl; - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (scan != STBI__SCAN_load) return 1; - if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); - // initial guess for decoded data size to avoid unnecessary reallocs - bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component - raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; - z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); - if (z->expanded == NULL) return 0; // zlib should set error - STBI_FREE(z->idata); z->idata = NULL; - if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) - s->img_out_n = s->img_n+1; + case STBI__PNG_TYPE('I', 'E', 'N', 'D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) + return stbi__err("no IDAT", "Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary + // reallocs + bpl = (s->img_x * z->depth + 7) / + 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + + s->img_y /* filter mode per row */; + z->expanded = + (stbi_uc*)stbi_zlib_decode_malloc_guesssize_headerflag( + (char*)z->idata, ioff, raw_len, (int*)&raw_len, + !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); + z->idata = NULL; + if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || + has_trans) + s->img_out_n = s->img_n + 1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, + s->img_out_n, z->depth, color, + interlace)) + return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, + s->img_out_n)) + return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) + return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, + s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has + // (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); + z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { +#ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); +#endif + return stbi__err( + invalid_chunk, + "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void* stbi__do_png(stbi__png* p, int* x, int* y, int* n, int req_comp, + stbi__result_info* ri) { + void* result = NULL; + if (req_comp < 0 || req_comp > 4) + return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", + "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char*)result, + p->s->img_out_n, req_comp, + p->s->img_x, p->s->img_y); else - s->img_out_n = s->img_n; - if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; - if (has_trans) { - if (z->depth == 16) { - if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; - } else { - if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; - } - } - if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) - stbi__de_iphone(z); - if (pal_img_n) { - // pal_img_n == 3 or 4 - s->img_n = pal_img_n; // record the actual colors we had - s->img_out_n = pal_img_n; - if (req_comp >= 3) s->img_out_n = req_comp; - if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) - return 0; - } else if (has_trans) { - // non-paletted image with tRNS -> source image has (constant) alpha - ++s->img_n; - } - STBI_FREE(z->expanded); z->expanded = NULL; - // end of PNG chunk, read and skip CRC - stbi__get32be(s); - return 1; - } + result = stbi__convert_format16((stbi__uint16*)result, + p->s->img_out_n, req_comp, + p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); + p->out = NULL; + STBI_FREE(p->expanded); + p->expanded = NULL; + STBI_FREE(p->idata); + p->idata = NULL; - default: - // if critical, fail - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if ((c.type & (1 << 29)) == 0) { - #ifndef STBI_NO_FAILURE_STRINGS - // not threadsafe - static char invalid_chunk[] = "XXXX PNG chunk not known"; - invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); - invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); - invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); - invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); - #endif - return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); - } - stbi__skip(s, c.length); - break; - } - // end of PNG chunk, read and skip CRC - stbi__get32be(s); - } + return result; } -static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) -{ - void *result=NULL; - if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); - if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { - if (p->depth <= 8) - ri->bits_per_channel = 8; - else if (p->depth == 16) - ri->bits_per_channel = 16; - else - return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); - result = p->out; - p->out = NULL; - if (req_comp && req_comp != p->s->img_out_n) { - if (ri->bits_per_channel == 8) - result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); - else - result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); - p->s->img_out_n = req_comp; - if (result == NULL) return result; - } - *x = p->s->img_x; - *y = p->s->img_y; - if (n) *n = p->s->img_n; - } - STBI_FREE(p->out); p->out = NULL; - STBI_FREE(p->expanded); p->expanded = NULL; - STBI_FREE(p->idata); p->idata = NULL; - - return result; +static void* stbi__png_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri) { + stbi__png p; + p.s = s; + return stbi__do_png(&p, x, y, comp, req_comp, ri); } -static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi__png p; - p.s = s; - return stbi__do_png(&p, x,y,comp,req_comp, ri); +static int stbi__png_test(stbi__context* s) { + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; } -static int stbi__png_test(stbi__context *s) -{ - int r; - r = stbi__check_png_header(s); - stbi__rewind(s); - return r; +static int stbi__png_info_raw(stbi__png* p, int* x, int* y, int* comp) { + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind(p->s); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; } -static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) -{ - if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { - stbi__rewind( p->s ); - return 0; - } - if (x) *x = p->s->img_x; - if (y) *y = p->s->img_y; - if (comp) *comp = p->s->img_n; - return 1; +static int stbi__png_info(stbi__context* s, int* x, int* y, int* comp) { + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); } -static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) -{ - stbi__png p; - p.s = s; - return stbi__png_info_raw(&p, x, y, comp); -} - -static int stbi__png_is16(stbi__context *s) -{ - stbi__png p; - p.s = s; - if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) - return 0; - if (p.depth != 16) { - stbi__rewind(p.s); - return 0; - } - return 1; +static int stbi__png_is16(stbi__context* s) { + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; } #endif // Microsoft/Windows BMP image #ifndef STBI_NO_BMP -static int stbi__bmp_test_raw(stbi__context *s) -{ - int r; - int sz; - if (stbi__get8(s) != 'B') return 0; - if (stbi__get8(s) != 'M') return 0; - stbi__get32le(s); // discard filesize - stbi__get16le(s); // discard reserved - stbi__get16le(s); // discard reserved - stbi__get32le(s); // discard data offset - sz = stbi__get32le(s); - r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); - return r; +static int stbi__bmp_test_raw(stbi__context* s) { + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; } -static int stbi__bmp_test(stbi__context *s) -{ - int r = stbi__bmp_test_raw(s); - stbi__rewind(s); - return r; +static int stbi__bmp_test(stbi__context* s) { + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; } - // returns 0..31 for the highest set bit -static int stbi__high_bit(unsigned int z) -{ - int n=0; - if (z == 0) return -1; - if (z >= 0x10000) { n += 16; z >>= 16; } - if (z >= 0x00100) { n += 8; z >>= 8; } - if (z >= 0x00010) { n += 4; z >>= 4; } - if (z >= 0x00004) { n += 2; z >>= 2; } - if (z >= 0x00002) { n += 1;/* >>= 1;*/ } - return n; +static int stbi__high_bit(unsigned int z) { + int n = 0; + if (z == 0) return -1; + if (z >= 0x10000) { + n += 16; + z >>= 16; + } + if (z >= 0x00100) { + n += 8; + z >>= 8; + } + if (z >= 0x00010) { + n += 4; + z >>= 4; + } + if (z >= 0x00004) { + n += 2; + z >>= 2; + } + if (z >= 0x00002) { + n += 1; /* >>= 1;*/ + } + return n; } -static int stbi__bitcount(unsigned int a) -{ - a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 - a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 - a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits - a = (a + (a >> 8)); // max 16 per 8 bits - a = (a + (a >> 16)); // max 32 per 8 bits - return a & 0xff; +static int stbi__bitcount(unsigned int a) { + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; } // extract an arbitrarily-aligned N-bit value (N=bits) // from v, and then make it 8-bits long and fractionally // extend it to full full range. -static int stbi__shiftsigned(unsigned int v, int shift, int bits) -{ - static unsigned int mul_table[9] = { - 0, - 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, - 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, - }; - static unsigned int shift_table[9] = { - 0, 0,0,1,0,2,4,6,0, - }; - if (shift < 0) - v <<= -shift; - else - v >>= shift; - STBI_ASSERT(v < 256); - v >>= (8-bits); - STBI_ASSERT(bits >= 0 && bits <= 8); - return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +static int stbi__shiftsigned(unsigned int v, int shift, int bits) { + static unsigned int mul_table[9] = { + 0, + 0xff /*0b11111111*/, + 0x55 /*0b01010101*/, + 0x49 /*0b01001001*/, + 0x11 /*0b00010001*/, + 0x21 /*0b00100001*/, + 0x41 /*0b01000001*/, + 0x81 /*0b10000001*/, + 0x01 /*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0, 0, 1, 0, 2, 4, 6, 0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8 - bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int)((unsigned)v * mul_table[bits]) >> shift_table[bits]; } -typedef struct -{ - int bpp, offset, hsz; - unsigned int mr,mg,mb,ma, all_a; - int extra_read; +typedef struct { + int bpp, offset, hsz; + unsigned int mr, mg, mb, ma, all_a; + int extra_read; } stbi__bmp_data; -static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) -{ - // BI_BITFIELDS specifies masks explicitly, don't override - if (compress == 3) - return 1; +static int stbi__bmp_set_mask_defaults(stbi__bmp_data* info, int compress) { + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) return 1; - if (compress == 0) { - if (info->bpp == 16) { - info->mr = 31u << 10; - info->mg = 31u << 5; - info->mb = 31u << 0; - } else if (info->bpp == 32) { - info->mr = 0xffu << 16; - info->mg = 0xffu << 8; - info->mb = 0xffu << 0; - info->ma = 0xffu << 24; - info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 - } else { - // otherwise, use defaults, which is all-0 - info->mr = info->mg = info->mb = info->ma = 0; - } - return 1; - } - return 0; // error + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha + // channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error } -static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) -{ - int hsz; - if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); - stbi__get32le(s); // discard filesize - stbi__get16le(s); // discard reserved - stbi__get16le(s); // discard reserved - info->offset = stbi__get32le(s); - info->hsz = hsz = stbi__get32le(s); - info->mr = info->mg = info->mb = info->ma = 0; - info->extra_read = 14; +static void* stbi__bmp_parse_header(stbi__context* s, stbi__bmp_data* info) { + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') + return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; - if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); - if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); - if (hsz == 12) { - s->img_x = stbi__get16le(s); - s->img_y = stbi__get16le(s); - } else { - s->img_x = stbi__get32le(s); - s->img_y = stbi__get32le(s); - } - if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); - info->bpp = stbi__get16le(s); - if (hsz != 12) { - int compress = stbi__get32le(s); - if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); - if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes - if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel - stbi__get32le(s); // discard sizeof - stbi__get32le(s); // discard hres - stbi__get32le(s); // discard vres - stbi__get32le(s); // discard colorsused - stbi__get32le(s); // discard max important - if (hsz == 40 || hsz == 56) { - if (hsz == 56) { - stbi__get32le(s); - stbi__get32le(s); - stbi__get32le(s); - stbi__get32le(s); - } - if (info->bpp == 16 || info->bpp == 32) { - if (compress == 0) { - stbi__bmp_set_mask_defaults(info, compress); - } else if (compress == 3) { - info->mr = stbi__get32le(s); - info->mg = stbi__get32le(s); - info->mb = stbi__get32le(s); - info->extra_read += 12; - // not documented, but generated by photoshop and handled by mspaint - if (info->mr == info->mg && info->mg == info->mb) { - // ?!?!? - return stbi__errpuc("bad BMP", "bad BMP"); - } - } else - return stbi__errpuc("bad BMP", "bad BMP"); - } - } else { - // V4/V5 header - int i; - if (hsz != 108 && hsz != 124) - return stbi__errpuc("bad BMP", "bad BMP"); - info->mr = stbi__get32le(s); - info->mg = stbi__get32le(s); - info->mb = stbi__get32le(s); - info->ma = stbi__get32le(s); - if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs - stbi__bmp_set_mask_defaults(info, compress); - stbi__get32le(s); // discard color space - for (i=0; i < 12; ++i) - stbi__get32le(s); // discard color space parameters - if (hsz == 124) { - stbi__get32le(s); // discard rendering intent - stbi__get32le(s); // discard offset of profile data - stbi__get32le(s); // discard size of profile data - stbi__get32le(s); // discard reserved - } - } - } - return (void *) 1; + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) + return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) + return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) + return stbi__errpuc( + "BMP JPEG/PNG", + "BMP type not supported: unsupported compression"); // this + // includes + // PNG/JPEG + // modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) + return stbi__errpuc( + "bad BMP", + "bad BMP"); // bitfields requires 16 or 32 bits/pixel + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + stbi__bmp_set_mask_defaults(info, compress); + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by + // mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS + // mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); + stbi__get32le(s); // discard color space + for (i = 0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void*)1; } +static void* stbi__bmp_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri) { + stbi_uc* out; + unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a; + stbi_uc pal[256][4]; + int psize = 0, i, j, width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); -static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *out; - unsigned int mr=0,mg=0,mb=0,ma=0, all_a; - stbi_uc pal[256][4]; - int psize=0,i,j,width; - int flip_vertically, pad, target; - stbi__bmp_data info; - STBI_NOTUSED(ri); + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set - info.all_a = 255; - if (stbi__bmp_parse_header(s, &info) == NULL) - return NULL; // error code already set + flip_vertically = ((int)s->img_y) > 0; + s->img_y = abs((int)s->img_y); - flip_vertically = ((int) s->img_y) > 0; - s->img_y = abs((int) s->img_y); + if (s->img_y > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; - mr = info.mr; - mg = info.mg; - mb = info.mb; - ma = info.ma; - all_a = info.all_a; + if (info.hsz == 12) { + if (info.bpp < 24) psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset + // points either to before the header ends or implies a large amount of + // extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = + 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = + 256 * 4; // what ordinarily goes here is a palette; 256 entries*4 + // bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small + // positives, or negative, and guarantees that info.offset >= + // bytes_read_so_far > 0. this in turn ensures the number computed in + // the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || + info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } - if (info.hsz == 12) { - if (info.bpp < 24) - psize = (info.offset - info.extra_read - 24) / 3; - } else { - if (info.bpp < 16) - psize = (info.offset - info.extra_read - info.hsz) >> 2; - } - if (psize == 0) { - // accept some number of extra bytes after the header, but if the offset points either to before - // the header ends or implies a large amount of extra data, reject the file as malformed - int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); - int header_limit = 1024; // max we actually read is below 256 bytes currently. - int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. - if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { - return stbi__errpuc("bad header", "Corrupt BMP"); - } - // we established that bytes_read_so_far is positive and sensible. - // the first half of this test rejects offsets that are either too small positives, or - // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn - // ensures the number computed in the second half of the test can't overflow. - if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { - return stbi__errpuc("bad offset", "Corrupt BMP"); - } else { - stbi__skip(s, info.offset - bytes_read_so_far); - } - } + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert - if (info.bpp == 24 && ma == 0xff000000) - s->img_n = 3; - else - s->img_n = ma ? 4 : 3; - if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 - target = req_comp; - else - target = s->img_n; // if they want monochrome, we'll post-convert + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); - // sanity-check size - if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) - return stbi__errpuc("too large", "Corrupt BMP"); - - out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (info.bpp < 16) { - int z=0; - if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } - for (i=0; i < psize; ++i) { - pal[i][2] = stbi__get8(s); - pal[i][1] = stbi__get8(s); - pal[i][0] = stbi__get8(s); - if (info.hsz != 12) stbi__get8(s); - pal[i][3] = 255; - } - stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); - if (info.bpp == 1) width = (s->img_x + 7) >> 3; - else if (info.bpp == 4) width = (s->img_x + 1) >> 1; - else if (info.bpp == 8) width = s->img_x; - else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } - pad = (-width)&3; - if (info.bpp == 1) { - for (j=0; j < (int) s->img_y; ++j) { - int bit_offset = 7, v = stbi__get8(s); - for (i=0; i < (int) s->img_x; ++i) { - int color = (v>>bit_offset)&0x1; - out[z++] = pal[color][0]; - out[z++] = pal[color][1]; - out[z++] = pal[color][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - if((--bit_offset) < 0) { - bit_offset = 7; - v = stbi__get8(s); - } + out = (stbi_uc*)stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z = 0; + if (psize == 0 || psize > 256) { + STBI_FREE(out); + return stbi__errpuc("invalid", "Corrupt BMP"); + } + for (i = 0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - + psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) + width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) + width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) + width = s->img_x; + else { + STBI_FREE(out); + return stbi__errpuc("bad bpp", "Corrupt BMP"); + } + pad = (-width) & 3; + if (info.bpp == 1) { + for (j = 0; j < (int)s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i = 0; i < (int)s->img_x; ++i) { + int color = (v >> bit_offset) & 0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i + 1 == (int)s->img_x) break; + if ((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j = 0; j < (int)s->img_y; ++j) { + for (i = 0; i < (int)s->img_x; i += 2) { + int v = stbi__get8(s), v2 = 0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i + 1 == (int)s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, + gcount = 0, bcount = 0, acount = 0; + int z = 0; + int easy = 0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) + width = 3 * s->img_x; + else if (info.bpp == 16) + width = 2 * s->img_x; + else /* bpp = 32 and pad = 0 */ + width = 0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && + ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { + STBI_FREE(out); + return stbi__errpuc("bad masks", "Corrupt BMP"); + } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr) - 7; + rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg) - 7; + gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb) - 7; + bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma) - 7; + acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { + STBI_FREE(out); + return stbi__errpuc("bad masks", "Corrupt BMP"); + } + } + for (j = 0; j < (int)s->img_y; ++j) { + if (easy) { + for (i = 0; i < (int)s->img_x; ++i) { + unsigned char a; + out[z + 2] = stbi__get8(s); + out[z + 1] = stbi__get8(s); + out[z + 0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i = 0; i < (int)s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32)stbi__get16le(s) + : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST( + stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST( + stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST( + stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } } stbi__skip(s, pad); - } - } else { - for (j=0; j < (int) s->img_y; ++j) { - for (i=0; i < (int) s->img_x; i += 2) { - int v=stbi__get8(s),v2=0; - if (info.bpp == 4) { - v2 = v & 15; - v >>= 4; - } - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - v = (info.bpp == 8) ? stbi__get8(s) : v2; - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i = 4 * s->img_x * s->img_y - 1; i >= 0; i -= 4) out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j = 0; j < (int)s->img_y >> 1; ++j) { + stbi_uc* p1 = out + j * s->img_x * target; + stbi_uc* p2 = out + (s->img_y - 1 - j) * s->img_x * target; + for (i = 0; i < (int)s->img_x * target; ++i) { + t = p1[i]; + p1[i] = p2[i]; + p2[i] = t; } - stbi__skip(s, pad); - } - } - } else { - int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; - int z = 0; - int easy=0; - stbi__skip(s, info.offset - info.extra_read - info.hsz); - if (info.bpp == 24) width = 3 * s->img_x; - else if (info.bpp == 16) width = 2*s->img_x; - else /* bpp = 32 and pad = 0 */ width=0; - pad = (-width) & 3; - if (info.bpp == 24) { - easy = 1; - } else if (info.bpp == 32) { - if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) - easy = 2; - } - if (!easy) { - if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } - // right shift amt to put high bit in position #7 - rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); - gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); - bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); - ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); - if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } - } - for (j=0; j < (int) s->img_y; ++j) { - if (easy) { - for (i=0; i < (int) s->img_x; ++i) { - unsigned char a; - out[z+2] = stbi__get8(s); - out[z+1] = stbi__get8(s); - out[z+0] = stbi__get8(s); - z += 3; - a = (easy == 2 ? stbi__get8(s) : 255); - all_a |= a; - if (target == 4) out[z++] = a; - } - } else { - int bpp = info.bpp; - for (i=0; i < (int) s->img_x; ++i) { - stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); - unsigned int a; - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); - a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); - all_a |= a; - if (target == 4) out[z++] = STBI__BYTECAST(a); - } - } - stbi__skip(s, pad); - } - } + } + } - // if alpha channel is all 0s, replace with all 255s - if (target == 4 && all_a == 0) - for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) - out[i] = 255; + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) + return out; // stbi__convert_format frees input on failure + } - if (flip_vertically) { - stbi_uc t; - for (j=0; j < (int) s->img_y>>1; ++j) { - stbi_uc *p1 = out + j *s->img_x*target; - stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; - for (i=0; i < (int) s->img_x*target; ++i) { - t = p1[i]; p1[i] = p2[i]; p2[i] = t; - } - } - } - - if (req_comp && req_comp != target) { - out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - - *x = s->img_x; - *y = s->img_y; - if (comp) *comp = s->img_n; - return out; + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; } #endif @@ -5736,592 +6301,612 @@ static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req // by Jonathan Dummer #ifndef STBI_NO_TGA // returns STBI_rgb or whatever, 0 on error -static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) -{ - // only RGB or RGBA (incl. 16bit) or grey allowed - if (is_rgb16) *is_rgb16 = 0; - switch(bits_per_pixel) { - case 8: return STBI_grey; - case 16: if(is_grey) return STBI_grey_alpha; - // fallthrough - case 15: if(is_rgb16) *is_rgb16 = 1; - return STBI_rgb; - case 24: // fallthrough - case 32: return bits_per_pixel/8; - default: return 0; - } +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) { + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch (bits_per_pixel) { + case 8: + return STBI_grey; + case 16: + if (is_grey) return STBI_grey_alpha; + // fallthrough + case 15: + if (is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: + return bits_per_pixel / 8; + default: + return 0; + } } -static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) -{ - int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; +static int stbi__tga_info(stbi__context* s, int* x, int* y, int* comp) { + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, + tga_colormap_bpp; int sz, tga_colormap_type; - stbi__get8(s); // discard Offset - tga_colormap_type = stbi__get8(s); // colormap type - if( tga_colormap_type > 1 ) { + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if (tga_colormap_type > 1) { stbi__rewind(s); - return 0; // only RGB or indexed allowed + return 0; // only RGB or indexed allowed } - tga_image_type = stbi__get8(s); // image type - if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + tga_image_type = stbi__get8(s); // image type + if (tga_colormap_type == 1) { // colormapped (paletted) image if (tga_image_type != 1 && tga_image_type != 9) { stbi__rewind(s); return 0; } - stbi__skip(s,4); // skip index of first colormap entry and number of entries - sz = stbi__get8(s); // check bits per palette color entry - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__skip( + s, 4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) { stbi__rewind(s); return 0; } - stbi__skip(s,4); // skip image x and y origin + stbi__skip(s, 4); // skip image x and y origin tga_colormap_bpp = sz; - } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE - if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ((tga_image_type != 2) && (tga_image_type != 3) && + (tga_image_type != 10) && (tga_image_type != 11)) { stbi__rewind(s); - return 0; // only RGB or grey allowed, +/- RLE + return 0; // only RGB or grey allowed, +/- RLE } - stbi__skip(s,9); // skip colormap specification and image x/y origin + stbi__skip(s, 9); // skip colormap specification and image x/y origin tga_colormap_bpp = 0; } tga_w = stbi__get16le(s); - if( tga_w < 1 ) { + if (tga_w < 1) { stbi__rewind(s); - return 0; // test width + return 0; // test width } tga_h = stbi__get16le(s); - if( tga_h < 1 ) { + if (tga_h < 1) { stbi__rewind(s); - return 0; // test height + return 0; // test height } - tga_bits_per_pixel = stbi__get8(s); // bits per pixel - stbi__get8(s); // ignore alpha bits + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits if (tga_colormap_bpp != 0) { - if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { - // when using a colormap, tga_bits_per_pixel is the size of the indexes - // I don't think anything but 8 or 16bit indexes makes sense + if ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the + // indexes I don't think anything but 8 or 16bit indexes makes sense stbi__rewind(s); return 0; } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { - tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + tga_comp = stbi__tga_get_comp( + tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), + NULL); } - if(!tga_comp) { - stbi__rewind(s); - return 0; + if (!tga_comp) { + stbi__rewind(s); + return 0; } if (x) *x = tga_w; if (y) *y = tga_h; if (comp) *comp = tga_comp; - return 1; // seems to have passed everything + return 1; // seems to have passed everything } -static int stbi__tga_test(stbi__context *s) -{ - int res = 0; - int sz, tga_color_type; - stbi__get8(s); // discard Offset - tga_color_type = stbi__get8(s); // color type - if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed - sz = stbi__get8(s); // image type - if ( tga_color_type == 1 ) { // colormapped (paletted) image - if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 - stbi__skip(s,4); // skip index of first colormap entry and number of entries - sz = stbi__get8(s); // check bits per palette color entry - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; - stbi__skip(s,4); // skip image x and y origin - } else { // "normal" image w/o colormap - if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE - stbi__skip(s,9); // skip colormap specification and image x/y origin - } - if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width - if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height - sz = stbi__get8(s); // bits per pixel - if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; +static int stbi__tga_test(stbi__context* s) { + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if (tga_color_type > 1) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if (tga_color_type == 1) { // colormapped (paletted) image + if (sz != 1 && sz != 9) + goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip( + s, 4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) + goto errorEnd; + stbi__skip(s, 4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ((sz != 2) && (sz != 3) && (sz != 10) && (sz != 11)) + goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s, 9); // skip colormap specification and image x/y origin + } + if (stbi__get16le(s) < 1) goto errorEnd; // test width + if (stbi__get16le(s) < 1) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ((tga_color_type == 1) && (sz != 8) && (sz != 16)) + goto errorEnd; // for colormapped images, bpp is size of an index + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) + goto errorEnd; - res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + res = 1; // if we got this far, everything's good and we can return 1 + // instead of 0 errorEnd: - stbi__rewind(s); - return res; + stbi__rewind(s); + return res; } // read 16bit value and convert to 24bit RGB -static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) -{ - stbi__uint16 px = (stbi__uint16)stbi__get16le(s); - stbi__uint16 fiveBitMask = 31; - // we have 3 channels with 5bits each - int r = (px >> 10) & fiveBitMask; - int g = (px >> 5) & fiveBitMask; - int b = px & fiveBitMask; - // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later - out[0] = (stbi_uc)((r * 255)/31); - out[1] = (stbi_uc)((g * 255)/31); - out[2] = (stbi_uc)((b * 255)/31); +static void stbi__tga_read_rgb16(stbi__context* s, stbi_uc* out) { + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be + // swapped later + out[0] = (stbi_uc)((r * 255) / 31); + out[1] = (stbi_uc)((g * 255) / 31); + out[2] = (stbi_uc)((b * 255) / 31); - // some people claim that the most significant bit might be used for alpha - // (possibly if an alpha-bit is set in the "image descriptor byte") - // but that only made 16bit test images completely translucent.. - // so let's treat all 15 and 16bit TGAs as RGB with no alpha. + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } -static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - // read in the TGA header stuff - int tga_offset = stbi__get8(s); - int tga_indexed = stbi__get8(s); - int tga_image_type = stbi__get8(s); - int tga_is_RLE = 0; - int tga_palette_start = stbi__get16le(s); - int tga_palette_len = stbi__get16le(s); - int tga_palette_bits = stbi__get8(s); - int tga_x_origin = stbi__get16le(s); - int tga_y_origin = stbi__get16le(s); - int tga_width = stbi__get16le(s); - int tga_height = stbi__get16le(s); - int tga_bits_per_pixel = stbi__get8(s); - int tga_comp, tga_rgb16=0; - int tga_inverted = stbi__get8(s); - // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) - // image data - unsigned char *tga_data; - unsigned char *tga_palette = NULL; - int i, j; - unsigned char raw_data[4] = {0}; - int RLE_count = 0; - int RLE_repeating = 0; - int read_next_pixel = 1; - STBI_NOTUSED(ri); - STBI_NOTUSED(tga_x_origin); // @TODO - STBI_NOTUSED(tga_y_origin); // @TODO +static void* stbi__tga_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri) { + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16 = 0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused + // (useless?) + // image data + unsigned char* tga_data; + unsigned char* tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO - if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_height > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); - // do a tiny bit of precessing - if ( tga_image_type >= 8 ) - { - tga_image_type -= 8; - tga_is_RLE = 1; - } - tga_inverted = 1 - ((tga_inverted >> 5) & 1); + // do a tiny bit of precessing + if (tga_image_type >= 8) { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); - // If I'm paletted, then I'll use the number of bits from the palette - if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); - else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + // If I'm paletted, then I'll use the number of bits from the palette + if (tga_indexed) + tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), + &tga_rgb16); - if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency - return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + if (!tga_comp) // shouldn't really happen, stbi__tga_test() should have + // ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); - // tga info - *x = tga_width; - *y = tga_height; - if (comp) *comp = tga_comp; + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; - if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) - return stbi__errpuc("too large", "Corrupt TGA"); + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); - tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); - if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + tga_data = + (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); - // skip to the data's starting position (offset usually = 0) - stbi__skip(s, tga_offset ); + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset); - if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { - for (i=0; i < tga_height; ++i) { - int row = tga_inverted ? tga_height -i - 1 : i; - stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; - stbi__getn(s, tga_row, tga_width * tga_comp); - } - } else { - // do I need to load a palette? - if ( tga_indexed) - { - if (tga_palette_len == 0) { /* you have to have at least one entry! */ - STBI_FREE(tga_data); - return stbi__errpuc("bad palette", "Corrupt TGA"); - } - - // any data to skip? (offset usually = 0) - stbi__skip(s, tga_palette_start ); - // load the palette - tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); - if (!tga_palette) { - STBI_FREE(tga_data); - return stbi__errpuc("outofmem", "Out of memory"); - } - if (tga_rgb16) { - stbi_uc *pal_entry = tga_palette; - STBI_ASSERT(tga_comp == STBI_rgb); - for (i=0; i < tga_palette_len; ++i) { - stbi__tga_read_rgb16(s, pal_entry); - pal_entry += tga_comp; + if (!tga_indexed && !tga_is_RLE && !tga_rgb16) { + for (i = 0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height - i - 1 : i; + stbi_uc* tga_row = tga_data + row * tga_width * tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if (tga_indexed) { + if (tga_palette_len == + 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); } - } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { - STBI_FREE(tga_data); - STBI_FREE(tga_palette); - return stbi__errpuc("bad palette", "Corrupt TGA"); - } - } - // load the data - for (i=0; i < tga_width * tga_height; ++i) - { - // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? - if ( tga_is_RLE ) - { - if ( RLE_count == 0 ) - { - // yep, get the next byte as a RLE command - int RLE_cmd = stbi__get8(s); - RLE_count = 1 + (RLE_cmd & 127); - RLE_repeating = RLE_cmd >> 7; - read_next_pixel = 1; - } else if ( !RLE_repeating ) - { - read_next_pixel = 1; + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start); + // load the palette + tga_palette = + (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); } - } else - { - read_next_pixel = 1; - } - // OK, if I need to read a pixel, do it now - if ( read_next_pixel ) - { - // load however much data we did have - if ( tga_indexed ) - { - // read in index, then perform the lookup - int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); - if ( pal_idx >= tga_palette_len ) { - // invalid index - pal_idx = 0; - } - pal_idx *= tga_comp; - for (j = 0; j < tga_comp; ++j) { - raw_data[j] = tga_palette[pal_idx+j]; - } - } else if(tga_rgb16) { - STBI_ASSERT(tga_comp == STBI_rgb); - stbi__tga_read_rgb16(s, raw_data); + if (tga_rgb16) { + stbi_uc* pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i = 0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, + tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i = 0; i < tga_width * tga_height; ++i) { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if (tga_is_RLE) { + if (RLE_count == 0) { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if (!RLE_repeating) { + read_next_pixel = 1; + } } else { - // read in the data raw - for (j = 0; j < tga_comp; ++j) { - raw_data[j] = stbi__get8(s); - } + read_next_pixel = 1; } - // clear the reading flag for the next pixel - read_next_pixel = 0; - } // end of reading a pixel + // OK, if I need to read a pixel, do it now + if (read_next_pixel) { + // load however much data we did have + if (tga_indexed) { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) + : stbi__get16le(s); + if (pal_idx >= tga_palette_len) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx + j]; + } + } else if (tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel - // copy data - for (j = 0; j < tga_comp; ++j) - tga_data[i*tga_comp+j] = raw_data[j]; + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i * tga_comp + j] = raw_data[j]; - // in case we're in RLE mode, keep counting down - --RLE_count; - } - // do I need to invert the image? - if ( tga_inverted ) - { - for (j = 0; j*2 < tga_height; ++j) - { - int index1 = j * tga_width * tga_comp; - int index2 = (tga_height - 1 - j) * tga_width * tga_comp; - for (i = tga_width * tga_comp; i > 0; --i) - { - unsigned char temp = tga_data[index1]; - tga_data[index1] = tga_data[index2]; - tga_data[index2] = temp; - ++index1; - ++index2; + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if (tga_inverted) { + for (j = 0; j * 2 < tga_height; ++j) { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } } - } - } - // clear my palette, if I had one - if ( tga_palette != NULL ) - { - STBI_FREE( tga_palette ); - } - } + } + // clear my palette, if I had one + if (tga_palette != NULL) { + STBI_FREE(tga_palette); + } + } - // swap RGB - if the source data was RGB16, it already is in the right order - if (tga_comp >= 3 && !tga_rgb16) - { - unsigned char* tga_pixel = tga_data; - for (i=0; i < tga_width * tga_height; ++i) - { - unsigned char temp = tga_pixel[0]; - tga_pixel[0] = tga_pixel[2]; - tga_pixel[2] = temp; - tga_pixel += tga_comp; - } - } + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) { + unsigned char* tga_pixel = tga_data; + for (i = 0; i < tga_width * tga_height; ++i) { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } - // convert to target component count - if (req_comp && req_comp != tga_comp) - tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, + tga_height); - // the things I do to get rid of an error message, and yet keep - // Microsoft's C compilers happy... [8^( - tga_palette_start = tga_palette_len = tga_palette_bits = - tga_x_origin = tga_y_origin = 0; - STBI_NOTUSED(tga_palette_start); - // OK, done - return tga_data; + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = + tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; } #endif // ************************************************************************************************* -// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, +// tweaked by STB #ifndef STBI_NO_PSD -static int stbi__psd_test(stbi__context *s) -{ - int r = (stbi__get32be(s) == 0x38425053); - stbi__rewind(s); - return r; +static int stbi__psd_test(stbi__context* s) { + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; } -static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) -{ - int count, nleft, len; +static int stbi__psd_decode_rle(stbi__context* s, stbi_uc* p, int pixelCount) { + int count, nleft, len; - count = 0; - while ((nleft = pixelCount - count) > 0) { - len = stbi__get8(s); - if (len == 128) { - // No-op. - } else if (len < 128) { - // Copy next len+1 bytes literally. - len++; - if (len > nleft) return 0; // corrupt data - count += len; - while (len) { - *p = stbi__get8(s); - p += 4; - len--; - } - } else if (len > 128) { - stbi_uc val; - // Next -len+1 bytes in the dest are replicated from next source byte. - // (Interpret len as a negative 8-bit int.) - len = 257 - len; - if (len > nleft) return 0; // corrupt data - val = stbi__get8(s); - count += len; - while (len) { - *p = val; - p += 4; - len--; - } - } - } + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source + // byte. (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } - return 1; + return 1; } -static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) -{ - int pixelCount; - int channelCount, compression; - int channel, i; - int bitdepth; - int w,h; - stbi_uc *out; - STBI_NOTUSED(ri); +static void* stbi__psd_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri, int bpc) { + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w, h; + stbi_uc* out; + STBI_NOTUSED(ri); - // Check identifier - if (stbi__get32be(s) != 0x38425053) // "8BPS" - return stbi__errpuc("not PSD", "Corrupt PSD image"); + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); - // Check file type version. - if (stbi__get16be(s) != 1) - return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", + "Unsupported version of PSD image"); - // Skip 6 reserved bytes. - stbi__skip(s, 6 ); + // Skip 6 reserved bytes. + stbi__skip(s, 6); - // Read the number of channels (R, G, B, A, etc). - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) - return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", + "Unsupported number of channels in PSD image"); - // Read the rows and columns of the image. - h = stbi__get32be(s); - w = stbi__get32be(s); + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); - if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (h > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); - // Make sure the depth is 8 bits. - bitdepth = stbi__get16be(s); - if (bitdepth != 8 && bitdepth != 16) - return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", + "PSD bit depth is not 8 or 16 bit"); - // Make sure the color mode is RGB. - // Valid options are: - // 0: Bitmap - // 1: Grayscale - // 2: Indexed color - // 3: RGB color - // 4: CMYK color - // 7: Multichannel - // 8: Duotone - // 9: Lab color - if (stbi__get16be(s) != 3) - return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", + "PSD is not in RGB color format"); - // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) - stbi__skip(s,stbi__get32be(s) ); + // Skip the Mode Data. (It's the palette for indexed color; other info for + // other modes.) + stbi__skip(s, stbi__get32be(s)); - // Skip the image resources. (resolution, pen tool paths, etc) - stbi__skip(s, stbi__get32be(s) ); + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s)); - // Skip the reserved data. - stbi__skip(s, stbi__get32be(s) ); + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s)); - // Find out if the data is compressed. - // Known values: - // 0: no compression - // 1: RLE compressed - compression = stbi__get16be(s); - if (compression > 1) - return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", + "PSD has an unknown compression format"); - // Check size - if (!stbi__mad3sizes_valid(4, w, h, 0)) - return stbi__errpuc("too large", "Corrupt PSD"); + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); - // Create the destination image. + // Create the destination image. - if (!compression && bitdepth == 16 && bpc == 16) { - out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); - ri->bits_per_channel = 16; - } else - out = (stbi_uc *) stbi__malloc(4 * w*h); + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc*)stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc*)stbi__malloc(4 * w * h); - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - pixelCount = w*h; + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w * h; - // Initialize the data to zero. - //memset( out, 0, pixelCount * 4 ); + // Initialize the data to zero. + // memset( out, 0, pixelCount * 4 ); - // Finally, the image data. - if (compression) { - // RLE as used by .PSD and .TIFF - // Loop until you get the number of unpacked bytes you are expecting: - // Read the next source byte into n. - // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. - // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. - // Else if n is 128, noop. - // Endloop + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes + // literally. Else if n is between -127 and -1 inclusive, copy the + // next byte -n+1 times. Else if n is 128, noop. + // Endloop - // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, - // which we're going to just skip. - stbi__skip(s, h * channelCount * 2 ); + // The RLE-compressed data is preceded by a 2-byte data count for each + // row in the data, which we're going to just skip. + stbi__skip(s, h * channelCount * 2); - // Read the RLE data by channel. - for (channel = 0; channel < 4; channel++) { - stbi_uc *p; + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc* p; - p = out+channel; - if (channel >= channelCount) { - // Fill this channel with default data. - for (i = 0; i < pixelCount; i++, p += 4) - *p = (channel == 3 ? 255 : 0); - } else { - // Read the RLE data. - if (!stbi__psd_decode_rle(s, p, pixelCount)) { - STBI_FREE(out); - return stbi__errpuc("corrupt", "bad RLE data"); - } - } - } - - } else { - // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) - // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. - - // Read the data by channel. - for (channel = 0; channel < 4; channel++) { - if (channel >= channelCount) { - // Fill this channel with default data. - if (bitdepth == 16 && bpc == 16) { - stbi__uint16 *q = ((stbi__uint16 *) out) + channel; - stbi__uint16 val = channel == 3 ? 65535 : 0; - for (i = 0; i < pixelCount; i++, q += 4) - *q = val; + p = out + channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); } else { - stbi_uc *p = out+channel; - stbi_uc val = channel == 3 ? 255 : 0; - for (i = 0; i < pixelCount; i++, p += 4) - *p = val; + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } } - } else { - if (ri->bits_per_channel == 16) { // output bpc - stbi__uint16 *q = ((stbi__uint16 *) out) + channel; - for (i = 0; i < pixelCount; i++, q += 4) - *q = (stbi__uint16) stbi__get16be(s); + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, + // Blue, Alpha, ...) where each channel consists of an 8-bit (or 16-bit) + // value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16* q = ((stbi__uint16*)out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) *q = val; + } else { + stbi_uc* p = out + channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) *p = val; + } } else { - stbi_uc *p = out+channel; - if (bitdepth == 16) { // input bpc - for (i = 0; i < pixelCount; i++, p += 4) - *p = (stbi_uc) (stbi__get16be(s) >> 8); - } else { - for (i = 0; i < pixelCount; i++, p += 4) - *p = stbi__get8(s); - } + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16* q = ((stbi__uint16*)out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16)stbi__get16be(s); + } else { + stbi_uc* p = out + channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc)(stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } } - } - } - } + } + } - // remove weird white matte from PSD - if (channelCount >= 4) { - if (ri->bits_per_channel == 16) { - for (i=0; i < w*h; ++i) { - stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; - if (pixel[3] != 0 && pixel[3] != 65535) { - float a = pixel[3] / 65535.0f; - float ra = 1.0f / a; - float inv_a = 65535.0f * (1 - ra); - pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); - pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); - pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i = 0; i < w * h; ++i) { + stbi__uint16* pixel = (stbi__uint16*)out + 4 * i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16)(pixel[0] * ra + inv_a); + pixel[1] = (stbi__uint16)(pixel[1] * ra + inv_a); + pixel[2] = (stbi__uint16)(pixel[2] * ra + inv_a); + } } - } - } else { - for (i=0; i < w*h; ++i) { - unsigned char *pixel = out + 4*i; - if (pixel[3] != 0 && pixel[3] != 255) { - float a = pixel[3] / 255.0f; - float ra = 1.0f / a; - float inv_a = 255.0f * (1 - ra); - pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); - pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); - pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } else { + for (i = 0; i < w * h; ++i) { + unsigned char* pixel = out + 4 * i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char)(pixel[0] * ra + inv_a); + pixel[1] = (unsigned char)(pixel[1] * ra + inv_a); + pixel[2] = (unsigned char)(pixel[2] * ra + inv_a); + } } - } - } - } + } + } - // convert to desired output format - if (req_comp && req_comp != 4) { - if (ri->bits_per_channel == 16) - out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); - else - out = stbi__convert_format(out, 4, req_comp, w, h); - if (out == NULL) return out; // stbi__convert_format frees input on failure - } + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc*)stbi__convert_format16((stbi__uint16*)out, 4, + req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) + return out; // stbi__convert_format frees input on failure + } - if (comp) *comp = 4; - *y = h; - *x = w; + if (comp) *comp = 4; + *y = h; + *x = w; - return out; + return out; } #endif @@ -6333,216 +6918,217 @@ static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ #ifndef STBI_NO_PIC -static int stbi__pic_is4(stbi__context *s,const char *str) -{ - int i; - for (i=0; i<4; ++i) - if (stbi__get8(s) != (stbi_uc)str[i]) - return 0; +static int stbi__pic_is4(stbi__context* s, const char* str) { + int i; + for (i = 0; i < 4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) return 0; - return 1; + return 1; } -static int stbi__pic_test_core(stbi__context *s) -{ - int i; +static int stbi__pic_test_core(stbi__context* s) { + int i; - if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) - return 0; + if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) return 0; - for(i=0;i<84;++i) - stbi__get8(s); + for (i = 0; i < 84; ++i) stbi__get8(s); - if (!stbi__pic_is4(s,"PICT")) - return 0; + if (!stbi__pic_is4(s, "PICT")) return 0; - return 1; + return 1; } -typedef struct -{ - stbi_uc size,type,channel; +typedef struct { + stbi_uc size, type, channel; } stbi__pic_packet; -static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) -{ - int mask=0x80, i; +static stbi_uc* stbi__readval(stbi__context* s, int channel, stbi_uc* dest) { + int mask = 0x80, i; - for (i=0; i<4; ++i, mask>>=1) { - if (channel & mask) { - if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); - dest[i]=stbi__get8(s); - } - } + for (i = 0; i < 4; ++i, mask >>= 1) { + if (channel & mask) { + if (stbi__at_eof(s)) + return stbi__errpuc("bad file", "PIC file too short"); + dest[i] = stbi__get8(s); + } + } - return dest; + return dest; } -static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) -{ - int mask=0x80,i; +static void stbi__copyval(int channel, stbi_uc* dest, const stbi_uc* src) { + int mask = 0x80, i; - for (i=0;i<4; ++i, mask>>=1) - if (channel&mask) - dest[i]=src[i]; + for (i = 0; i < 4; ++i, mask >>= 1) + if (channel & mask) dest[i] = src[i]; } -static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) -{ - int act_comp=0,num_packets=0,y,chained; - stbi__pic_packet packets[10]; +static stbi_uc* stbi__pic_load_core(stbi__context* s, int width, int height, + int* comp, stbi_uc* result) { + int act_comp = 0, num_packets = 0, y, chained; + stbi__pic_packet packets[10]; - // this will (should...) cater for even some bizarre stuff like having data + // this will (should...) cater for even some bizarre stuff like having data // for the same channel in multiple packets. - do { - stbi__pic_packet *packet; + do { + stbi__pic_packet* packet; - if (num_packets==sizeof(packets)/sizeof(packets[0])) - return stbi__errpuc("bad format","too many packets"); + if (num_packets == sizeof(packets) / sizeof(packets[0])) + return stbi__errpuc("bad format", "too many packets"); - packet = &packets[num_packets++]; + packet = &packets[num_packets++]; - chained = stbi__get8(s); - packet->size = stbi__get8(s); - packet->type = stbi__get8(s); - packet->channel = stbi__get8(s); + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); - act_comp |= packet->channel; + act_comp |= packet->channel; - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); - if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); - } while (chained); + if (stbi__at_eof(s)) + return stbi__errpuc("bad file", "file too short (reading packets)"); + if (packet->size != 8) + return stbi__errpuc("bad format", "packet isn't 8bpp"); + } while (chained); - *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? - for(y=0; ytype) { - default: - return stbi__errpuc("bad format","packet has bad compression type"); + switch (packet->type) { + default: + return stbi__errpuc("bad format", + "packet has bad compression type"); - case 0: {//uncompressed - int x; + case 0: { // uncompressed + int x; - for(x=0;xchannel,dest)) - return 0; - break; + for (x = 0; x < width; ++x, dest += 4) + if (!stbi__readval(s, packet->channel, dest)) return 0; + break; + } + + case 1: // Pure RLE + { + int left = width, i; + + while (left > 0) { + stbi_uc count, value[4]; + + count = stbi__get8(s); + if (stbi__at_eof(s)) + return stbi__errpuc( + "bad file", "file too short (pure read count)"); + + if (count > left) count = (stbi_uc)left; + + if (!stbi__readval(s, packet->channel, value)) return 0; + + for (i = 0; i < count; ++i, dest += 4) + stbi__copyval(packet->channel, dest, value); + left -= count; + } + } break; + + case 2: { // Mixed RLE + int left = width; + while (left > 0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) + return stbi__errpuc( + "bad file", + "file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count == 128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file", + "scanline overrun"); + + if (!stbi__readval(s, packet->channel, value)) + return 0; + + for (i = 0; i < count; ++i, dest += 4) + stbi__copyval(packet->channel, dest, value); + } else { // Raw + ++count; + if (count > left) + return stbi__errpuc("bad file", + "scanline overrun"); + + for (i = 0; i < count; ++i, dest += 4) + if (!stbi__readval(s, packet->channel, dest)) + return 0; + } + left -= count; + } + break; + } } + } + } - case 1://Pure RLE - { - int left=width, i; - - while (left>0) { - stbi_uc count,value[4]; - - count=stbi__get8(s); - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); - - if (count > left) - count = (stbi_uc) left; - - if (!stbi__readval(s,packet->channel,value)) return 0; - - for(i=0; ichannel,dest,value); - left -= count; - } - } - break; - - case 2: {//Mixed RLE - int left=width; - while (left>0) { - int count = stbi__get8(s), i; - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); - - if (count >= 128) { // Repeated - stbi_uc value[4]; - - if (count==128) - count = stbi__get16be(s); - else - count -= 127; - if (count > left) - return stbi__errpuc("bad file","scanline overrun"); - - if (!stbi__readval(s,packet->channel,value)) - return 0; - - for(i=0;ichannel,dest,value); - } else { // Raw - ++count; - if (count>left) return stbi__errpuc("bad file","scanline overrun"); - - for(i=0;ichannel,dest)) - return 0; - } - left-=count; - } - break; - } - } - } - } - - return result; + return result; } -static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) -{ - stbi_uc *result; - int i, x,y, internal_comp; - STBI_NOTUSED(ri); +static void* stbi__pic_load(stbi__context* s, int* px, int* py, int* comp, + int req_comp, stbi__result_info* ri) { + stbi_uc* result; + int i, x, y, internal_comp; + STBI_NOTUSED(ri); - if (!comp) comp = &internal_comp; + if (!comp) comp = &internal_comp; - for (i=0; i<92; ++i) - stbi__get8(s); + for (i = 0; i < 92; ++i) stbi__get8(s); - x = stbi__get16be(s); - y = stbi__get16be(s); + x = stbi__get16be(s); + y = stbi__get16be(s); - if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (y > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); - if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + if (stbi__at_eof(s)) + return stbi__errpuc("bad file", "file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) + return stbi__errpuc("too large", "PIC image too large to decode"); - stbi__get32be(s); //skip `ratio' - stbi__get16be(s); //skip `fields' - stbi__get16be(s); //skip `pad' + stbi__get32be(s); // skip `ratio' + stbi__get16be(s); // skip `fields' + stbi__get16be(s); // skip `pad' - // intermediate buffer is RGBA - result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); - if (!result) return stbi__errpuc("outofmem", "Out of memory"); - memset(result, 0xff, x*y*4); + // intermediate buffer is RGBA + result = (stbi_uc*)stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); + memset(result, 0xff, x * y * 4); - if (!stbi__pic_load_core(s,x,y,comp, result)) { - STBI_FREE(result); - result=0; - } - *px = x; - *py = y; - if (req_comp == 0) req_comp = *comp; - result=stbi__convert_format(result,4,req_comp,x,y); + if (!stbi__pic_load_core(s, x, y, comp, result)) { + STBI_FREE(result); + result = 0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result = stbi__convert_format(result, 4, req_comp, x, y); - return result; + return result; } -static int stbi__pic_test(stbi__context *s) -{ - int r = stbi__pic_test_core(s); - stbi__rewind(s); - return r; +static int stbi__pic_test(stbi__context* s) { + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; } #endif @@ -6550,533 +7136,556 @@ static int stbi__pic_test(stbi__context *s) // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb #ifndef STBI_NO_GIF -typedef struct -{ - stbi__int16 prefix; - stbi_uc first; - stbi_uc suffix; +typedef struct { + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; } stbi__gif_lzw; -typedef struct -{ - int w,h; - stbi_uc *out; // output buffer (always 4 components) - stbi_uc *background; // The current "background" as far as a gif is concerned - stbi_uc *history; - int flags, bgindex, ratio, transparent, eflags; - stbi_uc pal[256][4]; - stbi_uc lpal[256][4]; - stbi__gif_lzw codes[8192]; - stbi_uc *color_table; - int parse, step; - int lflags; - int start_x, start_y; - int max_x, max_y; - int cur_x, cur_y; - int line_size; - int delay; +typedef struct { + int w, h; + stbi_uc* out; // output buffer (always 4 components) + stbi_uc* + background; // The current "background" as far as a gif is concerned + stbi_uc* history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc* color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; } stbi__gif; -static int stbi__gif_test_raw(stbi__context *s) -{ - int sz; - if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; - sz = stbi__get8(s); - if (sz != '9' && sz != '7') return 0; - if (stbi__get8(s) != 'a') return 0; - return 1; +static int stbi__gif_test_raw(stbi__context* s) { + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || + stbi__get8(s) != '8') + return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; } -static int stbi__gif_test(stbi__context *s) -{ - int r = stbi__gif_test_raw(s); - stbi__rewind(s); - return r; +static int stbi__gif_test(stbi__context* s) { + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; } -static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) -{ - int i; - for (i=0; i < num_entries; ++i) { - pal[i][2] = stbi__get8(s); - pal[i][1] = stbi__get8(s); - pal[i][0] = stbi__get8(s); - pal[i][3] = transp == i ? 0 : 255; - } +static void stbi__gif_parse_colortable(stbi__context* s, stbi_uc pal[256][4], + int num_entries, int transp) { + int i; + for (i = 0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } } -static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) -{ - stbi_uc version; - if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') - return stbi__err("not GIF", "Corrupt GIF"); +static int stbi__gif_header(stbi__context* s, stbi__gif* g, int* comp, + int is_info) { + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || + stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); - version = stbi__get8(s); - if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); - if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + version = stbi__get8(s); + if (version != '7' && version != '9') + return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); - stbi__g_failure_reason = ""; - g->w = stbi__get16le(s); - g->h = stbi__get16le(s); - g->flags = stbi__get8(s); - g->bgindex = stbi__get8(s); - g->ratio = stbi__get8(s); - g->transparent = -1; + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; - if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->w > STBI_MAX_DIMENSIONS) + return stbi__err("too large", "Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) + return stbi__err("too large", "Very large image (corrupt?)"); - if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + if (comp != 0) + *comp = 4; // can't actually tell whether it's 3 or 4 until we parse + // the comments - if (is_info) return 1; + if (is_info) return 1; - if (g->flags & 0x80) - stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + if (g->flags & 0x80) + stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1); - return 1; + return 1; } -static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) -{ - stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); - if (!g) return stbi__err("outofmem", "Out of memory"); - if (!stbi__gif_header(s, g, comp, 1)) { - STBI_FREE(g); - stbi__rewind( s ); - return 0; - } - if (x) *x = g->w; - if (y) *y = g->h; - STBI_FREE(g); - return 1; +static int stbi__gif_info_raw(stbi__context* s, int* x, int* y, int* comp) { + stbi__gif* g = (stbi__gif*)stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind(s); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; } -static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) -{ - stbi_uc *p, *c; - int idx; +static void stbi__out_gif_code(stbi__gif* g, stbi__uint16 code) { + stbi_uc *p, *c; + int idx; - // recurse to decode the prefixes, since the linked-list is backwards, - // and working backwards through an interleaved image would be nasty - if (g->codes[code].prefix >= 0) - stbi__out_gif_code(g, g->codes[code].prefix); + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); - if (g->cur_y >= g->max_y) return; + if (g->cur_y >= g->max_y) return; - idx = g->cur_x + g->cur_y; - p = &g->out[idx]; - g->history[idx / 4] = 1; + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; - c = &g->color_table[g->codes[code].suffix * 4]; - if (c[3] > 128) { // don't render transparent pixels; - p[0] = c[2]; - p[1] = c[1]; - p[2] = c[0]; - p[3] = c[3]; - } - g->cur_x += 4; + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; - if (g->cur_x >= g->max_x) { - g->cur_x = g->start_x; - g->cur_y += g->step; + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; - while (g->cur_y >= g->max_y && g->parse > 0) { - g->step = (1 << g->parse) * g->line_size; - g->cur_y = g->start_y + (g->step >> 1); - --g->parse; - } - } + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } } -static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) -{ - stbi_uc lzw_cs; - stbi__int32 len, init_code; - stbi__uint32 first; - stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; - stbi__gif_lzw *p; +static stbi_uc* stbi__process_gif_raster(stbi__context* s, stbi__gif* g) { + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw* p; - lzw_cs = stbi__get8(s); - if (lzw_cs > 12) return NULL; - clear = 1 << lzw_cs; - first = 1; - codesize = lzw_cs + 1; - codemask = (1 << codesize) - 1; - bits = 0; - valid_bits = 0; - for (init_code = 0; init_code < clear; init_code++) { - g->codes[init_code].prefix = -1; - g->codes[init_code].first = (stbi_uc) init_code; - g->codes[init_code].suffix = (stbi_uc) init_code; - } + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc)init_code; + g->codes[init_code].suffix = (stbi_uc)init_code; + } - // support no starting clear code - avail = clear+2; - oldcode = -1; + // support no starting clear code + avail = clear + 2; + oldcode = -1; - len = 0; - for(;;) { - if (valid_bits < codesize) { - if (len == 0) { - len = stbi__get8(s); // start new block - if (len == 0) - return g->out; - } - --len; - bits |= (stbi__int32) stbi__get8(s) << valid_bits; - valid_bits += 8; - } else { - stbi__int32 code = bits & codemask; - bits >>= codesize; - valid_bits -= codesize; - // @OPTIMIZE: is there some way we can accelerate the non-clear path? - if (code == clear) { // clear code - codesize = lzw_cs + 1; - codemask = (1 << codesize) - 1; - avail = clear + 2; - oldcode = -1; - first = 0; - } else if (code == clear + 1) { // end of stream code - stbi__skip(s, len); - while ((len = stbi__get8(s)) > 0) - stbi__skip(s,len); - return g->out; - } else if (code <= avail) { - if (first) { - return stbi__errpuc("no clear code", "Corrupt GIF"); + len = 0; + for (;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) return g->out; } + --len; + bits |= (stbi__int32)stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear + // path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) stbi__skip(s, len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } - if (oldcode >= 0) { - p = &g->codes[avail++]; - if (avail > 8192) { - return stbi__errpuc("too many codes", "Corrupt GIF"); - } + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } - p->prefix = (stbi__int16) oldcode; - p->first = g->codes[oldcode].first; - p->suffix = (code == avail) ? p->first : g->codes[code].first; - } else if (code == avail) - return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + p->prefix = (stbi__int16)oldcode; + p->first = g->codes[oldcode].first; + p->suffix = + (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", + "Corrupt GIF"); - stbi__out_gif_code(g, (stbi__uint16) code); + stbi__out_gif_code(g, (stbi__uint16)code); - if ((avail & codemask) == 0 && avail <= 0x0FFF) { - codesize++; - codemask = (1 << codesize) - 1; - } + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } - oldcode = code; - } else { - return stbi__errpuc("illegal code in raster", "Corrupt GIF"); - } - } - } -} - -// this function is designed to support animated gifs, although stb_image doesn't support it -// two back is the image from two frames ago, used for a very specific disposal format -static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) -{ - int dispose; - int first_frame; - int pi; - int pcount; - STBI_NOTUSED(req_comp); - - // on first frame, any non-written pixels get the background colour (non-transparent) - first_frame = 0; - if (g->out == 0) { - if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header - if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) - return stbi__errpuc("too large", "GIF image is too large"); - pcount = g->w * g->h; - g->out = (stbi_uc *) stbi__malloc(4 * pcount); - g->background = (stbi_uc *) stbi__malloc(4 * pcount); - g->history = (stbi_uc *) stbi__malloc(pcount); - if (!g->out || !g->background || !g->history) - return stbi__errpuc("outofmem", "Out of memory"); - - // image is treated as "transparent" at the start - ie, nothing overwrites the current background; - // background colour is only used for pixels that are not rendered first frame, after that "background" - // color refers to the color that was there the previous frame. - memset(g->out, 0x00, 4 * pcount); - memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) - memset(g->history, 0x00, pcount); // pixels that were affected previous frame - first_frame = 1; - } else { - // second frame - how do we dispose of the previous one? - dispose = (g->eflags & 0x1C) >> 2; - pcount = g->w * g->h; - - if ((dispose == 3) && (two_back == 0)) { - dispose = 2; // if I don't have an image to revert back to, default to the old background - } - - if (dispose == 3) { // use previous graphic - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi]) { - memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); - } - } - } else if (dispose == 2) { - // restore what was changed last frame to background before that frame; - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi]) { - memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); - } - } - } else { - // This is a non-disposal case eithe way, so just - // leave the pixels as is, and they will become the new background - // 1: do not dispose - // 0: not specified. - } - - // background is what out is after the undoing of the previou frame; - memcpy( g->background, g->out, 4 * g->w * g->h ); - } - - // clear my history; - memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame - - for (;;) { - int tag = stbi__get8(s); - switch (tag) { - case 0x2C: /* Image Descriptor */ - { - stbi__int32 x, y, w, h; - stbi_uc *o; - - x = stbi__get16le(s); - y = stbi__get16le(s); - w = stbi__get16le(s); - h = stbi__get16le(s); - if (((x + w) > (g->w)) || ((y + h) > (g->h))) - return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); - - g->line_size = g->w * 4; - g->start_x = x * 4; - g->start_y = y * g->line_size; - g->max_x = g->start_x + w * 4; - g->max_y = g->start_y + h * g->line_size; - g->cur_x = g->start_x; - g->cur_y = g->start_y; - - // if the width of the specified rectangle is 0, that means - // we may not see *any* pixels or the image is malformed; - // to make sure this is caught, move the current y down to - // max_y (which is what out_gif_code checks). - if (w == 0) - g->cur_y = g->max_y; - - g->lflags = stbi__get8(s); - - if (g->lflags & 0x40) { - g->step = 8 * g->line_size; // first interlaced spacing - g->parse = 3; + oldcode = code; } else { - g->step = g->line_size; - g->parse = 0; + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); } - - if (g->lflags & 0x80) { - stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); - g->color_table = (stbi_uc *) g->lpal; - } else if (g->flags & 0x80) { - g->color_table = (stbi_uc *) g->pal; - } else - return stbi__errpuc("missing color table", "Corrupt GIF"); - - o = stbi__process_gif_raster(s, g); - if (!o) return NULL; - - // if this was the first frame, - pcount = g->w * g->h; - if (first_frame && (g->bgindex > 0)) { - // if first frame, any pixel not drawn to gets the background color - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi] == 0) { - g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; - memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); - } - } - } - - return o; - } - - case 0x21: // Comment Extension. - { - int len; - int ext = stbi__get8(s); - if (ext == 0xF9) { // Graphic Control Extension. - len = stbi__get8(s); - if (len == 4) { - g->eflags = stbi__get8(s); - g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. - - // unset old transparent - if (g->transparent >= 0) { - g->pal[g->transparent][3] = 255; - } - if (g->eflags & 0x01) { - g->transparent = stbi__get8(s); - if (g->transparent >= 0) { - g->pal[g->transparent][3] = 0; - } - } else { - // don't need transparent - stbi__skip(s, 1); - g->transparent = -1; - } - } else { - stbi__skip(s, len); - break; - } - } - while ((len = stbi__get8(s)) != 0) { - stbi__skip(s, len); - } - break; - } - - case 0x3B: // gif stream termination code - return (stbi_uc *) s; // using '1' causes warning on some compilers - - default: - return stbi__errpuc("unknown code", "Corrupt GIF"); - } - } + } + } } -static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) -{ - STBI_FREE(g->out); - STBI_FREE(g->history); - STBI_FREE(g->background); +// this function is designed to support animated gifs, although stb_image +// doesn't support it two back is the image from two frames ago, used for a very +// specific disposal format +static stbi_uc* stbi__gif_load_next(stbi__context* s, stbi__gif* g, int* comp, + int req_comp, stbi_uc* two_back) { + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); - if (out) STBI_FREE(out); - if (delays && *delays) STBI_FREE(*delays); - return stbi__errpuc("outofmem", "Out of memory"); -} + // on first frame, any non-written pixels get the background colour + // (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp, 0)) + return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc*)stbi__malloc(4 * pcount); + g->background = (stbi_uc*)stbi__malloc(4 * pcount); + g->history = (stbi_uc*)stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); -static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) -{ - if (stbi__gif_test(s)) { - int layers = 0; - stbi_uc *u = 0; - stbi_uc *out = 0; - stbi_uc *two_back = 0; - stbi__gif g; - int stride; - int out_size = 0; - int delays_size = 0; + // image is treated as "transparent" at the start - ie, nothing + // overwrites the current background; background colour is only used for + // pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, + 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, + pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; - STBI_NOTUSED(out_size); - STBI_NOTUSED(delays_size); + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default + // to the old background + } - memset(&g, 0, sizeof(g)); - if (delays) { - *delays = 0; - } - - do { - u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); - if (u == (stbi_uc *) s) u = 0; // end of animated gif marker - - if (u) { - *x = g.w; - *y = g.h; - ++layers; - stride = g.w * g.h * 4; - - if (out) { - void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); - if (!tmp) - return stbi__load_gif_main_outofmem(&g, out, delays); - else { - out = (stbi_uc*) tmp; - out_size = layers * stride; - } - - if (delays) { - int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); - if (!new_delays) - return stbi__load_gif_main_outofmem(&g, out, delays); - *delays = new_delays; - delays_size = layers * sizeof(int); - } - } else { - out = (stbi_uc*)stbi__malloc( layers * stride ); - if (!out) - return stbi__load_gif_main_outofmem(&g, out, delays); - out_size = layers * stride; - if (delays) { - *delays = (int*) stbi__malloc( layers * sizeof(int) ); - if (!*delays) - return stbi__load_gif_main_outofmem(&g, out, delays); - delays_size = layers * sizeof(int); - } + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy(&g->out[pi * 4], &two_back[pi * 4], 4); + } } - memcpy( out + ((layers - 1) * stride), u, stride ); - if (layers >= 2) { - two_back = out - 2 * stride; + } else if (dispose == 2) { + // restore what was changed last frame to background before that + // frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy(&g->out[pi * 4], &g->background[pi * 4], 4); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy(g->background, g->out, 4 * g->w * g->h); + } + + // clear my history; + memset(g->history, 0x00, + g->w * g->h); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc* o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable( + s, g->lpal, 2 << (g->lflags & 7), + g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc*)g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc*)g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the + // background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = + 255; // just in case it was made transparent, + // undo that; It will be reset next frame + // if need be; + memcpy(&g->out[pi * 4], &g->pal[g->bgindex], 4); + } + } + } + + return o; } - if (delays) { - (*delays)[layers - 1U] = g.delay; + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le( + s); // delay - 1/100th of a second, + // saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; } - } - } while (u != 0); - // free temp buffer; - STBI_FREE(g.out); - STBI_FREE(g.history); - STBI_FREE(g.background); + case 0x3B: // gif stream termination code + return ( + stbi_uc*)s; // using '1' causes warning on some compilers - // do the final conversion after loading everything; - if (req_comp && req_comp != 4) - out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); - - *z = layers; - return out; - } else { - return stbi__errpuc("not GIF", "Image was not as a gif type."); - } + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } } -static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *u = 0; - stbi__gif g; - memset(&g, 0, sizeof(g)); - STBI_NOTUSED(ri); +static void* stbi__load_gif_main_outofmem(stbi__gif* g, stbi_uc* out, + int** delays) { + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); - u = stbi__gif_load_next(s, &g, comp, req_comp, 0); - if (u == (stbi_uc *) s) u = 0; // end of animated gif marker - if (u) { - *x = g.w; - *y = g.h; - - // moved conversion to after successful load so that the same - // can be done for multiple frames. - if (req_comp && req_comp != 4) - u = stbi__convert_format(u, 4, req_comp, g.w, g.h); - } else if (g.out) { - // if there was an error and we allocated an image buffer, free it! - STBI_FREE(g.out); - } - - // free buffers needed for multiple frame loading; - STBI_FREE(g.history); - STBI_FREE(g.background); - - return u; + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); } -static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) -{ - return stbi__gif_info_raw(s,x,y,comp); +static void* stbi__load_gif_main(stbi__context* s, int** delays, int* x, int* y, + int* z, int* comp, int req_comp) { + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc* u = 0; + stbi_uc* out = 0; + stbi_uc* two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc*)s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void* tmp = (stbi_uc*)STBI_REALLOC_SIZED(out, out_size, + layers * stride); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*)tmp; + out_size = layers * stride; + } + + if (delays) { + int* new_delays = (int*)STBI_REALLOC_SIZED( + *delays, delays_size, sizeof(int) * layers); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, + delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc(layers * stride); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*)stbi__malloc(layers * sizeof(int)); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, + delays); + delays_size = layers * sizeof(int); + } + } + memcpy(out + ((layers - 1) * stride), u, stride); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void* stbi__gif_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri) { + stbi_uc* u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc*)s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context* s, int* x, int* y, int* comp) { + return stbi__gif_info_raw(s, x, y, comp); } #endif @@ -7084,397 +7693,413 @@ static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR -static int stbi__hdr_test_core(stbi__context *s, const char *signature) -{ - int i; - for (i=0; signature[i]; ++i) - if (stbi__get8(s) != signature[i]) - return 0; - stbi__rewind(s); - return 1; +static int stbi__hdr_test_core(stbi__context* s, const char* signature) { + int i; + for (i = 0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) return 0; + stbi__rewind(s); + return 1; } -static int stbi__hdr_test(stbi__context* s) -{ - int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); - stbi__rewind(s); - if(!r) { - r = stbi__hdr_test_core(s, "#?RGBE\n"); - stbi__rewind(s); - } - return r; +static int stbi__hdr_test(stbi__context* s) { + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if (!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; } -#define STBI__HDR_BUFLEN 1024 -static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) -{ - int len=0; - char c = '\0'; +#define STBI__HDR_BUFLEN 1024 +static char* stbi__hdr_gettoken(stbi__context* z, char* buffer) { + int len = 0; + char c = '\0'; - c = (char) stbi__get8(z); + c = (char)stbi__get8(z); - while (!stbi__at_eof(z) && c != '\n') { - buffer[len++] = c; - if (len == STBI__HDR_BUFLEN-1) { - // flush to end of line - while (!stbi__at_eof(z) && stbi__get8(z) != '\n') - ; - break; - } - c = (char) stbi__get8(z); - } + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN - 1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n'); + break; + } + c = (char)stbi__get8(z); + } - buffer[len] = 0; - return buffer; + buffer[len] = 0; + return buffer; } -static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) -{ - if ( input[3] != 0 ) { - float f1; - // Exponent - f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); - if (req_comp <= 2) - output[0] = (input[0] + input[1] + input[2]) * f1 / 3; - else { - output[0] = input[0] * f1; - output[1] = input[1] * f1; - output[2] = input[2] * f1; - } - if (req_comp == 2) output[1] = 1; - if (req_comp == 4) output[3] = 1; - } else { - switch (req_comp) { - case 4: output[3] = 1; /* fallthrough */ - case 3: output[0] = output[1] = output[2] = 0; - break; - case 2: output[1] = 1; /* fallthrough */ - case 1: output[0] = 0; - break; - } - } +static void stbi__hdr_convert(float* output, stbi_uc* input, int req_comp) { + if (input[3] != 0) { + float f1; + // Exponent + f1 = (float)ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: + output[3] = 1; /* fallthrough */ + case 3: + output[0] = output[1] = output[2] = 0; + break; + case 2: + output[1] = 1; /* fallthrough */ + case 1: + output[0] = 0; + break; + } + } } -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - char buffer[STBI__HDR_BUFLEN]; - char *token; - int valid = 0; - int width, height; - stbi_uc *scanline; - float *hdr_data; - int len; - unsigned char count, value; - int i, j, k, c1,c2, z; - const char *headerToken; - STBI_NOTUSED(ri); +static float* stbi__hdr_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri) { + char buffer[STBI__HDR_BUFLEN]; + char* token; + int valid = 0; + int width, height; + stbi_uc* scanline; + float* hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1, c2, z; + const char* headerToken; + STBI_NOTUSED(ri); - // Check identifier - headerToken = stbi__hdr_gettoken(s,buffer); - if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) - return stbi__errpf("not HDR", "Corrupt HDR image"); + // Check identifier + headerToken = stbi__hdr_gettoken(s, buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && + strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); - // Parse header - for(;;) { - token = stbi__hdr_gettoken(s,buffer); - if (token[0] == 0) break; - if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; - } + // Parse header + for (;;) { + token = stbi__hdr_gettoken(s, buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } - if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + if (!valid) + return stbi__errpf("unsupported format", "Unsupported HDR format"); - // Parse width and height - // can't use sscanf() if we're not using stdio! - token = stbi__hdr_gettoken(s,buffer); - if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); - token += 3; - height = (int) strtol(token, &token, 10); - while (*token == ' ') ++token; - if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); - token += 3; - width = (int) strtol(token, NULL, 10); + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s, buffer); + if (strncmp(token, "-Y ", 3)) + return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int)strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) + return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int)strtol(token, NULL, 10); - if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); - if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (height > STBI_MAX_DIMENSIONS) + return stbi__errpf("too large", "Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) + return stbi__errpf("too large", "Very large image (corrupt?)"); - *x = width; - *y = height; + *x = width; + *y = height; - if (comp) *comp = 3; - if (req_comp == 0) req_comp = 3; + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; - if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) - return stbi__errpf("too large", "HDR image is too large"); + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); - // Read data - hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); - if (!hdr_data) - return stbi__errpf("outofmem", "Out of memory"); + // Read data + hdr_data = + (float*)stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) return stbi__errpf("outofmem", "Out of memory"); - // Load image data - // image data is stored as some number of sca - if ( width < 8 || width >= 32768) { - // Read flat data - for (j=0; j < height; ++j) { - for (i=0; i < width; ++i) { - stbi_uc rgbe[4]; - main_decode_loop: - stbi__getn(s, rgbe, 4); - stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); - } - } - } else { - // Read RLE-encoded data - scanline = NULL; - - for (j = 0; j < height; ++j) { - c1 = stbi__get8(s); - c2 = stbi__get8(s); - len = stbi__get8(s); - if (c1 != 2 || c2 != 2 || (len & 0x80)) { - // not run-length encoded, so we have to actually use THIS data as a decoded - // pixel (note this can't be a valid pixel--one of RGB must be >= 128) - stbi_uc rgbe[4]; - rgbe[0] = (stbi_uc) c1; - rgbe[1] = (stbi_uc) c2; - rgbe[2] = (stbi_uc) len; - rgbe[3] = (stbi_uc) stbi__get8(s); - stbi__hdr_convert(hdr_data, rgbe, req_comp); - i = 1; - j = 0; - STBI_FREE(scanline); - goto main_decode_loop; // yes, this makes no sense - } - len <<= 8; - len |= stbi__get8(s); - if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } - if (scanline == NULL) { - scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); - if (!scanline) { - STBI_FREE(hdr_data); - return stbi__errpf("outofmem", "Out of memory"); + // Load image data + // image data is stored as some number of sca + if (width < 8 || width >= 32768) { + // Read flat data + for (j = 0; j < height; ++j) { + for (i = 0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert( + hdr_data + j * width * req_comp + i * req_comp, rgbe, + req_comp); } - } + } + } else { + // Read RLE-encoded data + scanline = NULL; - for (k = 0; k < 4; ++k) { - int nleft; - i = 0; - while ((nleft = width - i) > 0) { - count = stbi__get8(s); - if (count > 128) { - // Run - value = stbi__get8(s); - count -= 128; - if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = value; - } else { - // Dump - if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = stbi__get8(s); - } + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data + // as a decoded pixel (note this can't be a valid pixel--one of + // RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc)c1; + rgbe[1] = (stbi_uc)c2; + rgbe[2] = (stbi_uc)len; + rgbe[3] = (stbi_uc)stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { + STBI_FREE(hdr_data); + STBI_FREE(scanline); + return stbi__errpf("invalid decoded scanline length", + "corrupt HDR"); + } + if (scanline == NULL) { + scanline = (stbi_uc*)stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } } - } - for (i=0; i < width; ++i) - stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); - } - if (scanline) - STBI_FREE(scanline); - } - return hdr_data; + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if ((count == 0) || (count > nleft)) { + STBI_FREE(hdr_data); + STBI_FREE(scanline); + return stbi__errpf("corrupt", + "bad RLE data in HDR"); + } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if ((count == 0) || (count > nleft)) { + STBI_FREE(hdr_data); + STBI_FREE(scanline); + return stbi__errpf("corrupt", + "bad RLE data in HDR"); + } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i = 0; i < width; ++i) + stbi__hdr_convert(hdr_data + (j * width + i) * req_comp, + scanline + i * 4, req_comp); + } + if (scanline) STBI_FREE(scanline); + } + + return hdr_data; } -static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) -{ - char buffer[STBI__HDR_BUFLEN]; - char *token; - int valid = 0; - int dummy; +static int stbi__hdr_info(stbi__context* s, int* x, int* y, int* comp) { + char buffer[STBI__HDR_BUFLEN]; + char* token; + int valid = 0; + int dummy; - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; - if (stbi__hdr_test(s) == 0) { - stbi__rewind( s ); - return 0; - } + if (stbi__hdr_test(s) == 0) { + stbi__rewind(s); + return 0; + } - for(;;) { - token = stbi__hdr_gettoken(s,buffer); - if (token[0] == 0) break; - if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; - } + for (;;) { + token = stbi__hdr_gettoken(s, buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } - if (!valid) { - stbi__rewind( s ); - return 0; - } - token = stbi__hdr_gettoken(s,buffer); - if (strncmp(token, "-Y ", 3)) { - stbi__rewind( s ); - return 0; - } - token += 3; - *y = (int) strtol(token, &token, 10); - while (*token == ' ') ++token; - if (strncmp(token, "+X ", 3)) { - stbi__rewind( s ); - return 0; - } - token += 3; - *x = (int) strtol(token, NULL, 10); - *comp = 3; - return 1; + if (!valid) { + stbi__rewind(s); + return 0; + } + token = stbi__hdr_gettoken(s, buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind(s); + return 0; + } + token += 3; + *y = (int)strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind(s); + return 0; + } + token += 3; + *x = (int)strtol(token, NULL, 10); + *comp = 3; + return 1; } -#endif // STBI_NO_HDR +#endif // STBI_NO_HDR #ifndef STBI_NO_BMP -static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) -{ - void *p; - stbi__bmp_data info; +static int stbi__bmp_info(stbi__context* s, int* x, int* y, int* comp) { + void* p; + stbi__bmp_data info; - info.all_a = 255; - p = stbi__bmp_parse_header(s, &info); - if (p == NULL) { - stbi__rewind( s ); - return 0; - } - if (x) *x = s->img_x; - if (y) *y = s->img_y; - if (comp) { - if (info.bpp == 24 && info.ma == 0xff000000) - *comp = 3; - else - *comp = info.ma ? 4 : 3; - } - return 1; + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind(s); + return 0; + } + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; } #endif #ifndef STBI_NO_PSD -static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) -{ - int channelCount, dummy, depth; - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - if (stbi__get32be(s) != 0x38425053) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 1) { - stbi__rewind( s ); - return 0; - } - stbi__skip(s, 6); - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) { - stbi__rewind( s ); - return 0; - } - *y = stbi__get32be(s); - *x = stbi__get32be(s); - depth = stbi__get16be(s); - if (depth != 8 && depth != 16) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 3) { - stbi__rewind( s ); - return 0; - } - *comp = 4; - return 1; +static int stbi__psd_info(stbi__context* s, int* x, int* y, int* comp) { + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind(s); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind(s); + return 0; + } + *comp = 4; + return 1; } -static int stbi__psd_is16(stbi__context *s) -{ - int channelCount, depth; - if (stbi__get32be(s) != 0x38425053) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 1) { - stbi__rewind( s ); - return 0; - } - stbi__skip(s, 6); - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) { - stbi__rewind( s ); - return 0; - } - STBI_NOTUSED(stbi__get32be(s)); - STBI_NOTUSED(stbi__get32be(s)); - depth = stbi__get16be(s); - if (depth != 16) { - stbi__rewind( s ); - return 0; - } - return 1; +static int stbi__psd_is16(stbi__context* s) { + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind(s); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind(s); + return 0; + } + return 1; } #endif #ifndef STBI_NO_PIC -static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) -{ - int act_comp=0,num_packets=0,chained,dummy; - stbi__pic_packet packets[10]; +static int stbi__pic_info(stbi__context* s, int* x, int* y, int* comp) { + int act_comp = 0, num_packets = 0, chained, dummy; + stbi__pic_packet packets[10]; - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; - if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { - stbi__rewind(s); - return 0; - } + if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } - stbi__skip(s, 88); + stbi__skip(s, 88); - *x = stbi__get16be(s); - *y = stbi__get16be(s); - if (stbi__at_eof(s)) { - stbi__rewind( s); - return 0; - } - if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { - stbi__rewind( s ); - return 0; - } + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind(s); + return 0; + } + if ((*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind(s); + return 0; + } - stbi__skip(s, 8); + stbi__skip(s, 8); - do { - stbi__pic_packet *packet; + do { + stbi__pic_packet* packet; - if (num_packets==sizeof(packets)/sizeof(packets[0])) - return 0; + if (num_packets == sizeof(packets) / sizeof(packets[0])) return 0; - packet = &packets[num_packets++]; - chained = stbi__get8(s); - packet->size = stbi__get8(s); - packet->type = stbi__get8(s); - packet->channel = stbi__get8(s); - act_comp |= packet->channel; + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; - if (stbi__at_eof(s)) { - stbi__rewind( s ); - return 0; - } - if (packet->size != 8) { - stbi__rewind( s ); - return 0; - } - } while (chained); + if (stbi__at_eof(s)) { + stbi__rewind(s); + return 0; + } + if (packet->size != 8) { + stbi__rewind(s); + return 0; + } + } while (chained); - *comp = (act_comp & 0x10 ? 4 : 3); + *comp = (act_comp & 0x10 ? 4 : 3); - return 1; + return 1; } #endif @@ -7491,206 +8116,208 @@ static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) #ifndef STBI_NO_PNM -static int stbi__pnm_test(stbi__context *s) -{ - char p, t; - p = (char) stbi__get8(s); - t = (char) stbi__get8(s); - if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind( s ); - return 0; - } - return 1; +static int stbi__pnm_test(stbi__context* s) { + char p, t; + p = (char)stbi__get8(s); + t = (char)stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + return 1; } -static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *out; - STBI_NOTUSED(ri); +static void* stbi__pnm_load(stbi__context* s, int* x, int* y, int* comp, + int req_comp, stbi__result_info* ri) { + stbi_uc* out; + STBI_NOTUSED(ri); - ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); - if (ri->bits_per_channel == 0) - return 0; + ri->bits_per_channel = + stbi__pnm_info(s, (int*)&s->img_x, (int*)&s->img_y, (int*)&s->img_n); + if (ri->bits_per_channel == 0) return 0; - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_y > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) + return stbi__errpuc("too large", "Very large image (corrupt?)"); - *x = s->img_x; - *y = s->img_y; - if (comp) *comp = s->img_n; + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; - if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) - return stbi__errpuc("too large", "PNM too large"); + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, + ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); - out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { - STBI_FREE(out); - return stbi__errpuc("bad PNM", "PNM file truncated"); - } + out = (stbi_uc*)stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, + ri->bits_per_channel / 8, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__getn( + s, out, + s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } - if (req_comp && req_comp != s->img_n) { - if (ri->bits_per_channel == 16) { - out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); - } else { - out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); - } - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - return out; + if (req_comp && req_comp != s->img_n) { + if (ri->bits_per_channel == 16) { + out = (stbi_uc*)stbi__convert_format16( + (stbi__uint16*)out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, + s->img_y); + } + if (out == NULL) + return out; // stbi__convert_format frees input on failure + } + return out; } -static int stbi__pnm_isspace(char c) -{ - return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +static int stbi__pnm_isspace(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || + c == '\r'; } -static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) -{ - for (;;) { - while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) - *c = (char) stbi__get8(s); +static void stbi__pnm_skip_whitespace(stbi__context* s, char* c) { + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char)stbi__get8(s); - if (stbi__at_eof(s) || *c != '#') - break; + if (stbi__at_eof(s) || *c != '#') break; - while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) - *c = (char) stbi__get8(s); - } + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r') + *c = (char)stbi__get8(s); + } } -static int stbi__pnm_isdigit(char c) -{ - return c >= '0' && c <= '9'; +static int stbi__pnm_isdigit(char c) { return c >= '0' && c <= '9'; } + +static int stbi__pnm_getinteger(stbi__context* s, char* c) { + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value * 10 + (*c - '0'); + *c = (char)stbi__get8(s); + if ((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err( + "integer parse overflow", + "Parsing an integer in the PPM header overflowed a 32-bit int"); + } + + return value; } -static int stbi__pnm_getinteger(stbi__context *s, char *c) -{ - int value = 0; +static int stbi__pnm_info(stbi__context* s, int* x, int* y, int* comp) { + int maxv, dummy; + char c, p, t; - while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { - value = value*10 + (*c - '0'); - *c = (char) stbi__get8(s); - if((value > 214748364) || (value == 214748364 && *c > '7')) - return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); - } + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; - return value; + stbi__rewind(s); + + // Get identifier + p = (char)stbi__get8(s); + t = (char)stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = + (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char)stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + if (*x == 0) + return stbi__err("invalid width", + "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", + "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + if (maxv > 65535) + return stbi__err("max value > 65535", + "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; + else + return 8; } -static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) -{ - int maxv, dummy; - char c, p, t; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - stbi__rewind(s); - - // Get identifier - p = (char) stbi__get8(s); - t = (char) stbi__get8(s); - if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind(s); - return 0; - } - - *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm - - c = (char) stbi__get8(s); - stbi__pnm_skip_whitespace(s, &c); - - *x = stbi__pnm_getinteger(s, &c); // read width - if(*x == 0) - return stbi__err("invalid width", "PPM image header had zero or overflowing width"); - stbi__pnm_skip_whitespace(s, &c); - - *y = stbi__pnm_getinteger(s, &c); // read height - if (*y == 0) - return stbi__err("invalid width", "PPM image header had zero or overflowing width"); - stbi__pnm_skip_whitespace(s, &c); - - maxv = stbi__pnm_getinteger(s, &c); // read max value - if (maxv > 65535) - return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); - else if (maxv > 255) - return 16; - else - return 8; -} - -static int stbi__pnm_is16(stbi__context *s) -{ - if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) - return 1; - return 0; +static int stbi__pnm_is16(stbi__context* s) { + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) return 1; + return 0; } #endif -static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) -{ - #ifndef STBI_NO_JPEG - if (stbi__jpeg_info(s, x, y, comp)) return 1; - #endif +static int stbi__info_main(stbi__context* s, int* x, int* y, int* comp) { +#ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; +#endif - #ifndef STBI_NO_PNG - if (stbi__png_info(s, x, y, comp)) return 1; - #endif +#ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; +#endif - #ifndef STBI_NO_GIF - if (stbi__gif_info(s, x, y, comp)) return 1; - #endif +#ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; +#endif - #ifndef STBI_NO_BMP - if (stbi__bmp_info(s, x, y, comp)) return 1; - #endif +#ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; +#endif - #ifndef STBI_NO_PSD - if (stbi__psd_info(s, x, y, comp)) return 1; - #endif +#ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; +#endif - #ifndef STBI_NO_PIC - if (stbi__pic_info(s, x, y, comp)) return 1; - #endif +#ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; +#endif - #ifndef STBI_NO_PNM - if (stbi__pnm_info(s, x, y, comp)) return 1; - #endif +#ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; +#endif - #ifndef STBI_NO_HDR - if (stbi__hdr_info(s, x, y, comp)) return 1; - #endif +#ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; +#endif - // test tga last because it's a crappy test! - #ifndef STBI_NO_TGA - if (stbi__tga_info(s, x, y, comp)) - return 1; - #endif - return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +// test tga last because it's a crappy test! +#ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) return 1; +#endif + return stbi__err("unknown image type", + "Image not of any known type, or corrupt"); } -static int stbi__is_16_main(stbi__context *s) -{ - #ifndef STBI_NO_PNG - if (stbi__png_is16(s)) return 1; - #endif +static int stbi__is_16_main(stbi__context* s) { +#ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; +#endif - #ifndef STBI_NO_PSD - if (stbi__psd_is16(s)) return 1; - #endif +#ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; +#endif - #ifndef STBI_NO_PNM - if (stbi__pnm_is16(s)) return 1; - #endif - return 0; +#ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; +#endif + return 0; } #ifndef STBI_NO_STDIO -STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) -{ - FILE *f = stbi__fopen(filename, "rb"); +STBIDEF int stbi_info(char const* filename, int* x, int* y, int* comp) { + FILE* f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_info_from_file(f, x, y, comp); @@ -7698,20 +8325,18 @@ STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) return result; } -STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) -{ - int r; - stbi__context s; - long pos = ftell(f); - stbi__start_file(&s, f); - r = stbi__info_main(&s,x,y,comp); - fseek(f,pos,SEEK_SET); - return r; +STBIDEF int stbi_info_from_file(FILE* f, int* x, int* y, int* comp) { + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s, x, y, comp); + fseek(f, pos, SEEK_SET); + return r; } -STBIDEF int stbi_is_16_bit(char const *filename) -{ - FILE *f = stbi__fopen(filename, "rb"); +STBIDEF int stbi_is_16_bit(char const* filename) { + FILE* f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_is_16_bit_from_file(f); @@ -7719,54 +8344,51 @@ STBIDEF int stbi_is_16_bit(char const *filename) return result; } -STBIDEF int stbi_is_16_bit_from_file(FILE *f) -{ - int r; - stbi__context s; - long pos = ftell(f); - stbi__start_file(&s, f); - r = stbi__is_16_main(&s); - fseek(f,pos,SEEK_SET); - return r; +STBIDEF int stbi_is_16_bit_from_file(FILE* f) { + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f, pos, SEEK_SET); + return r; } -#endif // !STBI_NO_STDIO +#endif // !STBI_NO_STDIO -STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__info_main(&s,x,y,comp); +STBIDEF int stbi_info_from_memory(stbi_uc const* buffer, int len, int* x, + int* y, int* comp) { + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__info_main(&s, x, y, comp); } -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); - return stbi__info_main(&s,x,y,comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const* c, void* user, + int* x, int* y, int* comp) { + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)c, user); + return stbi__info_main(&s, x, y, comp); } -STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__is_16_main(&s); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const* buffer, int len) { + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__is_16_main(&s); } -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); - return stbi__is_16_main(&s); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const* c, + void* user) { + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks*)c, user); + return stbi__is_16_main(&s); } -#endif // STB_IMAGE_IMPLEMENTATION +#endif // STB_IMAGE_IMPLEMENTATION /* revision history: - 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs - 2.19 (2018-02-11) fix warning - 2.18 (2018-01-30) fix warnings - 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and + platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix + warnings 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug 1-bit BMP *_is_16_bit api avoid warnings @@ -7781,13 +8403,11 @@ STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user warning fixes; disable run-time SSE detection on gcc; uniform handling of optional "return" values; thread-safe initialization of zlib tables - 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs - 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now - 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes - 2.11 (2016-04-02) allocate large structures on the stack - remove white matting for transparent PSD - fix reported channel count for PNG & BMP - re-enable SSE2 in non-gcc 64-bit + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet + JPGs 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now 2.12 + (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) + allocate large structures on the stack remove white matting for transparent + PSD fix reported channel count for PNG & BMP re-enable SSE2 in non-gcc 64-bit support RGB-formatted JPEG read 16-bit PNGs (only as 8-bit) 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED @@ -7795,11 +8415,9 @@ STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user 16-bit-per-pixel TGA (not bit-per-component) info() for TGA could break due to .hdr handling info() for BMP to shares code instead of sloppy parse - can use STBI_REALLOC_SIZED if allocator doesn't support realloc - code cleanup - 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA - 2.07 (2015-09-13) fix compiler warnings - partial animated GIF support + can use STBI_REALLOC_SIZED if allocator doesn't support + realloc code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD + as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA @@ -7810,23 +8428,18 @@ STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user stbi_set_flip_vertically_on_load (nguillemot) fix NEON support; fix mingw support 2.02 (2015-01-19) fix incorrect assert, fix warning - 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 - 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG - 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) - progressive JPEG (stb) - PGM/PPM support (Ken Miller) - STBI_MALLOC,STBI_REALLOC,STBI_FREE + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit + without -msse2 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG 2.00 + (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) progressive + JPEG (stb) PGM/PPM support (Ken Miller) STBI_MALLOC,STBI_REALLOC,STBI_FREE GIF bugfix -- seemingly never worked STBI_NO_*, STBI_ONLY_* 1.48 (2014-12-14) fix incorrectly-named assert() - 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) - optimize PNG (ryg) - fix bug in interlaced PNG with user-specified channel count (stb) - 1.46 (2014-08-26) - fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG - 1.45 (2014-08-16) - fix MSVC-ARM internal compiler error by wrapping malloc - 1.44 (2014-08-07) + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar + Cornut & stb) optimize PNG (ryg) fix bug in interlaced PNG with + user-specified channel count (stb) 1.46 (2014-08-26) fix broken tRNS chunk + (colorkey-style transparency) in non-paletted PNG 1.45 (2014-08-16) fix + MSVC-ARM internal compiler error by wrapping malloc 1.44 (2014-08-07) various warning fixes from Ronny Chevalier 1.43 (2014-07-15) fix MSVC-only compiler problem in code changed in 1.42 @@ -7835,73 +8448,48 @@ STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user fixes to stbi__cleanup_jpeg path added STBI_ASSERT to avoid requiring assert.h 1.41 (2014-06-25) - fix search&replace from 1.36 that messed up comments/error messages - 1.40 (2014-06-22) - fix gcc struct-initialization warning - 1.39 (2014-06-15) - fix to TGA optimization when req_comp != number of components in TGA; - fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) - add support for BMP version 5 (more ignored fields) - 1.38 (2014-06-06) - suppress MSVC warnings on integer casts truncating values - fix accidental rename of 'skip' field of I/O - 1.37 (2014-06-04) - remove duplicate typedef - 1.36 (2014-06-03) - convert to header file single-file library - if de-iphone isn't set, load iphone images color-swapped instead of returning NULL - 1.35 (2014-05-27) - various warnings - fix broken STBI_SIMD path - fix bug where stbi_load_from_file no longer left file pointer in correct place - fix broken non-easy path for 32-bit BMP (possibly never used) - TGA optimization by Arseny Kapoulkine - 1.34 (unknown) - use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case - 1.33 (2011-07-14) - make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements - 1.32 (2011-07-13) - support for "info" function for all supported filetypes (SpartanJ) - 1.31 (2011-06-20) - a few more leak fixes, bug in PNG handling (SpartanJ) - 1.30 (2011-06-11) - added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + fix search&replace from 1.36 that messed up comments/error + messages 1.40 (2014-06-22) fix gcc struct-initialization warning 1.39 + (2014-06-15) fix to TGA optimization when req_comp != number of components in + TGA; fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my + test suite) add support for BMP version 5 (more ignored fields) 1.38 + (2014-06-06) suppress MSVC warnings on integer casts truncating values fix + accidental rename of 'skip' field of I/O 1.37 (2014-06-04) remove duplicate + typedef 1.36 (2014-06-03) convert to header file single-file library if + de-iphone isn't set, load iphone images color-swapped instead of returning + NULL 1.35 (2014-05-27) various warnings fix broken STBI_SIMD path fix bug + where stbi_load_from_file no longer left file pointer in correct place fix + broken non-easy path for 32-bit BMP (possibly never used) TGA optimization by + Arseny Kapoulkine 1.34 (unknown) use STBI_NOTUSED in + stbi__resample_row_generic(), fix one more leak in tga failure case 1.33 + (2011-07-14) make stbi_is_hdr work in STBI_NO_HDR (as specified), minor + compiler-friendly improvements 1.32 (2011-07-13) support for "info" function + for all supported filetypes (SpartanJ) 1.31 (2011-06-20) a few more leak + fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to + load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions - removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway - error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) - fix inefficiency in decoding 32-bit BMP (David Woo) - 1.29 (2010-08-16) - various warning fixes from Aurelien Pocheville - 1.28 (2010-08-01) - fix bug in GIF palette transparency (SpartanJ) - 1.27 (2010-08-01) - cast-to-stbi_uc to fix warnings - 1.26 (2010-07-24) - fix bug in file buffering for PNG reported by SpartanJ - 1.25 (2010-07-17) - refix trans_data warning (Won Chun) - 1.24 (2010-07-12) - perf improvements reading from files on platforms with lock-heavy fgetc() - minor perf improvements for jpeg - deprecated type-specific functions so we'll get feedback if they're needed - attempt to fix trans_data warning (Won Chun) - 1.23 fixed bug in iPhone support - 1.22 (2010-07-10) - removed image *writing* support - stbi_info support from Jetro Lauha - GIF support from Jean-Marc Lienher + removed support for installable file formats (stbi_loader) -- + would have been broken for IO callbacks anyway error cases in bmp and tga + give messages and don't leak (Raymond Barbiero, grisha) fix inefficiency in + decoding 32-bit BMP (David Woo) 1.29 (2010-08-16) various warning fixes from + Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency + (SpartanJ) 1.27 (2010-08-01) cast-to-stbi_uc to fix warnings 1.26 + (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ 1.25 + (2010-07-17) refix trans_data warning (Won Chun) 1.24 (2010-07-12) perf + improvements reading from files on platforms with lock-heavy fgetc() minor + perf improvements for jpeg deprecated type-specific functions so we'll get + feedback if they're needed attempt to fix trans_data warning (Won Chun) 1.23 + fixed bug in iPhone support 1.22 (2010-07-10) removed image *writing* + support stbi_info support from Jetro Lauha GIF support from Jean-Marc Lienher iPhone PNG-extensions from James Brown - warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) - 1.21 fix use of 'stbi_uc' in header (reported by jon blow) - 1.20 added support for Softimage PIC, by Tom Seddon - 1.19 bug in interlaced PNG corruption check (found by ryg) - 1.18 (2008-08-02) - fix a threading bug (local mutable static) - 1.17 support interlaced PNG - 1.16 major bugfix - stbi__convert_format converted one too many pixels - 1.15 initialize some fields for thread safety - 1.14 fix threadsafe conversion bug - header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. + Janez (U+017D)emva) 1.21 fix use of 'stbi_uc' in header (reported by jon + blow) 1.20 added support for Softimage PIC, by Tom Seddon 1.19 bug in + interlaced PNG corruption check (found by ryg) 1.18 (2008-08-02) fix a + threading bug (local mutable static) 1.17 support interlaced PNG 1.16 + major bugfix - stbi__convert_format converted one too many pixels 1.15 + initialize some fields for thread safety 1.14 fix threadsafe conversion + bug header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines @@ -7911,15 +8499,14 @@ STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again - 1.05 fix TGA loading to return correct *comp and use good luminance calc - 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free - 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR - 1.02 support for (subset of) HDR files, float interface for preferred access to them - 1.01 fix bug: possible bug in handling right-side up bmps... not sure - fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all - 1.00 interface to zlib that skips zlib header - 0.99 correct handling of alpha in palette - 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 1.05 fix TGA loading to return correct *comp and use good luminance + calc 1.04 default float alpha is 1, not 255; use 'void *' for + stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support + for (subset of) HDR files, float interface for preferred access to them 1.01 + fix bug: possible bug in handling right-side up bmps... not sure fix bug: the + stbi__bmp_load() and stbi__tga_load() functions didn't work at all 1.00 + interface to zlib that skips zlib header 0.99 correct handling of alpha in + palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding @@ -7932,8 +8519,8 @@ STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian - 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available - 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but + less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding @@ -7944,7 +8531,6 @@ STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user first released version */ - /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. diff --git a/4J.Render/stdafx.h b/4J.Render/stdafx.h index 0aa0f4359..274d433e1 100644 --- a/4J.Render/stdafx.h +++ b/4J.Render/stdafx.h @@ -5,4 +5,4 @@ #include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h" #endif -#endif //_4J_RENDER_STADAFX_H \ No newline at end of file +#endif //_4J_RENDER_STADAFX_H \ No newline at end of file diff --git a/4J.Storage/4J_Storage.cpp b/4J.Storage/4J_Storage.cpp index 50c11bbb8..f5a7b922a 100644 --- a/4J.Storage/4J_Storage.cpp +++ b/4J.Storage/4J_Storage.cpp @@ -12,66 +12,170 @@ C4JStorage::C4JStorage() : m_pStringTable(nullptr) {} void C4JStorage::Tick(void) {} -C4JStorage::EMessageResult C4JStorage::RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA, UINT uiOptionC, DWORD dwPad, - int(*Func)(void *, int, const C4JStorage::EMessageResult), void *lpParam, C4JStringTable *pStringTable, WCHAR *pwchFormatString, DWORD dwFocusButton) { +C4JStorage::EMessageResult C4JStorage::RequestMessageBox( + UINT uiTitle, UINT uiText, UINT* uiOptionA, UINT uiOptionC, DWORD dwPad, + int (*Func)(void*, int, const C4JStorage::EMessageResult), void* lpParam, + C4JStringTable* pStringTable, WCHAR* pwchFormatString, + DWORD dwFocusButton) { return EMessage_ResultAccept; } -C4JStorage::EMessageResult C4JStorage::GetMessageBoxResult() { return EMessage_Undefined; } +C4JStorage::EMessageResult C4JStorage::GetMessageBoxResult() { + return EMessage_Undefined; +} -bool C4JStorage::SetSaveDevice(int(*Func)(void *, const bool), void *lpParam, bool bForceResetOfSaveDevice) { return true; } +bool C4JStorage::SetSaveDevice(int (*Func)(void*, const bool), void* lpParam, + bool bForceResetOfSaveDevice) { + return true; +} -void C4JStorage::Init(unsigned int uiSaveVersion, LPCWSTR pwchDefaultSaveName, char *pszSavePackName, int iMinimumSaveSize, int(*Func)(void *, const ESavingMessage, int), void *lpParam, LPCSTR szGroupID) {} +void C4JStorage::Init(unsigned int uiSaveVersion, LPCWSTR pwchDefaultSaveName, + char* pszSavePackName, int iMinimumSaveSize, + int (*Func)(void*, const ESavingMessage, int), + void* lpParam, LPCSTR szGroupID) {} void C4JStorage::ResetSaveData() {} -void C4JStorage::SetDefaultSaveNameForKeyboardDisplay(LPCWSTR pwchDefaultSaveName) {} +void C4JStorage::SetDefaultSaveNameForKeyboardDisplay( + LPCWSTR pwchDefaultSaveName) {} void C4JStorage::SetSaveTitle(LPCWSTR pwchDefaultSaveName) {} -bool C4JStorage::GetSaveUniqueNumber(INT *piVal) { if (piVal) *piVal = 0; return true; } -bool C4JStorage::GetSaveUniqueFilename(char *pszName) { if (pszName) pszName[0] = '\0'; return true; } -void C4JStorage::SetSaveUniqueFilename(char *szFilename) {} -void C4JStorage::SetState(ESaveGameControlState eControlState, int(*Func)(void *, const bool), void *lpParam) {} +bool C4JStorage::GetSaveUniqueNumber(INT* piVal) { + if (piVal) *piVal = 0; + return true; +} +bool C4JStorage::GetSaveUniqueFilename(char* pszName) { + if (pszName) pszName[0] = '\0'; + return true; +} +void C4JStorage::SetSaveUniqueFilename(char* szFilename) {} +void C4JStorage::SetState(ESaveGameControlState eControlState, + int (*Func)(void*, const bool), void* lpParam) {} void C4JStorage::SetSaveDisabled(bool bDisable) {} bool C4JStorage::GetSaveDisabled(void) { return false; } unsigned int C4JStorage::GetSaveSize() { return 0; } -void C4JStorage::GetSaveData(void *pvData, unsigned int *puiBytes) { if (puiBytes) *puiBytes = 0; } -PVOID C4JStorage::AllocateSaveData(unsigned int uiBytes) { return malloc(uiBytes); } -void C4JStorage::SetSaveImages(PBYTE pbThumbnail, DWORD dwThumbnailBytes, PBYTE pbImage, DWORD dwImageBytes, PBYTE pbTextData, DWORD dwTextDataBytes) {} -C4JStorage::ESaveGameState C4JStorage::SaveSaveData(int(*Func)(void *, const bool), void *lpParam) { return ESaveGame_Idle; } -void C4JStorage::CopySaveDataToNewSave(PBYTE pbThumbnail, DWORD cbThumbnail, WCHAR *wchNewName, int(*Func)(void *lpParam, bool), void *lpParam) {} +void C4JStorage::GetSaveData(void* pvData, unsigned int* puiBytes) { + if (puiBytes) *puiBytes = 0; +} +PVOID C4JStorage::AllocateSaveData(unsigned int uiBytes) { + return malloc(uiBytes); +} +void C4JStorage::SetSaveImages(PBYTE pbThumbnail, DWORD dwThumbnailBytes, + PBYTE pbImage, DWORD dwImageBytes, + PBYTE pbTextData, DWORD dwTextDataBytes) {} +C4JStorage::ESaveGameState C4JStorage::SaveSaveData(int (*Func)(void*, + const bool), + void* lpParam) { + return ESaveGame_Idle; +} +void C4JStorage::CopySaveDataToNewSave(PBYTE pbThumbnail, DWORD cbThumbnail, + WCHAR* wchNewName, + int (*Func)(void* lpParam, bool), + void* lpParam) {} void C4JStorage::SetSaveDeviceSelected(unsigned int uiPad, bool bSelected) {} bool C4JStorage::GetSaveDeviceSelected(unsigned int iPad) { return true; } -C4JStorage::ESaveGameState C4JStorage::DoesSaveExist(bool *pbExists) { if (pbExists) *pbExists = false; return ESaveGame_Idle; } +C4JStorage::ESaveGameState C4JStorage::DoesSaveExist(bool* pbExists) { + if (pbExists) *pbExists = false; + return ESaveGame_Idle; +} bool C4JStorage::EnoughSpaceForAMinSaveGame() { return true; } void C4JStorage::SetSaveMessageVPosition(float fY) {} -C4JStorage::ESaveGameState C4JStorage::GetSavesInfo(int iPad, int(*Func)(void *lpParam, SAVE_DETAILS *pSaveDetails, const bool), void *lpParam, char *pszSavePackName) { return ESaveGame_Idle; } +C4JStorage::ESaveGameState C4JStorage::GetSavesInfo( + int iPad, + int (*Func)(void* lpParam, SAVE_DETAILS* pSaveDetails, const bool), + void* lpParam, char* pszSavePackName) { + return ESaveGame_Idle; +} PSAVE_DETAILS C4JStorage::ReturnSavesInfo() { return nullptr; } void C4JStorage::ClearSavesInfo() {} -C4JStorage::ESaveGameState C4JStorage::LoadSaveDataThumbnail(PSAVE_INFO pSaveInfo, int(*Func)(void *lpParam, std::uint8_t *thumbnailData, unsigned int thumbnailBytes), void *lpParam) { return ESaveGame_Idle; } -void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, XCONTENT_DATA &xContentData) { memset(&xContentData, 0, sizeof(xContentData)); } -void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, PBYTE *ppbImageData, DWORD *pdwImageBytes) { if (ppbImageData) *ppbImageData = nullptr; if (pdwImageBytes) *pdwImageBytes = 0; } -C4JStorage::ESaveGameState C4JStorage::LoadSaveData(PSAVE_INFO pSaveInfo, int(*Func)(void *lpParam, const bool, const bool), void *lpParam) { return ESaveGame_Idle; } -C4JStorage::ESaveGameState C4JStorage::DeleteSaveData(PSAVE_INFO pSaveInfo, int(*Func)(void *lpParam, const bool), void *lpParam) { return ESaveGame_Idle; } -void C4JStorage::RegisterMarketplaceCountsCallback(int(*Func)(void *lpParam, C4JStorage::DLC_TMS_DETAILS *, int), void *lpParam) {} -void C4JStorage::SetDLCPackageRoot(char *pszDLCRoot) {} -C4JStorage::EDLCStatus C4JStorage::GetDLCOffers(int iPad, int(*Func)(void *, int, std::uint32_t, int), void *lpParam, DWORD dwOfferTypesBitmask) { return EDLC_NoOffers; } +C4JStorage::ESaveGameState C4JStorage::LoadSaveDataThumbnail( + PSAVE_INFO pSaveInfo, + int (*Func)(void* lpParam, std::uint8_t* thumbnailData, + unsigned int thumbnailBytes), + void* lpParam) { + return ESaveGame_Idle; +} +void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, + XCONTENT_DATA& xContentData) { + memset(&xContentData, 0, sizeof(xContentData)); +} +void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, PBYTE* ppbImageData, + DWORD* pdwImageBytes) { + if (ppbImageData) *ppbImageData = nullptr; + if (pdwImageBytes) *pdwImageBytes = 0; +} +C4JStorage::ESaveGameState C4JStorage::LoadSaveData( + PSAVE_INFO pSaveInfo, int (*Func)(void* lpParam, const bool, const bool), + void* lpParam) { + return ESaveGame_Idle; +} +C4JStorage::ESaveGameState C4JStorage::DeleteSaveData(PSAVE_INFO pSaveInfo, + int (*Func)(void* lpParam, + const bool), + void* lpParam) { + return ESaveGame_Idle; +} +void C4JStorage::RegisterMarketplaceCountsCallback( + int (*Func)(void* lpParam, C4JStorage::DLC_TMS_DETAILS*, int), + void* lpParam) {} +void C4JStorage::SetDLCPackageRoot(char* pszDLCRoot) {} +C4JStorage::EDLCStatus C4JStorage::GetDLCOffers( + int iPad, int (*Func)(void*, int, std::uint32_t, int), void* lpParam, + DWORD dwOfferTypesBitmask) { + return EDLC_NoOffers; +} DWORD C4JStorage::CancelGetDLCOffers() { return 0; } void C4JStorage::ClearDLCOffers() {} -XMARKETPLACE_CONTENTOFFER_INFO& C4JStorage::GetOffer(DWORD dw) { return s_dummyOffer; } +XMARKETPLACE_CONTENTOFFER_INFO& C4JStorage::GetOffer(DWORD dw) { + return s_dummyOffer; +} int C4JStorage::GetOfferCount() { return 0; } -DWORD C4JStorage::InstallOffer(int iOfferIDC, __uint64 *ullOfferIDA, int(*Func)(void *, int, int), void *lpParam, bool bTrial) { return 0; } +DWORD C4JStorage::InstallOffer(int iOfferIDC, __uint64* ullOfferIDA, + int (*Func)(void*, int, int), void* lpParam, + bool bTrial) { + return 0; +} DWORD C4JStorage::GetAvailableDLCCount(int iPad) { return 0; } -C4JStorage::EDLCStatus C4JStorage::GetInstalledDLC(int iPad, int(*Func)(void *, int, int), void *lpParam) { return EDLC_NoInstalledDLC; } +C4JStorage::EDLCStatus C4JStorage::GetInstalledDLC(int iPad, + int (*Func)(void*, int, int), + void* lpParam) { + return EDLC_NoInstalledDLC; +} XCONTENT_DATA& C4JStorage::GetDLC(DWORD dw) { return s_dummyContentData; } -std::uint32_t C4JStorage::MountInstalledDLC(int iPad, std::uint32_t dwDLC, int(*Func)(void *, int, std::uint32_t, std::uint32_t), void *lpParam, LPCSTR szMountDrive) { return 0; } +std::uint32_t C4JStorage::MountInstalledDLC( + int iPad, std::uint32_t dwDLC, + int (*Func)(void*, int, std::uint32_t, std::uint32_t), void* lpParam, + LPCSTR szMountDrive) { + return 0; +} DWORD C4JStorage::UnmountInstalledDLC(LPCSTR szMountDrive) { return 0; } -void C4JStorage::GetMountedDLCFileList(const char *szMountDrive, std::vector &fileList) { fileList.clear(); } +void C4JStorage::GetMountedDLCFileList(const char* szMountDrive, + std::vector& fileList) { + fileList.clear(); +} std::string C4JStorage::GetMountedPath(std::string szMount) { return ""; } -C4JStorage::ETMSStatus C4JStorage::ReadTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, C4JStorage::eTMS_FileType eFileType, - WCHAR *pwchFilename, BYTE **ppBuffer, DWORD *pdwBufferSize, int(*Func)(void *, WCHAR *, int, bool, int), void *lpParam, int iAction) { return ETMSStatus_Fail; } -bool C4JStorage::WriteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, WCHAR *pwchFilename, BYTE *pBuffer, DWORD dwBufferSize) { return false; } -bool C4JStorage::DeleteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, WCHAR *pwchFilename) { return false; } -void C4JStorage::StoreTMSPathName(WCHAR *pwchName) {} -C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile(int iPad, C4JStorage::eGlobalStorage eStorageFacility, C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename, int(*Func)(void *, int, int, PTMSPP_FILEDATA, LPCSTR), void *lpParam, int iUserData) { return ETMSStatus_Fail; } -unsigned int C4JStorage::CRC(unsigned char *buf, int len) { +C4JStorage::ETMSStatus C4JStorage::ReadTMSFile( + int iQuadrant, eGlobalStorage eStorageFacility, + C4JStorage::eTMS_FileType eFileType, WCHAR* pwchFilename, BYTE** ppBuffer, + DWORD* pdwBufferSize, int (*Func)(void*, WCHAR*, int, bool, int), + void* lpParam, int iAction) { + return ETMSStatus_Fail; +} +bool C4JStorage::WriteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, + WCHAR* pwchFilename, BYTE* pBuffer, + DWORD dwBufferSize) { + return false; +} +bool C4JStorage::DeleteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, + WCHAR* pwchFilename) { + return false; +} +void C4JStorage::StoreTMSPathName(WCHAR* pwchName) {} +C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile( + int iPad, C4JStorage::eGlobalStorage eStorageFacility, + C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename, + int (*Func)(void*, int, int, PTMSPP_FILEDATA, LPCSTR), void* lpParam, + int iUserData) { + return ETMSStatus_Fail; +} +unsigned int C4JStorage::CRC(unsigned char* buf, int len) { unsigned int crc = 0xFFFFFFFF; for (int i = 0; i < len; i++) { crc ^= buf[i]; @@ -82,11 +186,26 @@ unsigned int C4JStorage::CRC(unsigned char *buf, int len) { return ~crc; } -int C4JStorage::AddSubfile(int regionIndex) { (void)regionIndex; return 0; } +int C4JStorage::AddSubfile(int regionIndex) { + (void)regionIndex; + return 0; +} unsigned int C4JStorage::GetSubfileCount() { return 0; } -void C4JStorage::GetSubfileDetails(unsigned int i, int* regionIndex, void** data, unsigned int* size) { (void)i; if(regionIndex) *regionIndex=0; if(data) *data=0; if(size) *size=0; } +void C4JStorage::GetSubfileDetails(unsigned int i, int* regionIndex, + void** data, unsigned int* size) { + (void)i; + if (regionIndex) *regionIndex = 0; + if (data) *data = 0; + if (size) *size = 0; +} void C4JStorage::ResetSubfiles() {} -void C4JStorage::UpdateSubfile(int index, void* data, unsigned int size) { (void)index; (void)data; (void)size; } -void C4JStorage::SaveSubfiles(int (*Func)(void*, const bool), void* param) { if(Func) Func(param, true); } +void C4JStorage::UpdateSubfile(int index, void* data, unsigned int size) { + (void)index; + (void)data; + (void)size; +} +void C4JStorage::SaveSubfiles(int (*Func)(void*, const bool), void* param) { + if (Func) Func(param, true); +} C4JStorage::ESaveGameState C4JStorage::GetSaveState() { return ESaveGame_Idle; } void C4JStorage::ContinueIncompleteOperation() {} diff --git a/4J.Storage/4J_Storage.h b/4J.Storage/4J_Storage.h index 973352e6b..b52c4fa8e 100644 --- a/4J.Storage/4J_Storage.h +++ b/4J.Storage/4J_Storage.h @@ -1,354 +1,380 @@ #pragma once - #include #include -//#include +// #include class C4JStringTable; -#define MAX_DISPLAYNAME_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3 -#define MAX_DETAILS_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3 -#define MAX_SAVEFILENAME_LENGTH 32 // CELL_SAVEDATA_DIRNAME_SIZE +#define MAX_DISPLAYNAME_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3 +#define MAX_DETAILS_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3 +#define MAX_SAVEFILENAME_LENGTH 32 // CELL_SAVEDATA_DIRNAME_SIZE -typedef struct -{ - time_t modifiedTime; - unsigned int dataSize; - unsigned int thumbnailSize; -} -CONTAINER_METADATA; +typedef struct { + time_t modifiedTime; + unsigned int dataSize; + unsigned int thumbnailSize; +} CONTAINER_METADATA; -typedef struct -{ - char UTF8SaveFilename[MAX_SAVEFILENAME_LENGTH]; - char UTF8SaveTitle[MAX_DISPLAYNAME_LENGTH]; - CONTAINER_METADATA metaData; - PBYTE thumbnailData; -} -SAVE_INFO,*PSAVE_INFO; +typedef struct { + char UTF8SaveFilename[MAX_SAVEFILENAME_LENGTH]; + char UTF8SaveTitle[MAX_DISPLAYNAME_LENGTH]; + CONTAINER_METADATA metaData; + PBYTE thumbnailData; +} SAVE_INFO, *PSAVE_INFO; -typedef struct -{ - int iSaveC; - PSAVE_INFO SaveInfoA; -} -SAVE_DETAILS,*PSAVE_DETAILS; +typedef struct { + int iSaveC; + PSAVE_INFO SaveInfoA; +} SAVE_DETAILS, *PSAVE_DETAILS; -typedef std::vector OfferDataArray; -typedef std::vector XContentDataArray; -//typedef std::vector SaveDetailsArray; +typedef std::vector OfferDataArray; +typedef std::vector XContentDataArray; +// typedef std::vector SaveDetailsArray; // Current version of the dlc data creator #define CURRENT_DLC_VERSION_NUM 3 -class C4JStorage -{ - +class C4JStorage { public: - // Structs defined in the DLC_Creator, but added here to be used in the app - typedef struct - { - unsigned int uiFileSize; - DWORD dwType; - DWORD dwWchCount; // count of WCHAR in next array - WCHAR wchFile[1]; - } - DLC_FILE_DETAILS, *PDLC_FILE_DETAILS; + // Structs defined in the DLC_Creator, but added here to be used in the app + typedef struct { + unsigned int uiFileSize; + DWORD dwType; + DWORD dwWchCount; // count of WCHAR in next array + WCHAR wchFile[1]; + } DLC_FILE_DETAILS, *PDLC_FILE_DETAILS; - typedef struct - { - DWORD dwType; - DWORD dwWchCount; // count of WCHAR in next array; - WCHAR wchData[1]; // will be an array of size dwBytes - } - DLC_FILE_PARAM, *PDLC_FILE_PARAM; - // End of DLC_Creator structs + typedef struct { + DWORD dwType; + DWORD dwWchCount; // count of WCHAR in next array; + WCHAR wchData[1]; // will be an array of size dwBytes + } DLC_FILE_PARAM, *PDLC_FILE_PARAM; + // End of DLC_Creator structs - typedef struct - { - WCHAR wchDisplayName[XCONTENT_MAX_DISPLAYNAME_LENGTH]; - CHAR szFileName[XCONTENT_MAX_FILENAME_LENGTH]; - DWORD dwImageOffset; - DWORD dwImageBytes; - } - CACHEINFOSTRUCT; + typedef struct { + WCHAR wchDisplayName[XCONTENT_MAX_DISPLAYNAME_LENGTH]; + CHAR szFileName[XCONTENT_MAX_FILENAME_LENGTH]; + DWORD dwImageOffset; + DWORD dwImageBytes; + } CACHEINFOSTRUCT; - // structure to hold DLC info in TMS - typedef struct - { - DWORD dwVersion; - DWORD dwNewOffers; - DWORD dwTotalOffers; - DWORD dwInstalledTotalOffers; - BYTE bPadding[1024-sizeof(DWORD)*4]; // future expansion - } - DLC_TMS_DETAILS; + // structure to hold DLC info in TMS + typedef struct { + DWORD dwVersion; + DWORD dwNewOffers; + DWORD dwTotalOffers; + DWORD dwInstalledTotalOffers; + BYTE bPadding[1024 - sizeof(DWORD) * 4]; // future expansion + } DLC_TMS_DETAILS; - enum eGTS_FileTypes - { - eGTS_Type_Skin=0, - eGTS_Type_Cape, - eGTS_Type_MAX - }; + enum eGTS_FileTypes { eGTS_Type_Skin = 0, eGTS_Type_Cape, eGTS_Type_MAX }; - enum eGlobalStorage - { - //eGlobalStorage_GameClip=0, - eGlobalStorage_Title=0, - eGlobalStorage_TitleUser, - eGlobalStorage_Max - }; + enum eGlobalStorage { + // eGlobalStorage_GameClip=0, + eGlobalStorage_Title = 0, + eGlobalStorage_TitleUser, + eGlobalStorage_Max + }; - enum EMessageResult - { - EMessage_Undefined=0, - EMessage_Busy, - EMessage_Pending, - EMessage_Cancelled, - EMessage_ResultAccept, - EMessage_ResultDecline, - EMessage_ResultThirdOption, - EMessage_ResultFourthOption - }; + enum EMessageResult { + EMessage_Undefined = 0, + EMessage_Busy, + EMessage_Pending, + EMessage_Cancelled, + EMessage_ResultAccept, + EMessage_ResultDecline, + EMessage_ResultThirdOption, + EMessage_ResultFourthOption + }; - enum ESaveGameControlState - { - ESaveGameControl_Idle=0, - ESaveGameControl_Save, - ESaveGameControl_InternalRequestingDevice, - ESaveGameControl_InternalGetSaveName, - ESaveGameControl_InternalSaving, - ESaveGameControl_CopySave, - ESaveGameControl_CopyingSave, - }; + enum ESaveGameControlState { + ESaveGameControl_Idle = 0, + ESaveGameControl_Save, + ESaveGameControl_InternalRequestingDevice, + ESaveGameControl_InternalGetSaveName, + ESaveGameControl_InternalSaving, + ESaveGameControl_CopySave, + ESaveGameControl_CopyingSave, + }; - enum ESaveGameState - { - ESaveGame_Idle=0, - ESaveGame_Save, - ESaveGame_InternalRequestingDevice, - ESaveGame_InternalGetSaveName, - ESaveGame_InternalSaving, - ESaveGame_CopySave, - ESaveGame_CopyingSave, - ESaveGame_Load, - ESaveGame_GetSavesInfo, - ESaveGame_Rename, - ESaveGame_Delete, + enum ESaveGameState { + ESaveGame_Idle = 0, + ESaveGame_Save, + ESaveGame_InternalRequestingDevice, + ESaveGame_InternalGetSaveName, + ESaveGame_InternalSaving, + ESaveGame_CopySave, + ESaveGame_CopyingSave, + ESaveGame_Load, + ESaveGame_GetSavesInfo, + ESaveGame_Rename, + ESaveGame_Delete, - ESaveGame_GetSaveThumbnail // Not used as an actual state in the PS4, but the game expects this to be returned to indicate success when getting a thumbnail + ESaveGame_GetSaveThumbnail // Not used as an actual state in the PS4, + // but the game expects this to be returned + // to indicate success when getting a + // thumbnail - }; - enum ELoadGameStatus - { - ELoadGame_Idle=0, - ELoadGame_InProgress, - ELoadGame_NoSaves, - ELoadGame_ChangedDevice, - ELoadGame_DeviceRemoved - }; + }; + enum ELoadGameStatus { + ELoadGame_Idle = 0, + ELoadGame_InProgress, + ELoadGame_NoSaves, + ELoadGame_ChangedDevice, + ELoadGame_DeviceRemoved + }; - enum EDeleteGameStatus - { - EDeleteGame_Idle=0, - EDeleteGame_InProgress, - }; + enum EDeleteGameStatus { + EDeleteGame_Idle = 0, + EDeleteGame_InProgress, + }; + enum ESGIStatus { + ESGIStatus_Error = 0, + ESGIStatus_Idle, + ESGIStatus_ReadInProgress, + ESGIStatus_NoSaves, + }; - enum ESGIStatus - { - ESGIStatus_Error=0, - ESGIStatus_Idle, - ESGIStatus_ReadInProgress, - ESGIStatus_NoSaves, - }; + enum EDLCStatus { + EDLC_Error = 0, + EDLC_Idle, + EDLC_NoOffers, + EDLC_AlreadyEnumeratedAllOffers, + EDLC_NoInstalledDLC, + EDLC_Pending, + EDLC_LoadInProgress, + EDLC_Loaded, + EDLC_ChangedDevice + }; - enum EDLCStatus - { - EDLC_Error=0, - EDLC_Idle, - EDLC_NoOffers, - EDLC_AlreadyEnumeratedAllOffers, - EDLC_NoInstalledDLC, - EDLC_Pending, - EDLC_LoadInProgress, - EDLC_Loaded, - EDLC_ChangedDevice - }; + enum ESavingMessage { + ESavingMessage_None = 0, + ESavingMessage_Short, + ESavingMessage_Long + }; - enum ESavingMessage - { - ESavingMessage_None=0, - ESavingMessage_Short, - ESavingMessage_Long - }; + enum ETMSStatus { + ETMSStatus_Idle = 0, + ETMSStatus_Fail, + ETMSStatus_Fail_ReadInProgress, + ETMSStatus_Fail_WriteInProgress, + ETMSStatus_Pending, + }; - enum ETMSStatus - { - ETMSStatus_Idle=0, - ETMSStatus_Fail, - ETMSStatus_Fail_ReadInProgress, - ETMSStatus_Fail_WriteInProgress, - ETMSStatus_Pending, - }; + enum eTMS_FileType { + eTMS_FileType_Normal = 0, + eTMS_FileType_Graphic, + }; - enum eTMS_FileType - { - eTMS_FileType_Normal=0, - eTMS_FileType_Graphic, - }; + enum eTMS_FILETYPEVAL { + TMS_FILETYPE_BINARY, + TMS_FILETYPE_CONFIG, + TMS_FILETYPE_JSON, + TMS_FILETYPE_MAX + }; + enum eTMS_UGCTYPE { TMS_UGCTYPE_NONE, TMS_UGCTYPE_IMAGE, TMS_UGCTYPE_MAX }; - enum eTMS_FILETYPEVAL - { - TMS_FILETYPE_BINARY, - TMS_FILETYPE_CONFIG, - TMS_FILETYPE_JSON, - TMS_FILETYPE_MAX - }; - enum eTMS_UGCTYPE - { - TMS_UGCTYPE_NONE, - TMS_UGCTYPE_IMAGE, - TMS_UGCTYPE_MAX - }; + typedef struct { + CHAR szFilename[256]; + int iFileSize; + eTMS_FILETYPEVAL eFileTypeVal; + } TMSPP_FILE_DETAILS, *PTMSPP_FILE_DETAILS; + typedef struct { + int iCount; + PTMSPP_FILE_DETAILS FileDetailsA; + } TMSPP_FILE_LIST, *PTMSPP_FILE_LIST; - typedef struct - { - CHAR szFilename[256]; - int iFileSize; - eTMS_FILETYPEVAL eFileTypeVal; - } - TMSPP_FILE_DETAILS, *PTMSPP_FILE_DETAILS; + typedef struct { + DWORD dwSize; + PBYTE pbData; + } TMSPP_FILEDATA, *PTMSPP_FILEDATA; - typedef struct - { - int iCount; - PTMSPP_FILE_DETAILS FileDetailsA; - } - TMSPP_FILE_LIST, *PTMSPP_FILE_LIST; + C4JStorage(); - typedef struct - { - DWORD dwSize; - PBYTE pbData; - } - TMSPP_FILEDATA, *PTMSPP_FILEDATA; + void Tick(void); + // Messages + C4JStorage::EMessageResult RequestMessageBox( + UINT uiTitle, UINT uiText, UINT* uiOptionA, UINT uiOptionC, + DWORD dwPad = XUSER_INDEX_ANY, + int (*Func)(void*, int, const C4JStorage::EMessageResult) = NULL, + void* lpParam = NULL, C4JStringTable* pStringTable = NULL, + WCHAR* pwchFormatString = NULL, DWORD dwFocusButton = 0); - C4JStorage(); + C4JStorage::EMessageResult GetMessageBoxResult(); - void Tick(void); + // save device + bool SetSaveDevice(int (*Func)(void*, const bool), void* lpParam, + bool bForceResetOfSaveDevice = false); - // Messages - C4JStorage::EMessageResult RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, - int( *Func)(void *,int,const C4JStorage::EMessageResult)=NULL,void *lpParam=NULL, C4JStringTable *pStringTable=NULL, WCHAR *pwchFormatString=NULL,DWORD dwFocusButton=0); + // savegame + void Init(unsigned int uiSaveVersion, LPCWSTR pwchDefaultSaveName, + char* pszSavePackName, int iMinimumSaveSize, + int (*Func)(void*, const ESavingMessage, int), void* lpParam, + LPCSTR szGroupID); + void ResetSaveData(); // Call before a new save to clear out stored save + // file name + void SetDefaultSaveNameForKeyboardDisplay(LPCWSTR pwchDefaultSaveName); + void SetSaveTitle(LPCWSTR pwchDefaultSaveName); + bool GetSaveUniqueNumber(INT* piVal); + bool GetSaveUniqueFilename(char* pszName); + void SetSaveUniqueFilename(char* szFilename); + void SetState(ESaveGameControlState eControlState, + int (*Func)(void*, const bool), void* lpParam); + void SetSaveDisabled(bool bDisable); + bool GetSaveDisabled(void); + unsigned int GetSaveSize(); + void GetSaveData(void* pvData, unsigned int* puiBytes); + PVOID AllocateSaveData(unsigned int uiBytes); + void SetSaveImages( + PBYTE pbThumbnail, DWORD dwThumbnailBytes, PBYTE pbImage, + DWORD dwImageBytes, PBYTE pbTextData, + DWORD dwTextDataBytes); // Sets the thumbnail & image for the save, + // optionally setting the metadata in the png + C4JStorage::ESaveGameState SaveSaveData(int (*Func)(void*, const bool), + void* lpParam); + void CopySaveDataToNewSave(PBYTE pbThumbnail, DWORD cbThumbnail, + WCHAR* wchNewName, + int (*Func)(void* lpParam, bool), void* lpParam); + void SetSaveDeviceSelected(unsigned int uiPad, bool bSelected); + bool GetSaveDeviceSelected(unsigned int iPad); + C4JStorage::ESaveGameState DoesSaveExist(bool* pbExists); + bool EnoughSpaceForAMinSaveGame(); + void SetSaveMessageVPosition( + float fY); // The 'Saving' message will display at a default position + // unless changed + // Get the info for the saves + C4JStorage::ESaveGameState GetSavesInfo( + int iPad, + int (*Func)(void* lpParam, SAVE_DETAILS* pSaveDetails, const bool), + void* lpParam, char* pszSavePackName); + PSAVE_DETAILS ReturnSavesInfo(); + void ClearSavesInfo(); // Clears results + C4JStorage::ESaveGameState LoadSaveDataThumbnail( + PSAVE_INFO pSaveInfo, + int (*Func)(void* lpParam, std::uint8_t* thumbnailData, + unsigned int thumbnailBytes), + void* lpParam); // Get the thumbnail for an individual save referenced + // by pSaveInfo - C4JStorage::EMessageResult GetMessageBoxResult(); + void GetSaveCacheFileInfo(DWORD dwFile, XCONTENT_DATA& xContentData); + void GetSaveCacheFileInfo(DWORD dwFile, PBYTE* ppbImageData, + DWORD* pdwImageBytes); - // save device - bool SetSaveDevice(int( *Func)(void *,const bool),void *lpParam, bool bForceResetOfSaveDevice=false); + // Load the save. Need to call GetSaveData once the callback is called + C4JStorage::ESaveGameState LoadSaveData(PSAVE_INFO pSaveInfo, + int (*Func)(void* lpParam, + const bool, const bool), + void* lpParam); + C4JStorage::ESaveGameState DeleteSaveData(PSAVE_INFO pSaveInfo, + int (*Func)(void* lpParam, + const bool), + void* lpParam); - // savegame - void Init(unsigned int uiSaveVersion,LPCWSTR pwchDefaultSaveName,char *pszSavePackName,int iMinimumSaveSize,int( *Func)(void *, const ESavingMessage, int),void *lpParam,LPCSTR szGroupID); - void ResetSaveData(); // Call before a new save to clear out stored save file name - void SetDefaultSaveNameForKeyboardDisplay(LPCWSTR pwchDefaultSaveName); - void SetSaveTitle(LPCWSTR pwchDefaultSaveName); - bool GetSaveUniqueNumber(INT *piVal); - bool GetSaveUniqueFilename(char *pszName); - void SetSaveUniqueFilename(char *szFilename); - void SetState(ESaveGameControlState eControlState,int( *Func)(void *,const bool),void *lpParam); - void SetSaveDisabled(bool bDisable); - bool GetSaveDisabled(void); - unsigned int GetSaveSize(); - void GetSaveData(void *pvData,unsigned int *puiBytes); - PVOID AllocateSaveData(unsigned int uiBytes); - void SetSaveImages( PBYTE pbThumbnail,DWORD dwThumbnailBytes,PBYTE pbImage,DWORD dwImageBytes, PBYTE pbTextData ,DWORD dwTextDataBytes); // Sets the thumbnail & image for the save, optionally setting the metadata in the png - C4JStorage::ESaveGameState SaveSaveData(int( *Func)(void * ,const bool),void *lpParam); - void CopySaveDataToNewSave(PBYTE pbThumbnail,DWORD cbThumbnail,WCHAR *wchNewName,int ( *Func)(void *lpParam, bool), void *lpParam); - void SetSaveDeviceSelected(unsigned int uiPad,bool bSelected); - bool GetSaveDeviceSelected(unsigned int iPad); - C4JStorage::ESaveGameState DoesSaveExist(bool *pbExists); - bool EnoughSpaceForAMinSaveGame(); + // DLC + void RegisterMarketplaceCountsCallback( + int (*Func)(void* lpParam, C4JStorage::DLC_TMS_DETAILS*, int), + void* lpParam); + void SetDLCPackageRoot(char* pszDLCRoot); + C4JStorage::EDLCStatus GetDLCOffers( + int iPad, int (*Func)(void*, int, std::uint32_t, int), void* lpParam, + DWORD dwOfferTypesBitmask = XMARKETPLACE_OFFERING_TYPE_CONTENT); + DWORD CancelGetDLCOffers(); + void ClearDLCOffers(); + XMARKETPLACE_CONTENTOFFER_INFO& GetOffer(DWORD dw); + int GetOfferCount(); + DWORD InstallOffer(int iOfferIDC, __uint64* ullOfferIDA, + int (*Func)(void*, int, int), void* lpParam, + bool bTrial = false); + DWORD GetAvailableDLCCount(int iPad); - void SetSaveMessageVPosition(float fY); // The 'Saving' message will display at a default position unless changed - // Get the info for the saves - C4JStorage::ESaveGameState GetSavesInfo(int iPad,int ( *Func)(void *lpParam,SAVE_DETAILS *pSaveDetails,const bool),void *lpParam,char *pszSavePackName); - PSAVE_DETAILS ReturnSavesInfo(); - void ClearSavesInfo(); // Clears results - C4JStorage::ESaveGameState LoadSaveDataThumbnail(PSAVE_INFO pSaveInfo,int( *Func)(void *lpParam,std::uint8_t *thumbnailData,unsigned int thumbnailBytes), void *lpParam); // Get the thumbnail for an individual save referenced by pSaveInfo + C4JStorage::EDLCStatus GetInstalledDLC(int iPad, + int (*Func)(void*, int, int), + void* lpParam); + XCONTENT_DATA& GetDLC(DWORD dw); + std::uint32_t MountInstalledDLC(int iPad, std::uint32_t dwDLC, + int (*Func)(void*, int, std::uint32_t, + std::uint32_t), + void* lpParam, LPCSTR szMountDrive = NULL); + DWORD UnmountInstalledDLC(LPCSTR szMountDrive = NULL); + void GetMountedDLCFileList(const char* szMountDrive, + std::vector& fileList); + std::string GetMountedPath(std::string szMount); - void GetSaveCacheFileInfo(DWORD dwFile,XCONTENT_DATA &xContentData); - void GetSaveCacheFileInfo(DWORD dwFile, PBYTE *ppbImageData, DWORD *pdwImageBytes); + // Global title storage + C4JStorage::ETMSStatus ReadTMSFile( + int iQuadrant, eGlobalStorage eStorageFacility, + C4JStorage::eTMS_FileType eFileType, WCHAR* pwchFilename, + BYTE** ppBuffer, DWORD* pdwBufferSize, + int (*Func)(void*, WCHAR*, int, bool, int) = NULL, void* lpParam = NULL, + int iAction = 0); + bool WriteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, + WCHAR* pwchFilename, BYTE* pBuffer, DWORD dwBufferSize); + bool DeleteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, + WCHAR* pwchFilename); + void StoreTMSPathName(WCHAR* pwchName = NULL); - // Load the save. Need to call GetSaveData once the callback is called - C4JStorage::ESaveGameState LoadSaveData(PSAVE_INFO pSaveInfo,int( *Func)(void *lpParam,const bool, const bool), void *lpParam); - C4JStorage::ESaveGameState DeleteSaveData(PSAVE_INFO pSaveInfo,int( *Func)(void *lpParam,const bool), void *lpParam); - - // DLC - void RegisterMarketplaceCountsCallback(int ( *Func)(void *lpParam, C4JStorage::DLC_TMS_DETAILS *, int), void *lpParam ); - void SetDLCPackageRoot(char *pszDLCRoot); - C4JStorage::EDLCStatus GetDLCOffers(int iPad,int( *Func)(void *, int, std::uint32_t, int),void *lpParam, DWORD dwOfferTypesBitmask=XMARKETPLACE_OFFERING_TYPE_CONTENT); - DWORD CancelGetDLCOffers(); - void ClearDLCOffers(); - XMARKETPLACE_CONTENTOFFER_INFO& GetOffer(DWORD dw); - int GetOfferCount(); - DWORD InstallOffer(int iOfferIDC, __uint64 *ullOfferIDA,int( *Func)(void *, int, int),void *lpParam, bool bTrial=false); - DWORD GetAvailableDLCCount( int iPad); - - C4JStorage::EDLCStatus GetInstalledDLC(int iPad,int( *Func)(void *, int, int),void *lpParam); - XCONTENT_DATA& GetDLC(DWORD dw); - std::uint32_t MountInstalledDLC(int iPad,std::uint32_t dwDLC,int( *Func)(void *, int, std::uint32_t, std::uint32_t),void *lpParam,LPCSTR szMountDrive=NULL); - DWORD UnmountInstalledDLC(LPCSTR szMountDrive = NULL); - void GetMountedDLCFileList(const char* szMountDrive, std::vector& fileList); - std::string GetMountedPath(std::string szMount); - - // Global title storage - C4JStorage::ETMSStatus ReadTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType, - WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(void *, WCHAR *,int, bool, int)=NULL,void *lpParam=NULL, int iAction=0); - bool WriteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename,BYTE *pBuffer,DWORD dwBufferSize); - bool DeleteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename); - void StoreTMSPathName(WCHAR *pwchName=NULL); - - // TMS++ + // TMS++ #ifdef _XBOX - C4JStorage::ETMSStatus WriteTMSFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,TMSCLIENT_CALLBACK Func,LPVOID lpParam); - HRESULT GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam); + C4JStorage::ETMSStatus WriteTMSFile( + int iPad, C4JStorage::eGlobalStorage eStorageFacility, + C4JStorage::eTMS_FileType eFileType, CHAR* pchFilePath, CHAR* pchBuffer, + DWORD dwBufferSize, TMSCLIENT_CALLBACK Func, LPVOID lpParam); + HRESULT GetUserQuotaInfo(int iPad, TMSCLIENT_CALLBACK Func, LPVOID lpParam); #endif - // C4JStorage::ETMSStatus TMSPP_WriteFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID lpParam=NULL, int iUserData=0); - // C4JStorage::ETMSStatus TMSPP_GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam, int iUserData=0); - C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(void *,int,int,PTMSPP_FILEDATA, LPCSTR)=NULL,void *lpParam=NULL, int iUserData=0); - // C4JStorage::ETMSStatus TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int( *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=NULL,LPVOID lpParam=NULL, int iUserData=0); - // C4JStorage::ETMSStatus TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=NULL, int iUserData=0); - // bool TMSPP_InFileList(eGlobalStorage eStorageFacility, int iPad,const std::wstring &Filename); - // unsigned int CRC(unsigned char *buf, int len); + // C4JStorage::ETMSStatus TMSPP_WriteFile(int + // iPad,C4JStorage::eGlobalStorage + // eStorageFacility,C4JStorage::eTMS_FILETYPEVAL + // eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR + // *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID + // lpParam=NULL, int iUserData=0); C4JStorage::ETMSStatus + // TMSPP_GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam, + // int iUserData=0); + C4JStorage::ETMSStatus TMSPP_ReadFile( + int iPad, C4JStorage::eGlobalStorage eStorageFacility, + C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename, + int (*Func)(void*, int, int, PTMSPP_FILEDATA, LPCSTR) = NULL, + void* lpParam = NULL, int iUserData = 0); + // C4JStorage::ETMSStatus TMSPP_ReadFileList(int + // iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int( + // *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=NULL,LPVOID lpParam=NULL, int + // iUserData=0); C4JStorage::ETMSStatus + // TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL + // eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=NULL, int + // iUserData=0); bool + // TMSPP_InFileList(eGlobalStorage eStorageFacility, int iPad,const + // std::wstring &Filename); unsigned int + // CRC(unsigned char *buf, int len); -// enum eXBLWS -// { -// eXBLWS_GET, -// eXBLWS_POST, -// eXBLWS_PUT, -// eXBLWS_DELETE, -// }; - //bool XBLWS_Command(eXBLWS eCommand); + // enum eXBLWS + // { + // eXBLWS_GET, + // eXBLWS_POST, + // eXBLWS_PUT, + // eXBLWS_DELETE, + // }; + // bool + // XBLWS_Command(eXBLWS eCommand); + unsigned int CRC(unsigned char* buf, int len); - unsigned int CRC(unsigned char *buf, int len); + int AddSubfile(int regionIndex); + unsigned int GetSubfileCount(); + void GetSubfileDetails(unsigned int i, int* regionIndex, void** data, + unsigned int* size); + void ResetSubfiles(); + void UpdateSubfile(int index, void* data, unsigned int size); + void SaveSubfiles(int (*Func)(void*, const bool), void* param); + ESaveGameState GetSaveState(); - int AddSubfile(int regionIndex); - unsigned int GetSubfileCount(); - void GetSubfileDetails(unsigned int i, int* regionIndex, void** data, unsigned int* size); - void ResetSubfiles(); - void UpdateSubfile(int index, void* data, unsigned int size); - void SaveSubfiles(int (*Func)(void*, const bool), void* param); - ESaveGameState GetSaveState(); + void ContinueIncompleteOperation(); - void ContinueIncompleteOperation(); - - C4JStringTable *m_pStringTable; + C4JStringTable* m_pStringTable; }; extern C4JStorage StorageManager; diff --git a/4J.Storage/stdafx.h b/4J.Storage/stdafx.h index d1d2c6318..19392809a 100644 --- a/4J.Storage/stdafx.h +++ b/4J.Storage/stdafx.h @@ -7,4 +7,4 @@ #include "../Minecraft.World/Platform/x64headers/extraX64.h" -#endif //_4J_STORAGE_STADAFX_H \ No newline at end of file +#endif //_4J_STORAGE_STADAFX_H \ No newline at end of file diff --git a/Minecraft.Client/ClientConstants.cpp b/Minecraft.Client/ClientConstants.cpp index 55a7ab0ad..9ac5d55bf 100644 --- a/Minecraft.Client/ClientConstants.cpp +++ b/Minecraft.Client/ClientConstants.cpp @@ -1,4 +1,6 @@ #include "Platform/stdafx.h" #include "ClientConstants.h" -const std::wstring ClientConstants::VERSION_STRING = std::wstring(L"Minecraft Xbox ") + VER_FILEVERSION_STR_W;//+ SharedConstants::VERSION_STRING; \ No newline at end of file +const std::wstring ClientConstants::VERSION_STRING = + std::wstring(L"Minecraft Xbox ") + + VER_FILEVERSION_STR_W; //+ SharedConstants::VERSION_STRING; \ No newline at end of file diff --git a/Minecraft.Client/ClientConstants.h b/Minecraft.Client/ClientConstants.h index 8533f59f4..1abca946c 100644 --- a/Minecraft.Client/ClientConstants.h +++ b/Minecraft.Client/ClientConstants.h @@ -1,19 +1,16 @@ #pragma once +class ClientConstants { + // This file holds global constants used by the client. + // The file should be replaced at compile-time with the + // proper settings for the given compilation. For example, + // release builds should replace this file with no-cheat + // settings. -class ClientConstants -{ - - // This file holds global constants used by the client. - // The file should be replaced at compile-time with the - // proper settings for the given compilation. For example, - // release builds should replace this file with no-cheat - // settings. - - // INTERNAL DEVELOPMENT SETTINGS + // INTERNAL DEVELOPMENT SETTINGS public: - static const std::wstring VERSION_STRING; + static const std::wstring VERSION_STRING; - static const bool DEADMAU5_CAMERA_CHEATS = false; - static const bool IS_DEMO_VERSION = false; + static const bool DEADMAU5_CAMERA_CHEATS = false; + static const bool IS_DEMO_VERSION = false; }; \ No newline at end of file diff --git a/Minecraft.Client/Commands/TeleportCommand.cpp b/Minecraft.Client/Commands/TeleportCommand.cpp index 5b997d16e..8919ec833 100644 --- a/Minecraft.Client/Commands/TeleportCommand.cpp +++ b/Minecraft.Client/Commands/TeleportCommand.cpp @@ -9,82 +9,90 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.dimension.h" #include "TeleportCommand.h" -EGameCommand TeleportCommand::getId() -{ - return eGameCommand_Teleport; +EGameCommand TeleportCommand::getId() { return eGameCommand_Teleport; } + +void TeleportCommand::execute(std::shared_ptr source, + byteArray commandData) { + ByteArrayInputStream bais(commandData); + DataInputStream dis(&bais); + + PlayerUID subjectID = dis.readPlayerUID(); + PlayerUID destinationID = dis.readPlayerUID(); + + bais.reset(); + + PlayerList* players = MinecraftServer::getInstance()->getPlayerList(); + + std::shared_ptr subject = players->getPlayer(subjectID); + std::shared_ptr destination = + players->getPlayer(destinationID); + + if (subject != NULL && destination != NULL && + subject->level->dimension->id == destination->level->dimension->id && + subject->isAlive()) { + subject->ride(nullptr); + subject->connection->teleport(destination->x, destination->y, + destination->z, destination->yRot, + destination->xRot); + // logAdminAction(source, "commands.tp.success", subject->getAName(), + // destination->getAName()); + logAdminAction(source, ChatPacket::e_ChatCommandTeleportSuccess, + subject->getName(), eTYPE_SERVERPLAYER, + destination->getName()); + + if (subject == source) { + destination->sendMessage(subject->getName(), + ChatPacket::e_ChatCommandTeleportToMe); + } else { + subject->sendMessage(destination->getName(), + ChatPacket::e_ChatCommandTeleportMe); + } + } + + // if (args.length >= 1) { + // MinecraftServer server = MinecraftServer.getInstance(); + // ServerPlayer victim; + + // if (args.length == 2 || args.length == 4) { + // victim = server.getPlayers().getPlayer(args[0]); + // if (victim == null) throw new PlayerNotFoundException(); + // } else { + // victim = (ServerPlayer) convertSourceToPlayer(source); + // } + + // if (args.length == 3 || args.length == 4) { + // if (victim.level != null) { + // int pos = args.length - 3; + // int maxPos = Level.MAX_LEVEL_SIZE; + // int x = convertArgToInt(source, args[pos++], -maxPos, + //maxPos); int y = convertArgToInt(source, args[pos++], + //Level.minBuildHeight, Level.maxBuildHeight); int z = + //convertArgToInt(source, args[pos++], -maxPos, maxPos); + + // victim.teleportTo(x + 0.5f, y, z + 0.5f); + // logAdminAction(source, "commands.tp.coordinates", + //victim.getAName(), x, y, z); + // } + // } else if (args.length == 1 || args.length == 2) { + // ServerPlayer destination = + //server.getPlayers().getPlayer(args[args.length - 1]); if (destination == + //null) throw new PlayerNotFoundException(); + + // victim.connection.teleport(destination.x, destination.y, + //destination.z, destination.yRot, destination.xRot); logAdminAction(source, + //"commands.tp.success", victim.getAName(), destination.getAName()); + // } + //} } -void TeleportCommand::execute(std::shared_ptr source, byteArray commandData) -{ - ByteArrayInputStream bais(commandData); - DataInputStream dis(&bais); +std::shared_ptr TeleportCommand::preparePacket( + PlayerUID subject, PlayerUID destination) { + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); - PlayerUID subjectID = dis.readPlayerUID(); - PlayerUID destinationID = dis.readPlayerUID(); - - bais.reset(); + dos.writePlayerUID(subject); + dos.writePlayerUID(destination); - PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - - std::shared_ptr subject = players->getPlayer(subjectID); - std::shared_ptr destination = players->getPlayer(destinationID); - - if(subject != NULL && destination != NULL && subject->level->dimension->id == destination->level->dimension->id && subject->isAlive() ) - { - subject->ride(nullptr); - subject->connection->teleport(destination->x, destination->y, destination->z, destination->yRot, destination->xRot); - //logAdminAction(source, "commands.tp.success", subject->getAName(), destination->getAName()); - logAdminAction(source, ChatPacket::e_ChatCommandTeleportSuccess, subject->getName(), eTYPE_SERVERPLAYER, destination->getName()); - - if(subject == source) - { - destination->sendMessage(subject->getName(), ChatPacket::e_ChatCommandTeleportToMe); - } - else - { - subject->sendMessage(destination->getName(), ChatPacket::e_ChatCommandTeleportMe); - } - } - - //if (args.length >= 1) { - // MinecraftServer server = MinecraftServer.getInstance(); - // ServerPlayer victim; - - // if (args.length == 2 || args.length == 4) { - // victim = server.getPlayers().getPlayer(args[0]); - // if (victim == null) throw new PlayerNotFoundException(); - // } else { - // victim = (ServerPlayer) convertSourceToPlayer(source); - // } - - // if (args.length == 3 || args.length == 4) { - // if (victim.level != null) { - // int pos = args.length - 3; - // int maxPos = Level.MAX_LEVEL_SIZE; - // int x = convertArgToInt(source, args[pos++], -maxPos, maxPos); - // int y = convertArgToInt(source, args[pos++], Level.minBuildHeight, Level.maxBuildHeight); - // int z = convertArgToInt(source, args[pos++], -maxPos, maxPos); - - // victim.teleportTo(x + 0.5f, y, z + 0.5f); - // logAdminAction(source, "commands.tp.coordinates", victim.getAName(), x, y, z); - // } - // } else if (args.length == 1 || args.length == 2) { - // ServerPlayer destination = server.getPlayers().getPlayer(args[args.length - 1]); - // if (destination == null) throw new PlayerNotFoundException(); - - // victim.connection.teleport(destination.x, destination.y, destination.z, destination.yRot, destination.xRot); - // logAdminAction(source, "commands.tp.success", victim.getAName(), destination.getAName()); - // } - //} -} - -std::shared_ptr TeleportCommand::preparePacket(PlayerUID subject, PlayerUID destination) -{ - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - - dos.writePlayerUID(subject); - dos.writePlayerUID(destination); - - return std::shared_ptr( new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray() )); + return std::shared_ptr( + new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray())); } \ No newline at end of file diff --git a/Minecraft.Client/Commands/TeleportCommand.h b/Minecraft.Client/Commands/TeleportCommand.h index f17e728df..f42016ab1 100644 --- a/Minecraft.Client/Commands/TeleportCommand.h +++ b/Minecraft.Client/Commands/TeleportCommand.h @@ -2,11 +2,12 @@ #include "../../Minecraft.World/Commands/Command.h" -class TeleportCommand : public Command -{ +class TeleportCommand : public Command { public: - virtual EGameCommand getId(); - virtual void execute(std::shared_ptr source, byteArray commandData); + virtual EGameCommand getId(); + virtual void execute(std::shared_ptr source, + byteArray commandData); - static std::shared_ptr preparePacket(PlayerUID subject, PlayerUID destination); + static std::shared_ptr preparePacket( + PlayerUID subject, PlayerUID destination); }; \ No newline at end of file diff --git a/Minecraft.Client/GameState/CreativeMode.cpp b/Minecraft.Client/GameState/CreativeMode.cpp index aab4b6e8d..86cb9ecc5 100644 --- a/Minecraft.Client/GameState/CreativeMode.cpp +++ b/Minecraft.Client/GameState/CreativeMode.cpp @@ -10,121 +10,91 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -CreativeMode::CreativeMode(Minecraft *minecraft) : GameMode(minecraft) -{ - destroyDelay = 0; - instaBuild = true; +CreativeMode::CreativeMode(Minecraft* minecraft) : GameMode(minecraft) { + destroyDelay = 0; + instaBuild = true; } -void CreativeMode::init() -{ - // initPlayer(); +void CreativeMode::init() { + // initPlayer(); } -void CreativeMode::enableCreativeForPlayer(std::shared_ptr player) -{ - // please check ServerPlayerGameMode.java if you change these - player->abilities.mayfly = true; - player->abilities.instabuild = true; - player->abilities.invulnerable = true; +void CreativeMode::enableCreativeForPlayer(std::shared_ptr player) { + // please check ServerPlayerGameMode.java if you change these + player->abilities.mayfly = true; + player->abilities.instabuild = true; + player->abilities.invulnerable = true; } -void CreativeMode::disableCreativeForPlayer(std::shared_ptr player) -{ - player->abilities.mayfly = false; - player->abilities.flying = false; - player->abilities.instabuild = false; - player->abilities.invulnerable = false; +void CreativeMode::disableCreativeForPlayer(std::shared_ptr player) { + player->abilities.mayfly = false; + player->abilities.flying = false; + player->abilities.instabuild = false; + player->abilities.invulnerable = false; } -void CreativeMode::adjustPlayer(std::shared_ptr player) -{ - enableCreativeForPlayer(player); +void CreativeMode::adjustPlayer(std::shared_ptr player) { + enableCreativeForPlayer(player); - for (int i = 0; i < 9; i++) - { - if (player->inventory->items[i] == NULL) - { - player->inventory->items[i] = std::shared_ptr( new ItemInstance(User::allowedTiles[i]) ); - } - else - { - // 4J-PB - this line is commented out in 1.0.1 - //player->inventory->items[i]->count = 1; + for (int i = 0; i < 9; i++) { + if (player->inventory->items[i] == NULL) { + player->inventory->items[i] = std::shared_ptr( + new ItemInstance(User::allowedTiles[i])); + } else { + // 4J-PB - this line is commented out in 1.0.1 + // player->inventory->items[i]->count = 1; } } } -void CreativeMode::creativeDestroyBlock(Minecraft *minecraft, GameMode *gameMode, int x, int y, int z, int face) -{ - if(!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) - { - gameMode->destroyBlock(x, y, z, face); - } +void CreativeMode::creativeDestroyBlock(Minecraft* minecraft, + GameMode* gameMode, int x, int y, int z, + int face) { + if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) { + gameMode->destroyBlock(x, y, z, face); + } } -bool CreativeMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly, bool *pbUsedItem) -{ - int t = level->getTile(x, y, z); - if (t > 0) - { - if (Tile::tiles[t]->use(level, x, y, z, player)) return true; - } - if (item == NULL) return false; - int aux = item->getAuxValue(); - int count = item->count; - bool success = item->useOn(player, level, x, y, z, face); - item->setAuxValue(aux); - item->count = count; - return success; +bool CreativeMode::useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly, + bool* pbUsedItem) { + int t = level->getTile(x, y, z); + if (t > 0) { + if (Tile::tiles[t]->use(level, x, y, z, player)) return true; + } + if (item == NULL) return false; + int aux = item->getAuxValue(); + int count = item->count; + bool success = item->useOn(player, level, x, y, z, face); + item->setAuxValue(aux); + item->count = count; + return success; } -void CreativeMode::startDestroyBlock(int x, int y, int z, int face) -{ - creativeDestroyBlock(minecraft, this, x, y, z, face); - destroyDelay = 5; +void CreativeMode::startDestroyBlock(int x, int y, int z, int face) { + creativeDestroyBlock(minecraft, this, x, y, z, face); + destroyDelay = 5; } -void CreativeMode::continueDestroyBlock(int x, int y, int z, int face) -{ - destroyDelay--; - if (destroyDelay <= 0) - { - destroyDelay = 5; - creativeDestroyBlock(minecraft, this, x, y, z, face); - } +void CreativeMode::continueDestroyBlock(int x, int y, int z, int face) { + destroyDelay--; + if (destroyDelay <= 0) { + destroyDelay = 5; + creativeDestroyBlock(minecraft, this, x, y, z, face); + } } -void CreativeMode::stopDestroyBlock() -{ -} +void CreativeMode::stopDestroyBlock() {} -bool CreativeMode::canHurtPlayer() -{ - return false; -} +bool CreativeMode::canHurtPlayer() { return false; } -void CreativeMode::initLevel(Level *level) -{ - GameMode::initLevel(level); -} +void CreativeMode::initLevel(Level* level) { GameMode::initLevel(level); } -float CreativeMode::getPickRange() -{ - return 5.0f; -} +float CreativeMode::getPickRange() { return 5.0f; } -bool CreativeMode::hasMissTime() -{ - return false; -} +bool CreativeMode::hasMissTime() { return false; } -bool CreativeMode::hasInfiniteItems() -{ - return true; -} +bool CreativeMode::hasInfiniteItems() { return true; } -bool CreativeMode::hasFarPickRange() -{ - return true; -} \ No newline at end of file +bool CreativeMode::hasFarPickRange() { return true; } \ No newline at end of file diff --git a/Minecraft.Client/GameState/CreativeMode.h b/Minecraft.Client/GameState/CreativeMode.h index 9732cfd0f..f98fd38e3 100644 --- a/Minecraft.Client/GameState/CreativeMode.h +++ b/Minecraft.Client/GameState/CreativeMode.h @@ -1,26 +1,29 @@ #pragma once #include "GameMode.h" -class CreativeMode : public GameMode -{ +class CreativeMode : public GameMode { private: - int destroyDelay; + int destroyDelay; public: - CreativeMode(Minecraft *minecraft); - virtual void init(); - static void enableCreativeForPlayer(std::shared_ptr player); - static void disableCreativeForPlayer(std::shared_ptr player); - virtual void adjustPlayer(std::shared_ptr player); - static void creativeDestroyBlock(Minecraft *minecraft, GameMode *gameMode, int x, int y, int z, int face); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem = NULL); - virtual void startDestroyBlock(int x, int y, int z, int face); - virtual void continueDestroyBlock(int x, int y, int z, int face); - virtual void stopDestroyBlock(); - virtual bool canHurtPlayer(); - virtual void initLevel(Level *level); - virtual float getPickRange(); - virtual bool hasMissTime(); - virtual bool hasInfiniteItems(); - virtual bool hasFarPickRange(); + CreativeMode(Minecraft* minecraft); + virtual void init(); + static void enableCreativeForPlayer(std::shared_ptr player); + static void disableCreativeForPlayer(std::shared_ptr player); + virtual void adjustPlayer(std::shared_ptr player); + static void creativeDestroyBlock(Minecraft* minecraft, GameMode* gameMode, + int x, int y, int z, int face); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly = false, + bool* pbUsedItem = NULL); + virtual void startDestroyBlock(int x, int y, int z, int face); + virtual void continueDestroyBlock(int x, int y, int z, int face); + virtual void stopDestroyBlock(); + virtual bool canHurtPlayer(); + virtual void initLevel(Level* level); + virtual float getPickRange(); + virtual bool hasMissTime(); + virtual bool hasInfiniteItems(); + virtual bool hasFarPickRange(); }; \ No newline at end of file diff --git a/Minecraft.Client/GameState/DemoMode.cpp b/Minecraft.Client/GameState/DemoMode.cpp index 9ecb5cf05..7b9a01bc0 100644 --- a/Minecraft.Client/GameState/DemoMode.cpp +++ b/Minecraft.Client/GameState/DemoMode.cpp @@ -2,111 +2,107 @@ #include "DemoMode.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" -DemoMode::DemoMode(Minecraft *minecraft) : SurvivalMode(minecraft) -{ - demoHasEnded = false; +DemoMode::DemoMode(Minecraft* minecraft) : SurvivalMode(minecraft) { + demoHasEnded = false; demoEndedReminder = 0; } -void DemoMode::tick() -{ +void DemoMode::tick() { SurvivalMode::tick(); -/* 4J - TODO - seems unlikely we need this demo mode anyway - __int64 time = minecraft->level->getTime(); - __int64 day = (time / Level::TICKS_PER_DAY) + 1; + /* 4J - TODO - seems unlikely we need this demo mode anyway + __int64 time = minecraft->level->getTime(); + __int64 day = (time / Level::TICKS_PER_DAY) + 1; - demoHasEnded = (time > (500 + Level::TICKS_PER_DAY * DEMO_DAYS)); - if (demoHasEnded) - { - demoEndedReminder++; - } + demoHasEnded = (time > (500 + Level::TICKS_PER_DAY * DEMO_DAYS)); + if (demoHasEnded) + { + demoEndedReminder++; + } - if ((time % Level::TICKS_PER_DAY) == 500) - { - if (day <= (DEMO_DAYS + 1)) - { - minecraft->gui->displayClientMessage(L"demo.day." + _toString<__int64>(day)); + if ((time % Level::TICKS_PER_DAY) == 500) + { + if (day <= (DEMO_DAYS + 1)) + { + minecraft->gui->displayClientMessage(L"demo.day." + + _toString<__int64>(day)); + } } - } - else if (day == 1) - { - Options *options = minecraft->options; - std::wstring message; + else if (day == 1) + { + Options *options = minecraft->options; + std::wstring message; - if (time == 100) { - minecraft.gui.addMessage("Seed: " + minecraft.level.getSeed()); - message = language.getElement("demo.help.movement"); - message = String.format(message, Keyboard.getKeyName(options.keyUp.key), Keyboard.getKeyName(options.keyLeft.key), Keyboard.getKeyName(options.keyDown.key), - Keyboard.getKeyName(options.keyRight.key)); - } else if (time == 175) { - message = language.getElement("demo.help.jump"); - message = String.format(message, Keyboard.getKeyName(options.keyJump.key)); - } else if (time == 250) { - message = language.getElement("demo.help.inventory"); - message = String.format(message, Keyboard.getKeyName(options.keyBuild.key)); + if (time == 100) { + minecraft.gui.addMessage("Seed: " + minecraft.level.getSeed()); + message = language.getElement("demo.help.movement"); + message = String.format(message, + Keyboard.getKeyName(options.keyUp.key), + Keyboard.getKeyName(options.keyLeft.key), + Keyboard.getKeyName(options.keyDown.key), + Keyboard.getKeyName(options.keyRight.key)); + } else if (time == 175) { + message = language.getElement("demo.help.jump"); + message = String.format(message, + Keyboard.getKeyName(options.keyJump.key)); } else if (time == 250) { + message = language.getElement("demo.help.inventory"); + message = String.format(message, + Keyboard.getKeyName(options.keyBuild.key)); + } + if (message != null) { + minecraft.gui.addMessage(message); + } + } else if (day == DEMO_DAYS) { + if ((time % Level.TICKS_PER_DAY) == 22000) { + minecraft.gui.displayClientMessage("demo.day.warning"); + } } - if (message != null) { - minecraft.gui.addMessage(message); - } - } else if (day == DEMO_DAYS) { - if ((time % Level.TICKS_PER_DAY) == 22000) { - minecraft.gui.displayClientMessage("demo.day.warning"); - } - } -*/ + */ } -void DemoMode::outputDemoReminder() -{ -/* 4J - TODO - if (demoEndedReminder > 100) { - minecraft.gui.displayClientMessage("demo.reminder"); - demoEndedReminder = 0; - } - */ +void DemoMode::outputDemoReminder() { + /* 4J - TODO + if (demoEndedReminder > 100) { + minecraft.gui.displayClientMessage("demo.reminder"); + demoEndedReminder = 0; + } + */ } -void DemoMode::startDestroyBlock(int x, int y, int z, int face) -{ - if (demoHasEnded) - { +void DemoMode::startDestroyBlock(int x, int y, int z, int face) { + if (demoHasEnded) { outputDemoReminder(); return; } SurvivalMode::startDestroyBlock(x, y, z, face); } -void DemoMode::continueDestroyBlock(int x, int y, int z, int face) -{ - if (demoHasEnded) - { +void DemoMode::continueDestroyBlock(int x, int y, int z, int face) { + if (demoHasEnded) { return; } SurvivalMode::continueDestroyBlock(x, y, z, face); } -bool DemoMode::destroyBlock(int x, int y, int z, int face) -{ - if (demoHasEnded) - { +bool DemoMode::destroyBlock(int x, int y, int z, int face) { + if (demoHasEnded) { return false; } return SurvivalMode::destroyBlock(x, y, z, face); } -bool DemoMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item) -{ - if (demoHasEnded) - { +bool DemoMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item) { + if (demoHasEnded) { outputDemoReminder(); return false; } return SurvivalMode::useItem(player, level, item); } -bool DemoMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face) -{ +bool DemoMode::useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face) { if (demoHasEnded) { outputDemoReminder(); return false; @@ -114,10 +110,9 @@ bool DemoMode::useItemOn(std::shared_ptr player, Level *level, std::shar return SurvivalMode::useItemOn(player, level, item, x, y, z, face); } -void DemoMode::attack(std::shared_ptr player, std::shared_ptr entity) -{ - if (demoHasEnded) - { +void DemoMode::attack(std::shared_ptr player, + std::shared_ptr entity) { + if (demoHasEnded) { outputDemoReminder(); return; } diff --git a/Minecraft.Client/GameState/DemoMode.h b/Minecraft.Client/GameState/DemoMode.h index 9b5f19401..3b6eee7b5 100644 --- a/Minecraft.Client/GameState/DemoMode.h +++ b/Minecraft.Client/GameState/DemoMode.h @@ -1,27 +1,32 @@ #pragma once #include "SurvivalMode.h" -class DemoMode : public SurvivalMode -{ +class DemoMode : public SurvivalMode { private: - static const int DEMO_DAYS = 5; + static const int DEMO_DAYS = 5; bool demoHasEnded; int demoEndedReminder; public: - DemoMode(Minecraft *minecraft); + DemoMode(Minecraft* minecraft); virtual void tick(); -private: - void outputDemoReminder(); -public: - using GameMode::useItem; - using SurvivalMode::useItemOn; - virtual void startDestroyBlock(int x, int y, int z, int face); +private: + void outputDemoReminder(); + +public: + using GameMode::useItem; + using SurvivalMode::useItemOn; + + virtual void startDestroyBlock(int x, int y, int z, int face); virtual void continueDestroyBlock(int x, int y, int z, int face); virtual bool destroyBlock(int x, int y, int z, int face); - virtual bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face); - virtual void attack(std::shared_ptr player, std::shared_ptr entity); + virtual bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face); + virtual void attack(std::shared_ptr player, + std::shared_ptr entity); }; diff --git a/Minecraft.Client/GameState/DemoUser.cpp b/Minecraft.Client/GameState/DemoUser.cpp index d44b29110..b38394972 100644 --- a/Minecraft.Client/GameState/DemoUser.cpp +++ b/Minecraft.Client/GameState/DemoUser.cpp @@ -1,6 +1,4 @@ #include "../Platform/stdafx.h" #include "DemoUser.h" -DemoUser::DemoUser() : User(L"DemoUser", L"n/a") -{ -} \ No newline at end of file +DemoUser::DemoUser() : User(L"DemoUser", L"n/a") {} \ No newline at end of file diff --git a/Minecraft.Client/GameState/DemoUser.h b/Minecraft.Client/GameState/DemoUser.h index b987a7e3e..6a3818904 100644 --- a/Minecraft.Client/GameState/DemoUser.h +++ b/Minecraft.Client/GameState/DemoUser.h @@ -1,8 +1,7 @@ #pragma once #include "../Player/User.h" -class DemoUser : public User -{ +class DemoUser : public User { public: - DemoUser(); + DemoUser(); }; \ No newline at end of file diff --git a/Minecraft.Client/GameState/GameMode.cpp b/Minecraft.Client/GameState/GameMode.cpp index 1ef38ca7a..eddaa7612 100644 --- a/Minecraft.Client/GameState/GameMode.cpp +++ b/Minecraft.Client/GameState/GameMode.cpp @@ -11,60 +11,55 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h" -GameMode::GameMode(Minecraft *minecraft) -{ - instaBuild = false; // 4J - added - this->minecraft = minecraft; +GameMode::GameMode(Minecraft* minecraft) { + instaBuild = false; // 4J - added + this->minecraft = minecraft; } -void GameMode::initLevel(Level *level) -{ -} +void GameMode::initLevel(Level* level) {} -bool GameMode::destroyBlock(int x, int y, int z, int face) -{ - Level *level = minecraft->level; - Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; - if (oldTile == NULL) return false; +bool GameMode::destroyBlock(int x, int y, int z, int face) { + Level* level = minecraft->level; + Tile* oldTile = Tile::tiles[level->getTile(x, y, z)]; + if (oldTile == NULL) return false; - // 4J - Let the rendering side of thing know we are about to destroy the tile, so we can synchronise collision with async render data upates. - minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(level, x, y, z); - level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); + // 4J - Let the rendering side of thing know we are about to destroy the + // tile, so we can synchronise collision with async render data upates. + minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(level, x, + y, z); + level->levelEvent( + LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, + oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); int data = level->getData(x, y, z); - // 4J - before we remove the tile, recalc the heightmap - setTile depends on this being valid to be able to do - // a quick update of skylighting when the block is removed, and there are cases with falling tiles where this can get out of sync - level->getChunkAt(x,z)->recalcHeightmapOnly(); + // 4J - before we remove the tile, recalc the heightmap - setTile depends on + // this being valid to be able to do a quick update of skylighting when the + // block is removed, and there are cases with falling tiles where this can + // get out of sync + level->getChunkAt(x, z)->recalcHeightmapOnly(); bool changed = level->setTile(x, y, z, 0); - if (oldTile != NULL && changed) - { + if (oldTile != NULL && changed) { oldTile->destroy(level, x, y, z, data); } return changed; } -void GameMode::render(float a) -{ +void GameMode::render(float a) {} + +bool GameMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, bool bTestUseOnly) { + return false; } -bool GameMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly) -{ - return false; -} +void GameMode::initPlayer(std::shared_ptr player) {} -void GameMode::initPlayer(std::shared_ptr player) -{ -} +void GameMode::tick() {} -void GameMode::tick() -{ -} +void GameMode::adjustPlayer(std::shared_ptr player) {} -void GameMode::adjustPlayer(std::shared_ptr player) -{ -} - -//bool GameMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly) +// bool GameMode::useItemOn(std::shared_ptr player, Level *level, +// std::shared_ptr item, int x, int y, int z, int face, bool +// bTestUseOnOnly) //{ // // 4J-PB - Adding a test only version to allow tooltips to be displayed // int t = level->getTile(x, y, z); @@ -74,9 +69,10 @@ void GameMode::adjustPlayer(std::shared_ptr player) // { // switch(t) // { -// case Tile::recordPlayer_Id: +// case Tile::recordPlayer_Id: // case Tile::bed_Id: // special case for a bed -// if (Tile::tiles[t]->TestUse(level, x, y, z, player )) +// if (Tile::tiles[t]->TestUse(level, x, y, z, +//player )) // { // return true; // } @@ -91,94 +87,73 @@ void GameMode::adjustPlayer(std::shared_ptr player) // break; // } // } -// else +// else // { -// if (Tile::tiles[t]->use(level, x, y, z, player )) return true; +// if (Tile::tiles[t]->use(level, x, y, z, player )) return +//true; // } // } -// -// if (item == NULL) return false; -// return item->useOn(player, level, x, y, z, face, bTestUseOnOnly); -//} +// +// if (item == NULL) return false; +// return item->useOn(player, level, x, y, z, face, bTestUseOnOnly); +// } - -std::shared_ptr GameMode::createPlayer(Level *level) -{ - return std::shared_ptr( new LocalPlayer(minecraft, level, minecraft->user, level->dimension->id) ); +std::shared_ptr GameMode::createPlayer(Level* level) { + return std::shared_ptr(new LocalPlayer( + minecraft, level, minecraft->user, level->dimension->id)); } -bool GameMode::interact(std::shared_ptr player, std::shared_ptr entity) -{ - return player->interact(entity); +bool GameMode::interact(std::shared_ptr player, + std::shared_ptr entity) { + return player->interact(entity); } -void GameMode::attack(std::shared_ptr player, std::shared_ptr entity) -{ - player->attack(entity); +void GameMode::attack(std::shared_ptr player, + std::shared_ptr entity) { + player->attack(entity); } -std::shared_ptr GameMode::handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player) -{ - return nullptr; +std::shared_ptr GameMode::handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player) { + return nullptr; } -void GameMode::handleCloseInventory(int containerId, std::shared_ptr player) -{ +void GameMode::handleCloseInventory(int containerId, + std::shared_ptr player) { player->containerMenu->removed(player); - delete player->containerMenu; + delete player->containerMenu; player->containerMenu = player->inventoryMenu; } -void GameMode::handleInventoryButtonClick(int containerId, int buttonId) -{ +void GameMode::handleInventoryButtonClick(int containerId, int buttonId) {} +bool GameMode::isCutScene() { return false; } + +void GameMode::releaseUsingItem(std::shared_ptr player) { + player->releaseUsingItem(); } -bool GameMode::isCutScene() -{ - return false; -} +bool GameMode::hasExperience() { return false; } -void GameMode::releaseUsingItem(std::shared_ptr player) -{ - player->releaseUsingItem(); -} +bool GameMode::hasMissTime() { return true; } -bool GameMode::hasExperience() -{ - return false; -} +bool GameMode::hasInfiniteItems() { return false; } -bool GameMode::hasMissTime() -{ - return true; -} +bool GameMode::hasFarPickRange() { return false; } -bool GameMode::hasInfiniteItems() -{ - return false; -} +void GameMode::handleCreativeModeItemAdd(std::shared_ptr clicked, + int i) {} -bool GameMode::hasFarPickRange() -{ - return false; -} +void GameMode::handleCreativeModeItemDrop( + std::shared_ptr clicked) {} -void GameMode::handleCreativeModeItemAdd(std::shared_ptr clicked, int i) -{ -} - -void GameMode::handleCreativeModeItemDrop(std::shared_ptr clicked) -{ -} - -bool GameMode::handleCraftItem(int recipe, std::shared_ptr player) -{ - return true; +bool GameMode::handleCraftItem(int recipe, std::shared_ptr player) { + return true; } // 4J-PB -void GameMode::handleDebugOptions(unsigned int uiVal, std::shared_ptr player) -{ - player->SetDebugOptions(uiVal); +void GameMode::handleDebugOptions(unsigned int uiVal, + std::shared_ptr player) { + player->SetDebugOptions(uiVal); } diff --git a/Minecraft.Client/GameState/GameMode.h b/Minecraft.Client/GameState/GameMode.h index 71559708a..e1c14b467 100644 --- a/Minecraft.Client/GameState/GameMode.h +++ b/Minecraft.Client/GameState/GameMode.h @@ -8,17 +8,17 @@ class Entity; class Tutorial; -class GameMode -{ +class GameMode { protected: - Minecraft *minecraft; + Minecraft* minecraft; + public: - bool instaBuild; + bool instaBuild; - GameMode(Minecraft *minecraft); - virtual ~GameMode() {} + GameMode(Minecraft* minecraft); + virtual ~GameMode() {} - virtual void initLevel(Level *level) ; + virtual void initLevel(Level* level); virtual void startDestroyBlock(int x, int y, int z, int face) = 0; virtual bool destroyBlock(int x, int y, int z, int face); virtual void continueDestroyBlock(int x, int y, int z, int face) = 0; @@ -29,31 +29,44 @@ public: virtual void tick(); virtual bool canHurtPlayer() = 0; virtual void adjustPlayer(std::shared_ptr player); - virtual bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly=false); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem = NULL) = 0; + virtual bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly = false); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly = false, + bool* pbUsedItem = NULL) = 0; - virtual std::shared_ptr createPlayer(Level *level); - virtual bool interact(std::shared_ptr player, std::shared_ptr entity); - virtual void attack(std::shared_ptr player, std::shared_ptr entity); - virtual std::shared_ptr handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player); - virtual void handleCloseInventory(int containerId, std::shared_ptr player); - virtual void handleInventoryButtonClick(int containerId, int buttonId); + virtual std::shared_ptr createPlayer(Level* level); + virtual bool interact(std::shared_ptr player, + std::shared_ptr entity); + virtual void attack(std::shared_ptr player, + std::shared_ptr entity); + virtual std::shared_ptr handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player); + virtual void handleCloseInventory(int containerId, + std::shared_ptr player); + virtual void handleInventoryButtonClick(int containerId, int buttonId); - virtual bool isCutScene(); - virtual void releaseUsingItem(std::shared_ptr player); - virtual bool hasExperience(); - virtual bool hasMissTime(); - virtual bool hasInfiniteItems(); - virtual bool hasFarPickRange(); - virtual void handleCreativeModeItemAdd(std::shared_ptr clicked, int i); - virtual void handleCreativeModeItemDrop(std::shared_ptr clicked); + virtual bool isCutScene(); + virtual void releaseUsingItem(std::shared_ptr player); + virtual bool hasExperience(); + virtual bool hasMissTime(); + virtual bool hasInfiniteItems(); + virtual bool hasFarPickRange(); + virtual void handleCreativeModeItemAdd( + std::shared_ptr clicked, int i); + virtual void handleCreativeModeItemDrop( + std::shared_ptr clicked); - // 4J Stu - Added so we can send packets for this in the network game - virtual bool handleCraftItem(int recipe, std::shared_ptr player); - virtual void handleDebugOptions(unsigned int uiVal, std::shared_ptr player); + // 4J Stu - Added so we can send packets for this in the network game + virtual bool handleCraftItem(int recipe, std::shared_ptr player); + virtual void handleDebugOptions(unsigned int uiVal, + std::shared_ptr player); - // 4J Stu - Added for tutorial checks - virtual bool isInputAllowed(int mapping) { return true; } - virtual bool isTutorial() { return false; } - virtual Tutorial *getTutorial() { return NULL; } + // 4J Stu - Added for tutorial checks + virtual bool isInputAllowed(int mapping) { return true; } + virtual bool isTutorial() { return false; } + virtual Tutorial* getTutorial() { return NULL; } }; diff --git a/Minecraft.Client/GameState/Options.cpp b/Minecraft.Client/GameState/Options.cpp index 06b08d5bd..556942464 100644 --- a/Minecraft.Client/GameState/Options.cpp +++ b/Minecraft.Client/GameState/Options.cpp @@ -14,100 +14,90 @@ #include "../../Minecraft.World/IO/Streams/DataOutputStream.h" #include "../../Minecraft.World/Util/StringHelpers.h" -// 4J - the Option sub-class used to be an java enumerated type, trying to emulate that functionality here -const Options::Option Options::Option::options[17] = -{ - Options::Option(L"options.music", true, false), - Options::Option(L"options.sound", true, false), - Options::Option(L"options.invertMouse", false, true), - Options::Option(L"options.sensitivity", true, false), - Options::Option(L"options.renderDistance", false, false), - Options::Option(L"options.viewBobbing", false, true), - Options::Option(L"options.anaglyph", false, true), - Options::Option(L"options.advancedOpengl", false, true), - Options::Option(L"options.framerateLimit", false, false), - Options::Option(L"options.difficulty", false, false), - Options::Option(L"options.graphics", false, false), - Options::Option(L"options.ao", false, true), - Options::Option(L"options.guiScale", false, false), - Options::Option(L"options.fov", true, false), - Options::Option(L"options.gamma", true, false), - Options::Option(L"options.renderClouds",false, true), - Options::Option(L"options.particles", false, false), +// 4J - the Option sub-class used to be an java enumerated type, trying to +// emulate that functionality here +const Options::Option Options::Option::options[17] = { + Options::Option(L"options.music", true, false), + Options::Option(L"options.sound", true, false), + Options::Option(L"options.invertMouse", false, true), + Options::Option(L"options.sensitivity", true, false), + Options::Option(L"options.renderDistance", false, false), + Options::Option(L"options.viewBobbing", false, true), + Options::Option(L"options.anaglyph", false, true), + Options::Option(L"options.advancedOpengl", false, true), + Options::Option(L"options.framerateLimit", false, false), + Options::Option(L"options.difficulty", false, false), + Options::Option(L"options.graphics", false, false), + Options::Option(L"options.ao", false, true), + Options::Option(L"options.guiScale", false, false), + Options::Option(L"options.fov", true, false), + Options::Option(L"options.gamma", true, false), + Options::Option(L"options.renderClouds", false, true), + Options::Option(L"options.particles", false, false), }; -const Options::Option *Options::Option::MUSIC = &Options::Option::options[0]; -const Options::Option *Options::Option::SOUND = &Options::Option::options[1]; -const Options::Option *Options::Option::INVERT_MOUSE = &Options::Option::options[2]; -const Options::Option *Options::Option::SENSITIVITY = &Options::Option::options[3]; -const Options::Option *Options::Option::RENDER_DISTANCE = &Options::Option::options[4]; -const Options::Option *Options::Option::VIEW_BOBBING = &Options::Option::options[5]; -const Options::Option *Options::Option::ANAGLYPH = &Options::Option::options[6]; -const Options::Option *Options::Option::ADVANCED_OPENGL = &Options::Option::options[7]; -const Options::Option *Options::Option::FRAMERATE_LIMIT = &Options::Option::options[8]; -const Options::Option *Options::Option::DIFFICULTY = &Options::Option::options[9]; -const Options::Option *Options::Option::GRAPHICS = &Options::Option::options[10]; -const Options::Option *Options::Option::AMBIENT_OCCLUSION = &Options::Option::options[11]; -const Options::Option *Options::Option::GUI_SCALE = &Options::Option::options[12]; -const Options::Option *Options::Option::FOV = &Options::Option::options[13]; -const Options::Option *Options::Option::GAMMA = &Options::Option::options[14]; -const Options::Option *Options::Option::RENDER_CLOUDS = &Options::Option::options[15]; -const Options::Option *Options::Option::PARTICLES = &Options::Option::options[16]; +const Options::Option* Options::Option::MUSIC = &Options::Option::options[0]; +const Options::Option* Options::Option::SOUND = &Options::Option::options[1]; +const Options::Option* Options::Option::INVERT_MOUSE = + &Options::Option::options[2]; +const Options::Option* Options::Option::SENSITIVITY = + &Options::Option::options[3]; +const Options::Option* Options::Option::RENDER_DISTANCE = + &Options::Option::options[4]; +const Options::Option* Options::Option::VIEW_BOBBING = + &Options::Option::options[5]; +const Options::Option* Options::Option::ANAGLYPH = &Options::Option::options[6]; +const Options::Option* Options::Option::ADVANCED_OPENGL = + &Options::Option::options[7]; +const Options::Option* Options::Option::FRAMERATE_LIMIT = + &Options::Option::options[8]; +const Options::Option* Options::Option::DIFFICULTY = + &Options::Option::options[9]; +const Options::Option* Options::Option::GRAPHICS = + &Options::Option::options[10]; +const Options::Option* Options::Option::AMBIENT_OCCLUSION = + &Options::Option::options[11]; +const Options::Option* Options::Option::GUI_SCALE = + &Options::Option::options[12]; +const Options::Option* Options::Option::FOV = &Options::Option::options[13]; +const Options::Option* Options::Option::GAMMA = &Options::Option::options[14]; +const Options::Option* Options::Option::RENDER_CLOUDS = + &Options::Option::options[15]; +const Options::Option* Options::Option::PARTICLES = + &Options::Option::options[16]; +const Options::Option* Options::Option::getItem(int id) { return &options[id]; } -const Options::Option *Options::Option::getItem(int id) -{ - return &options[id]; -} +Options::Option::Option(const std::wstring& captionId, bool hasProgress, + bool isBoolean) + : _isProgress(hasProgress), _isBoolean(isBoolean), captionId(captionId) {} -Options::Option::Option(const std::wstring& captionId, bool hasProgress, bool isBoolean) : _isProgress(hasProgress), _isBoolean(isBoolean), captionId(captionId) -{ -} +bool Options::Option::isProgress() const { return _isProgress; } -bool Options::Option::isProgress() const -{ - return _isProgress; -} +bool Options::Option::isBoolean() const { return _isBoolean; } -bool Options::Option::isBoolean() const -{ - return _isBoolean; -} +int Options::Option::getId() const { return (int)(this - options); } -int Options::Option::getId() const -{ - return (int)(this-options); -} +std::wstring Options::Option::getCaptionId() const { return captionId; } -std::wstring Options::Option::getCaptionId() const -{ - return captionId; -} +const std::wstring Options::RENDER_DISTANCE_NAMES[] = { + L"options.renderDistance.far", L"options.renderDistance.normal", + L"options.renderDistance.short", L"options.renderDistance.tiny"}; +const std::wstring Options::DIFFICULTY_NAMES[] = { + L"options.difficulty.peaceful", L"options.difficulty.easy", + L"options.difficulty.normal", L"options.difficulty.hard"}; +const std::wstring Options::GUI_SCALE[] = { + L"options.guiScale.auto", L"options.guiScale.small", + L"options.guiScale.normal", L"options.guiScale.large"}; +const std::wstring Options::FRAMERATE_LIMITS[] = { + L"performance.max", L"performance.balanced", L"performance.powersaver"}; -const std::wstring Options::RENDER_DISTANCE_NAMES[] = -{ - L"options.renderDistance.far", L"options.renderDistance.normal", L"options.renderDistance.short", L"options.renderDistance.tiny" -}; -const std::wstring Options::DIFFICULTY_NAMES[] = -{ - L"options.difficulty.peaceful", L"options.difficulty.easy", L"options.difficulty.normal", L"options.difficulty.hard" -}; -const std::wstring Options::GUI_SCALE[] = -{ - L"options.guiScale.auto", L"options.guiScale.small", L"options.guiScale.normal", L"options.guiScale.large" -}; -const std::wstring Options::FRAMERATE_LIMITS[] = -{ - L"performance.max", L"performance.balanced", L"performance.powersaver" -}; - -const std::wstring Options::PARTICLES[] = { - L"options.particles.all", L"options.particles.decreased", L"options.particles.minimal" -}; +const std::wstring Options::PARTICLES[] = {L"options.particles.all", + L"options.particles.decreased", + L"options.particles.minimal"}; // 4J added -void Options::init() -{ +void Options::init() { music = 1; sound = 1; sensitivity = 0.5f; @@ -116,16 +106,16 @@ void Options::init() bobView = true; anaglyph3d = false; advancedOpengl = false; - - //4JCRAFT V-Sync / VSync - #ifdef ENABLE_VSYNC + +// 4JCRAFT V-Sync / VSync +#ifdef ENABLE_VSYNC framerateLimit = 2; - #else +#else framerateLimit = 3; - #endif +#endif fancyGraphics = true; ambientOcclusion = true; - renderClouds = true; + renderClouds = true; skin = L"Default"; keyUp = new KeyMapping(L"key.forward", Keyboard::KEY_W); @@ -137,395 +127,348 @@ void Options::init() keyDrop = new KeyMapping(L"key.drop", Keyboard::KEY_Q); keyChat = new KeyMapping(L"key.chat", Keyboard::KEY_T); keySneak = new KeyMapping(L"key.sneak", Keyboard::KEY_LSHIFT); - keyAttack = new KeyMapping(L"key.attack", -100 + 0); + keyAttack = new KeyMapping(L"key.attack", -100 + 0); keyUse = new KeyMapping(L"key.use", -100 + 1); keyPlayerList = new KeyMapping(L"key.playerlist", Keyboard::KEY_TAB); keyPickItem = new KeyMapping(L"key.pickItem", -100 + 2); keyToggleFog = new KeyMapping(L"key.fog", Keyboard::KEY_F); - keyMappings[0] = keyAttack; - keyMappings[1] = keyUse; + keyMappings[0] = keyAttack; + keyMappings[1] = keyUse; keyMappings[2] = keyUp; - keyMappings[3] = keyLeft; - keyMappings[4] = keyDown; - keyMappings[5] = keyRight; - keyMappings[6] = keyJump; - keyMappings[7] = keySneak; - keyMappings[8] = keyDrop; - keyMappings[9] = keyBuild; - keyMappings[10] = keyChat; - keyMappings[11] = keyPlayerList; - keyMappings[12] = keyPickItem; - keyMappings[13] = keyToggleFog; + keyMappings[3] = keyLeft; + keyMappings[4] = keyDown; + keyMappings[5] = keyRight; + keyMappings[6] = keyJump; + keyMappings[7] = keySneak; + keyMappings[8] = keyDrop; + keyMappings[9] = keyBuild; + keyMappings[10] = keyChat; + keyMappings[11] = keyPlayerList; + keyMappings[12] = keyPickItem; + keyMappings[13] = keyToggleFog; - minecraft = NULL; - //optionsFile = NULL; + minecraft = NULL; + // optionsFile = NULL; - difficulty = 2; - hideGui = false; - thirdPersonView = false; - renderDebug = false; - lastMpIp = L""; + difficulty = 2; + hideGui = false; + thirdPersonView = false; + renderDebug = false; + lastMpIp = L""; - isFlying = false; - smoothCamera = false; - fixedCamera = false; - flySpeed = 1; - cameraSpeed = 1; - guiScale = 0; - particles = 0; - fov = 0; - gamma = 0; + isFlying = false; + smoothCamera = false; + fixedCamera = false; + flySpeed = 1; + cameraSpeed = 1; + guiScale = 0; + particles = 0; + fov = 0; + gamma = 0; } -Options::Options(Minecraft *minecraft, File workingDirectory) -{ - init(); - this->minecraft = minecraft; - optionsFile = File(workingDirectory, L"options.txt"); +Options::Options(Minecraft* minecraft, File workingDirectory) { + init(); + this->minecraft = minecraft; + optionsFile = File(workingDirectory, L"options.txt"); } -Options::Options() -{ - init(); -} +Options::Options() { init(); } -std::wstring Options::getKeyDescription(int i) -{ - Language *language = Language::getInstance(); +std::wstring Options::getKeyDescription(int i) { + Language* language = Language::getInstance(); return language->getElement(keyMappings[i]->name); } -std::wstring Options::getKeyMessage(int i) -{ - int key = keyMappings[i]->key; - if (key < 0) { - return I18n::get(L"key.mouseButton", key + 101); - } else { - return Keyboard::getKeyName(keyMappings[i]->key); - } +std::wstring Options::getKeyMessage(int i) { + int key = keyMappings[i]->key; + if (key < 0) { + return I18n::get(L"key.mouseButton", key + 101); + } else { + return Keyboard::getKeyName(keyMappings[i]->key); + } } -void Options::setKey(int i, int key) -{ +void Options::setKey(int i, int key) { keyMappings[i]->key = key; save(); } -void Options::set(const Options::Option *item, float fVal) -{ - if (item == Option::MUSIC) - { +void Options::set(const Options::Option* item, float fVal) { + if (item == Option::MUSIC) { music = fVal; #ifdef _XBOX - minecraft->soundEngine->updateMusicVolume(fVal*2.0f); + minecraft->soundEngine->updateMusicVolume(fVal * 2.0f); #else - minecraft->soundEngine->updateMusicVolume(fVal); + minecraft->soundEngine->updateMusicVolume(fVal); #endif } - if (item == Option::SOUND) - { + if (item == Option::SOUND) { sound = fVal; #ifdef _XBOX - minecraft->soundEngine->updateSoundEffectVolume(fVal*2.0f); + minecraft->soundEngine->updateSoundEffectVolume(fVal * 2.0f); #else - minecraft->soundEngine->updateSoundEffectVolume(fVal); + minecraft->soundEngine->updateSoundEffectVolume(fVal); #endif } - if (item == Option::SENSITIVITY) - { + if (item == Option::SENSITIVITY) { sensitivity = fVal; } - if (item == Option::FOV) - { - fov = fVal; - } - if (item == Option::GAMMA) - { - gamma = fVal; - } + if (item == Option::FOV) { + fov = fVal; + } + if (item == Option::GAMMA) { + gamma = fVal; + } } -void Options::toggle(const Options::Option *option, int dir) -{ +void Options::toggle(const Options::Option* option, int dir) { if (option == Option::INVERT_MOUSE) invertYMouse = !invertYMouse; - if (option == Option::RENDER_DISTANCE) viewDistance = (viewDistance + dir) & 3; + if (option == Option::RENDER_DISTANCE) + viewDistance = (viewDistance + dir) & 3; if (option == Option::GUI_SCALE) guiScale = (guiScale + dir) & 3; - if (option == Option::PARTICLES) particles = (particles + dir) % 3; + if (option == Option::PARTICLES) particles = (particles + dir) % 3; - // 4J-PB - changing - //if (option == Option::VIEW_BOBBING) bobView = !bobView; - if (option == Option::VIEW_BOBBING) ((dir==0)?bobView=false: bobView=true); - if (option == Option::RENDER_CLOUDS) renderClouds = !renderClouds; - if (option == Option::ADVANCED_OPENGL) - { + // 4J-PB - changing + // if (option == Option::VIEW_BOBBING) bobView = !bobView; + if (option == Option::VIEW_BOBBING) + ((dir == 0) ? bobView = false : bobView = true); + if (option == Option::RENDER_CLOUDS) renderClouds = !renderClouds; + if (option == Option::ADVANCED_OPENGL) { advancedOpengl = !advancedOpengl; minecraft->levelRenderer->allChanged(); } - if (option == Option::ANAGLYPH) - { + if (option == Option::ANAGLYPH) { anaglyph3d = !anaglyph3d; minecraft->textures->reloadAll(); } - if (option == Option::FRAMERATE_LIMIT) framerateLimit = (framerateLimit + dir + 3) % 3; + if (option == Option::FRAMERATE_LIMIT) + framerateLimit = (framerateLimit + dir + 3) % 3; - // 4J-PB - Change for Xbox - //if (option == Option::DIFFICULTY) difficulty = (difficulty + dir) & 3; - if (option == Option::DIFFICULTY) difficulty = (dir) & 3; + // 4J-PB - Change for Xbox + // if (option == Option::DIFFICULTY) difficulty = (difficulty + dir) & 3; + if (option == Option::DIFFICULTY) difficulty = (dir) & 3; - app.DebugPrintf("Option::DIFFICULTY = %d",difficulty); + app.DebugPrintf("Option::DIFFICULTY = %d", difficulty); - if (option == Option::GRAPHICS) - { + if (option == Option::GRAPHICS) { fancyGraphics = !fancyGraphics; minecraft->levelRenderer->allChanged(); } - if (option == Option::AMBIENT_OCCLUSION) - { + if (option == Option::AMBIENT_OCCLUSION) { ambientOcclusion = !ambientOcclusion; minecraft->levelRenderer->allChanged(); } - // 4J-PB - don't do the file save on the xbox + // 4J-PB - don't do the file save on the xbox // save(); - } -float Options::getProgressValue(const Options::Option *item) -{ - if (item == Option::FOV) return fov; - if (item == Option::GAMMA) return gamma; +float Options::getProgressValue(const Options::Option* item) { + if (item == Option::FOV) return fov; + if (item == Option::GAMMA) return gamma; if (item == Option::MUSIC) return music; if (item == Option::SOUND) return sound; if (item == Option::SENSITIVITY) return sensitivity; return 0; } -bool Options::getBooleanValue(const Options::Option *item) -{ - // 4J - was a switch statement which we can't do with our Option:: pointer types - if( item == Option::INVERT_MOUSE) return invertYMouse; - if( item == Option::VIEW_BOBBING) return bobView; - if( item == Option::ANAGLYPH) return anaglyph3d; - if( item == Option::ADVANCED_OPENGL) return advancedOpengl; - if( item == Option::AMBIENT_OCCLUSION) return ambientOcclusion; - if( item == Option::RENDER_CLOUDS) return renderClouds; - return false; +bool Options::getBooleanValue(const Options::Option* item) { + // 4J - was a switch statement which we can't do with our Option:: pointer + // types + if (item == Option::INVERT_MOUSE) return invertYMouse; + if (item == Option::VIEW_BOBBING) return bobView; + if (item == Option::ANAGLYPH) return anaglyph3d; + if (item == Option::ADVANCED_OPENGL) return advancedOpengl; + if (item == Option::AMBIENT_OCCLUSION) return ambientOcclusion; + if (item == Option::RENDER_CLOUDS) return renderClouds; + return false; } -std::wstring Options::getMessage(const Options::Option *item) -{ - // 4J TODO, should these std::wstrings append rather than add? +std::wstring Options::getMessage(const Options::Option* item) { + // 4J TODO, should these std::wstrings append rather than add? - Language *language = Language::getInstance(); + Language* language = Language::getInstance(); std::wstring caption = language->getElement(item->getCaptionId()) + L": "; - if (item->isProgress()) - { + if (item->isProgress()) { float progressValue = getProgressValue(item); - if (item == Option::SENSITIVITY) - { - if (progressValue == 0) - { - return caption + language->getElement(L"options.sensitivity.min"); + if (item == Option::SENSITIVITY) { + if (progressValue == 0) { + return caption + + language->getElement(L"options.sensitivity.min"); } - if (progressValue == 1) - { - return caption + language->getElement(L"options.sensitivity.max"); + if (progressValue == 1) { + return caption + + language->getElement(L"options.sensitivity.max"); } - return caption + _toString((int) (progressValue * 200)) + L"%"; - } else if (item == Option::FOV) - { - if (progressValue == 0) - { - return caption + language->getElement(L"options.fov.min"); - } - if (progressValue == 1) - { - return caption + language->getElement(L"options.fov.max"); - } - return caption + _toString((int) (70 + progressValue * 40)); - } else if (item == Option::GAMMA) - { - if (progressValue == 0) - { - return caption + language->getElement(L"options.gamma.min"); - } - if (progressValue == 1) - { - return caption + language->getElement(L"options.gamma.max"); - } - return caption + L"+" + _toString((int) (progressValue * 100)) + L"%"; - } - else - { - if (progressValue == 0) - { + return caption + _toString((int)(progressValue * 200)) + L"%"; + } else if (item == Option::FOV) { + if (progressValue == 0) { + return caption + language->getElement(L"options.fov.min"); + } + if (progressValue == 1) { + return caption + language->getElement(L"options.fov.max"); + } + return caption + _toString((int)(70 + progressValue * 40)); + } else if (item == Option::GAMMA) { + if (progressValue == 0) { + return caption + language->getElement(L"options.gamma.min"); + } + if (progressValue == 1) { + return caption + language->getElement(L"options.gamma.max"); + } + return caption + L"+" + _toString((int)(progressValue * 100)) + + L"%"; + } else { + if (progressValue == 0) { return caption + language->getElement(L"options.off"); } - return caption + _toString((int) (progressValue * 100)) + L"%"; + return caption + _toString((int)(progressValue * 100)) + L"%"; } - } else if (item->isBoolean()) - { - + } else if (item->isBoolean()) { bool booleanValue = getBooleanValue(item); - if (booleanValue) - { + if (booleanValue) { return caption + language->getElement(L"options.on"); } return caption + language->getElement(L"options.off"); - } - else if (item == Option::RENDER_DISTANCE) - { - return caption + language->getElement(RENDER_DISTANCE_NAMES[viewDistance]); - } - else if (item == Option::DIFFICULTY) - { + } else if (item == Option::RENDER_DISTANCE) { + return caption + + language->getElement(RENDER_DISTANCE_NAMES[viewDistance]); + } else if (item == Option::DIFFICULTY) { return caption + language->getElement(DIFFICULTY_NAMES[difficulty]); - } - else if (item == Option::GUI_SCALE) - { + } else if (item == Option::GUI_SCALE) { return caption + language->getElement(GUI_SCALE[guiScale]); - } - else if (item == Option::PARTICLES) - { - return caption + language->getElement(PARTICLES[particles]); - } - else if (item == Option::FRAMERATE_LIMIT) - { + } else if (item == Option::PARTICLES) { + return caption + language->getElement(PARTICLES[particles]); + } else if (item == Option::FRAMERATE_LIMIT) { return caption + I18n::get(FRAMERATE_LIMITS[framerateLimit]); - } - else if (item == Option::GRAPHICS) - { - if (fancyGraphics) - { + } else if (item == Option::GRAPHICS) { + if (fancyGraphics) { return caption + language->getElement(L"options.graphics.fancy"); } return caption + language->getElement(L"options.graphics.fast"); } return caption; - } -void Options::load() -{ - // 4J - removed try/catch -// try { - if (!optionsFile.exists()) return; - // 4J - was new BufferedReader(new FileReader(optionsFile)); - BufferedReader *br = new BufferedReader(new InputStreamReader( new FileInputStream( optionsFile ) ) ); - - std::wstring line = L""; - while ((line = br->readLine()) != L"") // 4J - was check against NULL - do we need to distinguish between empty lines and a fail here? - { - // 4J - removed try/catch -// try { - std::wstring cmds[2]; - int splitpos = (int)line.find(L":"); - if( splitpos == std::wstring::npos ) - { - cmds[0] = line; - cmds[1] = L""; - } - else - { - cmds[0] = line.substr(0,splitpos); - cmds[1] = line.substr(splitpos,line.length()-splitpos); - } +void Options::load() { + // 4J - removed try/catch + // try { + if (!optionsFile.exists()) return; + // 4J - was new BufferedReader(new FileReader(optionsFile)); + BufferedReader* br = new BufferedReader( + new InputStreamReader(new FileInputStream(optionsFile))); - if (cmds[0] == L"music") music = readFloat(cmds[1]); - if (cmds[0] == L"sound") sound = readFloat(cmds[1]); - if (cmds[0] == L"mouseSensitivity") sensitivity = readFloat(cmds[1]); - if (cmds[0] == L"fov") fov = readFloat(cmds[1]); - if (cmds[0] == L"gamma") gamma = readFloat(cmds[1]); - if (cmds[0] == L"invertYMouse") invertYMouse = cmds[1]==L"true"; - if (cmds[0] == L"viewDistance") viewDistance = _fromString(cmds[1]); - if (cmds[0] == L"guiScale") guiScale =_fromString(cmds[1]); - if (cmds[0] == L"particles") particles = _fromString(cmds[1]); - if (cmds[0] == L"bobView") bobView = cmds[1]==L"true"; - if (cmds[0] == L"anaglyph3d") anaglyph3d = cmds[1]==L"true"; - if (cmds[0] == L"advancedOpengl") advancedOpengl = cmds[1]==L"true"; - if (cmds[0] == L"fpsLimit") framerateLimit = _fromString(cmds[1]); - if (cmds[0] == L"difficulty") difficulty = _fromString(cmds[1]); - if (cmds[0] == L"fancyGraphics") fancyGraphics = cmds[1]==L"true"; - if (cmds[0] == L"ao") ambientOcclusion = cmds[1]==L"true"; - if (cmds[0] == L"clouds") renderClouds = cmds[1]==L"true"; - if (cmds[0] == L"skin") skin = cmds[1]; - if (cmds[0] == L"lastServer") lastMpIp = cmds[1]; - - for (int i = 0; i < keyMappings_length; i++) - { - if (cmds[0] == (L"key_" + keyMappings[i]->name)) - { - keyMappings[i]->key = _fromString(cmds[1]); - } - } -// } catch (Exception e) { -// System.out.println("Skipping bad option: " + line); -// } + std::wstring line = L""; + while ((line = br->readLine()) != + L"") // 4J - was check against NULL - do we need to distinguish + // between empty lines and a fail here? + { + // 4J - removed try/catch + // try { + std::wstring cmds[2]; + int splitpos = (int)line.find(L":"); + if (splitpos == std::wstring::npos) { + cmds[0] = line; + cmds[1] = L""; + } else { + cmds[0] = line.substr(0, splitpos); + cmds[1] = line.substr(splitpos, line.length() - splitpos); } - //KeyMapping.resetMapping(); // 4J Not implemented - br->close(); -// } catch (Exception e) { -// System.out.println("Failed to load options"); -// e.printStackTrace(); -// } + if (cmds[0] == L"music") music = readFloat(cmds[1]); + if (cmds[0] == L"sound") sound = readFloat(cmds[1]); + if (cmds[0] == L"mouseSensitivity") sensitivity = readFloat(cmds[1]); + if (cmds[0] == L"fov") fov = readFloat(cmds[1]); + if (cmds[0] == L"gamma") gamma = readFloat(cmds[1]); + if (cmds[0] == L"invertYMouse") invertYMouse = cmds[1] == L"true"; + if (cmds[0] == L"viewDistance") + viewDistance = _fromString(cmds[1]); + if (cmds[0] == L"guiScale") guiScale = _fromString(cmds[1]); + if (cmds[0] == L"particles") particles = _fromString(cmds[1]); + if (cmds[0] == L"bobView") bobView = cmds[1] == L"true"; + if (cmds[0] == L"anaglyph3d") anaglyph3d = cmds[1] == L"true"; + if (cmds[0] == L"advancedOpengl") advancedOpengl = cmds[1] == L"true"; + if (cmds[0] == L"fpsLimit") framerateLimit = _fromString(cmds[1]); + if (cmds[0] == L"difficulty") difficulty = _fromString(cmds[1]); + if (cmds[0] == L"fancyGraphics") fancyGraphics = cmds[1] == L"true"; + if (cmds[0] == L"ao") ambientOcclusion = cmds[1] == L"true"; + if (cmds[0] == L"clouds") renderClouds = cmds[1] == L"true"; + if (cmds[0] == L"skin") skin = cmds[1]; + if (cmds[0] == L"lastServer") lastMpIp = cmds[1]; + + for (int i = 0; i < keyMappings_length; i++) { + if (cmds[0] == (L"key_" + keyMappings[i]->name)) { + keyMappings[i]->key = _fromString(cmds[1]); + } + } + // } catch (Exception e) { + // System.out.println("Skipping bad option: " + line); + // } + } + // KeyMapping.resetMapping(); // 4J Not implemented + br->close(); + // } catch (Exception e) { + // System.out.println("Failed to load options"); + // e.printStackTrace(); + // } } -float Options::readFloat(std::wstring string) -{ +float Options::readFloat(std::wstring string) { if (string == L"true") return 1; if (string == L"false") return 0; return _fromString(string); } -void Options::save() -{ - // 4J - try/catch removed -// try { +void Options::save() { + // 4J - try/catch removed + // try { - // 4J - original used a PrintWriter & FileWriter, but seems a bit much implementing these just to do this - FileOutputStream fos = FileOutputStream(optionsFile); - DataOutputStream dos = DataOutputStream(&fos); -// PrintWriter pw = new PrintWriter(new FileWriter(optionsFile)); + // 4J - original used a PrintWriter & FileWriter, but seems a bit much + // implementing these just to do this + FileOutputStream fos = FileOutputStream(optionsFile); + DataOutputStream dos = DataOutputStream(&fos); + // PrintWriter pw = new PrintWriter(new FileWriter(optionsFile)); - dos.writeChars(L"music:" + _toString(music) + L"\n"); - dos.writeChars(L"sound:" + _toString(sound) + L"\n"); - dos.writeChars(L"invertYMouse:" + std::wstring(invertYMouse ? L"true" : L"false") + L"\n"); - dos.writeChars(L"mouseSensitivity:" + _toString(sensitivity)); - dos.writeChars(L"fov:" + _toString(fov)); - dos.writeChars(L"gamma:" + _toString(gamma)); - dos.writeChars(L"viewDistance:" + _toString(viewDistance)); - dos.writeChars(L"guiScale:" + _toString(guiScale)); - dos.writeChars(L"particles:" + _toString(particles)); - dos.writeChars(L"bobView:" + std::wstring(bobView ? L"true" : L"false")); - dos.writeChars(L"anaglyph3d:" + std::wstring(anaglyph3d ? L"true" : L"false")); - dos.writeChars(L"advancedOpengl:" + std::wstring(advancedOpengl ? L"true" : L"false")); - dos.writeChars(L"fpsLimit:" + _toString(framerateLimit)); - dos.writeChars(L"difficulty:" + _toString(difficulty)); - dos.writeChars(L"fancyGraphics:" + std::wstring(fancyGraphics ? L"true" : L"false")); - dos.writeChars(L"ao:" + std::wstring(ambientOcclusion ? L"true" : L"false")); - dos.writeChars(L"clouds:" + _toString(renderClouds)); - dos.writeChars(L"skin:" + skin); - dos.writeChars(L"lastServer:" + lastMpIp); + dos.writeChars(L"music:" + _toString(music) + L"\n"); + dos.writeChars(L"sound:" + _toString(sound) + L"\n"); + dos.writeChars(L"invertYMouse:" + + std::wstring(invertYMouse ? L"true" : L"false") + L"\n"); + dos.writeChars(L"mouseSensitivity:" + _toString(sensitivity)); + dos.writeChars(L"fov:" + _toString(fov)); + dos.writeChars(L"gamma:" + _toString(gamma)); + dos.writeChars(L"viewDistance:" + _toString(viewDistance)); + dos.writeChars(L"guiScale:" + _toString(guiScale)); + dos.writeChars(L"particles:" + _toString(particles)); + dos.writeChars(L"bobView:" + std::wstring(bobView ? L"true" : L"false")); + dos.writeChars(L"anaglyph3d:" + + std::wstring(anaglyph3d ? L"true" : L"false")); + dos.writeChars(L"advancedOpengl:" + + std::wstring(advancedOpengl ? L"true" : L"false")); + dos.writeChars(L"fpsLimit:" + _toString(framerateLimit)); + dos.writeChars(L"difficulty:" + _toString(difficulty)); + dos.writeChars(L"fancyGraphics:" + + std::wstring(fancyGraphics ? L"true" : L"false")); + dos.writeChars(L"ao:" + + std::wstring(ambientOcclusion ? L"true" : L"false")); + dos.writeChars(L"clouds:" + _toString(renderClouds)); + dos.writeChars(L"skin:" + skin); + dos.writeChars(L"lastServer:" + lastMpIp); - for (int i = 0; i < keyMappings_length; i++) - { - dos.writeChars(L"key_" + keyMappings[i]->name + L":" + _toString(keyMappings[i]->key)); - } - - dos.close(); -// } catch (Exception e) { -// System.out.println("Failed to save options"); -// e.printStackTrace(); -// } + for (int i = 0; i < keyMappings_length; i++) { + dos.writeChars(L"key_" + keyMappings[i]->name + L":" + + _toString(keyMappings[i]->key)); + } + dos.close(); + // } catch (Exception e) { + // System.out.println("Failed to save options"); + // e.printStackTrace(); + // } } -bool Options::isCloudsOn() -{ - return viewDistance < 2 && renderClouds; -} +bool Options::isCloudsOn() { return viewDistance < 2 && renderClouds; } diff --git a/Minecraft.Client/GameState/Options.h b/Minecraft.Client/GameState/Options.h index b9d2d4928..b727da4a0 100644 --- a/Minecraft.Client/GameState/Options.h +++ b/Minecraft.Client/GameState/Options.h @@ -4,60 +4,58 @@ class Minecraft; class KeyMapping; #include "../../Minecraft.World/IO/Files/File.h" -class Options -{ +class Options { public: - static const int AO_OFF = 0; - static const int AO_MIN = 1; - static const int AO_MAX = 2; + static const int AO_OFF = 0; + static const int AO_MIN = 1; + static const int AO_MAX = 2; - // 4J - this used to be an enum - class Option - { - public: - static const Option options[17]; - static const Option *MUSIC; - static const Option *SOUND; - static const Option *INVERT_MOUSE; - static const Option *SENSITIVITY; - static const Option *RENDER_DISTANCE; - static const Option *VIEW_BOBBING; - static const Option *ANAGLYPH; - static const Option *ADVANCED_OPENGL; - static const Option *FRAMERATE_LIMIT; - static const Option *DIFFICULTY; - static const Option *GRAPHICS; - static const Option *AMBIENT_OCCLUSION; - static const Option *GUI_SCALE; - static const Option *FOV; - static const Option *GAMMA; - static const Option *RENDER_CLOUDS; - static const Option *PARTICLES; + // 4J - this used to be an enum + class Option { + public: + static const Option options[17]; + static const Option* MUSIC; + static const Option* SOUND; + static const Option* INVERT_MOUSE; + static const Option* SENSITIVITY; + static const Option* RENDER_DISTANCE; + static const Option* VIEW_BOBBING; + static const Option* ANAGLYPH; + static const Option* ADVANCED_OPENGL; + static const Option* FRAMERATE_LIMIT; + static const Option* DIFFICULTY; + static const Option* GRAPHICS; + static const Option* AMBIENT_OCCLUSION; + static const Option* GUI_SCALE; + static const Option* FOV; + static const Option* GAMMA; + static const Option* RENDER_CLOUDS; + static const Option* PARTICLES; - private: - const bool _isProgress; + private: + const bool _isProgress; const bool _isBoolean; const std::wstring captionId; - public: - static const Option *getItem(int id); + public: + static const Option* getItem(int id); Option(const std::wstring& captionId, bool hasProgress, bool isBoolean); - bool isProgress() const; - bool isBoolean() const; - int getId() const; - std::wstring getCaptionId() const; + bool isProgress() const; + bool isBoolean() const; + int getId() const; + std::wstring getCaptionId() const; }; private: - static const std::wstring RENDER_DISTANCE_NAMES[]; + static const std::wstring RENDER_DISTANCE_NAMES[]; static const std::wstring DIFFICULTY_NAMES[]; static const std::wstring GUI_SCALE[]; static const std::wstring FRAMERATE_LIMITS[]; - static const std::wstring PARTICLES[]; + static const std::wstring PARTICLES[]; public: - float music; + float music; float sound; float sensitivity; bool invertYMouse; @@ -68,34 +66,35 @@ public: int framerateLimit; bool fancyGraphics; bool ambientOcclusion; - bool renderClouds; + bool renderClouds; std::wstring skin; - KeyMapping *keyUp; - KeyMapping *keyLeft; - KeyMapping *keyDown; - KeyMapping *keyRight; - KeyMapping *keyJump; - KeyMapping *keyBuild; - KeyMapping *keyDrop; - KeyMapping *keyChat; - KeyMapping *keySneak; - KeyMapping *keyAttack; - KeyMapping *keyUse; - KeyMapping *keyPlayerList; - KeyMapping *keyPickItem; - KeyMapping *keyToggleFog; + KeyMapping* keyUp; + KeyMapping* keyLeft; + KeyMapping* keyDown; + KeyMapping* keyRight; + KeyMapping* keyJump; + KeyMapping* keyBuild; + KeyMapping* keyDrop; + KeyMapping* keyChat; + KeyMapping* keySneak; + KeyMapping* keyAttack; + KeyMapping* keyUse; + KeyMapping* keyPlayerList; + KeyMapping* keyPickItem; + KeyMapping* keyToggleFog; - static const int keyMappings_length = 14; - KeyMapping *keyMappings[keyMappings_length]; + static const int keyMappings_length = 14; + KeyMapping* keyMappings[keyMappings_length]; protected: - Minecraft *minecraft; + Minecraft* minecraft; + private: - File optionsFile; + File optionsFile; public: - int difficulty; + int difficulty; bool hideGui; bool thirdPersonView; bool renderDebug; @@ -107,26 +106,28 @@ public: float flySpeed; float cameraSpeed; int guiScale; - int particles; // 0 is all, 1 is decreased and 2 is minimal - float fov; - float gamma; + int particles; // 0 is all, 1 is decreased and 2 is minimal + float fov; + float gamma; - void init(); // 4J added - Options(Minecraft *minecraft, File workingDirectory); + void init(); // 4J added + Options(Minecraft* minecraft, File workingDirectory); Options(); std::wstring getKeyDescription(int i); std::wstring getKeyMessage(int i); void setKey(int i, int key); - void set(const Options::Option *item, float value); - void toggle(const Options::Option *option, int dir); - float getProgressValue(const Options::Option *item); - bool getBooleanValue(const Options::Option *item); - std::wstring getMessage(const Options::Option *item); + void set(const Options::Option* item, float value); + void toggle(const Options::Option* option, int dir); + float getProgressValue(const Options::Option* item); + bool getBooleanValue(const Options::Option* item); + std::wstring getMessage(const Options::Option* item); void load(); -private: - float readFloat(std::wstring string); -public: - void save(); - bool isCloudsOn(); +private: + float readFloat(std::wstring string); + +public: + void save(); + + bool isCloudsOn(); }; diff --git a/Minecraft.Client/GameState/Settings.cpp b/Minecraft.Client/GameState/Settings.cpp index 7f035e18c..658cebd32 100644 --- a/Minecraft.Client/GameState/Settings.cpp +++ b/Minecraft.Client/GameState/Settings.cpp @@ -3,53 +3,41 @@ #include "../../Minecraft.World/Util/StringHelpers.h" // 4J - TODO - serialise/deserialise from file -Settings::Settings(File *file) -{ +Settings::Settings(File* file) {} + +void Settings::generateNewProperties() {} + +void Settings::saveProperties() {} + +std::wstring Settings::getString(const std::wstring& key, + const std::wstring& defaultValue) { + if (properties.find(key) == properties.end()) { + properties[key] = defaultValue; + saveProperties(); + } + return properties[key]; } -void Settings::generateNewProperties() -{ +int Settings::getInt(const std::wstring& key, int defaultValue) { + if (properties.find(key) == properties.end()) { + properties[key] = _toString(defaultValue); + saveProperties(); + } + return _fromString(properties[key]); } -void Settings::saveProperties() -{ +bool Settings::getBoolean(const std::wstring& key, bool defaultValue) { + if (properties.find(key) == properties.end()) { + properties[key] = _toString(defaultValue); + saveProperties(); + } + MemSect(35); + bool retval = _fromString(properties[key]); + MemSect(0); + return retval; } -std::wstring Settings::getString(const std::wstring& key, const std::wstring& defaultValue) -{ - if(properties.find(key) == properties.end()) - { - properties[key] = defaultValue; - saveProperties(); - } - return properties[key]; -} - -int Settings::getInt(const std::wstring& key, int defaultValue) -{ - if(properties.find(key) == properties.end()) - { - properties[key] = _toString(defaultValue); - saveProperties(); - } - return _fromString(properties[key]); -} - -bool Settings::getBoolean(const std::wstring& key, bool defaultValue) -{ - if(properties.find(key) == properties.end()) - { - properties[key] = _toString(defaultValue); - saveProperties(); - } - MemSect(35); - bool retval = _fromString(properties[key]); - MemSect(0); - return retval; -} - -void Settings::setBooleanAndSave(const std::wstring& key, bool value) -{ - properties[key] = _toString(value); - saveProperties(); +void Settings::setBooleanAndSave(const std::wstring& key, bool value) { + properties[key] = _toString(value); + saveProperties(); } \ No newline at end of file diff --git a/Minecraft.Client/GameState/Settings.h b/Minecraft.Client/GameState/Settings.h index 8ead97244..cacdd6857 100644 --- a/Minecraft.Client/GameState/Settings.h +++ b/Minecraft.Client/GameState/Settings.h @@ -1,20 +1,21 @@ #pragma once class File; - -class Settings -{ -// public static Logger logger = Logger.getLogger("Minecraft"); -// private Properties properties = new Properties(); +class Settings { + // public static Logger logger = Logger.getLogger("Minecraft"); + // private Properties properties = new Properties(); private: - std::unordered_map properties; // 4J - TODO was Properties type, will need to implement something we can serialise/deserialise too - //File *file; + std::unordered_map + properties; // 4J - TODO was Properties type, will need to implement + // something we can serialise/deserialise too + // File *file; public: - Settings(File *file); + Settings(File* file); void generateNewProperties(); void saveProperties(); - std::wstring getString(const std::wstring& key, const std::wstring& defaultValue); + std::wstring getString(const std::wstring& key, + const std::wstring& defaultValue); int getInt(const std::wstring& key, int defaultValue); bool getBoolean(const std::wstring& key, bool defaultValue); void setBooleanAndSave(const std::wstring& key, bool value); diff --git a/Minecraft.Client/GameState/StatsCounter.cpp b/Minecraft.Client/GameState/StatsCounter.cpp index b63e909f7..a03bd236c 100644 --- a/Minecraft.Client/GameState/StatsCounter.cpp +++ b/Minecraft.Client/GameState/StatsCounter.cpp @@ -12,1341 +12,1915 @@ #include "../Platform/Common/Leaderboards/LeaderboardManager.h" #include -Stat** StatsCounter::LARGE_STATS[] = { - &Stats::walkOneM, - &Stats::swimOneM, - &Stats::fallOneM, - &Stats::climbOneM, - &Stats::minecartOneM, - &Stats::boatOneM, - &Stats::pigOneM, - &Stats::timePlayed -}; +Stat** StatsCounter::LARGE_STATS[] = {&Stats::walkOneM, &Stats::swimOneM, + &Stats::fallOneM, &Stats::climbOneM, + &Stats::minecartOneM, &Stats::boatOneM, + &Stats::pigOneM, &Stats::timePlayed}; std::unordered_map StatsCounter::statBoards; -StatsCounter::StatsCounter() -{ - requiresSave = false; - saveCounter = 0; - modifiedBoards = 0; - flushCounter = 0; +StatsCounter::StatsCounter() { + requiresSave = false; + saveCounter = 0; + modifiedBoards = 0; + flushCounter = 0; } -void StatsCounter::award(Stat* stat, unsigned int difficulty, unsigned int count) -{ +void StatsCounter::award(Stat* stat, unsigned int difficulty, + unsigned int count) { #ifndef _DURANGO - if( stat->isAchievement() ) - difficulty = 0; + if (stat->isAchievement()) difficulty = 0; - StatsMap::iterator val = stats.find(stat); - if( val == stats.end() ) - { - StatContainer newVal; - newVal.stats[difficulty] = count; - stats.insert( std::make_pair(stat, newVal) ); - } - else - { - val->second.stats[difficulty] += count; + StatsMap::iterator val = stats.find(stat); + if (val == stats.end()) { + StatContainer newVal; + newVal.stats[difficulty] = count; + stats.insert(std::make_pair(stat, newVal)); + } else { + val->second.stats[difficulty] += count; - if (stat != GenericStats::timePlayed()) - app.DebugPrintf(""); + if (stat != GenericStats::timePlayed()) app.DebugPrintf(""); - //If value has wrapped, cap it to UINT_MAX - if( val->second.stats[difficulty] < (val->second.stats[difficulty]-count) ) - val->second.stats[difficulty] = UINT_MAX; + // If value has wrapped, cap it to UINT_MAX + if (val->second.stats[difficulty] < + (val->second.stats[difficulty] - count)) + val->second.stats[difficulty] = UINT_MAX; - //If value is larger than USHRT_MAX and is not designated as large, cap it to USHRT_MAX - if( val->second.stats[difficulty] > USHRT_MAX && !isLargeStat(stat) ) - val->second.stats[difficulty] = USHRT_MAX; - } + // If value is larger than USHRT_MAX and is not designated as large, cap + // it to USHRT_MAX + if (val->second.stats[difficulty] > USHRT_MAX && !isLargeStat(stat)) + val->second.stats[difficulty] = USHRT_MAX; + } - requiresSave = true; + requiresSave = true; - //If this stat is on a leaderboard, mark that leaderboard as needing updated - std::unordered_map::iterator leaderboardEntry = statBoards.find(stat); - if( leaderboardEntry != statBoards.end() ) - { - app.DebugPrintf("[StatsCounter] award(): %X\n", leaderboardEntry->second << difficulty); - modifiedBoards |= (leaderboardEntry->second << difficulty); - if( flushCounter == 0 ) - flushCounter = FLUSH_DELAY; - } + // If this stat is on a leaderboard, mark that leaderboard as needing + // updated + std::unordered_map::iterator leaderboardEntry = + statBoards.find(stat); + if (leaderboardEntry != statBoards.end()) { + app.DebugPrintf("[StatsCounter] award(): %X\n", + leaderboardEntry->second << difficulty); + modifiedBoards |= (leaderboardEntry->second << difficulty); + if (flushCounter == 0) flushCounter = FLUSH_DELAY; + } #endif } -bool StatsCounter::hasTaken(Achievement *ach) -{ - return stats.find(ach) != stats.end(); +bool StatsCounter::hasTaken(Achievement* ach) { + return stats.find(ach) != stats.end(); } -bool StatsCounter::canTake(Achievement *ach) -{ - //4J Gordon: Remove achievement dependencies, always able to take - return true; +bool StatsCounter::canTake(Achievement* ach) { + // 4J Gordon: Remove achievement dependencies, always able to take + return true; } -unsigned int StatsCounter::getValue(Stat *stat, unsigned int difficulty) -{ - StatsMap::iterator val = stats.find(stat); - if( val != stats.end() ) - return val->second.stats[difficulty]; - return 0; +unsigned int StatsCounter::getValue(Stat* stat, unsigned int difficulty) { + StatsMap::iterator val = stats.find(stat); + if (val != stats.end()) return val->second.stats[difficulty]; + return 0; } -unsigned int StatsCounter::getTotalValue(Stat *stat) -{ - StatsMap::iterator val = stats.find(stat); - if( val != stats.end() ) - return val->second.stats[0] + val->second.stats[1] + val->second.stats[2] + val->second.stats[3]; - return 0; +unsigned int StatsCounter::getTotalValue(Stat* stat) { + StatsMap::iterator val = stats.find(stat); + if (val != stats.end()) + return val->second.stats[0] + val->second.stats[1] + + val->second.stats[2] + val->second.stats[3]; + return 0; } -void StatsCounter::tick(int player) -{ - if( saveCounter > 0 ) - --saveCounter; +void StatsCounter::tick(int player) { + if (saveCounter > 0) --saveCounter; - if( requiresSave && saveCounter == 0 ) - save(player); + if (requiresSave && saveCounter == 0) save(player); - // 4J-JEV, we don't want to write leaderboards in the middle of a game. - // EDIT: Yes we do, people were not ending their games properly and not updating scores. -// #ifndef __PS3__ - if( flushCounter > 0 ) - { - --flushCounter; - if( flushCounter == 0 ) - flushLeaderboards(); - } -// #endif + // 4J-JEV, we don't want to write leaderboards in the middle of a game. + // EDIT: Yes we do, people were not ending their games properly and not + // updating scores. + // #ifndef __PS3__ + if (flushCounter > 0) { + --flushCounter; + if (flushCounter == 0) flushLeaderboards(); + } + // #endif } -void StatsCounter::clear() -{ - // clear out the stats when someone signs out - stats.clear(); +void StatsCounter::clear() { + // clear out the stats when someone signs out + stats.clear(); } -void StatsCounter::parse(void* data) -{ +void StatsCounter::parse(void* data) { #ifndef _DURANGO - // 4J-PB - If this is the trial game, let's just make sure all the stats are empty - // 4J-PB - removing - someone can have the full game, and then remove it and go back to the trial -// if(!ProfileManager.IsFullVersion()) -// { -// stats.clear(); -// return; -// } - //Check that we don't already have any stats - assert( stats.size() == 0 ); + // 4J-PB - If this is the trial game, let's just make sure all the stats are + // empty 4J-PB - removing - someone can have the full game, and then remove + // it and go back to the trial + // if(!ProfileManager.IsFullVersion()) + // { + // stats.clear(); + // return; + // } + // Check that we don't already have any stats + assert(stats.size() == 0); - //Pointer to current position in stat array - std::uint8_t* pbData = reinterpret_cast(data); - pbData += sizeof(GAME_SETTINGS); - std::uint8_t* statData = pbData; + // Pointer to current position in stat array + std::uint8_t* pbData = reinterpret_cast(data); + pbData += sizeof(GAME_SETTINGS); + std::uint8_t* statData = pbData; - //Value being read - StatContainer newVal; + // Value being read + StatContainer newVal; - //For each stat - std::vector::iterator end = Stats::all->end(); - for( std::vector::iterator iter = Stats::all->begin() ; iter != end ; ++iter ) - { - if( !(*iter)->isAchievement() ) - { - if( !isLargeStat(*iter) ) - { - std::uint16_t difficultyStats[eDifficulty_Max] = {}; - std::memcpy(difficultyStats, statData, sizeof(difficultyStats)); - if( difficultyStats[0] != 0 || difficultyStats[1] != 0 || difficultyStats[2] != 0 || difficultyStats[3] != 0 ) - { - newVal.stats[0] = difficultyStats[0]; - newVal.stats[1] = difficultyStats[1]; - newVal.stats[2] = difficultyStats[2]; - newVal.stats[3] = difficultyStats[3]; - stats.insert( std::make_pair(*iter, newVal) ); - } - statData += sizeof(difficultyStats); - } - else - { - std::uint32_t largeStatData[eDifficulty_Max] = {}; - std::memcpy(largeStatData, statData, sizeof(largeStatData)); - if( largeStatData[0] != 0 || largeStatData[1] != 0 || largeStatData[2] != 0 || largeStatData[3] != 0 ) - { - newVal.stats[0] = largeStatData[0]; - newVal.stats[1] = largeStatData[1]; - newVal.stats[2] = largeStatData[2]; - newVal.stats[3] = largeStatData[3]; - stats.insert( std::make_pair(*iter, newVal) ); - } - statData += sizeof(largeStatData); - } - } - else - { - std::uint16_t achievementValue = 0; - std::memcpy(&achievementValue, statData, sizeof(achievementValue)); - if( achievementValue != 0 ) - { - newVal.stats[0] = achievementValue; - newVal.stats[1] = 0; - newVal.stats[2] = 0; - newVal.stats[3] = 0; - stats.insert( std::make_pair(*iter, newVal) ); - } - statData += sizeof(achievementValue); - } - } + // For each stat + std::vector::iterator end = Stats::all->end(); + for (std::vector::iterator iter = Stats::all->begin(); iter != end; + ++iter) { + if (!(*iter)->isAchievement()) { + if (!isLargeStat(*iter)) { + std::uint16_t difficultyStats[eDifficulty_Max] = {}; + std::memcpy(difficultyStats, statData, sizeof(difficultyStats)); + if (difficultyStats[0] != 0 || difficultyStats[1] != 0 || + difficultyStats[2] != 0 || difficultyStats[3] != 0) { + newVal.stats[0] = difficultyStats[0]; + newVal.stats[1] = difficultyStats[1]; + newVal.stats[2] = difficultyStats[2]; + newVal.stats[3] = difficultyStats[3]; + stats.insert(std::make_pair(*iter, newVal)); + } + statData += sizeof(difficultyStats); + } else { + std::uint32_t largeStatData[eDifficulty_Max] = {}; + std::memcpy(largeStatData, statData, sizeof(largeStatData)); + if (largeStatData[0] != 0 || largeStatData[1] != 0 || + largeStatData[2] != 0 || largeStatData[3] != 0) { + newVal.stats[0] = largeStatData[0]; + newVal.stats[1] = largeStatData[1]; + newVal.stats[2] = largeStatData[2]; + newVal.stats[3] = largeStatData[3]; + stats.insert(std::make_pair(*iter, newVal)); + } + statData += sizeof(largeStatData); + } + } else { + std::uint16_t achievementValue = 0; + std::memcpy(&achievementValue, statData, sizeof(achievementValue)); + if (achievementValue != 0) { + newVal.stats[0] = achievementValue; + newVal.stats[1] = 0; + newVal.stats[2] = 0; + newVal.stats[3] = 0; + stats.insert(std::make_pair(*iter, newVal)); + } + statData += sizeof(achievementValue); + } + } - dumpStatsToTTY(); + dumpStatsToTTY(); #endif } -void StatsCounter::save(int player, bool force) -{ +void StatsCounter::save(int player, bool force) { #ifndef _DURANGO - // 4J-PB - If this is the trial game, don't save any stats - if(!ProfileManager.IsFullVersion()) - { - return; - } + // 4J-PB - If this is the trial game, don't save any stats + if (!ProfileManager.IsFullVersion()) { + return; + } - //Check we're going to have enough room to store all possible stats - unsigned int uiTotalStatsSize = (Stats::all->size() * 4 * sizeof(unsigned short)) - (Achievements::achievements->size() * 3 * sizeof(unsigned short)) + (LARGE_STATS_COUNT*4*(sizeof(unsigned int)-sizeof(unsigned short))); - assert( uiTotalStatsSize <= (CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES-sizeof(GAME_SETTINGS)) ); + // Check we're going to have enough room to store all possible stats + unsigned int uiTotalStatsSize = + (Stats::all->size() * 4 * sizeof(unsigned short)) - + (Achievements::achievements->size() * 3 * sizeof(unsigned short)) + + (LARGE_STATS_COUNT * 4 * + (sizeof(unsigned int) - sizeof(unsigned short))); + assert(uiTotalStatsSize <= + (CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES - + sizeof(GAME_SETTINGS))); - //Retrieve the data pointer from the profile -#if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__ ) - std::uint8_t* pbData = reinterpret_cast(StorageManager.GetGameDefinedProfileData(player)); + // Retrieve the data pointer from the profile +#if (defined __PS3__ || defined __ORBIS__ || defined _DURANGO || \ + defined __PSVITA__) + std::uint8_t* pbData = reinterpret_cast( + StorageManager.GetGameDefinedProfileData(player)); #else - std::uint8_t* pbData = reinterpret_cast(ProfileManager.GetGameDefinedProfileData(player)); + std::uint8_t* pbData = reinterpret_cast( + ProfileManager.GetGameDefinedProfileData(player)); #endif - pbData += sizeof(GAME_SETTINGS); - - //Pointer to current position in stat array - std::uint8_t* statData = pbData; + pbData += sizeof(GAME_SETTINGS); - //Reset all the data to 0 (we're going to replace it with the map data) - memset(statData, 0, CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES-sizeof(GAME_SETTINGS)); + // Pointer to current position in stat array + std::uint8_t* statData = pbData; - //For each stat - StatsMap::iterator val; - std::vector::iterator end = Stats::all->end(); - for( std::vector::iterator iter = Stats::all->begin() ; iter != end ; ++iter ) - { - //If the stat is in the map write out it's value - val = stats.find(*iter); - if( !(*iter)->isAchievement() ) - { - if( !isLargeStat(*iter) ) - { - std::uint16_t difficultyStats[eDifficulty_Max] = {}; - if( val != stats.end() ) - { - difficultyStats[0] = static_cast(val->second.stats[0]); - difficultyStats[1] = static_cast(val->second.stats[1]); - difficultyStats[2] = static_cast(val->second.stats[2]); - difficultyStats[3] = static_cast(val->second.stats[3]); - } - std::memcpy(statData, difficultyStats, sizeof(difficultyStats)); - statData += sizeof(difficultyStats); - } - else - { - std::uint32_t largeStatData[eDifficulty_Max] = {}; - if( val != stats.end() ) - { - largeStatData[0] = val->second.stats[0]; - largeStatData[1] = val->second.stats[1]; - largeStatData[2] = val->second.stats[2]; - largeStatData[3] = val->second.stats[3]; - } - std::memcpy(statData, largeStatData, sizeof(largeStatData)); - statData += sizeof(largeStatData); - } - } - else - { - std::uint16_t achievementValue = 0; - if( val != stats.end() ) - { - achievementValue = static_cast(val->second.stats[0]); - } - std::memcpy(statData, &achievementValue, sizeof(achievementValue)); - statData += sizeof(achievementValue); - } - } + // Reset all the data to 0 (we're going to replace it with the map data) + memset(statData, 0, + CConsoleMinecraftApp::GAME_DEFINED_PROFILE_DATA_BYTES - + sizeof(GAME_SETTINGS)); -#if ( defined __PS3__ || defined __ORBIS__ || defined _DURANGO || defined __PSVITA__ ) - StorageManager.WriteToProfile(player, true, force); + // For each stat + StatsMap::iterator val; + std::vector::iterator end = Stats::all->end(); + for (std::vector::iterator iter = Stats::all->begin(); iter != end; + ++iter) { + // If the stat is in the map write out it's value + val = stats.find(*iter); + if (!(*iter)->isAchievement()) { + if (!isLargeStat(*iter)) { + std::uint16_t difficultyStats[eDifficulty_Max] = {}; + if (val != stats.end()) { + difficultyStats[0] = + static_cast(val->second.stats[0]); + difficultyStats[1] = + static_cast(val->second.stats[1]); + difficultyStats[2] = + static_cast(val->second.stats[2]); + difficultyStats[3] = + static_cast(val->second.stats[3]); + } + std::memcpy(statData, difficultyStats, sizeof(difficultyStats)); + statData += sizeof(difficultyStats); + } else { + std::uint32_t largeStatData[eDifficulty_Max] = {}; + if (val != stats.end()) { + largeStatData[0] = val->second.stats[0]; + largeStatData[1] = val->second.stats[1]; + largeStatData[2] = val->second.stats[2]; + largeStatData[3] = val->second.stats[3]; + } + std::memcpy(statData, largeStatData, sizeof(largeStatData)); + statData += sizeof(largeStatData); + } + } else { + std::uint16_t achievementValue = 0; + if (val != stats.end()) { + achievementValue = + static_cast(val->second.stats[0]); + } + std::memcpy(statData, &achievementValue, sizeof(achievementValue)); + statData += sizeof(achievementValue); + } + } + +#if (defined __PS3__ || defined __ORBIS__ || defined _DURANGO || \ + defined __PSVITA__) + StorageManager.WriteToProfile(player, true, force); #else - ProfileManager.WriteToProfile(player, true, force); + ProfileManager.WriteToProfile(player, true, force); #endif - saveCounter = SAVE_DELAY; + saveCounter = SAVE_DELAY; #endif } #ifdef _XBOX -void StatsCounter::setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id, unsigned int value) -{ - app.DebugPrintf("Setting property id: %d to value %d\n", id, value); - prop->dwPropertyId = id; - prop->value.type = XUSER_DATA_TYPE_INT32; - prop->value.nData = (int)(value&0x7FFFFFFF); // Just making sure we clamp the unsigned int to the max val for a signed int +void StatsCounter::setLeaderboardProperty(XUSER_PROPERTY* prop, + std::uint32_t id, + unsigned int value) { + app.DebugPrintf("Setting property id: %d to value %d\n", id, value); + prop->dwPropertyId = id; + prop->value.type = XUSER_DATA_TYPE_INT32; + prop->value.nData = + (int)(value & 0x7FFFFFFF); // Just making sure we clamp the unsigned + // int to the max val for a signed int } -void StatsCounter::setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value) -{ - prop->dwPropertyId = PROPERTY_RATING; - prop->value.type = XUSER_DATA_TYPE_INT64; - prop->value.i64Data = value; +void StatsCounter::setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value) { + prop->dwPropertyId = PROPERTY_RATING; + prop->value.type = XUSER_DATA_TYPE_INT64; + prop->value.i64Data = value; } #endif -void StatsCounter::flushLeaderboards() -{ +void StatsCounter::flushLeaderboards() { #ifndef _DURANGO - if( LeaderboardManager::Instance()->OpenSession() ) - { - writeStats(); - LeaderboardManager::Instance()->FlushStats(); - } - else - { - app.DebugPrintf("Failed to open a session in order to write to leaderboard\n"); + if (LeaderboardManager::Instance()->OpenSession()) { + writeStats(); + LeaderboardManager::Instance()->FlushStats(); + } else { + app.DebugPrintf( + "Failed to open a session in order to write to leaderboard\n"); - // 4J-JEV: If user was not signed in it would hit this. - //assert(false);// && "Failed to open a session in order to write to leaderboard"); - } + // 4J-JEV: If user was not signed in it would hit this. + // assert(false);// && "Failed to open a session in order to write to + // leaderboard"); + } - modifiedBoards = 0; + modifiedBoards = 0; #endif } -void StatsCounter::saveLeaderboards() -{ +void StatsCounter::saveLeaderboards() { #ifndef _DURANGO - // 4J-PB - If this is the trial game, no writing leaderboards - if(!ProfileManager.IsFullVersion()) - { - return; - } + // 4J-PB - If this is the trial game, no writing leaderboards + if (!ProfileManager.IsFullVersion()) { + return; + } - if( LeaderboardManager::Instance()->OpenSession() ) - { - writeStats(); - LeaderboardManager::Instance()->CloseSession(); - } - else - { - app.DebugPrintf("Failed to open a session in order to write to leaderboard\n"); + if (LeaderboardManager::Instance()->OpenSession()) { + writeStats(); + LeaderboardManager::Instance()->CloseSession(); + } else { + app.DebugPrintf( + "Failed to open a session in order to write to leaderboard\n"); - // 4J-JEV: If user was not signed in it would hit this. - //assert(false);// && "Failed to open a session in order to write to leaderboard"); - } + // 4J-JEV: If user was not signed in it would hit this. + // assert(false);// && "Failed to open a session in order to write to + // leaderboard"); + } - modifiedBoards = 0; + modifiedBoards = 0; #endif } -void StatsCounter::writeStats() -{ +void StatsCounter::writeStats() { #ifndef _DURANGO - // 4J-PB - If this is the trial game, no writing - if(!ProfileManager.IsFullVersion()) - { - return; - } - //unsigned int locale = XGetLocale(); - - int viewCount = 0; - int iPad = ProfileManager.GetLockedProfile(); - -#if defined(__PS3__) || defined(__ORBIS__) || defined (__PSVITA__) - LeaderboardManager::RegisterScore *scores = new LeaderboardManager::RegisterScore[24]; - - if( modifiedBoards & LEADERBOARD_KILLS_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Kills; - - scores[viewCount].m_commentData.m_kills.m_zombie = getValue(Stats::killsZombie, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_skeleton = getValue(Stats::killsSkeleton, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_creeper = getValue(Stats::killsCreeper, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_spider = getValue(Stats::killsSpider, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_spiderJockey = getValue(Stats::killsSpiderJockey, eDifficulty_Easy); - //scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsZombiePigman, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); - scores[viewCount].m_commentData.m_kills.m_slime = getValue(Stats::killsSlime, eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_kills.m_zombie - + scores[viewCount].m_commentData.m_kills.m_skeleton - + scores[viewCount].m_commentData.m_kills.m_creeper - + scores[viewCount].m_commentData.m_kills.m_spider - + scores[viewCount].m_commentData.m_kills.m_spiderJockey - // + getValue(Stats::killsZombiePigman, eDifficulty_Easy); - + scores[viewCount].m_commentData.m_kills.m_zombiePigman - + scores[viewCount].m_commentData.m_kills.m_slime; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_KILLS_NORMAL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Kills; - - scores[viewCount].m_commentData.m_kills.m_zombie = getValue(Stats::killsZombie, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_skeleton = getValue(Stats::killsSkeleton, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_creeper = getValue(Stats::killsCreeper, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_spider = getValue(Stats::killsSpider, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_spiderJockey = getValue(Stats::killsSpiderJockey, eDifficulty_Normal); - //scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsZombiePigman, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); - scores[viewCount].m_commentData.m_kills.m_slime = getValue(Stats::killsSlime, eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_kills.m_zombie - + scores[viewCount].m_commentData.m_kills.m_skeleton - + scores[viewCount].m_commentData.m_kills.m_creeper - + scores[viewCount].m_commentData.m_kills.m_spider - + scores[viewCount].m_commentData.m_kills.m_spiderJockey - // + getValue(Stats::killsZombiePigman, eDifficulty_Normal); - + scores[viewCount].m_commentData.m_kills.m_zombiePigman - + scores[viewCount].m_commentData.m_kills.m_slime; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_KILLS_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Kills; - - scores[viewCount].m_commentData.m_kills.m_zombie = getValue(Stats::killsZombie, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_skeleton = getValue(Stats::killsSkeleton, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_creeper = getValue(Stats::killsCreeper, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_spider = getValue(Stats::killsSpider, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_spiderJockey = getValue(Stats::killsSpiderJockey, eDifficulty_Hard); - //scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsZombiePigman, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_zombiePigman = getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); - scores[viewCount].m_commentData.m_kills.m_slime = getValue(Stats::killsSlime, eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_kills.m_zombie - + scores[viewCount].m_commentData.m_kills.m_skeleton - + scores[viewCount].m_commentData.m_kills.m_creeper - + scores[viewCount].m_commentData.m_kills.m_spider - + scores[viewCount].m_commentData.m_kills.m_spiderJockey - // + getValue(Stats::killsZombiePigman, eDifficulty_Hard); - + scores[viewCount].m_commentData.m_kills.m_zombiePigman - + scores[viewCount].m_commentData.m_kills.m_slime; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); - scores[viewCount].m_difficulty = 0; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Mining; - - scores[viewCount].m_commentData.m_mining.m_dirt = getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_sand = getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_stone = getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_gravel = getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_clay = getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_mining.m_obsidian = getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_mining.m_dirt - + scores[viewCount].m_commentData.m_mining.m_cobblestone - + scores[viewCount].m_commentData.m_mining.m_sand - + scores[viewCount].m_commentData.m_mining.m_stone - + scores[viewCount].m_commentData.m_mining.m_gravel - + scores[viewCount].m_commentData.m_mining.m_clay - + scores[viewCount].m_commentData.m_mining.m_obsidian; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_PEACEFUL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); - scores[viewCount].m_difficulty = 0; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Easy); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_NORMAL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Normal); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_FARMING_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Farming; - - scores[viewCount].m_commentData.m_farming.m_eggs = getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_wheat = getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_mushroom = getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_sugarcane = getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_milk = getValue(Stats::cowsMilked, eDifficulty_Hard); - scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_farming.m_eggs - + scores[viewCount].m_commentData.m_farming.m_wheat - + scores[viewCount].m_commentData.m_farming.m_mushroom - + scores[viewCount].m_commentData.m_farming.m_sugarcane - + scores[viewCount].m_commentData.m_farming.m_milk - + scores[viewCount].m_commentData.m_farming.m_pumpkin; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); - scores[viewCount].m_difficulty = 0; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Peaceful); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Peaceful); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_EASY ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); - scores[viewCount].m_difficulty = 1; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Easy); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Easy); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Easy); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Easy); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); - scores[viewCount].m_difficulty = 2; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Normal); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Normal); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Normal); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Normal); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & LEADERBOARD_TRAVELLING_HARD ) - { - scores[viewCount].m_iPad = iPad; - - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); - scores[viewCount].m_difficulty = 3; - - scores[viewCount].m_commentData.m_statsType = LeaderboardManager::eStatsType_Travelling; - - scores[viewCount].m_commentData.m_travelling.m_walked = getValue(Stats::walkOneM, eDifficulty_Hard); - scores[viewCount].m_commentData.m_travelling.m_fallen = getValue(Stats::fallOneM, eDifficulty_Hard); - scores[viewCount].m_commentData.m_travelling.m_minecart = getValue(Stats::minecartOneM, eDifficulty_Hard); - scores[viewCount].m_commentData.m_travelling.m_boat = getValue(Stats::boatOneM, eDifficulty_Hard); - - scores[viewCount].m_score = scores[viewCount].m_commentData.m_travelling.m_walked - + scores[viewCount].m_commentData.m_travelling.m_fallen - + scores[viewCount].m_commentData.m_travelling.m_minecart - + scores[viewCount].m_commentData.m_travelling.m_boat; - - viewCount++; - } - - if( modifiedBoards & (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD) ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD\n"); - - //viewCount++; - } - - if( viewCount > 0 ) - { - if( !LeaderboardManager::Instance()->WriteStats(viewCount, scores) ) - { - app.DebugPrintf("Failed to write to leaderboard\n"); - assert(false);// && "Failed to write to leaderboard"); - //printf("Failed to write to leaderboard"); - } - else - { - app.DebugPrintf("Successfully wrote %d leadeboard views\n", viewCount); - } - } + // 4J-PB - If this is the trial game, no writing + if (!ProfileManager.IsFullVersion()) { + return; + } + // unsigned int locale = XGetLocale(); + + int viewCount = 0; + int iPad = ProfileManager.GetLockedProfile(); + +#if defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) + LeaderboardManager::RegisterScore* scores = + new LeaderboardManager::RegisterScore[24]; + + if (modifiedBoards & LEADERBOARD_KILLS_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Kills; + + scores[viewCount].m_commentData.m_kills.m_zombie = + getValue(Stats::killsZombie, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_skeleton = + getValue(Stats::killsSkeleton, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_creeper = + getValue(Stats::killsCreeper, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_spider = + getValue(Stats::killsSpider, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_spiderJockey = + getValue(Stats::killsSpiderJockey, eDifficulty_Easy); + // scores[viewCount].m_commentData.m_kills.m_zombiePigman = + // getValue(Stats::killsZombiePigman, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_zombiePigman = + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); + scores[viewCount].m_commentData.m_kills.m_slime = + getValue(Stats::killsSlime, eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_kills.m_zombie + + scores[viewCount].m_commentData.m_kills.m_skeleton + + scores[viewCount].m_commentData.m_kills.m_creeper + + scores[viewCount].m_commentData.m_kills.m_spider + + scores[viewCount].m_commentData.m_kills.m_spiderJockey + // + getValue(Stats::killsZombiePigman, + // eDifficulty_Easy); + + scores[viewCount].m_commentData.m_kills.m_zombiePigman + + scores[viewCount].m_commentData.m_kills.m_slime; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_KILLS_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Kills; + + scores[viewCount].m_commentData.m_kills.m_zombie = + getValue(Stats::killsZombie, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_skeleton = + getValue(Stats::killsSkeleton, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_creeper = + getValue(Stats::killsCreeper, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_spider = + getValue(Stats::killsSpider, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_spiderJockey = + getValue(Stats::killsSpiderJockey, eDifficulty_Normal); + // scores[viewCount].m_commentData.m_kills.m_zombiePigman = + // getValue(Stats::killsZombiePigman, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_zombiePigman = + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); + scores[viewCount].m_commentData.m_kills.m_slime = + getValue(Stats::killsSlime, eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_kills.m_zombie + + scores[viewCount].m_commentData.m_kills.m_skeleton + + scores[viewCount].m_commentData.m_kills.m_creeper + + scores[viewCount].m_commentData.m_kills.m_spider + + scores[viewCount].m_commentData.m_kills.m_spiderJockey + // + getValue(Stats::killsZombiePigman, + // eDifficulty_Normal); + + scores[viewCount].m_commentData.m_kills.m_zombiePigman + + scores[viewCount].m_commentData.m_kills.m_slime; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_KILLS_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Kills; + + scores[viewCount].m_commentData.m_kills.m_zombie = + getValue(Stats::killsZombie, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_skeleton = + getValue(Stats::killsSkeleton, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_creeper = + getValue(Stats::killsCreeper, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_spider = + getValue(Stats::killsSpider, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_spiderJockey = + getValue(Stats::killsSpiderJockey, eDifficulty_Hard); + // scores[viewCount].m_commentData.m_kills.m_zombiePigman = + // getValue(Stats::killsZombiePigman, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_zombiePigman = + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); + scores[viewCount].m_commentData.m_kills.m_slime = + getValue(Stats::killsSlime, eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_kills.m_zombie + + scores[viewCount].m_commentData.m_kills.m_skeleton + + scores[viewCount].m_commentData.m_kills.m_creeper + + scores[viewCount].m_commentData.m_kills.m_spider + + scores[viewCount].m_commentData.m_kills.m_spiderJockey + // + getValue(Stats::killsZombiePigman, + // eDifficulty_Hard); + + scores[viewCount].m_commentData.m_kills.m_zombiePigman + + scores[viewCount].m_commentData.m_kills.m_slime; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); + scores[viewCount].m_difficulty = 0; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_gravel = getValue( + Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_mining.m_obsidian = getValue( + Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_gravel = + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_mining.m_obsidian = + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_gravel = + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_mining.m_obsidian = getValue( + Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Mining; + + scores[viewCount].m_commentData.m_mining.m_dirt = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_cobblestone = getValue( + Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_sand = + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_stone = + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_gravel = + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_clay = + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_mining.m_obsidian = + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_mining.m_dirt + + scores[viewCount].m_commentData.m_mining.m_cobblestone + + scores[viewCount].m_commentData.m_mining.m_sand + + scores[viewCount].m_commentData.m_mining.m_stone + + scores[viewCount].m_commentData.m_mining.m_gravel + + scores[viewCount].m_commentData.m_mining.m_clay + + scores[viewCount].m_commentData.m_mining.m_obsidian; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_PEACEFUL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); + scores[viewCount].m_difficulty = 0; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = getValue( + Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_mushroom = getValue( + Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_mushroom = + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Easy); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_mushroom = getValue( + Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Normal); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Farming; + + scores[viewCount].m_commentData.m_farming.m_eggs = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_wheat = + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_mushroom = + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_sugarcane = + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_milk = + getValue(Stats::cowsMilked, eDifficulty_Hard); + scores[viewCount].m_commentData.m_farming.m_pumpkin = getValue( + Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_farming.m_eggs + + scores[viewCount].m_commentData.m_farming.m_wheat + + scores[viewCount].m_commentData.m_farming.m_mushroom + + scores[viewCount].m_commentData.m_farming.m_sugarcane + + scores[viewCount].m_commentData.m_farming.m_milk + + scores[viewCount].m_commentData.m_farming.m_pumpkin; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); + scores[viewCount].m_difficulty = 0; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Peaceful); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Peaceful); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_EASY) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); + scores[viewCount].m_difficulty = 1; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Easy); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Easy); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Easy); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Easy); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); + scores[viewCount].m_difficulty = 2; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Normal); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Normal); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Normal); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Normal); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_HARD) { + scores[viewCount].m_iPad = iPad; + + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); + scores[viewCount].m_difficulty = 3; + + scores[viewCount].m_commentData.m_statsType = + LeaderboardManager::eStatsType_Travelling; + + scores[viewCount].m_commentData.m_travelling.m_walked = + getValue(Stats::walkOneM, eDifficulty_Hard); + scores[viewCount].m_commentData.m_travelling.m_fallen = + getValue(Stats::fallOneM, eDifficulty_Hard); + scores[viewCount].m_commentData.m_travelling.m_minecart = + getValue(Stats::minecartOneM, eDifficulty_Hard); + scores[viewCount].m_commentData.m_travelling.m_boat = + getValue(Stats::boatOneM, eDifficulty_Hard); + + scores[viewCount].m_score = + scores[viewCount].m_commentData.m_travelling.m_walked + + scores[viewCount].m_commentData.m_travelling.m_fallen + + scores[viewCount].m_commentData.m_travelling.m_minecart + + scores[viewCount].m_commentData.m_travelling.m_boat; + + viewCount++; + } + + if (modifiedBoards & + (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | + LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD)) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | " + "LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | " + "LEADERBOARD_TRAVELLING_HARD\n"); + + // viewCount++; + } + + if (viewCount > 0) { + if (!LeaderboardManager::Instance()->WriteStats(viewCount, scores)) { + app.DebugPrintf("Failed to write to leaderboard\n"); + assert(false); // && "Failed to write to leaderboard"); + // printf("Failed to write to leaderboard"); + } else { + app.DebugPrintf("Successfully wrote %d leadeboard views\n", + viewCount); + } + } #elif defined _XBOX - - LONGLONG rating; - XSESSION_VIEW_PROPERTIES views[24]; + LONGLONG rating; - XUSER_PROPERTY killsEasyProperties[ LeaderboardManager::eProperty_Kills_Max]; - XUSER_PROPERTY killsNormalProperties[ LeaderboardManager::eProperty_Kills_Max]; - XUSER_PROPERTY killsHardProperties[ LeaderboardManager::eProperty_Kills_Max]; - XUSER_PROPERTY miningBlocksPeacefulProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY miningBlocksEasyProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY miningBlocksNormalProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY miningBlocksHardProperties[ LeaderboardManager::eProperty_Mining_Max]; - XUSER_PROPERTY farmingPeacefulProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY farmingEasyProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY farmingNormalProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY farmingHardProperties[ LeaderboardManager::eProperty_Farming_Max]; - XUSER_PROPERTY travellingPeacefulProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingEasyProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingNormalProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingHardProperties[ LeaderboardManager::eProperty_Travelling_Max]; - XUSER_PROPERTY travellingProperties[1]; // arcade leaderboard + XSESSION_VIEW_PROPERTIES views[24]; - if( modifiedBoards & LEADERBOARD_KILLS_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_KILLS_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Kills_Max; - views[viewCount].pProperties = killsEasyProperties; - - rating = - getValue(Stats::killsZombie, eDifficulty_Easy) + - getValue(Stats::killsSkeleton, eDifficulty_Easy) + - getValue(Stats::killsCreeper, eDifficulty_Easy) + - getValue(Stats::killsSpider, eDifficulty_Easy) + - getValue(Stats::killsSpiderJockey, eDifficulty_Easy) + - getValue(Stats::killsZombiePigman, eDifficulty_Easy) + - getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) + - getValue(Stats::killsSlime, eDifficulty_Easy); - - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Zombie ], PROPERTY_KILLS_ZOMBIE, getValue(Stats::killsZombie, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Skeleton ], PROPERTY_KILLS_SKELETON, getValue(Stats::killsSkeleton, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Creeper ], PROPERTY_KILLS_CREEPER, getValue(Stats::killsCreeper, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Spider ], PROPERTY_KILLS_SPIDER, getValue(Stats::killsSpider, eDifficulty_Easy) ); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_SpiderJockey ], PROPERTY_KILLS_SPIDERJOCKEY, getValue(Stats::killsSpiderJockey, eDifficulty_Easy) ); - // 4J-PB - this could overflow - //setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, getValue(Stats::killsZombiePigman, eDifficulty_Easy) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) ); - ULONGLONG ulTemp=getValue(Stats::killsZombiePigman, eDifficulty_Easy) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, (ulTemp>0xFFFFFFFFLL)?0xFFFFFFFF:(unsigned int)ulTemp ); + XUSER_PROPERTY killsEasyProperties[LeaderboardManager::eProperty_Kills_Max]; + XUSER_PROPERTY + killsNormalProperties[LeaderboardManager::eProperty_Kills_Max]; + XUSER_PROPERTY killsHardProperties[LeaderboardManager::eProperty_Kills_Max]; + XUSER_PROPERTY miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Max]; + XUSER_PROPERTY + farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY + farmingEasyProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY + farmingNormalProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY + farmingHardProperties[LeaderboardManager::eProperty_Farming_Max]; + XUSER_PROPERTY travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY + travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY + travellingHardProperties[LeaderboardManager::eProperty_Travelling_Max]; + XUSER_PROPERTY travellingProperties[1]; // arcade leaderboard - setLeaderboardProperty( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Slime ], PROPERTY_KILLS_SLIME, getValue(Stats::killsSlime, eDifficulty_Easy) ); - setLeaderboardRating( &killsEasyProperties[LeaderboardManager::eProperty_Kills_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_KILLS_EASY) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_KILLS_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Kills_Max; + views[viewCount].pProperties = killsEasyProperties; - viewCount++; - } + rating = getValue(Stats::killsZombie, eDifficulty_Easy) + + getValue(Stats::killsSkeleton, eDifficulty_Easy) + + getValue(Stats::killsCreeper, eDifficulty_Easy) + + getValue(Stats::killsSpider, eDifficulty_Easy) + + getValue(Stats::killsSpiderJockey, eDifficulty_Easy) + + getValue(Stats::killsZombiePigman, eDifficulty_Easy) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) + + getValue(Stats::killsSlime, eDifficulty_Easy); - if( modifiedBoards & LEADERBOARD_KILLS_NORMAL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_KILLS_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Kills_Max; - views[viewCount].pProperties = killsNormalProperties; - - rating = - getValue(Stats::killsZombie, eDifficulty_Normal) + - getValue(Stats::killsSkeleton, eDifficulty_Normal) + - getValue(Stats::killsCreeper, eDifficulty_Normal) + - getValue(Stats::killsSpider, eDifficulty_Normal) + - getValue(Stats::killsSpiderJockey, eDifficulty_Normal) + - getValue(Stats::killsZombiePigman, eDifficulty_Normal) + - getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) + - getValue(Stats::killsSlime, eDifficulty_Normal); - - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Zombie ], PROPERTY_KILLS_ZOMBIE, getValue(Stats::killsZombie, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Skeleton ], PROPERTY_KILLS_SKELETON, getValue(Stats::killsSkeleton, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Creeper ], PROPERTY_KILLS_CREEPER, getValue(Stats::killsCreeper, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Spider ], PROPERTY_KILLS_SPIDER, getValue(Stats::killsSpider, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_SpiderJockey ], PROPERTY_KILLS_SPIDERJOCKEY, getValue(Stats::killsSpiderJockey, eDifficulty_Normal) ); - // 4J-PB - this could overflow - ULONGLONG ulTemp=getValue(Stats::killsZombiePigman, eDifficulty_Normal) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); - //setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, getValue(Stats::killsZombiePigman, eDifficulty_Normal) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) ); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, (ulTemp>0xFFFFFFFFLL)?0xFFFFFFFF:(unsigned int)ulTemp ); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Zombie], + PROPERTY_KILLS_ZOMBIE, + getValue(Stats::killsZombie, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Skeleton], + PROPERTY_KILLS_SKELETON, + getValue(Stats::killsSkeleton, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Creeper], + PROPERTY_KILLS_CREEPER, + getValue(Stats::killsCreeper, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Spider], + PROPERTY_KILLS_SPIDER, + getValue(Stats::killsSpider, eDifficulty_Easy)); + setLeaderboardProperty( + &killsEasyProperties + [LeaderboardManager::eProperty_Kills_SpiderJockey], + PROPERTY_KILLS_SPIDERJOCKEY, + getValue(Stats::killsSpiderJockey, eDifficulty_Easy)); + // 4J-PB - this could overflow + // setLeaderboardProperty( + // &killsEasyProperties[LeaderboardManager::eProperty_Kills_ZombiePigman + // ], PROPERTY_KILLS_ZOMBIEPIGMAN, + // getValue(Stats::killsZombiePigman, eDifficulty_Easy) + + // getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy) ); + ULONGLONG ulTemp = + getValue(Stats::killsZombiePigman, eDifficulty_Easy) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Easy); + setLeaderboardProperty( + &killsEasyProperties + [LeaderboardManager::eProperty_Kills_ZombiePigman], + PROPERTY_KILLS_ZOMBIEPIGMAN, + (ulTemp > 0xFFFFFFFFLL) ? 0xFFFFFFFF : (unsigned int)ulTemp); - setLeaderboardProperty( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Slime ], PROPERTY_KILLS_SLIME, getValue(Stats::killsSlime, eDifficulty_Normal) ); - setLeaderboardRating( &killsNormalProperties[LeaderboardManager::eProperty_Kills_Rating ], rating ); + setLeaderboardProperty( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Slime], + PROPERTY_KILLS_SLIME, + getValue(Stats::killsSlime, eDifficulty_Easy)); + setLeaderboardRating( + &killsEasyProperties[LeaderboardManager::eProperty_Kills_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & LEADERBOARD_KILLS_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_KILLS_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Kills_Max; - views[viewCount].pProperties = killsHardProperties; - - rating = - getValue(Stats::killsZombie, eDifficulty_Hard) + - getValue(Stats::killsSkeleton, eDifficulty_Hard) + - getValue(Stats::killsCreeper, eDifficulty_Hard) + - getValue(Stats::killsSpider, eDifficulty_Hard) + - getValue(Stats::killsSpiderJockey, eDifficulty_Hard) + - getValue(Stats::killsZombiePigman, eDifficulty_Hard) + - getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) + - getValue(Stats::killsSlime, eDifficulty_Hard); - - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Zombie ], PROPERTY_KILLS_ZOMBIE, getValue(Stats::killsZombie, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Skeleton ], PROPERTY_KILLS_SKELETON, getValue(Stats::killsSkeleton, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Creeper ], PROPERTY_KILLS_CREEPER, getValue(Stats::killsCreeper, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Spider ], PROPERTY_KILLS_SPIDER, getValue(Stats::killsSpider, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_SpiderJockey ], PROPERTY_KILLS_SPIDERJOCKEY, getValue(Stats::killsSpiderJockey, eDifficulty_Hard) ); - // 4J-PB - this could overflow - ULONGLONG ulTemp=getValue(Stats::killsZombiePigman, eDifficulty_Hard) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); - //setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, getValue(Stats::killsZombiePigman, eDifficulty_Hard) + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) ); - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_ZombiePigman ], PROPERTY_KILLS_ZOMBIEPIGMAN, (ulTemp>0xFFFFFFFFLL)?0xFFFFFFFF:(unsigned int)ulTemp ); + if (modifiedBoards & LEADERBOARD_KILLS_NORMAL) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_KILLS_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Kills_Max; + views[viewCount].pProperties = killsNormalProperties; - setLeaderboardProperty( &killsHardProperties[LeaderboardManager::eProperty_Kills_Slime ], PROPERTY_KILLS_SLIME, getValue(Stats::killsSlime, eDifficulty_Hard) ); - setLeaderboardRating( &killsHardProperties[LeaderboardManager::eProperty_Kills_Rating ], rating ); + rating = getValue(Stats::killsZombie, eDifficulty_Normal) + + getValue(Stats::killsSkeleton, eDifficulty_Normal) + + getValue(Stats::killsCreeper, eDifficulty_Normal) + + getValue(Stats::killsSpider, eDifficulty_Normal) + + getValue(Stats::killsSpiderJockey, eDifficulty_Normal) + + getValue(Stats::killsZombiePigman, eDifficulty_Normal) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) + + getValue(Stats::killsSlime, eDifficulty_Normal); - viewCount++; - } + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Zombie], + PROPERTY_KILLS_ZOMBIE, + getValue(Stats::killsZombie, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties + [LeaderboardManager::eProperty_Kills_Skeleton], + PROPERTY_KILLS_SKELETON, + getValue(Stats::killsSkeleton, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Creeper], + PROPERTY_KILLS_CREEPER, + getValue(Stats::killsCreeper, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Spider], + PROPERTY_KILLS_SPIDER, + getValue(Stats::killsSpider, eDifficulty_Normal)); + setLeaderboardProperty( + &killsNormalProperties + [LeaderboardManager::eProperty_Kills_SpiderJockey], + PROPERTY_KILLS_SPIDERJOCKEY, + getValue(Stats::killsSpiderJockey, eDifficulty_Normal)); + // 4J-PB - this could overflow + ULONGLONG ulTemp = + getValue(Stats::killsZombiePigman, eDifficulty_Normal) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal); + // setLeaderboardProperty( + // &killsNormalProperties[LeaderboardManager::eProperty_Kills_ZombiePigman + // ], PROPERTY_KILLS_ZOMBIEPIGMAN, + // getValue(Stats::killsZombiePigman, eDifficulty_Normal) + + // getValue(Stats::killsNetherZombiePigman, eDifficulty_Normal) ); + setLeaderboardProperty( + &killsNormalProperties + [LeaderboardManager::eProperty_Kills_ZombiePigman], + PROPERTY_KILLS_ZOMBIEPIGMAN, + (ulTemp > 0xFFFFFFFFLL) ? 0xFFFFFFFF : (unsigned int)ulTemp); - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_PEACEFUL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksPeacefulProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful); - - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Cobblestone], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Peaceful) ); - setLeaderboardRating( &miningBlocksPeacefulProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + setLeaderboardProperty( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Slime], + PROPERTY_KILLS_SLIME, + getValue(Stats::killsSlime, eDifficulty_Normal)); + setLeaderboardRating( + &killsNormalProperties[LeaderboardManager::eProperty_Kills_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksEasyProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); - - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Cobblestone], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy) ); - setLeaderboardProperty( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy) ); - setLeaderboardRating( &miningBlocksEasyProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_KILLS_HARD) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_KILLS_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_KILLS_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Kills_Max; + views[viewCount].pProperties = killsHardProperties; - viewCount++; - } + rating = getValue(Stats::killsZombie, eDifficulty_Hard) + + getValue(Stats::killsSkeleton, eDifficulty_Hard) + + getValue(Stats::killsCreeper, eDifficulty_Hard) + + getValue(Stats::killsSpider, eDifficulty_Hard) + + getValue(Stats::killsSpiderJockey, eDifficulty_Hard) + + getValue(Stats::killsZombiePigman, eDifficulty_Hard) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) + + getValue(Stats::killsSlime, eDifficulty_Hard); - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksNormalProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal); - - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Cobblestone ], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal) ); - setLeaderboardProperty( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Normal) ); - setLeaderboardRating( &miningBlocksNormalProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Zombie], + PROPERTY_KILLS_ZOMBIE, + getValue(Stats::killsZombie, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Skeleton], + PROPERTY_KILLS_SKELETON, + getValue(Stats::killsSkeleton, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Creeper], + PROPERTY_KILLS_CREEPER, + getValue(Stats::killsCreeper, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Spider], + PROPERTY_KILLS_SPIDER, + getValue(Stats::killsSpider, eDifficulty_Hard)); + setLeaderboardProperty( + &killsHardProperties + [LeaderboardManager::eProperty_Kills_SpiderJockey], + PROPERTY_KILLS_SPIDERJOCKEY, + getValue(Stats::killsSpiderJockey, eDifficulty_Hard)); + // 4J-PB - this could overflow + ULONGLONG ulTemp = + getValue(Stats::killsZombiePigman, eDifficulty_Hard) + + getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard); + // setLeaderboardProperty( + // &killsHardProperties[LeaderboardManager::eProperty_Kills_ZombiePigman + // ], PROPERTY_KILLS_ZOMBIEPIGMAN, + // getValue(Stats::killsZombiePigman, eDifficulty_Hard) + + // getValue(Stats::killsNetherZombiePigman, eDifficulty_Hard) ); + setLeaderboardProperty( + &killsHardProperties + [LeaderboardManager::eProperty_Kills_ZombiePigman], + PROPERTY_KILLS_ZOMBIEPIGMAN, + (ulTemp > 0xFFFFFFFFLL) ? 0xFFFFFFFF : (unsigned int)ulTemp); - viewCount++; - } + setLeaderboardProperty( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Slime], + PROPERTY_KILLS_SLIME, + getValue(Stats::killsSlime, eDifficulty_Hard)); + setLeaderboardRating( + &killsHardProperties[LeaderboardManager::eProperty_Kills_Rating], + rating); - if( modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Mining_Max; - views[viewCount].pProperties = miningBlocksHardProperties; - - rating = - getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); - - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Dirt ], PROPERTY_MINED_DIRT, getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Stone ], PROPERTY_MINED_STONE, getValue(Stats::blocksMined[Tile::stoneBrick->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Sand ], PROPERTY_MINED_SAND, getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Cobblestone], PROPERTY_MINED_COBBLESTONE, getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Gravel ], PROPERTY_MINED_GRAVEL, getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Clay ], PROPERTY_MINED_CLAY, getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard) ); - setLeaderboardProperty( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Obsidian ], PROPERTY_MINED_OBSIDIAN, getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard) ); - setLeaderboardRating( &miningBlocksHardProperties[LeaderboardManager::eProperty_Mining_Rating ], rating ); + viewCount++; + } - viewCount++; - } + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_PEACEFUL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_PEACEFUL\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_PEACEFUL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksPeacefulProperties; - if( modifiedBoards & LEADERBOARD_FARMING_PEACEFUL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_PEACEFUL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingPeacefulProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful) + - getValue(Stats::cowsMilked, eDifficulty_Peaceful) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful); - - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Sugarcane ], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Peaceful) ); - setLeaderboardProperty( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Peaceful) ); - setLeaderboardRating( &farmingPeacefulProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::gravel->id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Peaceful); - viewCount++; - } + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Peaceful)); + setLeaderboardRating(&miningBlocksPeacefulProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - if( modifiedBoards & LEADERBOARD_FARMING_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingEasyProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy) + - getValue(Stats::cowsMilked, eDifficulty_Easy) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy); + viewCount++; + } - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Sugarcane ], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Easy) ); - setLeaderboardProperty( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Easy) ); - setLeaderboardRating( &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_EASY) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksEasyProperties; - viewCount++; - } + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy); - if( modifiedBoards & LEADERBOARD_FARMING_NORMAL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingNormalProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal) + - getValue(Stats::cowsMilked, eDifficulty_Normal) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Easy)); + setLeaderboardProperty( + &miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Easy)); + setLeaderboardRating(&miningBlocksEasyProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Sugarcane], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Normal) ); - setLeaderboardProperty( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Normal) ); - setLeaderboardRating( &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + viewCount++; + } - viewCount++; - } + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_NORMAL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksNormalProperties; - if( modifiedBoards & LEADERBOARD_FARMING_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_FARMING_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Farming_Max; - views[viewCount].pProperties = farmingHardProperties; - - rating = - getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard) + - getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard) + - getValue(Stats::cowsMilked, eDifficulty_Hard) + - getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard); + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Normal); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Egg ], PROPERTY_COLLECTED_EGG, getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Wheat ], PROPERTY_COLLECTED_WHEAT, getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Mushroom ], PROPERTY_COLLECTED_MUSHROOM, getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Sugarcane ], PROPERTY_COLLECTED_SUGARCANE, getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Milk ], PROPERTY_COLLECTED_MILK, getValue(Stats::cowsMilked, eDifficulty_Hard) ); - setLeaderboardProperty( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Pumpkin ], PROPERTY_COLLECTED_PUMPKIN, getValue(Stats::itemsCollected[Tile::pumpkin->id], eDifficulty_Hard) ); - setLeaderboardRating( &farmingHardProperties[LeaderboardManager::eProperty_Farming_Rating ], rating ); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Normal)); + setLeaderboardProperty( + &miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], + eDifficulty_Normal)); + setLeaderboardRating(&miningBlocksNormalProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_PEACEFUL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingPeacefulProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Peaceful) + - getValue(Stats::fallOneM, eDifficulty_Peaceful) + - getValue(Stats::minecartOneM, eDifficulty_Peaceful) + - getValue(Stats::boatOneM, eDifficulty_Peaceful); + if (modifiedBoards & LEADERBOARD_MININGBLOCKS_HARD) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_MININGBLOCKS_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_MINING_BLOCKS_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Mining_Max; + views[viewCount].pProperties = miningBlocksHardProperties; - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Peaceful) ); - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Peaceful) ); - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Peaceful) ); - setLeaderboardProperty( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Peaceful) ); - setLeaderboardRating( &travellingPeacefulProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + rating = + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard); - viewCount++; - } + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Dirt], + PROPERTY_MINED_DIRT, + getValue(Stats::blocksMined[Tile::dirt->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Stone], + PROPERTY_MINED_STONE, + getValue(Stats::blocksMined[Tile::stoneBrick->id], + eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Sand], + PROPERTY_MINED_SAND, + getValue(Stats::blocksMined[Tile::sand->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Cobblestone], + PROPERTY_MINED_COBBLESTONE, + getValue(Stats::blocksMined[Tile::rock->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Gravel], + PROPERTY_MINED_GRAVEL, + getValue(Stats::blocksMined[Tile::gravel->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Clay], + PROPERTY_MINED_CLAY, + getValue(Stats::blocksMined[Tile::clay->id], eDifficulty_Hard)); + setLeaderboardProperty( + &miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Obsidian], + PROPERTY_MINED_OBSIDIAN, + getValue(Stats::blocksMined[Tile::obsidian->id], eDifficulty_Hard)); + setLeaderboardRating(&miningBlocksHardProperties + [LeaderboardManager::eProperty_Mining_Rating], + rating); - if( modifiedBoards & LEADERBOARD_TRAVELLING_EASY ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_EASY; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingEasyProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Easy) + - getValue(Stats::fallOneM, eDifficulty_Easy) + - getValue(Stats::minecartOneM, eDifficulty_Easy) + - getValue(Stats::boatOneM, eDifficulty_Easy); + viewCount++; + } - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Easy) ); - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Easy) ); - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Easy) ); - setLeaderboardProperty( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Easy) ); - setLeaderboardRating( &travellingEasyProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + if (modifiedBoards & LEADERBOARD_FARMING_PEACEFUL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_PEACEFUL\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_PEACEFUL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingPeacefulProperties; - viewCount++; - } + rating = + getValue(Stats::itemsCollected[Item::egg->id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Peaceful) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful) + + getValue(Stats::cowsMilked, eDifficulty_Peaceful) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Peaceful); - if( modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_NORMAL; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingNormalProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Normal) + - getValue(Stats::fallOneM, eDifficulty_Normal) + - getValue(Stats::minecartOneM, eDifficulty_Normal) + - getValue(Stats::boatOneM, eDifficulty_Normal); + setLeaderboardProperty(&farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Peaceful)); + setLeaderboardProperty( + &farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Peaceful)); + setLeaderboardRating(&farmingPeacefulProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Normal) ); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Normal) ); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Normal) ); - setLeaderboardProperty( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Normal) ); - setLeaderboardRating( &travellingNormalProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + viewCount++; + } - viewCount++; - } + if (modifiedBoards & LEADERBOARD_FARMING_EASY) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingEasyProperties; - if( modifiedBoards & LEADERBOARD_TRAVELLING_HARD ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_HARD; - views[viewCount].dwNumProperties = LeaderboardManager::eProperty_Travelling_Max; - views[viewCount].pProperties = travellingHardProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Hard) + - getValue(Stats::fallOneM, eDifficulty_Hard) + - getValue(Stats::minecartOneM, eDifficulty_Hard) + - getValue(Stats::boatOneM, eDifficulty_Hard); + rating = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy) + + getValue(Stats::cowsMilked, eDifficulty_Easy) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Easy); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Walked ], PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Hard) ); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Fallen ], PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Hard) ); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Minecart ], PROPERTY_TRAVEL_MINECART, getValue(Stats::minecartOneM, eDifficulty_Hard) ); - setLeaderboardProperty( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Boat ], PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Hard) ); - setLeaderboardRating( &travellingHardProperties[LeaderboardManager::eProperty_Travelling_Rating ], rating ); + setLeaderboardProperty( + &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties[LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Easy)); + setLeaderboardProperty( + &farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Easy)); + setLeaderboardRating(&farmingEasyProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); - viewCount++; - } + viewCount++; + } - if( modifiedBoards & (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD) ) - { - app.DebugPrintf("Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD\n"); - views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_TOTAL; - views[viewCount].dwNumProperties = 1; - views[viewCount].pProperties = travellingProperties; - - rating = - getValue(Stats::walkOneM, eDifficulty_Peaceful) + getValue(Stats::fallOneM, eDifficulty_Peaceful) + getValue(Stats::boatOneM, eDifficulty_Peaceful) + getValue(Stats::minecartOneM, eDifficulty_Peaceful) + - getValue(Stats::walkOneM, eDifficulty_Easy) + getValue(Stats::fallOneM, eDifficulty_Easy) + getValue(Stats::boatOneM, eDifficulty_Easy) + getValue(Stats::minecartOneM, eDifficulty_Easy) + - getValue(Stats::walkOneM, eDifficulty_Normal) + getValue(Stats::fallOneM, eDifficulty_Normal) + getValue(Stats::boatOneM, eDifficulty_Normal) + getValue(Stats::minecartOneM, eDifficulty_Normal) + - getValue(Stats::walkOneM, eDifficulty_Hard) + getValue(Stats::fallOneM, eDifficulty_Hard) + getValue(Stats::boatOneM, eDifficulty_Hard) + getValue(Stats::minecartOneM, eDifficulty_Hard); + if (modifiedBoards & LEADERBOARD_FARMING_NORMAL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_FARMING_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingNormalProperties; - setLeaderboardRating( &travellingProperties[0], rating ); + rating = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Normal) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal) + + getValue(Stats::cowsMilked, eDifficulty_Normal) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Normal); - viewCount++; - } + setLeaderboardProperty( + &farmingNormalProperties[LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], + eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Normal)); + setLeaderboardProperty(&farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Normal)); + setLeaderboardProperty( + &farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Normal)); + setLeaderboardRating(&farmingNormalProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); - if( viewCount > 0 ) - { - if( !LeaderboardManager::Instance()->WriteStats(viewCount, views) ) - { - assert(false && "Failed to write to leaderboard"); - //printf("Failed to write to leaderboard"); - } - else - { - app.DebugPrintf("Successfully wrote %d leadeboard views\n", viewCount); - } - } -#endif // Xbox -#endif // ndef _DURANGO + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_FARMING_HARD) { + app.DebugPrintf("Updating leaderboard view LEADERBOARD_FARMING_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_FARMING_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Farming_Max; + views[viewCount].pProperties = farmingHardProperties; + + rating = + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard) + + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard) + + getValue(Stats::cowsMilked, eDifficulty_Hard) + + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Hard); + + setLeaderboardProperty( + &farmingHardProperties[LeaderboardManager::eProperty_Farming_Egg], + PROPERTY_COLLECTED_EGG, + getValue(Stats::itemsCollected[Item::egg->id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties[LeaderboardManager::eProperty_Farming_Wheat], + PROPERTY_COLLECTED_WHEAT, + getValue(Stats::blocksMined[Tile::crops_Id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties + [LeaderboardManager::eProperty_Farming_Mushroom], + PROPERTY_COLLECTED_MUSHROOM, + getValue(Stats::blocksMined[Tile::mushroom1_Id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties + [LeaderboardManager::eProperty_Farming_Sugarcane], + PROPERTY_COLLECTED_SUGARCANE, + getValue(Stats::blocksMined[Tile::reeds_Id], eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties[LeaderboardManager::eProperty_Farming_Milk], + PROPERTY_COLLECTED_MILK, + getValue(Stats::cowsMilked, eDifficulty_Hard)); + setLeaderboardProperty( + &farmingHardProperties + [LeaderboardManager::eProperty_Farming_Pumpkin], + PROPERTY_COLLECTED_PUMPKIN, + getValue(Stats::itemsCollected[Tile::pumpkin->id], + eDifficulty_Hard)); + setLeaderboardRating(&farmingHardProperties + [LeaderboardManager::eProperty_Farming_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_PEACEFUL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_PEACEFUL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingPeacefulProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Peaceful) + + getValue(Stats::fallOneM, eDifficulty_Peaceful) + + getValue(Stats::minecartOneM, eDifficulty_Peaceful) + + getValue(Stats::boatOneM, eDifficulty_Peaceful); + + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, + getValue(Stats::walkOneM, eDifficulty_Peaceful)); + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, + getValue(Stats::fallOneM, eDifficulty_Peaceful)); + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Peaceful)); + setLeaderboardProperty( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, + getValue(Stats::boatOneM, eDifficulty_Peaceful)); + setLeaderboardRating( + &travellingPeacefulProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_EASY) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_EASY\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_EASY; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingEasyProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Easy) + + getValue(Stats::fallOneM, eDifficulty_Easy) + + getValue(Stats::minecartOneM, eDifficulty_Easy) + + getValue(Stats::boatOneM, eDifficulty_Easy); + + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Easy)); + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Easy)); + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Easy)); + setLeaderboardProperty( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Easy)); + setLeaderboardRating( + &travellingEasyProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_NORMAL) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_NORMAL\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_NORMAL; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingNormalProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Normal) + + getValue(Stats::fallOneM, eDifficulty_Normal) + + getValue(Stats::minecartOneM, eDifficulty_Normal) + + getValue(Stats::boatOneM, eDifficulty_Normal); + + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, + getValue(Stats::walkOneM, eDifficulty_Normal)); + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, + getValue(Stats::fallOneM, eDifficulty_Normal)); + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Normal)); + setLeaderboardProperty( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, + getValue(Stats::boatOneM, eDifficulty_Normal)); + setLeaderboardRating( + &travellingNormalProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & LEADERBOARD_TRAVELLING_HARD) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_HARD; + views[viewCount].dwNumProperties = + LeaderboardManager::eProperty_Travelling_Max; + views[viewCount].pProperties = travellingHardProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Hard) + + getValue(Stats::fallOneM, eDifficulty_Hard) + + getValue(Stats::minecartOneM, eDifficulty_Hard) + + getValue(Stats::boatOneM, eDifficulty_Hard); + + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Walked], + PROPERTY_TRAVEL_WALK, getValue(Stats::walkOneM, eDifficulty_Hard)); + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Fallen], + PROPERTY_TRAVEL_FALL, getValue(Stats::fallOneM, eDifficulty_Hard)); + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Minecart], + PROPERTY_TRAVEL_MINECART, + getValue(Stats::minecartOneM, eDifficulty_Hard)); + setLeaderboardProperty( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Boat], + PROPERTY_TRAVEL_BOAT, getValue(Stats::boatOneM, eDifficulty_Hard)); + setLeaderboardRating( + &travellingHardProperties + [LeaderboardManager::eProperty_Travelling_Rating], + rating); + + viewCount++; + } + + if (modifiedBoards & + (LEADERBOARD_TRAVELLING_PEACEFUL | LEADERBOARD_TRAVELLING_EASY | + LEADERBOARD_TRAVELLING_NORMAL | LEADERBOARD_TRAVELLING_HARD)) { + app.DebugPrintf( + "Updating leaderboard view LEADERBOARD_TRAVELLING_PEACEFUL | " + "LEADERBOARD_TRAVELLING_EASY | LEADERBOARD_TRAVELLING_NORMAL | " + "LEADERBOARD_TRAVELLING_HARD\n"); + views[viewCount].dwViewId = STATS_VIEW_TRAVELLING_TOTAL; + views[viewCount].dwNumProperties = 1; + views[viewCount].pProperties = travellingProperties; + + rating = getValue(Stats::walkOneM, eDifficulty_Peaceful) + + getValue(Stats::fallOneM, eDifficulty_Peaceful) + + getValue(Stats::boatOneM, eDifficulty_Peaceful) + + getValue(Stats::minecartOneM, eDifficulty_Peaceful) + + getValue(Stats::walkOneM, eDifficulty_Easy) + + getValue(Stats::fallOneM, eDifficulty_Easy) + + getValue(Stats::boatOneM, eDifficulty_Easy) + + getValue(Stats::minecartOneM, eDifficulty_Easy) + + getValue(Stats::walkOneM, eDifficulty_Normal) + + getValue(Stats::fallOneM, eDifficulty_Normal) + + getValue(Stats::boatOneM, eDifficulty_Normal) + + getValue(Stats::minecartOneM, eDifficulty_Normal) + + getValue(Stats::walkOneM, eDifficulty_Hard) + + getValue(Stats::fallOneM, eDifficulty_Hard) + + getValue(Stats::boatOneM, eDifficulty_Hard) + + getValue(Stats::minecartOneM, eDifficulty_Hard); + + setLeaderboardRating(&travellingProperties[0], rating); + + viewCount++; + } + + if (viewCount > 0) { + if (!LeaderboardManager::Instance()->WriteStats(viewCount, views)) { + assert(false && "Failed to write to leaderboard"); + // printf("Failed to write to leaderboard"); + } else { + app.DebugPrintf("Successfully wrote %d leadeboard views\n", + viewCount); + } + } +#endif // Xbox +#endif // ndef _DURANGO } -void StatsCounter::setupStatBoards() -{ +void StatsCounter::setupStatBoards() { #ifndef _DURANGO - statBoards.insert( std::make_pair(Stats::killsZombie, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSkeleton, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsCreeper, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSpider, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSpiderJockey, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsZombiePigman, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsNetherZombiePigman, LEADERBOARD_KILLS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::killsSlime, LEADERBOARD_KILLS_PEACEFUL) ); + statBoards.insert( + std::make_pair(Stats::killsZombie, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSkeleton, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsCreeper, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSpider, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSpiderJockey, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsZombiePigman, LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::killsNetherZombiePigman, + LEADERBOARD_KILLS_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::killsSlime, LEADERBOARD_KILLS_PEACEFUL)); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::dirt->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::stoneBrick->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::sand->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::rock->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::gravel->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::clay->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::obsidian->id], LEADERBOARD_MININGBLOCKS_PEACEFUL) ); - - statBoards.insert( std::make_pair(Stats::itemsCollected[Item::egg->id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::crops_Id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::mushroom1_Id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::blocksMined[Tile::reeds_Id], LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::cowsMilked, LEADERBOARD_FARMING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::itemsCollected[Tile::pumpkin->id], LEADERBOARD_FARMING_PEACEFUL) ); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::dirt->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::stoneBrick->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::sand->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::rock->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::gravel->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::clay->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::obsidian->id], + LEADERBOARD_MININGBLOCKS_PEACEFUL)); - statBoards.insert( std::make_pair(Stats::walkOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::fallOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::minecartOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); - statBoards.insert( std::make_pair(Stats::boatOneM, LEADERBOARD_TRAVELLING_PEACEFUL) ); + statBoards.insert(std::make_pair(Stats::itemsCollected[Item::egg->id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::crops_Id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::mushroom1_Id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::blocksMined[Tile::reeds_Id], + LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::cowsMilked, LEADERBOARD_FARMING_PEACEFUL)); + statBoards.insert(std::make_pair(Stats::itemsCollected[Tile::pumpkin->id], + LEADERBOARD_FARMING_PEACEFUL)); + + statBoards.insert( + std::make_pair(Stats::walkOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::fallOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::minecartOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); + statBoards.insert( + std::make_pair(Stats::boatOneM, LEADERBOARD_TRAVELLING_PEACEFUL)); #endif } -bool StatsCounter::isLargeStat(Stat* stat) -{ +bool StatsCounter::isLargeStat(Stat* stat) { #ifndef _DURANGO - Stat*** end = &LARGE_STATS[LARGE_STATS_COUNT]; - for( Stat*** iter = LARGE_STATS ; iter != end ; ++iter ) - if( (*(*iter))->id == stat->id ) - return true; + Stat*** end = &LARGE_STATS[LARGE_STATS_COUNT]; + for (Stat*** iter = LARGE_STATS; iter != end; ++iter) + if ((*(*iter))->id == stat->id) return true; #endif - return false; + return false; } -void StatsCounter::dumpStatsToTTY() -{ - std::vector::iterator statsEnd = Stats::all->end(); - for( std::vector::iterator statsIter = Stats::all->begin() ; statsIter!=statsEnd ; ++statsIter ) - { - app.DebugPrintf("%ls\t\t%u\t%u\t%u\t%u\n", - (*statsIter)->name.c_str(), - getValue(*statsIter, 0), - getValue(*statsIter, 1), - getValue(*statsIter, 2), - getValue(*statsIter, 3) - ); - } +void StatsCounter::dumpStatsToTTY() { + std::vector::iterator statsEnd = Stats::all->end(); + for (std::vector::iterator statsIter = Stats::all->begin(); + statsIter != statsEnd; ++statsIter) { + app.DebugPrintf("%ls\t\t%u\t%u\t%u\t%u\n", (*statsIter)->name.c_str(), + getValue(*statsIter, 0), getValue(*statsIter, 1), + getValue(*statsIter, 2), getValue(*statsIter, 3)); + } } #ifdef _DEBUG -//To clear leaderboards set DEBUG_ENABLE_CLEAR_LEADERBOARDS to 1 and set DEBUG_CLEAR_LEADERBOARDS to be the bitmask of what you want to clear -//Leaderboards are updated on game exit so enter and exit a level to trigger the clear +// To clear leaderboards set DEBUG_ENABLE_CLEAR_LEADERBOARDS to 1 and set +// DEBUG_CLEAR_LEADERBOARDS to be the bitmask of what you want to clear +// Leaderboards are updated on game exit so enter and exit a level to trigger +// the clear -//#define DEBUG_CLEAR_LEADERBOARDS (LEADERBOARD_KILLS_EASY | LEADERBOARD_KILLS_NORMAL | LEADERBOARD_KILLS_HARD) -#define DEBUG_CLEAR_LEADERBOARDS (0xFFFFFFFF) +// #define DEBUG_CLEAR_LEADERBOARDS (LEADERBOARD_KILLS_EASY +// | LEADERBOARD_KILLS_NORMAL | LEADERBOARD_KILLS_HARD) +#define DEBUG_CLEAR_LEADERBOARDS (0xFFFFFFFF) #define DEBUG_ENABLE_CLEAR_LEADERBOARDS -void StatsCounter::WipeLeaderboards() -{ - +void StatsCounter::WipeLeaderboards() { #if defined DEBUG_ENABLE_CLEAR_LEADERBOARDS && defined _XBOX - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_HARD, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_PEACEFUL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_EASY, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_NORMAL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_PEACEFUL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_EASY, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_NORMAL, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_HARD, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_PEACEFUL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_PEACEFUL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_EASY ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_EASY, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_NORMAL ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_NORMAL, NULL); -// if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_HARD ) XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_HARD, NULL); - if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_TOTAL ) XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_TOTAL, NULL); - if( LeaderboardManager::Instance()->OpenSession() ) - { - writeStats(); - LeaderboardManager::Instance()->CloseSession(); - } -#endif + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_KILLS_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_KILLS_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_PEACEFUL) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_PEACEFUL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGBLOCKS_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_MINING_BLOCKS_HARD, NULL); + // if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_PEACEFUL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_PEACEFUL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_EASY ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_EASY, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_NORMAL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_NORMAL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_MININGORE_HARD ) + // XUserResetStatsViewAllUsers(STATS_VIEW_MINING_ORE_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_PEACEFUL) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_PEACEFUL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_FARMING_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_FARMING_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_PEACEFUL) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_PEACEFUL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_EASY) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_EASY, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_NORMAL) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_NORMAL, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_HARD) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_HARD, NULL); + // if( DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_PEACEFUL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_PEACEFUL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_EASY ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_EASY, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_NORMAL ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_NORMAL, NULL); if( + // DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_NETHER_HARD ) + // XUserResetStatsViewAllUsers(STATS_VIEW_NETHER_HARD, NULL); + if (DEBUG_CLEAR_LEADERBOARDS & LEADERBOARD_TRAVELLING_TOTAL) + XUserResetStatsViewAllUsers(STATS_VIEW_TRAVELLING_TOTAL, NULL); + if (LeaderboardManager::Instance()->OpenSession()) { + writeStats(); + LeaderboardManager::Instance()->CloseSession(); + } +#endif } #endif diff --git a/Minecraft.Client/GameState/StatsCounter.h b/Minecraft.Client/GameState/StatsCounter.h index 55298ae01..b02a09ad2 100644 --- a/Minecraft.Client/GameState/StatsCounter.h +++ b/Minecraft.Client/GameState/StatsCounter.h @@ -5,100 +5,96 @@ class Achievement; class StatsSyncher; class User; - -class StatsCounter -{ +class StatsCounter { private: + enum eDifficulty { + eDifficulty_Peaceful = 0, + eDifficulty_Easy, + eDifficulty_Normal, + eDifficulty_Hard, + eDifficulty_Max + }; - enum eDifficulty - { - eDifficulty_Peaceful=0, - eDifficulty_Easy, - eDifficulty_Normal, - eDifficulty_Hard, - eDifficulty_Max - }; + struct StatContainer { + unsigned int stats[eDifficulty_Max]; - struct StatContainer - { - unsigned int stats[eDifficulty_Max]; + StatContainer() { + stats[eDifficulty_Peaceful] = stats[eDifficulty_Easy] = + stats[eDifficulty_Normal] = stats[eDifficulty_Hard] = 0; + } + }; - StatContainer() - { - stats[eDifficulty_Peaceful] = stats[eDifficulty_Easy] = stats[eDifficulty_Normal] = stats[eDifficulty_Hard] = 0; - } - }; - - typedef std::unordered_map StatsMap; + typedef std::unordered_map StatsMap; - //static const int STAT_DATA_OFFSET = 32; - static const int LARGE_STATS_COUNT = 8; - static Stat** LARGE_STATS[LARGE_STATS_COUNT]; - static const int SAVE_DELAY = 30*60; - static const int FLUSH_DELAY = 30*60*5; + // static const int STAT_DATA_OFFSET = 32; + static const int LARGE_STATS_COUNT = 8; + static Stat** LARGE_STATS[LARGE_STATS_COUNT]; + static const int SAVE_DELAY = 30 * 60; + static const int FLUSH_DELAY = 30 * 60 * 5; - typedef enum { - LEADERBOARD_KILLS_PEACEFUL = 0x00000001, - LEADERBOARD_KILLS_EASY = 0x00000002, - LEADERBOARD_KILLS_NORMAL = 0x00000004, - LEADERBOARD_KILLS_HARD = 0x00000008, - LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010, - LEADERBOARD_MININGBLOCKS_EASY = 0x00000020, - LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040, - LEADERBOARD_MININGBLOCKS_HARD = 0x00000080, - LEADERBOARD_MININGORE_PEACEFUL = 0x00000100, - LEADERBOARD_MININGORE_EASY = 0x00000200, - LEADERBOARD_MININGORE_NORMAL = 0x00000400, - LEADERBOARD_MININGORE_HARD = 0x00000800, - LEADERBOARD_FARMING_PEACEFUL = 0x00001000, - LEADERBOARD_FARMING_EASY = 0x00002000, - LEADERBOARD_FARMING_NORMAL = 0x00004000, - LEADERBOARD_FARMING_HARD = 0x00008000, - LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000, - LEADERBOARD_TRAVELLING_EASY = 0x00020000, - LEADERBOARD_TRAVELLING_NORMAL = 0x00040000, - LEADERBOARD_TRAVELLING_HARD = 0x00080000, - LEADERBOARD_NETHER_PEACEFUL = 0x00100000, - LEADERBOARD_NETHER_EASY = 0x00200000, - LEADERBOARD_NETHER_NORMAL = 0x00400000, - LEADERBOARD_NETHER_HARD = 0x00800000, - LEADERBOARD_TRAVELLING_TOTAL = 0x01000000 - } LEADERBOARD_FLAG; + typedef enum { + LEADERBOARD_KILLS_PEACEFUL = 0x00000001, + LEADERBOARD_KILLS_EASY = 0x00000002, + LEADERBOARD_KILLS_NORMAL = 0x00000004, + LEADERBOARD_KILLS_HARD = 0x00000008, + LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010, + LEADERBOARD_MININGBLOCKS_EASY = 0x00000020, + LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040, + LEADERBOARD_MININGBLOCKS_HARD = 0x00000080, + LEADERBOARD_MININGORE_PEACEFUL = 0x00000100, + LEADERBOARD_MININGORE_EASY = 0x00000200, + LEADERBOARD_MININGORE_NORMAL = 0x00000400, + LEADERBOARD_MININGORE_HARD = 0x00000800, + LEADERBOARD_FARMING_PEACEFUL = 0x00001000, + LEADERBOARD_FARMING_EASY = 0x00002000, + LEADERBOARD_FARMING_NORMAL = 0x00004000, + LEADERBOARD_FARMING_HARD = 0x00008000, + LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000, + LEADERBOARD_TRAVELLING_EASY = 0x00020000, + LEADERBOARD_TRAVELLING_NORMAL = 0x00040000, + LEADERBOARD_TRAVELLING_HARD = 0x00080000, + LEADERBOARD_NETHER_PEACEFUL = 0x00100000, + LEADERBOARD_NETHER_EASY = 0x00200000, + LEADERBOARD_NETHER_NORMAL = 0x00400000, + LEADERBOARD_NETHER_HARD = 0x00800000, + LEADERBOARD_TRAVELLING_TOTAL = 0x01000000 + } LEADERBOARD_FLAG; - StatsMap stats; + StatsMap stats; bool requiresSave; - int saveCounter; + int saveCounter; - int modifiedBoards; - static std::unordered_map statBoards; - int flushCounter; + int modifiedBoards; + static std::unordered_map statBoards; + int flushCounter; public: - StatsCounter(); - void award(Stat *stat, unsigned int difficulty, unsigned int count); - bool hasTaken(Achievement *ach); - bool canTake(Achievement *ach); - unsigned int getValue(Stat *stat, unsigned int difficulty); - unsigned int getTotalValue(Stat *stat); + StatsCounter(); + void award(Stat* stat, unsigned int difficulty, unsigned int count); + bool hasTaken(Achievement* ach); + bool canTake(Achievement* ach); + unsigned int getValue(Stat* stat, unsigned int difficulty); + unsigned int getTotalValue(Stat* stat); void tick(int player); - void parse(void* data); - void clear(); - void save(int player, bool force=false); - void flushLeaderboards(); - void saveLeaderboards(); - static void setupStatBoards(); + void parse(void* data); + void clear(); + void save(int player, bool force = false); + void flushLeaderboards(); + void saveLeaderboards(); + static void setupStatBoards(); #ifdef _DEBUG - void WipeLeaderboards(); + void WipeLeaderboards(); #endif private: - bool isLargeStat(Stat* stat); - void dumpStatsToTTY(); + bool isLargeStat(Stat* stat); + void dumpStatsToTTY(); #ifdef _XBOX - static void setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id, unsigned int value); - static void setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value); + static void setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id, + unsigned int value); + static void setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value); #endif - void writeStats(); + void writeStats(); }; diff --git a/Minecraft.Client/GameState/StatsSyncer.h b/Minecraft.Client/GameState/StatsSyncer.h index 0742acc3d..61d59aaf1 100644 --- a/Minecraft.Client/GameState/StatsSyncer.h +++ b/Minecraft.Client/GameState/StatsSyncer.h @@ -5,42 +5,46 @@ class User; class File; class Stat; - -class StatsSyncher -{ +class StatsSyncher { private: - static const int SAVE_INTERVAL = 20 * 5; + static const int SAVE_INTERVAL = 20 * 5; static const int SEND_INTERVAL = 20 * 60; volatile bool busy; - volatile std::unordered_map *serverStats; - volatile std::unordered_map *failedSentStats; + volatile std::unordered_map* serverStats; + volatile std::unordered_map* failedSentStats; - StatsCounter *statsCounter; + StatsCounter* statsCounter; File *unsentFile, *lastServerFile; File *unsentFileTmp, *lastServerFileTmp; File *unsentFileOld, *lastServerFileOld; - User *user; + User* user; int noSaveIn, noSendIn; public: - StatsSyncher(User *user, StatsCounter *statsCounter, File *dir); + StatsSyncher(User* user, StatsCounter* statsCounter, File* dir); + private: - void attemptRename(File *dir, const std::wstring& name, File *to); - std::unordered_map *loadStatsFromDisk(File *file, File *tmp, File *old); - std::unordered_map *loadStatsFromDisk(File *file); - void doSend(std::unordered_map *stats); - void doSave(std::unordered_map *stats, File *file, File *tmp, File *old); + void attemptRename(File* dir, const std::wstring& name, File* to); + std::unordered_map* loadStatsFromDisk(File* file, File* tmp, + File* old); + std::unordered_map* loadStatsFromDisk(File* file); + void doSend(std::unordered_map* stats); + void doSave(std::unordered_map* stats, File* file, File* tmp, + File* old); + protected: - std::unordered_map *doGetStats(); + std::unordered_map* doGetStats(); + public: - void getStatsFromServer(); - void saveUnsent(std::unordered_map *stats); - void sendUnsent(std::unordered_map *stats, std::unordered_map *fullStats); - void forceSendUnsent(std::unordered_map *stats); - void forceSaveUnsent(std::unordered_map *stats); + void getStatsFromServer(); + void saveUnsent(std::unordered_map* stats); + void sendUnsent(std::unordered_map* stats, + std::unordered_map* fullStats); + void forceSendUnsent(std::unordered_map* stats); + void forceSaveUnsent(std::unordered_map* stats); bool maySave(); bool maySend(); void tick(); diff --git a/Minecraft.Client/GameState/SurvivalMode.cpp b/Minecraft.Client/GameState/SurvivalMode.cpp index 7fdf0dd27..ddf96d737 100644 --- a/Minecraft.Client/GameState/SurvivalMode.cpp +++ b/Minecraft.Client/GameState/SurvivalMode.cpp @@ -11,10 +11,9 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../ClientConstants.h" -SurvivalMode::SurvivalMode(Minecraft *minecraft) : GameMode(minecraft) -{ - // 4J - added initialisers - xDestroyBlock = -1; +SurvivalMode::SurvivalMode(Minecraft* minecraft) : GameMode(minecraft) { + // 4J - added initialisers + xDestroyBlock = -1; yDestroyBlock = -1; zDestroyBlock = -1; destroyProgress = 0; @@ -22,122 +21,103 @@ SurvivalMode::SurvivalMode(Minecraft *minecraft) : GameMode(minecraft) destroyTicks = 0; destroyDelay = 0; - if (ClientConstants::IS_DEMO_VERSION) - { - if( dynamic_cast(this) == NULL ) - { - assert(false); -// throw new IllegalStateException("Invalid game mode"); // 4J - removed + if (ClientConstants::IS_DEMO_VERSION) { + if (dynamic_cast(this) == NULL) { + assert(false); + // throw new IllegalStateException("Invalid game mode"); + // // 4J - removed } } } -// 4J Stu - Added this ctor so we can exit the tutorial and replace it with a standard -// survival mode -SurvivalMode::SurvivalMode(SurvivalMode *copy) : GameMode( copy->minecraft ) -{ - xDestroyBlock = copy->xDestroyBlock; - yDestroyBlock = copy->yDestroyBlock; - zDestroyBlock = copy->zDestroyBlock; - destroyProgress = copy->destroyProgress; - oDestroyProgress = copy->oDestroyProgress; - destroyTicks = copy->destroyTicks; +// 4J Stu - Added this ctor so we can exit the tutorial and replace it with a +// standard survival mode +SurvivalMode::SurvivalMode(SurvivalMode* copy) : GameMode(copy->minecraft) { + xDestroyBlock = copy->xDestroyBlock; + yDestroyBlock = copy->yDestroyBlock; + zDestroyBlock = copy->zDestroyBlock; + destroyProgress = copy->destroyProgress; + oDestroyProgress = copy->oDestroyProgress; + destroyTicks = copy->destroyTicks; destroyDelay = copy->destroyDelay; } -void SurvivalMode::initPlayer(std::shared_ptr player) -{ - player->yRot = -180; +void SurvivalMode::initPlayer(std::shared_ptr player) { + player->yRot = -180; } -void SurvivalMode::init() -{ -} +void SurvivalMode::init() {} -bool SurvivalMode::canHurtPlayer() -{ - return true; -} +bool SurvivalMode::canHurtPlayer() { return true; } -bool SurvivalMode::destroyBlock(int x, int y, int z, int face) -{ +bool SurvivalMode::destroyBlock(int x, int y, int z, int face) { int t = minecraft->level->getTile(x, y, z); int data = minecraft->level->getData(x, y, z); bool changed = GameMode::destroyBlock(x, y, z, face); std::shared_ptr item = minecraft->player->getSelectedItem(); bool couldDestroy = minecraft->player->canDestroy(Tile::tiles[t]); - if (item != NULL) - { + if (item != NULL) { item->mineBlock(minecraft->level, t, x, y, z, minecraft->player); - if (item->count == 0) - { + if (item->count == 0) { minecraft->player->removeSelectedItem(); } } - if (changed && couldDestroy) - { - Tile::tiles[t]->playerDestroy(minecraft->level, minecraft->player, x, y, z, data); - } + if (changed && couldDestroy) { + Tile::tiles[t]->playerDestroy(minecraft->level, minecraft->player, x, y, + z, data); + } return changed; - } -void SurvivalMode::startDestroyBlock(int x, int y, int z, int face) -{ - if (!minecraft->player->mayBuild(x, y, z)) return; +void SurvivalMode::startDestroyBlock(int x, int y, int z, int face) { + if (!minecraft->player->mayBuild(x, y, z)) return; minecraft->level->extinguishFire(minecraft->player, x, y, z, face); int t = minecraft->level->getTile(x, y, z); - if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); - if (t > 0 && Tile::tiles[t]->getDestroyProgress(minecraft->player) >= 1) - { + if (t > 0 && destroyProgress == 0) + Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); + if (t > 0 && Tile::tiles[t]->getDestroyProgress(minecraft->player) >= 1) { destroyBlock(x, y, z, face); } } -void SurvivalMode::stopDestroyBlock() -{ +void SurvivalMode::stopDestroyBlock() { destroyProgress = 0; destroyDelay = 0; } -void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) -{ - if (destroyDelay > 0) - { +void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) { + if (destroyDelay > 0) { destroyDelay--; return; } - if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) - { + if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) { int t = minecraft->level->getTile(x, y, z); - if (!minecraft->player->mayBuild(x, y, z)) return; + if (!minecraft->player->mayBuild(x, y, z)) return; if (t == 0) return; - Tile *tile = Tile::tiles[t]; + Tile* tile = Tile::tiles[t]; destroyProgress += tile->getDestroyProgress(minecraft->player); - if (destroyTicks % 4 == 0) - { - if (tile != NULL) - { - minecraft->soundEngine->play(tile->soundType->getStepSound(), x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f); + if (destroyTicks % 4 == 0) { + if (tile != NULL) { + minecraft->soundEngine->play( + tile->soundType->getStepSound(), x + 0.5f, y + 0.5f, + z + 0.5f, (tile->soundType->getVolume() + 1) / 8, + tile->soundType->getPitch() * 0.5f); } } destroyTicks++; - if (destroyProgress >= 1) - { + if (destroyProgress >= 1) { destroyBlock(x, y, z, face); destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; destroyDelay = 5; } - } - else - { + } else { destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; @@ -145,64 +125,49 @@ void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) yDestroyBlock = y; zDestroyBlock = z; } - } -void SurvivalMode::render(float a) -{ - if (destroyProgress <= 0) - { +void SurvivalMode::render(float a) { + if (destroyProgress <= 0) { minecraft->gui->progress = 0; minecraft->levelRenderer->destroyProgress = 0; - } - else - { + } else { float dp = oDestroyProgress + (destroyProgress - oDestroyProgress) * a; minecraft->gui->progress = dp; minecraft->levelRenderer->destroyProgress = dp; } } -float SurvivalMode::getPickRange() -{ - return 4.0f; +float SurvivalMode::getPickRange() { return 4.0f; } + +void SurvivalMode::initLevel(Level* level) { GameMode::initLevel(level); } + +std::shared_ptr SurvivalMode::createPlayer(Level* level) { + std::shared_ptr player = GameMode::createPlayer(level); + // player.inventory.add(new ItemInstance(Item.pickAxe_diamond)); + // player.inventory.add(new ItemInstance(Item.hatchet_diamond)); + // player.inventory.add(new ItemInstance(Tile.torch, 64)); + // player.inventory.add(new ItemInstance(Item.porkChop_cooked, 4)); + // player.inventory.add(new ItemInstance(Item.bow, 1)); + // player.inventory.add(new ItemInstance(Item.arrow, 64)); + return player; } -void SurvivalMode::initLevel(Level *level) -{ - GameMode::initLevel(level); -} - -std::shared_ptr SurvivalMode::createPlayer(Level *level) -{ - std::shared_ptr player = GameMode::createPlayer(level); - // player.inventory.add(new ItemInstance(Item.pickAxe_diamond)); - // player.inventory.add(new ItemInstance(Item.hatchet_diamond)); - // player.inventory.add(new ItemInstance(Tile.torch, 64)); - // player.inventory.add(new ItemInstance(Item.porkChop_cooked, 4)); - // player.inventory.add(new ItemInstance(Item.bow, 1)); - // player.inventory.add(new ItemInstance(Item.arrow, 64)); - return player; -} - -void SurvivalMode::tick() -{ +void SurvivalMode::tick() { oDestroyProgress = destroyProgress; - //minecraft->soundEngine->playMusicTick(); + // minecraft->soundEngine->playMusicTick(); } -bool SurvivalMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly, bool *pbUsedItem) -{ - int t = level->getTile(x, y, z); - if (t > 0) - { - if (Tile::tiles[t]->use(level, x, y, z, player)) return true; - } - if (item == NULL) return false; - return item->useOn(player, level, x, y, z, face); +bool SurvivalMode::useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly, + bool* pbUsedItem) { + int t = level->getTile(x, y, z); + if (t > 0) { + if (Tile::tiles[t]->use(level, x, y, z, player)) return true; + } + if (item == NULL) return false; + return item->useOn(player, level, x, y, z, face); } -bool SurvivalMode::hasExperience() -{ - return true; -} \ No newline at end of file +bool SurvivalMode::hasExperience() { return true; } \ No newline at end of file diff --git a/Minecraft.Client/GameState/SurvivalMode.h b/Minecraft.Client/GameState/SurvivalMode.h index 643e50d15..406cdcc1e 100644 --- a/Minecraft.Client/GameState/SurvivalMode.h +++ b/Minecraft.Client/GameState/SurvivalMode.h @@ -1,32 +1,34 @@ #pragma once #include "GameMode.h" -class SurvivalMode : public GameMode -{ +class SurvivalMode : public GameMode { private: - int xDestroyBlock; + int xDestroyBlock; int yDestroyBlock; int zDestroyBlock; float destroyProgress; float oDestroyProgress; - int destroyTicks; // 4J was float but doesn't seem to need to be + int destroyTicks; // 4J was float but doesn't seem to need to be int destroyDelay; public: - SurvivalMode(Minecraft *minecraft); - SurvivalMode(SurvivalMode *copy); + SurvivalMode(Minecraft* minecraft); + SurvivalMode(SurvivalMode* copy); virtual void initPlayer(std::shared_ptr player); virtual void init(); - virtual bool canHurtPlayer(); + virtual bool canHurtPlayer(); virtual bool destroyBlock(int x, int y, int z, int face); virtual void startDestroyBlock(int x, int y, int z, int face); virtual void stopDestroyBlock(); virtual void continueDestroyBlock(int x, int y, int z, int face); virtual void render(float a); virtual float getPickRange(); - virtual void initLevel(Level *level); - virtual std::shared_ptr createPlayer(Level *level); + virtual void initLevel(Level* level); + virtual std::shared_ptr createPlayer(Level* level); virtual void tick(); - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem=NULL); - virtual bool hasExperience(); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, bool bTestUseOnOnly = false, + bool* pbUsedItem = NULL); + virtual bool hasExperience(); }; \ No newline at end of file diff --git a/Minecraft.Client/Input/ConsoleInput.cpp b/Minecraft.Client/Input/ConsoleInput.cpp index 98f047d18..66aebd432 100644 --- a/Minecraft.Client/Input/ConsoleInput.cpp +++ b/Minecraft.Client/Input/ConsoleInput.cpp @@ -1,8 +1,8 @@ #include "../Platform/stdafx.h" #include "ConsoleInput.h" -ConsoleInput::ConsoleInput(const std::wstring& msg, ConsoleInputSource *source) -{ - this->msg = msg; - this->source = source; +ConsoleInput::ConsoleInput(const std::wstring& msg, + ConsoleInputSource* source) { + this->msg = msg; + this->source = source; } \ No newline at end of file diff --git a/Minecraft.Client/Input/ConsoleInput.h b/Minecraft.Client/Input/ConsoleInput.h index db228631a..4b0d36fbe 100644 --- a/Minecraft.Client/Input/ConsoleInput.h +++ b/Minecraft.Client/Input/ConsoleInput.h @@ -1,12 +1,10 @@ #pragma once #include "ConsoleInputSource.h" - -class ConsoleInput -{ +class ConsoleInput { public: - std::wstring msg; - ConsoleInputSource *source; + std::wstring msg; + ConsoleInputSource* source; - ConsoleInput(const std::wstring& msg, ConsoleInputSource *source); + ConsoleInput(const std::wstring& msg, ConsoleInputSource* source); }; \ No newline at end of file diff --git a/Minecraft.Client/Input/ConsoleInputSource.h b/Minecraft.Client/Input/ConsoleInputSource.h index 391d12916..82b66214a 100644 --- a/Minecraft.Client/Input/ConsoleInputSource.h +++ b/Minecraft.Client/Input/ConsoleInputSource.h @@ -1,10 +1,9 @@ #pragma once -class ConsoleInputSource -{ +class ConsoleInputSource { public: - virtual ~ConsoleInputSource(){} - virtual void info(const std::wstring& string) = 0; + virtual ~ConsoleInputSource() {} + virtual void info(const std::wstring& string) = 0; virtual void warn(const std::wstring& string) = 0; virtual std::wstring getConsoleName() = 0; }; diff --git a/Minecraft.Client/Input/Input.cpp b/Minecraft.Client/Input/Input.cpp index 439a0e536..69b5e9f09 100644 --- a/Minecraft.Client/Input/Input.cpp +++ b/Minecraft.Client/Input/Input.cpp @@ -8,108 +8,123 @@ #include "../Player/LocalPlayer.h" #include "../GameState/Options.h" -Input::Input() -{ - xa = 0; - ya = 0; - wasJumping = false; - jumping = false; - sneaking = false; - sprintKey = false; +Input::Input() { + xa = 0; + ya = 0; + wasJumping = false; + jumping = false; + sneaking = false; + sprintKey = false; - lReset = false; + lReset = false; rReset = false; } -void Input::tick(LocalPlayer *player) -{ - // 4J Stu - Assume that we only need one input class, even though the java has subclasses for keyboard/controller - // This function is based on the ControllerInput class in the Java, and will probably need changed - //OutputDebugString("INPUT: Beginning input tick\n"); +void Input::tick(LocalPlayer* player) { + // 4J Stu - Assume that we only need one input class, even though the java + // has subclasses for keyboard/controller This function is based on the + // ControllerInput class in the Java, and will probably need changed + // OutputDebugString("INPUT: Beginning input tick\n"); - Minecraft *pMinecraft=Minecraft::GetInstance(); - int iPad=player->GetXboxPad(); + Minecraft* pMinecraft = Minecraft::GetInstance(); + int iPad = player->GetXboxPad(); - // 4J-PB minecraft movement seems to be the wrong way round, so invert x! - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LEFT) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_RIGHT) ) - xa = -InputManager.GetJoypadStick_LX(iPad); - else - xa = 0.0f; - - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_FORWARD) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_BACKWARD) ) - ya = InputManager.GetJoypadStick_LY(iPad); - else - ya = 0.0f; + // 4J-PB minecraft movement seems to be the wrong way round, so invert x! + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LEFT) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_RIGHT)) + xa = -InputManager.GetJoypadStick_LX(iPad); + else + xa = 0.0f; + + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_FORWARD) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_BACKWARD)) + ya = InputManager.GetJoypadStick_LY(iPad); + else + ya = 0.0f; #ifndef _CONTENT_PACKAGE - if (app.GetFreezePlayers()) - { - xa = ya = 0.0f; - player->abilities.flying = true; - } + if (app.GetFreezePlayers()) { + xa = ya = 0.0f; + player->abilities.flying = true; + } #endif - - if (!lReset) - { - if (xa*xa+ya*ya==0.0f) - { + + if (!lReset) { + if (xa * xa + ya * ya == 0.0f) { lReset = true; } xa = ya = 0.0f; } - // 4J - in flying mode, don't actually toggle sneaking - if(!player->abilities.flying) - { - if((player->ullButtonsPressed&(1LL<localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SNEAK_TOGGLE)) - { - sneaking=!sneaking; - } - } + // 4J - in flying mode, don't actually toggle sneaking + if (!player->abilities.flying) { + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_SNEAK_TOGGLE)) && + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_SNEAK_TOGGLE)) { + sneaking = !sneaking; + } + } - if(sneaking) - { - xa*=0.3f; - ya*=0.3f; - } + if (sneaking) { + xa *= 0.3f; + ya *= 0.3f; + } float turnSpeed = 50.0f; - float tx = 0.0f; - float ty = 0.0f; - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_LEFT) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_RIGHT) ) - tx = InputManager.GetJoypadStick_RX(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look - if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_UP) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_DOWN) ) - ty = InputManager.GetJoypadStick_RY(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look - + float tx = 0.0f; + float ty = 0.0f; + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_LEFT) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_RIGHT)) + tx = InputManager.GetJoypadStick_RX(iPad) * + (((float)app.GetGameSettings(iPad, + eGameSetting_Sensitivity_InGame)) / + 100.0f); // apply sensitivity to look + if (pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_UP) || + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_LOOK_DOWN)) + ty = InputManager.GetJoypadStick_RY(iPad) * + (((float)app.GetGameSettings(iPad, + eGameSetting_Sensitivity_InGame)) / + 100.0f); // apply sensitivity to look + #ifndef _CONTENT_PACKAGE - if (app.GetFreezePlayers()) tx = ty = 0.0f; + if (app.GetFreezePlayers()) tx = ty = 0.0f; #endif - // 4J: WESTY : Invert look Y if required. - if ( app.GetGameSettings(iPad,eGameSetting_ControlInvertLook) ) - { - ty = -ty; - } + // 4J: WESTY : Invert look Y if required. + if (app.GetGameSettings(iPad, eGameSetting_ControlInvertLook)) { + ty = -ty; + } - if (!rReset) - { - if (tx*tx+ty*ty==0.0f) - { + if (!rReset) { + if (tx * tx + ty * ty == 0.0f) { rReset = true; } tx = ty = 0.0f; } - player->interpolateTurn(tx * abs(tx) * turnSpeed, ty * abs(ty) * turnSpeed); - - //jumping = controller.isButtonPressed(0); + player->interpolateTurn(tx * abs(tx) * turnSpeed, ty * abs(ty) * turnSpeed); - sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SPRINT); - jumping = InputManager.GetValue(iPad, MINECRAFT_ACTION_JUMP) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_JUMP); + // jumping = controller.isButtonPressed(0); + + sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) && + pMinecraft->localgameModes[iPad]->isInputAllowed( + MINECRAFT_ACTION_SPRINT); + jumping = + InputManager.GetValue(iPad, MINECRAFT_ACTION_JUMP) && + pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_JUMP); #ifndef _CONTENT_PACKAGE - if (app.GetFreezePlayers()) jumping = false; + if (app.GetFreezePlayers()) jumping = false; #endif - //OutputDebugString("INPUT: End input tick\n"); + // OutputDebugString("INPUT: End input tick\n"); } \ No newline at end of file diff --git a/Minecraft.Client/Input/Input.h b/Minecraft.Client/Input/Input.h index d30df79a2..fc2dc03dc 100644 --- a/Minecraft.Client/Input/Input.h +++ b/Minecraft.Client/Input/Input.h @@ -1,24 +1,22 @@ #pragma once class Player; -class Input -{ +class Input { public: - float xa; + float xa; float ya; bool wasJumping; bool jumping; bool sneaking; bool sprintKey; - - Input(); // 4J - added - virtual ~Input(){} - virtual void tick(LocalPlayer *player); + Input(); // 4J - added + virtual ~Input() {} + + virtual void tick(LocalPlayer* player); private: - bool lReset; bool rReset; }; diff --git a/Minecraft.Client/Input/KeyMapping.cpp b/Minecraft.Client/Input/KeyMapping.cpp index b993aabec..c439bde54 100644 --- a/Minecraft.Client/Input/KeyMapping.cpp +++ b/Minecraft.Client/Input/KeyMapping.cpp @@ -1,8 +1,7 @@ #include "../Platform/stdafx.h" #include "KeyMapping.h" -KeyMapping::KeyMapping(const std::wstring& name, int key) -{ - this->name = name; - this->key = key; +KeyMapping::KeyMapping(const std::wstring& name, int key) { + this->name = name; + this->key = key; } \ No newline at end of file diff --git a/Minecraft.Client/Input/KeyMapping.h b/Minecraft.Client/Input/KeyMapping.h index 85ac8d211..6f06e6c1a 100644 --- a/Minecraft.Client/Input/KeyMapping.h +++ b/Minecraft.Client/Input/KeyMapping.h @@ -1,10 +1,9 @@ #pragma once // 4J Stu - Not updated to 1.8.2 as we don't use this -class KeyMapping -{ +class KeyMapping { public: - std::wstring name; - int key; - KeyMapping(const std::wstring& name, int key); + std::wstring name; + int key; + KeyMapping(const std::wstring& name, int key); }; \ No newline at end of file diff --git a/Minecraft.Client/Level/DemoLevel.cpp b/Minecraft.Client/Level/DemoLevel.cpp index f7d633e96..6549de08d 100644 --- a/Minecraft.Client/Level/DemoLevel.cpp +++ b/Minecraft.Client/Level/DemoLevel.cpp @@ -2,24 +2,17 @@ #include "DemoLevel.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.storage.h" -LevelSettings DemoLevel::DEMO_LEVEL_SETTINGS = LevelSettings( - DemoLevel::DEMO_LEVEL_SEED, - GameType::SURVIVAL, - false, - false, - false, LevelType::lvl_normal_1_1, LEVEL_MAX_WIDTH, - 1.0 -); +LevelSettings DemoLevel::DEMO_LEVEL_SETTINGS = + LevelSettings(DemoLevel::DEMO_LEVEL_SEED, GameType::SURVIVAL, false, false, + false, LevelType::lvl_normal_1_1, LEVEL_MAX_WIDTH, 1.0); -DemoLevel::DemoLevel(std::shared_ptr levelStorage, const std::wstring& levelName) : Level(levelStorage, levelName, &DEMO_LEVEL_SETTINGS) -{ -} +DemoLevel::DemoLevel(std::shared_ptr levelStorage, + const std::wstring& levelName) + : Level(levelStorage, levelName, &DEMO_LEVEL_SETTINGS) {} -DemoLevel::DemoLevel(Level *level, Dimension *dimension): Level(level, dimension) -{ -} +DemoLevel::DemoLevel(Level* level, Dimension* dimension) + : Level(level, dimension) {} -void DemoLevel::setInitialSpawn() -{ - levelData->setSpawn(DEMO_SPAWN_X, DEMO_SPAWN_Y, DEMO_SPAWN_Z); +void DemoLevel::setInitialSpawn() { + levelData->setSpawn(DEMO_SPAWN_X, DEMO_SPAWN_Y, DEMO_SPAWN_Z); } \ No newline at end of file diff --git a/Minecraft.Client/Level/DemoLevel.h b/Minecraft.Client/Level/DemoLevel.h index d8639dee7..4bfa37984 100644 --- a/Minecraft.Client/Level/DemoLevel.h +++ b/Minecraft.Client/Level/DemoLevel.h @@ -1,17 +1,20 @@ #pragma once #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" -class DemoLevel : public Level -{ +class DemoLevel : public Level { private: - static const __int64 DEMO_LEVEL_SEED = 0; // 4J - TODO - was "Don't Look Back".hashCode(); + static const __int64 DEMO_LEVEL_SEED = + 0; // 4J - TODO - was "Don't Look Back".hashCode(); static const int DEMO_SPAWN_X = 796; static const int DEMO_SPAWN_Y = 72; static const int DEMO_SPAWN_Z = -731; static LevelSettings DEMO_LEVEL_SETTINGS; + public: - DemoLevel(std::shared_ptr levelStorage, const std::wstring& levelName); - DemoLevel(Level *level, Dimension *dimension); + DemoLevel(std::shared_ptr levelStorage, + const std::wstring& levelName); + DemoLevel(Level* level, Dimension* dimension); + protected: - virtual void setInitialSpawn(); + virtual void setInitialSpawn(); }; diff --git a/Minecraft.Client/Level/DerivedServerLevel.cpp b/Minecraft.Client/Level/DerivedServerLevel.cpp index 199db90fc..0038111b3 100644 --- a/Minecraft.Client/Level/DerivedServerLevel.cpp +++ b/Minecraft.Client/Level/DerivedServerLevel.cpp @@ -3,27 +3,28 @@ #include "../../Minecraft.World/Level/Storage/SavedDataStorage.h" #include "../../Minecraft.World/Level/DerivedLevelData.h" -DerivedServerLevel::DerivedServerLevel(MinecraftServer *server, std::shared_ptr levelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings, ServerLevel *wrapped) - : ServerLevel(server, levelStorage, levelName, dimension, levelSettings) -{ - // 4J-PB - we're going to override the savedDataStorage, so we need to delete the current one - if(this->savedDataStorage) - { - delete this->savedDataStorage; - this->savedDataStorage=NULL; - } - this->savedDataStorage = wrapped->savedDataStorage; - levelData = new DerivedLevelData(wrapped->getLevelData()); +DerivedServerLevel::DerivedServerLevel( + MinecraftServer* server, std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, LevelSettings* levelSettings, + ServerLevel* wrapped) + : ServerLevel(server, levelStorage, levelName, dimension, levelSettings) { + // 4J-PB - we're going to override the savedDataStorage, so we need to + // delete the current one + if (this->savedDataStorage) { + delete this->savedDataStorage; + this->savedDataStorage = NULL; + } + this->savedDataStorage = wrapped->savedDataStorage; + levelData = new DerivedLevelData(wrapped->getLevelData()); } -DerivedServerLevel::~DerivedServerLevel() -{ - // we didn't allocate savedDataStorage here, so we don't want the level destructor to delete it - this->savedDataStorage=NULL; +DerivedServerLevel::~DerivedServerLevel() { + // we didn't allocate savedDataStorage here, so we don't want the level + // destructor to delete it + this->savedDataStorage = NULL; } -void DerivedServerLevel::saveLevelData() -{ - // Do nothing? - // Do nothing! +void DerivedServerLevel::saveLevelData() { + // Do nothing? + // Do nothing! } \ No newline at end of file diff --git a/Minecraft.Client/Level/DerivedServerLevel.h b/Minecraft.Client/Level/DerivedServerLevel.h index 2c9048563..72e63880d 100644 --- a/Minecraft.Client/Level/DerivedServerLevel.h +++ b/Minecraft.Client/Level/DerivedServerLevel.h @@ -1,12 +1,14 @@ #pragma once #include "ServerLevel.h" -class DerivedServerLevel : public ServerLevel -{ +class DerivedServerLevel : public ServerLevel { public: - DerivedServerLevel(MinecraftServer *server, std::shared_ptrlevelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings, ServerLevel *wrapped); - ~DerivedServerLevel(); + DerivedServerLevel(MinecraftServer* server, + std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, + LevelSettings* levelSettings, ServerLevel* wrapped); + ~DerivedServerLevel(); protected: - void saveLevelData(); + void saveLevelData(); }; \ No newline at end of file diff --git a/Minecraft.Client/Level/MultiPlayerLevel.cpp b/Minecraft.Client/Level/MultiPlayerLevel.cpp index dc901fef7..4f0055489 100644 --- a/Minecraft.Client/Level/MultiPlayerLevel.cpp +++ b/Minecraft.Client/Level/MultiPlayerLevel.cpp @@ -13,8 +13,8 @@ #include "../../Minecraft.World/Blocks/Tile.h" #include "../../Minecraft.World/Blocks/TileEntities/TileEntity.h" -MultiPlayerLevel::ResetInfo::ResetInfo(int x, int y, int z, int tile, int data) -{ +MultiPlayerLevel::ResetInfo::ResetInfo(int x, int y, int z, int tile, + int data) { this->x = x; this->y = y; this->z = z; @@ -23,406 +23,407 @@ MultiPlayerLevel::ResetInfo::ResetInfo(int x, int y, int z, int tile, int data) this->data = data; } -MultiPlayerLevel::MultiPlayerLevel(ClientConnection *connection, LevelSettings *levelSettings, int dimension, int difficulty) - : Level(std::shared_ptr(new MockedLevelStorage()), L"MpServer", Dimension::getNew(dimension), levelSettings, false) -{ - minecraft = Minecraft::GetInstance(); +MultiPlayerLevel::MultiPlayerLevel(ClientConnection* connection, + LevelSettings* levelSettings, int dimension, + int difficulty) + : Level(std::shared_ptr(new MockedLevelStorage()), + L"MpServer", Dimension::getNew(dimension), levelSettings, false) { + minecraft = Minecraft::GetInstance(); - // 4J - this this used to be called in parent ctor via a virtual fn - chunkSource = createChunkSource(); - // 4J - optimisation - keep direct reference of underlying cache here - chunkSourceCache = chunkSource->getCache(); - chunkSourceXZSize = chunkSource->m_XZSize; + // 4J - this this used to be called in parent ctor via a virtual fn + chunkSource = createChunkSource(); + // 4J - optimisation - keep direct reference of underlying cache here + chunkSourceCache = chunkSource->getCache(); + chunkSourceXZSize = chunkSource->m_XZSize; - // This also used to be called in parent ctor, but can't be called until chunkSource is created. Call now if required. - if (!levelData->isInitialized()) - { - initializeLevel(levelSettings); - levelData->setInitialized(true); - } - - if(connection !=NULL) - { - this->connections.push_back( connection ); - } - this->difficulty = difficulty; - // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing towards the original spawn point, once the player has entered the Nether. - // 4J Stu - We should never be setting a specific spawn position for a multiplayer, this should only be set by receiving a packet from the server - // (which happens when a player logs in) - //setSpawnPos(new Pos(8, 64, 8)); - // The base ctor already has made some storage, so need to delete that - if( this->savedDataStorage ) delete savedDataStorage; - if(connection !=NULL) - { - this->savedDataStorage = connection->savedDataStorage; - } - unshareCheckX = 0; - unshareCheckZ = 0; - compressCheckX = 0; - compressCheckZ = 0; - - // 4J Added, as there are some times when we don't want to add tile updates to the updatesToReset vector - m_bEnableResetChanges = true; -} - -MultiPlayerLevel::~MultiPlayerLevel() -{ - // Don't let the base class delete this, it comes from the connection for multiplayerlevels, and we'll delete there - this->savedDataStorage = NULL; -} - -void MultiPlayerLevel::unshareChunkAt(int x, int z) -{ - if( g_NetworkManager.IsHost() ) - { - Level::getChunkAt(x,z)->stopSharingTilesAndData(); - } -} - -void MultiPlayerLevel::shareChunkAt(int x, int z) -{ - if( g_NetworkManager.IsHost() ) - { - Level::getChunkAt(x,z)->startSharingTilesAndData(); - } -} - - -void MultiPlayerLevel::tick() -{ - PIXBeginNamedEvent(0,"Sky color changing"); - setTime(getTime() + 1); - /* 4J - change brought forward from 1.8.2 - int newDark = this->getSkyDarken(1); - if (newDark != skyDarken) - { - skyDarken = newDark; - for (unsigned int i = 0; i < listeners.size(); i++) - { - listeners[i]->skyColorChanged(); - } - }*/ - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Entity re-entry"); - EnterCriticalSection(&m_entitiesCS); - for (int i = 0; i < 10 && !reEntries.empty(); i++) - { - std::shared_ptr e = *(reEntries.begin()); - - if (find(entities.begin(), entities.end(), e) == entities.end() ) addEntity(e); + // This also used to be called in parent ctor, but can't be called until + // chunkSource is created. Call now if required. + if (!levelData->isInitialized()) { + initializeLevel(levelSettings); + levelData->setInitialized(true); } - LeaveCriticalSection(&m_entitiesCS); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Connection ticking"); - // 4J HEG - Copy the connections vector to prevent crash when moving to Nether - std::vector connectionsTemp = connections; - for(AUTO_VAR(connection, connectionsTemp.begin()); connection < connectionsTemp.end(); ++connection ) - { - (*connection)->tick(); - } - PIXEndNamedEvent(); + if (connection != NULL) { + this->connections.push_back(connection); + } + this->difficulty = difficulty; + // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing + // towards the original spawn point, once the player has entered the Nether. + // 4J Stu - We should never be setting a specific spawn position for a + // multiplayer, this should only be set by receiving a packet from the + // server (which happens when a player logs in) + // setSpawnPos(new Pos(8, 64, 8)); + // The base ctor already has made some storage, so need to delete that + if (this->savedDataStorage) delete savedDataStorage; + if (connection != NULL) { + this->savedDataStorage = connection->savedDataStorage; + } + unshareCheckX = 0; + unshareCheckZ = 0; + compressCheckX = 0; + compressCheckZ = 0; - PIXBeginNamedEvent(0,"Updating resets"); - unsigned int lastIndexToRemove = 0; - bool eraseElements = false; - for (unsigned int i = 0; i < updatesToReset.size(); i++) - { + // 4J Added, as there are some times when we don't want to add tile updates + // to the updatesToReset vector + m_bEnableResetChanges = true; +} + +MultiPlayerLevel::~MultiPlayerLevel() { + // Don't let the base class delete this, it comes from the connection for + // multiplayerlevels, and we'll delete there + this->savedDataStorage = NULL; +} + +void MultiPlayerLevel::unshareChunkAt(int x, int z) { + if (g_NetworkManager.IsHost()) { + Level::getChunkAt(x, z)->stopSharingTilesAndData(); + } +} + +void MultiPlayerLevel::shareChunkAt(int x, int z) { + if (g_NetworkManager.IsHost()) { + Level::getChunkAt(x, z)->startSharingTilesAndData(); + } +} + +void MultiPlayerLevel::tick() { + PIXBeginNamedEvent(0, "Sky color changing"); + setTime(getTime() + 1); + /* 4J - change brought forward from 1.8.2 +int newDark = this->getSkyDarken(1); +if (newDark != skyDarken) + { + skyDarken = newDark; + for (unsigned int i = 0; i < listeners.size(); i++) + { + listeners[i]->skyColorChanged(); + } +}*/ + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Entity re-entry"); + EnterCriticalSection(&m_entitiesCS); + for (int i = 0; i < 10 && !reEntries.empty(); i++) { + std::shared_ptr e = *(reEntries.begin()); + + if (find(entities.begin(), entities.end(), e) == entities.end()) + addEntity(e); + } + LeaveCriticalSection(&m_entitiesCS); + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Connection ticking"); + // 4J HEG - Copy the connections vector to prevent crash when moving to + // Nether + std::vector connectionsTemp = connections; + for (AUTO_VAR(connection, connectionsTemp.begin()); + connection < connectionsTemp.end(); ++connection) { + (*connection)->tick(); + } + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Updating resets"); + unsigned int lastIndexToRemove = 0; + bool eraseElements = false; + for (unsigned int i = 0; i < updatesToReset.size(); i++) { ResetInfo& r = updatesToReset[i]; - if (--r.ticks == 0) - { + if (--r.ticks == 0) { Level::setTileAndDataNoUpdate(r.x, r.y, r.z, r.tile, r.data); Level::sendTileUpdated(r.x, r.y, r.z); - - //updatesToReset.erase(updatesToReset.begin()+i); - eraseElements = true; - lastIndexToRemove = 0; - i--; + // updatesToReset.erase(updatesToReset.begin()+i); + eraseElements = true; + lastIndexToRemove = 0; + + i--; } } - // 4J Stu - As elements in the updatesToReset vector are inserted with a fixed initial lifetime, the elements at the front should always be the oldest - // Therefore we can always remove from the first element - if(eraseElements) - { - updatesToReset.erase(updatesToReset.begin(), updatesToReset.begin()+lastIndexToRemove); - } - PIXEndNamedEvent(); + // 4J Stu - As elements in the updatesToReset vector are inserted with a + // fixed initial lifetime, the elements at the front should always be the + // oldest Therefore we can always remove from the first element + if (eraseElements) { + updatesToReset.erase(updatesToReset.begin(), + updatesToReset.begin() + lastIndexToRemove); + } + PIXEndNamedEvent(); - chunkCache->tick(); - tickTiles(); + chunkCache->tick(); + tickTiles(); - // 4J - added this section. Each tick we'll check a different block, and force it to share data if it has been - // more than 2 minutes since we last wanted to unshare it. This shouldn't really ever happen, and is added - // here as a safe guard against accumulated memory leaks should a lot of chunks become unshared over time. - - int ls = dimension->getXZSize(); - if( g_NetworkManager.IsHost() ) - { - if( Level::reallyHasChunk(unshareCheckX - ( ls / 2), unshareCheckZ - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(unshareCheckX - ( ls / 2), unshareCheckZ - ( ls / 2 )); - if( g_NetworkManager.IsHost() ) - { - lc->startSharingTilesAndData(1000 * 60 * 2); - } - } + // 4J - added this section. Each tick we'll check a different block, and + // force it to share data if it has been more than 2 minutes since we last + // wanted to unshare it. This shouldn't really ever happen, and is added + // here as a safe guard against accumulated memory leaks should a lot of + // chunks become unshared over time. - unshareCheckX++; - if( unshareCheckX >= ls ) - { - unshareCheckX = 0; - unshareCheckZ++; - if( unshareCheckZ >= ls ) - { - unshareCheckZ = 0; - } - } - } + int ls = dimension->getXZSize(); + if (g_NetworkManager.IsHost()) { + if (Level::reallyHasChunk(unshareCheckX - (ls / 2), + unshareCheckZ - (ls / 2))) { + LevelChunk* lc = Level::getChunk(unshareCheckX - (ls / 2), + unshareCheckZ - (ls / 2)); + if (g_NetworkManager.IsHost()) { + lc->startSharingTilesAndData(1000 * 60 * 2); + } + } - // 4J added - also similar thing tosee if we can compress the lighting in any of these chunks. This is slightly different - // as it does try to make sure that at least one chunk has something done to it. + unshareCheckX++; + if (unshareCheckX >= ls) { + unshareCheckX = 0; + unshareCheckZ++; + if (unshareCheckZ >= ls) { + unshareCheckZ = 0; + } + } + } - // At most loop round at least one row the chunks, so we should be able to at least find a non-empty chunk to do something with in 2.7 seconds of ticks, and process the whole thing in about 2.4 minutes. - for( int i = 0; i < ls; i++ ) - { - compressCheckX++; - if( compressCheckX >= ls ) - { - compressCheckX = 0; - compressCheckZ++; - if( compressCheckZ >= ls ) - { - compressCheckZ = 0; - } - } + // 4J added - also similar thing tosee if we can compress the lighting in + // any of these chunks. This is slightly different as it does try to make + // sure that at least one chunk has something done to it. - if( Level::reallyHasChunk(compressCheckX - ( ls / 2), compressCheckZ - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(compressCheckX - ( ls / 2), compressCheckZ - ( ls / 2 )); - lc->compressLighting(); - lc->compressBlocks(); - lc->compressData(); - break; - } - } + // At most loop round at least one row the chunks, so we should be able to + // at least find a non-empty chunk to do something with in 2.7 seconds of + // ticks, and process the whole thing in about 2.4 minutes. + for (int i = 0; i < ls; i++) { + compressCheckX++; + if (compressCheckX >= ls) { + compressCheckX = 0; + compressCheckZ++; + if (compressCheckZ >= ls) { + compressCheckZ = 0; + } + } + + if (Level::reallyHasChunk(compressCheckX - (ls / 2), + compressCheckZ - (ls / 2))) { + LevelChunk* lc = Level::getChunk(compressCheckX - (ls / 2), + compressCheckZ - (ls / 2)); + lc->compressLighting(); + lc->compressBlocks(); + lc->compressData(); + break; + } + } #ifdef LIGHT_COMPRESSION_STATS - static int updateTick = 0; + static int updateTick = 0; - if( ( updateTick % 60 ) == 0 ) - { - unsigned int totalBLu = 0; - unsigned int totalBLl = 0; - unsigned int totalSLu = 0; - unsigned int totalSLl = 0; - unsigned int totalChunks = 0; + if ((updateTick % 60) == 0) { + unsigned int totalBLu = 0; + unsigned int totalBLl = 0; + unsigned int totalSLu = 0; + unsigned int totalSLl = 0; + unsigned int totalChunks = 0; - for( int lcs_x = 0; lcs_x < ls; lcs_x++ ) - for( int lcs_z = 0; lcs_z < ls; lcs_z++ ) - { - if( Level::reallyHasChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 )); - totalChunks++; - totalBLu += lc->getBlockLightPlanesUpper(); - totalBLl += lc->getBlockLightPlanesLower(); - totalSLu += lc->getSkyLightPlanesUpper(); - totalSLl += lc->getSkyLightPlanesLower(); - } - } - if( totalChunks ) - { - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); + for (int lcs_x = 0; lcs_x < ls; lcs_x++) + for (int lcs_z = 0; lcs_z < ls; lcs_z++) { + if (Level::reallyHasChunk(lcs_x - (ls / 2), lcs_z - (ls / 2))) { + LevelChunk* lc = + Level::getChunk(lcs_x - (ls / 2), lcs_z - (ls / 2)); + totalChunks++; + totalBLu += lc->getBlockLightPlanesUpper(); + totalBLl += lc->getBlockLightPlanesLower(); + totalSLu += lc->getSkyLightPlanesUpper(); + totalSLl += lc->getSkyLightPlanesLower(); + } + } + if (totalChunks) { + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); - unsigned int totalBL = totalBLu + totalBLl; - unsigned int totalSL = totalSLu + totalSLl; - printf("%d: %d chunks, %d BL (%d + %d), %d SL (%d + %d ) (out of %d) - total %d %% (%dMB mem free)\n", - dimension->id, totalChunks, totalBL, totalBLu, totalBLl, totalSL, totalSLu, totalSLl, totalChunks * 256, ( 100 * (totalBL + totalSL) ) / ( totalChunks * 256 * 2),memStat.dwAvailPhys/(1024*1024) ); - } - } - updateTick++; + unsigned int totalBL = totalBLu + totalBLl; + unsigned int totalSL = totalSLu + totalSLl; + printf( + "%d: %d chunks, %d BL (%d + %d), %d SL (%d + %d ) (out of %d) " + "- total %d %% (%dMB mem free)\n", + dimension->id, totalChunks, totalBL, totalBLu, totalBLl, + totalSL, totalSLu, totalSLl, totalChunks * 256, + (100 * (totalBL + totalSL)) / (totalChunks * 256 * 2), + memStat.dwAvailPhys / (1024 * 1024)); + } + } + updateTick++; #endif #ifdef DATA_COMPRESSION_STATS - static int updateTick = 0; + static int updateTick = 0; - if( ( updateTick % 60 ) == 0 ) - { - unsigned int totalData = 0; - unsigned int totalChunks = 0; + if ((updateTick % 60) == 0) { + unsigned int totalData = 0; + unsigned int totalChunks = 0; - for( int lcs_x = 0; lcs_x < ls; lcs_x++ ) - for( int lcs_z = 0; lcs_z < ls; lcs_z++ ) - { - if( Level::reallyHasChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 )); - totalChunks++; - totalData += lc->getDataPlanes(); - } - } - if( totalChunks ) - { - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); + for (int lcs_x = 0; lcs_x < ls; lcs_x++) + for (int lcs_z = 0; lcs_z < ls; lcs_z++) { + if (Level::reallyHasChunk(lcs_x - (ls / 2), lcs_z - (ls / 2))) { + LevelChunk* lc = + Level::getChunk(lcs_x - (ls / 2), lcs_z - (ls / 2)); + totalChunks++; + totalData += lc->getDataPlanes(); + } + } + if (totalChunks) { + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); - printf("%d: %d chunks, %d data (out of %d) - total %d %% (%dMB mem free)\n", - dimension->id, totalChunks, totalData, totalChunks * 128, ( 100 * totalData)/ ( totalChunks * 128),memStat.dwAvailPhys/(1024*1024) ); - } - } - updateTick++; + printf( + "%d: %d chunks, %d data (out of %d) - total %d %% (%dMB mem " + "free)\n", + dimension->id, totalChunks, totalData, totalChunks * 128, + (100 * totalData) / (totalChunks * 128), + memStat.dwAvailPhys / (1024 * 1024)); + } + } + updateTick++; #endif #ifdef BLOCK_COMPRESSION_STATS - static int updateTick = 0; + static int updateTick = 0; - if( ( updateTick % 60 ) == 0 ) - { - unsigned int total = 0; - unsigned int totalChunks = 0; - unsigned int total0 = 0, total1 = 0, total2 = 0, total4 = 0, total8 = 0; + if ((updateTick % 60) == 0) { + unsigned int total = 0; + unsigned int totalChunks = 0; + unsigned int total0 = 0, total1 = 0, total2 = 0, total4 = 0, total8 = 0; - printf("*****************************************************************************************************************************************\n"); - printf("TODO: Report upper chunk data as well\n"); - for( int lcs_x = 0; lcs_x < ls; lcs_x++ ) - for( int lcs_z = 0; lcs_z < ls; lcs_z++ ) - { - if( Level::reallyHasChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 ) ) ) - { - LevelChunk *lc = Level::getChunk(lcs_x - ( ls / 2), lcs_z - ( ls / 2 )); - totalChunks++; - int i0, i1, i2, i4, i8; - int thisSize = lc->getBlocksAllocatedSize(&i0, &i1, &i2, &i4, &i8); - total0 += i0; - total1 += i1; - total2 += i2; - total4 += i4; - total8 += i8; - printf("%d ",thisSize); - thisSize = ( thisSize + 0xfff ) & 0xfffff000; // round to 4096k blocks for actual memory consumption - total += thisSize; - } - } - printf("\n*****************************************************************************************************************************************\n"); - if( totalChunks ) - { - printf("%d (0) %d (1) %d (2) %d (4) %d (8)\n",total0/totalChunks,total1/totalChunks,total2/totalChunks,total4/totalChunks,total8/totalChunks); - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); + printf( + "******************************************************************" + "******************************************************************" + "*****\n"); + printf("TODO: Report upper chunk data as well\n"); + for (int lcs_x = 0; lcs_x < ls; lcs_x++) + for (int lcs_z = 0; lcs_z < ls; lcs_z++) { + if (Level::reallyHasChunk(lcs_x - (ls / 2), lcs_z - (ls / 2))) { + LevelChunk* lc = + Level::getChunk(lcs_x - (ls / 2), lcs_z - (ls / 2)); + totalChunks++; + int i0, i1, i2, i4, i8; + int thisSize = + lc->getBlocksAllocatedSize(&i0, &i1, &i2, &i4, &i8); + total0 += i0; + total1 += i1; + total2 += i2; + total4 += i4; + total8 += i8; + printf("%d ", thisSize); + thisSize = (thisSize + 0xfff) & + 0xfffff000; // round to 4096k blocks for actual + // memory consumption + total += thisSize; + } + } + printf( + "\n****************************************************************" + "******************************************************************" + "*******\n"); + if (totalChunks) { + printf("%d (0) %d (1) %d (2) %d (4) %d (8)\n", total0 / totalChunks, + total1 / totalChunks, total2 / totalChunks, + total4 / totalChunks, total8 / totalChunks); + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); - printf("%d: %d chunks, %d KB (out of %dKB) : %d %% (%dMB mem free)\n", - dimension->id, totalChunks, total/1024, totalChunks * 32, ( ( total / 1024 ) * 100 ) / ( totalChunks * 32),memStat.dwAvailPhys/(1024*1024) ); - } - } - updateTick++; + printf( + "%d: %d chunks, %d KB (out of %dKB) : %d %% (%dMB mem free)\n", + dimension->id, totalChunks, total / 1024, totalChunks * 32, + ((total / 1024) * 100) / (totalChunks * 32), + memStat.dwAvailPhys / (1024 * 1024)); + } + } + updateTick++; #endif // super.tick(); - } -void MultiPlayerLevel::clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1) -{ - for (unsigned int i = 0; i < updatesToReset.size(); i++) - { +void MultiPlayerLevel::clearResetRegion(int x0, int y0, int z0, int x1, int y1, + int z1) { + for (unsigned int i = 0; i < updatesToReset.size(); i++) { ResetInfo& r = updatesToReset[i]; - if (r.x >= x0 && r.y >= y0 && r.z >= z0 && r.x <= x1 && r.y <= y1 && r.z <= z1) - { - updatesToReset.erase(updatesToReset.begin()+i); - i--; + if (r.x >= x0 && r.y >= y0 && r.z >= z0 && r.x <= x1 && r.y <= y1 && + r.z <= z1) { + updatesToReset.erase(updatesToReset.begin() + i); + i--; } } } -ChunkSource *MultiPlayerLevel::createChunkSource() -{ +ChunkSource* MultiPlayerLevel::createChunkSource() { chunkCache = new MultiPlayerChunkCache(this); return chunkCache; } -void MultiPlayerLevel::validateSpawn() -{ - // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing towards the original spawn point, once the player has entered the Nether. - // 4J Stu - We should never be setting a specific spawn position for a multiplayer, this should only be set by receiving a packet from the server - // (which happens when a player logs in) - //setSpawnPos(new Pos(8, 64, 8)); +void MultiPlayerLevel::validateSpawn() { + // Fix for #62566 - TU7: Content: Gameplay: Compass needle stops pointing + // towards the original spawn point, once the player has entered the Nether. + // 4J Stu - We should never be setting a specific spawn position for a + // multiplayer, this should only be set by receiving a packet from the + // server (which happens when a player logs in) + // setSpawnPos(new Pos(8, 64, 8)); } -void MultiPlayerLevel::tickTiles() -{ - chunksToPoll.clear(); // 4J - added or else we don't reset this set at all in a multiplayer level... think current java now resets in buildAndPrepareChunksToPoll rather than the calling functions +void MultiPlayerLevel::tickTiles() { + chunksToPoll.clear(); // 4J - added or else we don't reset this set at all + // in a multiplayer level... think current java now + // resets in buildAndPrepareChunksToPoll rather than + // the calling functions - PIXBeginNamedEvent(0,"Ticking tiles (multiplayer)"); - PIXBeginNamedEvent(0,"buildAndPrepareChunksToPoll"); - Level::tickTiles(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Ticking tiles (multiplayer)"); + PIXBeginNamedEvent(0, "buildAndPrepareChunksToPoll"); + Level::tickTiles(); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Ticking client side tiles"); + PIXBeginNamedEvent(0, "Ticking client side tiles"); #ifdef __PSVITA__ - // AP - see CustomSet.h for and explanation - for( int i = 0;i < chunksToPoll.end();i += 1 ) - { - ChunkPos cp = chunksToPoll.get(i); + // AP - see CustomSet.h for and explanation + for (int i = 0; i < chunksToPoll.end(); i += 1) { + ChunkPos cp = chunksToPoll.get(i); #else - AUTO_VAR(itEndCtp, chunksToPoll.end()); - for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCtp; it++) - { - ChunkPos cp = *it; + AUTO_VAR(itEndCtp, chunksToPoll.end()); + for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCtp; it++) { + ChunkPos cp = *it; #endif - int xo = cp.x * 16; - int zo = cp.z * 16; + int xo = cp.x * 16; + int zo = cp.z * 16; - LevelChunk *lc = this->getChunk(cp.x, cp.z); + LevelChunk* lc = this->getChunk(cp.x, cp.z); - tickClientSideTiles(xo, zo, lc); - } - PIXEndNamedEvent(); - PIXEndNamedEvent(); -} - -void MultiPlayerLevel::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, Level::maxBuildHeight, z * 16 + 15); + tickClientSideTiles(xo, zo, lc); } - + PIXEndNamedEvent(); + PIXEndNamedEvent(); } -bool MultiPlayerLevel::addEntity(std::shared_ptr e) -{ +void MultiPlayerLevel::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, + Level::maxBuildHeight, z * 16 + 15); + } +} + +bool MultiPlayerLevel::addEntity(std::shared_ptr e) { bool ok = Level::addEntity(e); forced.insert(e); - if (!ok) - { + if (!ok) { reEntries.insert(e); } return ok; } -void MultiPlayerLevel::removeEntity(std::shared_ptr e) -{ - // 4J Stu - Add this remove from the reEntries collection to stop us continually removing and re-adding things, - // in particular the MultiPlayerLocalPlayer when they die - AUTO_VAR(it, reEntries.find(e)); - if (it!=reEntries.end()) - { +void MultiPlayerLevel::removeEntity(std::shared_ptr e) { + // 4J Stu - Add this remove from the reEntries collection to stop us + // continually removing and re-adding things, in particular the + // MultiPlayerLocalPlayer when they die + AUTO_VAR(it, reEntries.find(e)); + if (it != reEntries.end()) { reEntries.erase(it); } @@ -430,486 +431,457 @@ void MultiPlayerLevel::removeEntity(std::shared_ptr e) forced.erase(e); } -void MultiPlayerLevel::entityAdded(std::shared_ptr e) -{ +void MultiPlayerLevel::entityAdded(std::shared_ptr e) { Level::entityAdded(e); - AUTO_VAR(it, reEntries.find(e)); - if (it!=reEntries.end()) - { + AUTO_VAR(it, reEntries.find(e)); + if (it != reEntries.end()) { reEntries.erase(it); } } -void MultiPlayerLevel::entityRemoved(std::shared_ptr e) -{ +void MultiPlayerLevel::entityRemoved(std::shared_ptr e) { Level::entityRemoved(e); - AUTO_VAR(it, forced.find(e)); - if (it!=forced.end()) - { + AUTO_VAR(it, forced.find(e)); + if (it != forced.end()) { reEntries.insert(e); } } -void MultiPlayerLevel::putEntity(int id, std::shared_ptr e) -{ +void MultiPlayerLevel::putEntity(int id, std::shared_ptr e) { std::shared_ptr old = getEntity(id); - if (old != NULL) - { + if (old != NULL) { removeEntity(old); } forced.insert(e); e->entityId = id; - if (!addEntity(e)) - { + if (!addEntity(e)) { this->reEntries.insert(e); } entitiesById[id] = e; } -std::shared_ptr MultiPlayerLevel::getEntity(int id) -{ - AUTO_VAR(it, entitiesById.find(id)); - if( it == entitiesById.end() ) return nullptr; - return it->second; +std::shared_ptr MultiPlayerLevel::getEntity(int id) { + AUTO_VAR(it, entitiesById.find(id)); + if (it == entitiesById.end()) return nullptr; + return it->second; } -std::shared_ptr MultiPlayerLevel::removeEntity(int id) -{ - std::shared_ptr e; - AUTO_VAR(it, entitiesById.find(id)); - if( it != entitiesById.end() ) - { - e = it->second; - entitiesById.erase(it); - forced.erase(e); - removeEntity(e); - } - else - { - } +std::shared_ptr MultiPlayerLevel::removeEntity(int id) { + std::shared_ptr e; + AUTO_VAR(it, entitiesById.find(id)); + if (it != entitiesById.end()) { + e = it->second; + entitiesById.erase(it); + forced.erase(e); + removeEntity(e); + } else { + } return e; } // 4J Added to remove the entities from the forced list -// This gets called when a chunk is unloaded, but we only do half an unload to remove entities slightly differently -void MultiPlayerLevel::removeEntities(std::vector > *list) -{ - for(AUTO_VAR(it, list->begin()); it < list->end(); ++it) - { - std::shared_ptr e = *it; +// This gets called when a chunk is unloaded, but we only do half an unload to +// remove entities slightly differently +void MultiPlayerLevel::removeEntities( + std::vector >* list) { + for (AUTO_VAR(it, list->begin()); it < list->end(); ++it) { + std::shared_ptr e = *it; - AUTO_VAR(reIt, reEntries.find(e)); - if (reIt!=reEntries.end()) - { - reEntries.erase(reIt); - } + AUTO_VAR(reIt, reEntries.find(e)); + if (reIt != reEntries.end()) { + reEntries.erase(reIt); + } - forced.erase(e); - } - Level::removeEntities(list); + forced.erase(e); + } + Level::removeEntities(list); } -bool MultiPlayerLevel::setDataNoUpdate(int x, int y, int z, int data) -{ +bool MultiPlayerLevel::setDataNoUpdate(int x, int y, int z, int data) { int t = getTile(x, y, z); int d = getData(x, y, z); - // 4J - added - if this is the host, then stop sharing block data with the server at this point - unshareChunkAt(x,z); + // 4J - added - if this is the host, then stop sharing block data with the + // server at this point + unshareChunkAt(x, z); - if (Level::setDataNoUpdate(x, y, z, data)) - { - //if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, t, d)); + if (Level::setDataNoUpdate(x, y, z, data)) { + // if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, + // t, d)); return true; } - // Didn't actually need to stop sharing - shareChunkAt(x,z); + // Didn't actually need to stop sharing + shareChunkAt(x, z); return false; } -bool MultiPlayerLevel::setTileAndDataNoUpdate(int x, int y, int z, int tile, int data) -{ - // First check if this isn't going to do anything, because if it isn't then the next stage (of unsharing data) is really quite - // expensive so far better to early out here +bool MultiPlayerLevel::setTileAndDataNoUpdate(int x, int y, int z, int tile, + int data) { + // First check if this isn't going to do anything, because if it isn't then + // the next stage (of unsharing data) is really quite expensive so far + // better to early out here int t = getTile(x, y, z); int d = getData(x, y, z); - if( ( t == tile ) && ( d == data ) ) - { - // If we early-out, its important that we still do a checkLight here (which would otherwise have happened as part of Level::setTileAndDataNoUpdate) - // This is because since we are potentially sharing tile/data but not lighting data, it is possible that the server might tell a client - // of a lighting update that doesn't need actioned on the client just because the chunk's data was being shared with the server when it was set. However, - // the lighting data will potentially now be out of sync on the client. - checkLight(x,y,z); - return false; - } - // 4J - added - if this is the host, then stop sharing block data with the server at this point - unshareChunkAt(x,z); + if ((t == tile) && (d == data)) { + // If we early-out, its important that we still do a checkLight here + // (which would otherwise have happened as part of + // Level::setTileAndDataNoUpdate) This is because since we are + // potentially sharing tile/data but not lighting data, it is possible + // that the server might tell a client of a lighting update that doesn't + // need actioned on the client just because the chunk's data was being + // shared with the server when it was set. However, the lighting data + // will potentially now be out of sync on the client. + checkLight(x, y, z); + return false; + } + // 4J - added - if this is the host, then stop sharing block data with the + // server at this point + unshareChunkAt(x, z); - if (Level::setTileAndDataNoUpdate(x, y, z, tile, data)) - { - //if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, t, d)); + if (Level::setTileAndDataNoUpdate(x, y, z, tile, data)) { + // if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, + // t, d)); return true; } - // Didn't actually need to stop sharing - shareChunkAt(x,z); + // Didn't actually need to stop sharing + shareChunkAt(x, z); return false; } -bool MultiPlayerLevel::setTileNoUpdate(int x, int y, int z, int tile) -{ +bool MultiPlayerLevel::setTileNoUpdate(int x, int y, int z, int tile) { int t = getTile(x, y, z); int d = getData(x, y, z); - // 4J - added - if this is the host, then stop sharing block data with the server at this point - unshareChunkAt(x,z); + // 4J - added - if this is the host, then stop sharing block data with the + // server at this point + unshareChunkAt(x, z); - if (Level::setTileNoUpdate(x, y, z, tile)) - { - //if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, t, d)); + if (Level::setTileNoUpdate(x, y, z, tile)) { + // if(m_bEnableResetChanges) updatesToReset.push_back(ResetInfo(x, y, z, + // t, d)); return true; } - // Didn't actually need to stop sharing - shareChunkAt(x,z); + // Didn't actually need to stop sharing + shareChunkAt(x, z); return false; } -bool MultiPlayerLevel::doSetTileAndData(int x, int y, int z, int tile, int data) -{ +bool MultiPlayerLevel::doSetTileAndData(int x, int y, int z, int tile, + int data) { clearResetRegion(x, y, z, x, y, z); - // 4J - Don't bother setting this to dirty if it isn't going to visually change - we get a lot of - // water changing from static to dynamic for instance. Note that this is only called from a client connection, - // and so the thing being notified of any update through tileUpdated is the renderer - int prevTile = getTile(x, y, z); - bool visuallyImportant = (!( ( ( prevTile == Tile::water_Id ) && ( tile == Tile::calmWater_Id ) ) || - ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || - ( ( prevTile == Tile::lava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::lava_Id ) ) ) ); - // If we're the host, need to tell the renderer for updates even if they don't change things as the host - // might have been sharing data and so set it already, but the renderer won't know to update - if( (Level::setTileAndData(x, y, z, tile, data) || g_NetworkManager.IsHost() ) ) - { - if( g_NetworkManager.IsHost() && visuallyImportant ) - { - // 4J Stu - This got removed from the tileUpdated function in TU14. Adding it back here as we need it - // to handle the cases where the chunk data is shared so the normal paths never call this - sendTileUpdated(x,y,z); + // 4J - Don't bother setting this to dirty if it isn't going to visually + // change - we get a lot of water changing from static to dynamic for + // instance. Note that this is only called from a client connection, and so + // the thing being notified of any update through tileUpdated is the + // renderer + int prevTile = getTile(x, y, z); + bool visuallyImportant = + (!(((prevTile == Tile::water_Id) && (tile == Tile::calmWater_Id)) || + ((prevTile == Tile::calmWater_Id) && (tile == Tile::water_Id)) || + ((prevTile == Tile::lava_Id) && (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && (tile == Tile::lava_Id)))); + // If we're the host, need to tell the renderer for updates even if they + // don't change things as the host might have been sharing data and so set + // it already, but the renderer won't know to update + if ((Level::setTileAndData(x, y, z, tile, data) || + g_NetworkManager.IsHost())) { + if (g_NetworkManager.IsHost() && visuallyImportant) { + // 4J Stu - This got removed from the tileUpdated function in TU14. + // Adding it back here as we need it to handle the cases where the + // chunk data is shared so the normal paths never call this + sendTileUpdated(x, y, z); - tileUpdated(x, y, z, tile); - } + tileUpdated(x, y, z, tile); + } return true; } - return false; + return false; } -void MultiPlayerLevel::disconnect(bool sendDisconnect /*= true*/) -{ - if( sendDisconnect ) - { - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->sendAndDisconnect( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); - } - } - else - { - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->close(); - } - } +void MultiPlayerLevel::disconnect(bool sendDisconnect /*= true*/) { + if (sendDisconnect) { + for (AUTO_VAR(it, connections.begin()); it < connections.end(); ++it) { + (*it)->sendAndDisconnect(std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting))); + } + } else { + for (AUTO_VAR(it, connections.begin()); it < connections.end(); ++it) { + (*it)->close(); + } + } } -void MultiPlayerLevel::tickWeather() -{ +void MultiPlayerLevel::tickWeather() { if (dimension->hasCeiling) return; - if (lightningTime > 0) - { + if (lightningTime > 0) { lightningTime--; } oRainLevel = rainLevel; - if (levelData->isRaining()) - { + if (levelData->isRaining()) { rainLevel += 0.01; - } - else - { + } else { rainLevel -= 0.01; } if (rainLevel < 0) rainLevel = 0; if (rainLevel > 1) rainLevel = 1; oThunderLevel = thunderLevel; - if (levelData->isThundering()) - { + if (levelData->isThundering()) { thunderLevel += 0.01; - } - else - { + } else { thunderLevel -= 0.01; } if (thunderLevel < 0) thunderLevel = 0; if (thunderLevel > 1) thunderLevel = 1; - } -void MultiPlayerLevel::animateTick(int xt, int yt, int zt) -{ - // Get 8x8x8 chunk (ie not like the renderer or game chunks... maybe we need another word here...) that the player is in - // We then want to add a 3x3 region of chunks into a set that we'll be ticking over. Set is stored as unsigned ints which encode - // this chunk position - int cx = xt >> 3; - int cy = yt >> 3; - int cz = zt >> 3; +void MultiPlayerLevel::animateTick(int xt, int yt, int zt) { + // Get 8x8x8 chunk (ie not like the renderer or game chunks... maybe we need + // another word here...) that the player is in We then want to add a 3x3 + // region of chunks into a set that we'll be ticking over. Set is stored as + // unsigned ints which encode this chunk position + int cx = xt >> 3; + int cy = yt >> 3; + int cz = zt >> 3; - for( int xx = -1; xx <= 1; xx++ ) - for( int yy = -1; yy <= 1; yy++ ) - for( int zz = -1; zz <= 1; zz++ ) - { - if( ( cy + yy ) < 0 ) continue; - if( ( cy + yy ) > 15 ) continue; - // Note - LEVEL_MAX_WIDTH is in game (16) tile chunks, and so our level goes from -LEVEL_MAX_WIDTH to LEVEL_MAX_WIDTH of our half-sized chunks - if( ( cx + xx ) >= LEVEL_MAX_WIDTH ) continue; - if( ( cx + xx ) < -LEVEL_MAX_WIDTH ) continue; - if( ( cz + zz ) >= LEVEL_MAX_WIDTH ) continue; - if( ( cz + zz ) < -LEVEL_MAX_WIDTH ) continue; - chunksToAnimate.insert( ( ( ( cx + xx ) & 0xff ) << 16 ) | ( ( ( cy + yy ) & 0xff ) << 8 ) | ( ( ( cz + zz ) & 0xff ) ) ); - } -} - -// 4J - the game used to tick 1000 tiles in a random region +/- 16 units round the player. We've got a 3x3 region of 8x8x8 chunks round each -// player. So the original game was ticking 1000 things in a 32x32x32 region ie had about a 1 in 32 chance of updating any one tile per tick. -// We're not dealing with quite such a big region round each player (24x24x24) but potentially we've got 4 players. Ultimately, we could end -// up ticking anywhere between 432 and 1728 tiles depending on how many players we've got, which seems like a good tradeoff from the original. -void MultiPlayerLevel::animateTickDoWork() -{ - const int ticksPerChunk = 16; // This ought to give us roughly the same 1000/32768 chance of a tile being animated as the original - - // Horrible hack to communicate with the level renderer, which is just attached as a listener to this level. This let's the particle - // rendering know to use this level (rather than try to work it out from the current player), and to not bother distance clipping particles - // which would again be based on the current player. - Minecraft::GetInstance()->animateTickLevel = this; - - MemSect(31); - Random *animateRandom = new Random(); - MemSect(0); - - for( int i = 0; i < ticksPerChunk; i++ ) - { - for( AUTO_VAR(it, chunksToAnimate.begin()); it != chunksToAnimate.end(); it++ ) - { - int packed = *it; - // 4jcraft changed the extraction logic to be safe - // constantly shifting a signed integer - int cx = (int8_t)(packed >> 16) * 8; - int cy = (int8_t)(packed >> 8) * 8; - int cz = (int8_t)packed * 8; - - int x = cx + random->nextInt(8); - int y = cy + random->nextInt(8); - int z = cz + random->nextInt(8); - int t = getTile(x, y, z); - if (random->nextInt(8) > y && t == 0 && dimension->hasBedrockFog()) // 4J - test for bedrock fog brought forward from 1.2.3 - { - addParticle(eParticleType_depthsuspend, x + random->nextFloat(), y + random->nextFloat(), z + random->nextFloat(), 0, 0, 0); + for (int xx = -1; xx <= 1; xx++) + for (int yy = -1; yy <= 1; yy++) + for (int zz = -1; zz <= 1; zz++) { + if ((cy + yy) < 0) continue; + if ((cy + yy) > 15) continue; + // Note - LEVEL_MAX_WIDTH is in game (16) tile chunks, and so + // our level goes from -LEVEL_MAX_WIDTH to LEVEL_MAX_WIDTH of + // our half-sized chunks + if ((cx + xx) >= LEVEL_MAX_WIDTH) continue; + if ((cx + xx) < -LEVEL_MAX_WIDTH) continue; + if ((cz + zz) >= LEVEL_MAX_WIDTH) continue; + if ((cz + zz) < -LEVEL_MAX_WIDTH) continue; + chunksToAnimate.insert((((cx + xx) & 0xff) << 16) | + (((cy + yy) & 0xff) << 8) | + (((cz + zz) & 0xff))); } - else if (t > 0) - { - Tile::tiles[t]->animateTick(this, x, y, z, animateRandom); - } - } - } - - Minecraft::GetInstance()->animateTickLevel = NULL; - delete animateRandom; - - chunksToAnimate.clear(); - } -void MultiPlayerLevel::playSound(std::shared_ptr entity, int iSound, float volume, float pitch) -{ - playLocalSound(entity->x, entity->y - entity->heightOffset, entity->z, iSound, volume, pitch); -} +// 4J - the game used to tick 1000 tiles in a random region +/- 16 units round +// the player. We've got a 3x3 region of 8x8x8 chunks round each player. So the +// original game was ticking 1000 things in a 32x32x32 region ie had about a 1 +// in 32 chance of updating any one tile per tick. We're not dealing with quite +// such a big region round each player (24x24x24) but potentially we've got 4 +// players. Ultimately, we could end up ticking anywhere between 432 and 1728 +// tiles depending on how many players we've got, which seems like a good +// tradeoff from the original. +void MultiPlayerLevel::animateTickDoWork() { + const int ticksPerChunk = + 16; // This ought to give us roughly the same 1000/32768 chance of a + // tile being animated as the original -void MultiPlayerLevel::playLocalSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist) -{ - //float dd = 16; - if (volume > 1) fClipSoundDist *= volume; + // Horrible hack to communicate with the level renderer, which is just + // attached as a listener to this level. This let's the particle rendering + // know to use this level (rather than try to work it out from the current + // player), and to not bother distance clipping particles which would again + // be based on the current player. + Minecraft::GetInstance()->animateTickLevel = this; - // 4J - find min distance to any players rather than just the current one - float minDistSq = FLT_MAX; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - float distSq = minecraft->localplayers[i]->distanceToSqr(x, y, z ); - if( distSq < minDistSq ) - { - minDistSq = distSq; - } - } - } + MemSect(31); + Random* animateRandom = new Random(); + MemSect(0); - if (minDistSq < fClipSoundDist * fClipSoundDist) - { - minecraft->soundEngine->play(iSound, (float) x, (float) y, (float) z, volume, pitch); - } -} + for (int i = 0; i < ticksPerChunk; i++) { + for (AUTO_VAR(it, chunksToAnimate.begin()); it != chunksToAnimate.end(); + it++) { + int packed = *it; + // 4jcraft changed the extraction logic to be safe + // constantly shifting a signed integer + int cx = (int8_t)(packed >> 16) * 8; + int cy = (int8_t)(packed >> 8) * 8; + int cz = (int8_t)packed * 8; -void MultiPlayerLevel::removeAllPendingEntityRemovals() -{ - //entities.removeAll(entitiesToRemove); - - EnterCriticalSection(&m_entitiesCS); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); ) - { - bool found = false; - for( AUTO_VAR(it2, entitiesToRemove.begin()); it2 != entitiesToRemove.end(); it2++ ) - { - if( (*it) == (*it2) ) - { - found = true; - break; - } - } - if( found ) - { - it = entities.erase(it); - } - else - { - it++; - } - } - LeaveCriticalSection(&m_entitiesCS); - - AUTO_VAR(endIt, entitiesToRemove.end()); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) - { - std::shared_ptr e = *it; - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) - { - getChunk(xc, zc)->removeEntity(e); - } - } - - // 4J Stu - Is there a reason do this in a separate loop? Thats what the Java does... - endIt = entitiesToRemove.end(); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) - { - entityRemoved(*it); - } - entitiesToRemove.clear(); - - //for (int i = 0; i < entities.size(); i++) - EnterCriticalSection(&m_entitiesCS); - std::vector >::iterator it = entities.begin(); - while( it != entities.end() ) - { - std::shared_ptr e = *it;//entities.at(i); - - if (e->riding != NULL) - { - if (e->riding->removed || e->riding->rider.lock() != e) - { - e->riding->rider = std::weak_ptr(); - e->riding = nullptr; - } - else - { - ++it; - continue; - } - } - - if (e->removed) - { - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) - { - getChunk(xc, zc)->removeEntity(e); - } - //entities.remove(i--); - - it = entities.erase( it ); - entityRemoved(e); - } - else - { - it++; - } - } - LeaveCriticalSection(&m_entitiesCS); -} - -void MultiPlayerLevel::removeClientConnection(ClientConnection *c, bool sendDisconnect) -{ - if( sendDisconnect ) - { - c->sendAndDisconnect( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); - } - - AUTO_VAR(it, find( connections.begin(), connections.end(), c )); - if( it != connections.end() ) - { - connections.erase( it ); - } -} - -void MultiPlayerLevel::tickAllConnections() -{ - PIXBeginNamedEvent(0,"Connection ticking"); - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->tick(); - } - PIXEndNamedEvent(); -} - -void MultiPlayerLevel::dataReceivedForChunk(int x, int z) -{ - chunkCache->dataReceived(x, z); -} - -// 4J added - removes all tile entities in the given region from both level & levelchunks -void MultiPlayerLevel::removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1) -{ - EnterCriticalSection(&m_tileEntityListCS); - - for (unsigned int i = 0; i < tileEntityList.size();) - { - bool removed = false; - std::shared_ptr te = tileEntityList[i]; - if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && te->y < y1 && te->z < z1) - { - LevelChunk *lc = getChunk(te->x >> 4, te->z >> 4); - if (lc != NULL) - { - // Only remove tile entities where this is no longer a tile entity - int tileId = lc->getTile(te->x & 15, te->y, te->z & 15 ); - if( Tile::tiles[tileId] == NULL || !Tile::tiles[tileId]->isEntityTile()) - { - tileEntityList[i] = tileEntityList.back(); - tileEntityList.pop_back(); - - // 4J Stu - Chests can create new tile entities when being removed, so disable this - m_bDisableAddNewTileEntities = true; - lc->removeTileEntity(te->x & 15, te->y, te->z & 15); - m_bDisableAddNewTileEntities = false; - removed = true; - } - } + int x = cx + random->nextInt(8); + int y = cy + random->nextInt(8); + int z = cz + random->nextInt(8); + int t = getTile(x, y, z); + if (random->nextInt(8) > y && t == 0 && + dimension->hasBedrockFog()) // 4J - test for bedrock fog + // brought forward from 1.2.3 + { + addParticle(eParticleType_depthsuspend, x + random->nextFloat(), + y + random->nextFloat(), z + random->nextFloat(), 0, + 0, 0); + } else if (t > 0) { + Tile::tiles[t]->animateTick(this, x, y, z, animateRandom); + } } - if( !removed ) i++; } - LeaveCriticalSection(&m_tileEntityListCS); + Minecraft::GetInstance()->animateTickLevel = NULL; + delete animateRandom; + + chunksToAnimate.clear(); } +void MultiPlayerLevel::playSound(std::shared_ptr entity, int iSound, + float volume, float pitch) { + playLocalSound(entity->x, entity->y - entity->heightOffset, entity->z, + iSound, volume, pitch); +} + +void MultiPlayerLevel::playLocalSound(double x, double y, double z, int iSound, + float volume, float pitch, + float fClipSoundDist) { + // float dd = 16; + if (volume > 1) fClipSoundDist *= volume; + + // 4J - find min distance to any players rather than just the current one + float minDistSq = FLT_MAX; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + float distSq = minecraft->localplayers[i]->distanceToSqr(x, y, z); + if (distSq < minDistSq) { + minDistSq = distSq; + } + } + } + + if (minDistSq < fClipSoundDist * fClipSoundDist) { + minecraft->soundEngine->play(iSound, (float)x, (float)y, (float)z, + volume, pitch); + } +} + +void MultiPlayerLevel::removeAllPendingEntityRemovals() { + // entities.removeAll(entitiesToRemove); + + EnterCriticalSection(&m_entitiesCS); + for (AUTO_VAR(it, entities.begin()); it != entities.end();) { + bool found = false; + for (AUTO_VAR(it2, entitiesToRemove.begin()); + it2 != entitiesToRemove.end(); it2++) { + if ((*it) == (*it2)) { + found = true; + break; + } + } + if (found) { + it = entities.erase(it); + } else { + it++; + } + } + LeaveCriticalSection(&m_entitiesCS); + + AUTO_VAR(endIt, entitiesToRemove.end()); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) { + std::shared_ptr e = *it; + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) { + getChunk(xc, zc)->removeEntity(e); + } + } + + // 4J Stu - Is there a reason do this in a separate loop? Thats what the + // Java does... + endIt = entitiesToRemove.end(); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) { + entityRemoved(*it); + } + entitiesToRemove.clear(); + + // for (int i = 0; i < entities.size(); i++) + EnterCriticalSection(&m_entitiesCS); + std::vector >::iterator it = entities.begin(); + while (it != entities.end()) { + std::shared_ptr e = *it; // entities.at(i); + + if (e->riding != NULL) { + if (e->riding->removed || e->riding->rider.lock() != e) { + e->riding->rider = std::weak_ptr(); + e->riding = nullptr; + } else { + ++it; + continue; + } + } + + if (e->removed) { + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) { + getChunk(xc, zc)->removeEntity(e); + } + // entities.remove(i--); + + it = entities.erase(it); + entityRemoved(e); + } else { + it++; + } + } + LeaveCriticalSection(&m_entitiesCS); +} + +void MultiPlayerLevel::removeClientConnection(ClientConnection* c, + bool sendDisconnect) { + if (sendDisconnect) { + c->sendAndDisconnect(std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting))); + } + + AUTO_VAR(it, find(connections.begin(), connections.end(), c)); + if (it != connections.end()) { + connections.erase(it); + } +} + +void MultiPlayerLevel::tickAllConnections() { + PIXBeginNamedEvent(0, "Connection ticking"); + for (AUTO_VAR(it, connections.begin()); it < connections.end(); ++it) { + (*it)->tick(); + } + PIXEndNamedEvent(); +} + +void MultiPlayerLevel::dataReceivedForChunk(int x, int z) { + chunkCache->dataReceived(x, z); +} + +// 4J added - removes all tile entities in the given region from both level & +// levelchunks +void MultiPlayerLevel::removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, + int x1, int y1, + int z1) { + EnterCriticalSection(&m_tileEntityListCS); + + for (unsigned int i = 0; i < tileEntityList.size();) { + bool removed = false; + std::shared_ptr te = tileEntityList[i]; + if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && + te->y < y1 && te->z < z1) { + LevelChunk* lc = getChunk(te->x >> 4, te->z >> 4); + if (lc != NULL) { + // Only remove tile entities where this is no longer a tile + // entity + int tileId = lc->getTile(te->x & 15, te->y, te->z & 15); + if (Tile::tiles[tileId] == NULL || + !Tile::tiles[tileId]->isEntityTile()) { + tileEntityList[i] = tileEntityList.back(); + tileEntityList.pop_back(); + + // 4J Stu - Chests can create new tile entities when being + // removed, so disable this + m_bDisableAddNewTileEntities = true; + lc->removeTileEntity(te->x & 15, te->y, te->z & 15); + m_bDisableAddNewTileEntities = false; + removed = true; + } + } + } + if (!removed) i++; + } + + LeaveCriticalSection(&m_tileEntityListCS); +} diff --git a/Minecraft.Client/Level/MultiPlayerLevel.h b/Minecraft.Client/Level/MultiPlayerLevel.h index ac6ed0812..0a02089d6 100644 --- a/Minecraft.Client/Level/MultiPlayerLevel.h +++ b/Minecraft.Client/Level/MultiPlayerLevel.h @@ -8,95 +8,111 @@ class ClientConnection; class MultiPlayerChunkCache; - - -class MultiPlayerLevel : public Level -{ +class MultiPlayerLevel : public Level { private: - static const int TICKS_BEFORE_RESET = 20 * 4; + static const int TICKS_BEFORE_RESET = 20 * 4; - class ResetInfo - { - public: + class ResetInfo { + public: int x, y, z, ticks, tile, data; ResetInfo(int x, int y, int z, int tile, int data); }; - std::vector updatesToReset; // 4J - was linked list but vector seems more appropriate - bool m_bEnableResetChanges; // 4J Added + std::vector updatesToReset; // 4J - was linked list but vector + // seems more appropriate + bool m_bEnableResetChanges; // 4J Added public: - void unshareChunkAt(int x, int z); // 4J - added - void shareChunkAt(int x, int z); // 4J - added + void unshareChunkAt(int x, int z); // 4J - added + void shareChunkAt(int x, int z); // 4J - added - void enableResetChanges(bool enable) { m_bEnableResetChanges = enable; } // 4J Added + void enableResetChanges(bool enable) { + m_bEnableResetChanges = enable; + } // 4J Added private: - int unshareCheckX; // 4J - added - int unshareCheckZ; // 4J - added - int compressCheckX; // 4J - added - int compressCheckZ; // 4J - added - std::vector connections; // 4J Stu - Made this a vector as we can have more than one local connection - MultiPlayerChunkCache *chunkCache; - Minecraft *minecraft; + int unshareCheckX; // 4J - added + int unshareCheckZ; // 4J - added + int compressCheckX; // 4J - added + int compressCheckZ; // 4J - added + std::vector + connections; // 4J Stu - Made this a vector as we can have more than + // one local connection + MultiPlayerChunkCache* chunkCache; + Minecraft* minecraft; public: - MultiPlayerLevel(ClientConnection *connection, LevelSettings *levelSettings, int dimension, int difficulty); - virtual ~MultiPlayerLevel(); - virtual void tick() ; + MultiPlayerLevel(ClientConnection* connection, LevelSettings* levelSettings, + int dimension, int difficulty); + virtual ~MultiPlayerLevel(); + virtual void tick(); + + void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1); - void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1); protected: - ChunkSource *createChunkSource(); // 4J - was virtual, but was called from parent ctor + ChunkSource* + createChunkSource(); // 4J - was virtual, but was called from parent ctor public: - virtual void validateSpawn(); + virtual void validateSpawn(); + protected: - virtual void tickTiles(); + virtual void tickTiles(); + public: void setChunkVisible(int x, int z, bool visible); private: - std::unordered_map, IntKeyHash2, IntKeyEq> entitiesById; // 4J - was IntHashMap + std::unordered_map, IntKeyHash2, IntKeyEq> + entitiesById; // 4J - was IntHashMap std::unordered_set > forced; std::unordered_set > reEntries; public: - virtual bool addEntity(std::shared_ptr e); + virtual bool addEntity(std::shared_ptr e); virtual void removeEntity(std::shared_ptr e); + protected: - virtual void entityAdded(std::shared_ptr e); + virtual void entityAdded(std::shared_ptr e); virtual void entityRemoved(std::shared_ptr e); + public: - void putEntity(int id, std::shared_ptr e); + void putEntity(int id, std::shared_ptr e); std::shared_ptr getEntity(int id); std::shared_ptr removeEntity(int id); - virtual void removeEntities(std::vector > *list); // 4J Added override + virtual void removeEntities( + std::vector >* list); // 4J Added override virtual bool setDataNoUpdate(int x, int y, int z, int data); - virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data); + virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, + int data); virtual bool setTileNoUpdate(int x, int y, int z, int tile); bool doSetTileAndData(int x, int y, int z, int tile, int data); virtual void disconnect(bool sendDisconnect = true); - void animateTick(int xt, int yt, int zt); + void animateTick(int xt, int yt, int zt); + protected: - virtual void tickWeather(); - - static const int ANIMATE_TICK_MAX_PARTICLES = 500; + virtual void tickWeather(); + + static const int ANIMATE_TICK_MAX_PARTICLES = 500; public: - void animateTickDoWork(); // 4J added - std::unordered_set chunksToAnimate; // 4J added + void animateTickDoWork(); // 4J added + std::unordered_set chunksToAnimate; // 4J added public: - void removeAllPendingEntityRemovals(); + void removeAllPendingEntityRemovals(); - virtual void playSound(std::shared_ptr entity, int iSound, float volume, float pitch); + virtual void playSound(std::shared_ptr entity, int iSound, + float volume, float pitch); - virtual void playLocalSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist=16.0f); + virtual void playLocalSound(double x, double y, double z, int iSound, + float volume, float pitch, + float fClipSoundDist = 16.0f); - // 4J Stu - Added so we can have multiple local connections - void addClientConnection(ClientConnection *c) { connections.push_back( c ); } - void removeClientConnection(ClientConnection *c, bool sendDisconnect); + // 4J Stu - Added so we can have multiple local connections + void addClientConnection(ClientConnection* c) { connections.push_back(c); } + void removeClientConnection(ClientConnection* c, bool sendDisconnect); - void tickAllConnections(); + void tickAllConnections(); - void dataReceivedForChunk(int x, int z); // 4J added - void removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1); // 4J added + void dataReceivedForChunk(int x, int z); // 4J added + void removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1, + int y1, int z1); // 4J added }; diff --git a/Minecraft.Client/Level/ServerLevel.cpp b/Minecraft.Client/Level/ServerLevel.cpp index 9657a3511..422c30a9f 100644 --- a/Minecraft.Client/Level/ServerLevel.cpp +++ b/Minecraft.Client/Level/ServerLevel.cpp @@ -41,1427 +41,1401 @@ C4JThread* ServerLevel::m_updateThread = NULL; C4JThread::EventArray* ServerLevel::m_updateTrigger; CRITICAL_SECTION ServerLevel::m_updateCS[3]; -Level *ServerLevel::m_level[3]; -int ServerLevel::m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; -int ServerLevel::m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; -int ServerLevel::m_updateChunkCount[3]; -int ServerLevel::m_updateTileX[3][MAX_UPDATES]; -int ServerLevel::m_updateTileY[3][MAX_UPDATES]; -int ServerLevel::m_updateTileZ[3][MAX_UPDATES]; -int ServerLevel::m_updateTileCount[3]; -int ServerLevel::m_randValue[3]; +Level* ServerLevel::m_level[3]; +int ServerLevel::m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; +int ServerLevel::m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; +int ServerLevel::m_updateChunkCount[3]; +int ServerLevel::m_updateTileX[3][MAX_UPDATES]; +int ServerLevel::m_updateTileY[3][MAX_UPDATES]; +int ServerLevel::m_updateTileZ[3][MAX_UPDATES]; +int ServerLevel::m_updateTileCount[3]; +int ServerLevel::m_randValue[3]; -void ServerLevel::staticCtor() -{ - m_updateTrigger = new C4JThread::EventArray(3); - InitializeCriticalSection(&m_updateCS[0]); - InitializeCriticalSection(&m_updateCS[1]); - InitializeCriticalSection(&m_updateCS[2]); +void ServerLevel::staticCtor() { + m_updateTrigger = new C4JThread::EventArray(3); + InitializeCriticalSection(&m_updateCS[0]); + InitializeCriticalSection(&m_updateCS[1]); + InitializeCriticalSection(&m_updateCS[2]); - m_updateThread = new C4JThread(runUpdate, NULL, "Tile update"); - m_updateThread->SetProcessor(CPU_CORE_TILE_UPDATE); + m_updateThread = new C4JThread(runUpdate, NULL, "Tile update"); + m_updateThread->SetProcessor(CPU_CORE_TILE_UPDATE); #ifdef __ORBIS__ - m_updateThread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. + m_updateThread->SetPriority( + THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for + // Matching 2, and that priority of that + // seems to be always at default no + // matter what we set it to. Prioritise + // this below Matching 2. #endif - m_updateThread->Run(); + m_updateThread->Run(); - RANDOM_BONUS_ITEMS = WeighedTreasureArray(20); + RANDOM_BONUS_ITEMS = WeighedTreasureArray(20); - RANDOM_BONUS_ITEMS[0] = new WeighedTreasure(Item::stick_Id, 0, 1, 3, 10); + RANDOM_BONUS_ITEMS[0] = new WeighedTreasure(Item::stick_Id, 0, 1, 3, 10); RANDOM_BONUS_ITEMS[1] = new WeighedTreasure(Tile::wood_Id, 0, 1, 3, 10); - RANDOM_BONUS_ITEMS[2] = new WeighedTreasure(Tile::treeTrunk_Id, 0, 1, 3, 10); - RANDOM_BONUS_ITEMS[3] = new WeighedTreasure(Item::hatchet_stone_Id, 0, 1, 1, 3); - RANDOM_BONUS_ITEMS[4] = new WeighedTreasure(Item::hatchet_wood_Id, 0, 1, 1, 5); - RANDOM_BONUS_ITEMS[5] = new WeighedTreasure(Item::pickAxe_stone_Id, 0, 1, 1, 3); - RANDOM_BONUS_ITEMS[6] = new WeighedTreasure(Item::pickAxe_wood_Id, 0, 1, 1, 5); + RANDOM_BONUS_ITEMS[2] = + new WeighedTreasure(Tile::treeTrunk_Id, 0, 1, 3, 10); + RANDOM_BONUS_ITEMS[3] = + new WeighedTreasure(Item::hatchet_stone_Id, 0, 1, 1, 3); + RANDOM_BONUS_ITEMS[4] = + new WeighedTreasure(Item::hatchet_wood_Id, 0, 1, 1, 5); + RANDOM_BONUS_ITEMS[5] = + new WeighedTreasure(Item::pickAxe_stone_Id, 0, 1, 1, 3); + RANDOM_BONUS_ITEMS[6] = + new WeighedTreasure(Item::pickAxe_wood_Id, 0, 1, 1, 5); RANDOM_BONUS_ITEMS[7] = new WeighedTreasure(Item::apple_Id, 0, 2, 3, 5); RANDOM_BONUS_ITEMS[8] = new WeighedTreasure(Item::bread_Id, 0, 2, 3, 3); - // 4J-PB - new items - RANDOM_BONUS_ITEMS[9] = new WeighedTreasure(Tile::sapling_Id, 0, 4, 4, 2); - RANDOM_BONUS_ITEMS[10] = new WeighedTreasure(Tile::sapling_Id, 1, 4, 4, 2); - RANDOM_BONUS_ITEMS[11] = new WeighedTreasure(Tile::sapling_Id, 2, 4, 4, 2); - RANDOM_BONUS_ITEMS[12] = new WeighedTreasure(Tile::sapling_Id, 3, 4, 4, 4); - RANDOM_BONUS_ITEMS[13] = new WeighedTreasure(Item::seeds_melon_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[14] = new WeighedTreasure(Item::seeds_pumpkin_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[15] = new WeighedTreasure(Tile::cactus_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[16] = new WeighedTreasure(Item::dye_powder_Id, DyePowderItem::BROWN, 1, 2, 2); - RANDOM_BONUS_ITEMS[17] = new WeighedTreasure(Item::potato_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[18] = new WeighedTreasure(Item::carrots_Id, 0, 1, 2, 3); - RANDOM_BONUS_ITEMS[19] = new WeighedTreasure(Tile::mushroom1_Id, 0, 1, 2, 2); - + // 4J-PB - new items + RANDOM_BONUS_ITEMS[9] = new WeighedTreasure(Tile::sapling_Id, 0, 4, 4, 2); + RANDOM_BONUS_ITEMS[10] = new WeighedTreasure(Tile::sapling_Id, 1, 4, 4, 2); + RANDOM_BONUS_ITEMS[11] = new WeighedTreasure(Tile::sapling_Id, 2, 4, 4, 2); + RANDOM_BONUS_ITEMS[12] = new WeighedTreasure(Tile::sapling_Id, 3, 4, 4, 4); + RANDOM_BONUS_ITEMS[13] = + new WeighedTreasure(Item::seeds_melon_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[14] = + new WeighedTreasure(Item::seeds_pumpkin_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[15] = new WeighedTreasure(Tile::cactus_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[16] = + new WeighedTreasure(Item::dye_powder_Id, DyePowderItem::BROWN, 1, 2, 2); + RANDOM_BONUS_ITEMS[17] = new WeighedTreasure(Item::potato_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[18] = new WeighedTreasure(Item::carrots_Id, 0, 1, 2, 3); + RANDOM_BONUS_ITEMS[19] = + new WeighedTreasure(Tile::mushroom1_Id, 0, 1, 2, 2); }; -ServerLevel::ServerLevel(MinecraftServer *server, std::shared_ptrlevelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings) : Level(levelStorage, levelName, levelSettings, Dimension::getNew(dimension), false) -{ - InitializeCriticalSection(&m_limiterCS); - InitializeCriticalSection(&m_tickNextTickCS); - InitializeCriticalSection(&m_csQueueSendTileUpdates); - m_fallingTileCount = 0; - m_primedTntCount = 0; +ServerLevel::ServerLevel(MinecraftServer* server, + std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, + LevelSettings* levelSettings) + : Level(levelStorage, levelName, levelSettings, + Dimension::getNew(dimension), false) { + InitializeCriticalSection(&m_limiterCS); + InitializeCriticalSection(&m_tickNextTickCS); + InitializeCriticalSection(&m_csQueueSendTileUpdates); + m_fallingTileCount = 0; + m_primedTntCount = 0; - // 4J - this this used to be called in parent ctor via a virtual fn - chunkSource = createChunkSource(); - // 4J - optimisation - keep direct reference of underlying cache here - chunkSourceCache = chunkSource->getCache(); - chunkSourceXZSize = chunkSource->m_XZSize; + // 4J - this this used to be called in parent ctor via a virtual fn + chunkSource = createChunkSource(); + // 4J - optimisation - keep direct reference of underlying cache here + chunkSourceCache = chunkSource->getCache(); + chunkSourceXZSize = chunkSource->m_XZSize; - // 4J - The listener used to be added in MinecraftServer::loadLevel but we need it to be set up before we do the next couple of things, or else chunks get loaded before we have the entity tracker set up to listen to them - this->server = server; - server->setLevel(dimension, this); // The listener needs the server to have the level set up... this will be set up anyway on return of this ctor but setting up early here - addListener(new ServerLevelListener(server, this)); + // 4J - The listener used to be added in MinecraftServer::loadLevel but we + // need it to be set up before we do the next couple of things, or else + // chunks get loaded before we have the entity tracker set up to listen to + // them + this->server = server; + server->setLevel(dimension, + this); // The listener needs the server to have the level + // set up... this will be set up anyway on return + // of this ctor but setting up early here + addListener(new ServerLevelListener(server, this)); - this->tracker = new EntityTracker(this); - this->chunkMap = new PlayerChunkMap(this, dimension, server->getPlayers()->getViewDistance()); + this->tracker = new EntityTracker(this); + this->chunkMap = new PlayerChunkMap( + this, dimension, server->getPlayers()->getViewDistance()); - // This also used to be called in parent ctor, but can't be called until chunkSource is created. Call now if required. - if (!levelData->isInitialized()) - { - initializeLevel(levelSettings); - levelData->setInitialized(true); - } - else if ( (dimension==0) && levelData->getSpawnBonusChest() ) // 4J-JEV, still would like bonus chests to respawn. - { - // 4J - added isFindingSpawn as we want any chunks we are looking in here for suitable locations for the bonus chest to actually create those chunks rather than just get emptychunks if they aren't loaded - isFindingSpawn = true; - generateBonusItemsNearSpawn(); - isFindingSpawn = false; - } + // This also used to be called in parent ctor, but can't be called until + // chunkSource is created. Call now if required. + if (!levelData->isInitialized()) { + initializeLevel(levelSettings); + levelData->setInitialized(true); + } else if ((dimension == 0) && + levelData->getSpawnBonusChest()) // 4J-JEV, still would like + // bonus chests to respawn. + { + // 4J - added isFindingSpawn as we want any chunks we are looking in + // here for suitable locations for the bonus chest to actually create + // those chunks rather than just get emptychunks if they aren't loaded + isFindingSpawn = true; + generateBonusItemsNearSpawn(); + isFindingSpawn = false; + } - // 4J - added initialisers - // 4J Stu - Allowing spawn edit for our game, and consider a better solution for the possible griefing - canEditSpawn = true; //false; - noSave = false; - allPlayersSleeping = false; - m_bAtLeastOnePlayerSleeping = false; - emptyTime = 0; - activeTileEventsList = 0; + // 4J - added initialisers + // 4J Stu - Allowing spawn edit for our game, and consider a better solution + // for the possible griefing + canEditSpawn = true; // false; + noSave = false; + allPlayersSleeping = false; + m_bAtLeastOnePlayerSleeping = false; + emptyTime = 0; + activeTileEventsList = 0; #ifdef _LARGE_WORLDS - saveInterval = 3; + saveInterval = 3; #else - saveInterval = 20 * 2; + saveInterval = 20 * 2; #endif } -ServerLevel::~ServerLevel() -{ - EnterCriticalSection(&m_csQueueSendTileUpdates); - for(AUTO_VAR(it, m_queuedSendTileUpdates.begin()); it != m_queuedSendTileUpdates.end(); ++it) - { - Pos *p = *it; - delete p; - } - m_queuedSendTileUpdates.clear(); +ServerLevel::~ServerLevel() { + EnterCriticalSection(&m_csQueueSendTileUpdates); + for (AUTO_VAR(it, m_queuedSendTileUpdates.begin()); + it != m_queuedSendTileUpdates.end(); ++it) { + Pos* p = *it; + delete p; + } + m_queuedSendTileUpdates.clear(); - delete this->tracker; // MGH - added, we were losing about 500K going in and out the menus - delete this->chunkMap; + delete this->tracker; // MGH - added, we were losing about 500K going in + // and out the menus + delete this->chunkMap; - LeaveCriticalSection(&m_csQueueSendTileUpdates); - DeleteCriticalSection(&m_csQueueSendTileUpdates); - DeleteCriticalSection(&m_limiterCS); - DeleteCriticalSection(&m_tickNextTickCS); + LeaveCriticalSection(&m_csQueueSendTileUpdates); + DeleteCriticalSection(&m_csQueueSendTileUpdates); + DeleteCriticalSection(&m_limiterCS); + DeleteCriticalSection(&m_tickNextTickCS); - // Make sure that the update thread isn't actually doing any updating - EnterCriticalSection(&m_updateCS[0]); - LeaveCriticalSection(&m_updateCS[0]); - EnterCriticalSection(&m_updateCS[1]); - LeaveCriticalSection(&m_updateCS[1]); - EnterCriticalSection(&m_updateCS[2]); - LeaveCriticalSection(&m_updateCS[2]); - m_updateTrigger->ClearAll(); + // Make sure that the update thread isn't actually doing any updating + EnterCriticalSection(&m_updateCS[0]); + LeaveCriticalSection(&m_updateCS[0]); + EnterCriticalSection(&m_updateCS[1]); + LeaveCriticalSection(&m_updateCS[1]); + EnterCriticalSection(&m_updateCS[2]); + LeaveCriticalSection(&m_updateCS[2]); + m_updateTrigger->ClearAll(); } - -void ServerLevel::tick() -{ - Level::tick(); - if (getLevelData()->isHardcore() && difficulty < 3) - { +void ServerLevel::tick() { + Level::tick(); + if (getLevelData()->isHardcore() && difficulty < 3) { difficulty = 3; } - dimension->biomeSource->update(); + dimension->biomeSource->update(); - if (allPlayersAreSleeping()) - { - bool somebodyWokeUp = false; - if (spawnEnemies && difficulty >= Difficulty::EASY) - { - } + if (allPlayersAreSleeping()) { + bool somebodyWokeUp = false; + if (spawnEnemies && difficulty >= Difficulty::EASY) { + } - if (!somebodyWokeUp) - { - // skip time until new day - __int64 newTime = levelData->getTime() + TICKS_PER_DAY; + if (!somebodyWokeUp) { + // skip time until new day + __int64 newTime = levelData->getTime() + TICKS_PER_DAY; - // 4J : WESTY : Changed so that time update goes through stats tracking update code. - //levelData->setTime(newTime - (newTime % TICKS_PER_DAY)); - setTime(newTime - (newTime % TICKS_PER_DAY)); + // 4J : WESTY : Changed so that time update goes through stats + // tracking update code. + // levelData->setTime(newTime - (newTime % TICKS_PER_DAY)); + setTime(newTime - (newTime % TICKS_PER_DAY)); - awakenAllPlayers(); - } - } + awakenAllPlayers(); + } + } - PIXBeginNamedEvent(0,"Mob spawner tick"); - // for Minecraft 1.8, spawn friendlies really rarely - 4J - altered from once every 400 ticks to 40 ticks as we depend on this a more than the original since we don't have chunk post-process spawning - MobSpawner::tick(this, spawnEnemies, spawnFriendlies && (levelData->getTime() % 40) == 0); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Chunk source tick"); - chunkSource->tick(); - PIXEndNamedEvent(); - int newDark = this->getOldSkyDarken(1); - if (newDark != skyDarken) - { - skyDarken = newDark; - if (!SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward from 1.8.2 - { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - { - (*it)->skyColorChanged(); - } - } - } - - PIXBeginNamedEvent(0,"runTileEvents"); - // run after entity updates - runTileEvents(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Mob spawner tick"); + // for Minecraft 1.8, spawn friendlies really rarely - 4J - altered + // from once every 400 ticks to 40 ticks as we depend on this a more than + // the original since we don't have chunk post-process spawning + MobSpawner::tick(this, spawnEnemies, + spawnFriendlies && (levelData->getTime() % 40) == 0); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Chunk source tick"); + chunkSource->tick(); + PIXEndNamedEvent(); + int newDark = this->getOldSkyDarken(1); + if (newDark != skyDarken) { + skyDarken = newDark; + if (!SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward + // from 1.8.2 + { + AUTO_VAR(itEnd, listeners.end()); + for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) { + (*it)->skyColorChanged(); + } + } + } - //4J - temporarily disabling saves as they are causing gameplay to generally stutter quite a lot + PIXBeginNamedEvent(0, "runTileEvents"); + // run after entity updates + runTileEvents(); + PIXEndNamedEvent(); - __int64 time = levelData->getTime() + 1; -// 4J Stu - Putting this back in, but I have reduced the number of chunks that save when not forced + // 4J - temporarily disabling saves as they are causing gameplay to + // generally stutter quite a lot + + __int64 time = levelData->getTime() + 1; +// 4J Stu - Putting this back in, but I have reduced the number of chunks that +// save when not forced #ifdef _LARGE_WORLDS - if (time % (saveInterval) == (dimension->id + 1)) + if (time % (saveInterval) == (dimension->id + 1)) #else - if (time % (saveInterval) == (dimension->id * dimension->id * (saveInterval/2))) + if (time % (saveInterval) == + (dimension->id * dimension->id * (saveInterval / 2))) #endif - { - //app.DebugPrintf("Incremental save\n"); - PIXBeginNamedEvent(0,"Incremental save"); - save(false, NULL); - PIXEndNamedEvent(); - } + { + // app.DebugPrintf("Incremental save\n"); + PIXBeginNamedEvent(0, "Incremental save"); + save(false, NULL); + PIXEndNamedEvent(); + } - // 4J : WESTY : Changed so that time update goes through stats tracking update code. - //levelData->setTime(time); - setTime(time); + // 4J : WESTY : Changed so that time update goes through stats tracking + // update code. + // levelData->setTime(time); + setTime(time); - PIXBeginNamedEvent(0,"Tick pending ticks"); - // if (tickCount % 5 == 0) { - tickPendingTicks(false); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Tick pending ticks"); + // if (tickCount % 5 == 0) { + tickPendingTicks(false); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Tick tiles"); - MemSect(18); - tickTiles(); - MemSect(0); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Tick tiles"); + MemSect(18); + tickTiles(); + MemSect(0); + PIXEndNamedEvent(); - chunkMap->tick(); + chunkMap->tick(); - PIXBeginNamedEvent(0,"Tick villages"); - //MemSect(18); - villages->tick(); - villageSiege->tick(); - //MemSect(0); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Tick villages"); + // MemSect(18); + villages->tick(); + villageSiege->tick(); + // MemSect(0); + PIXEndNamedEvent(); - // repeat after tile ticks - runTileEvents(); + // repeat after tile ticks + runTileEvents(); - // 4J Added - runQueuedSendTileUpdates(); + // 4J Added + runQueuedSendTileUpdates(); } -Biome::MobSpawnerData *ServerLevel::getRandomMobSpawnAt(MobCategory *mobCategory, int x, int y, int z) -{ - std::vector *mobList = getChunkSource()->getMobsAt(mobCategory, x, y, z); - if (mobList == NULL || mobList->empty()) return NULL; +Biome::MobSpawnerData* ServerLevel::getRandomMobSpawnAt( + MobCategory* mobCategory, int x, int y, int z) { + std::vector* mobList = + getChunkSource()->getMobsAt(mobCategory, x, y, z); + if (mobList == NULL || mobList->empty()) return NULL; - return (Biome::MobSpawnerData *) WeighedRandom::getRandomItem(random, (std::vector *)mobList); + return (Biome::MobSpawnerData*)WeighedRandom::getRandomItem( + random, (std::vector*)mobList); } -void ServerLevel::updateSleepingPlayerList() -{ - allPlayersSleeping = !players.empty(); - m_bAtLeastOnePlayerSleeping = false; +void ServerLevel::updateSleepingPlayerList() { + allPlayersSleeping = !players.empty(); + m_bAtLeastOnePlayerSleeping = false; - AUTO_VAR(itEnd, players.end()); - for (std::vector >::iterator it = players.begin(); it != itEnd; it++) - { - if (!(*it)->isSleeping()) - { - allPlayersSleeping = false; - //break; - } - else - { - m_bAtLeastOnePlayerSleeping = true; - } - if(m_bAtLeastOnePlayerSleeping && !allPlayersSleeping) break; - } + AUTO_VAR(itEnd, players.end()); + for (std::vector >::iterator it = players.begin(); + it != itEnd; it++) { + if (!(*it)->isSleeping()) { + allPlayersSleeping = false; + // break; + } else { + m_bAtLeastOnePlayerSleeping = true; + } + if (m_bAtLeastOnePlayerSleeping && !allPlayersSleeping) break; + } } -void ServerLevel::awakenAllPlayers() -{ - allPlayersSleeping = false; - m_bAtLeastOnePlayerSleeping = false; +void ServerLevel::awakenAllPlayers() { + allPlayersSleeping = false; + m_bAtLeastOnePlayerSleeping = false; - AUTO_VAR(itEnd, players.end()); - for (std::vector >::iterator it = players.begin(); it != itEnd; it++) - { - if ((*it)->isSleeping()) - { - (*it)->stopSleepInBed(false, false, true); - } - } + AUTO_VAR(itEnd, players.end()); + for (std::vector >::iterator it = players.begin(); + it != itEnd; it++) { + if ((*it)->isSleeping()) { + (*it)->stopSleepInBed(false, false, true); + } + } - stopWeather(); + stopWeather(); } -void ServerLevel::stopWeather() -{ - levelData->setRainTime(0); - levelData->setRaining(false); - levelData->setThunderTime(0); - levelData->setThundering(false); +void ServerLevel::stopWeather() { + levelData->setRainTime(0); + levelData->setRaining(false); + levelData->setThunderTime(0); + levelData->setThundering(false); } -bool ServerLevel::allPlayersAreSleeping() -{ - if (allPlayersSleeping && !isClientSide) - { - // all players are sleeping, but have they slept long enough? - AUTO_VAR(itEnd, players.end()); - for (std::vector >::iterator it = players.begin(); it != itEnd; it++ ) - { - // System.out.println(player->entityId + ": " + player->getSleepTimer()); - if (! (*it)->isSleepingLongEnough()) - { - return false; - } - } - // yep - return true; - } - return false; +bool ServerLevel::allPlayersAreSleeping() { + if (allPlayersSleeping && !isClientSide) { + // all players are sleeping, but have they slept long enough? + AUTO_VAR(itEnd, players.end()); + for (std::vector >::iterator it = + players.begin(); + it != itEnd; it++) { + // System.out.println(player->entityId + ": " + + // player->getSleepTimer()); + if (!(*it)->isSleepingLongEnough()) { + return false; + } + } + // yep + return true; + } + return false; } -void ServerLevel::validateSpawn() -{ - if (levelData->getYSpawn() <= 0) - { - levelData->setYSpawn(genDepth / 2); - } - int xSpawn = levelData->getXSpawn(); - int zSpawn = levelData->getZSpawn(); - int tries = 0; - while (getTopTile(xSpawn, zSpawn) == 0) - { - xSpawn += random->nextInt(8) - random->nextInt(8); - zSpawn += random->nextInt(8) - random->nextInt(8); - if (++tries == 10000) break; - } - levelData->setXSpawn(xSpawn); - levelData->setZSpawn(zSpawn); +void ServerLevel::validateSpawn() { + if (levelData->getYSpawn() <= 0) { + levelData->setYSpawn(genDepth / 2); + } + int xSpawn = levelData->getXSpawn(); + int zSpawn = levelData->getZSpawn(); + int tries = 0; + while (getTopTile(xSpawn, zSpawn) == 0) { + xSpawn += random->nextInt(8) - random->nextInt(8); + zSpawn += random->nextInt(8) - random->nextInt(8); + if (++tries == 10000) break; + } + levelData->setXSpawn(xSpawn); + levelData->setZSpawn(zSpawn); } -// 4J - Changes made here to move a section of code (which randomly determines which tiles in the current chunks to tick, and is very cache unfriendly by nature) -// This code now has a thread of its own so it can wait all it wants on the cache without holding the main game thread up. This slightly changes how things are -// processed, as we now tick the tiles that were determined in the previous tick. Have also limited the amount of tiles to be ticked to 256 (it never seemed to creep -// up much beyond this in normal play anyway, and we need some finite limit). -void ServerLevel::tickTiles() -{ - // Index into the arrays used by the update thread - int iLev = 0; - if( dimension->id == -1 ) - { - iLev = 1; - } - else if( dimension->id == 1 ) - { - iLev = 2; - } - chunksToPoll.clear(); +// 4J - Changes made here to move a section of code (which randomly determines +// which tiles in the current chunks to tick, and is very cache unfriendly by +// nature) This code now has a thread of its own so it can wait all it wants on +// the cache without holding the main game thread up. This slightly changes how +// things are processed, as we now tick the tiles that were determined in the +// previous tick. Have also limited the amount of tiles to be ticked to 256 (it +// never seemed to creep up much beyond this in normal play anyway, and we need +// some finite limit). +void ServerLevel::tickTiles() { + // Index into the arrays used by the update thread + int iLev = 0; + if (dimension->id == -1) { + iLev = 1; + } else if (dimension->id == 1) { + iLev = 2; + } + chunksToPoll.clear(); - unsigned int tickCount = 0; + unsigned int tickCount = 0; - EnterCriticalSection(&m_updateCS[iLev]); - // This section processes the tiles that need to be ticked, which we worked out in the previous tick (or haven't yet, if this is the first frame) - /*int grassTicks = 0; - int lavaTicks = 0; - int otherTicks = 0;*/ - for( int i = 0; i < m_updateTileCount[iLev]; i++ ) - { - int x = m_updateTileX[iLev][i]; - int y = m_updateTileY[iLev][i]; - int z = m_updateTileZ[iLev][i]; - if( hasChunkAt(x,y,z) ) - { - int id = getTile(x,y,z); - if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking()) - { - /*if(id == 2) ++grassTicks; - else if(id == 11) ++lavaTicks; - else ++otherTicks;*/ - Tile::tiles[id]->tick(this, x, y, z, random); - } - } - } - //printf("Total ticks - Grass: %d, Lava: %d, Other: %d, Total: %d\n", grassTicks, lavaTicks, otherTicks, grassTicks + lavaTicks + otherTicks); - m_updateTileCount[iLev] = 0; - m_updateChunkCount[iLev] = 0; - LeaveCriticalSection(&m_updateCS[iLev]); + EnterCriticalSection(&m_updateCS[iLev]); + // This section processes the tiles that need to be ticked, which we worked + // out in the previous tick (or haven't yet, if this is the first frame) + /*int grassTicks = 0; + int lavaTicks = 0; + int otherTicks = 0;*/ + for (int i = 0; i < m_updateTileCount[iLev]; i++) { + int x = m_updateTileX[iLev][i]; + int y = m_updateTileY[iLev][i]; + int z = m_updateTileZ[iLev][i]; + if (hasChunkAt(x, y, z)) { + int id = getTile(x, y, z); + if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking()) { + /*if(id == 2) ++grassTicks; + else if(id == 11) ++lavaTicks; + else ++otherTicks;*/ + Tile::tiles[id]->tick(this, x, y, z, random); + } + } + } + // printf("Total ticks - Grass: %d, Lava: %d, Other: %d, Total: %d\n", + // grassTicks, lavaTicks, otherTicks, grassTicks + lavaTicks + otherTicks); + m_updateTileCount[iLev] = 0; + m_updateChunkCount[iLev] = 0; + LeaveCriticalSection(&m_updateCS[iLev]); - Level::tickTiles(); + Level::tickTiles(); - // AP moved this outside of the loop - int prob = 100000; - if(app.GetGameSettingsDebugMask()&(1L<hasChunk(cp.x, cp.z) ) continue; + // 4J added - don't let this actually load/create any chunks, we'll let + // the normal updateDirtyChunks etc. processes do that, so it can happen + // on another thread + if (!this->hasChunk(cp.x, cp.z)) continue; - // 4J Stu - When adding a 5th player to the game, the number of chunksToPoll is greater than the size of - // the m_updateChunkX & m_updateChunkZ arrays (19*19*4 at time of writing). It doesn't seem like there should - // ever be that many chunks needing polled, so this needs looked at in more detail. For now I have enlarged - // the size of the array to 19*19*8 but this seems way to big for our needs. + // 4J Stu - When adding a 5th player to the game, the number of + // chunksToPoll is greater than the size of the m_updateChunkX & + // m_updateChunkZ arrays (19*19*4 at time of writing). It doesn't seem + // like there should ever be that many chunks needing polled, so this + // needs looked at in more detail. For now I have enlarged the size of + // the array to 19*19*8 but this seems way to big for our needs. - // The cause of this is largely because the chunksToPoll vector does not enforce unique elements - // The java version used a HashSet which would, although if our world size gets a lot larger - // then we may have no overlaps of players surrounding chunks - //assert(false); + // The cause of this is largely because the chunksToPoll vector does not + // enforce unique elements The java version used a HashSet which would, + // although if our world size gets a lot larger then we may have no + // overlaps of players surrounding chunks + // assert(false); - // If you hit this assert, then a memory overwrite will occur when you continue - assert(m_updateChunkCount[iLev] < LEVEL_CHUNKS_TO_UPDATE_MAX); + // If you hit this assert, then a memory overwrite will occur when you + // continue + assert(m_updateChunkCount[iLev] < LEVEL_CHUNKS_TO_UPDATE_MAX); - m_updateChunkX[iLev][m_updateChunkCount[iLev]] = cp.x; - m_updateChunkZ[iLev][m_updateChunkCount[iLev]++] = cp.z; + m_updateChunkX[iLev][m_updateChunkCount[iLev]] = cp.x; + m_updateChunkZ[iLev][m_updateChunkCount[iLev]++] = cp.z; - LevelChunk *lc = this->getChunk(cp.x, cp.z); - tickClientSideTiles(xo, zo, lc); + LevelChunk* lc = this->getChunk(cp.x, cp.z); + tickClientSideTiles(xo, zo, lc); - if (random->nextInt(prob) == 0 && isRaining() && isThundering()) - { - randValue = randValue * 3 + addend; - int val = (randValue >> 2); - int x = xo + (val & 15); - int z = zo + ((val >> 8) & 15); - int y = getTopRainBlock(x, z); + if (random->nextInt(prob) == 0 && isRaining() && isThundering()) { + randValue = randValue * 3 + addend; + int val = (randValue >> 2); + int x = xo + (val & 15); + int z = zo + ((val >> 8) & 15); + int y = getTopRainBlock(x, z); - if (isRainingAt(x, y, z)) - { - addGlobalEntity( std::shared_ptr( new LightningBolt(this, x, y, z) ) ); - lightningTime = 2; - } - } + if (isRainingAt(x, y, z)) { + addGlobalEntity(std::shared_ptr( + new LightningBolt(this, x, y, z))); + lightningTime = 2; + } + } - // 4J - changes here brought forrward from 1.2.3 - if (random->nextInt(16) == 0) - { - //4jcraft added cast to unsigned + // 4J - changes here brought forrward from 1.2.3 + if (random->nextInt(16) == 0) { + // 4jcraft added cast to unsigned randValue = (unsigned)randValue * 3 + (unsigned)addend; int val = (randValue >> 2); int x = (val & 15); int z = ((val >> 8) & 15); int yy = this->getTopRainBlock(x + xo, z + zo); - if (shouldFreeze(x + xo, yy - 1, z + zo)) - { + if (shouldFreeze(x + xo, yy - 1, z + zo)) { setTile(x + xo, yy - 1, z + zo, Tile::ice_Id); } - if (isRaining() && shouldSnow(x + xo, yy, z + zo)) - { + if (isRaining() && shouldSnow(x + xo, yy, z + zo)) { setTile(x + xo, yy, z + zo, Tile::topSnow_Id); - } - if (isRaining()) - { - Biome *b = getBiome(x + xo, z + zo); - if (b->hasRain()) - { - int tile = getTile(x + xo, yy - 1, z + zo); - if (tile != 0) - { - Tile::tiles[tile]->handleRain(this, x + xo, yy - 1, z + zo); - } - } - } - } + } + if (isRaining()) { + Biome* b = getBiome(x + xo, z + zo); + if (b->hasRain()) { + int tile = getTile(x + xo, yy - 1, z + zo); + if (tile != 0) { + Tile::tiles[tile]->handleRain(this, x + xo, yy - 1, + z + zo); + } + } + } + } - // 4J - lighting change brought forward from 1.8.2 - checkLight(xo + random->nextInt(16), random->nextInt(128), zo + random->nextInt(16)); - } + // 4J - lighting change brought forward from 1.8.2 + checkLight(xo + random->nextInt(16), random->nextInt(128), + zo + random->nextInt(16)); + } - m_level[iLev] = this; - m_randValue[iLev] = randValue; - // We've set up everything that the udpate thread needs, so kick it off - m_updateTrigger->Set(iLev); + m_level[iLev] = this; + m_randValue[iLev] = randValue; + // We've set up everything that the udpate thread needs, so kick it off + m_updateTrigger->Set(iLev); } -void ServerLevel::addToTickNextTick(int x, int y, int z, int tileId, int tickDelay) -{ - MemSect(27); - TickNextTickData td = TickNextTickData(x, y, z, tileId); - int r = 8; - if (getInstaTick()) - { - if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, td.z + r)) - { - int id = getTile(td.x, td.y, td.z); - if (id == td.tileId && id > 0) - { - Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); - } - } - MemSect(0); - return; - } +void ServerLevel::addToTickNextTick(int x, int y, int z, int tileId, + int tickDelay) { + MemSect(27); + TickNextTickData td = TickNextTickData(x, y, z, tileId); + int r = 8; + if (getInstaTick()) { + if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, + td.z + r)) { + int id = getTile(td.x, td.y, td.z); + if (id == td.tileId && id > 0) { + Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); + } + } + MemSect(0); + return; + } - if (hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r)) - { - if (tileId > 0) - { - td.delay(tickDelay + levelData->getTime()); - } - EnterCriticalSection(&m_tickNextTickCS); - if ( tickNextTickSet.find(td) == tickNextTickSet.end() ) - { - tickNextTickSet.insert(td); - tickNextTickList.insert(td); - } - LeaveCriticalSection(&m_tickNextTickCS); - } - MemSect(0); + if (hasChunksAt(x - r, y - r, z - r, x + r, y + r, z + r)) { + if (tileId > 0) { + td.delay(tickDelay + levelData->getTime()); + } + EnterCriticalSection(&m_tickNextTickCS); + if (tickNextTickSet.find(td) == tickNextTickSet.end()) { + tickNextTickSet.insert(td); + tickNextTickList.insert(td); + } + LeaveCriticalSection(&m_tickNextTickCS); + } + MemSect(0); } -void ServerLevel::forceAddTileTick(int x, int y, int z, int tileId, int tickDelay) -{ +void ServerLevel::forceAddTileTick(int x, int y, int z, int tileId, + int tickDelay) { TickNextTickData td = TickNextTickData(x, y, z, tileId); - if (tileId > 0) - { + if (tileId > 0) { td.delay(tickDelay + levelData->getTime()); } - EnterCriticalSection(&m_tickNextTickCS); - if ( tickNextTickSet.find(td) == tickNextTickSet.end() ) - { + EnterCriticalSection(&m_tickNextTickCS); + if (tickNextTickSet.find(td) == tickNextTickSet.end()) { tickNextTickSet.insert(td); tickNextTickList.insert(td); } - LeaveCriticalSection(&m_tickNextTickCS); + LeaveCriticalSection(&m_tickNextTickCS); } -void ServerLevel::tickEntities() -{ - if (players.empty()) - { - if (emptyTime++ >= EMPTY_TIME_NO_TICK) - { - return; - } - } - else - { - emptyTime = 0; - } +void ServerLevel::tickEntities() { + if (players.empty()) { + if (emptyTime++ >= EMPTY_TIME_NO_TICK) { + return; + } + } else { + emptyTime = 0; + } - Level::tickEntities(); + Level::tickEntities(); } -bool ServerLevel::tickPendingTicks(bool force) -{ - EnterCriticalSection(&m_tickNextTickCS); - int count = (int)tickNextTickList.size(); - int count2 = (int)tickNextTickSet.size(); - if (count != tickNextTickSet.size()) - { - // TODO 4J Stu - Add new exception types - //throw new IllegalStateException("TickNextTick list out of synch"); - } - if (count > MAX_TICK_TILES_PER_TICK) count = MAX_TICK_TILES_PER_TICK; - - AUTO_VAR(itTickList, tickNextTickList.begin()); - for (int i = 0; i < count; i++) - { - TickNextTickData td = *(itTickList); - if (!force && td.m_delay > levelData->getTime()) - { - break; - } +bool ServerLevel::tickPendingTicks(bool force) { + EnterCriticalSection(&m_tickNextTickCS); + int count = (int)tickNextTickList.size(); + int count2 = (int)tickNextTickSet.size(); + if (count != tickNextTickSet.size()) { + // TODO 4J Stu - Add new exception types + // throw new IllegalStateException("TickNextTick list out of synch"); + } + if (count > MAX_TICK_TILES_PER_TICK) count = MAX_TICK_TILES_PER_TICK; - itTickList = tickNextTickList.erase(itTickList); - tickNextTickSet.erase(td); - int r = 8; - if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, td.z + r)) - { - int id = getTile(td.x, td.y, td.z); - if (id == td.tileId && id > 0) - { - Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); - } - } - } + AUTO_VAR(itTickList, tickNextTickList.begin()); + for (int i = 0; i < count; i++) { + TickNextTickData td = *(itTickList); + if (!force && td.m_delay > levelData->getTime()) { + break; + } - int count3 = (int)tickNextTickList.size(); - int count4 = (int)tickNextTickSet.size(); + itTickList = tickNextTickList.erase(itTickList); + tickNextTickSet.erase(td); + int r = 8; + if (hasChunksAt(td.x - r, td.y - r, td.z - r, td.x + r, td.y + r, + td.z + r)) { + int id = getTile(td.x, td.y, td.z); + if (id == td.tileId && id > 0) { + Tile::tiles[id]->tick(this, td.x, td.y, td.z, random); + } + } + } - bool retval = tickNextTickList.size() != 0; - LeaveCriticalSection(&m_tickNextTickCS); + int count3 = (int)tickNextTickList.size(); + int count4 = (int)tickNextTickSet.size(); - return retval; + bool retval = tickNextTickList.size() != 0; + LeaveCriticalSection(&m_tickNextTickCS); + + return retval; } -std::vector *ServerLevel::fetchTicksInChunk(LevelChunk *chunk, bool remove) -{ - EnterCriticalSection(&m_tickNextTickCS); - std::vector *results = new std::vector; +std::vector* ServerLevel::fetchTicksInChunk(LevelChunk* chunk, + bool remove) { + EnterCriticalSection(&m_tickNextTickCS); + std::vector* results = new std::vector; - ChunkPos *pos = chunk->getPos(); + ChunkPos* pos = chunk->getPos(); // 4jcraft added cast to unsigned - int west = (unsigned) pos->x << 4; + int west = (unsigned)pos->x << 4; int east = west + 16; - int north =(unsigned) pos->z << 4; + int north = (unsigned)pos->z << 4; int south = north + 16; - delete pos; + delete pos; - for( AUTO_VAR(it, tickNextTickSet.begin()); it != tickNextTickSet.end(); ) - { - TickNextTickData td = *it; + for (AUTO_VAR(it, tickNextTickSet.begin()); it != tickNextTickSet.end();) { + TickNextTickData td = *it; - if (td.x >= west && td.x < east && td.z >= north && td.z < south) - { - if (remove) - { + if (td.x >= west && td.x < east && td.z >= north && td.z < south) { + if (remove) { tickNextTickList.erase(td); it = tickNextTickSet.erase(it); + } else { + it++; } - else - { - it++; - } - results->push_back(td); + results->push_back(td); + } else { + it++; } - else - { - it++; - } - } + } - LeaveCriticalSection(&m_tickNextTickCS); - return results; + LeaveCriticalSection(&m_tickNextTickCS); + return results; } -void ServerLevel::tick(std::shared_ptr e, bool actual) -{ - if (!server->isAnimals() && ((e->GetType() & eTYPE_ANIMAL) || (e->GetType() & eTYPE_WATERANIMAL))) - { +void ServerLevel::tick(std::shared_ptr e, bool actual) { + if (!server->isAnimals() && + ((e->GetType() & eTYPE_ANIMAL) || (e->GetType() & eTYPE_WATERANIMAL))) { e->remove(); } - if (!server->isNpcsEnabled() && (std::dynamic_pointer_cast(e) != NULL)) - { - e->remove(); - } - if (e->rider.lock() == NULL || (std::dynamic_pointer_cast(e->rider.lock())==NULL) ) // 4J - was !(e->rider instanceof Player) - { + if (!server->isNpcsEnabled() && + (std::dynamic_pointer_cast(e) != NULL)) { + e->remove(); + } + if (e->rider.lock() == NULL || + (std::dynamic_pointer_cast(e->rider.lock()) == + NULL)) // 4J - was !(e->rider instanceof Player) + { Level::tick(e, actual); } } -void ServerLevel::forceTick(std::shared_ptr e, bool actual) -{ - Level::tick(e, actual); +void ServerLevel::forceTick(std::shared_ptr e, bool actual) { + Level::tick(e, actual); } -ChunkSource *ServerLevel::createChunkSource() -{ - ChunkStorage *storage = levelStorage->createChunkStorage(dimension); - cache = new ServerChunkCache(this, storage, dimension->createRandomLevelSource()); +ChunkSource* ServerLevel::createChunkSource() { + ChunkStorage* storage = levelStorage->createChunkStorage(dimension); + cache = new ServerChunkCache(this, storage, + dimension->createRandomLevelSource()); return cache; } -std::vector > *ServerLevel::getTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1) -{ - std::vector > *result = new std::vector >; - for (unsigned int i = 0; i < tileEntityList.size(); i++) - { +std::vector >* ServerLevel::getTileEntitiesInRegion( + int x0, int y0, int z0, int x1, int y1, int z1) { + std::vector >* result = + new std::vector >; + for (unsigned int i = 0; i < tileEntityList.size(); i++) { std::shared_ptr te = tileEntityList[i]; - if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && te->y < y1 && te->z < z1) - { + if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && + te->y < y1 && te->z < z1) { result->push_back(te); } } return result; } -bool ServerLevel::mayInteract(std::shared_ptr player, int xt, int yt, int zt, int content) -{ - // 4J-PB - This will look like a bug to players, and we really should have a message to explain why we're not allowing lava to be placed at or near a spawn point - // We'll need to do this in a future update +bool ServerLevel::mayInteract(std::shared_ptr player, int xt, int yt, + int zt, int content) { + // 4J-PB - This will look like a bug to players, and we really should have a + // message to explain why we're not allowing lava to be placed at or near a + // spawn point We'll need to do this in a future update - // 4J-PB - Let's allow water near the spawn point, but not lava - if(content!=Tile::lava_Id) - { - // allow this to be used - return true; - } - else if(dimension->id == 0) // 4J Stu - Only limit this in the overworld - { - int xd = (int) Mth::abs((float)(xt - levelData->getXSpawn())); - int zd = (int) Mth::abs((float)(zt - levelData->getZSpawn())); - if (xd > zd) zd = xd; - return (zd > 16 || server->getPlayers()->isOp(player->name)); - } - return true; + // 4J-PB - Let's allow water near the spawn point, but not lava + if (content != Tile::lava_Id) { + // allow this to be used + return true; + } else if (dimension->id == 0) // 4J Stu - Only limit this in the overworld + { + int xd = (int)Mth::abs((float)(xt - levelData->getXSpawn())); + int zd = (int)Mth::abs((float)(zt - levelData->getZSpawn())); + if (xd > zd) zd = xd; + return (zd > 16 || server->getPlayers()->isOp(player->name)); + } + return true; } -void ServerLevel::initializeLevel(LevelSettings *settings) -{ - setInitialSpawn(settings); +void ServerLevel::initializeLevel(LevelSettings* settings) { + setInitialSpawn(settings); - Level::initializeLevel(settings); + Level::initializeLevel(settings); } /** -* Sets the initial spawn, created this method so we could do a special -* location for the demo version. -*/ -void ServerLevel::setInitialSpawn(LevelSettings *levelSettings) -{ - if (!dimension->mayRespawn()) - { - levelData->setSpawn(0, dimension->getSpawnYPosition(), 0); - return; - } + * Sets the initial spawn, created this method so we could do a special + * location for the demo version. + */ +void ServerLevel::setInitialSpawn(LevelSettings* levelSettings) { + if (!dimension->mayRespawn()) { + levelData->setSpawn(0, dimension->getSpawnYPosition(), 0); + return; + } - isFindingSpawn = true; + isFindingSpawn = true; - BiomeSource *biomeSource = dimension->biomeSource; - std::vector playerSpawnBiomes = biomeSource->getPlayerSpawnBiomes(); - Random random(getSeed()); + BiomeSource* biomeSource = dimension->biomeSource; + std::vector playerSpawnBiomes = biomeSource->getPlayerSpawnBiomes(); + Random random(getSeed()); - TilePos *findBiome = biomeSource->findBiome(0, 0, 16 * 16, playerSpawnBiomes, &random); + TilePos* findBiome = + biomeSource->findBiome(0, 0, 16 * 16, playerSpawnBiomes, &random); - int xSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; - int ySpawn = dimension->getSpawnYPosition(); - int zSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; - int minXZ = - (dimension->getXZSize() * 16 ) / 2; - int maxXZ = (dimension->getXZSize() * 16 ) / 2 - 1; + int xSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; + int ySpawn = dimension->getSpawnYPosition(); + int zSpawn = 0; // (Level.MAX_LEVEL_SIZE - 100) * 0; + int minXZ = -(dimension->getXZSize() * 16) / 2; + int maxXZ = (dimension->getXZSize() * 16) / 2 - 1; - if (findBiome != NULL) - { - xSpawn = findBiome->x; - zSpawn = findBiome->z; - delete findBiome; - } - else - { - app.DebugPrintf("Level::setInitialSpawn - Unable to find spawn biome\n"); - } + if (findBiome != NULL) { + xSpawn = findBiome->x; + zSpawn = findBiome->z; + delete findBiome; + } else { + app.DebugPrintf( + "Level::setInitialSpawn - Unable to find spawn biome\n"); + } - int tries = 0; + int tries = 0; - while (!dimension->isValidSpawn(xSpawn, zSpawn)) - { - // 4J-PB changed to stay within our level limits - xSpawn += random.nextInt(64) - random.nextInt(64); - if(xSpawn>maxXZ) xSpawn=0; - if(xSpawnmaxXZ) zSpawn=0; - if(zSpawnisValidSpawn(xSpawn, zSpawn)) { + // 4J-PB changed to stay within our level limits + xSpawn += random.nextInt(64) - random.nextInt(64); + if (xSpawn > maxXZ) xSpawn = 0; + if (xSpawn < minXZ) xSpawn = 0; + zSpawn += random.nextInt(64) - random.nextInt(64); + if (zSpawn > maxXZ) zSpawn = 0; + if (zSpawn < minXZ) zSpawn = 0; - levelData->setSpawn(xSpawn, ySpawn, zSpawn); - if (levelSettings->hasStartingBonusItems()) - { - generateBonusItemsNearSpawn(); - } - isFindingSpawn = false; + if (++tries == 1000) break; + } + + levelData->setSpawn(xSpawn, ySpawn, zSpawn); + if (levelSettings->hasStartingBonusItems()) { + generateBonusItemsNearSpawn(); + } + isFindingSpawn = false; } // 4J - brought forward from 1.3.2 -void ServerLevel::generateBonusItemsNearSpawn() -{ +void ServerLevel::generateBonusItemsNearSpawn() { // once we've found the initial spawn, try to find a location for the -// starting bonus chest - // 4J - added - scan the spawn area first to see if there's already a chest near here + // starting bonus chest + // 4J - added - scan the spawn area first to see if there's already a chest + // near here - static const int r = 20; - int xs = levelData->getXSpawn(); - int zs = levelData->getZSpawn(); - for( int xx = -r; xx <= r; xx++ ) - for( int zz = -r; zz <= r; zz++ ) - { - int x = xx + xs; - int z = zz + zs; - int y = getTopSolidBlock( x, z ) - 1; - - if( getTile( x, y, z ) == Tile::chest_Id ) - { - std::shared_ptr chest = std::dynamic_pointer_cast(getTileEntity(x, y, z)); - if (chest != NULL) - { - if( chest->isBonusChest ) - { - return; - } - } - } - } + static const int r = 20; + int xs = levelData->getXSpawn(); + int zs = levelData->getZSpawn(); + for (int xx = -r; xx <= r; xx++) + for (int zz = -r; zz <= r; zz++) { + int x = xx + xs; + int z = zz + zs; + int y = getTopSolidBlock(x, z) - 1; - BonusChestFeature *feature = new BonusChestFeature(RANDOM_BONUS_ITEMS, 16); - for (int attempt = 0; attempt < 16; attempt++) - { - int x = levelData->getXSpawn() + random->nextInt(6) - random->nextInt(6); - int z = levelData->getZSpawn() + random->nextInt(6) - random->nextInt(6); + if (getTile(x, y, z) == Tile::chest_Id) { + std::shared_ptr chest = + std::dynamic_pointer_cast( + getTileEntity(x, y, z)); + if (chest != NULL) { + if (chest->isBonusChest) { + return; + } + } + } + } + + BonusChestFeature* feature = new BonusChestFeature(RANDOM_BONUS_ITEMS, 16); + for (int attempt = 0; attempt < 16; attempt++) { + int x = + levelData->getXSpawn() + random->nextInt(6) - random->nextInt(6); + int z = + levelData->getZSpawn() + random->nextInt(6) - random->nextInt(6); int y = getTopSolidBlock(x, z) + 1; - if (feature->place(this, random, x, y, z, (attempt == 15) )) - { + if (feature->place(this, random, x, y, z, (attempt == 15))) { break; } } - delete feature; + delete feature; } -Pos *ServerLevel::getDimensionSpecificSpawn() -{ - return dimension->getSpawnPos(); +Pos* ServerLevel::getDimensionSpecificSpawn() { + return dimension->getSpawnPos(); } // 4j Added for XboxOne PLM -void ServerLevel::Suspend() -{ - if(StorageManager.GetSaveDisabled()) return; - saveLevelData(); - chunkSource->saveAllEntities(); +void ServerLevel::Suspend() { + if (StorageManager.GetSaveDisabled()) return; + saveLevelData(); + chunkSource->saveAllEntities(); } -void ServerLevel::save(bool force, ProgressListener *progressListener, bool bAutosave) -{ - if (!chunkSource->shouldSave()) return; +void ServerLevel::save(bool force, ProgressListener* progressListener, + bool bAutosave) { + if (!chunkSource->shouldSave()) return; - // 4J-PB - check that saves are enabled - if(StorageManager.GetSaveDisabled()) return; + // 4J-PB - check that saves are enabled + if (StorageManager.GetSaveDisabled()) return; + if (progressListener != NULL) { + if (bAutosave) { + progressListener->progressStartNoAbort( + IDS_PROGRESS_AUTOSAVING_LEVEL); + } else { + progressListener->progressStartNoAbort(IDS_PROGRESS_SAVING_LEVEL); + } + } + PIXBeginNamedEvent(0, "Saving level data"); + saveLevelData(); + PIXEndNamedEvent(); - if (progressListener != NULL) - { - if(bAutosave) - { - progressListener->progressStartNoAbort(IDS_PROGRESS_AUTOSAVING_LEVEL); - } - else - { - progressListener->progressStartNoAbort(IDS_PROGRESS_SAVING_LEVEL); - } - - } - PIXBeginNamedEvent(0,"Saving level data"); - saveLevelData(); - PIXEndNamedEvent(); - - if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_CHUNKS); + if (progressListener != NULL) + progressListener->progressStage(IDS_PROGRESS_SAVING_CHUNKS); #if defined(_XBOX_ONE) || defined(__ORBIS__) - // Our autosave is a minimal save. All the chunks are saves by the constant save process - if(bAutosave) - { - chunkSource->saveAllEntities(); - } - else + // Our autosave is a minimal save. All the chunks are saves by the constant + // save process + if (bAutosave) { + chunkSource->saveAllEntities(); + } else #endif - { - chunkSource->save(force, progressListener); + { + chunkSource->save(force, progressListener); #ifdef _LARGE_WORLDS - // 4J Stu - Only do this if there are players in the level - if(chunkMap->players.size() > 0) - { - // 4J Stu - This will come in a later change anyway - // clean cache - std::vector *loadedChunkList = cache->getLoadedChunkList(); - for (AUTO_VAR(it, loadedChunkList->begin()); it != loadedChunkList->end(); ++it) - { - LevelChunk *lc = *it; - if (!chunkMap->hasChunk(lc->x, lc->z) ) - { - cache->drop(lc->x, lc->z); - } - } - } + // 4J Stu - Only do this if there are players in the level + if (chunkMap->players.size() > 0) { + // 4J Stu - This will come in a later change anyway + // clean cache + std::vector* loadedChunkList = + cache->getLoadedChunkList(); + for (AUTO_VAR(it, loadedChunkList->begin()); + it != loadedChunkList->end(); ++it) { + LevelChunk* lc = *it; + if (!chunkMap->hasChunk(lc->x, lc->z)) { + cache->drop(lc->x, lc->z); + } + } + } #endif - } + } - //if( force && !isClientSide ) - //{ - // if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); - // levelStorage->flushSaveFile(); - //} + // if( force && !isClientSide ) + //{ + // if (progressListener != NULL) + //progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); + // levelStorage->flushSaveFile(); + // } } // 4J Added -void ServerLevel::saveToDisc(ProgressListener *progressListener, bool autosave) -{ - // 4J-PB - check that saves are enabled - if(StorageManager.GetSaveDisabled()) return; +void ServerLevel::saveToDisc(ProgressListener* progressListener, + bool autosave) { + // 4J-PB - check that saves are enabled + if (StorageManager.GetSaveDisabled()) return; - // Check if we are using a trial version of a texture pack (which will be the case for going into the mash-up pack world with a trial version) - if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) - { - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + // Check if we are using a trial version of a texture pack (which will be + // the case for going into the mash-up pack world with a trial version) + if (!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { + TexturePack* tPack = Minecraft::GetInstance()->skins->getSelected(); + DLCTexturePack* pDLCTexPack = (DLCTexturePack*)tPack; - DLCPack * pDLCPack=pDLCTexPack->getDLCInfoParentPack(); + DLCPack* pDLCPack = pDLCTexPack->getDLCInfoParentPack(); - if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { - return; - } - } + if (!pDLCPack->hasPurchasedFile(DLCManager::e_DLCType_Texture, L"")) { + return; + } + } - if (progressListener != NULL) progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); - levelStorage->flushSaveFile(autosave); + if (progressListener != NULL) + progressListener->progressStage(IDS_PROGRESS_SAVING_TO_DISC); + levelStorage->flushSaveFile(autosave); } -void ServerLevel::saveLevelData() -{ - checkSession(); +void ServerLevel::saveLevelData() { + checkSession(); - levelStorage->saveLevelData(levelData, &players); - savedDataStorage->save(); + levelStorage->saveLevelData(levelData, &players); + savedDataStorage->save(); } -void ServerLevel::entityAdded(std::shared_ptr e) -{ +void ServerLevel::entityAdded(std::shared_ptr e) { Level::entityAdded(e); entitiesById[e->entityId] = e; - std::vector > *es = e->getSubEntities(); - if (es != NULL) - { - //for (int i = 0; i < es.length; i++) - for(AUTO_VAR(it, es->begin()); it != es->end(); ++it) - { - entitiesById.insert( intEntityMap::value_type( (*it)->entityId, (*it) )); - } - } - entityAddedExtra(e); // 4J added + std::vector >* es = e->getSubEntities(); + if (es != NULL) { + // for (int i = 0; i < es.length; i++) + for (AUTO_VAR(it, es->begin()); it != es->end(); ++it) { + entitiesById.insert( + intEntityMap::value_type((*it)->entityId, (*it))); + } + } + entityAddedExtra(e); // 4J added } -void ServerLevel::entityRemoved(std::shared_ptr e) -{ +void ServerLevel::entityRemoved(std::shared_ptr e) { Level::entityRemoved(e); - entitiesById.erase(e->entityId); - std::vector > *es = e->getSubEntities(); - if (es != NULL) - { - //for (int i = 0; i < es.length; i++) - for(AUTO_VAR(it, es->begin()); it != es->end(); ++it) - { - entitiesById.erase((*it)->entityId); - } - } - entityRemovedExtra(e); // 4J added + entitiesById.erase(e->entityId); + std::vector >* es = e->getSubEntities(); + if (es != NULL) { + // for (int i = 0; i < es.length; i++) + for (AUTO_VAR(it, es->begin()); it != es->end(); ++it) { + entitiesById.erase((*it)->entityId); + } + } + entityRemovedExtra(e); // 4J added } -std::shared_ptr ServerLevel::getEntity(int id) -{ - return entitiesById[id]; +std::shared_ptr ServerLevel::getEntity(int id) { + return entitiesById[id]; } -bool ServerLevel::addGlobalEntity(std::shared_ptr e) -{ - if (Level::addGlobalEntity(e)) - { - server->getPlayers()->broadcast(e->x, e->y, e->z, 512, dimension->id, std::shared_ptr( new AddGlobalEntityPacket(e) ) ); +bool ServerLevel::addGlobalEntity(std::shared_ptr e) { + if (Level::addGlobalEntity(e)) { + server->getPlayers()->broadcast(e->x, e->y, e->z, 512, dimension->id, + std::shared_ptr( + new AddGlobalEntityPacket(e))); return true; } return false; } -void ServerLevel::broadcastEntityEvent(std::shared_ptr e, uint8_t event) -{ - std::shared_ptr p = std::shared_ptr( new EntityEventPacket(e->entityId, event) ); +void ServerLevel::broadcastEntityEvent(std::shared_ptr e, + uint8_t event) { + std::shared_ptr p = std::shared_ptr( + new EntityEventPacket(e->entityId, event)); server->getLevel(dimension->id)->getTracker()->broadcastAndSend(e, p); } -std::shared_ptr ServerLevel::explode(std::shared_ptr source, double x, double y, double z, float r, bool fire, bool destroyBlocks) -{ +std::shared_ptr ServerLevel::explode(std::shared_ptr source, + double x, double y, double z, + float r, bool fire, + bool destroyBlocks) { // instead of calling super, we run the same explosion code here except // we don't generate any particles - std::shared_ptr explosion = std::shared_ptr( new Explosion(this, source, x, y, z, r) ); + std::shared_ptr explosion = + std::shared_ptr(new Explosion(this, source, x, y, z, r)); explosion->fire = fire; - explosion->destroyBlocks = destroyBlocks; + explosion->destroyBlocks = destroyBlocks; explosion->explode(); explosion->finalizeExplosion(false); - if (!destroyBlocks) - { - explosion->toBlow.clear(); - } + if (!destroyBlocks) { + explosion->toBlow.clear(); + } - std::vector > sentTo; - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) - { - std::shared_ptr player = std::dynamic_pointer_cast(*it); - if (player->dimension != dimension->id) continue; + std::vector > sentTo; + for (AUTO_VAR(it, players.begin()); it != players.end(); ++it) { + std::shared_ptr player = + std::dynamic_pointer_cast(*it); + if (player->dimension != dimension->id) continue; - bool knockbackOnly = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - continue; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - knockbackOnly = true; - } - } - } - } + bool knockbackOnly = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + continue; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + knockbackOnly = true; + } + } + } + } - if (player->distanceToSqr(x, y, z) < 64 * 64) - { - Vec3 *knockbackVec = explosion->getHitPlayerKnockback(player); - //app.DebugPrintf("Sending %s with knockback (%f,%f,%f)\n", knockbackOnly?"knockbackOnly":"allExplosion",knockbackVec->x,knockbackVec->y,knockbackVec->z); - // If the player is not the primary on the system, then we only want to send info for the knockback - player->connection->send( std::shared_ptr( new ExplodePacket(x, y, z, r, &explosion->toBlow, knockbackVec, knockbackOnly))); - sentTo.push_back( player ); + if (player->distanceToSqr(x, y, z) < 64 * 64) { + Vec3* knockbackVec = explosion->getHitPlayerKnockback(player); + // app.DebugPrintf("Sending %s with knockback (%f,%f,%f)\n", + // knockbackOnly?"knockbackOnly":"allExplosion",knockbackVec->x,knockbackVec->y,knockbackVec->z); + // If the player is not the primary on the system, then we only + // want to send info for the knockback + player->connection->send(std::shared_ptr( + new ExplodePacket(x, y, z, r, &explosion->toBlow, knockbackVec, + knockbackOnly))); + sentTo.push_back(player); } } return explosion; } -void ServerLevel::tileEvent(int x, int y, int z, int tile, int b0, int b1) -{ - // super.tileEvent(x, y, z, b0, b1); - // server.getPlayers().broadcast(x, y, z, 64, dimension.id, new TileEventPacket(x, y, z, b0, b1)); - TileEventData newEvent(x, y, z, tile, b0, b1); - //for (TileEventData te : tileEvents[activeTileEventsList]) - for(AUTO_VAR(it, tileEvents[activeTileEventsList].begin()); it != tileEvents[activeTileEventsList].end(); ++it) - { - if ((*it).equals(newEvent)) - { - return; - } - } - tileEvents[activeTileEventsList].push_back(newEvent); +void ServerLevel::tileEvent(int x, int y, int z, int tile, int b0, int b1) { + // super.tileEvent(x, y, z, b0, b1); + // server.getPlayers().broadcast(x, y, z, 64, dimension.id, new + // TileEventPacket(x, y, z, b0, b1)); + TileEventData newEvent(x, y, z, tile, b0, b1); + // for (TileEventData te : tileEvents[activeTileEventsList]) + for (AUTO_VAR(it, tileEvents[activeTileEventsList].begin()); + it != tileEvents[activeTileEventsList].end(); ++it) { + if ((*it).equals(newEvent)) { + return; + } + } + tileEvents[activeTileEventsList].push_back(newEvent); } -void ServerLevel::runTileEvents() -{ - // use two lists until both are empty, intended to avoid concurrent - // modifications - while (!tileEvents[activeTileEventsList].empty()) - { - int runList = activeTileEventsList; - activeTileEventsList ^= 1; +void ServerLevel::runTileEvents() { + // use two lists until both are empty, intended to avoid concurrent + // modifications + while (!tileEvents[activeTileEventsList].empty()) { + int runList = activeTileEventsList; + activeTileEventsList ^= 1; - //for (TileEventData te : tileEvents[runList]) - for(AUTO_VAR(it, tileEvents[runList].begin()); it != tileEvents[runList].end(); ++it) - { - if (doTileEvent(&(*it))) - { - TileEventData te = *it; - server->getPlayers()->broadcast(te.getX(), te.getY(), te.getZ(), 64, dimension->id, std::shared_ptr( new TileEventPacket(te.getX(), te.getY(), te.getZ(), te.getTile(), te.getParamA(), te.getParamB()))); - } - } - tileEvents[runList].clear(); - } + // for (TileEventData te : tileEvents[runList]) + for (AUTO_VAR(it, tileEvents[runList].begin()); + it != tileEvents[runList].end(); ++it) { + if (doTileEvent(&(*it))) { + TileEventData te = *it; + server->getPlayers()->broadcast( + te.getX(), te.getY(), te.getZ(), 64, dimension->id, + std::shared_ptr(new TileEventPacket( + te.getX(), te.getY(), te.getZ(), te.getTile(), + te.getParamA(), te.getParamB()))); + } + } + tileEvents[runList].clear(); + } } -bool ServerLevel::doTileEvent(TileEventData *te) -{ - int t = getTile(te->getX(), te->getY(), te->getZ()); - if (t == te->getTile()) { - Tile::tiles[t]->triggerEvent(this, te->getX(), te->getY(), te->getZ(), te->getParamA(), te->getParamB()); - return true; - } - return false; +bool ServerLevel::doTileEvent(TileEventData* te) { + int t = getTile(te->getX(), te->getY(), te->getZ()); + if (t == te->getTile()) { + Tile::tiles[t]->triggerEvent(this, te->getX(), te->getY(), te->getZ(), + te->getParamA(), te->getParamB()); + return true; + } + return false; } -void ServerLevel::closeLevelStorage() -{ - levelStorage->closeAll(); -} +void ServerLevel::closeLevelStorage() { levelStorage->closeAll(); } -void ServerLevel::tickWeather() -{ +void ServerLevel::tickWeather() { bool wasRaining = isRaining(); Level::tickWeather(); - if (wasRaining != isRaining()) - { - if (wasRaining) - { - server->getPlayers()->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::STOP_RAINING, 0) ) ); - } - else - { - server->getPlayers()->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::START_RAINING, 0) ) ); + if (wasRaining != isRaining()) { + if (wasRaining) { + server->getPlayers()->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::STOP_RAINING, 0))); + } else { + server->getPlayers()->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::START_RAINING, 0))); } } - } -MinecraftServer *ServerLevel::getServer() -{ - return server; +MinecraftServer* ServerLevel::getServer() { return server; } + +EntityTracker* ServerLevel::getTracker() { return tracker; } + +void ServerLevel::setTimeAndAdjustTileTicks(__int64 newTime) { + __int64 delta = newTime - levelData->getTime(); + // 4J - can't directly adjust m_delay in a set as it has a const interator, + // since changing values in here might change the ordering of the elements + // in the set. Instead move to a vector, do the adjustment, put back in the + // set. + std::vector temp; + for (AUTO_VAR(it, tickNextTickList.begin()); it != tickNextTickList.end(); + ++it) { + temp.push_back(*it); + temp.back().m_delay += delta; + } + tickNextTickList.clear(); + for (unsigned int i = 0; i < temp.size(); i++) { + tickNextTickList.insert(temp[i]); + } + setTime(newTime); } -EntityTracker *ServerLevel::getTracker() -{ - return tracker; +PlayerChunkMap* ServerLevel::getChunkMap() { return chunkMap; } + +// 4J Stu - Sometimes we want to update tiles on the server from the main thread +// (eg SignTileEntity when string verify returns) +void ServerLevel::queueSendTileUpdate(int x, int y, int z) { + EnterCriticalSection(&m_csQueueSendTileUpdates); + m_queuedSendTileUpdates.push_back(new Pos(x, y, z)); + LeaveCriticalSection(&m_csQueueSendTileUpdates); } -void ServerLevel::setTimeAndAdjustTileTicks(__int64 newTime) -{ - __int64 delta = newTime - levelData->getTime(); - // 4J - can't directly adjust m_delay in a set as it has a const interator, since changing values in here might change the ordering of the elements in the set. - // Instead move to a vector, do the adjustment, put back in the set. - std::vector temp; - for(AUTO_VAR(it, tickNextTickList.begin()); it != tickNextTickList.end(); ++it) - { - temp.push_back(*it); - temp.back().m_delay += delta; - } - tickNextTickList.clear(); - for(unsigned int i = 0; i < temp.size(); i++ ) - { - tickNextTickList.insert(temp[i]); - } - setTime(newTime); +void ServerLevel::runQueuedSendTileUpdates() { + EnterCriticalSection(&m_csQueueSendTileUpdates); + for (AUTO_VAR(it, m_queuedSendTileUpdates.begin()); + it != m_queuedSendTileUpdates.end(); ++it) { + Pos* p = *it; + sendTileUpdated(p->x, p->y, p->z); + delete p; + } + m_queuedSendTileUpdates.clear(); + LeaveCriticalSection(&m_csQueueSendTileUpdates); } -PlayerChunkMap *ServerLevel::getChunkMap() -{ - return chunkMap; -} +// 4J - added special versions of addEntity and extra processing on entity +// removed and added so we can limit the number of itementities created +bool ServerLevel::addEntity(std::shared_ptr e) { + // If its an item entity, and we've got to our capacity, delete the oldest + if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding item entity count + //%d\n",m_itemEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_itemEntities.size() >= MAX_ITEM_ENTITIES) { + // printf("Adding - doing remove\n"); + removeEntityImmediately(m_itemEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + // If its an hanging entity, and we've got to our capacity, delete the + // oldest + else if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding item entity count + //%d\n",m_itemEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_hangingEntities.size() >= MAX_HANGING_ENTITIES) { + // printf("Adding - doing remove\n"); -// 4J Stu - Sometimes we want to update tiles on the server from the main thread (eg SignTileEntity when string verify returns) -void ServerLevel::queueSendTileUpdate(int x, int y, int z) -{ - EnterCriticalSection(&m_csQueueSendTileUpdates); - m_queuedSendTileUpdates.push_back( new Pos(x,y,z) ); - LeaveCriticalSection(&m_csQueueSendTileUpdates); -} + // 4J-PB - refuse to add the entity, since we'll be removing one + // already there, and it may be an item frame with something in it. + LeaveCriticalSection(&m_limiterCS); + return FALSE; -void ServerLevel::runQueuedSendTileUpdates() -{ - EnterCriticalSection(&m_csQueueSendTileUpdates); - for(AUTO_VAR(it, m_queuedSendTileUpdates.begin()); it != m_queuedSendTileUpdates.end(); ++it) - { - Pos *p = *it; - sendTileUpdated(p->x, p->y, p->z); - delete p; - } - m_queuedSendTileUpdates.clear(); - LeaveCriticalSection(&m_csQueueSendTileUpdates); -} - -// 4J - added special versions of addEntity and extra processing on entity removed and added so we can limit the number of itementities created -bool ServerLevel::addEntity(std::shared_ptr e) -{ - // If its an item entity, and we've got to our capacity, delete the oldest - if( std::dynamic_pointer_cast(e) != NULL ) - { -// printf("Adding item entity count %d\n",m_itemEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_itemEntities.size() >= MAX_ITEM_ENTITIES ) - { -// printf("Adding - doing remove\n"); - removeEntityImmediately(m_itemEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - // If its an hanging entity, and we've got to our capacity, delete the oldest - else if( std::dynamic_pointer_cast(e) != NULL ) - { - // printf("Adding item entity count %d\n",m_itemEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_hangingEntities.size() >= MAX_HANGING_ENTITIES ) - { - // printf("Adding - doing remove\n"); - - // 4J-PB - refuse to add the entity, since we'll be removing one already there, and it may be an item frame with something in it. - LeaveCriticalSection(&m_limiterCS); - return FALSE; - - //removeEntityImmediately(m_hangingEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - // If its an arrow entity, and we've got to our capacity, delete the oldest - else if( std::dynamic_pointer_cast(e) != NULL ) - { -// printf("Adding arrow entity count %d\n",m_arrowEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_arrowEntities.size() >= MAX_ARROW_ENTITIES ) - { -// printf("Adding - doing remove\n"); - removeEntityImmediately(m_arrowEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - // If its an experience orb entity, and we've got to our capacity, delete the oldest - else if( std::dynamic_pointer_cast(e) != NULL ) - { -// printf("Adding arrow entity count %d\n",m_arrowEntities.size()); - EnterCriticalSection(&m_limiterCS); - if( m_experienceOrbEntities.size() >= MAX_EXPERIENCEORB_ENTITIES ) - { -// printf("Adding - doing remove\n"); - removeEntityImmediately(m_experienceOrbEntities.front()); - } - LeaveCriticalSection(&m_limiterCS); - } - return Level::addEntity(e); + // removeEntityImmediately(m_hangingEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + // If its an arrow entity, and we've got to our capacity, delete the oldest + else if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding arrow entity count + //%d\n",m_arrowEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_arrowEntities.size() >= MAX_ARROW_ENTITIES) { + // printf("Adding - doing remove\n"); + removeEntityImmediately(m_arrowEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + // If its an experience orb entity, and we've got to our capacity, delete + // the oldest + else if (std::dynamic_pointer_cast(e) != NULL) { + // printf("Adding arrow entity count + //%d\n",m_arrowEntities.size()); + EnterCriticalSection(&m_limiterCS); + if (m_experienceOrbEntities.size() >= MAX_EXPERIENCEORB_ENTITIES) { + // printf("Adding - doing remove\n"); + removeEntityImmediately(m_experienceOrbEntities.front()); + } + LeaveCriticalSection(&m_limiterCS); + } + return Level::addEntity(e); } // Maintain a cound of primed tnt & falling tiles in this level -void ServerLevel::entityAddedExtra(std::shared_ptr e) -{ - if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_itemEntities.push_back(e); -// printf("entity added: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_hangingEntities.push_back(e); - // printf("entity added: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_arrowEntities.push_back(e); -// printf("entity added: arrow entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_experienceOrbEntities.push_back(e); -// printf("entity added: experience orb entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_primedTntCount++; - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_fallingTileCount++; - LeaveCriticalSection(&m_limiterCS); - } +void ServerLevel::entityAddedExtra(std::shared_ptr e) { + if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_itemEntities.push_back(e); + // printf("entity added: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_hangingEntities.push_back(e); + // printf("entity added: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_arrowEntities.push_back(e); + // printf("entity added: arrow entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_experienceOrbEntities.push_back(e); + // printf("entity added: experience orb entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_primedTntCount++; + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_fallingTileCount++; + LeaveCriticalSection(&m_limiterCS); + } } -// Maintain a cound of primed tnt & falling tiles in this level, and remove any item entities from our list -void ServerLevel::entityRemovedExtra(std::shared_ptr e) -{ - if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); -// printf("entity removed: item entity count %d\n",m_itemEntities.size()); - AUTO_VAR(it, find(m_itemEntities.begin(),m_itemEntities.end(),e)); - if( it != m_itemEntities.end() ) - { -// printf("Item to remove found\n"); - m_itemEntities.erase(it); - } -// printf("entity removed: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - // printf("entity removed: item entity count %d\n",m_itemEntities.size()); - AUTO_VAR(it, find(m_hangingEntities.begin(),m_hangingEntities.end(),e)); - if( it != m_hangingEntities.end() ) - { - // printf("Item to remove found\n"); - m_hangingEntities.erase(it); - } - // printf("entity removed: item entity count now %d\n",m_itemEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); -// printf("entity removed: arrow entity count %d\n",m_arrowEntities.size()); - AUTO_VAR(it, find(m_arrowEntities.begin(),m_arrowEntities.end(),e)); - if( it != m_arrowEntities.end() ) - { -// printf("Item to remove found\n"); - m_arrowEntities.erase(it); - } -// printf("entity removed: arrow entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); -// printf("entity removed: experience orb entity count %d\n",m_arrowEntities.size()); - AUTO_VAR(it, find(m_experienceOrbEntities.begin(),m_experienceOrbEntities.end(),e)); - if( it != m_experienceOrbEntities.end() ) - { -// printf("Item to remove found\n"); - m_experienceOrbEntities.erase(it); - } -// printf("entity removed: experience orb entity count now %d\n",m_arrowEntities.size()); - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_primedTntCount--; - LeaveCriticalSection(&m_limiterCS); - } - else if( std::dynamic_pointer_cast(e) != NULL ) - { - EnterCriticalSection(&m_limiterCS); - m_fallingTileCount--; - LeaveCriticalSection(&m_limiterCS); - } +// Maintain a cound of primed tnt & falling tiles in this level, and remove any +// item entities from our list +void ServerLevel::entityRemovedExtra(std::shared_ptr e) { + if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: item entity count + //%d\n",m_itemEntities.size()); + AUTO_VAR(it, find(m_itemEntities.begin(), m_itemEntities.end(), e)); + if (it != m_itemEntities.end()) { + // printf("Item to remove found\n"); + m_itemEntities.erase(it); + } + // printf("entity removed: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: item entity count + //%d\n",m_itemEntities.size()); + AUTO_VAR(it, + find(m_hangingEntities.begin(), m_hangingEntities.end(), e)); + if (it != m_hangingEntities.end()) { + // printf("Item to remove found\n"); + m_hangingEntities.erase(it); + } + // printf("entity removed: item entity count now + //%d\n",m_itemEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: arrow entity count + //%d\n",m_arrowEntities.size()); + AUTO_VAR(it, find(m_arrowEntities.begin(), m_arrowEntities.end(), e)); + if (it != m_arrowEntities.end()) { + // printf("Item to remove found\n"); + m_arrowEntities.erase(it); + } + // printf("entity removed: arrow entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + // printf("entity removed: experience orb entity count + //%d\n",m_arrowEntities.size()); + AUTO_VAR(it, find(m_experienceOrbEntities.begin(), + m_experienceOrbEntities.end(), e)); + if (it != m_experienceOrbEntities.end()) { + // printf("Item to remove found\n"); + m_experienceOrbEntities.erase(it); + } + // printf("entity removed: experience orb entity count now + //%d\n",m_arrowEntities.size()); + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_primedTntCount--; + LeaveCriticalSection(&m_limiterCS); + } else if (std::dynamic_pointer_cast(e) != NULL) { + EnterCriticalSection(&m_limiterCS); + m_fallingTileCount--; + LeaveCriticalSection(&m_limiterCS); + } } -bool ServerLevel::newPrimedTntAllowed() -{ - EnterCriticalSection(&m_limiterCS); - bool retval = m_primedTntCount < MAX_PRIMED_TNT; - LeaveCriticalSection(&m_limiterCS); - return retval; +bool ServerLevel::newPrimedTntAllowed() { + EnterCriticalSection(&m_limiterCS); + bool retval = m_primedTntCount < MAX_PRIMED_TNT; + LeaveCriticalSection(&m_limiterCS); + return retval; } -bool ServerLevel::newFallingTileAllowed() -{ - EnterCriticalSection(&m_limiterCS); - bool retval = m_fallingTileCount < MAX_FALLING_TILE; - LeaveCriticalSection(&m_limiterCS); - return retval; +bool ServerLevel::newFallingTileAllowed() { + EnterCriticalSection(&m_limiterCS); + bool retval = m_fallingTileCount < MAX_FALLING_TILE; + LeaveCriticalSection(&m_limiterCS); + return retval; } -int ServerLevel::runUpdate(void* lpParam) -{ - ShutdownManager::HasStarted(ShutdownManager::eRunUpdateThread,m_updateTrigger); - while(ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) - { - m_updateTrigger->WaitForAll(INFINITE); +int ServerLevel::runUpdate(void* lpParam) { + ShutdownManager::HasStarted(ShutdownManager::eRunUpdateThread, + m_updateTrigger); + while (ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) { + m_updateTrigger->WaitForAll(INFINITE); - if(!ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) break; + if (!ShutdownManager::ShouldRun(ShutdownManager::eRunUpdateThread)) + break; - PIXBeginNamedEvent(0,"Updating tiles to be ticked"); - // 4J Stu - Grass and Lava ticks currently take up the majority of all tile updates, so I am limiting them - int grassTicks = 0; - int lavaTicks = 0; - for( unsigned int iLev = 0; iLev < 3; ++iLev ) - { - EnterCriticalSection(&m_updateCS[iLev]); - for( int i = 0; i < m_updateChunkCount[iLev]; i++ ) - { - // 4J - some of these tile ticks will check things in neighbouring tiles, causing chunks to load/create that aren't yet in memory. - // Try and avoid this by limiting the min/max x & z values that we will try and inspect in this chunk according to what surround chunks are loaded - int cx = m_updateChunkX[iLev][i]; - int cz = m_updateChunkZ[iLev][i]; - int minx = 0; - int maxx = 15; - int minz = 0; - int maxz = 15; - if( !m_level[iLev]->hasChunk(cx, cz) ) continue; + PIXBeginNamedEvent(0, "Updating tiles to be ticked"); + // 4J Stu - Grass and Lava ticks currently take up the majority of all + // tile updates, so I am limiting them + int grassTicks = 0; + int lavaTicks = 0; + for (unsigned int iLev = 0; iLev < 3; ++iLev) { + EnterCriticalSection(&m_updateCS[iLev]); + for (int i = 0; i < m_updateChunkCount[iLev]; i++) { + // 4J - some of these tile ticks will check things in + // neighbouring tiles, causing chunks to load/create that aren't + // yet in memory. Try and avoid this by limiting the min/max x & + // z values that we will try and inspect in this chunk according + // to what surround chunks are loaded + int cx = m_updateChunkX[iLev][i]; + int cz = m_updateChunkZ[iLev][i]; + int minx = 0; + int maxx = 15; + int minz = 0; + int maxz = 15; + if (!m_level[iLev]->hasChunk(cx, cz)) continue; - if( !m_level[iLev]->hasChunk(cx + 1, cz + 0) ) { maxx = 11; } - if( !m_level[iLev]->hasChunk(cx + 0, cz + 1) ) { maxz = 11; } - if( !m_level[iLev]->hasChunk(cx - 1, cz + 0) ) { minx = 4; } - if( !m_level[iLev]->hasChunk(cx + 0, cz - 1) ) { minz = 4; } - if( !m_level[iLev]->hasChunk(cx + 1, cz + 1) ) { maxx = 11; maxz = 11; } - if( !m_level[iLev]->hasChunk(cx + 1, cz - 1) ) { maxx = 11; minz = 4; } - if( !m_level[iLev]->hasChunk(cx - 1, cz - 1) ) { minx = 4; minz = 4; } - if( !m_level[iLev]->hasChunk(cx - 1, cz + 1) ) { minx = 4; maxz = 11; } + if (!m_level[iLev]->hasChunk(cx + 1, cz + 0)) { + maxx = 11; + } + if (!m_level[iLev]->hasChunk(cx + 0, cz + 1)) { + maxz = 11; + } + if (!m_level[iLev]->hasChunk(cx - 1, cz + 0)) { + minx = 4; + } + if (!m_level[iLev]->hasChunk(cx + 0, cz - 1)) { + minz = 4; + } + if (!m_level[iLev]->hasChunk(cx + 1, cz + 1)) { + maxx = 11; + maxz = 11; + } + if (!m_level[iLev]->hasChunk(cx + 1, cz - 1)) { + maxx = 11; + minz = 4; + } + if (!m_level[iLev]->hasChunk(cx - 1, cz - 1)) { + minx = 4; + minz = 4; + } + if (!m_level[iLev]->hasChunk(cx - 1, cz + 1)) { + minx = 4; + maxz = 11; + } - LevelChunk *lc = m_level[iLev]->getChunk(cx, cz); + LevelChunk* lc = m_level[iLev]->getChunk(cx, cz); - for (int j = 0; j < 80; j++) - { - // 4jcraft added cast to unsigned - m_randValue[iLev] = (unsigned) m_randValue[iLev] * 3 + (unsigned) m_level[iLev]->addend; - int val = (m_randValue[iLev] >> 2); - int x = (val & 15); - if( ( x < minx ) || ( x > maxx ) ) continue; - int z = ((val >> 8) & 15); - if( ( z < minz ) || ( z > maxz ) ) continue; - int y = ((val >> 16) & (Level::maxBuildHeight - 1)); + for (int j = 0; j < 80; j++) { + // 4jcraft added cast to unsigned + m_randValue[iLev] = (unsigned)m_randValue[iLev] * 3 + + (unsigned)m_level[iLev]->addend; + int val = (m_randValue[iLev] >> 2); + int x = (val & 15); + if ((x < minx) || (x > maxx)) continue; + int z = ((val >> 8) & 15); + if ((z < minz) || (z > maxz)) continue; + int y = ((val >> 16) & (Level::maxBuildHeight - 1)); - // This array access is a cache miss pretty much every time - int id = lc->getTile(x,y,z); - if( m_updateTileCount[iLev] >= MAX_UPDATES ) break; + // This array access is a cache miss pretty much every time + int id = lc->getTile(x, y, z); + if (m_updateTileCount[iLev] >= MAX_UPDATES) break; - // 4J Stu - Grass and Lava ticks currently take up the majority of all tile updates, so I am limiting them - if( (id == Tile::grass_Id && grassTicks >= MAX_GRASS_TICKS) || (id == Tile::calmLava_Id && lavaTicks >= MAX_LAVA_TICKS) ) continue; + // 4J Stu - Grass and Lava ticks currently take up the + // majority of all tile updates, so I am limiting them + if ((id == Tile::grass_Id && + grassTicks >= MAX_GRASS_TICKS) || + (id == Tile::calmLava_Id && + lavaTicks >= MAX_LAVA_TICKS)) + continue; - // 4J Stu - Added shouldTileTick as some tiles won't even do anything if they are set to tick and use up one of our updates - if (Tile::tiles[id] != NULL && Tile::tiles[id]->isTicking() && Tile::tiles[id]->shouldTileTick(m_level[iLev],x + (cx * 16), y, z + (cz * 16) ) ) - { - if(id == Tile::grass_Id) ++grassTicks; - else if(id == Tile::calmLava_Id) ++lavaTicks; - m_updateTileX[iLev][m_updateTileCount[iLev]] = x + (cx * 16); - m_updateTileY[iLev][m_updateTileCount[iLev]] = y; - m_updateTileZ[iLev][m_updateTileCount[iLev]] = z + (cz * 16); + // 4J Stu - Added shouldTileTick as some tiles won't even do + // anything if they are set to tick and use up one of our + // updates + if (Tile::tiles[id] != NULL && + Tile::tiles[id]->isTicking() && + Tile::tiles[id]->shouldTileTick( + m_level[iLev], x + (cx * 16), y, z + (cz * 16))) { + if (id == Tile::grass_Id) + ++grassTicks; + else if (id == Tile::calmLava_Id) + ++lavaTicks; + m_updateTileX[iLev][m_updateTileCount[iLev]] = + x + (cx * 16); + m_updateTileY[iLev][m_updateTileCount[iLev]] = y; + m_updateTileZ[iLev][m_updateTileCount[iLev]] = + z + (cz * 16); - m_updateTileCount[iLev]++; - } - } - } - LeaveCriticalSection(&m_updateCS[iLev]); - } - PIXEndNamedEvent(); + m_updateTileCount[iLev]++; + } + } + } + LeaveCriticalSection(&m_updateCS[iLev]); + } + PIXEndNamedEvent(); #ifdef __PS3__ - Sleep(10); -#endif //__PS3__ - } + Sleep(10); +#endif //__PS3__ + } - ShutdownManager::HasFinished(ShutdownManager::eRunUpdateThread); + ShutdownManager::HasFinished(ShutdownManager::eRunUpdateThread); - return 0; + return 0; } -void ServerLevel::flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound) -{ - if( chunkMap ) - { - chunkMap->flagEntitiesToBeRemoved(flags, removedFound); - } +void ServerLevel::flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound) { + if (chunkMap) { + chunkMap->flagEntitiesToBeRemoved(flags, removedFound); + } } diff --git a/Minecraft.Client/Level/ServerLevel.h b/Minecraft.Client/Level/ServerLevel.h index 3605eb195..56b0a9884 100644 --- a/Minecraft.Client/Level/ServerLevel.h +++ b/Minecraft.Client/Level/ServerLevel.h @@ -7,165 +7,193 @@ class Node; class EntityTracker; class PlayerChunkMap; - -class ServerLevel : public Level -{ +class ServerLevel : public Level { private: - static const int EMPTY_TIME_NO_TICK = SharedConstants::TICKS_PER_SECOND * 3; + static const int EMPTY_TIME_NO_TICK = SharedConstants::TICKS_PER_SECOND * 3; - MinecraftServer *server; - EntityTracker *tracker; - PlayerChunkMap *chunkMap; + MinecraftServer* server; + EntityTracker* tracker; + PlayerChunkMap* chunkMap; - CRITICAL_SECTION m_tickNextTickCS; // 4J added - std::set tickNextTickList; // 4J Was TreeSet - std::unordered_set tickNextTickSet; // 4J Was HashSet + CRITICAL_SECTION m_tickNextTickCS; // 4J added + std::set + tickNextTickList; // 4J Was TreeSet + std::unordered_set + tickNextTickSet; // 4J Was HashSet - std::vector m_queuedSendTileUpdates; // 4J added - CRITICAL_SECTION m_csQueueSendTileUpdates; + std::vector m_queuedSendTileUpdates; // 4J added + CRITICAL_SECTION m_csQueueSendTileUpdates; protected: - int saveInterval; + int saveInterval; public: - ServerChunkCache *cache; + ServerChunkCache* cache; bool canEditSpawn; bool noSave; -private: - bool allPlayersSleeping; - int emptyTime; - bool m_bAtLeastOnePlayerSleeping; // 4J Added - static WeighedTreasureArray RANDOM_BONUS_ITEMS; // 4J - brought forward from 1.3.2 - - std::vector tileEvents[2]; - int activeTileEventsList; -public: - static void staticCtor(); - ServerLevel(MinecraftServer *server, std::shared_ptrlevelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings); - ~ServerLevel(); - void tick(); - Biome::MobSpawnerData *getRandomMobSpawnAt(MobCategory *mobCategory, int x, int y, int z); - void updateSleepingPlayerList(); -protected: - void awakenAllPlayers(); private: - void stopWeather(); + bool allPlayersSleeping; + int emptyTime; + bool m_bAtLeastOnePlayerSleeping; // 4J Added + static WeighedTreasureArray + RANDOM_BONUS_ITEMS; // 4J - brought forward from 1.3.2 + + std::vector tileEvents[2]; + int activeTileEventsList; public: - bool allPlayersAreSleeping(); - void validateSpawn(); + static void staticCtor(); + ServerLevel(MinecraftServer* server, + std::shared_ptr levelStorage, + const std::wstring& levelName, int dimension, + LevelSettings* levelSettings); + ~ServerLevel(); + void tick(); + Biome::MobSpawnerData* getRandomMobSpawnAt(MobCategory* mobCategory, int x, + int y, int z); + void updateSleepingPlayerList(); protected: - void tickTiles(); + void awakenAllPlayers(); + +private: + void stopWeather(); public: - void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay); - void forceAddTileTick(int x, int y, int z, int tileId, int tickDelay); - void tickEntities(); - bool tickPendingTicks(bool force); - std::vector *fetchTicksInChunk(LevelChunk *chunk, bool remove); + bool allPlayersAreSleeping(); + void validateSpawn(); + +protected: + void tickTiles(); + +public: + void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay); + void forceAddTileTick(int x, int y, int z, int tileId, int tickDelay); + void tickEntities(); + bool tickPendingTicks(bool force); + std::vector* fetchTicksInChunk(LevelChunk* chunk, + bool remove); virtual void tick(std::shared_ptr e, bool actual); void forceTick(std::shared_ptr e, bool actual); - bool AllPlayersAreSleeping() { return allPlayersSleeping;} // 4J added for a message to other players - bool isAtLeastOnePlayerSleeping() { return m_bAtLeastOnePlayerSleeping;} + bool AllPlayersAreSleeping() { + return allPlayersSleeping; + } // 4J added for a message to other players + bool isAtLeastOnePlayerSleeping() { return m_bAtLeastOnePlayerSleeping; } + protected: - ChunkSource *createChunkSource(); // 4J - was virtual, but was called from parent ctor + ChunkSource* + createChunkSource(); // 4J - was virtual, but was called from parent ctor public: - std::vector > *getTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1); - virtual bool mayInteract(std::shared_ptr player, int xt, int yt, int zt, int id); + std::vector >* getTileEntitiesInRegion( + int x0, int y0, int z0, int x1, int y1, int z1); + virtual bool mayInteract(std::shared_ptr player, int xt, int yt, + int zt, int id); + protected: - virtual void initializeLevel(LevelSettings *settings); - virtual void setInitialSpawn(LevelSettings *settings); - void generateBonusItemsNearSpawn(); // 4J - brought forward from 1.3.2 + virtual void initializeLevel(LevelSettings* settings); + virtual void setInitialSpawn(LevelSettings* settings); + void generateBonusItemsNearSpawn(); // 4J - brought forward from 1.3.2 public: - Pos *getDimensionSpecificSpawn(); + Pos* getDimensionSpecificSpawn(); - void Suspend(); // 4j Added for XboxOne PLM + void Suspend(); // 4j Added for XboxOne PLM - void save(bool force, ProgressListener *progressListener, bool bAutosave=false); - void saveToDisc(ProgressListener *progressListener, bool autosave); // 4J Added + void save(bool force, ProgressListener* progressListener, + bool bAutosave = false); + void saveToDisc(ProgressListener* progressListener, + bool autosave); // 4J Added private: - void saveLevelData(); + void saveLevelData(); - typedef std::unordered_map , IntKeyHash2, IntKeyEq> intEntityMap; - intEntityMap entitiesById; // 4J - was IntHashMap, using same hashing function as this uses + typedef std::unordered_map, IntKeyHash2, + IntKeyEq> + intEntityMap; + intEntityMap entitiesById; // 4J - was IntHashMap, using same hashing + // function as this uses protected: - virtual void entityAdded(std::shared_ptr e); + virtual void entityAdded(std::shared_ptr e); virtual void entityRemoved(std::shared_ptr e); + public: - std::shared_ptr getEntity(int id); + std::shared_ptr getEntity(int id); virtual bool addGlobalEntity(std::shared_ptr e); void broadcastEntityEvent(std::shared_ptr e, uint8_t event); - virtual std::shared_ptr explode(std::shared_ptr source, double x, double y, double z, float r, bool fire, bool destroyBlocks); + virtual std::shared_ptr explode(std::shared_ptr source, + double x, double y, double z, + float r, bool fire, + bool destroyBlocks); virtual void tileEvent(int x, int y, int z, int tile, int b0, int b1); private: - void runTileEvents(); - bool doTileEvent(TileEventData *te); + void runTileEvents(); + bool doTileEvent(TileEventData* te); public: void closeLevelStorage(); + protected: - virtual void tickWeather(); + virtual void tickWeather(); public: - MinecraftServer *getServer(); - EntityTracker *getTracker(); - void setTimeAndAdjustTileTicks(__int64 newTime); - PlayerChunkMap *getChunkMap(); + MinecraftServer* getServer(); + EntityTracker* getTracker(); + void setTimeAndAdjustTileTicks(__int64 newTime); + PlayerChunkMap* getChunkMap(); - void queueSendTileUpdate(int x, int y, int z); // 4J Added + void queueSendTileUpdate(int x, int y, int z); // 4J Added private: - void runQueuedSendTileUpdates();// 4J Added + void runQueuedSendTileUpdates(); // 4J Added - // 4J - added for implementation of finite limit to number of item entities, tnt and falling block entities + // 4J - added for implementation of finite limit to number of item entities, + // tnt and falling block entities public: + static const int MAX_HANGING_ENTITIES = 400; + static const int MAX_ITEM_ENTITIES = 200; + static const int MAX_ARROW_ENTITIES = 200; + static const int MAX_EXPERIENCEORB_ENTITIES = 50; + static const int MAX_PRIMED_TNT = 20; + static const int MAX_FALLING_TILE = 20; - static const int MAX_HANGING_ENTITIES = 400; - static const int MAX_ITEM_ENTITIES = 200; - static const int MAX_ARROW_ENTITIES = 200; - static const int MAX_EXPERIENCEORB_ENTITIES = 50; - static const int MAX_PRIMED_TNT = 20; - static const int MAX_FALLING_TILE = 20; + int m_primedTntCount; + int m_fallingTileCount; + CRITICAL_SECTION m_limiterCS; + std::list > m_itemEntities; + std::list > m_hangingEntities; + std::list > m_arrowEntities; + std::list > m_experienceOrbEntities; - int m_primedTntCount; - int m_fallingTileCount; - CRITICAL_SECTION m_limiterCS; - std::list< std::shared_ptr > m_itemEntities; - std::list< std::shared_ptr > m_hangingEntities; - std::list< std::shared_ptr > m_arrowEntities; - std::list< std::shared_ptr > m_experienceOrbEntities; + virtual bool addEntity(std::shared_ptr e); + void entityAddedExtra(std::shared_ptr e); + void entityRemovedExtra(std::shared_ptr e); - virtual bool addEntity(std::shared_ptr e); - void entityAddedExtra(std::shared_ptr e); - void entityRemovedExtra(std::shared_ptr e); - - virtual bool newPrimedTntAllowed(); - virtual bool newFallingTileAllowed(); + virtual bool newPrimedTntAllowed(); + virtual bool newFallingTileAllowed(); - void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added + void flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound); // 4J added - // 4J added - static const int MAX_UPDATES = 256; + // 4J added + static const int MAX_UPDATES = 256; - // Each of these need to be duplicated for each level in the current game. As we currently only have 2 (over/nether), making this constant - static Level *m_level[3]; - static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; - static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; - static int m_updateChunkCount[3]; - static int m_updateTileX[3][MAX_UPDATES]; - static int m_updateTileY[3][MAX_UPDATES]; - static int m_updateTileZ[3][MAX_UPDATES]; - static int m_updateTileCount[3]; - static int m_randValue[3]; + // Each of these need to be duplicated for each level in the current game. + // As we currently only have 2 (over/nether), making this constant + static Level* m_level[3]; + static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; + static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; + static int m_updateChunkCount[3]; + static int m_updateTileX[3][MAX_UPDATES]; + static int m_updateTileY[3][MAX_UPDATES]; + static int m_updateTileZ[3][MAX_UPDATES]; + static int m_updateTileCount[3]; + static int m_randValue[3]; - static C4JThread::EventArray* m_updateTrigger; - static CRITICAL_SECTION m_updateCS[3]; - - static C4JThread* m_updateThread; - static int runUpdate(void* lpParam); + static C4JThread::EventArray* m_updateTrigger; + static CRITICAL_SECTION m_updateCS[3]; + static C4JThread* m_updateThread; + static int runUpdate(void* lpParam); }; diff --git a/Minecraft.Client/Level/ServerLevelListener.cpp b/Minecraft.Client/Level/ServerLevelListener.cpp index 6705a16fe..0440f6dbc 100644 --- a/Minecraft.Client/Level/ServerLevelListener.cpp +++ b/Minecraft.Client/Level/ServerLevelListener.cpp @@ -11,116 +11,120 @@ #include "../../Minecraft.World/Headers/net.minecraft.network.packet.h" #include "../../Minecraft.World/Level/LevelData.h" - -ServerLevelListener::ServerLevelListener(MinecraftServer *server, ServerLevel *level) -{ - this->server = server; - this->level = level; +ServerLevelListener::ServerLevelListener(MinecraftServer* server, + ServerLevel* level) { + this->server = server; + this->level = level; } -// 4J removed - +// 4J removed - /* -void ServerLevelListener::addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za) +void ServerLevelListener::addParticle(const std::wstring& name, double x, double +y, double z, double xa, double ya, double za) { } */ -void ServerLevelListener::addParticle(ePARTICLE_TYPE name, double x, double y, double z, double xa, double ya, double za) -{ +void ServerLevelListener::addParticle(ePARTICLE_TYPE name, double x, double y, + double z, double xa, double ya, + double za) {} + +void ServerLevelListener::allChanged() {} + +void ServerLevelListener::entityAdded(std::shared_ptr entity) { + MemSect(10); + level->getTracker()->addEntity(entity); + MemSect(0); } -void ServerLevelListener::allChanged() -{ -} - -void ServerLevelListener::entityAdded(std::shared_ptr entity) -{ - MemSect(10); - level->getTracker()->addEntity(entity); - MemSect(0); -} - -void ServerLevelListener::entityRemoved(std::shared_ptr entity) -{ - level->getTracker()->removeEntity(entity); +void ServerLevelListener::entityRemoved(std::shared_ptr entity) { + level->getTracker()->removeEntity(entity); } // 4J added -void ServerLevelListener::playerRemoved(std::shared_ptr entity) -{ - std::shared_ptr player = std::dynamic_pointer_cast(entity); - player->getLevel()->getTracker()->removePlayer(entity); +void ServerLevelListener::playerRemoved(std::shared_ptr entity) { + std::shared_ptr player = + std::dynamic_pointer_cast(entity); + player->getLevel()->getTracker()->removePlayer(entity); } -void ServerLevelListener::playSound(int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist) -{ - if(iSound < 0) - { - app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); - } - else - { - // 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. - // The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay - server->getPlayers()->broadcast(x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::shared_ptr(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); - } +void ServerLevelListener::playSound(int iSound, double x, double y, double z, + float volume, float pitch, + float fClipSoundDist) { + if (iSound < 0) { + app.DebugPrintf( + "ServerLevelListener received request for sound less than 0, so " + "ignoring\n"); + } else { + // 4J-PB - I don't want to broadcast player sounds to my local machine, + // since we're already playing these in the LevelRenderer::playSound. + // The PC version does seem to do this and the result is I can stop + // walking , and then I'll hear my footstep sound with a delay + server->getPlayers()->broadcast( + x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, + std::shared_ptr( + new LevelSoundPacket(iSound, x, y, z, volume, pitch))); + } } -void ServerLevelListener::playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist) -{ - if(iSound < 0) - { - app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); - } - else - { - // 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. - // The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay - std::shared_ptr player= std::dynamic_pointer_cast(entity); - server->getPlayers()->broadcast(player,x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::shared_ptr(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); - } +void ServerLevelListener::playSound(std::shared_ptr entity, int iSound, + double x, double y, double z, float volume, + float pitch, float fClipSoundDist) { + if (iSound < 0) { + app.DebugPrintf( + "ServerLevelListener received request for sound less than 0, so " + "ignoring\n"); + } else { + // 4J-PB - I don't want to broadcast player sounds to my local machine, + // since we're already playing these in the LevelRenderer::playSound. + // The PC version does seem to do this and the result is I can stop + // walking , and then I'll hear my footstep sound with a delay + std::shared_ptr player = + std::dynamic_pointer_cast(entity); + server->getPlayers()->broadcast( + player, x, y, z, volume > 1 ? 16 * volume : 16, + level->dimension->id, + std::shared_ptr( + new LevelSoundPacket(iSound, x, y, z, volume, pitch))); + } } -void ServerLevelListener::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) -{ +void ServerLevelListener::setTilesDirty(int x0, int y0, int z0, int x1, int y1, + int z1, Level* level) {} + +void ServerLevelListener::skyColorChanged() {} + +void ServerLevelListener::tileChanged(int x, int y, int z) { + level->getChunkMap()->tileChanged(x, y, z); } -void ServerLevelListener::skyColorChanged() -{ +void ServerLevelListener::tileLightChanged(int x, int y, int z) {} + +void ServerLevelListener::playStreamingMusic(const std::wstring& name, int x, + int y, int z) {} + +void ServerLevelListener::levelEvent(std::shared_ptr source, int type, + int x, int y, int z, int data) { + server->getPlayers()->broadcast( + source, x, y, z, 64, level->dimension->id, + std::shared_ptr( + new LevelEventPacket(type, x, y, z, data))); } -void ServerLevelListener::tileChanged(int x, int y, int z) -{ - level->getChunkMap()->tileChanged(x, y, z); -} +void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z, + int progress) { + // for (ServerPlayer p : server->getPlayers()->players) + for (AUTO_VAR(it, server->getPlayers()->players.begin()); + it != server->getPlayers()->players.end(); ++it) { + std::shared_ptr p = *it; + if (p == NULL || p->level != level || p->entityId == id) continue; + double xd = (double)x - p->x; + double yd = (double)y - p->y; + double zd = (double)z - p->z; -void ServerLevelListener::tileLightChanged(int x, int y, int z) -{ -} - -void ServerLevelListener::playStreamingMusic(const std::wstring& name, int x, int y, int z) -{ -} - -void ServerLevelListener::levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data) -{ - server->getPlayers()->broadcast(source, x, y, z, 64, level->dimension->id, std::shared_ptr( new LevelEventPacket(type, x, y, z, data) ) ); -} - -void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z, int progress) -{ - //for (ServerPlayer p : server->getPlayers()->players) - for(AUTO_VAR(it, server->getPlayers()->players.begin()); it != server->getPlayers()->players.end(); ++it) - { - std::shared_ptr p = *it; - if (p == NULL || p->level != level || p->entityId == id) continue; - double xd = (double) x - p->x; - double yd = (double) y - p->y; - double zd = (double) z - p->z; - - if (xd * xd + yd * yd + zd * zd < 32 * 32) - { - p->connection->send(std::shared_ptr(new TileDestructionPacket(id, x, y, z, progress))); - } - } + if (xd * xd + yd * yd + zd * zd < 32 * 32) { + p->connection->send(std::shared_ptr( + new TileDestructionPacket(id, x, y, z, progress))); + } + } } \ No newline at end of file diff --git a/Minecraft.Client/Level/ServerLevelListener.h b/Minecraft.Client/Level/ServerLevelListener.h index d5ba2cbc2..6212df1b1 100644 --- a/Minecraft.Client/Level/ServerLevelListener.h +++ b/Minecraft.Client/Level/ServerLevelListener.h @@ -7,27 +7,37 @@ class MinecraftServer; class ServerLevel; // 4J - renamed class to ServerLevelListener to avoid clash with LevelListener -class ServerLevelListener : public LevelListener -{ +class ServerLevelListener : public LevelListener { private: - MinecraftServer *server; - ServerLevel *level; + MinecraftServer* server; + ServerLevel* level; public: - ServerLevelListener(MinecraftServer *server, ServerLevel *level); - // 4J removed - virtual void addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za); - virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z, double xa, double ya, double za); // 4J added + ServerLevelListener(MinecraftServer* server, ServerLevel* level); + // 4J removed - virtual void addParticle(const std::wstring& name, double x, + // double y, double z, double xa, double ya, double za); + virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z, + double xa, double ya, double za); // 4J added virtual void allChanged(); virtual void entityAdded(std::shared_ptr entity); virtual void entityRemoved(std::shared_ptr entity); - virtual void playerRemoved(std::shared_ptr entity); // 4J added - for when a player is removed from the level's player array, not just the entity storage - virtual void playSound(int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist); - virtual void playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist); - virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level); // 4J - added level param + virtual void playerRemoved( + std::shared_ptr + entity); // 4J added - for when a player is removed from the + // level's player array, not just the entity storage + virtual void playSound(int iSound, double x, double y, double z, + float volume, float pitch, float fClipSoundDist); + virtual void playSound(std::shared_ptr entity, int iSound, double x, + double y, double z, float volume, float pitch, + float fClipSoundDist); + virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level); // 4J - added level param virtual void skyColorChanged(); virtual void tileChanged(int x, int y, int z); - virtual void tileLightChanged(int x, int y, int z); - virtual void playStreamingMusic(const std::wstring& name, int x, int y, int z); - virtual void levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data); - virtual void destroyTileProgress(int id, int x, int y, int z, int progress); + virtual void tileLightChanged(int x, int y, int z); + virtual void playStreamingMusic(const std::wstring& name, int x, int y, + int z); + virtual void levelEvent(std::shared_ptr source, int type, int x, + int y, int z, int data); + virtual void destroyTileProgress(int id, int x, int y, int z, int progress); }; diff --git a/Minecraft.Client/Minecraft.cpp b/Minecraft.Client/Minecraft.cpp index d91d0cb4b..96aaafbbd 100644 --- a/Minecraft.Client/Minecraft.cpp +++ b/Minecraft.Client/Minecraft.cpp @@ -73,15 +73,17 @@ #include "Platform/Orbis/Network/PsPlusUpsellWrapper_Orbis.h" #endif -// 4J Turning this on will change the graph at the bottom of the debug overlay to show the number of packets of each type added per fram -//#define DEBUG_RENDER_SHOWS_PACKETS 1 -//#define SPLITSCREEN_TEST +// 4J Turning this on will change the graph at the bottom of the debug overlay +// to show the number of packets of each type added per fram +// #define DEBUG_RENDER_SHOWS_PACKETS 1 +// #define SPLITSCREEN_TEST -// If not disabled, this creates an event queue on a seperate thread so that the Level::tick calls can be offloaded -// from the main thread, and have longer to run, since it's called at 20Hz instead of 60 +// If not disabled, this creates an event queue on a seperate thread so that the +// Level::tick calls can be offloaded from the main thread, and have longer to +// run, since it's called at 20Hz instead of 60 #define DISABLE_LEVELTICK_THREAD -Minecraft *Minecraft::m_instance = NULL; +Minecraft* Minecraft::m_instance = NULL; __int64 Minecraft::frameTimes[512]; __int64 Minecraft::tickTimes[512]; int Minecraft::frameTimePos = 0; @@ -90,161 +92,154 @@ File Minecraft::workDir = File(L""); #ifdef __PSVITA__ -TOUCHSCREENRECT QuickSelectRect[3]= -{ - { 560, 890, 1360, 980 }, - { 450, 840, 1449, 960 }, - { 320, 840, 1600, 970 }, +TOUCHSCREENRECT QuickSelectRect[3] = { + {560, 890, 1360, 980}, + {450, 840, 1449, 960}, + {320, 840, 1600, 970}, }; -int QuickSelectBoxWidth[3]= -{ - 89, - 111, - 142 -}; +int QuickSelectBoxWidth[3] = {89, 111, 142}; #endif -Minecraft::Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet *minecraftApplet, int width, int height, bool fullscreen) -{ - // 4J - added this block of initialisers - gameMode = NULL; - hasCrashed = false; - timer = new Timer(SharedConstants::TICKS_PER_SECOND); - oldLevel = NULL; //4J Stu added - level = NULL; - levels = MultiPlayerLevelArray(3); // 4J Added - levelRenderer = NULL; - player = nullptr; - cameraTargetPlayer = nullptr; - particleEngine = NULL; - user = NULL; - parent = NULL; - pause = false; - textures = NULL; - font = NULL; - screen = NULL; - localPlayerIdx = 0; - rightClickDelay = 0; +Minecraft::Minecraft(Component* mouseComponent, Canvas* parent, + MinecraftApplet* minecraftApplet, int width, int height, + bool fullscreen) { + // 4J - added this block of initialisers + gameMode = NULL; + hasCrashed = false; + timer = new Timer(SharedConstants::TICKS_PER_SECOND); + oldLevel = NULL; // 4J Stu added + level = NULL; + levels = MultiPlayerLevelArray(3); // 4J Added + levelRenderer = NULL; + player = nullptr; + cameraTargetPlayer = nullptr; + particleEngine = NULL; + user = NULL; + parent = NULL; + pause = false; + textures = NULL; + font = NULL; + screen = NULL; + localPlayerIdx = 0; + rightClickDelay = 0; - // 4J Stu Added - InitializeCriticalSection( &ProgressRenderer::s_progress ); - InitializeCriticalSection(&m_setLevelCS); - //m_hPlayerRespawned = CreateEvent(NULL, FALSE, FALSE, NULL); + // 4J Stu Added + InitializeCriticalSection(&ProgressRenderer::s_progress); + InitializeCriticalSection(&m_setLevelCS); + // m_hPlayerRespawned = CreateEvent(NULL, FALSE, FALSE, NULL); - progressRenderer = NULL; - gameRenderer = NULL; - bgLoader = NULL; + progressRenderer = NULL; + gameRenderer = NULL; + bgLoader = NULL; - ticks = 0; - // 4J-PB - moved into the local player - //missTime = 0; - //lastClickTick = 0; - //isRaining = false; - // 4J-PB - end + ticks = 0; + // 4J-PB - moved into the local player + // missTime = 0; + // lastClickTick = 0; + // isRaining = false; + // 4J-PB - end - orgWidth = orgHeight = 0; - achievementPopup = new AchievementPopup(this); - gui = NULL; - noRender = false; - humanoidModel = new HumanoidModel(0); - hitResult = 0; - options = NULL; - soundEngine = new SoundEngine(); - mouseHandler = NULL; - skins = NULL; - workingDirectory = File(L""); - levelSource = NULL; - stats[0] = NULL; - stats[1] = NULL; - stats[2] = NULL; - stats[3] = NULL; - connectToPort = 0; - workDir = File(L""); - // 4J removed - //wasDown = false; - lastTimer = -1; + orgWidth = orgHeight = 0; + achievementPopup = new AchievementPopup(this); + gui = NULL; + noRender = false; + humanoidModel = new HumanoidModel(0); + hitResult = 0; + options = NULL; + soundEngine = new SoundEngine(); + mouseHandler = NULL; + skins = NULL; + workingDirectory = File(L""); + levelSource = NULL; + stats[0] = NULL; + stats[1] = NULL; + stats[2] = NULL; + stats[3] = NULL; + connectToPort = 0; + workDir = File(L""); + // 4J removed + // wasDown = false; + lastTimer = -1; - // 4J removed - //lastTickTime = System::currentTimeMillis(); - recheckPlayerIn = 0; - running = true; - unoccupiedQuadrant = -1; + // 4J removed + // lastTickTime = System::currentTimeMillis(); + recheckPlayerIn = 0; + running = true; + unoccupiedQuadrant = -1; - Stats::init(); + Stats::init(); - orgHeight = height; - this->fullscreen = fullscreen; - this->minecraftApplet = NULL; + orgHeight = height; + this->fullscreen = fullscreen; + this->minecraftApplet = NULL; - this->parent = parent; - // 4J - Our actual physical frame buffer is always 1280x720 ie in a 16:9 ratio. If we want to do a 4:3 mode, we are telling the original minecraft code - // that the width is 3/4 what it actually is, to correctly present a 4:3 image. Have added width_phys and height_phys for any code we add that requires - // to know the real physical dimensions of the frame buffer. - if( RenderManager.IsWidescreen() ) - { - this->width = width; - } - else - { - this->width = (width * 3 ) / 4; - } - this->height = height; - this->width_phys = width; - this->height_phys = height; + this->parent = parent; + // 4J - Our actual physical frame buffer is always 1280x720 ie in a 16:9 + // ratio. If we want to do a 4:3 mode, we are telling the original minecraft + // code that the width is 3/4 what it actually is, to correctly present a + // 4:3 image. Have added width_phys and height_phys for any code we add that + // requires to know the real physical dimensions of the frame buffer. + if (RenderManager.IsWidescreen()) { + this->width = width; + } else { + this->width = (width * 3) / 4; + } + this->height = height; + this->width_phys = width; + this->height_phys = height; - this->fullscreen = fullscreen; + this->fullscreen = fullscreen; - appletMode = false; + appletMode = false; - Minecraft::m_instance = this; - TextureManager::createInstance(); + Minecraft::m_instance = this; + TextureManager::createInstance(); - for(int i=0;isoundEngine->init(NULL); + this->soundEngine->init(NULL); #endif #ifndef DISABLE_LEVELTICK_THREAD - levelTickEventQueue = new C4JThread::EventQueue(levelTickUpdateFunc, levelTickThreadInitFunc, "LevelTick_EventQueuePoll"); - levelTickEventQueue->setProcessor(3); - levelTickEventQueue->setPriority(THREAD_PRIORITY_NORMAL); -#endif // DISABLE_LEVELTICK_THREAD + levelTickEventQueue = + new C4JThread::EventQueue(levelTickUpdateFunc, levelTickThreadInitFunc, + "LevelTick_EventQueuePoll"); + levelTickEventQueue->setProcessor(3); + levelTickEventQueue->setPriority(THREAD_PRIORITY_NORMAL); +#endif // DISABLE_LEVELTICK_THREAD } -void Minecraft::clearConnectionFailed() -{ - for(int i=0;iaddDebugPacks(); - textures = new Textures(skins, options); - //renderLoadingScreen(); + workingDirectory = getWorkingDirectory(); + levelSource = + new McRegionLevelStorageSource(File(workingDirectory, L"saves")); + // levelSource = new MemoryLevelStorageSource(); + options = new Options(this, workingDirectory); + skins = new TexturePackRepository(workingDirectory, this); + skins->addDebugPacks(); + textures = new Textures(skins, options); + // renderLoadingScreen(); - font = new Font(options, L"font/Default.png", textures, false, TN_DEFAULT_FONT, 23, 20, 8, 8, SFontData::Codepoints); - altFont = new Font(options, L"font/alternate.png", textures, false, TN_ALT_FONT, 16, 16, 8, 8); + font = new Font(options, L"font/Default.png", textures, false, + TN_DEFAULT_FONT, 23, 20, 8, 8, SFontData::Codepoints); + altFont = new Font(options, L"font/alternate.png", textures, false, + TN_ALT_FONT, 16, 16, 8, 8); - //if (options.languageCode != null) { - // Language.getInstance().loadLanguage(options.languageCode); - // // font.setEnforceUnicodeSheet("true".equalsIgnoreCase(I18n.get("language.enforceUnicode"))); - // font.setEnforceUnicodeSheet(Language.getInstance().isSelectedLanguageIsUnicode()); - // font.setBidirectional(Language.isBidirectional(options.languageCode)); - //} + // if (options.languageCode != null) { + // Language.getInstance().loadLanguage(options.languageCode); + // // + //font.setEnforceUnicodeSheet("true".equalsIgnoreCase(I18n.get("language.enforceUnicode"))); + // font.setEnforceUnicodeSheet(Language.getInstance().isSelectedLanguageIsUnicode()); + // font.setBidirectional(Language.isBidirectional(options.languageCode)); + // } - // 4J Stu - Not using these any more - //WaterColor::init(textures->loadTexturePixels(L"misc/watercolor.png")); - //GrassColor::init(textures->loadTexturePixels(L"misc/grasscolor.png")); - //FoliageColor::init(textures->loadTexturePixels(L"misc/foliagecolor.png")); + // 4J Stu - Not using these any more + // WaterColor::init(textures->loadTexturePixels(L"misc/watercolor.png")); + // GrassColor::init(textures->loadTexturePixels(L"misc/grasscolor.png")); + // FoliageColor::init(textures->loadTexturePixels(L"misc/foliagecolor.png")); - gameRenderer = new GameRenderer(this); - EntityRenderDispatcher::instance->itemInHandRenderer = new ItemInHandRenderer(this,false); + gameRenderer = new GameRenderer(this); + EntityRenderDispatcher::instance->itemInHandRenderer = + new ItemInHandRenderer(this, false); - for( int i=0 ; i<4 ; ++i ) - stats[i] = new StatsCounter(); + for (int i = 0; i < 4; ++i) stats[i] = new StatsCounter(); - /* 4J - TODO, 4J-JEV: Unnecessary. - Achievements::openInventory->setDescFormatter(NULL); - Achievements.openInventory.setDescFormatter(new DescFormatter(){ - public String format(String i18nValue) { - return String.format(i18nValue, Keyboard.getKeyName(options.keyBuild.key)); - } - }); - */ + /* 4J - TODO, 4J-JEV: Unnecessary. + Achievements::openInventory->setDescFormatter(NULL); + Achievements.openInventory.setDescFormatter(new DescFormatter(){ + public String format(String i18nValue) { + return String.format(i18nValue, Keyboard.getKeyName(options.keyBuild.key)); + } + }); + */ - // 4J-PB - We'll do this in a xui intro - //renderLoadingScreen(); + // 4J-PB - We'll do this in a xui intro + // renderLoadingScreen(); - //Keyboard::create(); - Mouse::create(); -#if 0 // 4J - removed + // Keyboard::create(); + Mouse::create(); +#if 0 // 4J - removed mouseHandler = new MouseHandler(parent); try { Controllers.create(); @@ -364,295 +363,281 @@ void Minecraft::init() } #endif - MemSect(31); - checkGlError(L"Pre startup"); - MemSect(0); + MemSect(31); + checkGlError(L"Pre startup"); + MemSect(0); - // width = Display.getDisplayMode().getWidth(); - // height = Display.getDisplayMode().getHeight(); + // width = Display.getDisplayMode().getWidth(); + // height = Display.getDisplayMode().getHeight(); - glEnable(GL_TEXTURE_2D); - glShadeModel(GL_SMOOTH); - glClearDepth(1.0); - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.1f); - glCullFace(GL_BACK); + glEnable(GL_TEXTURE_2D); + glShadeModel(GL_SMOOTH); + glClearDepth(1.0); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.1f); + glCullFace(GL_BACK); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - MemSect(31); - checkGlError(L"Startup"); - MemSect(0); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + MemSect(31); + checkGlError(L"Startup"); + MemSect(0); - // openGLCapabilities = new OpenGLCapabilities(); // 4J - removed + // openGLCapabilities = new OpenGLCapabilities(); // 4J - removed - levelRenderer = new LevelRenderer(this, textures); - textures->stitch(); + levelRenderer = new LevelRenderer(this, textures); + textures->stitch(); - glViewport(0, 0, width, height); + glViewport(0, 0, width, height); - particleEngine = new ParticleEngine(level, textures); - // try { // 4J - removed try/catch - bgLoader = new BackgroundDownloader(workingDirectory, this); - bgLoader->start(); - // } catch (Exception e) { - // } + particleEngine = new ParticleEngine(level, textures); + // try { // 4J - removed try/catch + bgLoader = new BackgroundDownloader(workingDirectory, this); + bgLoader->start(); + // } catch (Exception e) { + // } - MemSect(31); - checkGlError(L"Post startup"); - MemSect(0); - gui = new Gui(this); + MemSect(31); + checkGlError(L"Post startup"); + MemSect(0); + gui = new Gui(this); - if (connectToIp != L"") // 4J - was NULL comparison - { - // setScreen(new ConnectScreen(this, connectToIp, connectToPort)); // 4J TODO - put back in - } - else - { - setScreen(new TitleScreen()); - } - progressRenderer = new ProgressRenderer(this); + if (connectToIp != L"") // 4J - was NULL comparison + { + // setScreen(new ConnectScreen(this, connectToIp, + // connectToPort)); // 4J TODO - put back in + } else { + setScreen(new TitleScreen()); + } + progressRenderer = new ProgressRenderer(this); - RenderManager.CBuffLockStaticCreations(); + RenderManager.CBuffLockStaticCreations(); } -void Minecraft::renderLoadingScreen() -{ - // 4J Unused - // testing stuff on vita just now +void Minecraft::renderLoadingScreen() { + // 4J Unused + // testing stuff on vita just now #ifdef __PSVITA__ - ScreenSizeCalculator ssc(options, width, height); + ScreenSizeCalculator ssc(options, width, height); - // xxx - RenderManager.StartFrame(); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); - glViewport(0, 0, width, height); - glClearColor(0, 0, 0, 0); + // xxx + RenderManager.StartFrame(); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); + glViewport(0, 0, width, height); + glClearColor(0, 0, 0, 0); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - glDisable(GL_LIGHTING); - glEnable(GL_TEXTURE_2D); - glDisable(GL_FOG); - // xxx - glBindTexture(GL_TEXTURE_2D, textures->loadTexture(TN_MOB_PIG)); - t->begin(); - t->color(0xffffff); - t->vertexUV((float)(0), (float)( height), (float)( 0), (float)( 0), (float)( 0)); - t->vertexUV((float)(width), (float)( height), (float)( 0), (float)( 0), (float)( 0)); - t->vertexUV((float)(width), (float)( 0), (float)( 0), (float)( 0), (float)( 0)); - t->vertexUV((float)(0), (float)( 0), (float)( 0), (float)( 0), (float)( 0)); - t->end(); + glDisable(GL_LIGHTING); + glEnable(GL_TEXTURE_2D); + glDisable(GL_FOG); + // xxx + glBindTexture(GL_TEXTURE_2D, textures->loadTexture(TN_MOB_PIG)); + t->begin(); + t->color(0xffffff); + t->vertexUV((float)(0), (float)(height), (float)(0), (float)(0), + (float)(0)); + t->vertexUV((float)(width), (float)(height), (float)(0), (float)(0), + (float)(0)); + t->vertexUV((float)(width), (float)(0), (float)(0), (float)(0), (float)(0)); + t->vertexUV((float)(0), (float)(0), (float)(0), (float)(0), (float)(0)); + t->end(); - int lw = 256; - int lh = 256; - glColor4f(1, 1, 1, 1); - t->color(0xffffff); - blit((ssc.getWidth() - lw) / 2, (ssc.getHeight() - lh) / 2, 0, 0, lw, lh); - glDisable(GL_LIGHTING); - glDisable(GL_FOG); + int lw = 256; + int lh = 256; + glColor4f(1, 1, 1, 1); + t->color(0xffffff); + blit((ssc.getWidth() - lw) / 2, (ssc.getHeight() - lh) / 2, 0, 0, lw, lh); + glDisable(GL_LIGHTING); + glDisable(GL_FOG); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.1f); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.1f); - Display::swapBuffers(); - // xxx - RenderManager.Present(); + Display::swapBuffers(); + // xxx + RenderManager.Present(); #endif } -void Minecraft::blit(int x, int y, int sx, int sy, int w, int h) -{ - float us = 1 / 256.0f; - float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->vertexUV((float)(x + 0), (float)( y + h), (float)( 0), (float)( (sx + 0) * us), (float)( (sy + h) * vs)); - t->vertexUV((float)(x + w), (float)( y + h), (float)( 0), (float)( (sx + w) * us), (float)( (sy + h) * vs)); - t->vertexUV((float)(x + w), (float)( y + 0), (float)( 0), (float)( (sx + w) * us), (float)( (sy + 0) * vs)); - t->vertexUV((float)(x + 0), (float)( y + 0), (float)( 0), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); - t->end(); +void Minecraft::blit(int x, int y, int sx, int sy, int w, int h) { + float us = 1 / 256.0f; + float vs = 1 / 256.0f; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(0), + (float)((sx + 0) * us), (float)((sy + h) * vs)); + t->vertexUV((float)(x + w), (float)(y + h), (float)(0), + (float)((sx + w) * us), (float)((sy + h) * vs)); + t->vertexUV((float)(x + w), (float)(y + 0), (float)(0), + (float)((sx + w) * us), (float)((sy + 0) * vs)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(0), + (float)((sx + 0) * us), (float)((sy + 0) * vs)); + t->end(); } -File Minecraft::getWorkingDirectory() -{ - if (workDir.getPath().empty()) workDir = getWorkingDirectory(L"4jcraft"); - return workDir; +File Minecraft::getWorkingDirectory() { + if (workDir.getPath().empty()) workDir = getWorkingDirectory(L"4jcraft"); + return workDir; } -File Minecraft::getWorkingDirectory(const std::wstring& applicationName) -{ - // 4J - original version - // 4jcraft: ported to C++ - std::wstring userHome = convStringToWstring(getenv("HOME")); - File *workingDirectory; +File Minecraft::getWorkingDirectory(const std::wstring& applicationName) { + // 4J - original version + // 4jcraft: ported to C++ + std::wstring userHome = convStringToWstring(getenv("HOME")); + File* workingDirectory; #if defined(__linux__) - workingDirectory = new File(userHome, L'.' + applicationName + L'/'); + workingDirectory = new File(userHome, L'.' + applicationName + L'/'); #elif defined(_WINDOWS64) - std::string applicationData = getenv("APPDATA"); - if (!applicationData.empty()) - { - workingDirectory = new File(convStringToWstring(applicationData), L'.' + applicationName + L'/'); - } - else - { - workingDirectory = new File(userHome, L'.' + applicationName + L'/'); - } -//#elif defined(_MACOS) -// workingDirectory = new File(userHome, "Library/Application Support/" + applicationName); + std::string applicationData = getenv("APPDATA"); + if (!applicationData.empty()) { + workingDirectory = new File(convStringToWstring(applicationData), + L'.' + applicationName + L'/'); + } else { + workingDirectory = new File(userHome, L'.' + applicationName + L'/'); + } +// #elif defined(_MACOS) +// workingDirectory = new File(userHome, "Library/Application +//Support/" + applicationName); #else - workingDirectory = new File(userHome, applicationName + L'/'); + workingDirectory = new File(userHome, applicationName + L'/'); #endif - if (!workingDirectory->exists()){ - if (!workingDirectory->mkdirs()) { - app.DebugPrintf("The working directory could not be created"); - assert(0); - //throw new RuntimeException(L"The working directory could not be created: " + workingDirectory); - } - } - return *workingDirectory; + if (!workingDirectory->exists()) { + if (!workingDirectory->mkdirs()) { + app.DebugPrintf("The working directory could not be created"); + assert(0); + // throw new RuntimeException(L"The working directory could not be + // created: " + workingDirectory); + } + } + return *workingDirectory; } -LevelStorageSource *Minecraft::getLevelSource() -{ - return levelSource; +LevelStorageSource* Minecraft::getLevelSource() { return levelSource; } + +void Minecraft::setScreen(Screen* screen) { + if (dynamic_cast(this->screen) != NULL) return; + + if (this->screen != NULL) { + this->screen->removed(); + } + + // 4J Gordon: Do not force a stats save here + /*if (dynamic_cast(screen)!=NULL) + { + stats->forceSend(); + } + stats->forceSave();*/ + + if (screen == NULL && level == NULL) { + screen = new TitleScreen(); + } else if (player != NULL && !ui.GetMenuDisplayed(player->GetXboxPad()) && + player->getHealth() <= 0) { + // screen = new DeathScreen(); + + // 4J Stu - If we exit from the death screen then we are saved as being + // dead. In the Java game when you load the game you are still dead, but + // this is silly so only show the dead screen if we have died during + // gameplay + if (ticks == 0) { + player->respawn(); + } else { + ui.NavigateToScene(player->GetXboxPad(), eUIScene_DeathMenu, NULL); + } + } + + if (dynamic_cast(screen) != NULL) { + options->renderDebug = false; + gui->clearMessages(); + } + + this->screen = screen; + if (screen != NULL) { + // releaseMouse(); // 4J - removed + ScreenSizeCalculator ssc(options, width, height); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + screen->init(this, screenWidth, screenHeight); + noRender = false; + } else { + // grabMouse(); // 4J - removed + } + + // 4J-PB - if a screen has been set, go into menu mode + // it's possible that player doesn't exist here yet + /*if(screen!=NULL) + { + if(player && player->GetXboxPad()!=-1) + { + InputManager.SetMenuDisplayed(player->GetXboxPad(),true); + } + else + { + // set all + //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,true); + } + } + else + { + if(player && player->GetXboxPad()!=-1) + { + InputManager.SetMenuDisplayed(player->GetXboxPad(),false); + } + else + { + //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,false); + } + }*/ } -void Minecraft::setScreen(Screen *screen) -{ - if( dynamic_cast(this->screen) != NULL ) return; - - if (this->screen != NULL) - { - this->screen->removed(); - } - - //4J Gordon: Do not force a stats save here - /*if (dynamic_cast(screen)!=NULL) - { - stats->forceSend(); - } - stats->forceSave();*/ - - if (screen == NULL && level == NULL) - { - screen = new TitleScreen(); - } - else if (player != NULL && !ui.GetMenuDisplayed(player->GetXboxPad()) && player->getHealth() <= 0) - { - //screen = new DeathScreen(); - - // 4J Stu - If we exit from the death screen then we are saved as being dead. In the Java - // game when you load the game you are still dead, but this is silly so only show the dead - // screen if we have died during gameplay - if(ticks==0) - { - player->respawn(); - } - else - { - ui.NavigateToScene(player->GetXboxPad(),eUIScene_DeathMenu,NULL); - } - } - - if (dynamic_cast(screen)!=NULL) - { - options->renderDebug = false; - gui->clearMessages(); - } - - this->screen = screen; - if (screen != NULL) - { - // releaseMouse(); // 4J - removed - ScreenSizeCalculator ssc(options, width, height); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - screen->init(this, screenWidth, screenHeight); - noRender = false; - } - else - { - // grabMouse(); // 4J - removed - } - - // 4J-PB - if a screen has been set, go into menu mode - // it's possible that player doesn't exist here yet - /*if(screen!=NULL) - { - if(player && player->GetXboxPad()!=-1) - { - InputManager.SetMenuDisplayed(player->GetXboxPad(),true); - } - else - { - // set all - //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,true); - } - } - else - { - if(player && player->GetXboxPad()!=-1) - { - InputManager.SetMenuDisplayed(player->GetXboxPad(),false); - } - else - { - //InputManager.SetMenuDisplayed(XUSER_INDEX_ANY,false); - } - }*/ +void Minecraft::checkGlError(const std::wstring& string) { + // 4J - TODO } -void Minecraft::checkGlError(const std::wstring& string) -{ - // 4J - TODO +void Minecraft::destroy() { + // 4J Gordon: Do not force a stats save here + /*stats->forceSend(); + stats->forceSave();*/ + + // 4J - all try/catch/finally things in here removed + // try { + if (this->bgLoader != NULL) { + bgLoader->halt(); + } + // } catch (Exception e) { + // } + + // try { + setLevel(NULL); + // } catch (Throwable e) { + // } + + // try { + MemoryTracker::release(); + // } catch (Throwable e) { + // } + + soundEngine->destroy(); + Mouse::destroy(); + Keyboard::destroy(); + //} finally { + Display::destroy(); + // if (!hasCrashed) System.exit(0); //4J - removed + //} + // System.gc(); // 4J - removed } -void Minecraft::destroy() -{ - //4J Gordon: Do not force a stats save here - /*stats->forceSend(); - stats->forceSave();*/ - - // 4J - all try/catch/finally things in here removed - // try { - if (this->bgLoader != NULL) - { - bgLoader->halt(); - } - // } catch (Exception e) { - // } - - // try { - setLevel(NULL); - // } catch (Throwable e) { - // } - - // try { - MemoryTracker::release(); - // } catch (Throwable e) { - // } - - soundEngine->destroy(); - Mouse::destroy(); - Keyboard::destroy(); - //} finally { - Display::destroy(); - // if (!hasCrashed) System.exit(0); //4J - removed - //} - //System.gc(); // 4J - removed -} - -// 4J-PB - splitting this function into 3 parts, so we can call the middle part from our xbox game loop +// 4J-PB - splitting this function into 3 parts, so we can call the middle part +// from our xbox game loop #if 0 void Minecraft::run() @@ -810,1364 +795,1520 @@ void Minecraft::run() } #endif -void Minecraft::run() -{ - running = true; - // try { // 4J - removed try/catch - init(); - // } catch (Exception e) { - // e.printStackTrace(); - // crash(new CrashReport("Failed to start game", e)); - // return; - // } - // try { // 4J - removed try/catch - } - -// 4J added - Selects which local player is currently active for processing by the existing minecraft code -bool Minecraft::setLocalPlayerIdx(int idx) -{ - localPlayerIdx = idx; - // If the player is not null, but the game mode is then this is just a temp player - // whose only real purpose is to hold the viewport position - if( localplayers[idx] == NULL || localgameModes[idx] == NULL ) return false; - - gameMode = localgameModes[idx]; - player = localplayers[idx]; - cameraTargetPlayer = localplayers[idx]; - gameRenderer->itemInHandRenderer = localitemInHandRenderers[idx]; - level = getLevel( localplayers[idx]->dimension ); - particleEngine->setLevel( level ); - - return true; +void Minecraft::run() { + running = true; + // try { // 4J - removed try/catch + init(); + // } catch (Exception e) { + // e.printStackTrace(); + // crash(new CrashReport("Failed to start game", e)); + // return; + // } + // try { // 4J - removed try/catch } -int Minecraft::getLocalPlayerIdx() -{ - return localPlayerIdx; +// 4J added - Selects which local player is currently active for processing by +// the existing minecraft code +bool Minecraft::setLocalPlayerIdx(int idx) { + localPlayerIdx = idx; + // If the player is not null, but the game mode is then this is just a temp + // player whose only real purpose is to hold the viewport position + if (localplayers[idx] == NULL || localgameModes[idx] == NULL) return false; + + gameMode = localgameModes[idx]; + player = localplayers[idx]; + cameraTargetPlayer = localplayers[idx]; + gameRenderer->itemInHandRenderer = localitemInHandRenderers[idx]; + level = getLevel(localplayers[idx]->dimension); + particleEngine->setLevel(level); + + return true; } -void Minecraft::updatePlayerViewportAssignments() -{ - unoccupiedQuadrant = -1; - // Find out how many viewports we'll be needing - int viewportsRequired = 0; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) viewportsRequired++; - } - if( viewportsRequired == 3 ) viewportsRequired = 4; +int Minecraft::getLocalPlayerIdx() { return localPlayerIdx; } - // Allocate away... - if( viewportsRequired == 1 ) - { - // Single viewport - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; - } - } - else if( viewportsRequired == 2 ) - { - // Split screen - TODO - option for vertical/horizontal split - int found = 0; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) - { - // Primary player settings decide what the mode is - if(app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_SplitScreenVertical)) - { - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_SPLIT_LEFT + found; - } - else - { - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_SPLIT_TOP + found; - } - found++; - } - } - } - else if( viewportsRequired >= 3 ) - { - // Quadrants - this is slightly more complicated. We don't want to move viewports around if we are going from 3 to 4, or 4 to 3 players, - // so persist any allocations for quadrants that already exist. - bool quadrantsAllocated[4] = {false,false,false,false}; +void Minecraft::updatePlayerViewportAssignments() { + unoccupiedQuadrant = -1; + // Find out how many viewports we'll be needing + int viewportsRequired = 0; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) viewportsRequired++; + } + if (viewportsRequired == 3) viewportsRequired = 4; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) - { + // Allocate away... + if (viewportsRequired == 1) { + // Single viewport + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_FULLSCREEN; + } + } else if (viewportsRequired == 2) { + // Split screen - TODO - option for vertical/horizontal split + int found = 0; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) { + // Primary player settings decide what the mode is + if (app.GetGameSettings(ProfileManager.GetPrimaryPad(), + eGameSetting_SplitScreenVertical)) { + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_SPLIT_LEFT + found; + } else { + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_SPLIT_TOP + found; + } + found++; + } + } + } else if (viewportsRequired >= 3) { + // Quadrants - this is slightly more complicated. We don't want to move + // viewports around if we are going from 3 to 4, or 4 to 3 players, so + // persist any allocations for quadrants that already exist. + bool quadrantsAllocated[4] = {false, false, false, false}; - // 4J Stu - If the game hasn't started, ignore current allocations (as the players won't have seen them) - // This fixes an issue with the primary player being the 4th controller quadrant, but ending up in the 3rd viewport. - if(app.GetGameStarted()) - { - if( ( localplayers[i]->m_iScreenSection >= C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT ) && - ( localplayers[i]->m_iScreenSection <= C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT ) ) - { - quadrantsAllocated[localplayers[i]->m_iScreenSection - C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT] = true; - } - } - else - { - // Reset the viewport so that it can be assigned in the next loop - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; - } - } - } + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) { + // 4J Stu - If the game hasn't started, ignore current + // allocations (as the players won't have seen them) This fixes + // an issue with the primary player being the 4th controller + // quadrant, but ending up in the 3rd viewport. + if (app.GetGameStarted()) { + if ((localplayers[i]->m_iScreenSection >= + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT) && + (localplayers[i]->m_iScreenSection <= + C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT)) { + quadrantsAllocated + [localplayers[i]->m_iScreenSection - + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT] = true; + } + } else { + // Reset the viewport so that it can be assigned in the next + // loop + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_FULLSCREEN; + } + } + } - // Found which quadrants are currently in use, now allocate out any spares that are required - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] != NULL ) - { - if( ( localplayers[i]->m_iScreenSection < C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT ) || - ( localplayers[i]->m_iScreenSection > C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT ) ) - { - for( int j = 0; j < 4; j++ ) - { - if( !quadrantsAllocated[j] ) - { - localplayers[i]->m_iScreenSection = C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + j; - quadrantsAllocated[j] = true; - break; - } - } - } - } - } - // If there's an unoccupied quadrant, record which one so we can clear it to black when rendering - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( quadrantsAllocated[i] == false ) - { - unoccupiedQuadrant = i; - } - } - } + // Found which quadrants are currently in use, now allocate out any + // spares that are required + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] != NULL) { + if ((localplayers[i]->m_iScreenSection < + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT) || + (localplayers[i]->m_iScreenSection > + C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT)) { + for (int j = 0; j < 4; j++) { + if (!quadrantsAllocated[j]) { + localplayers[i]->m_iScreenSection = + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + j; + quadrantsAllocated[j] = true; + break; + } + } + } + } + } + // If there's an unoccupied quadrant, record which one so we can clear + // it to black when rendering + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (quadrantsAllocated[i] == false) { + unoccupiedQuadrant = i; + } + } + } - // 4J Stu - If the game is not running we do not want to do this yet, and should wait until the task - // that caused the app to not be running is finished - if(app.GetGameStarted())ui.UpdatePlayerBasePositions(); + // 4J Stu - If the game is not running we do not want to do this yet, and + // should wait until the task that caused the app to not be running is + // finished + if (app.GetGameStarted()) ui.UpdatePlayerBasePositions(); } -// Add a temporary player so that the viewports get re-arranged, and add the player to the game session -bool Minecraft::addLocalPlayer(int idx) -{ - //int iLocalPlayerC=app.GetLocalPlayerCount(); - if( m_pendingLocalConnections[idx] != NULL ) - { - // 4J Stu - Should we ever be in a state where this happens? - assert(false); - m_pendingLocalConnections[idx]->close(); - } - m_connectionFailed[idx] = false; - m_pendingLocalConnections[idx] = NULL; +// Add a temporary player so that the viewports get re-arranged, and add the +// player to the game session +bool Minecraft::addLocalPlayer(int idx) { + // int iLocalPlayerC=app.GetLocalPlayerCount(); + if (m_pendingLocalConnections[idx] != NULL) { + // 4J Stu - Should we ever be in a state where this happens? + assert(false); + m_pendingLocalConnections[idx]->close(); + } + m_connectionFailed[idx] = false; + m_pendingLocalConnections[idx] = NULL; - bool success=g_NetworkManager.AddLocalPlayerByUserIndex(idx); + bool success = g_NetworkManager.AddLocalPlayerByUserIndex(idx); - if(success) - { - app.DebugPrintf("Adding temp local player on pad %d\n", idx); - localplayers[idx] = std::shared_ptr( new MultiplayerLocalPlayer(this, level, user, NULL ) ); - localgameModes[idx] = NULL; + if (success) { + app.DebugPrintf("Adding temp local player on pad %d\n", idx); + localplayers[idx] = std::shared_ptr( + new MultiplayerLocalPlayer(this, level, user, NULL)); + localgameModes[idx] = NULL; - updatePlayerViewportAssignments(); + updatePlayerViewportAssignments(); #ifdef _XBOX - // tell the xui scenes a splitscreen player joined - XUIMessage xuiMsg; - CustomMessage_Splitscreenplayer_Struct myMsgData; - CustomMessage_Splitscreenplayer( &xuiMsg, &myMsgData, true); + // tell the xui scenes a splitscreen player joined + XUIMessage xuiMsg; + CustomMessage_Splitscreenplayer_Struct myMsgData; + CustomMessage_Splitscreenplayer(&xuiMsg, &myMsgData, true); - // send the message - for(int i=0;iiPad = idx; - param->stringId = IDS_PROGRESS_CONNECTING; - param->showTooltips = true; - param->setFailTimer = true; - param->timerTime = CONNECTING_PROGRESS_CHECK_TIME; + ConnectionProgressParams* param = new ConnectionProgressParams(); + param->iPad = idx; + param->stringId = IDS_PROGRESS_CONNECTING; + param->showTooltips = true; + param->setFailTimer = true; + param->timerTime = CONNECTING_PROGRESS_CHECK_TIME; - // Joining as second player so always the small progress - ui.NavigateToScene(idx, eUIScene_ConnectingProgress, param); + // Joining as second player so always the small progress + ui.NavigateToScene(idx, eUIScene_ConnectingProgress, param); - } - else - { - app.DebugPrintf("g_NetworkManager.AddLocalPlayerByUserIndex failed\n"); + } else { + app.DebugPrintf("g_NetworkManager.AddLocalPlayerByUserIndex failed\n"); #ifdef _DURANGO - ProfileManager.RemoveGamepadFromGame(idx); + ProfileManager.RemoveGamepadFromGame(idx); #endif - } + } - return success; + return success; } -void Minecraft::addPendingLocalConnection(int idx, ClientConnection *connection) -{ - m_pendingLocalConnections[idx] = connection; +void Minecraft::addPendingLocalConnection(int idx, + ClientConnection* connection) { + m_pendingLocalConnections[idx] = connection; } -std::shared_ptr Minecraft::createExtraLocalPlayer(int idx, const std::wstring& name, int iPad, int iDimension, ClientConnection *clientConnection /*= NULL*/,MultiPlayerLevel *levelpassedin) -{ - if( clientConnection == NULL) return nullptr; +std::shared_ptr Minecraft::createExtraLocalPlayer( + int idx, const std::wstring& name, int iPad, int iDimension, + ClientConnection* clientConnection /*= NULL*/, + MultiPlayerLevel* levelpassedin) { + if (clientConnection == NULL) return nullptr; - if( clientConnection == m_pendingLocalConnections[idx] ) - { - int tempScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; - if( localplayers[idx] != NULL && localgameModes[idx] == NULL ) - { - // A temp player displaying a connecting screen - tempScreenSection = localplayers[idx]->m_iScreenSection; - } - std::wstring prevname = user->name; - user->name = name; + if (clientConnection == m_pendingLocalConnections[idx]) { + int tempScreenSection = C4JRender::VIEWPORT_TYPE_FULLSCREEN; + if (localplayers[idx] != NULL && localgameModes[idx] == NULL) { + // A temp player displaying a connecting screen + tempScreenSection = localplayers[idx]->m_iScreenSection; + } + std::wstring prevname = user->name; + user->name = name; - // Don't need this any more - m_pendingLocalConnections[idx] = NULL; + // Don't need this any more + m_pendingLocalConnections[idx] = NULL; - // Add the connection to the level which will now take responsibility for ticking it - // 4J-PB - can't use the dimension from localplayers[idx], since there may be no localplayers at this point - //MultiPlayerLevel *mpLevel = (MultiPlayerLevel *)getLevel( localplayers[idx]->dimension ); + // Add the connection to the level which will now take responsibility + // for ticking it 4J-PB - can't use the dimension from + // localplayers[idx], since there may be no localplayers at this point + // MultiPlayerLevel *mpLevel = (MultiPlayerLevel *)getLevel( + // localplayers[idx]->dimension ); - MultiPlayerLevel *mpLevel; + MultiPlayerLevel* mpLevel; - if(levelpassedin) - { - level=levelpassedin; - mpLevel=levelpassedin; - } - else - { - level=getLevel( iDimension ); - mpLevel = getLevel( iDimension ); - mpLevel->addClientConnection( clientConnection ); - } + if (levelpassedin) { + level = levelpassedin; + mpLevel = levelpassedin; + } else { + level = getLevel(iDimension); + mpLevel = getLevel(iDimension); + mpLevel->addClientConnection(clientConnection); + } - if( app.GetTutorialMode() ) - { - localgameModes[idx] = new FullTutorialMode(idx, this, clientConnection); - } - // check if we're in the trial version - else if(ProfileManager.IsFullVersion()==false) - { - localgameModes[idx] = new TrialMode(idx, this, clientConnection); - } - else - { - localgameModes[idx] = new ConsoleGameMode(idx, this, clientConnection); - } + if (app.GetTutorialMode()) { + localgameModes[idx] = + new FullTutorialMode(idx, this, clientConnection); + } + // check if we're in the trial version + else if (ProfileManager.IsFullVersion() == false) { + localgameModes[idx] = new TrialMode(idx, this, clientConnection); + } else { + localgameModes[idx] = + new ConsoleGameMode(idx, this, clientConnection); + } - // 4J-PB - can't do this here because they use a render context, but this is running from a thread. - // Moved the creation of these into the main thread, before level launch - //localitemInHandRenderers[idx] = new ItemInHandRenderer(this); - localplayers[idx] = localgameModes[idx]->createPlayer(level); + // 4J-PB - can't do this here because they use a render context, but + // this is running from a thread. Moved the creation of these into the + // main thread, before level launch + // localitemInHandRenderers[idx] = new ItemInHandRenderer(this); + localplayers[idx] = localgameModes[idx]->createPlayer(level); - PlayerUID playerXUIDOffline = INVALID_XUID; - PlayerUID playerXUIDOnline = INVALID_XUID; - ProfileManager.GetXUID(idx,&playerXUIDOffline,false); - ProfileManager.GetXUID(idx,&playerXUIDOnline,true); - localplayers[idx]->setXuid(playerXUIDOffline); - localplayers[idx]->setOnlineXuid(playerXUIDOnline); - localplayers[idx]->setIsGuest(ProfileManager.IsGuest(idx)); + PlayerUID playerXUIDOffline = INVALID_XUID; + PlayerUID playerXUIDOnline = INVALID_XUID; + ProfileManager.GetXUID(idx, &playerXUIDOffline, false); + ProfileManager.GetXUID(idx, &playerXUIDOnline, true); + localplayers[idx]->setXuid(playerXUIDOffline); + localplayers[idx]->setOnlineXuid(playerXUIDOnline); + localplayers[idx]->setIsGuest(ProfileManager.IsGuest(idx)); - localplayers[idx]->displayName = ProfileManager.GetDisplayName(idx); + localplayers[idx]->displayName = ProfileManager.GetDisplayName(idx); - localplayers[idx]->m_iScreenSection = tempScreenSection; + localplayers[idx]->m_iScreenSection = tempScreenSection; - if( levelpassedin == NULL) level->addEntity(localplayers[idx]); // Don't add if we're passing the level in, we only do this from the client connection & we'll be handling adding it ourselves + if (levelpassedin == NULL) + level->addEntity( + localplayers[idx]); // Don't add if we're passing the level in, + // we only do this from the client + // connection & we'll be handling adding it + // ourselves - localplayers[idx]->SetXboxPad(iPad); + localplayers[idx]->SetXboxPad(iPad); - if( localplayers[idx]->input != NULL ) delete localplayers[idx]->input; - localplayers[idx]->input = new Input(); + if (localplayers[idx]->input != NULL) delete localplayers[idx]->input; + localplayers[idx]->input = new Input(); - localplayers[idx]->resetPos(); + localplayers[idx]->resetPos(); - levelRenderer->setLevel(idx, level); - localplayers[idx]->level = level; + levelRenderer->setLevel(idx, level); + localplayers[idx]->level = level; - user->name = prevname; + user->name = prevname; - updatePlayerViewportAssignments(); + updatePlayerViewportAssignments(); - // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players are spawned at incorrect places after re-joining previously saved and loaded "Mass Effect World". - // Move this check to ClientConnection::handleMovePlayer -// // 4J-PB - can't call this when this function is called from the qnet thread (GetGameStarted will be false) -// if(app.GetGameStarted()) -// { -// ui.CloseUIScenes(idx); -// } - } + // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players + // are spawned at incorrect places after re-joining previously saved and + // loaded "Mass Effect World". Move this check to + // ClientConnection::handleMovePlayer + // // 4J-PB - can't call this when this function is called + //from the qnet thread (GetGameStarted will be false) + // if(app.GetGameStarted()) + // { + // ui.CloseUIScenes(idx); + // } + } - return localplayers[idx]; + return localplayers[idx]; } // on a respawn of the local player, just store them -void Minecraft::storeExtraLocalPlayer(int idx) -{ - localplayers[idx] = player; +void Minecraft::storeExtraLocalPlayer(int idx) { + localplayers[idx] = player; - if( localplayers[idx]->input != NULL ) delete localplayers[idx]->input; - localplayers[idx]->input = new Input(); + if (localplayers[idx]->input != NULL) delete localplayers[idx]->input; + localplayers[idx]->input = new Input(); - if(ProfileManager.IsSignedIn(idx)) - { - localplayers[idx]->name = convStringToWstring( ProfileManager.GetGamertag(idx) ); - } + if (ProfileManager.IsSignedIn(idx)) { + localplayers[idx]->name = + convStringToWstring(ProfileManager.GetGamertag(idx)); + } } -void Minecraft::removeLocalPlayerIdx(int idx) -{ - bool updateXui = true; - if(localgameModes[idx] != NULL) - { - if( getLevel( localplayers[idx]->dimension )->isClientSide ) - { - std::shared_ptr mplp = localplayers[idx]; - ( (MultiPlayerLevel *)getLevel( localplayers[idx]->dimension ) )->removeClientConnection(mplp->connection, true); - delete mplp->connection; - mplp->connection = NULL; - g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); - } - getLevel( localplayers[idx]->dimension )->removeEntity(localplayers[idx]); +void Minecraft::removeLocalPlayerIdx(int idx) { + bool updateXui = true; + if (localgameModes[idx] != NULL) { + if (getLevel(localplayers[idx]->dimension)->isClientSide) { + std::shared_ptr mplp = localplayers[idx]; + ((MultiPlayerLevel*)getLevel(localplayers[idx]->dimension)) + ->removeClientConnection(mplp->connection, true); + delete mplp->connection; + mplp->connection = NULL; + g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); + } + getLevel(localplayers[idx]->dimension)->removeEntity(localplayers[idx]); #ifdef _XBOX - // 4J Stu - Fix for #12368 - Crash: Game crashes when saving then exiting and selecting to save - app.TutorialSceneNavigateBack(idx); + // 4J Stu - Fix for #12368 - Crash: Game crashes when saving then + // exiting and selecting to save + app.TutorialSceneNavigateBack(idx); #endif - // 4J Stu - Fix for #13257 - CRASH: Gameplay: Title crashed after exiting the tutorial - // It doesn't matter if they were in the tutorial already - playerLeftTutorial( idx ); + // 4J Stu - Fix for #13257 - CRASH: Gameplay: Title crashed after + // exiting the tutorial It doesn't matter if they were in the tutorial + // already + playerLeftTutorial(idx); - delete localgameModes[idx]; - localgameModes[idx] = NULL; - } - else if( m_pendingLocalConnections[idx] != NULL ) - { - m_pendingLocalConnections[idx]->sendAndDisconnect( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) );; - delete m_pendingLocalConnections[idx]; - m_pendingLocalConnections[idx] = NULL; - g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); - } - else - { - // Not sure how this works on qnet, but for other platforms, calling RemoveLocalPlayerByUserIndex won't do anything if there isn't a local user to remove - // Now just updating the UI directly in this case + delete localgameModes[idx]; + localgameModes[idx] = NULL; + } else if (m_pendingLocalConnections[idx] != NULL) { + m_pendingLocalConnections[idx]->sendAndDisconnect( + std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting))); + ; + delete m_pendingLocalConnections[idx]; + m_pendingLocalConnections[idx] = NULL; + g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); + } else { + // Not sure how this works on qnet, but for other platforms, calling + // RemoveLocalPlayerByUserIndex won't do anything if there isn't a local + // user to remove Now just updating the UI directly in this case #ifdef _XBOX - // 4J Stu - A signout early in the game creation before this player has connected to the game server - updateXui = false; + // 4J Stu - A signout early in the game creation before this player has + // connected to the game server + updateXui = false; #endif - // 4J Stu - Adding this back in for exactly the reason my comment above suggests it was added in the first place + // 4J Stu - Adding this back in for exactly the reason my comment above + // suggests it was added in the first place #ifdef _XBOX_ONE - g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); + g_NetworkManager.RemoveLocalPlayerByUserIndex(idx); #endif - } - localplayers[idx] = nullptr; + } + localplayers[idx] = nullptr; - if( idx == ProfileManager.GetPrimaryPad() ) - { - // We should never try to remove the Primary player in this way - assert(false); - /* - // If we are removing the primary player then there can't be a valid gamemode left anymore, this - // pointer will be referring to the one we've just deleted - gameMode = NULL; - // Remove references to player - player = NULL; - cameraTargetPlayer = NULL; - EntityRenderDispatcher::instance->cameraEntity = NULL; - TileEntityRenderDispatcher::instance->cameraEntity = NULL; - */ - } - else if( updateXui ) - { - gameRenderer->DisableUpdateThread(); - levelRenderer->setLevel(idx, NULL); - gameRenderer->EnableUpdateThread(); - ui.CloseUIScenes(idx,true); - updatePlayerViewportAssignments(); - } + if (idx == ProfileManager.GetPrimaryPad()) { + // We should never try to remove the Primary player in this way + assert(false); + /* + // If we are removing the primary player then there can't be a valid + gamemode left anymore, this + // pointer will be referring to the one we've just deleted + gameMode = NULL; + // Remove references to player + player = NULL; + cameraTargetPlayer = NULL; + EntityRenderDispatcher::instance->cameraEntity = NULL; + TileEntityRenderDispatcher::instance->cameraEntity = NULL; + */ + } else if (updateXui) { + gameRenderer->DisableUpdateThread(); + levelRenderer->setLevel(idx, NULL); + gameRenderer->EnableUpdateThread(); + ui.CloseUIScenes(idx, true); + updatePlayerViewportAssignments(); + } - // We only create these once ever so don't delete it here - //delete localitemInHandRenderers[idx]; + // We only create these once ever so don't delete it here + // delete localitemInHandRenderers[idx]; } -void Minecraft::createPrimaryLocalPlayer(int iPad) -{ - localgameModes[iPad] = gameMode; - localplayers[iPad] = player; - //gameRenderer->itemInHandRenderer = localitemInHandRenderers[iPad]; - // Give them the gamertag if they're signed in - if(ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) - { - user->name = convStringToWstring( ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad()) ); - } +void Minecraft::createPrimaryLocalPlayer(int iPad) { + localgameModes[iPad] = gameMode; + localplayers[iPad] = player; + // gameRenderer->itemInHandRenderer = localitemInHandRenderers[iPad]; + // Give them the gamertag if they're signed in + if (ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) { + user->name = convStringToWstring( + ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad())); + } } -void Minecraft::run_middle() -{ - static __int64 lastTime = 0; - static bool bFirstTimeIntoGame = true; - static bool bAutosaveTimerSet=false; - static unsigned int uiAutosaveTimer=0; - static int iFirstTimeCountdown=60; - if( lastTime == 0 ) lastTime = System::nanoTime(); - static int frames = 0; +void Minecraft::run_middle() { + static __int64 lastTime = 0; + static bool bFirstTimeIntoGame = true; + static bool bAutosaveTimerSet = false; + static unsigned int uiAutosaveTimer = 0; + static int iFirstTimeCountdown = 60; + if (lastTime == 0) lastTime = System::nanoTime(); + static int frames = 0; - EnterCriticalSection(&m_setLevelCS); + EnterCriticalSection(&m_setLevelCS); - if(running) - { - if (reloadTextures) - { - reloadTextures = false; - textures->reloadAll(); - } + if (running) { + if (reloadTextures) { + reloadTextures = false; + textures->reloadAll(); + } - //while (running) - { - // try { // 4J - removed try/catch - // if (minecraftApplet != null && !minecraftApplet.isActive()) break; // 4J - removed - AABB::resetPool(); - Vec3::resetPool(); + // while (running) + { + // try { // 4J - removed try/catch + // if (minecraftApplet != null && + // !minecraftApplet.isActive()) break; // 4J - removed + AABB::resetPool(); + Vec3::resetPool(); - // if (parent == NULL && Display.isCloseRequested()) { // 4J - removed - // stop(); - // } + // if (parent == NULL && Display.isCloseRequested()) { + // // 4J - removed + // stop(); + // } - // 4J-PB - AUTOSAVE TIMER - only in the full game and if the player is the host - if(level!=NULL && ProfileManager.IsFullVersion() && g_NetworkManager.IsHost()) - { - /*if(!bAutosaveTimerSet) - { - // set the timer - bAutosaveTimerSet=true; + // 4J-PB - AUTOSAVE TIMER - only in the full game and if the player + // is the host + if (level != NULL && ProfileManager.IsFullVersion() && + g_NetworkManager.IsHost()) { + /*if(!bAutosaveTimerSet) + { + // set the timer + bAutosaveTimerSet=true; - app.SetAutosaveTimerTime(); - } - else*/ - { - // if the pause menu is up for the primary player, don't autosave - // If saving isn't disabled, and the main player has a app action running , or has any crafting or containers open, don't autosave - if(!StorageManager.GetSaveDisabled() && (app.GetXuiAction(ProfileManager.GetPrimaryPad())==eAppAction_Idle) ) - { - if(!ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()) && !ui.IsIgnoreAutosaveMenuDisplayed(ProfileManager.GetPrimaryPad())) - { - // check if the autotimer countdown has reached zero - unsigned char ucAutosaveVal=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_Autosave); - bool bTrialTexturepack=false; - if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) - { - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; + app.SetAutosaveTimerTime(); + } + else*/ + { + // if the pause menu is up for the primary player, don't + // autosave If saving isn't disabled, and the main player + // has a app action running , or has any crafting or + // containers open, don't autosave + if (!StorageManager.GetSaveDisabled() && + (app.GetXuiAction(ProfileManager.GetPrimaryPad()) == + eAppAction_Idle)) { + if (!ui.IsPauseMenuDisplayed( + ProfileManager.GetPrimaryPad()) && + !ui.IsIgnoreAutosaveMenuDisplayed( + ProfileManager.GetPrimaryPad())) { + // check if the autotimer countdown has reached zero + unsigned char ucAutosaveVal = app.GetGameSettings( + ProfileManager.GetPrimaryPad(), + eGameSetting_Autosave); + bool bTrialTexturepack = false; + if (!Minecraft::GetInstance() + ->skins->isUsingDefaultSkin()) { + TexturePack* tPack = Minecraft::GetInstance() + ->skins->getSelected(); + DLCTexturePack* pDLCTexPack = + (DLCTexturePack*)tPack; - DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack(); + DLCPack* pDLCPack = + pDLCTexPack->getDLCInfoParentPack(); - if( pDLCPack ) - { - if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { - bTrialTexturepack=true; - } - } - } + if (pDLCPack) { + if (!pDLCPack->hasPurchasedFile( + DLCManager::e_DLCType_Texture, + L"")) { + bTrialTexturepack = true; + } + } + } - // If the autosave value is not zero, and the player isn't using a trial texture pack, then check whether we need to save this tick - if((ucAutosaveVal!=0) && !bTrialTexturepack) - { - if(app.AutosaveDue()) - { - // disable the autosave countdown - ui.ShowAutosaveCountdownTimer(false); + // If the autosave value is not zero, and the player + // isn't using a trial texture pack, then check + // whether we need to save this tick + if ((ucAutosaveVal != 0) && !bTrialTexturepack) { + if (app.AutosaveDue()) { + // disable the autosave countdown + ui.ShowAutosaveCountdownTimer(false); - // Need to save now - app.DebugPrintf("+++++++++++\n"); - app.DebugPrintf("+++Autosave\n"); - app.DebugPrintf("+++++++++++\n"); - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_AutosaveSaveGame); - //app.SetAutosaveTimerTime(); + // Need to save now + app.DebugPrintf("+++++++++++\n"); + app.DebugPrintf("+++Autosave\n"); + app.DebugPrintf("+++++++++++\n"); + app.SetAction( + ProfileManager.GetPrimaryPad(), + eAppAction_AutosaveSaveGame); + // app.SetAutosaveTimerTime(); #ifndef _CONTENT_PACKAGE - { - // print the time - SYSTEMTIME UTCSysTime; - GetSystemTime( &UTCSysTime ); - //char szTime[15]; + { + // print the time + SYSTEMTIME UTCSysTime; + GetSystemTime(&UTCSysTime); + // char szTime[15]; - app.DebugPrintf("%02d:%02d:%02d\n",UTCSysTime.wHour,UTCSysTime.wMinute,UTCSysTime.wSecond); - } + app.DebugPrintf("%02d:%02d:%02d\n", + UTCSysTime.wHour, + UTCSysTime.wMinute, + UTCSysTime.wSecond); + } #endif - } - else - { - unsigned int uiTimeToAutosave=app.SecondsToAutosave(); + } else { + unsigned int uiTimeToAutosave = + app.SecondsToAutosave(); - if(uiTimeToAutosave<6) - { - ui.ShowAutosaveCountdownTimer(true); - ui.UpdateAutosaveCountdownTimer(uiTimeToAutosave); - } - } - } - } - else - { - // disable the autosave countdown - ui.ShowAutosaveCountdownTimer(false); - } - } - } - } + if (uiTimeToAutosave < 6) { + ui.ShowAutosaveCountdownTimer(true); + ui.UpdateAutosaveCountdownTimer( + uiTimeToAutosave); + } + } + } + } else { + // disable the autosave countdown + ui.ShowAutosaveCountdownTimer(false); + } + } + } + } - // 4J-PB - Once we're in the level, check if the players have the level in their banned list and ask if they want to play it - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( localplayers[i] && (app.GetBanListCheck(i)==false) && !Minecraft::GetInstance()->isTutorial() && ProfileManager.IsSignedInLive(i) && !ProfileManager.IsGuest(i) ) - { - // If there is a sys ui displayed, we can't display the message box here, so ignore until we can - if(!ProfileManager.IsSystemUIDisplayed()) - { - app.SetBanListCheck(i,true); - // 4J-PB - check if the level is in the banned level list - // get the unique save name and xuid from whoever is the host + // 4J-PB - Once we're in the level, check if the players have the + // level in their banned list and ask if they want to play it + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] && (app.GetBanListCheck(i) == false) && + !Minecraft::GetInstance()->isTutorial() && + ProfileManager.IsSignedInLive(i) && + !ProfileManager.IsGuest(i)) { + // If there is a sys ui displayed, we can't display the + // message box here, so ignore until we can + if (!ProfileManager.IsSystemUIDisplayed()) { + app.SetBanListCheck(i, true); + // 4J-PB - check if the level is in the banned level + // list get the unique save name and xuid from whoever + // is the host #if defined _XBOX || defined _XBOX_ONE - INetworkPlayer *pHostPlayer = g_NetworkManager.GetHostPlayer(); + INetworkPlayer* pHostPlayer = + g_NetworkManager.GetHostPlayer(); #ifdef _XBOX - PlayerUID xuid=((NetworkPlayerXbox *)pHostPlayer)->GetUID(); + PlayerUID xuid = + ((NetworkPlayerXbox*)pHostPlayer)->GetUID(); #else - PlayerUID xuid=pHostPlayer->GetUID(); + PlayerUID xuid = pHostPlayer->GetUID(); #endif - if(app.IsInBannedLevelList(i,xuid,app.GetUniqueMapName())) - { - // put up a message box asking if the player would like to unban this level - app.DebugPrintf("This level is banned\n"); - // set the app action to bring up the message box to give them the option to remove from the ban list or exit the level - app.SetAction(i,eAppAction_LevelInBanLevelList,(void *)TRUE); - } + if (app.IsInBannedLevelList(i, xuid, + app.GetUniqueMapName())) { + // put up a message box asking if the player would + // like to unban this level + app.DebugPrintf("This level is banned\n"); + // set the app action to bring up the message box to + // give them the option to remove from the ban list + // or exit the level + app.SetAction(i, eAppAction_LevelInBanLevelList, + (void*)TRUE); + } #endif - } - } - } + } + } + } - if(!ProfileManager.IsSystemUIDisplayed() && app.DLCInstallProcessCompleted() && !app.DLCInstallPending() && app.m_dlcManager.NeedsCorruptCheck() ) - { - app.m_dlcManager.checkForCorruptDLCAndAlert(); - } + if (!ProfileManager.IsSystemUIDisplayed() && + app.DLCInstallProcessCompleted() && !app.DLCInstallPending() && + app.m_dlcManager.NeedsCorruptCheck()) { + app.m_dlcManager.checkForCorruptDLCAndAlert(); + } - // When we go into the first loaded level, check if the console has active joypads that are not in the game, and bring up the quadrant display to remind them to press start (if the session has space) - if(level!=NULL && bFirstTimeIntoGame && g_NetworkManager.SessionHasSpace()) - { - // have a short delay before the display - if(iFirstTimeCountdown==0) - { - bFirstTimeIntoGame=false; + // When we go into the first loaded level, check if the console has + // active joypads that are not in the game, and bring up the + // quadrant display to remind them to press start (if the session + // has space) + if (level != NULL && bFirstTimeIntoGame && + g_NetworkManager.SessionHasSpace()) { + // have a short delay before the display + if (iFirstTimeCountdown == 0) { + bFirstTimeIntoGame = false; - if(app.IsLocalMultiplayerAvailable()) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if((localplayers[i] == NULL) && InputManager.IsPadConnected(i)) - { - if(!ui.PressStartPlaying(i)) - { - ui.ShowPressStart(i); - } - } - } - } - } - else iFirstTimeCountdown--; - } - // 4J-PB - store any button toggles for the players, since the minecraft::tick may not be called if we're running fast, and a button press and release will be missed + if (app.IsLocalMultiplayerAvailable()) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if ((localplayers[i] == NULL) && + InputManager.IsPadConnected(i)) { + if (!ui.PressStartPlaying(i)) { + ui.ShowPressStart(i); + } + } + } + } + } else + iFirstTimeCountdown--; + } + // 4J-PB - store any button toggles for the players, since the + // minecraft::tick may not be called if we're running fast, and a + // button press and release will be missed - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { #ifdef __ORBIS__ - if ( m_pPsPlusUpsell != NULL && m_pPsPlusUpsell->hasResponse() && m_pPsPlusUpsell->m_userIndex == i ) - { - delete m_pPsPlusUpsell; - m_pPsPlusUpsell = NULL; - - if ( ProfileManager.HasPlayStationPlus(i) ) - { - app.DebugPrintf(" Player_%i is now authorised for PsPlus.\n", i); - if (!ui.PressStartPlaying(i)) ui.ShowPressStart(i); - } - else - { - unsigned int uiIDA[1] = { IDS_OK }; - ui.RequestMessageBox( IDS_CANTJOIN_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA, 1, i, NULL, NULL, app.GetStringTable() ); - } - } - else -#endif - if(localplayers[i]) - { - // 4J-PB - add these to check for coming out of idle - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_JUMP)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<hasResponse() && + m_pPsPlusUpsell->m_userIndex == i) { + delete m_pPsPlusUpsell; + m_pPsPlusUpsell = NULL; - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_INVENTORY)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL< Player_%i is now authorised for " + "PsPlus.\n", + i); + if (!ui.PressStartPlaying(i)) ui.ShowPressStart(i); + } else { + unsigned int uiIDA[1] = {IDS_OK}; + ui.RequestMessageBox( + IDS_CANTJOIN_TITLE, IDS_NO_PLAYSTATIONPLUS, uiIDA, + 1, i, NULL, NULL, app.GetStringTable()); + } + } else +#endif + if (localplayers[i]) { + // 4J-PB - add these to check for coming out of idle + if (InputManager.ButtonPressed(i, MINECRAFT_ACTION_JUMP)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_JUMP; + if (InputManager.ButtonPressed(i, MINECRAFT_ACTION_USE)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_USE; + + if (InputManager.ButtonPressed(i, + MINECRAFT_ACTION_INVENTORY)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_INVENTORY; + if (InputManager.ButtonPressed(i, MINECRAFT_ACTION_ACTION)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_ACTION; + if (InputManager.ButtonPressed(i, + MINECRAFT_ACTION_CRAFTING)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_CRAFTING; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_PAUSEMENU)) { + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_PAUSEMENU; + app.DebugPrintf( + "PAUSE PRESSED - ipad = %d, Storing press\n", i); + } #ifdef _DURANGO - if(InputManager.ButtonPressed(i, ACTION_MENU_GTC_PAUSE)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed |= + 1LL << ACTION_MENU_GTC_PAUSE; #endif - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_DROP)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_DROP; - // 4J-PB - If we're flying, the sneak needs to be held on to go down - if(localplayers[i]->abilities.flying) - { - if(InputManager.ButtonDown(i, MINECRAFT_ACTION_SNEAK_TOGGLE)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<abilities.flying) { + if (InputManager.ButtonDown( + i, MINECRAFT_ACTION_SNEAK_TOGGLE)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_SNEAK_TOGGLE; + } else { + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_SNEAK_TOGGLE)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_SNEAK_TOGGLE; + } + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_RENDER_THIRD_PERSON)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_RENDER_THIRD_PERSON; + if (InputManager.ButtonPressed(i, + MINECRAFT_ACTION_GAME_INFO)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_GAME_INFO; #ifndef _FINAL_BUILD - if( app.DebugSettingsOn() && app.GetUseDPadForDebug() ) - { - localplayers[i]->ullDpad_last = 0; - localplayers[i]->ullDpad_this = 0; - localplayers[i]->ullDpad_filtered = 0; - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_DPAD_RIGHT)) localplayers[i]->ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullButtonsPressed|=1LL<ullDpad_last = 0; + localplayers[i]->ullDpad_this = 0; + localplayers[i]->ullDpad_filtered = 0; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_RIGHT)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_CHANGE_SKIN; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_UP)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_FLY_TOGGLE; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_DOWN)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_RENDER_DEBUG; + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_DPAD_LEFT)) + localplayers[i]->ullButtonsPressed |= + 1LL << MINECRAFT_ACTION_SPAWN_CREEPER; + } else #endif - { - // Movement on DPAD is stored ulimately into ullDpad_filtered - this ignores any diagonals pressed, instead reporting the last single direction - otherwise - // we get loads of accidental diagonal movements + { + // Movement on DPAD is stored ulimately into + // ullDpad_filtered - this ignores any diagonals + // pressed, instead reporting the last single direction + // - otherwise we get loads of accidental diagonal + // movements - localplayers[i]->ullDpad_this = 0; - int dirCount = 0; + localplayers[i]->ullDpad_this = 0; + int dirCount = 0; #ifndef __PSVITA__ - if(InputManager.ButtonDown(i, MINECRAFT_ACTION_DPAD_LEFT)) { localplayers[i]->ullDpad_this|=1LL<ullDpad_this|=1LL<ullDpad_this|=1LL<ullDpad_this|=1LL<ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_LEFT; + dirCount++; + } + if (InputManager.ButtonDown( + i, MINECRAFT_ACTION_DPAD_RIGHT)) { + localplayers[i]->ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_RIGHT; + dirCount++; + } + if (InputManager.ButtonDown(i, + MINECRAFT_ACTION_DPAD_UP)) { + localplayers[i]->ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_UP; + dirCount++; + } + if (InputManager.ButtonDown( + i, MINECRAFT_ACTION_DPAD_DOWN)) { + localplayers[i]->ullDpad_this |= + 1LL << MINECRAFT_ACTION_DPAD_DOWN; + dirCount++; + } #endif - if( dirCount <= 1 ) - { - localplayers[i]->ullDpad_last = localplayers[i]->ullDpad_this; - localplayers[i]->ullDpad_filtered = localplayers[i]->ullDpad_this; - } - else - { - localplayers[i]->ullDpad_filtered = localplayers[i]->ullDpad_last; - } - } + if (dirCount <= 1) { + localplayers[i]->ullDpad_last = + localplayers[i]->ullDpad_this; + localplayers[i]->ullDpad_filtered = + localplayers[i]->ullDpad_this; + } else { + localplayers[i]->ullDpad_filtered = + localplayers[i]->ullDpad_last; + } + } - // for the opacity timer - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_LEFT_SCROLL) || InputManager.ButtonPressed(i, MINECRAFT_ACTION_RIGHT_SCROLL)) - //InputManager.ButtonPressed(i, MINECRAFT_ACTION_USE) || InputManager.ButtonPressed(i, MINECRAFT_ACTION_ACTION)) - { - app.SetOpacityTimer(i); - } - } - else - { - // 4J Stu - This doesn't make any sense with the way we handle XboxOne users + // for the opacity timer + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_LEFT_SCROLL) || + InputManager.ButtonPressed( + i, MINECRAFT_ACTION_RIGHT_SCROLL)) + // InputManager.ButtonPressed(i, MINECRAFT_ACTION_USE) || + // InputManager.ButtonPressed(i, MINECRAFT_ACTION_ACTION)) + { + app.SetOpacityTimer(i); + } + } else { + // 4J Stu - This doesn't make any sense with the way we + // handle XboxOne users #ifndef _DURANGO - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then - bool tryJoin = !pause && !ui.IsIgnorePlayerJoinMenuDisplayed(ProfileManager.GetPrimaryPad()) && g_NetworkManager.SessionHasSpace() && RenderManager.IsHiDef() && InputManager.ButtonPressed(i); + // did we just get input from a player who doesn't exist? + // They'll be wanting to join the game then + bool tryJoin = !pause && + !ui.IsIgnorePlayerJoinMenuDisplayed( + ProfileManager.GetPrimaryPad()) && + g_NetworkManager.SessionHasSpace() && + RenderManager.IsHiDef() && + InputManager.ButtonPressed(i); #ifdef __ORBIS__ - // Check for remote play - tryJoin = tryJoin && InputManager.IsLocalMultiplayerAvailable(); + // Check for remote play + tryJoin = + tryJoin && InputManager.IsLocalMultiplayerAvailable(); - // 4J Stu - Check that content restriction information has been received - if( !g_NetworkManager.IsLocalGame() ) - { - tryJoin = tryJoin && ProfileManager.GetChatAndContentRestrictions(i,true,NULL,NULL,NULL); - } + // 4J Stu - Check that content restriction information has + // been received + if (!g_NetworkManager.IsLocalGame()) { + tryJoin = tryJoin && + ProfileManager.GetChatAndContentRestrictions( + i, true, NULL, NULL, NULL); + } #endif - if(tryJoin) - { - if(!ui.PressStartPlaying(i)) - { + if (tryJoin) { + if (!ui.PressStartPlaying(i)) { #ifdef __ORBIS__ - // Don't let player start joining until their PS Plus check has finished - if (g_NetworkManager.IsLocalGame() || !ProfileManager.RequestingPlaystationPlus(i)) + // Don't let player start joining until their PS + // Plus check has finished + if (g_NetworkManager.IsLocalGame() || + !ProfileManager.RequestingPlaystationPlus(i)) #endif - { - ui.ShowPressStart(i); - } - } - else - { - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then + { + ui.ShowPressStart(i); + } + } else { + // did we just get input from a player who doesn't + // exist? They'll be wanting to join the game then #ifdef __ORBIS__ - if(InputManager.ButtonPressed(i, ACTION_MENU_A)) + if (InputManager.ButtonPressed(i, ACTION_MENU_A)) #else - if(InputManager.ButtonPressed(i, MINECRAFT_ACTION_PAUSEMENU)) + if (InputManager.ButtonPressed( + i, MINECRAFT_ACTION_PAUSEMENU)) #endif - { - // Let them join + { + // Let them join - // are they signed in? - if(ProfileManager.IsSignedIn(i)) - { - // if this is a local game, then the player just needs to be signed in - if( g_NetworkManager.IsLocalGame() || (ProfileManager.IsSignedInLive(i) && ProfileManager.AllowedToPlayMultiplayer(i) ) ) - { + // are they signed in? + if (ProfileManager.IsSignedIn(i)) { + // if this is a local game, then the player + // just needs to be signed in + if (g_NetworkManager.IsLocalGame() || + (ProfileManager.IsSignedInLive(i) && + ProfileManager + .AllowedToPlayMultiplayer(i))) { #ifdef __ORBIS__ - bool contentRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,false,NULL,&contentRestricted,NULL); // TODO! + bool contentRestricted = false; + ProfileManager + .GetChatAndContentRestrictions( + i, false, NULL, + &contentRestricted, + NULL); // TODO! - if (!g_NetworkManager.IsLocalGame() && contentRestricted) - { - ui.RequestContentRestrictedMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_CONTENT_RESTRICTION, i); - } - else if(!g_NetworkManager.IsLocalGame() && !ProfileManager.HasPlayStationPlus(i)) - { - m_pPsPlusUpsell = new PsPlusUpsellWrapper(i); - m_pPsPlusUpsell->displayUpsell(); - } - else + if (!g_NetworkManager.IsLocalGame() && + contentRestricted) { + ui.RequestContentRestrictedMessageBox( + IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_CONTENT_RESTRICTION, i); + } else if (!g_NetworkManager + .IsLocalGame() && + !ProfileManager + .HasPlayStationPlus( + i)) { + m_pPsPlusUpsell = + new PsPlusUpsellWrapper(i); + m_pPsPlusUpsell->displayUpsell(); + } else #endif - if( level->isClientSide ) - { - bool success=addLocalPlayer(i); + if (level->isClientSide) { + bool success = addLocalPlayer(i); - if(!success) - { - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,i); - } - else - { + if (!success) { + app.DebugPrintf( + "Bringing up the sign in " + "ui\n"); + ProfileManager.RequestSignInUI( + false, + g_NetworkManager + .IsLocalGame(), + true, false, true, + &Minecraft:: + InGame_SignInReturned, + this, i); + } else { #ifdef __ORBIS__ - if(g_NetworkManager.IsLocalGame() == false) - { - bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(i,false,&chatRestricted,NULL,NULL); - if(chatRestricted) - { - ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, i ); - } - } + if (g_NetworkManager + .IsLocalGame() == + false) { + bool chatRestricted = false; + ProfileManager + .GetChatAndContentRestrictions( + i, false, + &chatRestricted, + NULL, NULL); + if (chatRestricted) { + ProfileManager + .DisplaySystemMessage( + SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, + i); + } + } #endif - } - } - else - { - // create the localplayer - std::shared_ptr player = localplayers[i]; - if( player == NULL) - { - player = createExtraLocalPlayer(i, (convStringToWstring( ProfileManager.GetGamertag(i) )).c_str(), i, level->dimension->id); - } - } - } - else - { - if( ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad()) && !ProfileManager.AllowedToPlayMultiplayer(i) ) - { - ProfileManager.RequestConvertOfflineToGuestUI( &Minecraft::InGame_SignInReturned, this,i); - // 4J Stu - Don't allow converting to guests as we don't allow any guest sign-in while in the game - // Fix for #66516 - TCR #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The game crashes when second Guest signs-in on console which takes part in Xbox LIVE multiplayer session. - //ProfileManager.RequestConvertOfflineToGuestUI( &Minecraft::InGame_SignInReturned, this,i); + } + } else { + // create the localplayer + std::shared_ptr player = + localplayers[i]; + if (player == NULL) { + player = createExtraLocalPlayer( + i, + (convStringToWstring( + ProfileManager + .GetGamertag(i))) + .c_str(), + i, level->dimension->id); + } + } + } else { + if (ProfileManager.IsSignedInLive( + ProfileManager + .GetPrimaryPad()) && + !ProfileManager + .AllowedToPlayMultiplayer(i)) { + ProfileManager + .RequestConvertOfflineToGuestUI( + &Minecraft:: + InGame_SignInReturned, + this, i); + // 4J Stu - Don't allow converting + // to guests as we don't allow any + // guest sign-in while in the game + // Fix for #66516 - TCR #124: MPS + // Guest Support ; #001: BAS Game + // Stability: TU8: The game crashes + // when second Guest signs-in on + // console which takes part in Xbox + // LIVE multiplayer session. + // ProfileManager.RequestConvertOfflineToGuestUI( + // &Minecraft::InGame_SignInReturned, + // this,i); #ifndef _XBOX - ui.HidePressStart(); + ui.HidePressStart(); #endif #ifdef __ORBIS__ - int npAvailability = ProfileManager.getNPAvailability(i); + int npAvailability = + ProfileManager + .getNPAvailability(i); - // Check if PSN is unavailable because of age restriction - if (npAvailability == SCE_NP_ERROR_AGE_RESTRICTION) - { - unsigned int uiIDA[1]; - uiIDA[0] = IDS_OK; - ui.RequestMessageBox(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, i, NULL, NULL, app.GetStringTable()); - } - else if (ProfileManager.IsSignedIn(i) && !ProfileManager.IsSignedInLive(i)) - { - // You're not signed in to PSN! - unsigned int uiIDA[2]; - uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; - uiIDA[1] = IDS_CANCEL; - ui.RequestMessageBox(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 2, i,&Minecraft::MustSignInReturnedPSN, this, app.GetStringTable(), NULL, 0, false); - } - else + // Check if PSN is unavailable + // because of age restriction + if (npAvailability == + SCE_NP_ERROR_AGE_RESTRICTION) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox( + IDS_ONLINE_SERVICE_TITLE, + IDS_CONTENT_RESTRICTION, + uiIDA, 1, i, NULL, NULL, + app.GetStringTable()); + } else if (ProfileManager + .IsSignedIn(i) && + !ProfileManager + .IsSignedInLive( + i)) { + // You're not signed in to PSN! + unsigned int uiIDA[2]; + uiIDA[0] = + IDS_PRO_NOTONLINE_ACCEPT; + uiIDA[1] = IDS_CANCEL; + ui.RequestMessageBox( + IDS_PRO_NOTONLINE_TITLE, + IDS_PRO_NOTONLINE_TEXT, + uiIDA, 2, i, + &Minecraft:: + MustSignInReturnedPSN, + this, app.GetStringTable(), + NULL, 0, false); + } else #endif - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA, 1, i, NULL, NULL, app.GetStringTable()); - } - } - //else - { - // player not signed in to live - // bring up the sign in dialog - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,i); - } - } - } - else - { - // bring up the sign in dialog - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,i); - } - } - } - } -#endif // _DURANGO - } - } + { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox( + IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, + uiIDA, 1, i, NULL, NULL, + app.GetStringTable()); + } + } + // else + { + // player not signed in to live + // bring up the sign in dialog + app.DebugPrintf( + "Bringing up the sign in ui\n"); + ProfileManager.RequestSignInUI( + false, + g_NetworkManager.IsLocalGame(), + true, false, true, + &Minecraft:: + InGame_SignInReturned, + this, i); + } + } + } else { + // bring up the sign in dialog + app.DebugPrintf( + "Bringing up the sign in ui\n"); + ProfileManager.RequestSignInUI( + false, g_NetworkManager.IsLocalGame(), + true, false, true, + &Minecraft::InGame_SignInReturned, this, + i); + } + } + } + } +#endif // _DURANGO + } + } #ifdef _DURANGO - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then - if(!pause && !ui.IsIgnorePlayerJoinMenuDisplayed(ProfileManager.GetPrimaryPad()) && g_NetworkManager.SessionHasSpace() && RenderManager.IsHiDef() ) - { - int firstEmptyUser = 0; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if(localplayers[i] == NULL) - { - firstEmptyUser = i; - break; - } - } + // did we just get input from a player who doesn't exist? They'll be + // wanting to join the game then + if (!pause && + !ui.IsIgnorePlayerJoinMenuDisplayed( + ProfileManager.GetPrimaryPad()) && + g_NetworkManager.SessionHasSpace() && RenderManager.IsHiDef()) { + int firstEmptyUser = 0; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (localplayers[i] == NULL) { + firstEmptyUser = i; + break; + } + } - // For durango, check for unmapped controllers - for(unsigned int iPad = XUSER_MAX_COUNT; iPad < (XUSER_MAX_COUNT + InputManager.MAX_GAMEPADS); ++iPad) - { - if(InputManager.IsPadLocked(iPad) || !InputManager.IsPadConnected(iPad) ) continue; - if(!InputManager.ButtonPressed(iPad)) continue; + // For durango, check for unmapped controllers + for (unsigned int iPad = XUSER_MAX_COUNT; + iPad < (XUSER_MAX_COUNT + InputManager.MAX_GAMEPADS); + ++iPad) { + if (InputManager.IsPadLocked(iPad) || + !InputManager.IsPadConnected(iPad)) + continue; + if (!InputManager.ButtonPressed(iPad)) continue; - if(!ui.PressStartPlaying(firstEmptyUser)) - { - ui.ShowPressStart(firstEmptyUser); - } - else - { - // did we just get input from a player who doesn't exist? They'll be wanting to join the game then - if(InputManager.ButtonPressed(iPad, MINECRAFT_ACTION_PAUSEMENU)) - { - // bring up the sign in dialog - app.DebugPrintf("Bringing up the sign in ui\n"); - ProfileManager.RequestSignInUI(false, g_NetworkManager.IsLocalGame(), true, false,true,&Minecraft::InGame_SignInReturned, this,iPad); + if (!ui.PressStartPlaying(firstEmptyUser)) { + ui.ShowPressStart(firstEmptyUser); + } else { + // did we just get input from a player who doesn't + // exist? They'll be wanting to join the game then + if (InputManager.ButtonPressed( + iPad, MINECRAFT_ACTION_PAUSEMENU)) { + // bring up the sign in dialog + app.DebugPrintf("Bringing up the sign in ui\n"); + ProfileManager.RequestSignInUI( + false, g_NetworkManager.IsLocalGame(), true, + false, true, &Minecraft::InGame_SignInReturned, + this, iPad); - // 4J Stu - If we are joining a pad here, then we don't want to try and join any others - break; - } - } - } - } + // 4J Stu - If we are joining a pad here, then we + // don't want to try and join any others + break; + } + } + } + } #endif - if (pause && level != NULL) - { - float lastA = timer->a; - timer->advanceTime(); - timer->a = lastA; - } - else - { - timer->advanceTime(); - } + if (pause && level != NULL) { + float lastA = timer->a; + timer->advanceTime(); + timer->a = lastA; + } else { + timer->advanceTime(); + } - __int64 beforeTickTime = System::nanoTime(); - for (int i = 0; i < timer->ticks; i++) - { - bool bLastTimerTick = ( i == ( timer->ticks - 1 ) ); - // 4J-PB - the tick here can run more than once, and this is a problem for our input, which would see the a key press twice with the same time - let's tick the inputmanager again - if(i!=0) - { - InputManager.Tick(); - app.HandleButtonPresses(); - } + __int64 beforeTickTime = System::nanoTime(); + for (int i = 0; i < timer->ticks; i++) { + bool bLastTimerTick = (i == (timer->ticks - 1)); + // 4J-PB - the tick here can run more than once, and this is a + // problem for our input, which would see the a key press twice + // with the same time - let's tick the inputmanager again + if (i != 0) { + InputManager.Tick(); + app.HandleButtonPresses(); + } - ticks++; - // try { // 4J - try/catch removed - bool bFirst = true; - for( int idx = 0; idx < XUSER_MAX_COUNT; idx++ ) - { - // 4J - If we are waiting for this connection to do something, then tick it here. - // This replaces many of the original Java scenes which would tick the connection while showing that scene - if( m_pendingLocalConnections[idx] != NULL ) - { - m_pendingLocalConnections[idx]->tick(); - } + ticks++; + // try { // 4J - try/catch removed + bool bFirst = true; + for (int idx = 0; idx < XUSER_MAX_COUNT; idx++) { + // 4J - If we are waiting for this connection to do + // something, then tick it here. This replaces many of the + // original Java scenes which would tick the connection + // while showing that scene + if (m_pendingLocalConnections[idx] != NULL) { + m_pendingLocalConnections[idx]->tick(); + } - // reset the player inactive tick - if(localplayers[idx]!=NULL) - { - // any input received? - if((localplayers[idx]->ullButtonsPressed!=0) || InputManager.GetJoypadStick_LX(idx,false)!=0.0f || - InputManager.GetJoypadStick_LY(idx,false)!=0.0f || InputManager.GetJoypadStick_RX(idx,false)!=0.0f || - InputManager.GetJoypadStick_RY(idx,false)!=0.0f ) - { - localplayers[idx]->ResetInactiveTicks(); - } - else - { - localplayers[idx]->IncrementInactiveTicks(); - } + // reset the player inactive tick + if (localplayers[idx] != NULL) { + // any input received? + if ((localplayers[idx]->ullButtonsPressed != 0) || + InputManager.GetJoypadStick_LX(idx, false) != + 0.0f || + InputManager.GetJoypadStick_LY(idx, false) != + 0.0f || + InputManager.GetJoypadStick_RX(idx, false) != + 0.0f || + InputManager.GetJoypadStick_RY(idx, false) != + 0.0f) { + localplayers[idx]->ResetInactiveTicks(); + } else { + localplayers[idx]->IncrementInactiveTicks(); + } - if(localplayers[idx]->GetInactiveTicks()>200) - { - if(!localplayers[idx]->isIdle() && localplayers[idx]->onGround) - { - localplayers[idx]->setIsIdle(true); - } - } - else - { - if(localplayers[idx]->isIdle()) - { - localplayers[idx]->setIsIdle(false); - } - } - } + if (localplayers[idx]->GetInactiveTicks() > 200) { + if (!localplayers[idx]->isIdle() && + localplayers[idx]->onGround) { + localplayers[idx]->setIsIdle(true); + } + } else { + if (localplayers[idx]->isIdle()) { + localplayers[idx]->setIsIdle(false); + } + } + } - if( setLocalPlayerIdx(idx) ) - { - tick(bFirst, bLastTimerTick); - bFirst = false; - // clear the stored button downs since the tick for this player will now have actioned them - player->ullButtonsPressed=0LL; - } - } + if (setLocalPlayerIdx(idx)) { + tick(bFirst, bLastTimerTick); + bFirst = false; + // clear the stored button downs since the tick for this + // player will now have actioned them + player->ullButtonsPressed = 0LL; + } + } - ui.HandleGameTick(); + ui.HandleGameTick(); - setLocalPlayerIdx(ProfileManager.GetPrimaryPad()); + setLocalPlayerIdx(ProfileManager.GetPrimaryPad()); - // 4J - added - now do the equivalent of level::animateTick, but taking into account the positions of all our players + // 4J - added - now do the equivalent of level::animateTick, but + // taking into account the positions of all our players - for( int l = 0; l < levels.length; l++ ) - { - if( levels[l] ) - { - levels[l]->animateTickDoWork(); - } - } + for (int l = 0; l < levels.length; l++) { + if (levels[l]) { + levels[l]->animateTickDoWork(); + } + } - // } catch (LevelConflictException e) { - // this.level = null; - // setLevel(null); - // setScreen(new LevelConflictScreen()); - // } -// SparseLightStorage::tick(); // 4J added -// CompressedTileStorage::tick(); // 4J added -// SparseDataStorage::tick(); // 4J added - } - __int64 tickDuraction = System::nanoTime() - beforeTickTime; - MemSect(31); - checkGlError(L"Pre render"); - MemSect(0); + // } catch (LevelConflictException e) { + // this.level = null; + // setLevel(null); + // setScreen(new LevelConflictScreen()); + // } + // SparseLightStorage::tick(); + // // 4J added CompressedTileStorage::tick(); // 4J added + // SparseDataStorage::tick(); + // // 4J added + } + __int64 tickDuraction = System::nanoTime() - beforeTickTime; + MemSect(31); + checkGlError(L"Pre render"); + MemSect(0); - TileRenderer::fancy = options->fancyGraphics; + TileRenderer::fancy = options->fancyGraphics; - // if (pause) timer.a = 1; + // if (pause) timer.a = 1; - PIXBeginNamedEvent(0,"Sound engine update"); - soundEngine->tick((std::shared_ptr *)localplayers, timer->a); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Sound engine update"); + soundEngine->tick((std::shared_ptr*)localplayers, timer->a); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Light update"); + PIXBeginNamedEvent(0, "Light update"); - if (level != NULL) level->updateLights(); - glEnable(GL_TEXTURE_2D); + if (level != NULL) level->updateLights(); + glEnable(GL_TEXTURE_2D); - PIXEndNamedEvent(); + PIXEndNamedEvent(); - // if (!Keyboard::isKeyDown(Keyboard.KEY_F7)) Display.update(); // 4J - removed + // if (!Keyboard::isKeyDown(Keyboard.KEY_F7)) + // Display.update(); // 4J - removed - // 4J-PB - changing this to be per player - //if (player != NULL && player->isInWall()) options->thirdPersonView = false; - if (player != NULL && player->isInWall()) player->SetThirdPersonView(0); + // 4J-PB - changing this to be per player + // if (player != NULL && player->isInWall()) + // options->thirdPersonView = false; + if (player != NULL && player->isInWall()) + player->SetThirdPersonView(0); - if (!noRender) - { - bool bFirst = true; - int iPrimaryPad=ProfileManager.GetPrimaryPad(); - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( setLocalPlayerIdx(i) ) - { - PIXBeginNamedEvent(0,"Game render player idx %d",i); - RenderManager.StateSetViewport((C4JRender::eViewportType)player->m_iScreenSection); - gameRenderer->render(timer->a, bFirst); - bFirst = false; - PIXEndNamedEvent(); + if (!noRender) { + bool bFirst = true; + int iPrimaryPad = ProfileManager.GetPrimaryPad(); + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (setLocalPlayerIdx(i)) { + PIXBeginNamedEvent(0, "Game render player idx %d", i); + RenderManager.StateSetViewport( + (C4JRender::eViewportType)player->m_iScreenSection); + gameRenderer->render(timer->a, bFirst); + bFirst = false; + PIXEndNamedEvent(); - if(i==iPrimaryPad) - { + if (i == iPrimaryPad) { #ifdef __ORBIS__ - // PS4 does much of the screen-capturing for every frame, to simplify the synchronisation when we actually want a capture. This call tells it the point in the frame to do it. - RenderManager.InternalScreenCapture(); + // PS4 does much of the screen-capturing for every + // frame, to simplify the synchronisation when we + // actually want a capture. This call tells it the + // point in the frame to do it. + RenderManager.InternalScreenCapture(); #endif - // check to see if we need to capture a screenshot for the save game thumbnail - switch(app.GetXuiAction(i)) - { - case eAppAction_ExitWorldCapturedThumbnail: - case eAppAction_SaveGameCapturedThumbnail: - case eAppAction_AutosaveSaveGameCapturedThumbnail: - // capture the save thumbnail - app.CaptureSaveThumbnail(); - break; - default: - break; - } - } - } - } + // check to see if we need to capture a screenshot + // for the save game thumbnail + switch (app.GetXuiAction(i)) { + case eAppAction_ExitWorldCapturedThumbnail: + case eAppAction_SaveGameCapturedThumbnail: + case eAppAction_AutosaveSaveGameCapturedThumbnail: + // capture the save thumbnail + app.CaptureSaveThumbnail(); + break; + default: + break; + } + } + } + } #ifdef __linux__ - // On Linux, Iggy Flash UI is not available. If no players were rendered - // (menu / title-screen state), call GameRenderer directly so mc->screen draws. - if (bFirst) - { - localPlayerIdx = 0; - RenderManager.StateSetViewport(C4JRender::VIEWPORT_TYPE_FULLSCREEN); - gameRenderer->render(timer->a, true); - } + // On Linux, Iggy Flash UI is not available. If no players were + // rendered (menu / title-screen state), call GameRenderer + // directly so mc->screen draws. + if (bFirst) { + localPlayerIdx = 0; + RenderManager.StateSetViewport( + C4JRender::VIEWPORT_TYPE_FULLSCREEN); + gameRenderer->render(timer->a, true); + } #endif - // If there's an unoccupied quadrant, then clear that to black - if( unoccupiedQuadrant > -1 ) - { - // render a logo - RenderManager.StateSetViewport((C4JRender::eViewportType)(C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + unoccupiedQuadrant)); - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT); + // If there's an unoccupied quadrant, then clear that to black + if (unoccupiedQuadrant > -1) { + // render a logo + RenderManager.StateSetViewport(( + C4JRender:: + eViewportType)(C4JRender:: + VIEWPORT_TYPE_QUADRANT_TOP_LEFT + + unoccupiedQuadrant)); + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT); - ui.SetEmptyQuadrantLogo(C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + unoccupiedQuadrant); - } - setLocalPlayerIdx(iPrimaryPad); - RenderManager.StateSetViewport(C4JRender::VIEWPORT_TYPE_FULLSCREEN); + ui.SetEmptyQuadrantLogo( + C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT + + unoccupiedQuadrant); + } + setLocalPlayerIdx(iPrimaryPad); + RenderManager.StateSetViewport( + C4JRender::VIEWPORT_TYPE_FULLSCREEN); #ifdef _XBOX - // Do we need to capture a screenshot for a social post? - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if(app.GetXuiAction(i)==eAppAction_SocialPostScreenshot) - { - app.CaptureScreenshot(i); - } - } + // Do we need to capture a screenshot for a social post? + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (app.GetXuiAction(i) == + eAppAction_SocialPostScreenshot) { + app.CaptureScreenshot(i); + } + } #endif - } - glFlush(); - - /* 4J - removed - if (!Display::isActive()) - { - if (fullscreen) - { - this->toggleFullScreen(); - } - Sleep(10); - } - */ - if (options->renderDebug) - { - + } + glFlush(); + /* 4J - removed + if (!Display::isActive()) + { + if (fullscreen) + { + this->toggleFullScreen(); + } + Sleep(10); + } + */ + if (options->renderDebug) { #if DEBUG_RENDER_SHOWS_PACKETS - // To show data for only one packet type - //Packet::renderPacketStats(31); + // To show data for only one packet type + // Packet::renderPacketStats(31); - // To show data for all packet types selected as being renderable in the Packet:static_ctor call to Packet::map - Packet::renderAllPacketStats(); + // To show data for all packet types selected as being + // renderable in the Packet:static_ctor call to Packet::map + Packet::renderAllPacketStats(); #else - // To show the size of the QNet queue in bytes and messages - g_NetworkManager.renderQueueMeter(); + // To show the size of the QNet queue in bytes and messages + g_NetworkManager.renderQueueMeter(); #endif - } - else - { - lastTimer = System::nanoTime(); - } + } else { + lastTimer = System::nanoTime(); + } - achievementPopup->render(); + achievementPopup->render(); - PIXBeginNamedEvent(0,"Sleeping"); - Sleep(0); // 4J - was Thread.yield() - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Sleeping"); + Sleep(0); // 4J - was Thread.yield() + PIXEndNamedEvent(); - // if (Keyboard::isKeyDown(Keyboard::KEY_F7)) Display.update(); // 4J - removed condition - PIXBeginNamedEvent(0,"Display update"); - Display::update(); - PIXEndNamedEvent(); + // if (Keyboard::isKeyDown(Keyboard::KEY_F7)) + // Display.update(); // 4J - removed condition + PIXBeginNamedEvent(0, "Display update"); + Display::update(); + PIXEndNamedEvent(); - // checkScreenshot(); // 4J - removed + // checkScreenshot(); // 4J - removed - /* 4J - removed - if (parent != NULL && !fullscreen) - { - if (parent.getWidth() != width || parent.getHeight() != height) - { - width = parent.getWidth(); - height = parent.getHeight(); - if (width <= 0) width = 1; - if (height <= 0) height = 1; + /* 4J - removed + if (parent != NULL && !fullscreen) + { + if (parent.getWidth() != width || parent.getHeight() != height) + { + width = parent.getWidth(); + height = parent.getHeight(); + if (width <= 0) width = 1; + if (height <= 0) height = 1; - resize(width, height); - } - } - */ - MemSect(31); - checkGlError(L"Post render"); - MemSect(0); - frames++; - //pause = !isClientSide() && screen != NULL && screen->isPauseScreen(); - //pause = g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()); - pause = app.IsAppPaused(); + resize(width, height); + } + } + */ + MemSect(31); + checkGlError(L"Post render"); + MemSect(0); + frames++; + // pause = !isClientSide() && screen != NULL && + // screen->isPauseScreen(); pause = g_NetworkManager.IsLocalGame() + // && g_NetworkManager.GetPlayerCount() == 1 && + // app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()); + pause = app.IsAppPaused(); #ifndef _CONTENT_PACKAGE - while (System::nanoTime() >= lastTime + 1000000000) - { - MemSect(31); - fpsString = _toString(frames) + L" fps, " + _toString(Chunk::updates) + L" chunk updates"; - MemSect(0); - Chunk::updates = 0; - lastTime += 1000000000; - frames = 0; - } + while (System::nanoTime() >= lastTime + 1000000000) { + MemSect(31); + fpsString = _toString(frames) + L" fps, " + + _toString(Chunk::updates) + L" chunk updates"; + MemSect(0); + Chunk::updates = 0; + lastTime += 1000000000; + frames = 0; + } #endif - /* - } catch (LevelConflictException e) { - this.level = null; - setLevel(null); - setScreen(new LevelConflictScreen()); - } catch (OutOfMemoryError e) { - emergencySave(); - setScreen(new OutOfMemoryScreen()); - System.gc(); - } - */ - } - /* - } catch (StopGameException e) { - } catch (Throwable e) { - emergencySave(); - e.printStackTrace(); - crash(new CrashReport("Unexpected error", e)); - } finally { - destroy(); - } - */ - } - LeaveCriticalSection(&m_setLevelCS); + /* + } catch (LevelConflictException e) { + this.level = null; + setLevel(null); + setScreen(new LevelConflictScreen()); + } catch (OutOfMemoryError e) { + emergencySave(); + setScreen(new OutOfMemoryScreen()); + System.gc(); + } + */ + } + /* + } catch (StopGameException e) { + } catch (Throwable e) { + emergencySave(); + e.printStackTrace(); + crash(new CrashReport("Unexpected error", e)); + } finally { + destroy(); + } + */ + } + LeaveCriticalSection(&m_setLevelCS); } -void Minecraft::run_end() -{ - destroy(); +void Minecraft::run_end() { destroy(); } + +void Minecraft::emergencySave() { + // 4J - lots of try/catches removed here, and garbage collector things + levelRenderer->clear(); + AABB::clearPool(); + Vec3::clearPool(); + setLevel(NULL); } -void Minecraft::emergencySave() -{ - // 4J - lots of try/catches removed here, and garbage collector things - levelRenderer->clear(); - AABB::clearPool(); - Vec3::clearPool(); - setLevel(NULL); +void Minecraft::renderFpsMeter(__int64 tickTime) { + int nsPer60Fps = 1000000000l / 60; + if (lastTimer == -1) { + lastTimer = System::nanoTime(); + } + __int64 now = System::nanoTime(); + Minecraft::tickTimes[(Minecraft::frameTimePos) & + (Minecraft::frameTimes_length - 1)] = tickTime; + Minecraft::frameTimes[(Minecraft::frameTimePos++) & + (Minecraft::frameTimes_length - 1)] = now - lastTimer; + lastTimer = now; + + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glEnable(GL_COLOR_MATERIAL); + glLoadIdentity(); + glOrtho(0, (float)width, (float)height, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); + + glLineWidth(1); + glDisable(GL_TEXTURE_2D); + Tesselator* t = Tesselator::getInstance(); + t->begin(GL_QUADS); + int hh1 = (int)(nsPer60Fps / 200000); + t->color(0x20000000); + t->vertex((float)(0), (float)(height - hh1), (float)(0)); + t->vertex((float)(0), (float)(height), (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height), + (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh1), + (float)(0)); + + t->color(0x20200000); + t->vertex((float)(0), (float)(height - hh1 * 2), (float)(0)); + t->vertex((float)(0), (float)(height - hh1), (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh1), + (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh1 * 2), + (float)(0)); + + t->end(); + __int64 totalTime = 0; + for (int i = 0; i < Minecraft::frameTimes_length; i++) { + totalTime += Minecraft::frameTimes[i]; + } + int hh = (int)(totalTime / 200000 / Minecraft::frameTimes_length); + t->begin(GL_QUADS); + t->color(0x20400000); + t->vertex((float)(0), (float)(height - hh), (float)(0)); + t->vertex((float)(0), (float)(height), (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height), + (float)(0)); + t->vertex((float)(Minecraft::frameTimes_length), (float)(height - hh), + (float)(0)); + t->end(); + t->begin(GL_LINES); + for (int i = 0; i < Minecraft::frameTimes_length; i++) { + int col = ((i - Minecraft::frameTimePos) & + (Minecraft::frameTimes_length - 1)) * + 255 / Minecraft::frameTimes_length; + int cc = col * col / 255; + cc = cc * cc / 255; + int cc2 = cc * cc / 255; + cc2 = cc2 * cc2 / 255; + if (Minecraft::frameTimes[i] > nsPer60Fps) { + t->color(0xff000000 + cc * 65536); + } else { + t->color(0xff000000 + cc * 256); + } + + __int64 time = Minecraft::frameTimes[i] / 200000; + __int64 time2 = Minecraft::tickTimes[i] / 200000; + + t->vertex((float)(i + 0.5f), (float)(height - time + 0.5f), (float)(0)); + t->vertex((float)(i + 0.5f), (float)(height + 0.5f), (float)(0)); + + // if (Minecraft.frameTimes[i]>nsPer60Fps) { + t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); + // } else { + // t.color(0xff808080 + cc/2 * 256); + // } + t->vertex((float)(i + 0.5f), (float)(height - time + 0.5f), (float)(0)); + t->vertex((float)(i + 0.5f), (float)(height - (time - time2) + 0.5f), + (float)(0)); + } + t->end(); + + glEnable(GL_TEXTURE_2D); } -void Minecraft::renderFpsMeter(__int64 tickTime) -{ - int nsPer60Fps = 1000000000l / 60; - if (lastTimer == -1) - { - lastTimer = System::nanoTime(); - } - __int64 now = System::nanoTime(); - Minecraft::tickTimes[(Minecraft::frameTimePos) & (Minecraft::frameTimes_length - 1)] = tickTime; - Minecraft::frameTimes[(Minecraft::frameTimePos++) & (Minecraft::frameTimes_length - 1)] = now - lastTimer; - lastTimer = now; - - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glEnable(GL_COLOR_MATERIAL); - glLoadIdentity(); - glOrtho(0, (float)width, (float)height, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); - - glLineWidth(1); - glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); - t->begin(GL_QUADS); - int hh1 = (int) (nsPer60Fps / 200000); - t->color(0x20000000); - t->vertex((float)(0), (float)( height - hh1), (float)( 0)); - t->vertex((float)(0), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1), (float)( 0)); - - t->color(0x20200000); - t->vertex((float)(0), (float)( height - hh1 * 2), (float)( 0)); - t->vertex((float)(0), (float)( height - hh1), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh1 * 2), (float)( 0)); - - t->end(); - __int64 totalTime = 0; - for (int i = 0; i < Minecraft::frameTimes_length; i++) - { - totalTime += Minecraft::frameTimes[i]; - } - int hh = (int) (totalTime / 200000 / Minecraft::frameTimes_length); - t->begin(GL_QUADS); - t->color(0x20400000); - t->vertex((float)(0), (float)( height - hh), (float)( 0)); - t->vertex((float)(0), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height), (float)( 0)); - t->vertex((float)(Minecraft::frameTimes_length), (float)( height - hh), (float)( 0)); - t->end(); - t->begin(GL_LINES); - for (int i = 0; i < Minecraft::frameTimes_length; i++) - { - int col = ((i - Minecraft::frameTimePos) & (Minecraft::frameTimes_length - 1)) * 255 / Minecraft::frameTimes_length; - int cc = col * col / 255; - cc = cc * cc / 255; - int cc2 = cc * cc / 255; - cc2 = cc2 * cc2 / 255; - if (Minecraft::frameTimes[i] > nsPer60Fps) - { - t->color(0xff000000 + cc * 65536); - } - else - { - t->color(0xff000000 + cc * 256); - } - - __int64 time = Minecraft::frameTimes[i] / 200000; - __int64 time2 = Minecraft::tickTimes[i] / 200000; - - t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height + 0.5f), (float)( 0)); - - // if (Minecraft.frameTimes[i]>nsPer60Fps) { - t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); - // } else { - // t.color(0xff808080 + cc/2 * 256); - // } - t->vertex((float)(i + 0.5f), (float)( height - time + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height - (time - time2) + 0.5f), (float)( 0)); - } - t->end(); - - glEnable(GL_TEXTURE_2D); +void Minecraft::stop() { + running = false; + // keepPolling = false; } -void Minecraft::stop() -{ - running = false; - // keepPolling = false; +void Minecraft::pauseGame() { + if (screen != NULL) return; + + // setScreen(new PauseScreen()); // 4J - TODO put back in } -void Minecraft::pauseGame() -{ - if (screen != NULL) return; +void Minecraft::resize(int width, int height) { + if (width <= 0) width = 1; + if (height <= 0) height = 1; + this->width = width; + this->height = height; - // setScreen(new PauseScreen()); // 4J - TODO put back in + if (screen != NULL) { + ScreenSizeCalculator ssc(options, width, height); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + // screen->init(this, screenWidth, screenHeight); // 4J - + // TODO - put back in + } } -void Minecraft::resize(int width, int height) -{ - if (width <= 0) width = 1; - if (height <= 0) height = 1; - this->width = width; - this->height = height; - - if (screen != NULL) - { - ScreenSizeCalculator ssc(options, width, height); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - // screen->init(this, screenWidth, screenHeight); // 4J - TODO - put back in - } +void Minecraft::verify() { + /* 4J - TODO + new Thread() { + public void run() { + try { + HttpURLConnection huc = (HttpURLConnection) new + URL("https://login.minecraft.net/session?name=" + user.name + "&session=" + + user.sessionId).openConnection(); huc.connect(); if (huc.getResponseCode() + == 400) { warezTime = System.currentTimeMillis(); + } + huc.disconnect(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + */ } -void Minecraft::verify() -{ - /* 4J - TODO - new Thread() { - public void run() { - try { - HttpURLConnection huc = (HttpURLConnection) new URL("https://login.minecraft.net/session?name=" + user.name + "&session=" + user.sessionId).openConnection(); - huc.connect(); - if (huc.getResponseCode() == 400) { - warezTime = System.currentTimeMillis(); - } - huc.disconnect(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - */ +void Minecraft::levelTickUpdateFunc(void* pParam) { + Level* pLevel = (Level*)pParam; + pLevel->tick(); } - - - -void Minecraft::levelTickUpdateFunc(void* pParam) -{ - Level* pLevel = (Level*)pParam; - pLevel->tick(); +void Minecraft::levelTickThreadInitFunc() { + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Compression::UseDefaultThreadStorage(); } -void Minecraft::levelTickThreadInitFunc() -{ - AABB::CreateNewThreadStorage(); - Vec3::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - Compression::UseDefaultThreadStorage(); -} +// 4J - added bFirst parameter, which is true for the first active viewport in +// splitscreen 4J - added bUpdateTextures, which is true if the actual renderer +// textures are to be updated - this will be true for the last time this tick +// runs with bFirst true +void Minecraft::tick(bool bFirst, bool bUpdateTextures) { + int iPad = player->GetXboxPad(); + // OutputDebugString("Minecraft::tick\n"); + // 4J-PB - only tick this player's stats + stats[iPad]->tick(iPad); -// 4J - added bFirst parameter, which is true for the first active viewport in splitscreen -// 4J - added bUpdateTextures, which is true if the actual renderer textures are to be updated - this will be true for the last time this tick runs with bFirst true -void Minecraft::tick(bool bFirst, bool bUpdateTextures) -{ - int iPad=player->GetXboxPad(); - //OutputDebugString("Minecraft::tick\n"); + // Tick the opacity timer (to display the interface at default opacity for a + // certain time if the user has been navigating it) + app.TickOpacityTimer(iPad); - //4J-PB - only tick this player's stats - stats[iPad]->tick(iPad); + // 4J added + if (bFirst) levelRenderer->destroyedTileManager->tick(); - // Tick the opacity timer (to display the interface at default opacity for a certain time if the user has been navigating it) - app.TickOpacityTimer(iPad); - - // 4J added - if( bFirst ) levelRenderer->destroyedTileManager->tick(); - - gui->tick(); - gameRenderer->pick(1); + gui->tick(); + gameRenderer->pick(1); #if 0 // 4J - removed - we don't use ChunkCache anymore if (player != NULL) @@ -2185,1300 +2326,1365 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } #endif - // soundEngine.playMusicTick(); - - if (!pause && level != NULL) gameMode->tick(); - MemSect(31); - glBindTexture(GL_TEXTURE_2D, textures->loadTexture(TN_TERRAIN));//L"/terrain.png")); - MemSect(0); - if( bFirst ) - { - PIXBeginNamedEvent(0,"Texture tick"); - if (!pause) textures->tick(bUpdateTextures); - PIXEndNamedEvent(); - } - - /* - * if (serverConnection != null && !(screen instanceof ErrorScreen)) { - * if (!serverConnection.isConnected()) { - * progressRenderer.progressStart("Connecting.."); - * progressRenderer.progressStagePercentage(0); } else { - * serverConnection.tick(); serverConnection.sendPosition(player); } } - */ - if (screen == NULL && player != NULL ) - { - if (player->getHealth() <= 0 && !ui.GetMenuDisplayed(iPad) ) - { - setScreen(NULL); - } - else if (player->isSleeping() && level != NULL && level->isClientSide) - { - // setScreen(new InBedChatScreen()); // 4J - TODO put back in - } - } - else if (screen != NULL && (dynamic_cast(screen)!=NULL) && !player->isSleeping()) - { - setScreen(NULL); - } - - if (screen != NULL) - { - player->missTime = 10000; - player->lastClickTick[0] = ticks + 10000; - player->lastClickTick[1] = ticks + 10000; - } - - if (screen != NULL) - { - screen->updateEvents(); - if (screen != NULL) - { - screen->particles->tick(); - screen->tick(); - } - } - - if (screen == NULL && !ui.GetMenuDisplayed(iPad) ) - { - // 4J-PB - add some tooltips if required - int iA=-1, iB=-1, iX, iY=IDS_CONTROLS_INVENTORY, iLT=-1, iRT=-1, iLB=-1, iRB=-1; - - if(player->abilities.instabuild) - { - iX=IDS_TOOLTIPS_CREATIVE; - } - else - { - iX=IDS_CONTROLS_CRAFTING; - } - // control scheme remapping can move the Action button, so we need to check this - int *piAction; - int *piJump; - int *piUse; - - unsigned int uiAction = InputManager.GetGameJoypadMaps(InputManager.GetJoypadMapVal( iPad ) ,MINECRAFT_ACTION_ACTION ); - unsigned int uiJump = InputManager.GetGameJoypadMaps(InputManager.GetJoypadMapVal( iPad ) ,MINECRAFT_ACTION_JUMP ); - unsigned int uiUse = InputManager.GetGameJoypadMaps(InputManager.GetJoypadMapVal( iPad ) ,MINECRAFT_ACTION_USE ); - - // Also need to handle PS3 having swapped triggers/bumpers - switch(uiAction) - { - case _360_JOY_BUTTON_RT: - piAction=&iRT; - break; - case _360_JOY_BUTTON_LT: - piAction=&iLT; - break; - case _360_JOY_BUTTON_LB: - piAction=&iLB; - break; - case _360_JOY_BUTTON_RB: - piAction=&iRB; - break; - case _360_JOY_BUTTON_A: - default: - piAction=&iA; - break; - } - - switch(uiJump) - { - case _360_JOY_BUTTON_LT: - piJump=&iLT; - break; - case _360_JOY_BUTTON_RT: - piJump=&iRT; - break; - case _360_JOY_BUTTON_LB: - piJump=&iLB; - break; - case _360_JOY_BUTTON_RB: - piJump=&iRB; - break; - case _360_JOY_BUTTON_A: - default: - piJump=&iA; - break; - } - - switch(uiUse) - { - case _360_JOY_BUTTON_LB: - piUse=&iLB; - break; - case _360_JOY_BUTTON_RB: - piUse=&iRB; - break; - case _360_JOY_BUTTON_LT: - piUse=&iLT; - break; - case _360_JOY_BUTTON_RT: - default: - piUse=&iRT; - break; - } - - if (player->isUnderLiquid(Material::water)) - { - *piJump=IDS_TOOLTIPS_SWIMUP; - } - else - { - *piJump=-1; - } - - *piUse=-1; - *piAction=-1; - - // 4J-PB another special case for when the player is sleeping in a bed - if (player->isSleeping() && (level != NULL) && level->isClientSide) - { - *piUse=IDS_TOOLTIPS_WAKEUP; - } - else - { - // no hit result, but we may have something in our hand that we can do something with - std::shared_ptr itemInstance = player->inventory->getSelected(); - - // 4J-JEV: Moved all this here to avoid having it in 3 different places. - if (itemInstance) - { - // 4J-PB - very special case for boat and empty bucket and glass bottle and more - bool bUseItem = gameMode->useItem(player, level, itemInstance, true); - - switch (itemInstance->getItem()->id) - { - // food - case Item::potatoBaked_Id: - case Item::potato_Id: - case Item::pumpkinPie_Id: - case Item::potatoPoisonous_Id: - case Item::carrotGolden_Id: - case Item::carrots_Id: - case Item::mushroomStew_Id: - case Item::apple_Id: - case Item::bread_Id: - case Item::porkChop_raw_Id: - case Item::porkChop_cooked_Id: - case Item::apple_gold_Id: - case Item::fish_raw_Id: - case Item::fish_cooked_Id: - case Item::cookie_Id: - case Item::beef_cooked_Id: - case Item::beef_raw_Id: - case Item::chicken_cooked_Id: - case Item::chicken_raw_Id: - case Item::melon_Id: - case Item::rotten_flesh_Id: - case Item::spiderEye_Id: - // Check that we are actually hungry so will eat this item - { - FoodItem *food = (FoodItem *)itemInstance->getItem(); - if (food != NULL && food->canEat(player)) - { - *piUse=IDS_TOOLTIPS_EAT; - } - } - break; - - case Item::milk_Id: - *piUse=IDS_TOOLTIPS_DRINK; - break; - - case Item::fishingRod_Id: // use - *piUse=IDS_TOOLTIPS_USE; - break; - - case Item::egg_Id: // throw - case Item::snowBall_Id: - *piUse=IDS_TOOLTIPS_THROW; - break; - - case Item::bow_Id: // draw or release - if ( player->abilities.instabuild || player->inventory->hasResource(Item::arrow_Id) ) - { - if (player->isUsingItem()) *piUse=IDS_TOOLTIPS_RELEASE_BOW; - else *piUse=IDS_TOOLTIPS_DRAW_BOW; - } - break; - - case Item::sword_wood_Id: - case Item::sword_stone_Id: - case Item::sword_iron_Id: - case Item::sword_diamond_Id: - case Item::sword_gold_Id: - *piUse=IDS_TOOLTIPS_BLOCK; - break; - - case Item::bucket_empty_Id: - case Item::glassBottle_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_COLLECT; - break; - - case Item::boat_Id: - case Tile::waterLily_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_PLACE; - break; - - case Item::potion_Id: - if (bUseItem) - { - if (MACRO_POTION_IS_SPLASH(itemInstance->getAuxValue())) *piUse=IDS_TOOLTIPS_THROW; - else *piUse=IDS_TOOLTIPS_DRINK; - } - break; - - case Item::enderPearl_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_THROW; - break; - - case Item::eyeOfEnder_Id: - // This will only work if there is a stronghold in this dimension - if ( bUseItem && (level->dimension->id==0) && level->getLevelData()->getHasStronghold() ) - { - *piUse=IDS_TOOLTIPS_THROW; - } - break; - - case Item::expBottle_Id: - if (bUseItem) *piUse=IDS_TOOLTIPS_THROW; - break; - } - } - - if (hitResult!=NULL) - { - switch(hitResult->type) - { - case HitResult::TILE: - { - int x,y,z; - x=hitResult->x; - y=hitResult->y; - z=hitResult->z; - int face = hitResult->f; - - int iTileID=level->getTile(x,y ,z ); - int iData = level->getData(x, y, z); - - if( gameMode != NULL && gameMode->getTutorial() != NULL ) - { - // 4J Stu - For the tutorial we want to be able to record what items we look at so that we can give hints - gameMode->getTutorial()->onLookAt(iTileID,iData); - } - - // 4J-PB - Call the useItemOn with the TestOnly flag set - bool bUseItemOn=gameMode->useItemOn(player, level, itemInstance, x, y, z, face, hitResult->pos, true); - - /* 4J-Jev: - * Moved this here so we have item tooltips to fallback on - * for noteblocks, enderportals and flowerpots in case of non-standard items. - * (ie. ignite behaviour) - */ - if (bUseItemOn && itemInstance!=NULL) - { - switch (itemInstance->getItem()->id) - { - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - case Tile::tallgrass_Id: - case Tile::cactus_Id: - case Tile::sapling_Id: - case Tile::reeds_Id: - case Tile::flower_Id: - case Tile::rose_Id: - *piUse=IDS_TOOLTIPS_PLANT; - break; - - // Things to USE - case Item::hoe_wood_Id: - case Item::hoe_stone_Id: - case Item::hoe_iron_Id: - case Item::hoe_diamond_Id: - case Item::hoe_gold_Id: - *piUse=IDS_TOOLTIPS_TILL; - break; - - case Item::seeds_wheat_Id: - case Item::netherStalkSeeds_Id: - *piUse=IDS_TOOLTIPS_PLANT; - break; - - case Item::bucket_empty_Id: - switch(iTileID) - { - // can collect lava or water in the empty bucket - case Tile::water_Id: - case Tile::calmWater_Id: - case Tile::lava_Id: - case Tile::calmLava_Id: - *piUse=IDS_TOOLTIPS_COLLECT; - break; - } - break; - - case Item::bucket_lava_Id: - case Item::bucket_water_Id: - *piUse=IDS_TOOLTIPS_EMPTY; - break; - - case Item::dye_powder_Id: - // bonemeal grows various plants - if (itemInstance->getAuxValue() == DyePowderItem::WHITE) - { - switch(iTileID) - { - case Tile::sapling_Id: - case Tile::crops_Id: - case Tile::grass_Id: - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - case Tile::melonStem_Id: - case Tile::pumpkinStem_Id: - case Tile::carrots_Id: - case Tile::potatoes_Id: - *piUse=IDS_TOOLTIPS_GROW; - break; - } - } - break; - - case Item::painting_Id: - *piUse=IDS_TOOLTIPS_HANG; - break; - - case Item::flintAndSteel_Id: - case Item::fireball_Id: - *piUse=IDS_TOOLTIPS_IGNITE; - break; - - default: - *piUse=IDS_TOOLTIPS_PLACE; - break; - } - } - - switch(iTileID) - { - case Tile::anvil_Id: - case Tile::enchantTable_Id: - case Tile::brewingStand_Id: - case Tile::workBench_Id: - case Tile::furnace_Id: - case Tile::furnace_lit_Id: - case Tile::door_wood_Id: - case Tile::dispenser_Id: - case Tile::lever_Id: - case Tile::button_stone_Id: - case Tile::button_wood_Id: - case Tile::trapdoor_Id: - case Tile::fenceGate_Id: - *piAction=IDS_TOOLTIPS_MINE; - *piUse=IDS_TOOLTIPS_USE; - break; - - case Tile::goldenRail_Id: - case Tile::detectorRail_Id: - case Tile::rail_Id: - if (bUseItemOn) *piUse=IDS_TOOLTIPS_PLACE; - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::chest_Id: - case Tile::enderChest_Id: - *piUse=IDS_TOOLTIPS_OPEN; - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::bed_Id: - if (bUseItemOn) *piUse=IDS_TOOLTIPS_SLEEP; - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::musicBlock_Id: - // if in creative mode, we will mine - if (player->abilities.instabuild) *piAction=IDS_TOOLTIPS_MINE; - else *piAction=IDS_TOOLTIPS_PLAY; - *piUse=IDS_TOOLTIPS_CHANGEPITCH; - break; - - case Tile::sign_Id: - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::cauldron_Id: - // special case for a cauldron of water and an empty bottle - if (itemInstance) - { - int iID=itemInstance->getItem()->id; - int currentData = level->getData(x, y, z); - if ((iID==Item::glassBottle_Id) && (currentData > 0)) - { - *piUse=IDS_TOOLTIPS_COLLECT; - } - } - *piAction=IDS_TOOLTIPS_MINE; - break; - - case Tile::cake_Id: - if (player->abilities.instabuild) // if in creative mode, we will mine - { - *piAction=IDS_TOOLTIPS_MINE; - } - else - { - if (player->getFoodData()->needsFood() ) // 4J-JEV: Changed from healthto hunger. - { - *piAction=IDS_TOOLTIPS_EAT; - *piUse=IDS_TOOLTIPS_EAT; - } - else - { - *piAction=IDS_TOOLTIPS_MINE; - } - } - break; - - case Tile::recordPlayer_Id: - if (!bUseItemOn && itemInstance!=NULL) - { - int iID=itemInstance->getItem()->id; - if ( (iID>=Item::record_01_Id) && (iID<=Item::record_12_Id) ) - { - *piUse=IDS_TOOLTIPS_PLAY; - } - *piAction=IDS_TOOLTIPS_MINE; - } - else - { - if (Tile::recordPlayer->TestUse(level, x, y, z, player)) // means we can eject - { - *piUse=IDS_TOOLTIPS_EJECT; - } - *piAction=IDS_TOOLTIPS_MINE; - } - break; - - case Tile::flowerPot_Id: - if ( !bUseItemOn && (itemInstance != NULL) && (iData == 0) ) - { - int iID = itemInstance->getItem()->id; - if (iID<256) // is it a tile? - { - switch(iID) - { - case Tile::flower_Id: - case Tile::rose_Id: - case Tile::sapling_Id: - case Tile::mushroom1_Id: - case Tile::mushroom2_Id: - case Tile::cactus_Id: - case Tile::deadBush_Id: - *piUse=IDS_TOOLTIPS_PLANT; - break; - - case Tile::tallgrass_Id: - if (itemInstance->getAuxValue() != TallGrass::TALL_GRASS) *piUse=IDS_TOOLTIPS_PLANT; - break; - } - } - } - *piAction=IDS_TOOLTIPS_MINE; - break; - - default: - *piAction=IDS_TOOLTIPS_MINE; - break; - } - } - break; - - case HitResult::ENTITY: - eINSTANCEOF entityType = hitResult->entity->GetType(); - - if( gameMode != NULL && gameMode->getTutorial() != NULL ) - { - // 4J Stu - For the tutorial we want to be able to record what items we look at so that we can give hints - gameMode->getTutorial()->onLookAtEntity(entityType); - } - - switch(entityType) - { - case eTYPE_CHICKEN: - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - switch(iID) - { - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - break; - - case eTYPE_COW: - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - // It's an item - switch(iID) - { - // Things to USE - case Item::bucket_empty_Id: - *piUse=IDS_TOOLTIPS_MILK; - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - break; - case eTYPE_MUSHROOMCOW: - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - // It's an item - switch(iID) - { - // Things to USE - case Item::bowl_Id: - case Item::bucket_empty_Id: // You can milk a mooshroom with either a bowl (mushroom soup) or a bucket (milk)! - *piUse=IDS_TOOLTIPS_MILK; - break; - case Item::shears_Id: - { - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - if(!animal->isBaby()) *piUse=IDS_TOOLTIPS_SHEAR; - } - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - else - { - // 4J-PB - Fix for #13081 - No tooltip is displayed for hitting a cow when you have nothing in your hand - // nothing in your hand - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - } - break; - - case eTYPE_BOAT: - *piAction=IDS_TOOLTIPS_MINE; - - // are we in the boat already? - if (std::dynamic_pointer_cast( player->riding ) != NULL) - { - *piUse=IDS_TOOLTIPS_EXIT; - } - else - { - *piUse=IDS_TOOLTIPS_SAIL; - } - break; - case eTYPE_MINECART: - *piAction=IDS_TOOLTIPS_MINE; - // are we in the minecart already? - if (std::dynamic_pointer_cast( player->riding ) != NULL) - { - *piUse=IDS_TOOLTIPS_EXIT; - } - else - { - switch(std::dynamic_pointer_cast(hitResult->entity)->type) - { - case Minecart::RIDEABLE: - *piUse=IDS_TOOLTIPS_RIDE; - break; - case Minecart::CHEST: - *piUse=IDS_TOOLTIPS_OPEN; - break; - case Minecart::FURNACE: - // if you have coal, it'll go - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - if(iID==Item::coal->id) - { - *piUse=IDS_TOOLTIPS_USE; - } - else - { - *piUse=IDS_TOOLTIPS_HIT; - } - } - break; - } - } - - break; - case eTYPE_SHEEP: - // can dye a sheep - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - switch(iID) - { - case Item::dye_powder_Id: - { - std::shared_ptr sheep = std::dynamic_pointer_cast(hitResult->entity); - // convert to tile-based color value (0 is white instead of black) - int newColor = ClothTile::getTileDataForItemAuxValue(heldItem->getAuxValue()); - - // can only use a dye on sheep that haven't been sheared - if(!(sheep->isSheared() && sheep->getColor() != newColor)) - { - *piUse=IDS_TOOLTIPS_DYE; - } - } - break; - case Item::shears_Id: - { - std::shared_ptr sheep = std::dynamic_pointer_cast(hitResult->entity); - - // can only shear a sheep that hasn't been sheared - if(!sheep->isSheared() ) - { - *piUse=IDS_TOOLTIPS_SHEAR; - } - } - - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - - break; - case eTYPE_PIG: - // can ride a pig - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - if (std::dynamic_pointer_cast( player->riding ) != NULL) - { - *piUse=IDS_TOOLTIPS_EXIT; - } - else - { - // does the pig have a saddle? - if(std::dynamic_pointer_cast(hitResult->entity)->hasSaddle()) - { - *piUse=IDS_TOOLTIPS_RIDE; - } - else if (!std::dynamic_pointer_cast(hitResult->entity)->isBaby()) - { - if(player->inventory->IsHeldItem()) - { - std::shared_ptr heldItem=player->inventory->getSelected(); - int iID=heldItem->getItem()->id; - - switch(iID) - { - case Item::saddle_Id: - *piUse=IDS_TOOLTIPS_SADDLE; - break; - default: - { - std::shared_ptr animal = std::dynamic_pointer_cast(hitResult->entity); - - if(!animal->isBaby() && !animal->isInLove() && (animal->getAge() == 0) && animal->isFood(heldItem)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - break; - } - } - } - } - - break; - case eTYPE_WOLF: - // can be tamed, fed, and made to sit/stand, or enter love mode - { - int iID=-1; - std::shared_ptr heldItem=nullptr; - std::shared_ptr wolf = std::dynamic_pointer_cast(hitResult->entity); - - if(player->inventory->IsHeldItem()) - { - heldItem=player->inventory->getSelected(); - iID=heldItem->getItem()->id; - } - - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - - switch(iID) - { - case Item::bone_Id: - if (!wolf->isAngry() && !wolf->isTame()) - { - *piUse=IDS_TOOLTIPS_TAME; - } - else if (equalsIgnoreCase(player->getUUID(), wolf->getOwnerUUID())) - { - if(wolf->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - - break; - case Item::enderPearl_Id: - // Use is throw, so don't change the tips for the wolf - break; - case Item::dye_powder_Id: - if (wolf->isTame()) - { - if (ClothTile::getTileDataForItemAuxValue(heldItem->getAuxValue()) != wolf->getCollarColor()) - { - *piUse=IDS_TOOLTIPS_DYECOLLAR; - } - else if (wolf->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - break; - default: - if(wolf->isTame()) - { - if(wolf->isFood(heldItem)) - { - if(wolf->GetSynchedHealth() < wolf->getMaxHealth()) - { - *piUse=IDS_TOOLTIPS_HEAL; - } - else - { - if(!wolf->isBaby() && !wolf->isInLove() && (wolf->getAge() == 0)) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - // break out here - break; - } - - if (equalsIgnoreCase(player->getUUID(), wolf->getOwnerUUID())) - { - if(wolf->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - } - break; - } - } - break; - case eTYPE_OZELOT: - { - int iID=-1; - std::shared_ptr heldItem=nullptr; - std::shared_ptr ocelot = std::dynamic_pointer_cast(hitResult->entity); - - if(player->inventory->IsHeldItem()) - { - heldItem=player->inventory->getSelected(); - iID=heldItem->getItem()->id; - } - - if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - - if(ocelot->isTame()) - { - // 4J-PB - if you have a raw fish in your hand, you will feed the ocelot rather than have it sit/follow - if(ocelot->isFood(heldItem)) - { - if(!ocelot->isBaby()) - { - if(!ocelot->isInLove()) - { - if(ocelot->getAge() == 0) - { - *piUse=IDS_TOOLTIPS_LOVEMODE; - } - } - else - { - *piUse=IDS_TOOLTIPS_FEED; - } - } - - } - else if (equalsIgnoreCase(player->getUUID(), ocelot->getOwnerUUID())) - { - if(ocelot->isSitting()) - { - *piUse=IDS_TOOLTIPS_FOLLOWME; - } - else - { - *piUse=IDS_TOOLTIPS_SIT; - } - } - } - else if(iID!=-1) - { - switch(iID) - { - default: - { - if(ocelot->isFood(heldItem)) *piUse=IDS_TOOLTIPS_TAME; - } - break; - } - } - } - - break; - - case eTYPE_PLAYER: - { - // Fix for #58576 - TU6: Content: Gameplay: Hit button prompt is available when attacking a host who has "Invisible" option turned on - std::shared_ptr TargetPlayer = std::dynamic_pointer_cast(hitResult->entity); - - if(!TargetPlayer->hasInvisiblePrivilege()) // This means they are invisible, not just that they have the privilege - { - if( app.GetGameHostOption(eGameHostOption_PvP) && player->isAllowedToAttackPlayers()) - { - *piAction=IDS_TOOLTIPS_HIT; - } - } - } - break; - case eTYPE_ITEM_FRAME: - { - std::shared_ptr itemFrame = std::dynamic_pointer_cast(hitResult->entity); - - // is the frame occupied? - if(itemFrame->getItem()!=NULL) - { - // rotate the item - *piUse=IDS_TOOLTIPS_ROTATE; - } - else - { - // is there an object in hand? - if(player->inventory->IsHeldItem()) - { - *piUse=IDS_TOOLTIPS_PLACE; - } - } - - *piAction=IDS_TOOLTIPS_HIT; - } - break; - case eTYPE_VILLAGER: - { - std::shared_ptr villager = std::dynamic_pointer_cast(hitResult->entity); - if (!villager->isBaby()) - { - *piUse=IDS_TOOLTIPS_TRADE; - } - *piAction=IDS_TOOLTIPS_HIT; - } - break; - case eTYPE_ZOMBIE: - { - std::shared_ptr zomb = std::dynamic_pointer_cast(hitResult->entity); - std::shared_ptr heldItem=nullptr; - - if(player->inventory->IsHeldItem()) - { - heldItem=player->inventory->getSelected(); - } - - if ( zomb->isVillager() && zomb->isWeakened() //zomb->hasEffect(MobEffect::weakness) - not present on client. - && heldItem != NULL && heldItem->getItem()->id == Item::apple_gold_Id ) - { - *piUse=IDS_TOOLTIPS_CURE; - } - *piAction=IDS_TOOLTIPS_HIT; - } - break; - default: - *piAction=IDS_TOOLTIPS_HIT; - break; - } - break; - } - } - } - - ui.SetTooltips( iPad, iA,iB,iX,iY,iLT,iRT,iLB,iRB); - - int wheel = 0; - unsigned int leftTicks = InputManager.GetValue(iPad, MINECRAFT_ACTION_LEFT_SCROLL, true); - unsigned int rightTicks = InputManager.GetValue(iPad, MINECRAFT_ACTION_RIGHT_SCROLL, true); - if (leftTicks > 0 && gameMode->isInputAllowed(MINECRAFT_ACTION_LEFT_SCROLL)) { - wheel = (int)leftTicks; // positive = left - } else if (rightTicks > 0 && gameMode->isInputAllowed(MINECRAFT_ACTION_RIGHT_SCROLL)) { - wheel = -(int)rightTicks; // negative = right - } - if (wheel != 0) - { - player->inventory->swapPaint(wheel); - - if( gameMode != NULL && gameMode->getTutorial() != NULL ) - { - // 4J Stu - For the tutorial we want to be able to record what items we are using so that we can give hints - gameMode->getTutorial()->onSelectedItemChanged(player->inventory->getSelected()); - } - - // Update presence - player->updateRichPresence(); - - if (options->isFlying) - { - if (wheel > 0) wheel = 1; - if (wheel < 0) wheel = -1; - - options->flySpeed += wheel * .25f; - } - } - if( gameMode->isInputAllowed(MINECRAFT_ACTION_ACTION) ) - { - if((player->ullButtonsPressed&(1LL<handleMouseClick(0); - player->lastClickTick[0] = ticks; - } - - if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION) && ticks - player->lastClickTick[0] >= timer->ticksPerSecond / 4) - { - //printf("MINECRAFT_ACTION_ACTION ButtonDown"); - player->handleMouseClick(0); - player->lastClickTick[0] = ticks; - } - - if(InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION) ) - { - player->handleMouseDown(0, true ); - } - else - { - player->handleMouseDown(0, false ); - } - } - - // 4J Stu - This is how we used to handle the USE action. It has now been replaced with the block below which is more like the way the Java game does it, - // however we may find that the way we had it previously is more fun to play. - /* - if ((InputManager.GetValue(iPad, MINECRAFT_ACTION_USE,true)>0) && gameMode->isInputAllowed(MINECRAFT_ACTION_USE) ) - { - handleMouseClick(1); - lastClickTick = ticks; - } - */ - if( player->isUsingItem() ) - { - if(!InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)) gameMode->releaseUsingItem(player); - } - else if( gameMode->isInputAllowed(MINECRAFT_ACTION_USE) ) - { - if( player->abilities.instabuild ) - { - // 4J - attempt to handle click in special creative mode fashion if possible (used for placing blocks at regular intervals) - bool didClick = player->creativeModeHandleMouseClick(1, InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE) ); - // If this handler has put us in lastClick_oldRepeat mode then it is because we aren't placing blocks - behave largely as the code used to - if( player->lastClickState == LocalPlayer::lastClick_oldRepeat ) - { - // If we've already handled the click in creativeModeHandleMouseClick then just record the time of this click - if( didClick ) - { - player->lastClickTick[1] = ticks; - } - else - { - // Otherwise just the original game code for handling autorepeat - if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE) && ticks - player->lastClickTick[1] >= timer->ticksPerSecond / 4) - { - player->handleMouseClick(1); - player->lastClickTick[1] = ticks; - } - } - } - } - else - { - // Consider as a click if we've had a period of not pressing the button, or we've reached auto-repeat time since the last time - // Auto-repeat is only considered if we aren't riding or sprinting, to avoid photo sensitivity issues when placing fire whilst doing fast things - // Also disable repeat when the player is sleeping to stop the waking up right after using the bed - bool firstClick = ( player->lastClickTick[1] == 0 ); - bool autoRepeat = ticks - player->lastClickTick[1] >= timer->ticksPerSecond / 4; - if ( player->isRiding() || player->isSprinting() || player->isSleeping() ) autoRepeat = false; - if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE) ) - { - // If the player has just exited a bed, then delay the time before a repeat key is allowed without releasing - if(player->isSleeping() ) player->lastClickTick[1] = ticks + (timer->ticksPerSecond * 2); - if( firstClick || autoRepeat ) - { - bool wasSleeping = player->isSleeping(); - - player->handleMouseClick(1); - - // If the player has just exited a bed, then delay the time before a repeat key is allowed without releasing - if(wasSleeping) player->lastClickTick[1] = ticks + (timer->ticksPerSecond * 2); - else player->lastClickTick[1] = ticks; - } - } - else - { - player->lastClickTick[1] = 0; - } - } - } - - if(app.DebugSettingsOn()) - { - if (player->ullButtonsPressed & ( 1LL << MINECRAFT_ACTION_CHANGE_SKIN) ) - { - player->ChangePlayerSkin(); - } - } - - if (player->missTime > 0) player->missTime--; + // soundEngine.playMusicTick(); + + if (!pause && level != NULL) gameMode->tick(); + MemSect(31); + glBindTexture(GL_TEXTURE_2D, + textures->loadTexture(TN_TERRAIN)); // L"/terrain.png")); + MemSect(0); + if (bFirst) { + PIXBeginNamedEvent(0, "Texture tick"); + if (!pause) textures->tick(bUpdateTextures); + PIXEndNamedEvent(); + } + + /* + * if (serverConnection != null && !(screen instanceof ErrorScreen)) { + * if (!serverConnection.isConnected()) { + * progressRenderer.progressStart("Connecting.."); + * progressRenderer.progressStagePercentage(0); } else { + * serverConnection.tick(); serverConnection.sendPosition(player); } } + */ + if (screen == NULL && player != NULL) { + if (player->getHealth() <= 0 && !ui.GetMenuDisplayed(iPad)) { + setScreen(NULL); + } else if (player->isSleeping() && level != NULL && + level->isClientSide) { + // setScreen(new InBedChatScreen()); // 4J - + // TODO put back in + } + } else if (screen != NULL && + (dynamic_cast(screen) != NULL) && + !player->isSleeping()) { + setScreen(NULL); + } + + if (screen != NULL) { + player->missTime = 10000; + player->lastClickTick[0] = ticks + 10000; + player->lastClickTick[1] = ticks + 10000; + } + + if (screen != NULL) { + screen->updateEvents(); + if (screen != NULL) { + screen->particles->tick(); + screen->tick(); + } + } + + if (screen == NULL && !ui.GetMenuDisplayed(iPad)) { + // 4J-PB - add some tooltips if required + int iA = -1, iB = -1, iX, iY = IDS_CONTROLS_INVENTORY, iLT = -1, + iRT = -1, iLB = -1, iRB = -1; + + if (player->abilities.instabuild) { + iX = IDS_TOOLTIPS_CREATIVE; + } else { + iX = IDS_CONTROLS_CRAFTING; + } + // control scheme remapping can move the Action button, so we need to + // check this + int* piAction; + int* piJump; + int* piUse; + + unsigned int uiAction = InputManager.GetGameJoypadMaps( + InputManager.GetJoypadMapVal(iPad), MINECRAFT_ACTION_ACTION); + unsigned int uiJump = InputManager.GetGameJoypadMaps( + InputManager.GetJoypadMapVal(iPad), MINECRAFT_ACTION_JUMP); + unsigned int uiUse = InputManager.GetGameJoypadMaps( + InputManager.GetJoypadMapVal(iPad), MINECRAFT_ACTION_USE); + + // Also need to handle PS3 having swapped triggers/bumpers + switch (uiAction) { + case _360_JOY_BUTTON_RT: + piAction = &iRT; + break; + case _360_JOY_BUTTON_LT: + piAction = &iLT; + break; + case _360_JOY_BUTTON_LB: + piAction = &iLB; + break; + case _360_JOY_BUTTON_RB: + piAction = &iRB; + break; + case _360_JOY_BUTTON_A: + default: + piAction = &iA; + break; + } + + switch (uiJump) { + case _360_JOY_BUTTON_LT: + piJump = &iLT; + break; + case _360_JOY_BUTTON_RT: + piJump = &iRT; + break; + case _360_JOY_BUTTON_LB: + piJump = &iLB; + break; + case _360_JOY_BUTTON_RB: + piJump = &iRB; + break; + case _360_JOY_BUTTON_A: + default: + piJump = &iA; + break; + } + + switch (uiUse) { + case _360_JOY_BUTTON_LB: + piUse = &iLB; + break; + case _360_JOY_BUTTON_RB: + piUse = &iRB; + break; + case _360_JOY_BUTTON_LT: + piUse = &iLT; + break; + case _360_JOY_BUTTON_RT: + default: + piUse = &iRT; + break; + } + + if (player->isUnderLiquid(Material::water)) { + *piJump = IDS_TOOLTIPS_SWIMUP; + } else { + *piJump = -1; + } + + *piUse = -1; + *piAction = -1; + + // 4J-PB another special case for when the player is sleeping in a bed + if (player->isSleeping() && (level != NULL) && level->isClientSide) { + *piUse = IDS_TOOLTIPS_WAKEUP; + } else { + // no hit result, but we may have something in our hand that we can + // do something with + std::shared_ptr itemInstance = + player->inventory->getSelected(); + + // 4J-JEV: Moved all this here to avoid having it in 3 different + // places. + if (itemInstance) { + // 4J-PB - very special case for boat and empty bucket and glass + // bottle and more + bool bUseItem = + gameMode->useItem(player, level, itemInstance, true); + + switch (itemInstance->getItem()->id) { + // food + case Item::potatoBaked_Id: + case Item::potato_Id: + case Item::pumpkinPie_Id: + case Item::potatoPoisonous_Id: + case Item::carrotGolden_Id: + case Item::carrots_Id: + case Item::mushroomStew_Id: + case Item::apple_Id: + case Item::bread_Id: + case Item::porkChop_raw_Id: + case Item::porkChop_cooked_Id: + case Item::apple_gold_Id: + case Item::fish_raw_Id: + case Item::fish_cooked_Id: + case Item::cookie_Id: + case Item::beef_cooked_Id: + case Item::beef_raw_Id: + case Item::chicken_cooked_Id: + case Item::chicken_raw_Id: + case Item::melon_Id: + case Item::rotten_flesh_Id: + case Item::spiderEye_Id: + // Check that we are actually hungry so will eat this + // item + { + FoodItem* food = (FoodItem*)itemInstance->getItem(); + if (food != NULL && food->canEat(player)) { + *piUse = IDS_TOOLTIPS_EAT; + } + } + break; + + case Item::milk_Id: + *piUse = IDS_TOOLTIPS_DRINK; + break; + + case Item::fishingRod_Id: // use + *piUse = IDS_TOOLTIPS_USE; + break; + + case Item::egg_Id: // throw + case Item::snowBall_Id: + *piUse = IDS_TOOLTIPS_THROW; + break; + + case Item::bow_Id: // draw or release + if (player->abilities.instabuild || + player->inventory->hasResource(Item::arrow_Id)) { + if (player->isUsingItem()) + *piUse = IDS_TOOLTIPS_RELEASE_BOW; + else + *piUse = IDS_TOOLTIPS_DRAW_BOW; + } + break; + + case Item::sword_wood_Id: + case Item::sword_stone_Id: + case Item::sword_iron_Id: + case Item::sword_diamond_Id: + case Item::sword_gold_Id: + *piUse = IDS_TOOLTIPS_BLOCK; + break; + + case Item::bucket_empty_Id: + case Item::glassBottle_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_COLLECT; + break; + + case Item::boat_Id: + case Tile::waterLily_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_PLACE; + break; + + case Item::potion_Id: + if (bUseItem) { + if (MACRO_POTION_IS_SPLASH( + itemInstance->getAuxValue())) + *piUse = IDS_TOOLTIPS_THROW; + else + *piUse = IDS_TOOLTIPS_DRINK; + } + break; + + case Item::enderPearl_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_THROW; + break; + + case Item::eyeOfEnder_Id: + // This will only work if there is a stronghold in this + // dimension + if (bUseItem && (level->dimension->id == 0) && + level->getLevelData()->getHasStronghold()) { + *piUse = IDS_TOOLTIPS_THROW; + } + break; + + case Item::expBottle_Id: + if (bUseItem) *piUse = IDS_TOOLTIPS_THROW; + break; + } + } + + if (hitResult != NULL) { + switch (hitResult->type) { + case HitResult::TILE: { + int x, y, z; + x = hitResult->x; + y = hitResult->y; + z = hitResult->z; + int face = hitResult->f; + + int iTileID = level->getTile(x, y, z); + int iData = level->getData(x, y, z); + + if (gameMode != NULL && + gameMode->getTutorial() != NULL) { + // 4J Stu - For the tutorial we want to be able to + // record what items we look at so that we can give + // hints + gameMode->getTutorial()->onLookAt(iTileID, iData); + } + + // 4J-PB - Call the useItemOn with the TestOnly flag set + bool bUseItemOn = gameMode->useItemOn( + player, level, itemInstance, x, y, z, face, + hitResult->pos, true); + + /* 4J-Jev: + * Moved this here so we have item tooltips to + * fallback on for noteblocks, enderportals and + * flowerpots in case of non-standard items. (ie. ignite + * behaviour) + */ + if (bUseItemOn && itemInstance != NULL) { + switch (itemInstance->getItem()->id) { + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + case Tile::tallgrass_Id: + case Tile::cactus_Id: + case Tile::sapling_Id: + case Tile::reeds_Id: + case Tile::flower_Id: + case Tile::rose_Id: + *piUse = IDS_TOOLTIPS_PLANT; + break; + + // Things to USE + case Item::hoe_wood_Id: + case Item::hoe_stone_Id: + case Item::hoe_iron_Id: + case Item::hoe_diamond_Id: + case Item::hoe_gold_Id: + *piUse = IDS_TOOLTIPS_TILL; + break; + + case Item::seeds_wheat_Id: + case Item::netherStalkSeeds_Id: + *piUse = IDS_TOOLTIPS_PLANT; + break; + + case Item::bucket_empty_Id: + switch (iTileID) { + // can collect lava or water in the + // empty bucket + case Tile::water_Id: + case Tile::calmWater_Id: + case Tile::lava_Id: + case Tile::calmLava_Id: + *piUse = IDS_TOOLTIPS_COLLECT; + break; + } + break; + + case Item::bucket_lava_Id: + case Item::bucket_water_Id: + *piUse = IDS_TOOLTIPS_EMPTY; + break; + + case Item::dye_powder_Id: + // bonemeal grows various plants + if (itemInstance->getAuxValue() == + DyePowderItem::WHITE) { + switch (iTileID) { + case Tile::sapling_Id: + case Tile::crops_Id: + case Tile::grass_Id: + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + case Tile::melonStem_Id: + case Tile::pumpkinStem_Id: + case Tile::carrots_Id: + case Tile::potatoes_Id: + *piUse = IDS_TOOLTIPS_GROW; + break; + } + } + break; + + case Item::painting_Id: + *piUse = IDS_TOOLTIPS_HANG; + break; + + case Item::flintAndSteel_Id: + case Item::fireball_Id: + *piUse = IDS_TOOLTIPS_IGNITE; + break; + + default: + *piUse = IDS_TOOLTIPS_PLACE; + break; + } + } + + switch (iTileID) { + case Tile::anvil_Id: + case Tile::enchantTable_Id: + case Tile::brewingStand_Id: + case Tile::workBench_Id: + case Tile::furnace_Id: + case Tile::furnace_lit_Id: + case Tile::door_wood_Id: + case Tile::dispenser_Id: + case Tile::lever_Id: + case Tile::button_stone_Id: + case Tile::button_wood_Id: + case Tile::trapdoor_Id: + case Tile::fenceGate_Id: + *piAction = IDS_TOOLTIPS_MINE; + *piUse = IDS_TOOLTIPS_USE; + break; + + case Tile::goldenRail_Id: + case Tile::detectorRail_Id: + case Tile::rail_Id: + if (bUseItemOn) *piUse = IDS_TOOLTIPS_PLACE; + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::chest_Id: + case Tile::enderChest_Id: + *piUse = IDS_TOOLTIPS_OPEN; + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::bed_Id: + if (bUseItemOn) *piUse = IDS_TOOLTIPS_SLEEP; + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::musicBlock_Id: + // if in creative mode, we will mine + if (player->abilities.instabuild) + *piAction = IDS_TOOLTIPS_MINE; + else + *piAction = IDS_TOOLTIPS_PLAY; + *piUse = IDS_TOOLTIPS_CHANGEPITCH; + break; + + case Tile::sign_Id: + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::cauldron_Id: + // special case for a cauldron of water and an + // empty bottle + if (itemInstance) { + int iID = itemInstance->getItem()->id; + int currentData = level->getData(x, y, z); + if ((iID == Item::glassBottle_Id) && + (currentData > 0)) { + *piUse = IDS_TOOLTIPS_COLLECT; + } + } + *piAction = IDS_TOOLTIPS_MINE; + break; + + case Tile::cake_Id: + if (player->abilities + .instabuild) // if in creative mode, we + // will mine + { + *piAction = IDS_TOOLTIPS_MINE; + } else { + if (player->getFoodData() + ->needsFood()) // 4J-JEV: Changed + // from healthto + // hunger. + { + *piAction = IDS_TOOLTIPS_EAT; + *piUse = IDS_TOOLTIPS_EAT; + } else { + *piAction = IDS_TOOLTIPS_MINE; + } + } + break; + + case Tile::recordPlayer_Id: + if (!bUseItemOn && itemInstance != NULL) { + int iID = itemInstance->getItem()->id; + if ((iID >= Item::record_01_Id) && + (iID <= Item::record_12_Id)) { + *piUse = IDS_TOOLTIPS_PLAY; + } + *piAction = IDS_TOOLTIPS_MINE; + } else { + if (Tile::recordPlayer->TestUse( + level, x, y, z, + player)) // means we can eject + { + *piUse = IDS_TOOLTIPS_EJECT; + } + *piAction = IDS_TOOLTIPS_MINE; + } + break; + + case Tile::flowerPot_Id: + if (!bUseItemOn && (itemInstance != NULL) && + (iData == 0)) { + int iID = itemInstance->getItem()->id; + if (iID < 256) // is it a tile? + { + switch (iID) { + case Tile::flower_Id: + case Tile::rose_Id: + case Tile::sapling_Id: + case Tile::mushroom1_Id: + case Tile::mushroom2_Id: + case Tile::cactus_Id: + case Tile::deadBush_Id: + *piUse = IDS_TOOLTIPS_PLANT; + break; + + case Tile::tallgrass_Id: + if (itemInstance + ->getAuxValue() != + TallGrass::TALL_GRASS) + *piUse = IDS_TOOLTIPS_PLANT; + break; + } + } + } + *piAction = IDS_TOOLTIPS_MINE; + break; + + default: + *piAction = IDS_TOOLTIPS_MINE; + break; + } + } break; + + case HitResult::ENTITY: + eINSTANCEOF entityType = hitResult->entity->GetType(); + + if (gameMode != NULL && + gameMode->getTutorial() != NULL) { + // 4J Stu - For the tutorial we want to be able to + // record what items we look at so that we can give + // hints + gameMode->getTutorial()->onLookAtEntity(entityType); + } + + switch (entityType) { + case eTYPE_CHICKEN: + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + switch (iID) { + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + break; + + case eTYPE_COW: + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + // It's an item + switch (iID) { + // Things to USE + case Item::bucket_empty_Id: + *piUse = IDS_TOOLTIPS_MILK; + break; + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + break; + case eTYPE_MUSHROOMCOW: + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + // It's an item + switch (iID) { + // Things to USE + case Item::bowl_Id: + case Item:: + bucket_empty_Id: // You can milk a + // mooshroom with + // either a bowl + // (mushroom soup) + // or a bucket + // (milk)! + *piUse = IDS_TOOLTIPS_MILK; + break; + case Item::shears_Id: { + if (player + ->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + if (!animal->isBaby()) + *piUse = IDS_TOOLTIPS_SHEAR; + } break; + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } else { + // 4J-PB - Fix for #13081 - No tooltip is + // displayed for hitting a cow when you have + // nothing in your hand nothing in your hand + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + } + break; + + case eTYPE_BOAT: + *piAction = IDS_TOOLTIPS_MINE; + + // are we in the boat already? + if (std::dynamic_pointer_cast( + player->riding) != NULL) { + *piUse = IDS_TOOLTIPS_EXIT; + } else { + *piUse = IDS_TOOLTIPS_SAIL; + } + break; + case eTYPE_MINECART: + *piAction = IDS_TOOLTIPS_MINE; + // are we in the minecart already? + if (std::dynamic_pointer_cast( + player->riding) != NULL) { + *piUse = IDS_TOOLTIPS_EXIT; + } else { + switch (std::dynamic_pointer_cast( + hitResult->entity) + ->type) { + case Minecart::RIDEABLE: + *piUse = IDS_TOOLTIPS_RIDE; + break; + case Minecart::CHEST: + *piUse = IDS_TOOLTIPS_OPEN; + break; + case Minecart::FURNACE: + // if you have coal, it'll go + // is there an object in hand? + if (player->inventory + ->IsHeldItem()) { + std::shared_ptr + heldItem = + player->inventory + ->getSelected(); + int iID = + heldItem->getItem()->id; + + if (iID == Item::coal->id) { + *piUse = IDS_TOOLTIPS_USE; + } else { + *piUse = IDS_TOOLTIPS_HIT; + } + } + break; + } + } + + break; + case eTYPE_SHEEP: + // can dye a sheep + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + if (player->inventory->IsHeldItem()) { + std::shared_ptr heldItem = + player->inventory->getSelected(); + int iID = heldItem->getItem()->id; + + switch (iID) { + case Item::dye_powder_Id: { + std::shared_ptr sheep = + std::dynamic_pointer_cast< + Sheep>(hitResult->entity); + // convert to tile-based color value + // (0 is white instead of black) + int newColor = ClothTile:: + getTileDataForItemAuxValue( + heldItem->getAuxValue()); + + // can only use a dye on sheep that + // haven't been sheared + if (!(sheep->isSheared() && + sheep->getColor() != + newColor)) { + *piUse = IDS_TOOLTIPS_DYE; + } + } break; + case Item::shears_Id: { + std::shared_ptr sheep = + std::dynamic_pointer_cast< + Sheep>(hitResult->entity); + + // can only shear a sheep that + // hasn't been sheared + if (!sheep->isSheared()) { + *piUse = IDS_TOOLTIPS_SHEAR; + } + } + + break; + default: { + std::shared_ptr animal = + std::dynamic_pointer_cast< + Animal>(hitResult->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == 0) && + animal->isFood(heldItem)) { + *piUse = IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + + break; + case eTYPE_PIG: + // can ride a pig + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + if (std::dynamic_pointer_cast( + player->riding) != NULL) { + *piUse = IDS_TOOLTIPS_EXIT; + } else { + // does the pig have a saddle? + if (std::dynamic_pointer_cast( + hitResult->entity) + ->hasSaddle()) { + *piUse = IDS_TOOLTIPS_RIDE; + } else if (!std::dynamic_pointer_cast( + hitResult->entity) + ->isBaby()) { + if (player->inventory->IsHeldItem()) { + std::shared_ptr + heldItem = player->inventory + ->getSelected(); + int iID = heldItem->getItem()->id; + + switch (iID) { + case Item::saddle_Id: + *piUse = + IDS_TOOLTIPS_SADDLE; + break; + default: { + std::shared_ptr + animal = std:: + dynamic_pointer_cast< + Animal>( + hitResult + ->entity); + + if (!animal->isBaby() && + !animal->isInLove() && + (animal->getAge() == + 0) && + animal->isFood( + heldItem)) { + *piUse = + IDS_TOOLTIPS_LOVEMODE; + } + } break; + } + } + } + } + + break; + case eTYPE_WOLF: + // can be tamed, fed, and made to sit/stand, or + // enter love mode + { + int iID = -1; + std::shared_ptr heldItem = + nullptr; + std::shared_ptr wolf = + std::dynamic_pointer_cast( + hitResult->entity); + + if (player->inventory->IsHeldItem()) { + heldItem = + player->inventory->getSelected(); + iID = heldItem->getItem()->id; + } + + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + + switch (iID) { + case Item::bone_Id: + if (!wolf->isAngry() && + !wolf->isTame()) { + *piUse = IDS_TOOLTIPS_TAME; + } else if ( + equalsIgnoreCase( + player->getUUID(), + wolf->getOwnerUUID())) { + if (wolf->isSitting()) { + *piUse = + IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = IDS_TOOLTIPS_SIT; + } + } + + break; + case Item::enderPearl_Id: + // Use is throw, so don't change the + // tips for the wolf + break; + case Item::dye_powder_Id: + if (wolf->isTame()) { + if (ClothTile:: + getTileDataForItemAuxValue( + heldItem + ->getAuxValue()) != + wolf->getCollarColor()) { + *piUse = + IDS_TOOLTIPS_DYECOLLAR; + } else if (wolf->isSitting()) { + *piUse = + IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = IDS_TOOLTIPS_SIT; + } + } + break; + default: + if (wolf->isTame()) { + if (wolf->isFood(heldItem)) { + if (wolf->GetSynchedHealth() < + wolf->getMaxHealth()) { + *piUse = + IDS_TOOLTIPS_HEAL; + } else { + if (!wolf->isBaby() && + !wolf->isInLove() && + (wolf->getAge() == + 0)) { + *piUse = + IDS_TOOLTIPS_LOVEMODE; + } + } + // break out here + break; + } + + if (equalsIgnoreCase( + player->getUUID(), + wolf->getOwnerUUID())) { + if (wolf->isSitting()) { + *piUse = + IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = + IDS_TOOLTIPS_SIT; + } + } + } + break; + } + } + break; + case eTYPE_OZELOT: { + int iID = -1; + std::shared_ptr heldItem = + nullptr; + std::shared_ptr ocelot = + std::dynamic_pointer_cast( + hitResult->entity); + + if (player->inventory->IsHeldItem()) { + heldItem = player->inventory->getSelected(); + iID = heldItem->getItem()->id; + } + + if (player->isAllowedToAttackAnimals()) + *piAction = IDS_TOOLTIPS_HIT; + + if (ocelot->isTame()) { + // 4J-PB - if you have a raw fish in your + // hand, you will feed the ocelot rather + // than have it sit/follow + if (ocelot->isFood(heldItem)) { + if (!ocelot->isBaby()) { + if (!ocelot->isInLove()) { + if (ocelot->getAge() == 0) { + *piUse = + IDS_TOOLTIPS_LOVEMODE; + } + } else { + *piUse = IDS_TOOLTIPS_FEED; + } + } + + } else if (equalsIgnoreCase( + player->getUUID(), + ocelot->getOwnerUUID())) { + if (ocelot->isSitting()) { + *piUse = IDS_TOOLTIPS_FOLLOWME; + } else { + *piUse = IDS_TOOLTIPS_SIT; + } + } + } else if (iID != -1) { + switch (iID) { + default: { + if (ocelot->isFood(heldItem)) + *piUse = IDS_TOOLTIPS_TAME; + } break; + } + } + } + + break; + + case eTYPE_PLAYER: { + // Fix for #58576 - TU6: Content: Gameplay: Hit + // button prompt is available when attacking a + // host who has "Invisible" option turned on + std::shared_ptr TargetPlayer = + std::dynamic_pointer_cast( + hitResult->entity); + + if (!TargetPlayer + ->hasInvisiblePrivilege()) // This + // means + // they are + // invisible, + // not just + // that + // they + // have the + // privilege + { + if (app.GetGameHostOption( + eGameHostOption_PvP) && + player->isAllowedToAttackPlayers()) { + *piAction = IDS_TOOLTIPS_HIT; + } + } + } break; + case eTYPE_ITEM_FRAME: { + std::shared_ptr itemFrame = + std::dynamic_pointer_cast( + hitResult->entity); + + // is the frame occupied? + if (itemFrame->getItem() != NULL) { + // rotate the item + *piUse = IDS_TOOLTIPS_ROTATE; + } else { + // is there an object in hand? + if (player->inventory->IsHeldItem()) { + *piUse = IDS_TOOLTIPS_PLACE; + } + } + + *piAction = IDS_TOOLTIPS_HIT; + } break; + case eTYPE_VILLAGER: { + std::shared_ptr villager = + std::dynamic_pointer_cast( + hitResult->entity); + if (!villager->isBaby()) { + *piUse = IDS_TOOLTIPS_TRADE; + } + *piAction = IDS_TOOLTIPS_HIT; + } break; + case eTYPE_ZOMBIE: { + std::shared_ptr zomb = + std::dynamic_pointer_cast( + hitResult->entity); + std::shared_ptr heldItem = + nullptr; + + if (player->inventory->IsHeldItem()) { + heldItem = player->inventory->getSelected(); + } + + if (zomb->isVillager() && + zomb->isWeakened() // zomb->hasEffect(MobEffect::weakness) + // - not present on + // client. + && heldItem != NULL && + heldItem->getItem()->id == + Item::apple_gold_Id) { + *piUse = IDS_TOOLTIPS_CURE; + } + *piAction = IDS_TOOLTIPS_HIT; + } break; + default: + *piAction = IDS_TOOLTIPS_HIT; + break; + } + break; + } + } + } + + ui.SetTooltips(iPad, iA, iB, iX, iY, iLT, iRT, iLB, iRB); + + int wheel = 0; + unsigned int leftTicks = + InputManager.GetValue(iPad, MINECRAFT_ACTION_LEFT_SCROLL, true); + unsigned int rightTicks = + InputManager.GetValue(iPad, MINECRAFT_ACTION_RIGHT_SCROLL, true); + if (leftTicks > 0 && + gameMode->isInputAllowed(MINECRAFT_ACTION_LEFT_SCROLL)) { + wheel = (int)leftTicks; // positive = left + } else if (rightTicks > 0 && + gameMode->isInputAllowed(MINECRAFT_ACTION_RIGHT_SCROLL)) { + wheel = -(int)rightTicks; // negative = right + } + if (wheel != 0) { + player->inventory->swapPaint(wheel); + + if (gameMode != NULL && gameMode->getTutorial() != NULL) { + // 4J Stu - For the tutorial we want to be able to record what + // items we are using so that we can give hints + gameMode->getTutorial()->onSelectedItemChanged( + player->inventory->getSelected()); + } + + // Update presence + player->updateRichPresence(); + + if (options->isFlying) { + if (wheel > 0) wheel = 1; + if (wheel < 0) wheel = -1; + + options->flySpeed += wheel * .25f; + } + } + if (gameMode->isInputAllowed(MINECRAFT_ACTION_ACTION)) { + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_ACTION))) + // if(InputManager.ButtonPressed(iPad, MINECRAFT_ACTION_ACTION) ) + { + // printf("MINECRAFT_ACTION_ACTION ButtonPressed"); + player->handleMouseClick(0); + player->lastClickTick[0] = ticks; + } + + if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION) && + ticks - player->lastClickTick[0] >= timer->ticksPerSecond / 4) { + // printf("MINECRAFT_ACTION_ACTION ButtonDown"); + player->handleMouseClick(0); + player->lastClickTick[0] = ticks; + } + + if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_ACTION)) { + player->handleMouseDown(0, true); + } else { + player->handleMouseDown(0, false); + } + } + + // 4J Stu - This is how we used to handle the USE action. It has now + // been replaced with the block below which is more like the way the + // Java game does it, however we may find that the way we had it + // previously is more fun to play. + /* + if ((InputManager.GetValue(iPad, MINECRAFT_ACTION_USE,true)>0) && + gameMode->isInputAllowed(MINECRAFT_ACTION_USE) ) + { + handleMouseClick(1); + lastClickTick = ticks; + } + */ + if (player->isUsingItem()) { + if (!InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)) + gameMode->releaseUsingItem(player); + } else if (gameMode->isInputAllowed(MINECRAFT_ACTION_USE)) { + if (player->abilities.instabuild) { + // 4J - attempt to handle click in special creative mode fashion + // if possible (used for placing blocks at regular intervals) + bool didClick = player->creativeModeHandleMouseClick( + 1, InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)); + // If this handler has put us in lastClick_oldRepeat mode then + // it is because we aren't placing blocks - behave largely as + // the code used to + if (player->lastClickState == + LocalPlayer::lastClick_oldRepeat) { + // If we've already handled the click in + // creativeModeHandleMouseClick then just record the time of + // this click + if (didClick) { + player->lastClickTick[1] = ticks; + } else { + // Otherwise just the original game code for handling + // autorepeat + if (InputManager.ButtonDown(iPad, + MINECRAFT_ACTION_USE) && + ticks - player->lastClickTick[1] >= + timer->ticksPerSecond / 4) { + player->handleMouseClick(1); + player->lastClickTick[1] = ticks; + } + } + } + } else { + // Consider as a click if we've had a period of not pressing the + // button, or we've reached auto-repeat time since the last time + // Auto-repeat is only considered if we aren't riding or + // sprinting, to avoid photo sensitivity issues when placing + // fire whilst doing fast things Also disable repeat when the + // player is sleeping to stop the waking up right after using + // the bed + bool firstClick = (player->lastClickTick[1] == 0); + bool autoRepeat = ticks - player->lastClickTick[1] >= + timer->ticksPerSecond / 4; + if (player->isRiding() || player->isSprinting() || + player->isSleeping()) + autoRepeat = false; + if (InputManager.ButtonDown(iPad, MINECRAFT_ACTION_USE)) { + // If the player has just exited a bed, then delay the time + // before a repeat key is allowed without releasing + if (player->isSleeping()) + player->lastClickTick[1] = + ticks + (timer->ticksPerSecond * 2); + if (firstClick || autoRepeat) { + bool wasSleeping = player->isSleeping(); + + player->handleMouseClick(1); + + // If the player has just exited a bed, then delay the + // time before a repeat key is allowed without releasing + if (wasSleeping) + player->lastClickTick[1] = + ticks + (timer->ticksPerSecond * 2); + else + player->lastClickTick[1] = ticks; + } + } else { + player->lastClickTick[1] = 0; + } + } + } + + if (app.DebugSettingsOn()) { + if (player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_CHANGE_SKIN)) { + player->ChangePlayerSkin(); + } + } + + if (player->missTime > 0) player->missTime--; #ifdef _DEBUG_MENUS_ENABLED - if(app.DebugSettingsOn()) - { + if (app.DebugSettingsOn()) { #ifndef __PSVITA__ - // 4J-PB - debugoverlay for primary player only - if(iPad==ProfileManager.GetPrimaryPad()) - { - if((player->ullButtonsPressed&(1LL<ullButtonsPressed & + (1LL << MINECRAFT_ACTION_RENDER_DEBUG))) { #ifndef _CONTENT_PACKAGE - options->renderDebug = !options->renderDebug; + options->renderDebug = !options->renderDebug; #ifdef _XBOX - app.EnableDebugOverlay(options->renderDebug,iPad); + app.EnableDebugOverlay(options->renderDebug, iPad); #else - // 4J Stu - The xbox uses a completely different way of navigating to this scene - ui.NavigateToScene(0, eUIScene_DebugOverlay, NULL, eUILayer_Debug); + // 4J Stu - The xbox uses a completely different way of + // navigating to this scene + ui.NavigateToScene(0, eUIScene_DebugOverlay, NULL, + eUILayer_Debug); #endif #endif - } + } - if((player->ullButtonsPressed&(1LL< mob = std::dynamic_pointer_cast(Creeper::_class->newInstance( level )); - //std::shared_ptr mob = std::dynamic_pointer_cast(Wolf::_class->newInstance( level )); - std::shared_ptr mob = std::dynamic_pointer_cast(std::shared_ptr(new Spider( level ))); - mob->moveTo(player->x+1, player->y, player->z+1, level->random->nextFloat() * 360, 0); - level->addEntity(mob); - } - } + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_SPAWN_CREEPER)) && + app.GetMobsDontAttackEnabled()) { + // std::shared_ptr mob = + // std::dynamic_pointer_cast(Creeper::_class->newInstance( + // level )); std::shared_ptr mob = + // std::dynamic_pointer_cast(Wolf::_class->newInstance( + // level )); + std::shared_ptr mob = std::dynamic_pointer_cast( + std::shared_ptr(new Spider(level))); + mob->moveTo(player->x + 1, player->y, player->z + 1, + level->random->nextFloat() * 360, 0); + level->addEntity(mob); + } + } - if( (player->ullButtonsPressed&(1LL<abilities.debugflying = !player->abilities.debugflying; - player->abilities.flying = !player->abilities.flying; - } -#endif // PSVITA - } + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_FLY_TOGGLE))) { + player->abilities.debugflying = !player->abilities.debugflying; + player->abilities.flying = !player->abilities.flying; + } +#endif // PSVITA + } #endif - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_RENDER_THIRD_PERSON)) - { - // 4J-PB - changing this to be per player - player->SetThirdPersonView((player->ThirdPersonView()+1)%3); - //options->thirdPersonView = !options->thirdPersonView; - } + if ((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_RENDER_THIRD_PERSON)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_RENDER_THIRD_PERSON)) { + // 4J-PB - changing this to be per player + player->SetThirdPersonView((player->ThirdPersonView() + 1) % 3); + // options->thirdPersonView = !options->thirdPersonView; + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_GAME_INFO)) - { - ui.NavigateToScene(iPad,eUIScene_InGameInfoMenu); - ui.PlayUISFX(eSFX_Press); - } + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_GAME_INFO)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_GAME_INFO)) { + ui.NavigateToScene(iPad, eUIScene_InGameInfoMenu); + ui.PlayUISFX(eSFX_Press); + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_INVENTORY)) - { - std::shared_ptr player = std::dynamic_pointer_cast( Minecraft::GetInstance()->player ); - ui.PlayUISFX(eSFX_Press); - app.LoadInventoryMenu(iPad,player); - } + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_INVENTORY)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_INVENTORY)) { + std::shared_ptr player = + std::dynamic_pointer_cast( + Minecraft::GetInstance()->player); + ui.PlayUISFX(eSFX_Press); + app.LoadInventoryMenu(iPad, player); + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_CRAFTING)) - { - std::shared_ptr player = std::dynamic_pointer_cast( Minecraft::GetInstance()->player ); + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_CRAFTING)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_CRAFTING)) { + std::shared_ptr player = + std::dynamic_pointer_cast( + Minecraft::GetInstance()->player); - // 4J-PB - reordered the if statement so creative mode doesn't bring up the crafting table - // Fix for #39014 - TU5: Creative Mode: Pressing X to access the creative menu while looking at a crafting table causes the crafting menu to display - if(gameMode->hasInfiniteItems()) - { - // Creative mode + // 4J-PB - reordered the if statement so creative mode doesn't bring + // up the crafting table Fix for #39014 - TU5: Creative Mode: + // Pressing X to access the creative menu while looking at a + // crafting table causes the crafting menu to display + if (gameMode->hasInfiniteItems()) { + // Creative mode - ui.PlayUISFX(eSFX_Press); - app.LoadCreativeMenu(iPad,player); - } - // 4J-PB - Microsoft request that we use the 3x3 crafting if someone presses X while at the workbench - else if ((hitResult!=NULL) && (hitResult->type == HitResult::TILE) && (level->getTile(hitResult->x, hitResult->y, hitResult->z) == Tile::workBench_Id)) - { - //ui.PlayUISFX(eSFX_Press); - //app.LoadXuiCrafting3x3Menu(iPad,player,hitResult->x, hitResult->y, hitResult->z); - bool usedItem = false; - gameMode->useItemOn(player, level, nullptr, hitResult->x, hitResult->y, hitResult->z, 0, hitResult->pos, false, &usedItem); - } - else - { - ui.PlayUISFX(eSFX_Press); - app.LoadCrafting2x2Menu(iPad,player); - } - } + ui.PlayUISFX(eSFX_Press); + app.LoadCreativeMenu(iPad, player); + } + // 4J-PB - Microsoft request that we use the 3x3 crafting if someone + // presses X while at the workbench + else if ((hitResult != NULL) && + (hitResult->type == HitResult::TILE) && + (level->getTile(hitResult->x, hitResult->y, + hitResult->z) == Tile::workBench_Id)) { + // ui.PlayUISFX(eSFX_Press); + // app.LoadXuiCrafting3x3Menu(iPad,player,hitResult->x, + // hitResult->y, hitResult->z); + bool usedItem = false; + gameMode->useItemOn(player, level, nullptr, hitResult->x, + hitResult->y, hitResult->z, 0, + hitResult->pos, false, &usedItem); + } else { + ui.PlayUISFX(eSFX_Press); + app.LoadCrafting2x2Menu(iPad, player); + } + } - if ( (player->ullButtonsPressed&(1LL<ullButtonsPressed&(1LL<ullButtonsPressed & (1LL << MINECRAFT_ACTION_PAUSEMENU)) +#ifdef _DURANGO + || (player->ullButtonsPressed & (1LL << ACTION_MENU_GTC_PAUSE)) #endif - ) - { - app.DebugPrintf("PAUSE PRESS PROCESSING - ipad = %d, NavigateToScene\n",player->GetXboxPad()); - ui.PlayUISFX(eSFX_Press); - ui.NavigateToScene(iPad, eUIScene_PauseMenu, NULL, eUILayer_Scene); - } + ) { + app.DebugPrintf( + "PAUSE PRESS PROCESSING - ipad = %d, NavigateToScene\n", + player->GetXboxPad()); + ui.PlayUISFX(eSFX_Press); + ui.NavigateToScene(iPad, eUIScene_PauseMenu, NULL, eUILayer_Scene); + } - if((player->ullButtonsPressed&(1LL<isInputAllowed(MINECRAFT_ACTION_DROP)) - { - player->drop(); - } + if ((player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_DROP)) && + gameMode->isInputAllowed(MINECRAFT_ACTION_DROP)) { + player->drop(); + } + + __uint64 ullButtonsPressed = player->ullButtonsPressed; + + bool selected = false; - __uint64 ullButtonsPressed=player->ullButtonsPressed; - - bool selected = false; - #ifdef __PSVITA__ - // 4J-PB - use the touchscreen for quickselect - SceTouchData* pTouchData = InputManager.GetTouchPadData(iPad,false); + // 4J-PB - use the touchscreen for quickselect + SceTouchData* pTouchData = InputManager.GetTouchPadData(iPad, false); - if(pTouchData->reportNum==1) - { - int iHudSize=app.GetGameSettings(iPad,eGameSetting_UISize); - if((pTouchData->report[0].x>QuickSelectRect[iHudSize].left)&&(pTouchData->report[0].xreport[0].y>QuickSelectRect[iHudSize].top)&&(pTouchData->report[0].yinventory->selected=(pTouchData->report[0].x-QuickSelectRect[iHudSize].left)/QuickSelectBoxWidth[iHudSize]; - selected = true; - app.DebugPrintf("Touch %d\n",player->inventory->selected); - } - } + if (pTouchData->reportNum == 1) { + int iHudSize = app.GetGameSettings(iPad, eGameSetting_UISize); + if ((pTouchData->report[0].x > QuickSelectRect[iHudSize].left) && + (pTouchData->report[0].x < QuickSelectRect[iHudSize].right) && + (pTouchData->report[0].y > QuickSelectRect[iHudSize].top) && + (pTouchData->report[0].y < QuickSelectRect[iHudSize].bottom)) { + player->inventory->selected = + (pTouchData->report[0].x - QuickSelectRect[iHudSize].left) / + QuickSelectBoxWidth[iHudSize]; + selected = true; + app.DebugPrintf("Touch %d\n", player->inventory->selected); + } + } #endif - { - int hotbarSlot = InputManager.GetHotbarSlotPressed(iPad); - if (hotbarSlot >= 0 && hotbarSlot <= 9) - { - player->inventory->selected = hotbarSlot; - selected = true; - } - } - if( selected || wheel != 0 || (player->ullButtonsPressed&(1LL< selectedItem = player->getSelectedItem(); - // Dropping items happens over network, so if we only have one then assume that we dropped it and should hide the item - int iCount=0; - - if(selectedItem != NULL) iCount=selectedItem->GetCount(); - if(selectedItem != NULL && !( (player->ullButtonsPressed&(1LL<GetCount() == 1)) - { - itemName = selectedItem->getHoverName(); - } - if( !(player->ullButtonsPressed&(1LL<GetCount() <= 1) ) ui.SetSelectedItem( iPad, itemName ); - } - } - else - { - // 4J-PB - if (InputManager.GetValue(iPad, ACTION_MENU_CANCEL) > 0 && gameMode->isInputAllowed(ACTION_MENU_CANCEL)) - { - setScreen(NULL); - } - } + { + int hotbarSlot = InputManager.GetHotbarSlotPressed(iPad); + if (hotbarSlot >= 0 && hotbarSlot <= 9) { + player->inventory->selected = hotbarSlot; + selected = true; + } + } + if (selected || wheel != 0 || + (player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_DROP))) { + std::wstring itemName = L""; + std::shared_ptr selectedItem = + player->getSelectedItem(); + // Dropping items happens over network, so if we only have one then + // assume that we dropped it and should hide the item + int iCount = 0; - // monitor for keyboard input - // #ifndef _CONTENT_PACKAGE - // if(!(ui.GetMenuDisplayed(iPad))) - // { - // WCHAR wchInput; - // if(InputManager.InputDetected(iPad,&wchInput)) - // { - // printf("Input Detected!\n"); - // - // // see if we can react to this - // if(app.GetXuiAction(iPad)==eAppAction_Idle) - // { - // app.SetAction(iPad,eAppAction_DebugText,(LPVOID)wchInput); - // } - // } - // } - // #endif + if (selectedItem != NULL) iCount = selectedItem->GetCount(); + if (selectedItem != NULL && !((player->ullButtonsPressed & + (1LL << MINECRAFT_ACTION_DROP)) && + selectedItem->GetCount() == 1)) { + itemName = selectedItem->getHoverName(); + } + if (!(player->ullButtonsPressed & (1LL << MINECRAFT_ACTION_DROP)) || + (selectedItem != NULL && selectedItem->GetCount() <= 1)) + ui.SetSelectedItem(iPad, itemName); + } + } else { + // 4J-PB + if (InputManager.GetValue(iPad, ACTION_MENU_CANCEL) > 0 && + gameMode->isInputAllowed(ACTION_MENU_CANCEL)) { + setScreen(NULL); + } + } + + // monitor for keyboard input + // #ifndef _CONTENT_PACKAGE + // if(!(ui.GetMenuDisplayed(iPad))) + // { + // WCHAR wchInput; + // if(InputManager.InputDetected(iPad,&wchInput)) + // { + // printf("Input Detected!\n"); + // + // // see if we can react to this + // if(app.GetXuiAction(iPad)==eAppAction_Idle) + // { + // app.SetAction(iPad,eAppAction_DebugText,(LPVOID)wchInput); + // } + // } + // } + // #endif #if 0 // 4J - TODO - some replacement for input handling... @@ -3632,388 +3838,397 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } #endif - if (level != NULL) - { - if (player != NULL) - { - recheckPlayerIn++; - if (recheckPlayerIn == 30) - { - recheckPlayerIn = 0; - level->ensureAdded(player); - } - } - // 4J Changed - We are setting the difficulty the same as the server so that leaderboard updates work correctly - //level->difficulty = options->difficulty; - //if (level->isClientSide) level->difficulty = Difficulty::HARD; - if( !level->isClientSide ) - { - //app.DebugPrintf("Minecraft::tick - Difficulty = %d",options->difficulty); - level->difficulty = options->difficulty; - } + if (level != NULL) { + if (player != NULL) { + recheckPlayerIn++; + if (recheckPlayerIn == 30) { + recheckPlayerIn = 0; + level->ensureAdded(player); + } + } + // 4J Changed - We are setting the difficulty the same as the server so + // that leaderboard updates work correctly + // level->difficulty = options->difficulty; + // if (level->isClientSide) level->difficulty = Difficulty::HARD; + if (!level->isClientSide) { + // app.DebugPrintf("Minecraft::tick - Difficulty = + // %d",options->difficulty); + level->difficulty = options->difficulty; + } - PIXBeginNamedEvent(0,"Game renderer tick"); - if (!pause) gameRenderer->tick( bFirst); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Game renderer tick"); + if (!pause) gameRenderer->tick(bFirst); + PIXEndNamedEvent(); - // 4J - we want to tick each level once only per frame, and do it when a player that is actually in that level happens to be active. - // This is important as things that get called in the level tick (eg the levellistener) eventually end up working out what the current - // level is by determing it from the current player. Use flags here to make sure each level is only ticked the once. - static unsigned int levelsTickedFlags; - if( bFirst ) - { - levelsTickedFlags = 0; + // 4J - we want to tick each level once only per frame, and do it when a + // player that is actually in that level happens to be active. This is + // important as things that get called in the level tick (eg the + // levellistener) eventually end up working out what the current level + // is by determing it from the current player. Use flags here to make + // sure each level is only ticked the once. + static unsigned int levelsTickedFlags; + if (bFirst) { + levelsTickedFlags = 0; #ifndef DISABLE_LEVELTICK_THREAD - PIXBeginNamedEvent(0,"levelTickEventQueue waitForFinish"); - levelTickEventQueue->waitForFinish(); - PIXEndNamedEvent(); -#endif // DISABLE_LEVELTICK_THREAD - SparseLightStorage::tick(); // 4J added - CompressedTileStorage::tick(); // 4J added - SparseDataStorage::tick(); // 4J added - } + PIXBeginNamedEvent(0, "levelTickEventQueue waitForFinish"); + levelTickEventQueue->waitForFinish(); + PIXEndNamedEvent(); +#endif // DISABLE_LEVELTICK_THREAD + SparseLightStorage::tick(); // 4J added + CompressedTileStorage::tick(); // 4J added + SparseDataStorage::tick(); // 4J added + } - for(unsigned int i = 0; i < levels.length; ++i) - { - if( player->level != levels[i] ) continue; // Don't tick if the current player isn't in this level + for (unsigned int i = 0; i < levels.length; ++i) { + if (player->level != levels[i]) + continue; // Don't tick if the current player isn't in this + // level - // 4J - this doesn't fully tick the animateTick here, but does register this player's position. The actual - // work is now done in Level::animateTickDoWork() so we can take into account multiple players in the one level. - if (!pause && levels[i] != NULL) levels[i]->animateTick(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + // 4J - this doesn't fully tick the animateTick here, but does + // register this player's position. The actual work is now done in + // Level::animateTickDoWork() so we can take into account multiple + // players in the one level. + if (!pause && levels[i] != NULL) + levels[i]->animateTick(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z)); - if( levelsTickedFlags & ( 1 << i ) ) continue; // Don't tick further if we've already ticked this level this frame - levelsTickedFlags |= (1 << i); + if (levelsTickedFlags & (1 << i)) + continue; // Don't tick further if we've already ticked this + // level this frame + levelsTickedFlags |= (1 << i); - PIXBeginNamedEvent(0,"Level renderer tick"); - if (!pause) levelRenderer->tick(); - PIXEndNamedEvent(); - // if (!pause && player!=null) { - // if (player != null && !level.entities.contains(player)) { - // level.addEntity(player); - // } - // } - if( levels[i] != NULL ) - { - if (!pause) - { - if (levels[i]->lightningBoltTime > 0) levels[i]->lightningBoltTime--; - PIXBeginNamedEvent(0,"Level entity tick"); - levels[i]->tickEntities(); - PIXEndNamedEvent(); - } + PIXBeginNamedEvent(0, "Level renderer tick"); + if (!pause) levelRenderer->tick(); + PIXEndNamedEvent(); + // if (!pause && player!=null) { + // if (player != null && !level.entities.contains(player)) { + // level.addEntity(player); + // } + // } + if (levels[i] != NULL) { + if (!pause) { + if (levels[i]->lightningBoltTime > 0) + levels[i]->lightningBoltTime--; + PIXBeginNamedEvent(0, "Level entity tick"); + levels[i]->tickEntities(); + PIXEndNamedEvent(); + } - // optimisation to set the culling off early, in parallel with other stuff + // optimisation to set the culling off early, in parallel with + // other stuff #if defined __PS3__ && !defined DISABLE_SPU_CODE - // kick off the culling for all valid players in this level - int currPlayerIdx = getLocalPlayerIdx(); - for( int idx = 0; idx < XUSER_MAX_COUNT; idx++ ) - { - if(localplayers[idx]!=NULL) - { - if( localplayers[idx]->level == levels[i] ) - { - setLocalPlayerIdx(idx); - gameRenderer->setupCamera(timer->a, i); - Camera::prepare(localplayers[idx], localplayers[idx]->ThirdPersonView() == 2); - std::shared_ptr cameraEntity = cameraTargetPlayer; - double xOff = cameraEntity->xOld + (cameraEntity->x - cameraEntity->xOld) * timer->a; - double yOff = cameraEntity->yOld + (cameraEntity->y - cameraEntity->yOld) * timer->a; - double zOff = cameraEntity->zOld + (cameraEntity->z - cameraEntity->zOld) * timer->a; - FrustumCuller frustObj; - Culler *frustum = &frustObj; - MemSect(0); - frustum->prepare(xOff, yOff, zOff); - levelRenderer->cull_SPU(idx, frustum, 0); - } - } - } - setLocalPlayerIdx(currPlayerIdx); -#endif // __PS3__ + // kick off the culling for all valid players in this level + int currPlayerIdx = getLocalPlayerIdx(); + for (int idx = 0; idx < XUSER_MAX_COUNT; idx++) { + if (localplayers[idx] != NULL) { + if (localplayers[idx]->level == levels[i]) { + setLocalPlayerIdx(idx); + gameRenderer->setupCamera(timer->a, i); + Camera::prepare( + localplayers[idx], + localplayers[idx]->ThirdPersonView() == 2); + std::shared_ptr cameraEntity = + cameraTargetPlayer; + double xOff = + cameraEntity->xOld + + (cameraEntity->x - cameraEntity->xOld) * + timer->a; + double yOff = + cameraEntity->yOld + + (cameraEntity->y - cameraEntity->yOld) * + timer->a; + double zOff = + cameraEntity->zOld + + (cameraEntity->z - cameraEntity->zOld) * + timer->a; + FrustumCuller frustObj; + Culler* frustum = &frustObj; + MemSect(0); + frustum->prepare(xOff, yOff, zOff); + levelRenderer->cull_SPU(idx, frustum, 0); + } + } + } + setLocalPlayerIdx(currPlayerIdx); +#endif // __PS3__ - // 4J Stu - We are always online, but still could be paused - if (!pause) // || isClientSide()) - { - //app.DebugPrintf("Minecraft::tick spawn settings - Difficulty = %d",options->difficulty); - levels[i]->setSpawnSettings(level->difficulty > 0, true); - PIXBeginNamedEvent(0,"Level tick"); + // 4J Stu - We are always online, but still could be paused + if (!pause) // || isClientSide()) + { + // app.DebugPrintf("Minecraft::tick spawn settings - + // Difficulty = %d",options->difficulty); + levels[i]->setSpawnSettings(level->difficulty > 0, true); + PIXBeginNamedEvent(0, "Level tick"); #ifdef DISABLE_LEVELTICK_THREAD - levels[i]->tick(); + levels[i]->tick(); #else - levelTickEventQueue->sendEvent(levels[i]); -#endif // DISABLE_LEVELTICK_THREAD - PIXEndNamedEvent(); - } - } - } + levelTickEventQueue->sendEvent(levels[i]); +#endif // DISABLE_LEVELTICK_THREAD + PIXEndNamedEvent(); + } + } + } - if( bFirst ) - { - PIXBeginNamedEvent(0,"Particle tick"); - if (!pause) particleEngine->tick(); - PIXEndNamedEvent(); - } + if (bFirst) { + PIXBeginNamedEvent(0, "Particle tick"); + if (!pause) particleEngine->tick(); + PIXEndNamedEvent(); + } - // 4J Stu - Keep ticking the connections if paused so that they don't time out - if( pause ) tickAllConnections(); - // player->tick(); - } + // 4J Stu - Keep ticking the connections if paused so that they don't + // time out + if (pause) tickAllConnections(); + // player->tick(); + } #ifdef __PS3__ -// while(!g_tickLevelQueue.empty()) -// { -// Level* pLevel = g_tickLevelQueue.front(); -// g_tickLevelQueue.pop(); -// pLevel->tick(); -// }; + // while(!g_tickLevelQueue.empty()) + // { + // Level* pLevel = g_tickLevelQueue.front(); + // g_tickLevelQueue.pop(); + // pLevel->tick(); + // }; #endif - // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD7) || - // Keyboard.isKeyDown(Keyboard.KEY_Q)) rota++; - // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD9) || - // Keyboard.isKeyDown(Keyboard.KEY_E)) rota--; - // 4J removed - //lastTickTime = System::currentTimeMillis(); + // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD7) || + // Keyboard.isKeyDown(Keyboard.KEY_Q)) rota++; + // if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD9) || + // Keyboard.isKeyDown(Keyboard.KEY_E)) rota--; + // 4J removed + // lastTickTime = System::currentTimeMillis(); } -void Minecraft::reloadSound() -{ - // System.out.println("FORCING RELOAD!"); // 4J - removed - soundEngine = new SoundEngine(); - soundEngine->init(options); - bgLoader->forceReload(); +void Minecraft::reloadSound() { + // System.out.println("FORCING RELOAD!"); // 4J - removed + soundEngine = new SoundEngine(); + soundEngine->init(options); + bgLoader->forceReload(); } -bool Minecraft::isClientSide() -{ - return level != NULL && level->isClientSide; +bool Minecraft::isClientSide() { return level != NULL && level->isClientSide; } + +void Minecraft::selectLevel(ConsoleSaveFile* saveFile, + const std::wstring& levelId, + const std::wstring& levelName, + LevelSettings* levelSettings) {} + +bool Minecraft::saveSlot(int slot, const std::wstring& name) { return false; } + +bool Minecraft::loadSlot(const std::wstring& userName, int slot) { + return false; } -void Minecraft::selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, const std::wstring& levelName, LevelSettings *levelSettings) -{ - } - -bool Minecraft::saveSlot(int slot, const std::wstring& name) -{ - return false; +void Minecraft::releaseLevel(int message) { + // this->level = NULL; + setLevel(NULL, message); } -bool Minecraft::loadSlot(const std::wstring& userName, int slot) -{ - return false; -} +// 4J Stu - This code was within setLevel, but I moved it out so that I can call +// it at a better time when exiting from an online game +void Minecraft::forceStatsSave(int idx) { + // 4J Gordon: Force a stats save + stats[idx]->save(idx, true); -void Minecraft::releaseLevel(int message) -{ - //this->level = NULL; - setLevel(NULL, message); -} - -// 4J Stu - This code was within setLevel, but I moved it out so that I can call it at a better -// time when exiting from an online game -void Minecraft::forceStatsSave(int idx) -{ - //4J Gordon: Force a stats save - stats[idx]->save(idx, true); - - //4J Gordon: If the player is signed in, save the leaderboards - if( ProfileManager.IsSignedInLive(idx) ) - { - int tempLockedProfile = ProfileManager.GetLockedProfile(); - ProfileManager.SetLockedProfile(idx); - stats[idx]->saveLeaderboards(); - ProfileManager.SetLockedProfile(tempLockedProfile); - } + // 4J Gordon: If the player is signed in, save the leaderboards + if (ProfileManager.IsSignedInLive(idx)) { + int tempLockedProfile = ProfileManager.GetLockedProfile(); + ProfileManager.SetLockedProfile(idx); + stats[idx]->saveLeaderboards(); + ProfileManager.SetLockedProfile(tempLockedProfile); + } } // 4J Added -MultiPlayerLevel *Minecraft::getLevel(int dimension) -{ - if (dimension == -1) return levels[1]; - else if(dimension == 1) return levels[2]; - else return levels[0]; +MultiPlayerLevel* Minecraft::getLevel(int dimension) { + if (dimension == -1) + return levels[1]; + else if (dimension == 1) + return levels[2]; + else + return levels[0]; } // 4J Stu - Removed as redundant with default values in params. -//void Minecraft::setLevel(Level *level, bool doForceStatsSave /*= true*/) +// void Minecraft::setLevel(Level *level, bool doForceStatsSave /*= true*/) //{ // setLevel(level, -1, NULL, doForceStatsSave); //} // Also causing ambiguous call for some reason -// as it is matching std::shared_ptr from the func below with bool from this one -//void Minecraft::setLevel(Level *level, const std::wstring& message, bool doForceStatsSave /*= true*/) +// as it is matching std::shared_ptr from the func below with bool from +// this one +// void Minecraft::setLevel(Level *level, const std::wstring& message, bool +// doForceStatsSave /*= true*/) //{ // setLevel(level, message, NULL, doForceStatsSave); //} -void Minecraft::forceaddLevel(MultiPlayerLevel *level) -{ - int dimId = level->dimension->id; - if (dimId == -1) levels[1] = level; - else if(dimId == 1) levels[2] = level; - else levels[0] = level; +void Minecraft::forceaddLevel(MultiPlayerLevel* level) { + int dimId = level->dimension->id; + if (dimId == -1) + levels[1] = level; + else if (dimId == 1) + levels[2] = level; + else + levels[0] = level; } -void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, std::shared_ptr forceInsertPlayer /*=NULL*/, bool doForceStatsSave /*=true*/, bool bPrimaryPlayerSignedOut /*=false*/) -{ - EnterCriticalSection(&m_setLevelCS); - bool playerAdded = false; - this->cameraTargetPlayer = nullptr; +void Minecraft::setLevel(MultiPlayerLevel* level, int message /*=-1*/, + std::shared_ptr forceInsertPlayer /*=NULL*/, + bool doForceStatsSave /*=true*/, + bool bPrimaryPlayerSignedOut /*=false*/) { + EnterCriticalSection(&m_setLevelCS); + bool playerAdded = false; + this->cameraTargetPlayer = nullptr; - if(progressRenderer != NULL) - { - this->progressRenderer->progressStart(message); - this->progressRenderer->progressStage(-1); - } + if (progressRenderer != NULL) { + this->progressRenderer->progressStart(message); + this->progressRenderer->progressStage(-1); + } - // 4J-PB - since we now play music in the menu, just let it keep playing - //soundEngine->playStreaming(L"", 0, 0, 0, 0, 0); + // 4J-PB - since we now play music in the menu, just let it keep playing + // soundEngine->playStreaming(L"", 0, 0, 0, 0, 0); - // 4J - stop update thread from processing this level, which blocks until it is safe to move on - will be re-enabled if we set the level to be non-NULL - gameRenderer->DisableUpdateThread(); + // 4J - stop update thread from processing this level, which blocks until it + // is safe to move on - will be re-enabled if we set the level to be + // non-NULL + gameRenderer->DisableUpdateThread(); - for(unsigned int i = 0; i < levels.length; ++i) - { - // 4J We only need to save out in multiplayer is we are setting the level to NULL - // If we ever go back to making single player only then this will not work properly! - if (levels[i] != NULL && level == NULL) - { - // 4J Stu - This is really only relevant for single player (ie not what we do at the moment) - if((doForceStatsSave==true) && player!=NULL) - forceStatsSave(player->GetXboxPad() ); + for (unsigned int i = 0; i < levels.length; ++i) { + // 4J We only need to save out in multiplayer is we are setting the + // level to NULL If we ever go back to making single player only then + // this will not work properly! + if (levels[i] != NULL && level == NULL) { + // 4J Stu - This is really only relevant for single player (ie not + // what we do at the moment) + if ((doForceStatsSave == true) && player != NULL) + forceStatsSave(player->GetXboxPad()); - // 4J Stu - Added these for the case when we exit a level so we are setting the level to NULL - // The level renderer needs to have it's stored level set to NULL so that it doesn't break next time we set one - if (levelRenderer != NULL) - { - for(unsigned int p = 0; p < XUSER_MAX_COUNT; ++p) - { - levelRenderer->setLevel(p, NULL); - } - } - if (particleEngine != NULL) particleEngine->setLevel(NULL); - } - } - // 4J If we are setting the level to NULL then we are exiting, so delete the levels - if( level == NULL ) - { - if(levels[0]!=NULL) - { - delete levels[0]; - levels[0] = NULL; + // 4J Stu - Added these for the case when we exit a level so we are + // setting the level to NULL The level renderer needs to have it's + // stored level set to NULL so that it doesn't break next time we + // set one + if (levelRenderer != NULL) { + for (unsigned int p = 0; p < XUSER_MAX_COUNT; ++p) { + levelRenderer->setLevel(p, NULL); + } + } + if (particleEngine != NULL) particleEngine->setLevel(NULL); + } + } + // 4J If we are setting the level to NULL then we are exiting, so delete the + // levels + if (level == NULL) { + if (levels[0] != NULL) { + delete levels[0]; + levels[0] = NULL; - // Both level share the same savedDataStorage - if(levels[1]!=NULL) levels[1]->savedDataStorage = NULL; - } - if(levels[1]!=NULL) - { - delete levels[1]; - levels[1] = NULL; - } - if(levels[2]!=NULL) - { - delete levels[2]; - levels[2] = NULL; - } + // Both level share the same savedDataStorage + if (levels[1] != NULL) levels[1]->savedDataStorage = NULL; + } + if (levels[1] != NULL) { + delete levels[1]; + levels[1] = NULL; + } + if (levels[2] != NULL) { + delete levels[2]; + levels[2] = NULL; + } - // Delete all the player objects - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - std::shared_ptr mplp = localplayers[idx]; - if(mplp != NULL && mplp->connection != NULL ) - { - delete mplp->connection; - mplp->connection = NULL; - } + // Delete all the player objects + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + std::shared_ptr mplp = localplayers[idx]; + if (mplp != NULL && mplp->connection != NULL) { + delete mplp->connection; + mplp->connection = NULL; + } - if( localgameModes[idx] != NULL ) - { - delete localgameModes[idx]; - localgameModes[idx] = NULL; - } + if (localgameModes[idx] != NULL) { + delete localgameModes[idx]; + localgameModes[idx] = NULL; + } - if( m_pendingLocalConnections[idx] != NULL ) - { - delete m_pendingLocalConnections[idx]; - m_pendingLocalConnections[idx] = NULL; - } + if (m_pendingLocalConnections[idx] != NULL) { + delete m_pendingLocalConnections[idx]; + m_pendingLocalConnections[idx] = NULL; + } - localplayers[idx] = nullptr; - } - // If we are removing the primary player then there can't be a valid gamemode left anymore, this - // pointer will be referring to the one we've just deleted - gameMode = NULL; - // Remove references to player - player = nullptr; - cameraTargetPlayer = nullptr; - EntityRenderDispatcher::instance->cameraEntity = nullptr; - TileEntityRenderDispatcher::instance->cameraEntity = nullptr; - } - this->level = level; + localplayers[idx] = nullptr; + } + // If we are removing the primary player then there can't be a valid + // gamemode left anymore, this pointer will be referring to the one + // we've just deleted + gameMode = NULL; + // Remove references to player + player = nullptr; + cameraTargetPlayer = nullptr; + EntityRenderDispatcher::instance->cameraEntity = nullptr; + TileEntityRenderDispatcher::instance->cameraEntity = nullptr; + } + this->level = level; - if (level != NULL) - { - int dimId = level->dimension->id; - if (dimId == -1) levels[1] = level; - else if(dimId == 1) levels[2] = level; - else levels[0] = level; + if (level != NULL) { + int dimId = level->dimension->id; + if (dimId == -1) + levels[1] = level; + else if (dimId == 1) + levels[2] = level; + else + levels[0] = level; - // If no player has been set, then this is the first level to be set this game, so set up - // a primary player & initialise some other things - if (player == NULL) - { - int iPrimaryPlayer = ProfileManager.GetPrimaryPad(); + // If no player has been set, then this is the first level to be set + // this game, so set up a primary player & initialise some other things + if (player == NULL) { + int iPrimaryPlayer = ProfileManager.GetPrimaryPad(); - player = gameMode->createPlayer(level); + player = gameMode->createPlayer(level); - PlayerUID playerXUIDOffline = INVALID_XUID; - PlayerUID playerXUIDOnline = INVALID_XUID; - ProfileManager.GetXUID(iPrimaryPlayer,&playerXUIDOffline,false); - ProfileManager.GetXUID(iPrimaryPlayer,&playerXUIDOnline,true); + PlayerUID playerXUIDOffline = INVALID_XUID; + PlayerUID playerXUIDOnline = INVALID_XUID; + ProfileManager.GetXUID(iPrimaryPlayer, &playerXUIDOffline, false); + ProfileManager.GetXUID(iPrimaryPlayer, &playerXUIDOnline, true); #ifdef __PSVITA__ - if(CGameNetworkManager::usingAdhocMode() && playerXUIDOnline.getOnlineID()[0] == 0) - { - // player doesn't have an online UID, set it from the player name - playerXUIDOnline.setForAdhoc(); - } + if (CGameNetworkManager::usingAdhocMode() && + playerXUIDOnline.getOnlineID()[0] == 0) { + // player doesn't have an online UID, set it from the player + // name + playerXUIDOnline.setForAdhoc(); + } #endif - player->setXuid(playerXUIDOffline); - player->setOnlineXuid(playerXUIDOnline); + player->setXuid(playerXUIDOffline); + player->setOnlineXuid(playerXUIDOnline); - player->displayName = ProfileManager.GetDisplayName(iPrimaryPlayer); + player->displayName = ProfileManager.GetDisplayName(iPrimaryPlayer); + player->resetPos(); + gameMode->initPlayer(player); + player->SetXboxPad(iPrimaryPlayer); - player->resetPos(); - gameMode->initPlayer(player); - - player->SetXboxPad(iPrimaryPlayer); + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + m_pendingLocalConnections[i] = NULL; + if (i != iPrimaryPlayer) localgameModes[i] = NULL; + } + } - for(int i=0;iresetPos(); + // gameMode.initPlayer(player); + if (level != NULL) { + level->addEntity(player); + playerAdded = true; + } + } - if (player != NULL) - { - player->resetPos(); - // gameMode.initPlayer(player); - if (level != NULL) - { - level->addEntity(player); - playerAdded = true; - } - } + if (player->input != NULL) delete player->input; + player->input = new Input(); - if(player->input != NULL) delete player->input; - player->input = new Input(); - - if (levelRenderer != NULL) levelRenderer->setLevel(player->GetXboxPad(), level); - if (particleEngine != NULL) particleEngine->setLevel(level); + if (levelRenderer != NULL) + levelRenderer->setLevel(player->GetXboxPad(), level); + if (particleEngine != NULL) particleEngine->setLevel(level); #if 0 // 4J - removed - we don't use ChunkCache anymore @@ -4029,60 +4244,55 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, std::shar spcc->centerOn(xt, zt); } #endif - gameMode->adjustPlayer(player); + gameMode->adjustPlayer(player); - for(int i=0;icameraTargetPlayer = player; + this->cameraTargetPlayer = player; - // 4J - allow update thread to start processing the level now both it & the player should be ok - gameRenderer->EnableUpdateThread(); - } - else - { - levelSource->clearAll(); - player = nullptr; + // 4J - allow update thread to start processing the level now both it & + // the player should be ok + gameRenderer->EnableUpdateThread(); + } else { + levelSource->clearAll(); + player = nullptr; - // Clear all players if the new level is NULL - for(int i=0;iclose(); - m_pendingLocalConnections[i] = NULL; - localplayers[i] = nullptr; - localgameModes[i] = NULL; - } - } + // Clear all players if the new level is NULL + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (m_pendingLocalConnections[i] != NULL) + m_pendingLocalConnections[i]->close(); + m_pendingLocalConnections[i] = NULL; + localplayers[i] = nullptr; + localgameModes[i] = NULL; + } + } - // System.gc(); // 4J - removed - // 4J removed - //this->lastTickTime = 0; - LeaveCriticalSection(&m_setLevelCS); + // System.gc(); // 4J - removed + // 4J removed + // this->lastTickTime = 0; + LeaveCriticalSection(&m_setLevelCS); } -void Minecraft::prepareLevel(int title) -{ - if(progressRenderer != NULL) - { - this->progressRenderer->progressStart(title); - this->progressRenderer->progressStage(IDS_PROGRESS_BUILDING_TERRAIN); - } - int r = 128; - if (gameMode->isCutScene()) r = 64; - int pp = 0; - int max = r * 2 / 16 + 1; - max = max * max; - ChunkSource *cs = level->getChunkSource(); +void Minecraft::prepareLevel(int title) { + if (progressRenderer != NULL) { + this->progressRenderer->progressStart(title); + this->progressRenderer->progressStage(IDS_PROGRESS_BUILDING_TERRAIN); + } + int r = 128; + if (gameMode->isCutScene()) r = 64; + int pp = 0; + int max = r * 2 / 16 + 1; + max = max * max; + ChunkSource* cs = level->getChunkSource(); - Pos *spawnPos = level->getSharedSpawnPos(); - if (player != NULL) - { - spawnPos->x = (int) player->x; - spawnPos->z = (int) player->z; - } + Pos* spawnPos = level->getSharedSpawnPos(); + if (player != NULL) { + spawnPos->x = (int)player->x; + spawnPos->z = (int)player->z; + } #if 0 // 4J - removed - we don't use ChunkCache anymore @@ -4094,437 +4304,419 @@ void Minecraft::prepareLevel(int title) } #endif - for (int x = -r; x <= r; x += 16) - { - for (int z = -r; z <= r; z += 16) - { - if(progressRenderer != NULL) this->progressRenderer->progressStagePercentage((pp++) * 100 / max); - level->getTile(spawnPos->x + x, 64, spawnPos->z + z); - if (!gameMode->isCutScene()) { - while (level->updateLights()) - ; - } - } - } - delete spawnPos; - if (!gameMode->isCutScene()) - { - if(progressRenderer != NULL) this->progressRenderer->progressStage(IDS_PROGRESS_SIMULATING_WORLD); - max = 2000; -} + for (int x = -r; x <= r; x += 16) { + for (int z = -r; z <= r; z += 16) { + if (progressRenderer != NULL) + this->progressRenderer->progressStagePercentage((pp++) * 100 / + max); + level->getTile(spawnPos->x + x, 64, spawnPos->z + z); + if (!gameMode->isCutScene()) { + while (level->updateLights()); + } + } + } + delete spawnPos; + if (!gameMode->isCutScene()) { + if (progressRenderer != NULL) + this->progressRenderer->progressStage( + IDS_PROGRESS_SIMULATING_WORLD); + max = 2000; + } } -void Minecraft::fileDownloaded(const std::wstring& name, File *file) -{ - int p = (int)name.find(L"/"); - std::wstring category = name.substr(0, p); - std::wstring name2 = name.substr(p + 1); - toLower(category); - if (category==L"sound") - { - soundEngine->add(name, file); - } - else if (category==L"newsound") - { - soundEngine->add(name, file); - } - else if (category==L"streaming") - { - soundEngine->addStreaming(name, file); - } - else if (category==L"music") - { - soundEngine->addMusic(name, file); - } - else if (category==L"newmusic") - { - soundEngine->addMusic(name, file); - } +void Minecraft::fileDownloaded(const std::wstring& name, File* file) { + int p = (int)name.find(L"/"); + std::wstring category = name.substr(0, p); + std::wstring name2 = name.substr(p + 1); + toLower(category); + if (category == L"sound") { + soundEngine->add(name, file); + } else if (category == L"newsound") { + soundEngine->add(name, file); + } else if (category == L"streaming") { + soundEngine->addStreaming(name, file); + } else if (category == L"music") { + soundEngine->addMusic(name, file); + } else if (category == L"newmusic") { + soundEngine->addMusic(name, file); + } } -std::wstring Minecraft::gatherStats1() -{ - //return levelRenderer->gatherStats1(); - return L"Time to autosave: " + _toString( app.SecondsToAutosave() ) + L"s"; +std::wstring Minecraft::gatherStats1() { + // return levelRenderer->gatherStats1(); + return L"Time to autosave: " + + _toString(app.SecondsToAutosave()) + L"s"; } -std::wstring Minecraft::gatherStats2() -{ - return g_NetworkManager.GatherStats(); - //return levelRenderer->gatherStats2(); +std::wstring Minecraft::gatherStats2() { + return g_NetworkManager.GatherStats(); + // return levelRenderer->gatherStats2(); } -std::wstring Minecraft::gatherStats3() -{ - return g_NetworkManager.GatherRTTStats(); - //return L"P: " + particleEngine->countParticles() + L". T: " + level->gatherStats(); +std::wstring Minecraft::gatherStats3() { + return g_NetworkManager.GatherRTTStats(); + // return L"P: " + particleEngine->countParticles() + L". T: " + + // level->gatherStats(); } -std::wstring Minecraft::gatherStats4() -{ - return level->gatherChunkSourceStats(); +std::wstring Minecraft::gatherStats4() { + return level->gatherChunkSourceStats(); } -void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) -{ - gameRenderer->DisableUpdateThread(); // 4J - don't do updating whilst we are adjusting the player & localplayer array - std::shared_ptr localPlayer = localplayers[iPad]; +void Minecraft::respawnPlayer(int iPad, int dimension, int newEntityId) { + gameRenderer + ->DisableUpdateThread(); // 4J - don't do updating whilst we are + // adjusting the player & localplayer array + std::shared_ptr localPlayer = localplayers[iPad]; - level->validateSpawn(); - level->removeAllPendingEntityRemovals(); + level->validateSpawn(); + level->removeAllPendingEntityRemovals(); - if (localPlayer != NULL) - { + if (localPlayer != NULL) { + level->removeEntity(localPlayer); + } - level->removeEntity(localPlayer); - } + std::shared_ptr oldPlayer = localPlayer; + cameraTargetPlayer = nullptr; - std::shared_ptr oldPlayer = localPlayer; - cameraTargetPlayer = nullptr; + // 4J-PB - copy and set the players xbox pad + int iTempPad = localPlayer->GetXboxPad(); + int iTempScreenSection = localPlayer->m_iScreenSection; + EDefaultSkins skin = localPlayer->getPlayerDefaultSkin(); + player = localgameModes[iPad]->createPlayer(level); - // 4J-PB - copy and set the players xbox pad - int iTempPad=localPlayer->GetXboxPad(); - int iTempScreenSection = localPlayer->m_iScreenSection; - EDefaultSkins skin = localPlayer->getPlayerDefaultSkin(); - player = localgameModes[iPad]->createPlayer(level); + PlayerUID playerXUIDOffline = INVALID_XUID; + PlayerUID playerXUIDOnline = INVALID_XUID; + ProfileManager.GetXUID(iTempPad, &playerXUIDOffline, false); + ProfileManager.GetXUID(iTempPad, &playerXUIDOnline, true); + player->setXuid(playerXUIDOffline); + player->setOnlineXuid(playerXUIDOnline); + player->setIsGuest(ProfileManager.IsGuest(iTempPad)); - PlayerUID playerXUIDOffline = INVALID_XUID; - PlayerUID playerXUIDOnline = INVALID_XUID; - ProfileManager.GetXUID(iTempPad,&playerXUIDOffline,false); - ProfileManager.GetXUID(iTempPad,&playerXUIDOnline,true); - player->setXuid(playerXUIDOffline); - player->setOnlineXuid(playerXUIDOnline); - player->setIsGuest( ProfileManager.IsGuest(iTempPad) ); + player->displayName = ProfileManager.GetDisplayName(iPad); - player->displayName = ProfileManager.GetDisplayName(iPad); + player->SetXboxPad(iTempPad); - player->SetXboxPad(iTempPad); + player->m_iScreenSection = iTempScreenSection; + player->setPlayerIndex(localPlayer->getPlayerIndex()); + player->setCustomSkin(localPlayer->getCustomSkin()); + player->setPlayerDefaultSkin(skin); + player->setCustomCape(localPlayer->getCustomCape()); + player->m_sessionTimeStart = localPlayer->m_sessionTimeStart; + player->m_dimensionTimeStart = localPlayer->m_dimensionTimeStart; + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + localPlayer->getAllPlayerGamePrivileges()); - player->m_iScreenSection = iTempScreenSection; - player->setPlayerIndex( localPlayer->getPlayerIndex() ); - player->setCustomSkin(localPlayer->getCustomSkin()); - player->setPlayerDefaultSkin( skin ); - player->setCustomCape(localPlayer->getCustomCape()); - player->m_sessionTimeStart = localPlayer->m_sessionTimeStart; - player->m_dimensionTimeStart = localPlayer->m_dimensionTimeStart; - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, localPlayer->getAllPlayerGamePrivileges()); + player->SetThirdPersonView(oldPlayer->ThirdPersonView()); - player->SetThirdPersonView(oldPlayer->ThirdPersonView()); + // Fix for #63021 - TU7: Content: UI: Travelling from/to the Nether results + // in switching currently held item to another. Fix for #81759 - TU9: + // Content: Gameplay: Entering The End Exit Portal replaces the Player's + // currently held item with the first one from the Quickbar + if (localPlayer->getHealth() > 0 && localPlayer->y > -64) { + player->inventory->selected = localPlayer->inventory->selected; + } - // Fix for #63021 - TU7: Content: UI: Travelling from/to the Nether results in switching currently held item to another. - // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal replaces the Player's currently held item with the first one from the Quickbar - if( localPlayer->getHealth() > 0 && localPlayer->y > -64) - { - player->inventory->selected = localPlayer->inventory->selected; - } + // Set the animation override if the skin has one + std::uint32_t dwSkinID = app.getSkinIdFromPath(player->customTextureUrl); + if (GET_IS_DLC_SKIN_FROM_BITMASK(dwSkinID)) { + player->setAnimOverrideBitmask( + player->getSkinAnimOverrideBitmask(dwSkinID)); + } - // Set the animation override if the skin has one - std::uint32_t dwSkinID = app.getSkinIdFromPath(player->customTextureUrl); - if(GET_IS_DLC_SKIN_FROM_BITMASK(dwSkinID)) - { - player->setAnimOverrideBitmask(player->getSkinAnimOverrideBitmask(dwSkinID)); - } + player->dimension = dimension; + cameraTargetPlayer = player; - player->dimension = dimension; - cameraTargetPlayer = player; + // 4J-PB - are we the primary player or a local player? + if (iPad == ProfileManager.GetPrimaryPad()) { + createPrimaryLocalPlayer(iPad); - // 4J-PB - are we the primary player or a local player? - if(iPad==ProfileManager.GetPrimaryPad()) - { - createPrimaryLocalPlayer(iPad); + // update the debugoptions + app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(), + app.GetGameSettingsDebugMask(-1, true)); + } else { + storeExtraLocalPlayer(iPad); + } - // update the debugoptions - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),app.GetGameSettingsDebugMask(-1,true)); - } - else - { - storeExtraLocalPlayer(iPad); - } + player->setShowOnMaps( + app.GetGameHostOption(eGameHostOption_Gamertags) != 0 ? true : false); - player->setShowOnMaps(app.GetGameHostOption(eGameHostOption_Gamertags)!=0?true:false); + player->resetPos(); + level->addEntity(player); + gameMode->initPlayer(player); - player->resetPos(); - level->addEntity(player); - gameMode->initPlayer(player); + if (player->input != NULL) delete player->input; + player->input = new Input(); + player->entityId = newEntityId; + player->animateRespawn(); + gameMode->adjustPlayer(player); - if(player->input != NULL) delete player->input; - player->input = new Input(); - player->entityId = newEntityId; - player->animateRespawn(); - gameMode->adjustPlayer(player); + // 4J - added isClientSide check here + if (!level->isClientSide) { + prepareLevel(IDS_PROGRESS_RESPAWNING); + } - // 4J - added isClientSide check here - if (!level->isClientSide) - { - prepareLevel(IDS_PROGRESS_RESPAWNING); - } + // 4J Added for multiplayer. At this point we know everything is ready to + // run again + // SetEvent(m_hPlayerRespawned); + player->SetPlayerRespawned(true); - // 4J Added for multiplayer. At this point we know everything is ready to run again - //SetEvent(m_hPlayerRespawned); - player->SetPlayerRespawned(true); + if (dynamic_cast(screen) != NULL) setScreen(NULL); - if (dynamic_cast(screen) != NULL) setScreen(NULL); - - gameRenderer->EnableUpdateThread(); + gameRenderer->EnableUpdateThread(); } -void Minecraft::start(const std::wstring& name, const std::wstring& sid) -{ - startAndConnectTo(name, sid, L""); +void Minecraft::start(const std::wstring& name, const std::wstring& sid) { + startAndConnectTo(name, sid, L""); } -void Minecraft::startAndConnectTo(const std::wstring& name, const std::wstring& sid, const std::wstring& url) -{ - bool fullScreen = false; - std::wstring userName = name; +void Minecraft::startAndConnectTo(const std::wstring& name, + const std::wstring& sid, + const std::wstring& url) { + bool fullScreen = false; + std::wstring userName = name; - /* 4J - removed window handling things here - final Frame frame = new Frame("Minecraft"); - Canvas canvas = new Canvas(); - frame.setLayout(new BorderLayout()); + /* 4J - removed window handling things here + final Frame frame = new Frame("Minecraft"); + Canvas canvas = new Canvas(); + frame.setLayout(new BorderLayout()); - frame.add(canvas, BorderLayout.CENTER); + frame.add(canvas, BorderLayout.CENTER); - // OverlayLayout oll = new OverlayLayout(frame); - // oll.addLayoutComponent(canvas, BorderLayout.CENTER); - // oll.addLayoutComponent(new JLabel("TEST"), BorderLayout.EAST); + // OverlayLayout oll = new OverlayLayout(frame); + // oll.addLayoutComponent(canvas, BorderLayout.CENTER); + // oll.addLayoutComponent(new JLabel("TEST"), BorderLayout.EAST); - canvas.setPreferredSize(new Dimension(854, 480)); - frame.pack(); - frame.setLocationRelativeTo(null); - */ + canvas.setPreferredSize(new Dimension(854, 480)); + frame.pack(); + frame.setLocationRelativeTo(null); + */ - Minecraft *minecraft; - // 4J - was new Minecraft(frame, canvas, NULL, 854, 480, fullScreen); + Minecraft* minecraft; + // 4J - was new Minecraft(frame, canvas, NULL, 854, 480, fullScreen); - minecraft = new Minecraft(NULL, NULL, NULL, 1280, 720, fullScreen); + minecraft = new Minecraft(NULL, NULL, NULL, 1280, 720, fullScreen); - /* - 4J - removed - { - @Override - public void onCrash(CrashReport crashReport) { - frame.removeAll(); - frame.add(new CrashInfoPanel(crashReport), BorderLayout.CENTER); - frame.validate(); - } - }; */ + /* - 4J - removed + { + @Override + public void onCrash(CrashReport crashReport) { + frame.removeAll(); + frame.add(new CrashInfoPanel(crashReport), BorderLayout.CENTER); + frame.validate(); + } + }; */ - /* 4J - removed - final Thread thread = new Thread(minecraft, "Minecraft main thread"); - thread.setPriority(Thread.MAX_PRIORITY); - */ - minecraft->serverDomain = L"www.minecraft.net"; + /* 4J - removed + final Thread thread = new Thread(minecraft, "Minecraft main thread"); + thread.setPriority(Thread.MAX_PRIORITY); + */ + minecraft->serverDomain = L"www.minecraft.net"; - // 4J Stu - We never want the player to be DemoUser, we always want them to have their gamertag displayed - //if (ProfileManager.IsFullVersion()) - { - if (userName != L"" && sid != L"") // 4J - username & side were compared with NULL rather than empty strings - { - minecraft->user = new User(userName, sid); - } - else - { - minecraft->user = new User(L"Player" + _toString(System::currentTimeMillis() % 1000), L""); - } - } - //else - //{ - // minecraft->user = new DemoUser(); - //} + // 4J Stu - We never want the player to be DemoUser, we always want them to + // have their gamertag displayed + // if (ProfileManager.IsFullVersion()) + { + if (userName != L"" && + sid != L"") // 4J - username & side were compared with NULL rather + // than empty strings + { + minecraft->user = new User(userName, sid); + } else { + minecraft->user = new User( + L"Player" + _toString(System::currentTimeMillis() % 1000), + L""); + } + } + // else + //{ + // minecraft->user = new DemoUser(); + // } - /* 4J - TODO - if (url != NULL) - { - String[] tokens = url.split(":"); - minecraft.connectTo(tokens[0], Integer.parseInt(tokens[1])); - } - */ + /* 4J - TODO + if (url != NULL) + { + String[] tokens = url.split(":"); + minecraft.connectTo(tokens[0], Integer.parseInt(tokens[1])); + } + */ - /* 4J - removed - frame.setVisible(true); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent arg0) { - minecraft.stop(); - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.exit(0); - } - }); - */ - // 4J - TODO - consider whether we need to actually create a thread here - minecraft->run(); + /* 4J - removed + frame.setVisible(true); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent arg0) { + minecraft.stop(); + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.exit(0); + } + }); + */ + // 4J - TODO - consider whether we need to actually create a thread here + minecraft->run(); } -ClientConnection *Minecraft::getConnection(int iPad) -{ - return localplayers[iPad]->connection; +ClientConnection* Minecraft::getConnection(int iPad) { + return localplayers[iPad]->connection; } // 4J-PB - so we can access this from within our xbox game loop -Minecraft *Minecraft::GetInstance() -{ - return m_instance; -} +Minecraft* Minecraft::GetInstance() { return m_instance; } bool useLomp = false; int g_iMainThreadId; -void Minecraft::main() -{ - std::wstring name; - std::wstring sessionId; +void Minecraft::main() { + std::wstring name; + std::wstring sessionId; - //g_iMainThreadId = GetCurrentThreadId(); + // g_iMainThreadId = GetCurrentThreadId(); - useLomp = true; + useLomp = true; - MinecraftWorld_RunStaticCtors(); - EntityRenderDispatcher::staticCtor(); - TileEntityRenderDispatcher::staticCtor(); - User::staticCtor(); - Tutorial::staticCtor(); - ColourTable::staticCtor(); - app.loadDefaultGameRules(); + MinecraftWorld_RunStaticCtors(); + EntityRenderDispatcher::staticCtor(); + TileEntityRenderDispatcher::staticCtor(); + User::staticCtor(); + Tutorial::staticCtor(); + ColourTable::staticCtor(); + app.loadDefaultGameRules(); #ifdef _LARGE_WORLDS - LevelRenderer::staticCtor(); + LevelRenderer::staticCtor(); #endif - // 4J Stu - This block generates XML for the game rules schema - //for(unsigned int i = 0; i < Item::items.length; ++i) - //{ - // if(Item::items[i] != NULL) - // { - // wprintf(L"%ls\n", i, app.GetString( Item::items[i]->getDescriptionId() )); - // } - //} + // 4J Stu - This block generates XML for the game rules schema + // for(unsigned int i = 0; i < Item::items.length; ++i) + //{ + // if(Item::items[i] != NULL) + // { + // wprintf(L"%ls\n", + //i, app.GetString( Item::items[i]->getDescriptionId() )); + // } + //} - //wprintf(L"\n\n\n\n\n"); - // - //for(unsigned int i = 0; i < 256; ++i) - //{ - // if(Tile::tiles[i] != NULL) - // { - // wprintf(L"%ls\n", i, app.GetString( Tile::tiles[i]->getDescriptionId() )); - // } - //} - //__debugbreak(); + // wprintf(L"\n\n\n\n\n"); + // + // for(unsigned int i = 0; i < 256; ++i) + //{ + // if(Tile::tiles[i] != NULL) + // { + // wprintf(L"%ls\n", + //i, app.GetString( Tile::tiles[i]->getDescriptionId() )); + // } + // } + //__debugbreak(); - // 4J-PB - Can't call this for the first 5 seconds of a game - MS rule - //if (ProfileManager.IsFullVersion()) - { - name = L"Player" + _toString<__int64>(System::currentTimeMillis() % 1000); - sessionId = L"-"; - /* 4J - TODO - get a session ID from somewhere? - if (args.length > 0) name = args[0]; - sessionId = "-"; - if (args.length > 1) sessionId = args[1]; - */ - } + // 4J-PB - Can't call this for the first 5 seconds of a game - MS rule + // if (ProfileManager.IsFullVersion()) + { + name = + L"Player" + _toString<__int64>(System::currentTimeMillis() % 1000); + sessionId = L"-"; + /* 4J - TODO - get a session ID from somewhere? + if (args.length > 0) name = args[0]; + sessionId = "-"; + if (args.length > 1) sessionId = args[1]; + */ + } - // Common for all platforms - IUIScene_CreativeMenu::staticCtor(); + // Common for all platforms + IUIScene_CreativeMenu::staticCtor(); - // On PS4, we call Minecraft::Start from another thread, as this has been timed taking ~2.5 seconds and we need to do some basic - // rendering stuff so that we don't break the TRCs on SubmitDone calls + // On PS4, we call Minecraft::Start from another thread, as this has been + // timed taking ~2.5 seconds and we need to do some basic rendering stuff so + // that we don't break the TRCs on SubmitDone calls #ifndef __ORBIS__ - Minecraft::start(name, sessionId); + Minecraft::start(name, sessionId); #endif } -bool Minecraft::renderNames() -{ - if (m_instance == NULL || !m_instance->options->hideGui) - { - return true; - } - return false; +bool Minecraft::renderNames() { + if (m_instance == NULL || !m_instance->options->hideGui) { + return true; + } + return false; } -bool Minecraft::useFancyGraphics() -{ - return (m_instance != NULL && m_instance->options->fancyGraphics); +bool Minecraft::useFancyGraphics() { + return (m_instance != NULL && m_instance->options->fancyGraphics); } -bool Minecraft::useAmbientOcclusion() -{ - return (m_instance != NULL && m_instance->options->ambientOcclusion); +bool Minecraft::useAmbientOcclusion() { + return (m_instance != NULL && m_instance->options->ambientOcclusion); } -bool Minecraft::renderDebug() -{ - return (m_instance != NULL && m_instance->options->renderDebug); +bool Minecraft::renderDebug() { + return (m_instance != NULL && m_instance->options->renderDebug); } -bool Minecraft::handleClientSideCommand(const std::wstring& chatMessage) -{ - /* 4J - TODO - if (chatMessage.startsWith("/")) { - if (DEADMAU5_CAMERA_CHEATS) { - if (chatMessage.startsWith("/follow")) { - String[] tokens = chatMessage.split(" "); - if (tokens.length >= 2) { - String playerName = tokens[1]; +bool Minecraft::handleClientSideCommand(const std::wstring& chatMessage) { + /* 4J - TODO + if (chatMessage.startsWith("/")) { + if (DEADMAU5_CAMERA_CHEATS) { + if (chatMessage.startsWith("/follow")) { + String[] tokens = chatMessage.split(" "); + if (tokens.length >= 2) { + String playerName = tokens[1]; - boolean found = false; - for (Player player : level.players) { - if (playerName.equalsIgnoreCase(player.name)) { - cameraTargetPlayer = player; - found = true; - break; - } - } + boolean found = false; + for (Player player : level.players) { + if (playerName.equalsIgnoreCase(player.name)) { + cameraTargetPlayer = player; + found = true; + break; + } + } - if (!found) { - try { - int entityId = Integer.parseInt(playerName); - for (Entity e : level.entities) { - if (e.entityId == entityId && e instanceof Mob) { - cameraTargetPlayer = (Mob) e; - found = true; - break; - } - } - } catch (NumberFormatException e) { - } - } - } + if (!found) { + try { + int entityId = Integer.parseInt(playerName); + for (Entity e : level.entities) { + if (e.entityId == entityId && e instanceof Mob) { + cameraTargetPlayer = (Mob) e; + found = true; + break; + } + } + } catch (NumberFormatException e) { + } + } + } - return true; - } - } - } - */ - return false; + return true; + } + } + } + */ + return false; } -int Minecraft::maxSupportedTextureSize() -{ - // 4J Force value - return 1024; +int Minecraft::maxSupportedTextureSize() { + // 4J Force value + return 1024; - //for (int texSize = 16384; texSize > 0; texSize >>= 1) { - // GL11.glTexImage2D(GL11.GL_PROXY_TEXTURE_2D, 0, GL11.GL_RGBA, texSize, texSize, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); - // final int width = GL11.glGetTexLevelParameteri(GL11.GL_PROXY_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); - // if (width != 0) { - // return texSize; - // } - //} - //return -1; + // for (int texSize = 16384; texSize > 0; texSize >>= 1) { + // GL11.glTexImage2D(GL11.GL_PROXY_TEXTURE_2D, 0, GL11.GL_RGBA, texSize, + //texSize, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); final + //int width = GL11.glGetTexLevelParameteri(GL11.GL_PROXY_TEXTURE_2D, 0, + //GL11.GL_TEXTURE_WIDTH); if (width != 0) { return texSize; + // } + // } + // return -1; } -void Minecraft::delayTextureReload() -{ - reloadTextures = true; -} +void Minecraft::delayTextureReload() { reloadTextures = true; } -__int64 Minecraft::currentTimeMillis() -{ - return System::currentTimeMillis();//(Sys.getTime() * 1000) / Sys.getTimerResolution(); +__int64 Minecraft::currentTimeMillis() { + return System::currentTimeMillis(); //(Sys.getTime() * 1000) / + //Sys.getTimerResolution(); } /*void Minecraft::handleMouseDown(int button, bool down) @@ -4533,7 +4725,8 @@ if (gameMode->instaBuild) return; if (!down) missTime = 0; if (button == 0 && missTime > 0) return; -if (down && hitResult != NULL && hitResult->type == HitResult::TILE && button == 0) +if (down && hitResult != NULL && hitResult->type == HitResult::TILE && button == +0) { int x = hitResult->x; int y = hitResult->y; @@ -4552,8 +4745,8 @@ void Minecraft::handleMouseClick(int button) if (button == 0 && missTime > 0) return; if (button == 0) { -app.DebugPrintf("handleMouseClick - Player %d is swinging\n",player->GetXboxPad()); -player->swing(); +app.DebugPrintf("handleMouseClick - Player %d is +swinging\n",player->GetXboxPad()); player->swing(); } bool mayUse = true; @@ -4563,25 +4756,30 @@ bool mayUse = true; // * (gameMode.useItem(player, item)) { // * gameRenderer.itemInHandRenderer.itemUsed(); return; } } } -// 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer game - we need to wake up, and we don't have the inbedchatscreen with a button +// 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer +game - we need to wake up, and we don't have the inbedchatscreen with a button if(button==1 && (player->isSleeping() && level != NULL && level->isClientSide)) { -std::shared_ptr mplp = std::dynamic_pointer_cast( player ); +std::shared_ptr mplp = +std::dynamic_pointer_cast( player ); if(mplp) mplp->StopSleeping(); // 4J - TODO //if (minecraft.player instanceof MultiplayerLocalPlayer) //{ -// ClientConnection connection = ((MultiplayerLocalPlayer) minecraft.player).connection; -// connection.send(new PlayerCommandPacket(minecraft.player, PlayerCommandPacket.STOP_SLEEPING)); +// ClientConnection connection = ((MultiplayerLocalPlayer) +minecraft.player).connection; +// connection.send(new PlayerCommandPacket(minecraft.player, +PlayerCommandPacket.STOP_SLEEPING)); //} } if (hitResult == NULL) { -if (button == 0 && !(dynamic_cast(gameMode) != NULL)) missTime = 10; +if (button == 0 && !(dynamic_cast(gameMode) != NULL)) missTime = +10; } else if (hitResult->type == HitResult::ENTITY) { @@ -4655,247 +4853,249 @@ gameRenderer->itemInHandRenderer->itemUsed(); */ // 4J-PB -Screen * Minecraft::getScreen() -{ - return screen; +Screen* Minecraft::getScreen() { return screen; } + +bool Minecraft::isTutorial() { + return m_inFullTutorialBits > 0; + + /*if( gameMode != NULL && gameMode->isTutorial() ) + { + return true; + } + else + { + return false; + }*/ } -bool Minecraft::isTutorial() -{ - return m_inFullTutorialBits > 0; - - /*if( gameMode != NULL && gameMode->isTutorial() ) - { - return true; - } - else - { - return false; - }*/ +void Minecraft::playerStartedTutorial(int iPad) { + // If the app doesn't think we are in a tutorial mode then just ignore this + // add + if (app.GetTutorialMode()) + m_inFullTutorialBits = m_inFullTutorialBits | (1 << iPad); } -void Minecraft::playerStartedTutorial(int iPad) -{ - // If the app doesn't think we are in a tutorial mode then just ignore this add - if( app.GetTutorialMode() ) m_inFullTutorialBits = m_inFullTutorialBits | ( 1 << iPad ); -} +void Minecraft::playerLeftTutorial(int iPad) { + // 4J Stu - Fix for bug that was flooding Sentient with LevelStart events + // If the tutorial bits are already 0 then don't need to update anything + if (m_inFullTutorialBits == 0) { + app.SetTutorialMode(false); + return; + } -void Minecraft::playerLeftTutorial(int iPad) -{ - // 4J Stu - Fix for bug that was flooding Sentient with LevelStart events - // If the tutorial bits are already 0 then don't need to update anything - if(m_inFullTutorialBits == 0) - { - app.SetTutorialMode( false ); - return; - } + m_inFullTutorialBits = m_inFullTutorialBits & ~(1 << iPad); + if (m_inFullTutorialBits == 0) { + app.SetTutorialMode(false); - m_inFullTutorialBits = m_inFullTutorialBits & ~( 1 << iPad ); - if(m_inFullTutorialBits == 0) - { - app.SetTutorialMode( false ); - - // 4J Stu -This telemetry event means something different on XboxOne, so we don't call it for simple state changes like this + // 4J Stu -This telemetry event means something different on XboxOne, so + // we don't call it for simple state changes like this #ifndef _XBOX_ONE - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(localplayers[idx] != NULL) - { - TelemetryManager->RecordLevelStart(idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, level->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); - } - } + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (localplayers[idx] != NULL) { + TelemetryManager->RecordLevelStart( + idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, level->difficulty, + app.GetLocalPlayerCount(), + g_NetworkManager.GetOnlinePlayerCount()); + } + } #endif - } + } } #ifdef _DURANGO -void Minecraft::inGameSignInCheckAllPrivilegesCallback(void *lpParam, bool hasPrivileges, int iPad) -{ - Minecraft* pClass = (Minecraft*)lpParam; +void Minecraft::inGameSignInCheckAllPrivilegesCallback(void* lpParam, + bool hasPrivileges, + int iPad) { + Minecraft* pClass = (Minecraft*)lpParam; - if(!hasPrivileges) - { - ProfileManager.RemoveGamepadFromGame(iPad); - } - else - { - if( !g_NetworkManager.SessionHasSpace() ) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_OK; - ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); - ProfileManager.RemoveGamepadFromGame(iPad); - } - else if( ProfileManager.IsSignedInLive(iPad) && ProfileManager.AllowedToPlayMultiplayer(iPad) ) - { - // create the local player for the iPad - std::shared_ptr player = pClass->localplayers[iPad]; - if( player == NULL) - { - if( pClass->level->isClientSide ) - { - pClass->addLocalPlayer(iPad); - } - else - { - // create the local player for the iPad - std::shared_ptr player = pClass->localplayers[iPad]; - if( player == NULL) - { - player = pClass->createExtraLocalPlayer(iPad, (convStringToWstring( ProfileManager.GetGamertag(iPad) )).c_str(), iPad, pClass->level->dimension->id); - } - } - } - } - } + if (!hasPrivileges) { + ProfileManager.RemoveGamepadFromGame(iPad); + } else { + if (!g_NetworkManager.SessionHasSpace()) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, + IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); + ProfileManager.RemoveGamepadFromGame(iPad); + } else if (ProfileManager.IsSignedInLive(iPad) && + ProfileManager.AllowedToPlayMultiplayer(iPad)) { + // create the local player for the iPad + std::shared_ptr player = pClass->localplayers[iPad]; + if (player == NULL) { + if (pClass->level->isClientSide) { + pClass->addLocalPlayer(iPad); + } else { + // create the local player for the iPad + std::shared_ptr player = pClass->localplayers[iPad]; + if (player == NULL) { + player = pClass->createExtraLocalPlayer( + iPad, + (convStringToWstring( + ProfileManager.GetGamertag(iPad))) + .c_str(), + iPad, pClass->level->dimension->id); + } + } + } + } + } } #endif -int Minecraft::InGame_SignInReturned(void *pParam,bool bContinue, int iPad) -{ - Minecraft* pMinecraftClass = (Minecraft*)pParam; +int Minecraft::InGame_SignInReturned(void* pParam, bool bContinue, int iPad) { + Minecraft* pMinecraftClass = (Minecraft*)pParam; - if(g_NetworkManager.IsInSession()) - { - // 4J Stu - There seems to be a bug in the signin ui call that enables guest sign in. We never allow this within game, so make sure that it's disabled - // Fix for #66516 - TCR #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The game crashes when second Guest signs-in on console which takes part in Xbox LIVE multiplayer session. - app.DebugPrintf("Disabling Guest Signin\n"); - XEnableGuestSignin(FALSE); - } + if (g_NetworkManager.IsInSession()) { + // 4J Stu - There seems to be a bug in the signin ui call that enables + // guest sign in. We never allow this within game, so make sure that + // it's disabled Fix for #66516 - TCR #124: MPS Guest Support ; #001: + // BAS Game Stability: TU8: The game crashes when second Guest signs-in + // on console which takes part in Xbox LIVE multiplayer session. + app.DebugPrintf("Disabling Guest Signin\n"); + XEnableGuestSignin(FALSE); + } - // If sign in succeded, we're in game and this player isn't already playing, continue - if(bContinue==true && g_NetworkManager.IsInSession() && pMinecraftClass->localplayers[iPad] == NULL) - { - // It's possible that the player has not signed in - they can back out or choose no for the converttoguest - if(ProfileManager.IsSignedIn(iPad)) - { + // If sign in succeded, we're in game and this player isn't already playing, + // continue + if (bContinue == true && g_NetworkManager.IsInSession() && + pMinecraftClass->localplayers[iPad] == NULL) { + // It's possible that the player has not signed in - they can back out + // or choose no for the converttoguest + if (ProfileManager.IsSignedIn(iPad)) { #ifdef _DURANGO - if(!g_NetworkManager.IsLocalGame() && ProfileManager.IsSignedInLive(iPad) && ProfileManager.AllowedToPlayMultiplayer(iPad)) - { - ProfileManager.CheckMultiplayerPrivileges(iPad, true, &inGameSignInCheckAllPrivilegesCallback, pMinecraftClass); - } - else + if (!g_NetworkManager.IsLocalGame() && + ProfileManager.IsSignedInLive(iPad) && + ProfileManager.AllowedToPlayMultiplayer(iPad)) { + ProfileManager.CheckMultiplayerPrivileges( + iPad, true, &inGameSignInCheckAllPrivilegesCallback, + pMinecraftClass); + } else #endif - if( !g_NetworkManager.SessionHasSpace() ) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_OK; - ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); + if (!g_NetworkManager.SessionHasSpace()) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox(IDS_MULTIPLAYER_FULL_TITLE, + IDS_MULTIPLAYER_FULL_TEXT, uiIDA, 1); #ifdef _DURANGO - ProfileManager.RemoveGamepadFromGame(iPad); + ProfileManager.RemoveGamepadFromGame(iPad); #endif - } - // if this is a local game then profiles just need to be signed in - else if( g_NetworkManager.IsLocalGame() || (ProfileManager.IsSignedInLive(iPad) && ProfileManager.AllowedToPlayMultiplayer(iPad)) ) - { + } + // if this is a local game then profiles just need to be signed in + else if (g_NetworkManager.IsLocalGame() || + (ProfileManager.IsSignedInLive(iPad) && + ProfileManager.AllowedToPlayMultiplayer(iPad))) { #ifdef __ORBIS__ - bool contentRestricted = false; - ProfileManager.GetChatAndContentRestrictions(iPad,false,NULL,&contentRestricted,NULL); // TODO! + bool contentRestricted = false; + ProfileManager.GetChatAndContentRestrictions( + iPad, false, NULL, &contentRestricted, NULL); // TODO! - if (!g_NetworkManager.IsLocalGame() && contentRestricted) - { - ui.RequestContentRestrictedMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_CONTENT_RESTRICTION, iPad); - } - else if(!g_NetworkManager.IsLocalGame() && !ProfileManager.HasPlayStationPlus(iPad)) - { - pMinecraftClass->m_pPsPlusUpsell = new PsPlusUpsellWrapper(iPad); - pMinecraftClass->m_pPsPlusUpsell->displayUpsell(); - } - else + if (!g_NetworkManager.IsLocalGame() && contentRestricted) { + ui.RequestContentRestrictedMessageBox( + IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_CONTENT_RESTRICTION, iPad); + } else if (!g_NetworkManager.IsLocalGame() && + !ProfileManager.HasPlayStationPlus(iPad)) { + pMinecraftClass->m_pPsPlusUpsell = + new PsPlusUpsellWrapper(iPad); + pMinecraftClass->m_pPsPlusUpsell->displayUpsell(); + } else #endif - if( pMinecraftClass->level->isClientSide ) - { - pMinecraftClass->addLocalPlayer(iPad); - } - else - { - // create the local player for the iPad - std::shared_ptr player = pMinecraftClass->localplayers[iPad]; - if( player == NULL) - { - player = pMinecraftClass->createExtraLocalPlayer(iPad, (convStringToWstring( ProfileManager.GetGamertag(iPad) )).c_str(), iPad, pMinecraftClass->level->dimension->id); - } - } - } - else if( ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad()) && !ProfileManager.AllowedToPlayMultiplayer(iPad) ) - { - // 4J Stu - Don't allow converting to guests as we don't allow any guest sign-in while in the game - // Fix for #66516 - TCR #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The game crashes when second Guest signs-in on console which takes part in Xbox LIVE multiplayer session. - //ProfileManager.RequestConvertOfflineToGuestUI( &Minecraft::InGame_SignInReturned, pMinecraftClass,iPad); - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,iPad,NULL,NULL, app.GetStringTable()); + if (pMinecraftClass->level->isClientSide) { + pMinecraftClass->addLocalPlayer(iPad); + } else { + // create the local player for the iPad + std::shared_ptr player = + pMinecraftClass->localplayers[iPad]; + if (player == NULL) { + player = pMinecraftClass->createExtraLocalPlayer( + iPad, + (convStringToWstring( + ProfileManager.GetGamertag(iPad))) + .c_str(), + iPad, pMinecraftClass->level->dimension->id); + } + } + } else if (ProfileManager.IsSignedInLive( + ProfileManager.GetPrimaryPad()) && + !ProfileManager.AllowedToPlayMultiplayer(iPad)) { + // 4J Stu - Don't allow converting to guests as we don't allow + // any guest sign-in while in the game Fix for #66516 - TCR + // #124: MPS Guest Support ; #001: BAS Game Stability: TU8: The + // game crashes when second Guest signs-in on console which + // takes part in Xbox LIVE multiplayer session. + // ProfileManager.RequestConvertOfflineToGuestUI( + // &Minecraft::InGame_SignInReturned, pMinecraftClass,iPad); + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, + uiIDA, 1, iPad, NULL, NULL, + app.GetStringTable()); #ifdef _DURANGO - ProfileManager.RemoveGamepadFromGame(iPad); + ProfileManager.RemoveGamepadFromGame(iPad); #endif - } - } - } - return 0; + } + } + } + return 0; } -void Minecraft::tickAllConnections() -{ - int oldIdx = getLocalPlayerIdx(); - for(unsigned int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - std::shared_ptr mplp = localplayers[i]; - if( mplp && mplp->connection) - { - setLocalPlayerIdx(i); - mplp->connection->tick(); - } - } - setLocalPlayerIdx(oldIdx); +void Minecraft::tickAllConnections() { + int oldIdx = getLocalPlayerIdx(); + for (unsigned int i = 0; i < XUSER_MAX_COUNT; i++) { + std::shared_ptr mplp = localplayers[i]; + if (mplp && mplp->connection) { + setLocalPlayerIdx(i); + mplp->connection->tick(); + } + } + setLocalPlayerIdx(oldIdx); } -bool Minecraft::addPendingClientTextureRequest(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it == m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.push_back(textureName); - return true; - } - return false; +bool Minecraft::addPendingClientTextureRequest( + const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it == m_pendingTextureRequests.end()) { + m_pendingTextureRequests.push_back(textureName); + return true; + } + return false; } -void Minecraft::handleClientTextureReceived(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.erase(it); - } +void Minecraft::handleClientTextureReceived(const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it != m_pendingTextureRequests.end()) { + m_pendingTextureRequests.erase(it); + } } -unsigned int Minecraft::getCurrentTexturePackId() -{ - return skins->getSelected()->getId(); +unsigned int Minecraft::getCurrentTexturePackId() { + return skins->getSelected()->getId(); } -ColourTable *Minecraft::getColourTable() -{ - TexturePack *selected = skins->getSelected(); +ColourTable* Minecraft::getColourTable() { + TexturePack* selected = skins->getSelected(); - ColourTable *colours = selected->getColourTable(); + ColourTable* colours = selected->getColourTable(); - if(colours == NULL) - { - colours = skins->getDefault()->getColourTable(); - } + if (colours == NULL) { + colours = skins->getDefault()->getColourTable(); + } - return colours; + return colours; } #if defined __ORBIS__ -int Minecraft::MustSignInReturnedPSN(void *pParam, int iPad, C4JStorage::EMessageResult result) -{ - Minecraft* pMinecraft = (Minecraft *)pParam; +int Minecraft::MustSignInReturnedPSN(void* pParam, int iPad, + C4JStorage::EMessageResult result) { + Minecraft* pMinecraft = (Minecraft*)pParam; - if(result == C4JStorage::EMessage_ResultAccept) - { - SQRNetworkManager_Orbis::AttemptPSNSignIn(&Minecraft::InGame_SignInReturned, pMinecraft, false, iPad); + if (result == C4JStorage::EMessage_ResultAccept) { + SQRNetworkManager_Orbis::AttemptPSNSignIn( + &Minecraft::InGame_SignInReturned, pMinecraft, false, iPad); } return 0; diff --git a/Minecraft.Client/Minecraft.h b/Minecraft.Client/Minecraft.h index 1e54067e3..8493675f7 100644 --- a/Minecraft.Client/Minecraft.h +++ b/Minecraft.Client/Minecraft.h @@ -46,299 +46,349 @@ class PsPlusUpsellWrapper; #undef linux #endif - - -class Minecraft -{ +class Minecraft { public: - static const std::wstring VERSION_STRING; - Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet *minecraftApplet, int width, int height, bool fullscreen); - void init(); + static const std::wstring VERSION_STRING; + Minecraft(Component* mouseComponent, Canvas* parent, + MinecraftApplet* minecraftApplet, int width, int height, + bool fullscreen); + void init(); - // 4J - removed - // void crash(CrashReport crash); - // public abstract void onCrash(CrashReport crash); + // 4J - removed + // void crash(CrashReport crash); + // public abstract void onCrash(CrashReport crash); private: - static Minecraft *m_instance; + static Minecraft* m_instance; public: - MultiPlayerGameMode *gameMode; + MultiPlayerGameMode* gameMode; private: - bool fullscreen; - bool hasCrashed; + bool fullscreen; + bool hasCrashed; - C4JThread::EventQueue* levelTickEventQueue; - - static void levelTickUpdateFunc(void* pParam); - static void levelTickThreadInitFunc(); + C4JThread::EventQueue* levelTickEventQueue; + + static void levelTickUpdateFunc(void* pParam); + static void levelTickThreadInitFunc(); public: - int width, height; - int width_phys, height_phys; // 4J - added - // private OpenGLCapabilities openGLCapabilities; + int width, height; + int width_phys, height_phys; // 4J - added + // private OpenGLCapabilities openGLCapabilities; private: - Timer *timer; - bool reloadTextures; + Timer* timer; + bool reloadTextures; + public: - Level *oldLevel; // 4J Stu added to keep a handle on an old level so we can delete it - //HANDLE m_hPlayerRespawned; // 4J Added so we can wait in menus until it is done (for async in multiplayer) + Level* oldLevel; // 4J Stu added to keep a handle on an old level so we can + // delete it + // HANDLE m_hPlayerRespawned; // 4J Added so we can wait in menus until it + // is done (for async in multiplayer) public: + MultiPlayerLevel* level; + LevelRenderer* levelRenderer; + std::shared_ptr player; - MultiPlayerLevel *level; - LevelRenderer *levelRenderer; - std::shared_ptr player; + MultiPlayerLevelArray levels; - MultiPlayerLevelArray levels; + std::shared_ptr localplayers[XUSER_MAX_COUNT]; + MultiPlayerGameMode* localgameModes[XUSER_MAX_COUNT]; + int localPlayerIdx; + ItemInHandRenderer* localitemInHandRenderers[XUSER_MAX_COUNT]; + // 4J-PB - so we can have debugoptions in the server + unsigned int uiDebugOptionsA[XUSER_MAX_COUNT]; - std::shared_ptr localplayers[XUSER_MAX_COUNT]; - MultiPlayerGameMode *localgameModes[XUSER_MAX_COUNT]; - int localPlayerIdx; - ItemInHandRenderer *localitemInHandRenderers[XUSER_MAX_COUNT]; - // 4J-PB - so we can have debugoptions in the server - unsigned int uiDebugOptionsA[XUSER_MAX_COUNT]; + // 4J Stu - Added these so that we can show a Xui scene while connecting + bool m_connectionFailed[XUSER_MAX_COUNT]; + DisconnectPacket::eDisconnectReason + m_connectionFailedReason[XUSER_MAX_COUNT]; + ClientConnection* m_pendingLocalConnections[XUSER_MAX_COUNT]; - // 4J Stu - Added these so that we can show a Xui scene while connecting - bool m_connectionFailed[XUSER_MAX_COUNT]; - DisconnectPacket::eDisconnectReason m_connectionFailedReason[XUSER_MAX_COUNT]; - ClientConnection *m_pendingLocalConnections[XUSER_MAX_COUNT]; + bool addLocalPlayer( + int idx); // Re-arrange the screen and start the connection + void addPendingLocalConnection(int idx, ClientConnection* connection); + void connectionDisconnected(int idx, + DisconnectPacket::eDisconnectReason reason) { + m_connectionFailed[idx] = true; + m_connectionFailedReason[idx] = reason; + } - bool addLocalPlayer(int idx); // Re-arrange the screen and start the connection - void addPendingLocalConnection(int idx, ClientConnection *connection); - void connectionDisconnected(int idx, DisconnectPacket::eDisconnectReason reason) { m_connectionFailed[idx] = true; m_connectionFailedReason[idx] = reason; } + std::shared_ptr createExtraLocalPlayer( + int idx, const std::wstring& name, int pad, int iDimension, + ClientConnection* clientConnection = NULL, + MultiPlayerLevel* levelpassedin = NULL); + void createPrimaryLocalPlayer(int iPad); + bool setLocalPlayerIdx(int idx); + int getLocalPlayerIdx(); + void removeLocalPlayerIdx(int idx); + void storeExtraLocalPlayer(int idx); + void updatePlayerViewportAssignments(); + int unoccupiedQuadrant; // 4J - added - std::shared_ptr createExtraLocalPlayer(int idx, const std::wstring& name, int pad, int iDimension, ClientConnection *clientConnection = NULL,MultiPlayerLevel *levelpassedin=NULL); - void createPrimaryLocalPlayer(int iPad); - bool setLocalPlayerIdx(int idx); - int getLocalPlayerIdx(); - void removeLocalPlayerIdx(int idx); - void storeExtraLocalPlayer(int idx); - void updatePlayerViewportAssignments(); - int unoccupiedQuadrant; // 4J - added + std::shared_ptr cameraTargetPlayer; + ParticleEngine* particleEngine; + User* user; + std::wstring serverDomain; + Canvas* parent; + bool appletMode; - std::shared_ptr cameraTargetPlayer; - ParticleEngine *particleEngine; - User *user; - std::wstring serverDomain; - Canvas *parent; - bool appletMode; + // 4J - per player ? + volatile bool pause; - // 4J - per player ? - volatile bool pause; + Textures* textures; + Font *font, *altFont; + Screen* screen; + ProgressRenderer* progressRenderer; + GameRenderer* gameRenderer; - Textures *textures; - Font *font, *altFont; - Screen *screen; - ProgressRenderer *progressRenderer; - GameRenderer *gameRenderer; private: - BackgroundDownloader *bgLoader; + BackgroundDownloader* bgLoader; - int ticks; - // 4J-PB - moved to per player + int ticks; + // 4J-PB - moved to per player - //int missTime; + // int missTime; + + int orgWidth, orgHeight; - int orgWidth, orgHeight; public: - AchievementPopup *achievementPopup; -public: - Gui *gui; - // 4J - move to the per player structure? - bool noRender; + AchievementPopup* achievementPopup; + +public: + Gui* gui; + // 4J - move to the per player structure? + bool noRender; + + HumanoidModel* humanoidModel; + HitResult* hitResult; + Options* options; - HumanoidModel *humanoidModel; - HitResult *hitResult; - Options *options; protected: - MinecraftApplet *minecraftApplet; -public: - SoundEngine *soundEngine; - MouseHandler *mouseHandler; -public: - TexturePackRepository *skins; - File workingDirectory; -private: - LevelStorageSource *levelSource; -public: - static const int frameTimes_length = 512; - static __int64 frameTimes[frameTimes_length]; - static const int tickTimes_length = 512; - static __int64 tickTimes[tickTimes_length]; - static int frameTimePos; - static __int64 warezTime; -private: - int rightClickDelay; -public: - // 4J- this should really be in localplayer - StatsCounter* stats[4]; - -private: - std::wstring connectToIp; - int connectToPort; + MinecraftApplet* minecraftApplet; public: - void clearConnectionFailed(); - void connectTo(const std::wstring& server, int port); - -private: - void renderLoadingScreen(); + SoundEngine* soundEngine; + MouseHandler* mouseHandler; public: - void blit(int x, int y, int sx, int sy, int w, int h); + TexturePackRepository* skins; + File workingDirectory; private: - static File workDir; + LevelStorageSource* levelSource; public: - static File getWorkingDirectory(); - static File getWorkingDirectory(const std::wstring& applicationName); -public: - LevelStorageSource *getLevelSource(); - void setScreen(Screen *screen); + static const int frameTimes_length = 512; + static __int64 frameTimes[frameTimes_length]; + static const int tickTimes_length = 512; + static __int64 tickTimes[tickTimes_length]; + static int frameTimePos; + static __int64 warezTime; + private: - void checkGlError(const std::wstring& string); + int rightClickDelay; + +public: + // 4J- this should really be in localplayer + StatsCounter* stats[4]; + +private: + std::wstring connectToIp; + int connectToPort; + +public: + void clearConnectionFailed(); + void connectTo(const std::wstring& server, int port); + +private: + void renderLoadingScreen(); + +public: + void blit(int x, int y, int sx, int sy, int w, int h); + +private: + static File workDir; + +public: + static File getWorkingDirectory(); + static File getWorkingDirectory(const std::wstring& applicationName); + +public: + LevelStorageSource* getLevelSource(); + void setScreen(Screen* screen); + +private: + void checkGlError(const std::wstring& string); #ifdef __ORBIS__ - PsPlusUpsellWrapper *m_pPsPlusUpsell; + PsPlusUpsellWrapper* m_pPsPlusUpsell; #endif public: - void destroy(); - volatile bool running; - std::wstring fpsString; - void run(); - // 4J-PB - split the run into 3 parts so we can run it from our xbox game loop - static Minecraft *GetInstance(); - void run_middle(); - void run_end(); + void destroy(); + volatile bool running; + std::wstring fpsString; + void run(); + // 4J-PB - split the run into 3 parts so we can run it from our xbox game + // loop + static Minecraft* GetInstance(); + void run_middle(); + void run_end(); - void emergencySave(); + void emergencySave(); - // 4J - removed - //bool wasDown ; + // 4J - removed + // bool wasDown ; private: - // void checkScreenshot(); // 4J - removed - // String grabHugeScreenshot(File workDir2, int width, int height, int ssWidth, int ssHeight); // 4J - removed + // void checkScreenshot(); // 4J - removed + // String grabHugeScreenshot(File workDir2, int width, int height, int + // ssWidth, int ssHeight); // 4J - removed - // 4J - per player thing? - __int64 lastTimer; + // 4J - per player thing? + __int64 lastTimer; - void renderFpsMeter(__int64 tickTime); -public: - void stop(); - // 4J removed - // bool mouseGrabbed; - // void grabMouse(); - // void releaseMouse(); - // 4J-PB - moved these into localplayer - //void handleMouseDown(int button, bool down); - //void handleMouseClick(int button); - - void pauseGame(); - // void toggleFullScreen(); // 4J - removed -private: - void resize(int width, int height); + void renderFpsMeter(__int64 tickTime); public: - // 4J - Moved to per player - //bool isRaining ; - - // 4J - Moved to per player - //__int64 lastTickTime; + void stop(); + // 4J removed + // bool mouseGrabbed; + // void grabMouse(); + // void releaseMouse(); + // 4J-PB - moved these into localplayer + // void handleMouseDown(int button, bool down); + // void handleMouseClick(int button); + void pauseGame(); + // void toggleFullScreen(); // 4J - removed private: - // 4J- per player? - int recheckPlayerIn; - void verify(); + void resize(int width, int height); public: - // 4J - added bFirst parameter, which is true for the first active viewport in splitscreen - // 4J - added bUpdateTextures, which is true if the actual renderer textures are to be updated - this will be true for the last time this tick runs with bFirst true - void tick(bool bFirst, bool bUpdateTextures); + // 4J - Moved to per player + // bool isRaining ; + + // 4J - Moved to per player + //__int64 lastTickTime; + private: - void reloadSound(); + // 4J- per player? + int recheckPlayerIn; + void verify(); + public: - bool isClientSide(); - void selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, const std::wstring& levelName, LevelSettings *levelSettings); - //void toggleDimension(int targetDimension); - bool saveSlot(int slot, const std::wstring& name); - bool loadSlot(const std::wstring& userName, int slot); - void releaseLevel(int message); - // 4J Stu - Added the doForceStatsSave param - //void setLevel(Level *level, bool doForceStatsSave = true); - //void setLevel(Level *level, const std::wstring& message, bool doForceStatsSave = true); - void setLevel(MultiPlayerLevel *level, int message = -1, std::shared_ptr forceInsertPlayer = nullptr, bool doForceStatsSave = true,bool bPrimaryPlayerSignedOut=false); - // 4J-PB - added to force in the 'other' level when the main player creates the level at game load time - void forceaddLevel(MultiPlayerLevel *level); - void prepareLevel(int title); // 4J - changed to public - void fileDownloaded(const std::wstring& name, File *file); - // OpenGLCapabilities getOpenGLCapabilities(); // 4J - removed + // 4J - added bFirst parameter, which is true for the first active viewport + // in splitscreen 4J - added bUpdateTextures, which is true if the actual + // renderer textures are to be updated - this will be true for the last time + // this tick runs with bFirst true + void tick(bool bFirst, bool bUpdateTextures); - std::wstring gatherStats1(); - std::wstring gatherStats2(); - std::wstring gatherStats3(); - std::wstring gatherStats4(); +private: + void reloadSound(); - void respawnPlayer(int iPad,int dimension,int newEntityId); - static void start(const std::wstring& name, const std::wstring& sid); - static void startAndConnectTo(const std::wstring& name, const std::wstring& sid, const std::wstring& url); - ClientConnection *getConnection(int iPad); // 4J Stu added iPad param - static void main(); - static bool renderNames(); - static bool useFancyGraphics(); - static bool useAmbientOcclusion(); - static bool renderDebug(); - bool handleClientSideCommand(const std::wstring& chatMessage); +public: + bool isClientSide(); + void selectLevel(ConsoleSaveFile* saveFile, const std::wstring& levelId, + const std::wstring& levelName, + LevelSettings* levelSettings); + // void toggleDimension(int targetDimension); + bool saveSlot(int slot, const std::wstring& name); + bool loadSlot(const std::wstring& userName, int slot); + void releaseLevel(int message); + // 4J Stu - Added the doForceStatsSave param + // void setLevel(Level *level, bool doForceStatsSave = true); + // void setLevel(Level *level, const std::wstring& message, bool + // doForceStatsSave = true); + void setLevel(MultiPlayerLevel* level, int message = -1, + std::shared_ptr forceInsertPlayer = nullptr, + bool doForceStatsSave = true, + bool bPrimaryPlayerSignedOut = false); + // 4J-PB - added to force in the 'other' level when the main player creates + // the level at game load time + void forceaddLevel(MultiPlayerLevel* level); + void prepareLevel(int title); // 4J - changed to public + void fileDownloaded(const std::wstring& name, File* file); + // OpenGLCapabilities getOpenGLCapabilities(); // 4J - removed - static int maxSupportedTextureSize(); - void delayTextureReload(); - static __int64 currentTimeMillis(); + std::wstring gatherStats1(); + std::wstring gatherStats2(); + std::wstring gatherStats3(); + std::wstring gatherStats4(); + + void respawnPlayer(int iPad, int dimension, int newEntityId); + static void start(const std::wstring& name, const std::wstring& sid); + static void startAndConnectTo(const std::wstring& name, + const std::wstring& sid, + const std::wstring& url); + ClientConnection* getConnection(int iPad); // 4J Stu added iPad param + static void main(); + static bool renderNames(); + static bool useFancyGraphics(); + static bool useAmbientOcclusion(); + static bool renderDebug(); + bool handleClientSideCommand(const std::wstring& chatMessage); + + static int maxSupportedTextureSize(); + void delayTextureReload(); + static __int64 currentTimeMillis(); #ifdef _DURANGO - static void inGameSignInCheckAllPrivilegesCallback(void *lpParam, bool hasPrivileges, int iPad); + static void inGameSignInCheckAllPrivilegesCallback(void* lpParam, + bool hasPrivileges, + int iPad); #endif - static int InGame_SignInReturned(void *pParam,bool bContinue, int iPad); - // 4J-PB - Screen * getScreen(); + static int InGame_SignInReturned(void* pParam, bool bContinue, int iPad); + // 4J-PB + Screen* getScreen(); - // 4J Stu - void forceStatsSave(int idx); + // 4J Stu + void forceStatsSave(int idx); + + CRITICAL_SECTION m_setLevelCS; - CRITICAL_SECTION m_setLevelCS; private: - // A bit field that store whether a particular quadrant is in the full tutorial or not - std::uint8_t m_inFullTutorialBits; + // A bit field that store whether a particular quadrant is in the full + // tutorial or not + std::uint8_t m_inFullTutorialBits; + public: - bool isTutorial(); - void playerStartedTutorial(int iPad); - void playerLeftTutorial(int iPad); + bool isTutorial(); + void playerStartedTutorial(int iPad); + void playerLeftTutorial(int iPad); - // 4J Added - MultiPlayerLevel *getLevel(int dimension); + // 4J Added + MultiPlayerLevel* getLevel(int dimension); - void tickAllConnections(); + void tickAllConnections(); - Level *animateTickLevel; // 4J added + Level* animateTickLevel; // 4J added - // 4J - When a client requests a texture, it should add it to here while we are waiting for it - std::vector m_pendingTextureRequests; - std::vector m_pendingGeometryRequests; // additional skin box geometry + // 4J - When a client requests a texture, it should add it to here while we + // are waiting for it + std::vector m_pendingTextureRequests; + std::vector + m_pendingGeometryRequests; // additional skin box geometry - // 4J Added - bool addPendingClientTextureRequest(const std::wstring &textureName); - void handleClientTextureReceived(const std::wstring &textureName); - void clearPendingClientTextureRequests() { m_pendingTextureRequests.clear(); } - bool addPendingClientGeometryRequest(const std::wstring &textureName); - void handleClientGeometryReceived(const std::wstring &textureName); - void clearPendingClientGeometryRequests() { m_pendingGeometryRequests.clear(); } + // 4J Added + bool addPendingClientTextureRequest(const std::wstring& textureName); + void handleClientTextureReceived(const std::wstring& textureName); + void clearPendingClientTextureRequests() { + m_pendingTextureRequests.clear(); + } + bool addPendingClientGeometryRequest(const std::wstring& textureName); + void handleClientGeometryReceived(const std::wstring& textureName); + void clearPendingClientGeometryRequests() { + m_pendingGeometryRequests.clear(); + } - unsigned int getCurrentTexturePackId(); - ColourTable *getColourTable(); + unsigned int getCurrentTexturePackId(); + ColourTable* getColourTable(); #if defined __ORBIS__ - static int MustSignInReturnedPSN(void *pParam, int iPad, C4JStorage::EMessageResult result); + static int MustSignInReturnedPSN(void* pParam, int iPad, + C4JStorage::EMessageResult result); #endif }; diff --git a/Minecraft.Client/MinecraftServer.cpp b/Minecraft.Client/MinecraftServer.cpp index 71910a18a..cf6bf483b 100644 --- a/Minecraft.Client/MinecraftServer.cpp +++ b/Minecraft.Client/MinecraftServer.cpp @@ -1,5 +1,5 @@ #include "Platform/stdafx.h" -//#include "Minecraft.h" +// #include "Minecraft.h" #include @@ -51,57 +51,54 @@ #define DEBUG_SERVER_DONT_SPAWN_MOBS 0 -//4J Added -MinecraftServer *MinecraftServer::server = NULL; +// 4J Added +MinecraftServer* MinecraftServer::server = NULL; bool MinecraftServer::setTimeAtEndOfTick = false; __int64 MinecraftServer::setTime = 0; bool MinecraftServer::setTimeOfDayAtEndOfTick = false; __int64 MinecraftServer::setTimeOfDay = 0; -bool MinecraftServer::m_bPrimaryPlayerSignedOut=false; -bool MinecraftServer::s_bServerHalted=false; -bool MinecraftServer::s_bSaveOnExitAnswered=false; +bool MinecraftServer::m_bPrimaryPlayerSignedOut = false; +bool MinecraftServer::s_bServerHalted = false; +bool MinecraftServer::s_bSaveOnExitAnswered = false; int MinecraftServer::s_slowQueuePlayerIndex = 0; int MinecraftServer::s_slowQueueLastTime = 0; bool MinecraftServer::s_slowQueuePacketSent = false; std::unordered_map MinecraftServer::ironTimers; -MinecraftServer::MinecraftServer() -{ - // 4J - added initialisers - connection = NULL; +MinecraftServer::MinecraftServer() { + // 4J - added initialisers + connection = NULL; settings = NULL; players = NULL; - commands = NULL; + commands = NULL; running = true; - m_bLoaded = false; - stopped = false; + m_bLoaded = false; + stopped = false; tickCount = 0; - std::wstring progressStatus; + std::wstring progressStatus; progress = 0; - motd = L""; + motd = L""; - m_isServerPaused = false; - m_serverPausedEvent = new C4JThread::Event; + m_isServerPaused = false; + m_serverPausedEvent = new C4JThread::Event; - m_saveOnExit = false; - m_suspending = false; + m_saveOnExit = false; + m_suspending = false; - m_ugcPlayersVersion = 0; - m_texturePackId = 0; - maxBuildHeight = Level::maxBuildHeight; - m_postUpdateThread = NULL; + m_ugcPlayersVersion = 0; + m_texturePackId = 0; + maxBuildHeight = Level::maxBuildHeight; + m_postUpdateThread = NULL; - commandDispatcher = new ServerCommandDispatcher(); + commandDispatcher = new ServerCommandDispatcher(); } -MinecraftServer::~MinecraftServer() -{ -} +MinecraftServer::~MinecraftServer() {} -bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, std::uint32_t initSettings, bool findSeed) -{ - // 4J - removed +bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData* initData, + std::uint32_t initSettings, bool findSeed) { + // 4J - removed #if 0 commands = new ConsoleCommands(this); @@ -132,116 +129,141 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, st logger.info("Loading properties"); #endif - settings = new Settings(new File(L"server.properties")); + settings = new Settings(new File(L"server.properties")); - app.DebugPrintf("\n*** SERVER SETTINGS ***\n"); - app.DebugPrintf("ServerSettings: host-friends-only is %s\n",(app.GetGameHostOption(eGameHostOption_FriendsOfFriends)>0)?"on":"off"); - app.DebugPrintf("ServerSettings: game-type is %s\n",(app.GetGameHostOption(eGameHostOption_GameType)==0)?"Survival Mode":"Creative Mode"); - app.DebugPrintf("ServerSettings: pvp is %s\n",(app.GetGameHostOption(eGameHostOption_PvP)>0)?"on":"off"); - app.DebugPrintf("ServerSettings: fire spreads is %s\n",(app.GetGameHostOption(eGameHostOption_FireSpreads)>0)?"on":"off"); - app.DebugPrintf("ServerSettings: tnt explodes is %s\n",(app.GetGameHostOption(eGameHostOption_TNT)>0)?"on":"off"); - app.DebugPrintf("\n"); + app.DebugPrintf("\n*** SERVER SETTINGS ***\n"); + app.DebugPrintf( + "ServerSettings: host-friends-only is %s\n", + (app.GetGameHostOption(eGameHostOption_FriendsOfFriends) > 0) ? "on" + : "off"); + app.DebugPrintf("ServerSettings: game-type is %s\n", + (app.GetGameHostOption(eGameHostOption_GameType) == 0) + ? "Survival Mode" + : "Creative Mode"); + app.DebugPrintf( + "ServerSettings: pvp is %s\n", + (app.GetGameHostOption(eGameHostOption_PvP) > 0) ? "on" : "off"); + app.DebugPrintf("ServerSettings: fire spreads is %s\n", + (app.GetGameHostOption(eGameHostOption_FireSpreads) > 0) + ? "on" + : "off"); + app.DebugPrintf( + "ServerSettings: tnt explodes is %s\n", + (app.GetGameHostOption(eGameHostOption_TNT) > 0) ? "on" : "off"); + app.DebugPrintf("\n"); - // TODO 4J Stu - Init a load of settings based on data passed as params - //settings->setBooleanAndSave( L"host-friends-only", (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)>0) ); + // TODO 4J Stu - Init a load of settings based on data passed as params + // settings->setBooleanAndSave( L"host-friends-only", + // (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)>0) ); - // 4J - Unused - //localIp = settings->getString(L"server-ip", L""); - //onlineMode = settings->getBoolean(L"online-mode", true); - //motd = settings->getString(L"motd", L"A Minecraft Server"); - //motd.replace('§', '$'); + // 4J - Unused + // localIp = settings->getString(L"server-ip", L""); + // onlineMode = settings->getBoolean(L"online-mode", true); + // motd = settings->getString(L"motd", L"A Minecraft Server"); + // motd.replace('§', '$'); - setAnimals(settings->getBoolean(L"spawn-animals", true)); - setNpcsEnabled(settings->getBoolean(L"spawn-npcs", true)); - setPvpAllowed(app.GetGameHostOption( eGameHostOption_PvP )>0?true:false); // settings->getBoolean(L"pvp", true); + setAnimals(settings->getBoolean(L"spawn-animals", true)); + setNpcsEnabled(settings->getBoolean(L"spawn-npcs", true)); + setPvpAllowed(app.GetGameHostOption(eGameHostOption_PvP) > 0 + ? true + : false); // settings->getBoolean(L"pvp", true); - // 4J Stu - We should never have hacked clients flying when they shouldn't be like the PC version, so enable flying always - // Fix for #46612 - TU5: Code: Multiplayer: A client can be banned for flying when accidentaly being blown by dynamite - setFlightAllowed(true); //settings->getBoolean(L"allow-flight", false); + // 4J Stu - We should never have hacked clients flying when they shouldn't + // be like the PC version, so enable flying always Fix for #46612 - TU5: + // Code: Multiplayer: A client can be banned for flying when accidentaly + // being blown by dynamite + setFlightAllowed(true); // settings->getBoolean(L"allow-flight", false); - // 4J Stu - Enabling flight to stop it kicking us when we use it + // 4J Stu - Enabling flight to stop it kicking us when we use it #ifdef _DEBUG_MENUS_ENABLED - setFlightAllowed(true); + setFlightAllowed(true); #endif #if 1 - connection = new ServerConnection(this); - Socket::Initialise(connection); // 4J - added + connection = new ServerConnection(this); + Socket::Initialise(connection); // 4J - added #else - // 4J - removed - InetAddress localAddress = null; - if (localIp.length() > 0) localAddress = InetAddress.getByName(localIp); - port = settings.getInt("server-port", DEFAULT_MINECRAFT_PORT); + // 4J - removed + InetAddress localAddress = null; + if (localIp.length() > 0) localAddress = InetAddress.getByName(localIp); + port = settings.getInt("server-port", DEFAULT_MINECRAFT_PORT); - logger.info("Starting Minecraft server on " + (localIp.length() == 0 ? "*" : localIp) + ":" + port); - try { - connection = new ServerConnection(this, localAddress, port); - } catch (IOException e) { - logger.warning("**** FAILED TO BIND TO PORT!"); - logger.log(Level.WARNING, "The exception was: " + e.toString()); - logger.warning("Perhaps a server is already running on that port?"); - return false; - } + logger.info("Starting Minecraft server on " + + (localIp.length() == 0 ? "*" : localIp) + ":" + port); + try { + connection = new ServerConnection(this, localAddress, port); + } catch (IOException e) { + logger.warning("**** FAILED TO BIND TO PORT!"); + logger.log(Level.WARNING, "The exception was: " + e.toString()); + logger.warning("Perhaps a server is already running on that port?"); + return false; + } - if (!onlineMode) { - logger.warning("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); - logger.warning("The server will make no attempt to authenticate usernames. Beware."); - logger.warning("While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose."); - logger.warning("To change this, set \"online-mode\" to \"true\" in the server.settings file."); - } + if (!onlineMode) { + logger.warning("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); + logger.warning( + "The server will make no attempt to authenticate usernames. " + "Beware."); + logger.warning( + "While this makes the game possible to play without internet " + "access, it also opens up the ability for hackers to connect with " + "any username they choose."); + logger.warning( + "To change this, set \"online-mode\" to \"true\" in the " + "server.settings file."); + } #endif - setPlayers(new PlayerList(this)); + setPlayers(new PlayerList(this)); - // 4J-JEV: Need to wait for levelGenerationOptions to load. - while ( app.getLevelGenerationOptions() != NULL && !app.getLevelGenerationOptions()->hasLoadedData() ) - Sleep(1); + // 4J-JEV: Need to wait for levelGenerationOptions to load. + while (app.getLevelGenerationOptions() != NULL && + !app.getLevelGenerationOptions()->hasLoadedData()) + Sleep(1); - if ( app.getLevelGenerationOptions() != NULL && !app.getLevelGenerationOptions()->ready() ) - { - // TODO: Stop loading, add error message. - } + if (app.getLevelGenerationOptions() != NULL && + !app.getLevelGenerationOptions()->ready()) { + // TODO: Stop loading, add error message. + } - __int64 levelNanoTime = System::nanoTime(); + __int64 levelNanoTime = System::nanoTime(); - std::wstring levelName = settings->getString(L"level-name", L"world"); - std::wstring levelTypeString; + std::wstring levelName = settings->getString(L"level-name", L"world"); + std::wstring levelTypeString; - bool gameRuleUseFlatWorld = false; - if(app.getLevelGenerationOptions() != NULL) - { - gameRuleUseFlatWorld = app.getLevelGenerationOptions()->getuseFlatWorld(); - } - if(gameRuleUseFlatWorld || app.GetGameHostOption(eGameHostOption_LevelType)>0) - { - levelTypeString = settings->getString(L"level-type", L"flat"); - } - else - { - levelTypeString = settings->getString(L"level-type",L"default"); - } + bool gameRuleUseFlatWorld = false; + if (app.getLevelGenerationOptions() != NULL) { + gameRuleUseFlatWorld = + app.getLevelGenerationOptions()->getuseFlatWorld(); + } + if (gameRuleUseFlatWorld || + app.GetGameHostOption(eGameHostOption_LevelType) > 0) { + levelTypeString = settings->getString(L"level-type", L"flat"); + } else { + levelTypeString = settings->getString(L"level-type", L"default"); + } - LevelType *pLevelType = LevelType::getLevelType(levelTypeString); - if (pLevelType == NULL) - { - pLevelType = LevelType::lvl_normal; - } + LevelType* pLevelType = LevelType::getLevelType(levelTypeString); + if (pLevelType == NULL) { + pLevelType = LevelType::lvl_normal; + } - ProgressRenderer *mcprogress = Minecraft::GetInstance()->progressRenderer; - mcprogress->progressStart(IDS_PROGRESS_INITIALISING_SERVER); + ProgressRenderer* mcprogress = Minecraft::GetInstance()->progressRenderer; + mcprogress->progressStart(IDS_PROGRESS_INITIALISING_SERVER); - if( findSeed ) - { + if (findSeed) { #ifdef __PSVITA__ - seed = BiomeSource::findSeed(pLevelType, &running); + seed = BiomeSource::findSeed(pLevelType, &running); #else - seed = BiomeSource::findSeed(pLevelType); + seed = BiomeSource::findSeed(pLevelType); #endif - } + } - setMaxBuildHeight(settings->getInt(L"max-build-height", Level::maxBuildHeight)); - setMaxBuildHeight(((getMaxBuildHeight() + 8) / 16) * 16); - setMaxBuildHeight(Mth::clamp(getMaxBuildHeight(), 64, Level::maxBuildHeight)); - //settings->setProperty(L"max-build-height", maxBuildHeight); + setMaxBuildHeight( + settings->getInt(L"max-build-height", Level::maxBuildHeight)); + setMaxBuildHeight(((getMaxBuildHeight() + 8) / 16) * 16); + setMaxBuildHeight( + Mth::clamp(getMaxBuildHeight(), 64, Level::maxBuildHeight)); + // settings->setProperty(L"max-build-height", maxBuildHeight); #if 0 std::wstring levelSeedString = settings->getString(L"level-seed", L""); @@ -254,317 +276,342 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, st } } #endif -// logger.info("Preparing level \"" + levelName + "\""); - m_bLoaded = loadLevel(new McRegionLevelStorageSource(File(L".")), levelName, seed, pLevelType, initData); -// logger.info("Done (" + (System.nanoTime() - levelNanoTime) + "ns)! For help, type \"help\" or \"?\""); - app.DebugPrintf("[SRV] loadLevel returned %d\n", m_bLoaded); + // logger.info("Preparing level \"" + levelName + "\""); + m_bLoaded = loadLevel(new McRegionLevelStorageSource(File(L".")), levelName, + seed, pLevelType, initData); + // logger.info("Done (" + (System.nanoTime() - levelNanoTime) + "ns)! + // For help, type \"help\" or \"?\""); + app.DebugPrintf("[SRV] loadLevel returned %d\n", m_bLoaded); - // 4J delete passed in save data now - this is only required for the tutorial which is loaded by passing data directly in rather than using the storage manager - if( initData->saveData ) - { - delete[] reinterpret_cast(initData->saveData->data); - initData->saveData->data = 0; - initData->saveData->fileSize = 0; - } - - app.DebugPrintf("[SRV] Signaling ServerReady\n"); - g_NetworkManager.ServerReady(); // 4J added - app.DebugPrintf("[SRV] ServerReady signaled, returning m_bLoaded=%d\n", m_bLoaded); - return m_bLoaded; + // 4J delete passed in save data now - this is only required for the + // tutorial which is loaded by passing data directly in rather than using + // the storage manager + if (initData->saveData) { + delete[] reinterpret_cast(initData->saveData->data); + initData->saveData->data = 0; + initData->saveData->fileSize = 0; + } + app.DebugPrintf("[SRV] Signaling ServerReady\n"); + g_NetworkManager.ServerReady(); // 4J added + app.DebugPrintf("[SRV] ServerReady signaled, returning m_bLoaded=%d\n", + m_bLoaded); + return m_bLoaded; } -// 4J - added - extra thread to post processing on separate thread during level creation -int MinecraftServer::runPostUpdate(void* lpParam) -{ - ShutdownManager::HasStarted(ShutdownManager::ePostProcessThread); +// 4J - added - extra thread to post processing on separate thread during level +// creation +int MinecraftServer::runPostUpdate(void* lpParam) { + ShutdownManager::HasStarted(ShutdownManager::ePostProcessThread); - MinecraftServer *server = (MinecraftServer *)lpParam; - Entity::useSmallIds(); // This thread can end up spawning entities as resources - IntCache::CreateNewThreadStorage(); - AABB::CreateNewThreadStorage(); - Vec3::CreateNewThreadStorage(); - Compression::UseDefaultThreadStorage(); - Level::enableLightingCache(); - Tile::CreateNewThreadStorage(); + MinecraftServer* server = (MinecraftServer*)lpParam; + Entity::useSmallIds(); // This thread can end up spawning entities as + // resources + IntCache::CreateNewThreadStorage(); + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + Compression::UseDefaultThreadStorage(); + Level::enableLightingCache(); + Tile::CreateNewThreadStorage(); - // Update lights for both levels until we are signalled to terminate - do - { - EnterCriticalSection(&server->m_postProcessCS); - if( server->m_postProcessRequests.size() ) - { - MinecraftServer::postProcessRequest request = server->m_postProcessRequests.back(); - server->m_postProcessRequests.pop_back(); - LeaveCriticalSection(&server->m_postProcessCS); - static int count = 0; - PIXBeginNamedEvent(0,"Post processing %d ", (count++)%8); - request.chunkSource->postProcess(request.chunkSource, request.x, request.z ); - PIXEndNamedEvent(); - } - else - { - LeaveCriticalSection(&server->m_postProcessCS); - } - Sleep(1); - } while (!server->m_postUpdateTerminate && ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)); -//#ifndef __PS3__ - // One final pass through updates to make sure we're done - EnterCriticalSection(&server->m_postProcessCS); - int maxRequests = server->m_postProcessRequests.size(); - while(server->m_postProcessRequests.size() && ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread) ) - { - MinecraftServer::postProcessRequest request = server->m_postProcessRequests.back(); - server->m_postProcessRequests.pop_back(); - LeaveCriticalSection(&server->m_postProcessCS); - request.chunkSource->postProcess(request.chunkSource, request.x, request.z ); + // Update lights for both levels until we are signalled to terminate + do { + EnterCriticalSection(&server->m_postProcessCS); + if (server->m_postProcessRequests.size()) { + MinecraftServer::postProcessRequest request = + server->m_postProcessRequests.back(); + server->m_postProcessRequests.pop_back(); + LeaveCriticalSection(&server->m_postProcessCS); + static int count = 0; + PIXBeginNamedEvent(0, "Post processing %d ", (count++) % 8); + request.chunkSource->postProcess(request.chunkSource, request.x, + request.z); + PIXEndNamedEvent(); + } else { + LeaveCriticalSection(&server->m_postProcessCS); + } + Sleep(1); + } while (!server->m_postUpdateTerminate && + ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)); + // #ifndef __PS3__ + // One final pass through updates to make sure we're done + EnterCriticalSection(&server->m_postProcessCS); + int maxRequests = server->m_postProcessRequests.size(); + while (server->m_postProcessRequests.size() && + ShutdownManager::ShouldRun(ShutdownManager::ePostProcessThread)) { + MinecraftServer::postProcessRequest request = + server->m_postProcessRequests.back(); + server->m_postProcessRequests.pop_back(); + LeaveCriticalSection(&server->m_postProcessCS); + request.chunkSource->postProcess(request.chunkSource, request.x, + request.z); #ifdef __PS3__ #ifndef _CONTENT_PACKAGE - if((server->m_postProcessRequests.size() % 10) == 0) - printf("processing request %00d\n", server->m_postProcessRequests.size()); + if ((server->m_postProcessRequests.size() % 10) == 0) + printf("processing request %00d\n", + server->m_postProcessRequests.size()); #endif - Sleep(1); + Sleep(1); #endif - EnterCriticalSection(&server->m_postProcessCS); - } - LeaveCriticalSection(&server->m_postProcessCS); -//#endif //__PS3__ - Tile::ReleaseThreadStorage(); - IntCache::ReleaseThreadStorage(); - AABB::ReleaseThreadStorage(); - Vec3::ReleaseThreadStorage(); - Level::destroyLightingCache(); + EnterCriticalSection(&server->m_postProcessCS); + } + LeaveCriticalSection(&server->m_postProcessCS); + // #endif //__PS3__ + Tile::ReleaseThreadStorage(); + IntCache::ReleaseThreadStorage(); + AABB::ReleaseThreadStorage(); + Vec3::ReleaseThreadStorage(); + Level::destroyLightingCache(); - ShutdownManager::HasFinished(ShutdownManager::ePostProcessThread); + ShutdownManager::HasFinished(ShutdownManager::ePostProcessThread); - return 0; + return 0; } -void MinecraftServer::addPostProcessRequest(ChunkSource *chunkSource, int x, int z) -{ - EnterCriticalSection(&m_postProcessCS); - m_postProcessRequests.push_back(MinecraftServer::postProcessRequest(x,z,chunkSource)); - LeaveCriticalSection(&m_postProcessCS); +void MinecraftServer::addPostProcessRequest(ChunkSource* chunkSource, int x, + int z) { + EnterCriticalSection(&m_postProcessCS); + m_postProcessRequests.push_back( + MinecraftServer::postProcessRequest(x, z, chunkSource)); + LeaveCriticalSection(&m_postProcessCS); } -void MinecraftServer::postProcessTerminate(ProgressRenderer *mcprogress) -{ - std::uint32_t status = 0; +void MinecraftServer::postProcessTerminate(ProgressRenderer* mcprogress) { + std::uint32_t status = 0; - EnterCriticalSection(&server->m_postProcessCS); - size_t postProcessItemCount = server->m_postProcessRequests.size(); - LeaveCriticalSection(&server->m_postProcessCS); + EnterCriticalSection(&server->m_postProcessCS); + size_t postProcessItemCount = server->m_postProcessRequests.size(); + LeaveCriticalSection(&server->m_postProcessCS); - do - { - status = m_postUpdateThread->WaitForCompletion(50); - if( status == WAIT_TIMEOUT ) - { - EnterCriticalSection(&server->m_postProcessCS); - size_t postProcessItemRemaining = server->m_postProcessRequests.size(); - LeaveCriticalSection(&server->m_postProcessCS); + do { + status = m_postUpdateThread->WaitForCompletion(50); + if (status == WAIT_TIMEOUT) { + EnterCriticalSection(&server->m_postProcessCS); + size_t postProcessItemRemaining = + server->m_postProcessRequests.size(); + LeaveCriticalSection(&server->m_postProcessCS); - if( postProcessItemCount ) - { - mcprogress->progressStagePercentage((postProcessItemCount - postProcessItemRemaining) * 100 / postProcessItemCount); - } - CompressedTileStorage::tick(); - SparseLightStorage::tick(); - SparseDataStorage::tick(); - } - } while ( status == WAIT_TIMEOUT ); - delete m_postUpdateThread; - m_postUpdateThread = NULL; - DeleteCriticalSection(&m_postProcessCS); + if (postProcessItemCount) { + mcprogress->progressStagePercentage( + (postProcessItemCount - postProcessItemRemaining) * 100 / + postProcessItemCount); + } + CompressedTileStorage::tick(); + SparseLightStorage::tick(); + SparseDataStorage::tick(); + } + } while (status == WAIT_TIMEOUT); + delete m_postUpdateThread; + m_postUpdateThread = NULL; + DeleteCriticalSection(&m_postProcessCS); } -bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const std::wstring& name, __int64 levelSeed, LevelType *pLevelType, NetworkGameInitData *initData) -{ -// 4J - TODO - do with new save stuff -// if (storageSource->requiresConversion(name)) -// { -// assert(false); -// } - ProgressRenderer *mcprogress = Minecraft::GetInstance()->progressRenderer; +bool MinecraftServer::loadLevel(LevelStorageSource* storageSource, + const std::wstring& name, __int64 levelSeed, + LevelType* pLevelType, + NetworkGameInitData* initData) { + // 4J - TODO - do with new save stuff + // if (storageSource->requiresConversion(name)) + // { + // assert(false); + // } + ProgressRenderer* mcprogress = Minecraft::GetInstance()->progressRenderer; - // 4J TODO - free levels here if there are already some? + // 4J TODO - free levels here if there are already some? levels = ServerLevelArray(3); - int gameTypeId = settings->getInt(L"gamemode", app.GetGameHostOption(eGameHostOption_GameType));//LevelSettings::GAMETYPE_SURVIVAL); - GameType *gameType = LevelSettings::validateGameType(gameTypeId); - app.DebugPrintf("Default game type: %d\n" , gameTypeId); + int gameTypeId = settings->getInt( + L"gamemode", + app.GetGameHostOption( + eGameHostOption_GameType)); // LevelSettings::GAMETYPE_SURVIVAL); + GameType* gameType = LevelSettings::validateGameType(gameTypeId); + app.DebugPrintf("Default game type: %d\n", gameTypeId); - LevelSettings *levelSettings = new LevelSettings(levelSeed, gameType, app.GetGameHostOption(eGameHostOption_Structures)>0?true:false, isHardcore(), true, pLevelType, initData->xzSize, initData->hellScale); - if( app.GetGameHostOption(eGameHostOption_BonusChest ) ) levelSettings->enableStartingBonusItems(); + LevelSettings* levelSettings = new LevelSettings( + levelSeed, gameType, + app.GetGameHostOption(eGameHostOption_Structures) > 0 ? true : false, + isHardcore(), true, pLevelType, initData->xzSize, initData->hellScale); + if (app.GetGameHostOption(eGameHostOption_BonusChest)) + levelSettings->enableStartingBonusItems(); - // 4J - temp - load existing level - std::shared_ptr storage = nullptr; - bool levelChunksNeedConverted = false; - if( initData->saveData != NULL ) - { - // We are loading a file from disk with the data passed in + // 4J - temp - load existing level + std::shared_ptr storage = nullptr; + bool levelChunksNeedConverted = false; + if (initData->saveData != NULL) { + // We are loading a file from disk with the data passed in -#ifdef SPLIT_SAVES - ConsoleSaveFileOriginal oldFormatSave( initData->saveData->saveName, initData->saveData->data, initData->saveData->fileSize, false, initData->savePlatform ); - ConsoleSaveFile* pSave = new ConsoleSaveFileSplit( &oldFormatSave ); - - //ConsoleSaveFile* pSave = new ConsoleSaveFileSplit( initData->saveData->saveName, initData->saveData->data, initData->saveData->fileSize, false, initData->savePlatform ); -#else - ConsoleSaveFile* pSave = new ConsoleSaveFileOriginal( initData->saveData->saveName, initData->saveData->data, initData->saveData->fileSize, false, initData->savePlatform ); -#endif - if(pSave->isSaveEndianDifferent()) - levelChunksNeedConverted = true; - pSave->ConvertToLocalPlatform(); // check if we need to convert this file from PS3->PS4 - - storage = std::shared_ptr(new McRegionLevelStorage(pSave, File(L"."), name, true)); - } - else - { - // We are loading a save from the storage manager #ifdef SPLIT_SAVES - bool bLevelGenBaseSave = false; - LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if( levelGen != NULL && levelGen->requiresBaseSave()) - { - unsigned int fileSize = 0; - std::uint8_t *pvSaveData = levelGen->getBaseSaveData(fileSize); - if(pvSaveData && fileSize != 0) bLevelGenBaseSave = true; - } - ConsoleSaveFileSplit *newFormatSave = NULL; - if(bLevelGenBaseSave) - { - ConsoleSaveFileOriginal oldFormatSave( L"" ); - newFormatSave = new ConsoleSaveFileSplit( &oldFormatSave ); - } - else - { - newFormatSave = new ConsoleSaveFileSplit( L"" ); - } + ConsoleSaveFileOriginal oldFormatSave( + initData->saveData->saveName, initData->saveData->data, + initData->saveData->fileSize, false, initData->savePlatform); + ConsoleSaveFile* pSave = new ConsoleSaveFileSplit(&oldFormatSave); - storage = std::shared_ptr(new McRegionLevelStorage(newFormatSave, File(L"."), name, true)); + // ConsoleSaveFile* pSave = new ConsoleSaveFileSplit( + // initData->saveData->saveName, initData->saveData->data, + // initData->saveData->fileSize, false, initData->savePlatform ); #else - storage = std::shared_ptr(new McRegionLevelStorage(new ConsoleSaveFileOriginal( L"" ), File(L"."), name, true)); + ConsoleSaveFile* pSave = new ConsoleSaveFileOriginal( + initData->saveData->saveName, initData->saveData->data, + initData->saveData->fileSize, false, initData->savePlatform); #endif - } + if (pSave->isSaveEndianDifferent()) levelChunksNeedConverted = true; + pSave->ConvertToLocalPlatform(); // check if we need to convert this + // file from PS3->PS4 -// McRegionLevelStorage *storage = new McRegionLevelStorage(new ConsoleSaveFile( L"" ), L"", L"", 0); // original -// McRegionLevelStorage *storage = new McRegionLevelStorage(File(L"."), name, true); // TODO - for (unsigned int i = 0; i < levels.length; i++) - { - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) - { - return false; - } + storage = std::shared_ptr( + new McRegionLevelStorage(pSave, File(L"."), name, true)); + } else { + // We are loading a save from the storage manager +#ifdef SPLIT_SAVES + bool bLevelGenBaseSave = false; + LevelGenerationOptions* levelGen = app.getLevelGenerationOptions(); + if (levelGen != NULL && levelGen->requiresBaseSave()) { + unsigned int fileSize = 0; + std::uint8_t* pvSaveData = levelGen->getBaseSaveData(fileSize); + if (pvSaveData && fileSize != 0) bLevelGenBaseSave = true; + } + ConsoleSaveFileSplit* newFormatSave = NULL; + if (bLevelGenBaseSave) { + ConsoleSaveFileOriginal oldFormatSave(L""); + newFormatSave = new ConsoleSaveFileSplit(&oldFormatSave); + } else { + newFormatSave = new ConsoleSaveFileSplit(L""); + } -// String levelName = name; -// if (i == 1) levelName += "_nether"; - int dimension = 0; - if (i == 1) dimension = -1; - if (i == 2) dimension = 1; - if (i == 0) - { - levels[i] = new ServerLevel(this, storage, name, dimension, levelSettings); - if(app.getLevelGenerationOptions() != NULL) - { - LevelGenerationOptions *mapOptions = app.getLevelGenerationOptions(); - Pos *spawnPos = mapOptions->getSpawnPos(); - if( spawnPos != NULL ) - { - levels[i]->setSpawnPos( spawnPos ); - } + storage = std::shared_ptr( + new McRegionLevelStorage(newFormatSave, File(L"."), name, true)); +#else + storage = + std::shared_ptr(new McRegionLevelStorage( + new ConsoleSaveFileOriginal(L""), File(L"."), name, true)); +#endif + } - levels[i]->getLevelData()->setHasBeenInCreative(mapOptions->isFromDLC()); - } - } - else levels[i] = new DerivedServerLevel(this, storage, name, dimension, levelSettings, levels[0]); -// levels[i]->addListener(new ServerLevelListener(this, levels[i])); // 4J - have moved this to the ServerLevel ctor so that it is set up in time for the first chunk to load, which might actually happen there + // McRegionLevelStorage *storage = new McRegionLevelStorage(new + //ConsoleSaveFile( L"" ), L"", L"", 0); // original + // McRegionLevelStorage *storage = new McRegionLevelStorage(File(L"."), + // name, true); // TODO + for (unsigned int i = 0; i < levels.length; i++) { + if (s_bServerHalted || !g_NetworkManager.IsInSession()) { + return false; + } - // 4J Stu - We set the levels difficulty based on the minecraft options - //levels[i]->difficulty = settings->getBoolean(L"spawn-monsters", true) ? Difficulty::EASY : Difficulty::PEACEFUL; - Minecraft *pMinecraft = Minecraft::GetInstance(); -// m_lastSentDifficulty = pMinecraft->options->difficulty; - levels[i]->difficulty = app.GetGameHostOption(eGameHostOption_Difficulty); //pMinecraft->options->difficulty; - app.DebugPrintf("MinecraftServer::loadLevel - Difficulty = %d\n",levels[i]->difficulty); + // String levelName = name; + // if (i == 1) levelName += "_nether"; + int dimension = 0; + if (i == 1) dimension = -1; + if (i == 2) dimension = 1; + if (i == 0) { + levels[i] = + new ServerLevel(this, storage, name, dimension, levelSettings); + if (app.getLevelGenerationOptions() != NULL) { + LevelGenerationOptions* mapOptions = + app.getLevelGenerationOptions(); + Pos* spawnPos = mapOptions->getSpawnPos(); + if (spawnPos != NULL) { + levels[i]->setSpawnPos(spawnPos); + } + + levels[i]->getLevelData()->setHasBeenInCreative( + mapOptions->isFromDLC()); + } + } else + levels[i] = new DerivedServerLevel(this, storage, name, dimension, + levelSettings, levels[0]); + // levels[i]->addListener(new ServerLevelListener(this, + // levels[i])); // 4J - have moved this to the + // ServerLevel ctor so that it is set up in time for the first + // chunk to load, which might actually happen there + + // 4J Stu - We set the levels difficulty based on the minecraft options + // levels[i]->difficulty = settings->getBoolean(L"spawn-monsters", true) + // ? Difficulty::EASY : Difficulty::PEACEFUL; + Minecraft* pMinecraft = Minecraft::GetInstance(); + // m_lastSentDifficulty = pMinecraft->options->difficulty; + levels[i]->difficulty = app.GetGameHostOption( + eGameHostOption_Difficulty); // pMinecraft->options->difficulty; + app.DebugPrintf("MinecraftServer::loadLevel - Difficulty = %d\n", + levels[i]->difficulty); #if DEBUG_SERVER_DONT_SPAWN_MOBS levels[i]->setSpawnSettings(false, false); #else - levels[i]->setSpawnSettings(settings->getBoolean(L"spawn-monsters", true), animals); + levels[i]->setSpawnSettings( + settings->getBoolean(L"spawn-monsters", true), animals); #endif - levels[i]->getLevelData()->setGameType(gameType); + levels[i]->getLevelData()->setGameType(gameType); players->setLevel(levels); } - if( levels[0]->isNew ) - { - mcprogress->progressStage(IDS_PROGRESS_GENERATING_SPAWN_AREA); - } - else - { - mcprogress->progressStage(IDS_PROGRESS_LOADING_SPAWN_AREA); - } - app.SetGameHostOption( eGameHostOption_HasBeenInCreative, gameType == GameType::CREATIVE || levels[0]->getHasBeenInCreative() ); - app.SetGameHostOption( eGameHostOption_Structures, levels[0]->isGenerateMapFeatures() ); + if (levels[0]->isNew) { + mcprogress->progressStage(IDS_PROGRESS_GENERATING_SPAWN_AREA); + } else { + mcprogress->progressStage(IDS_PROGRESS_LOADING_SPAWN_AREA); + } + app.SetGameHostOption( + eGameHostOption_HasBeenInCreative, + gameType == GameType::CREATIVE || levels[0]->getHasBeenInCreative()); + app.SetGameHostOption(eGameHostOption_Structures, + levels[0]->isGenerateMapFeatures()); - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - // 4J - Make a new thread to do post processing - InitializeCriticalSection(&m_postProcessCS); + // 4J - Make a new thread to do post processing + InitializeCriticalSection(&m_postProcessCS); - app.DebugPrintf("[SRV] Starting post-processing thread\n"); + app.DebugPrintf("[SRV] Starting post-processing thread\n"); - m_postUpdateThread = new C4JThread(runPostUpdate, this, "Post processing", 256*1024); + m_postUpdateThread = + new C4JThread(runPostUpdate, this, "Post processing", 256 * 1024); - m_postUpdateTerminate = false; - m_postUpdateThread->SetProcessor(CPU_CORE_POST_PROCESSING); - m_postUpdateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); - m_postUpdateThread->Run(); - app.DebugPrintf("[SRV] Post-processing thread started\n"); + m_postUpdateTerminate = false; + m_postUpdateThread->SetProcessor(CPU_CORE_POST_PROCESSING); + m_postUpdateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); + m_postUpdateThread->Run(); + app.DebugPrintf("[SRV] Post-processing thread started\n"); - __int64 startTime = System::currentTimeMillis(); + __int64 startTime = System::currentTimeMillis(); - // 4J Stu - Added this to temporarily make starting games on vita faster + // 4J Stu - Added this to temporarily make starting games on vita faster #ifdef __PSVITA__ - int r = 48; + int r = 48; #else - int r = 196; + int r = 196; #endif - // 4J JEV: load gameRules. - ConsoleSavePath filepath(GAME_RULE_SAVENAME); - ConsoleSaveFile *csf = getLevel(0)->getLevelStorage()->getSaveFile(); - if( csf->doesFileExist(filepath) ) - { - unsigned int numberOfBytesRead; - byteArray ba_gameRules; + // 4J JEV: load gameRules. + ConsoleSavePath filepath(GAME_RULE_SAVENAME); + ConsoleSaveFile* csf = getLevel(0)->getLevelStorage()->getSaveFile(); + if (csf->doesFileExist(filepath)) { + unsigned int numberOfBytesRead; + byteArray ba_gameRules; - FileEntry *fe = csf->createFile(filepath); + FileEntry* fe = csf->createFile(filepath); - ba_gameRules.length = fe->getFileSize(); - ba_gameRules.data = new std::uint8_t[ ba_gameRules.length ]; + ba_gameRules.length = fe->getFileSize(); + ba_gameRules.data = new std::uint8_t[ba_gameRules.length]; - csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); - csf->readFile(fe, ba_gameRules.data, ba_gameRules.length, &numberOfBytesRead); - assert(numberOfBytesRead == ba_gameRules.length); + csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); + csf->readFile(fe, ba_gameRules.data, ba_gameRules.length, + &numberOfBytesRead); + assert(numberOfBytesRead == ba_gameRules.length); - app.m_gameRules.loadGameRules(ba_gameRules.data, ba_gameRules.length); - csf->closeHandle(fe); - } + app.m_gameRules.loadGameRules(ba_gameRules.data, ba_gameRules.length); + csf->closeHandle(fe); + } __int64 lastTime = System::currentTimeMillis(); - // 4J Stu - This loop is changed in 1.0.1 to only process the first level (ie the overworld), but I think we still want to do them all - int i = 0; - for (int i = 0; i < levels.length ; i++) - { -// logger.info("Preparing start region for level " + i); - if (i == 0 || settings->getBoolean(L"allow-nether", true)) - { - ServerLevel *level = levels[i]; - if(levelChunksNeedConverted) - { -// storage->getSaveFile()->convertLevelChunks(level) - } + // 4J Stu - This loop is changed in 1.0.1 to only process the first level + // (ie the overworld), but I think we still want to do them all + int i = 0; + for (int i = 0; i < levels.length; i++) { + // logger.info("Preparing start region for level " + i); + if (i == 0 || settings->getBoolean(L"allow-nether", true)) { + ServerLevel* level = levels[i]; + if (levelChunksNeedConverted) { + // storage->getSaveFile()->convertLevelChunks(level) + } #if 0 __int64 lastStorageTickTime = System::currentTimeMillis(); @@ -590,53 +637,63 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const std::ws } } #else - __int64 lastStorageTickTime = System::currentTimeMillis(); - Pos *spawnPos = level->getSharedSpawnPos(); - app.DebugPrintf("[SRV] dim=%d spawn=(%d,%d) r=%d\n", i, spawnPos->x, spawnPos->z, r); + __int64 lastStorageTickTime = System::currentTimeMillis(); + Pos* spawnPos = level->getSharedSpawnPos(); + app.DebugPrintf("[SRV] dim=%d spawn=(%d,%d) r=%d\n", i, spawnPos->x, + spawnPos->z, r); - int twoRPlusOne = r*2 + 1; - int total = twoRPlusOne * twoRPlusOne; - int chunksDone = 0; - for (int x = -r; x <= r && running; x += 16) - { - for (int z = -r; z <= r && running; z += 16) - { - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) - { - delete spawnPos; - m_postUpdateTerminate = true; - postProcessTerminate(mcprogress); - return false; - } -// printf(">>>%d %d %d\n",i,x,z); -// __int64 now = System::currentTimeMillis(); -// if (now < lastTime) lastTime = now; -// if (now > lastTime + 1000) - { - int pos = (x + r) * twoRPlusOne + (z + 1); -// setProgress(L"Preparing spawn area", (pos) * 100 / total); - mcprogress->progressStagePercentage((pos+r) * 100 / total); -// lastTime = now; + int twoRPlusOne = r * 2 + 1; + int total = twoRPlusOne * twoRPlusOne; + int chunksDone = 0; + for (int x = -r; x <= r && running; x += 16) { + for (int z = -r; z <= r && running; z += 16) { + if (s_bServerHalted || !g_NetworkManager.IsInSession()) { + delete spawnPos; + m_postUpdateTerminate = true; + postProcessTerminate(mcprogress); + return false; + } + // printf(">>>%d %d + //%d\n",i,x,z); + // __int64 now = + // System::currentTimeMillis(); if (now < + // lastTime) lastTime = now; if (now > + // lastTime + 1000) + { + int pos = (x + r) * twoRPlusOne + (z + 1); + // setProgress(L"Preparing spawn + // area", (pos) * 100 / total); + mcprogress->progressStagePercentage((pos + r) * 100 / + total); + // lastTime = now; + } + static int count = 0; + PIXBeginNamedEvent(0, "Creating %d ", (count++) % 8); + level->cache->create((spawnPos->x + x) >> 4, + (spawnPos->z + z) >> 4, + true); // 4J - added parameter to + // disable postprocessing here + PIXEndNamedEvent(); + chunksDone++; + if (chunksDone % 50 == 0) + app.DebugPrintf("[SRV] dim=%d chunk %d/%d\n", i, + chunksDone, total); + // while (level->updateLights() && + // running) + // ; + if (System::currentTimeMillis() - lastStorageTickTime > + 50) { + CompressedTileStorage::tick(); + SparseLightStorage::tick(); + SparseDataStorage::tick(); + lastStorageTickTime = System::currentTimeMillis(); } - static int count = 0; - PIXBeginNamedEvent(0,"Creating %d ", (count++)%8); - level->cache->create((spawnPos->x + x) >> 4, (spawnPos->z + z) >> 4, true); // 4J - added parameter to disable postprocessing here - PIXEndNamedEvent(); - chunksDone++; - if(chunksDone % 50 == 0) app.DebugPrintf("[SRV] dim=%d chunk %d/%d\n", i, chunksDone, total); -// while (level->updateLights() && running) -// ; - if( System::currentTimeMillis() - lastStorageTickTime > 50 ) - { - CompressedTileStorage::tick(); - SparseLightStorage::tick(); - SparseDataStorage::tick(); - lastStorageTickTime = System::currentTimeMillis(); - } } } - // 4J - removed this as now doing the recheckGaps call when each chunk is post-processed, so can happen on things outside of the spawn area too + // 4J - removed this as now doing the recheckGaps call when each + // chunk is post-processed, so can happen on things outside of the + // spawn area too #if 0 // 4J - added this code to propagate lighting properly in the spawn area before we go sharing it with the local client or across the network for (int x = -r; x <= r && running; x += 16) @@ -650,754 +707,778 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const std::ws } #endif - delete spawnPos; + delete spawnPos; #endif } } -// printf("Main thread complete at %dms\n",System::currentTimeMillis() - startTime); + // printf("Main thread complete at %dms\n",System::currentTimeMillis() - + //startTime); - app.DebugPrintf("[SRV] All chunk loops done, waiting for postProcess\n"); - // Wait for post processing, then lighting threads, to end (post-processing may make more lighting changes) - m_postUpdateTerminate = true; + app.DebugPrintf("[SRV] All chunk loops done, waiting for postProcess\n"); + // Wait for post processing, then lighting threads, to end (post-processing + // may make more lighting changes) + m_postUpdateTerminate = true; - postProcessTerminate(mcprogress); - app.DebugPrintf("[SRV] postProcessTerminate done\n"); + postProcessTerminate(mcprogress); + app.DebugPrintf("[SRV] postProcessTerminate done\n"); + // stronghold position? + if (levels[0]->dimension->id == 0) { + app.DebugPrintf("===================================\n"); - // stronghold position? - if(levels[0]->dimension->id==0) - { + if (!levels[0]->getLevelData()->getHasStronghold()) { + int x, z; + if (app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold, &x, + &z)) { + levels[0]->getLevelData()->setXStronghold(x); + levels[0]->getLevelData()->setZStronghold(z); + levels[0]->getLevelData()->setHasStronghold(); - app.DebugPrintf("===================================\n"); + app.DebugPrintf( + "=== FOUND stronghold in terrain features list\n"); - if(!levels[0]->getLevelData()->getHasStronghold()) - { - int x,z; - if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) - { - levels[0]->getLevelData()->setXStronghold(x); - levels[0]->getLevelData()->setZStronghold(z); - levels[0]->getLevelData()->setHasStronghold(); + } else { + // can't find the stronghold position in the terrain feature + // list. Do we have to run a post-process? + app.DebugPrintf( + "=== Can't find stronghold in terrain features list\n"); + } + } else { + app.DebugPrintf("=== Leveldata has stronghold position\n"); + } + app.DebugPrintf("===================================\n"); + } - app.DebugPrintf("=== FOUND stronghold in terrain features list\n"); + // printf("Post processing complete at %dms\n",System::currentTimeMillis() + //- startTime); - } - else - { - // can't find the stronghold position in the terrain feature list. Do we have to run a post-process? - app.DebugPrintf("=== Can't find stronghold in terrain features list\n"); - } - } - else - { - app.DebugPrintf("=== Leveldata has stronghold position\n"); - } - app.DebugPrintf("===================================\n"); - } + // printf("Lighting complete at %dms\n",System::currentTimeMillis() - + //startTime); -// printf("Post processing complete at %dms\n",System::currentTimeMillis() - startTime); + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; -// printf("Lighting complete at %dms\n",System::currentTimeMillis() - startTime); + if (levels[1]->isNew) { + levels[1]->save(true, mcprogress); + } - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; - - if( levels[1]->isNew ) - { - levels[1]->save(true, mcprogress); - } + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (levels[2]->isNew) { + levels[2]->save(true, mcprogress); + } - if( levels[2]->isNew ) - { - levels[2]->save(true, mcprogress); - } + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + // 4J - added - immediately save newly created level, like single player + // game 4J Stu - We also want to immediately save the tutorial + if (levels[0]->isNew) saveGameRules(); - // 4J - added - immediately save newly created level, like single player game - // 4J Stu - We also want to immediately save the tutorial - if ( levels[0]->isNew ) - saveGameRules(); - - if( levels[0]->isNew ) - { - app.DebugPrintf("[SRV] Saving level 0...\n"); - levels[0]->save(true, mcprogress); - app.DebugPrintf("[SRV] Level 0 saved\n"); - } + if (levels[0]->isNew) { + app.DebugPrintf("[SRV] Saving level 0...\n"); + levels[0]->save(true, mcprogress); + app.DebugPrintf("[SRV] Level 0 saved\n"); + } - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; - if( levels[0]->isNew || levels[1]->isNew || levels[2]->isNew ) - { - app.DebugPrintf("[SRV] Saving to disc...\n"); - levels[0]->saveToDisc(mcprogress, false); - app.DebugPrintf("[SRV] saveToDisc done\n"); - } + if (levels[0]->isNew || levels[1]->isNew || levels[2]->isNew) { + app.DebugPrintf("[SRV] Saving to disc...\n"); + levels[0]->saveToDisc(mcprogress, false); + app.DebugPrintf("[SRV] saveToDisc done\n"); + } - if( s_bServerHalted || !g_NetworkManager.IsInSession() ) return false; + if (s_bServerHalted || !g_NetworkManager.IsInSession()) return false; -/* -* int r = 24; for (int x = -r; x <= r; x++) { -* setProgress("Preparing spawn area", (x + r) * 100 / (r + r + 1)); for (int z -* = -r; z <= r; z++) { if (!running) return; level.cache.create((level.xSpawn -* >> 4) + x, (level.zSpawn >> 4) + z); while (running && level.updateLights()) -* ; } } -*/ + /* + * int r = 24; for (int x = -r; x <= r; x++) { + * setProgress("Preparing spawn area", (x + r) * 100 / (r + r + 1)); for + * (int z = -r; z <= r; z++) { if (!running) return; + * level.cache.create((level.xSpawn + * >> 4) + x, (level.zSpawn >> 4) + z); while (running && + * level.updateLights()) ; } } + */ endProgress(); - return true; + return true; } -void MinecraftServer::setProgress(const std::wstring& status, int progress) -{ +void MinecraftServer::setProgress(const std::wstring& status, int progress) { progressStatus = status; this->progress = progress; -// logger.info(status + ": " + progress + "%"); + // logger.info(status + ": " + progress + "%"); } -void MinecraftServer::endProgress() -{ +void MinecraftServer::endProgress() { progressStatus = L""; this->progress = 0; } -void MinecraftServer::saveAllChunks() -{ -// logger.info("Saving chunks"); - for (unsigned int i = 0; i < levels.length; i++) - { - // 4J Stu - Due to the way save mounting is handled on XboxOne, we can actually save after the player has signed out. +void MinecraftServer::saveAllChunks() { + // logger.info("Saving chunks"); + for (unsigned int i = 0; i < levels.length; i++) { + // 4J Stu - Due to the way save mounting is handled on XboxOne, we can + // actually save after the player has signed out. #ifndef _XBOX_ONE - if( m_bPrimaryPlayerSignedOut ) break; + if (m_bPrimaryPlayerSignedOut) break; #endif - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - i]; - if( level ) // 4J - added check as level can be NULL if we end up in stopServer really early on due to network failure - { - level->save(true, Minecraft::GetInstance()->progressRenderer); + // 4J Stu - Save the levels in reverse order so we don't overwrite the + // level.dat with the data from the nethers leveldata. Fix for #7418 - + // Functional: Gameplay: Saving after sleeping in a bed will place + // player at nighttime when restarting. + ServerLevel* level = levels[levels.length - 1 - i]; + if (level) // 4J - added check as level can be NULL if we end up in + // stopServer really early on due to network failure + { + level->save(true, Minecraft::GetInstance()->progressRenderer); - // Only close the level storage when we have saved the last level, otherwise we need to recreate the region files - // when saving the next levels - if( i == (levels.length - 1)) - { - level->closeLevelStorage(); - } - } + // Only close the level storage when we have saved the last level, + // otherwise we need to recreate the region files when saving the + // next levels + if (i == (levels.length - 1)) { + level->closeLevelStorage(); + } + } } } // 4J-JEV: Added -void MinecraftServer::saveGameRules() -{ +void MinecraftServer::saveGameRules() { #ifndef _CONTENT_PACKAGE - if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getLevelStorage()->getSaveFile(); - FileEntry *fe = csf->createFile(ConsoleSavePath(GAME_RULE_SAVENAME)); - csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); - unsigned int length; - csf->writeFile(fe, ba.data, ba.length, &length ); + if (ba.data != NULL) { + ConsoleSaveFile* csf = + getLevel(0)->getLevelStorage()->getSaveFile(); + FileEntry* fe = + csf->createFile(ConsoleSavePath(GAME_RULE_SAVENAME)); + csf->setFilePointer(fe, 0, SaveFileSeekOrigin::Begin); + unsigned int length; + csf->writeFile(fe, ba.data, ba.length, &length); - delete [] ba.data; + delete[] ba.data; - csf->closeHandle(fe); - } - } + csf->closeHandle(fe); + } + } } -void MinecraftServer::Suspend() -{ - PIXBeginNamedEvent(0,"Suspending server"); - m_suspending = true; - // Get the frequency of the timer - LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; - float fElapsedTime = 0.0f; - QueryPerformanceFrequency( &qwTicksPerSec ); - float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; - // Save the start time - QueryPerformanceCounter( &qwTime ); - if(m_bLoaded && ProfileManager.IsFullVersion() && (!StorageManager.GetSaveDisabled())) - { - if (players != NULL) - { - players->saveAll(NULL); - } - for (unsigned int j = 0; j < levels.length; j++) - { - if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; - level->Suspend(); - } - if( !s_bServerHalted ) - { - saveGameRules(); - levels[0]->saveToDisc(NULL, true); - } - } - QueryPerformanceCounter( &qwNewTime ); +void MinecraftServer::Suspend() { + PIXBeginNamedEvent(0, "Suspending server"); + m_suspending = true; + // Get the frequency of the timer + LARGE_INTEGER qwTicksPerSec, qwTime, qwNewTime, qwDeltaTime; + float fElapsedTime = 0.0f; + QueryPerformanceFrequency(&qwTicksPerSec); + float fSecsPerTick = 1.0f / (float)qwTicksPerSec.QuadPart; + // Save the start time + QueryPerformanceCounter(&qwTime); + if (m_bLoaded && ProfileManager.IsFullVersion() && + (!StorageManager.GetSaveDisabled())) { + if (players != NULL) { + players->saveAll(NULL); + } + for (unsigned int j = 0; j < levels.length; j++) { + if (s_bServerHalted) break; + // 4J Stu - Save the levels in reverse order so we don't overwrite + // the level.dat with the data from the nethers leveldata. Fix for + // #7418 - Functional: Gameplay: Saving after sleeping in a bed will + // place player at nighttime when restarting. + ServerLevel* level = levels[levels.length - 1 - j]; + level->Suspend(); + } + if (!s_bServerHalted) { + saveGameRules(); + levels[0]->saveToDisc(NULL, true); + } + } + QueryPerformanceCounter(&qwNewTime); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - // 4J-JEV: Flush stats and call PlayerSessionExit. - for (int iPad = 0; iPad < XUSER_MAX_COUNT; iPad++) - { - if (ProfileManager.IsSignedIn(iPad)) - { - TelemetryManager->RecordPlayerSessionExit(iPad, DisconnectPacket::eDisconnect_Quitting); - } - } + // 4J-JEV: Flush stats and call PlayerSessionExit. + for (int iPad = 0; iPad < XUSER_MAX_COUNT; iPad++) { + if (ProfileManager.IsSignedIn(iPad)) { + TelemetryManager->RecordPlayerSessionExit( + iPad, DisconnectPacket::eDisconnect_Quitting); + } + } - m_suspending = false; - app.DebugPrintf("Suspend server: Elapsed time %f\n", fElapsedTime); - PIXEndNamedEvent(); + m_suspending = false; + app.DebugPrintf("Suspend server: Elapsed time %f\n", fElapsedTime); + PIXEndNamedEvent(); } -bool MinecraftServer::IsSuspending() -{ - return m_suspending; -} +bool MinecraftServer::IsSuspending() { return m_suspending; } -void MinecraftServer::stopServer() -{ - - // 4J-PB - need to halt the rendering of the data, since we're about to remove it +void MinecraftServer::stopServer() { + // 4J-PB - need to halt the rendering of the data, since we're about to + // remove it #ifdef __PS3__ - if( ShutdownManager::ShouldRun(ShutdownManager::eServerThread ) ) // This thread will take itself out if we are shutting down + if (ShutdownManager::ShouldRun( + ShutdownManager::eServerThread)) // This thread will take itself + // out if we are shutting down #endif - { - Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); - } + { + Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); + } - connection->stop(); + connection->stop(); - app.DebugPrintf("Stopping server\n"); -// logger.info("Stopping server"); - // 4J-PB - If the primary player has signed out, then don't attempt to save anything - - // also need to check for a profile switch here - primary player signs out, and another player signs in before dismissing the dash + app.DebugPrintf("Stopping server\n"); + // logger.info("Stopping server"); + // 4J-PB - If the primary player has signed out, then don't attempt to save + // anything + + // also need to check for a profile switch here - primary player signs out, + // and another player signs in before dismissing the dash #ifdef _DURANGO - // On Durango check if the primary user is signed in OR mid-sign-out - if(ProfileManager.GetUser(0, true) != nullptr) + // On Durango check if the primary user is signed in OR mid-sign-out + if (ProfileManager.GetUser(0, true) != nullptr) #else - if((m_bPrimaryPlayerSignedOut==false) && ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) + if ((m_bPrimaryPlayerSignedOut == false) && + ProfileManager.IsSignedIn(ProfileManager.GetPrimaryPad())) #endif - { + { #if defined(_XBOX_ONE) || defined(__ORBIS__) - // Always save on exit! Except if saves are disabled. - if(!saveOnExitAnswered()) m_saveOnExit = true; + // Always save on exit! Except if saves are disabled. + if (!saveOnExitAnswered()) m_saveOnExit = true; #endif - // if trial version or saving is disabled, then don't save anything - if(m_saveOnExit && ProfileManager.IsFullVersion() && (!StorageManager.GetSaveDisabled())) - { - if (players != NULL) - { - players->saveAll(Minecraft::GetInstance()->progressRenderer, true); - } - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - //for (unsigned int i = levels.length - 1; i >= 0; i--) - //{ - // ServerLevel *level = levels[i]; - // if (level != NULL) - // { - saveAllChunks(); - // } - //} + // if trial version or saving is disabled, then don't save anything + if (m_saveOnExit && ProfileManager.IsFullVersion() && + (!StorageManager.GetSaveDisabled())) { + if (players != NULL) { + players->saveAll(Minecraft::GetInstance()->progressRenderer, + true); + } + // 4J Stu - Save the levels in reverse order so we don't overwrite + // the level.dat with the data from the nethers leveldata. Fix for + // #7418 - Functional: Gameplay: Saving after sleeping in a bed will + // place player at nighttime when restarting. + // for (unsigned int i = levels.length - 1; i >= 0; i--) + //{ + // ServerLevel *level = levels[i]; + // if (level != NULL) + // { + saveAllChunks(); + // } + //} - saveGameRules(); - app.m_gameRules.unloadCurrentGameRules(); - if( levels[0] != NULL ) // This can be null if stopServer happens very quickly due to network error - { - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, false); - } - } - } - // reset the primary player signout flag - m_bPrimaryPlayerSignedOut=false; - s_bServerHalted = false; + saveGameRules(); + app.m_gameRules.unloadCurrentGameRules(); + if (levels[0] != NULL) // This can be null if stopServer happens + // very quickly due to network error + { + levels[0]->saveToDisc( + Minecraft::GetInstance()->progressRenderer, false); + } + } + } + // reset the primary player signout flag + m_bPrimaryPlayerSignedOut = false; + s_bServerHalted = false; - // On Durango/Orbis, we need to wait for all the asynchronous saving processes to complete before destroying the levels, as that will ultimately delete - // the directory level storage & therefore the ConsoleSaveSplit instance, which needs to be around until all the sub files have completed saving. + // On Durango/Orbis, we need to wait for all the asynchronous saving + // processes to complete before destroying the levels, as that will + // ultimately delete the directory level storage & therefore the + // ConsoleSaveSplit instance, which needs to be around until all the sub + // files have completed saving. #if defined(_DURANGO) || defined(__ORBIS__) || defined(__PSVITA__) - while(StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle ) - { - Sleep(10); - } + while (StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle) { + Sleep(10); + } #endif - // 4J-PB remove the server levels - unsigned int iServerLevelC=levels.length; - for (unsigned int i = 0; i < iServerLevelC; i++) - { - if(levels[i]!=NULL) - { - delete levels[i]; - levels[i] = NULL; - } - } + // 4J-PB remove the server levels + unsigned int iServerLevelC = levels.length; + for (unsigned int i = 0; i < iServerLevelC; i++) { + if (levels[i] != NULL) { + delete levels[i]; + levels[i] = NULL; + } + } #if defined(__PS3__) || defined(__ORBIS__) - // Clear the update flags as it's possible they could be out of sync, causing a crash when starting a new world after the first new level ticks - // Fix for PS3 #1538 - [IN GAME] If the user 'Exit without saving' from inside the Nether or The End, the title can hang when loading back into the save. + // Clear the update flags as it's possible they could be out of sync, + // causing a crash when starting a new world after the first new level ticks + // Fix for PS3 #1538 - [IN GAME] If the user 'Exit without saving' from + // inside the Nether or The End, the title can hang when loading back into + // the save. #endif - delete connection; - connection = NULL; - delete players; - players = NULL; - delete settings; - settings = NULL; + delete connection; + connection = NULL; + delete players; + players = NULL; + delete settings; + settings = NULL; - g_NetworkManager.ServerStopped(); + g_NetworkManager.ServerStopped(); } -void MinecraftServer::halt() -{ - running = false; +void MinecraftServer::halt() { running = false; } + +void MinecraftServer::setMaxBuildHeight(int maxBuildHeight) { + this->maxBuildHeight = maxBuildHeight; } -void MinecraftServer::setMaxBuildHeight(int maxBuildHeight) -{ - this->maxBuildHeight = maxBuildHeight; +int MinecraftServer::getMaxBuildHeight() { return maxBuildHeight; } + +PlayerList* MinecraftServer::getPlayers() { return players; } + +void MinecraftServer::setPlayers(PlayerList* players) { + this->players = players; } -int MinecraftServer::getMaxBuildHeight() -{ - return maxBuildHeight; +ServerConnection* MinecraftServer::getConnection() { return connection; } + +bool MinecraftServer::isAnimals() { return animals; } + +void MinecraftServer::setAnimals(bool animals) { this->animals = animals; } + +bool MinecraftServer::isNpcsEnabled() { return npcs; } + +void MinecraftServer::setNpcsEnabled(bool npcs) { this->npcs = npcs; } + +bool MinecraftServer::isPvpAllowed() { return pvp; } + +void MinecraftServer::setPvpAllowed(bool pvp) { this->pvp = pvp; } + +bool MinecraftServer::isFlightAllowed() { return allowFlight; } + +void MinecraftServer::setFlightAllowed(bool allowFlight) { + this->allowFlight = allowFlight; } -PlayerList *MinecraftServer::getPlayers() -{ - return players; +bool MinecraftServer::isNetherEnabled() { + return true; // settings.getBoolean("allow-nether", true); } -void MinecraftServer::setPlayers(PlayerList *players) -{ - this->players = players; -} +bool MinecraftServer::isHardcore() { return false; } -ServerConnection *MinecraftServer::getConnection() -{ - return connection; -} - -bool MinecraftServer::isAnimals() -{ - return animals; -} - -void MinecraftServer::setAnimals(bool animals) -{ - this->animals = animals; -} - -bool MinecraftServer::isNpcsEnabled() -{ - return npcs; -} - -void MinecraftServer::setNpcsEnabled(bool npcs) -{ - this->npcs = npcs; -} - -bool MinecraftServer::isPvpAllowed() -{ - return pvp; -} - -void MinecraftServer::setPvpAllowed(bool pvp) -{ - this->pvp = pvp; -} - -bool MinecraftServer::isFlightAllowed() -{ - return allowFlight; -} - -void MinecraftServer::setFlightAllowed(bool allowFlight) -{ - this->allowFlight = allowFlight; -} - -bool MinecraftServer::isNetherEnabled() -{ - return true; //settings.getBoolean("allow-nether", true); -} - -bool MinecraftServer::isHardcore() -{ - return false; -} - -CommandDispatcher *MinecraftServer::getCommandDispatcher() -{ - return commandDispatcher; +CommandDispatcher* MinecraftServer::getCommandDispatcher() { + return commandDispatcher; } extern int c0a, c0b, c1a, c1b, c1c, c2a, c2b; -void MinecraftServer::run(__int64 seed, void *lpParameter) -{ - NetworkGameInitData *initData = NULL; - std::uint32_t initSettings = 0; - bool findSeed = false; - if(lpParameter != NULL) - { - initData = (NetworkGameInitData *)lpParameter; - initSettings = app.GetGameHostOption(eGameHostOption_All); - findSeed = initData->findSeed; - m_texturePackId = initData->texturePackId; - } -// try { // 4J - removed try/catch/finally - if (initServer(seed, initData, initSettings,findSeed)) - { - ServerLevel *levelNormalDimension = levels[0]; - // 4J-PB - Set the Stronghold position in the leveldata if there isn't one in there - Minecraft *pMinecraft = Minecraft::GetInstance(); - LevelData *pLevelData=levelNormalDimension->getLevelData(); +void MinecraftServer::run(__int64 seed, void* lpParameter) { + NetworkGameInitData* initData = NULL; + std::uint32_t initSettings = 0; + bool findSeed = false; + if (lpParameter != NULL) { + initData = (NetworkGameInitData*)lpParameter; + initSettings = app.GetGameHostOption(eGameHostOption_All); + findSeed = initData->findSeed; + m_texturePackId = initData->texturePackId; + } + // try { // 4J - removed try/catch/finally + if (initServer(seed, initData, initSettings, findSeed)) { + ServerLevel* levelNormalDimension = levels[0]; + // 4J-PB - Set the Stronghold position in the leveldata if there isn't + // one in there + Minecraft* pMinecraft = Minecraft::GetInstance(); + LevelData* pLevelData = levelNormalDimension->getLevelData(); - if(pLevelData && pLevelData->getHasStronghold()==false) - { - int x,z; - if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) - { - pLevelData->setXStronghold(x); - pLevelData->setZStronghold(z); - pLevelData->setHasStronghold(); - } - } + if (pLevelData && pLevelData->getHasStronghold() == false) { + int x, z; + if (app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold, &x, + &z)) { + pLevelData->setXStronghold(x); + pLevelData->setZStronghold(z); + pLevelData->setHasStronghold(); + } + } __int64 lastTime = System::currentTimeMillis(); __int64 unprocessedTime = 0; - while (running && !s_bServerHalted) - { + while (running && !s_bServerHalted) { __int64 now = System::currentTimeMillis(); - // 4J Stu - When we pause the server, we don't want to count that as time passed - // 4J Stu - TU-1 hotifx - Remove this line. We want to make sure that we tick connections at the proper rate when paused - //Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost - //if(m_isServerPaused) lastTime = now; + // 4J Stu - When we pause the server, we don't want to count that as + // time passed 4J Stu - TU-1 hotifx - Remove this line. We want to + // make sure that we tick connections at the proper rate when paused + // Fix for #13191 - The host of a game can get a message informing + // them that the connection to the server has been lost + // if(m_isServerPaused) lastTime = now; __int64 passedTime = now - lastTime; - if (passedTime > MS_PER_TICK * 40) - { -// logger.warning("Can't keep up! Did the system time change, or is the server overloaded?"); + if (passedTime > MS_PER_TICK * 40) { + // logger.warning("Can't keep up! Did the system + // time change, or is the server overloaded?"); passedTime = MS_PER_TICK * 40; } - if (passedTime < 0) - { -// logger.warning("Time ran backwards! Did the system time change?"); + if (passedTime < 0) { + // logger.warning("Time ran backwards! Did the + // system time change?"); passedTime = 0; } unprocessedTime += passedTime; lastTime = now; - // 4J Added ability to pause the server - if( !m_isServerPaused ) - { - bool didTick = false; - if (levels[0]->allPlayersAreSleeping()) - { - tick(); - unprocessedTime = 0; - } - else - { -// int tickcount = 0; -// __int64 beforeall = System::currentTimeMillis(); - while (unprocessedTime > MS_PER_TICK) - { - unprocessedTime -= MS_PER_TICK; -// __int64 before = System::currentTimeMillis(); - tick(); -// __int64 after = System::currentTimeMillis(); -// PIXReportCounter(L"Server time",(float)(after-before)); + // 4J Added ability to pause the server + if (!m_isServerPaused) { + bool didTick = false; + if (levels[0]->allPlayersAreSleeping()) { + tick(); + unprocessedTime = 0; + } else { + // int tickcount = 0; + // __int64 beforeall = + //System::currentTimeMillis(); + while (unprocessedTime > MS_PER_TICK) { + unprocessedTime -= MS_PER_TICK; + // __int64 + //before = System::currentTimeMillis(); + tick(); + // __int64 + //after = System::currentTimeMillis(); + // PIXReportCounter(L"Server + //time",(float)(after-before)); - // 4J Ensure that the slow queue owner keeps cycling if it's not been used in a while - int time = GetTickCount(); - if( ( s_slowQueuePacketSent ) || ( (time - s_slowQueueLastTime) > ( 2 * MINECRAFT_SERVER_SLOW_QUEUE_DELAY ) ) ) - { -// app.DebugPrintf("Considering cycling: (%d) %d - %d -> %d > %d\n",s_slowQueuePacketSent, time, s_slowQueueLastTime, (time - s_slowQueueLastTime), (2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); - MinecraftServer::cycleSlowQueueIndex(); - s_slowQueuePacketSent = false; - s_slowQueueLastTime = time; - } -// else -// { -// app.DebugPrintf("Not considering cycling: %d - %d -> %d > %d\n",time, s_slowQueueLastTime, (time - s_slowQueueLastTime), (2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); -// } - } -// __int64 afterall = System::currentTimeMillis(); -// PIXReportCounter(L"Server time all",(float)(afterall-beforeall)); -// PIXReportCounter(L"Server ticks",(float)tickcount); - } - } - else - { - // 4J Stu - TU1-hotfix - //Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost - // The connections should tick at the same frequency even when paused - while (unprocessedTime > MS_PER_TICK) - { - unprocessedTime -= MS_PER_TICK; - // Keep ticking the connections to stop them timing out - connection->tick(); - } - } - if(MinecraftServer::setTimeAtEndOfTick) - { - MinecraftServer::setTimeAtEndOfTick = false; - for (unsigned int i = 0; i < levels.length; i++) - { -// if (i == 0 || settings->getBoolean(L"allow-nether", true)) // 4J removed - we always have nether - { - ServerLevel *level = levels[i]; - level->setTime( MinecraftServer::setTime ); - level->setOverrideTimeOfDay( -1 ); - } - } - } - if(MinecraftServer::setTimeOfDayAtEndOfTick) - { - MinecraftServer::setTimeOfDayAtEndOfTick = false; - for (unsigned int i = 0; i < levels.length; i++) - { - if (i == 0 || settings->getBoolean(L"allow-nether", true)) - { - ServerLevel *level = levels[i]; - //level->setTime( MinecraftServer::setTime ); - level->setOverrideTimeOfDay( MinecraftServer::setTimeOfDay ); - } - } - } + // 4J Ensure that the slow queue owner keeps cycling if + // it's not been used in a while + int time = GetTickCount(); + if ((s_slowQueuePacketSent) || + ((time - s_slowQueueLastTime) > + (2 * MINECRAFT_SERVER_SLOW_QUEUE_DELAY))) { + // app.DebugPrintf("Considering + //cycling: (%d) %d - %d -> %d > + //%d\n",s_slowQueuePacketSent, time, + //s_slowQueueLastTime, (time - s_slowQueueLastTime), + //(2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); + MinecraftServer::cycleSlowQueueIndex(); + s_slowQueuePacketSent = false; + s_slowQueueLastTime = time; + } + // else + // { + // app.DebugPrintf("Not + //considering cycling: %d - %d -> %d > %d\n",time, + //s_slowQueueLastTime, (time - s_slowQueueLastTime), + //(2*MINECRAFT_SERVER_SLOW_QUEUE_DELAY)); + // } + } + // __int64 afterall = + //System::currentTimeMillis(); PIXReportCounter(L"Server + //time all",(float)(afterall-beforeall)); + // PIXReportCounter(L"Server + //ticks",(float)tickcount); + } + } else { + // 4J Stu - TU1-hotfix + // Fix for #13191 - The host of a game can get a message + // informing them that the connection to the server has been + // lost + // The connections should tick at the same frequency even when + // paused + while (unprocessedTime > MS_PER_TICK) { + unprocessedTime -= MS_PER_TICK; + // Keep ticking the connections to stop them timing out + connection->tick(); + } + } + if (MinecraftServer::setTimeAtEndOfTick) { + MinecraftServer::setTimeAtEndOfTick = false; + for (unsigned int i = 0; i < levels.length; i++) { + // if (i == 0 || + //settings->getBoolean(L"allow-nether", true)) + //// 4J removed - we always have nether + { + ServerLevel* level = levels[i]; + level->setTime(MinecraftServer::setTime); + level->setOverrideTimeOfDay(-1); + } + } + } + if (MinecraftServer::setTimeOfDayAtEndOfTick) { + MinecraftServer::setTimeOfDayAtEndOfTick = false; + for (unsigned int i = 0; i < levels.length; i++) { + if (i == 0 || settings->getBoolean(L"allow-nether", true)) { + ServerLevel* level = levels[i]; + // level->setTime( MinecraftServer::setTime ); + level->setOverrideTimeOfDay( + MinecraftServer::setTimeOfDay); + } + } + } - // Process delayed actions - eXuiServerAction eAction; - void *param; - for(int i=0;isaveAll(NULL); - } + if (players != NULL) { + players->saveAll(NULL); + } - for (unsigned int j = 0; j < levels.length; j++) - { - if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; - PIXBeginNamedEvent(0, "Saving level %d",levels.length - 1 - j); - level->save(false, NULL, true); - PIXEndNamedEvent(); - } - if( !s_bServerHalted ) - { - PIXBeginNamedEvent(0,"Saving game rules"); - saveGameRules(); - PIXEndNamedEvent(); + for (unsigned int j = 0; j < levels.length; j++) { + if (s_bServerHalted) break; + // 4J Stu - Save the levels in reverse order so we + // don't overwrite the level.dat with the data from + // the nethers leveldata. Fix for #7418 - + // Functional: Gameplay: Saving after sleeping in a + // bed will place player at nighttime when + // restarting. + ServerLevel* level = levels[levels.length - 1 - j]; + PIXBeginNamedEvent(0, "Saving level %d", + levels.length - 1 - j); + level->save(false, NULL, true); + PIXEndNamedEvent(); + } + if (!s_bServerHalted) { + PIXBeginNamedEvent(0, "Saving game rules"); + saveGameRules(); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Save to disc"); - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, true); - PIXEndNamedEvent(); - } - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Save to disc"); + levels[0]->saveToDisc( + Minecraft::GetInstance()->progressRenderer, + true); + PIXEndNamedEvent(); + } + PIXEndNamedEvent(); - QueryPerformanceCounter( &qwNewTime ); - qwDeltaTime.QuadPart = qwNewTime.QuadPart - qwTime.QuadPart; - fElapsedTime = fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); - app.DebugPrintf("Autosave: Elapsed time %f\n", fElapsedTime); - } - break; + QueryPerformanceCounter(&qwNewTime); + qwDeltaTime.QuadPart = + qwNewTime.QuadPart - qwTime.QuadPart; + fElapsedTime = + fSecsPerTick * ((FLOAT)(qwDeltaTime.QuadPart)); + app.DebugPrintf("Autosave: Elapsed time %f\n", + fElapsedTime); + } break; #endif - case eXuiServerAction_SaveGame: - app.EnterSaveNotificationSection(); - if (players != NULL) - { - players->saveAll(Minecraft::GetInstance()->progressRenderer); - } - - players->broadcastAll( std::shared_ptr( new UpdateProgressPacket(20) ) ); + case eXuiServerAction_SaveGame: + app.EnterSaveNotificationSection(); + if (players != NULL) { + players->saveAll( + Minecraft::GetInstance()->progressRenderer); + } - for (unsigned int j = 0; j < levels.length; j++) - { - if( s_bServerHalted ) break; - // 4J Stu - Save the levels in reverse order so we don't overwrite the level.dat - // with the data from the nethers leveldata. - // Fix for #7418 - Functional: Gameplay: Saving after sleeping in a bed will place player at nighttime when restarting. - ServerLevel *level = levels[levels.length - 1 - j]; - level->save(true, Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); - - players->broadcastAll( std::shared_ptr( new UpdateProgressPacket(33 + (j*33) ) ) ); - } - if( !s_bServerHalted ) - { - saveGameRules(); + players->broadcastAll( + std::shared_ptr( + new UpdateProgressPacket(20))); - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); - } - app.LeaveSaveNotificationSection(); - break; - case eXuiServerAction_DropItem: - // Find the player, and drop the id at their feet - { - std::shared_ptr player = players->players.at(0); - size_t id = (size_t) param; - player->drop( std::shared_ptr( new ItemInstance(id, 1, 0 ) ) ); - } - break; - case eXuiServerAction_SpawnMob: - { - std::shared_ptr player = players->players.at(0); - eINSTANCEOF factory = (eINSTANCEOF)((size_t)param); - std::shared_ptr mob = std::dynamic_pointer_cast(EntityIO::newByEnumType(factory,player->level )); - mob->moveTo(player->x+1, player->y, player->z+1, player->level->random->nextFloat() * 360, 0); - mob->setDespawnProtected(); // 4J added, default to being protected against despawning (has to be done after initial position is set) - player->level->addEntity(mob); - } - break; - case eXuiServerAction_PauseServer: - m_isServerPaused = ( (size_t) param == TRUE ); - if( m_isServerPaused ) - { - m_serverPausedEvent->Set(); - } - break; - case eXuiServerAction_ToggleRain: - { - bool isRaining = levels[0]->getLevelData()->isRaining(); - levels[0]->getLevelData()->setRaining(!isRaining); - levels[0]->getLevelData()->setRainTime(levels[0]->random->nextInt(Level::TICKS_PER_DAY * 7) + Level::TICKS_PER_DAY / 2); - } - break; - case eXuiServerAction_ToggleThunder: - { - bool isThundering = levels[0]->getLevelData()->isThundering(); - levels[0]->getLevelData()->setThundering(!isThundering); - levels[0]->getLevelData()->setThunderTime(levels[0]->random->nextInt(Level::TICKS_PER_DAY * 7) + Level::TICKS_PER_DAY / 2); - } - break; - case eXuiServerAction_ServerSettingChanged_Gamertags: - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_OPTIONS, app.GetGameHostOption(eGameHostOption_Gamertags)) ) ); - break; - case eXuiServerAction_ServerSettingChanged_BedrockFog: - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, app.GetGameHostOption(eGameHostOption_All)) ) ); - break; + for (unsigned int j = 0; j < levels.length; j++) { + if (s_bServerHalted) break; + // 4J Stu - Save the levels in reverse order so we + // don't overwrite the level.dat with the data from + // the nethers leveldata. Fix for #7418 - + // Functional: Gameplay: Saving after sleeping in a + // bed will place player at nighttime when + // restarting. + ServerLevel* level = levels[levels.length - 1 - j]; + level->save( + true, + Minecraft::GetInstance()->progressRenderer, + (eAction == eXuiServerAction_AutoSaveGame)); - case eXuiServerAction_ServerSettingChanged_Difficulty: - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_DIFFICULTY, Minecraft::GetInstance()->options->difficulty) ) ); - break; - case eXuiServerAction_ExportSchematic: + players->broadcastAll( + std::shared_ptr( + new UpdateProgressPacket(33 + (j * 33)))); + } + if (!s_bServerHalted) { + saveGameRules(); + + levels[0]->saveToDisc( + Minecraft::GetInstance()->progressRenderer, + (eAction == eXuiServerAction_AutoSaveGame)); + } + app.LeaveSaveNotificationSection(); + break; + case eXuiServerAction_DropItem: + // Find the player, and drop the id at their feet + { + std::shared_ptr player = + players->players.at(0); + size_t id = (size_t)param; + player->drop(std::shared_ptr( + new ItemInstance(id, 1, 0))); + } + break; + case eXuiServerAction_SpawnMob: { + std::shared_ptr player = + players->players.at(0); + eINSTANCEOF factory = (eINSTANCEOF)((size_t)param); + std::shared_ptr mob = + std::dynamic_pointer_cast( + EntityIO::newByEnumType(factory, + player->level)); + mob->moveTo(player->x + 1, player->y, player->z + 1, + player->level->random->nextFloat() * 360, + 0); + mob->setDespawnProtected(); // 4J added, default to + // being protected against + // despawning (has to be + // done after initial + // position is set) + player->level->addEntity(mob); + } break; + case eXuiServerAction_PauseServer: + m_isServerPaused = ((size_t)param == TRUE); + if (m_isServerPaused) { + m_serverPausedEvent->Set(); + } + break; + case eXuiServerAction_ToggleRain: { + bool isRaining = levels[0]->getLevelData()->isRaining(); + levels[0]->getLevelData()->setRaining(!isRaining); + levels[0]->getLevelData()->setRainTime( + levels[0]->random->nextInt(Level::TICKS_PER_DAY * + 7) + + Level::TICKS_PER_DAY / 2); + } break; + case eXuiServerAction_ToggleThunder: { + bool isThundering = + levels[0]->getLevelData()->isThundering(); + levels[0]->getLevelData()->setThundering(!isThundering); + levels[0]->getLevelData()->setThunderTime( + levels[0]->random->nextInt(Level::TICKS_PER_DAY * + 7) + + Level::TICKS_PER_DAY / 2); + } break; + case eXuiServerAction_ServerSettingChanged_Gamertags: + players->broadcastAll( + std::shared_ptr( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_OPTIONS, + app.GetGameHostOption( + eGameHostOption_Gamertags)))); + break; + case eXuiServerAction_ServerSettingChanged_BedrockFog: + players->broadcastAll( + std::shared_ptr( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket:: + HOST_IN_GAME_SETTINGS, + app.GetGameHostOption( + eGameHostOption_All)))); + break; + + case eXuiServerAction_ServerSettingChanged_Difficulty: + players->broadcastAll(std::shared_ptr< + ServerSettingsChangedPacket>( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_DIFFICULTY, + Minecraft::GetInstance() + ->options->difficulty))); + break; + case eXuiServerAction_ExportSchematic: #ifndef _CONTENT_PACKAGE - app.EnterSaveNotificationSection(); - - //players->broadcastAll( std::shared_ptr( new UpdateProgressPacket(20) ) ); + app.EnterSaveNotificationSection(); - if( !s_bServerHalted ) - { - ConsoleSchematicFile::XboxSchematicInitParam *initData = (ConsoleSchematicFile::XboxSchematicInitParam *)param; + // players->broadcastAll( + // std::shared_ptr( new + // UpdateProgressPacket(20) ) ); + + if (!s_bServerHalted) { + ConsoleSchematicFile::XboxSchematicInitParam* + initData = (ConsoleSchematicFile:: + XboxSchematicInitParam*)param; #ifdef _XBOX - File targetFileDir(File::pathRoot + File::pathSeparator + L"Schematics"); + File targetFileDir(File::pathRoot + + File::pathSeparator + + L"Schematics"); #else - File targetFileDir(L"Schematics"); + File targetFileDir(L"Schematics"); #endif - if(!targetFileDir.exists()) targetFileDir.mkdir(); + if (!targetFileDir.exists()) targetFileDir.mkdir(); - wchar_t filename[128]; - swprintf(filename,128,L"%ls%dx%dx%d.sch",initData->name,(initData->endX - initData->startX + 1), (initData->endY - initData->startY + 1), (initData->endZ - initData->startZ + 1)); + wchar_t filename[128]; + swprintf(filename, 128, L"%ls%dx%dx%d.sch", + initData->name, + (initData->endX - initData->startX + 1), + (initData->endY - initData->startY + 1), + (initData->endZ - initData->startZ + 1)); - File dataFile = File( targetFileDir, std::wstring(filename) ); - if(dataFile.exists()) dataFile._delete(); - FileOutputStream fos = FileOutputStream(dataFile); - DataOutputStream dos = DataOutputStream(&fos); - ConsoleSchematicFile::generateSchematicFile(&dos, levels[0], initData->startX, initData->startY, initData->startZ, initData->endX, initData->endY, initData->endZ, initData->bSaveMobs, initData->compressionType); - dos.close(); + File dataFile = + File(targetFileDir, std::wstring(filename)); + if (dataFile.exists()) dataFile._delete(); + FileOutputStream fos = FileOutputStream(dataFile); + DataOutputStream dos = DataOutputStream(&fos); + ConsoleSchematicFile::generateSchematicFile( + &dos, levels[0], initData->startX, + initData->startY, initData->startZ, + initData->endX, initData->endY, initData->endZ, + initData->bSaveMobs, initData->compressionType); + dos.close(); - delete initData; - } - app.LeaveSaveNotificationSection(); + delete initData; + } + app.LeaveSaveNotificationSection(); #endif - break; - case eXuiServerAction_SetCameraLocation: + break; + case eXuiServerAction_SetCameraLocation: #ifndef _CONTENT_PACKAGE - { - DebugSetCameraPosition *pos = (DebugSetCameraPosition *)param; + { + DebugSetCameraPosition* pos = + (DebugSetCameraPosition*)param; - app.DebugPrintf( "DEBUG: Player=%i\n", pos->player ); - app.DebugPrintf( "DEBUG: Teleporting to pos=(%f.2, %f.2, %f.2), looking at=(%f.2,%f.2)\n", - pos->m_camX, pos->m_camY, pos->m_camZ, - pos->m_yRot, pos->m_elev - ); + app.DebugPrintf("DEBUG: Player=%i\n", pos->player); + app.DebugPrintf( + "DEBUG: Teleporting to pos=(%f.2, %f.2, %f.2), " + "looking at=(%f.2,%f.2)\n", + pos->m_camX, pos->m_camY, pos->m_camZ, pos->m_yRot, + pos->m_elev); - std::shared_ptr player = players->players.at(pos->player); - player->debug_setPosition( pos->m_camX, pos->m_camY, pos->m_camZ, - pos->m_yRot, pos->m_elev ); + std::shared_ptr player = + players->players.at(pos->player); + player->debug_setPosition(pos->m_camX, pos->m_camY, + pos->m_camZ, pos->m_yRot, + pos->m_elev); - // Doesn't work - //player->setYHeadRot(pos->m_yRot); - //player->absMoveTo(pos->m_camX, pos->m_camY, pos->m_camZ, pos->m_yRot, pos->m_elev); - } + // Doesn't work + // player->setYHeadRot(pos->m_yRot); + // player->absMoveTo(pos->m_camX, pos->m_camY, + // pos->m_camZ, pos->m_yRot, pos->m_elev); + } #endif - break; - default: - break; - } - - app.SetXuiServerAction(i,eXuiServerAction_Idle); - } + break; + default: + break; + } - Sleep(1); + app.SetXuiServerAction(i, eXuiServerAction_Idle); + } + + Sleep(1); } } - //else - //{ - // while (running) - // { + // else + //{ + // while (running) + // { // handleConsoleInputs(); - // Sleep(10); + // Sleep(10); // } //} #if 0 @@ -1424,279 +1505,284 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) } #endif - // 4J Stu - Stop the server when the loops complete, as the finally would do - stopServer(); - stopped = true; + // 4J Stu - Stop the server when the loops complete, as the finally would do + stopServer(); + stopped = true; } -void MinecraftServer::broadcastStartSavingPacket() -{ - players->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::START_SAVING, 0) ) );; +void MinecraftServer::broadcastStartSavingPacket() { + players->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::START_SAVING, 0))); + ; } -void MinecraftServer::broadcastStopSavingPacket() -{ - if( !s_bServerHalted ) - { - players->broadcastAll( std::shared_ptr( new GameEventPacket(GameEventPacket::STOP_SAVING, 0) ) );; - } +void MinecraftServer::broadcastStopSavingPacket() { + if (!s_bServerHalted) { + players->broadcastAll(std::shared_ptr( + new GameEventPacket(GameEventPacket::STOP_SAVING, 0))); + ; + } } -void MinecraftServer::tick() -{ +void MinecraftServer::tick() { std::vector toRemove; - for (AUTO_VAR(it, ironTimers.begin()); it != ironTimers.end(); it++ ) - { + for (AUTO_VAR(it, ironTimers.begin()); it != ironTimers.end(); it++) { int t = it->second; - if (t > 0) - { + if (t > 0) { ironTimers[it->first] = t - 1; - } - else - { + } else { toRemove.push_back(it->first); } } - for (unsigned int i = 0; i < toRemove.size(); i++) - { + for (unsigned int i = 0; i < toRemove.size(); i++) { ironTimers.erase(toRemove[i]); } AABB::resetPool(); Vec3::resetPool(); - + tickCount++; - // 4J We need to update client difficulty levels based on the servers - Minecraft *pMinecraft = Minecraft::GetInstance(); - // 4J-PB - sending this on the host changing the difficulty in the menus -/* if(m_lastSentDifficulty != pMinecraft->options->difficulty) - { - m_lastSentDifficulty = pMinecraft->options->difficulty; - players->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_DIFFICULTY, pMinecraft->options->difficulty) ) ); - }*/ + // 4J We need to update client difficulty levels based on the servers + Minecraft* pMinecraft = Minecraft::GetInstance(); + // 4J-PB - sending this on the host changing the difficulty in the menus + /* if(m_lastSentDifficulty != pMinecraft->options->difficulty) + { + m_lastSentDifficulty = pMinecraft->options->difficulty; + players->broadcastAll( + std::shared_ptr( new + ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_DIFFICULTY, + pMinecraft->options->difficulty) ) ); + }*/ - for (unsigned int i = 0; i < levels.length; i++) - { -// if (i == 0 || settings->getBoolean(L"allow-nether", true)) // 4J removed - we always have nether - { - ServerLevel *level = levels[i]; + for (unsigned int i = 0; i < levels.length; i++) { + // if (i == 0 || settings->getBoolean(L"allow-nether", true)) + // // 4J removed - we always have nether + { + ServerLevel* level = levels[i]; - // 4J Stu - We set the levels difficulty based on the minecraft options - level->difficulty = app.GetGameHostOption(eGameHostOption_Difficulty); //pMinecraft->options->difficulty; + // 4J Stu - We set the levels difficulty based on the minecraft + // options + level->difficulty = app.GetGameHostOption( + eGameHostOption_Difficulty); // pMinecraft->options->difficulty; #if DEBUG_SERVER_DONT_SPAWN_MOBS - level->setSpawnSettings(false, false); + level->setSpawnSettings(false, false); #else - level->setSpawnSettings(level->difficulty > 0 && !Minecraft::GetInstance()->isTutorial(), animals); + level->setSpawnSettings(level->difficulty > 0 && + !Minecraft::GetInstance()->isTutorial(), + animals); #endif - if (tickCount % 20 == 0) - { - players->broadcastAll( std::shared_ptr( new SetTimePacket(level->getTime() ) ), level->dimension->id); + if (tickCount % 20 == 0) { + players->broadcastAll(std::shared_ptr( + new SetTimePacket(level->getTime())), + level->dimension->id); } -// #ifndef __PS3__ - static __int64 stc = 0; - __int64 st0 = System::currentTimeMillis(); - PIXBeginNamedEvent(0,"Level tick %d",i); - ((Level *)level)->tick(); - __int64 st1 = System::currentTimeMillis(); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Update lights %d",i); - // 4J - used to be in a while loop, but we don't want the server locking up for a big chunk of time (could end up trying to process 1,000,000 lights...) - // Instead call this once, which will try and process up to 2000 lights per tick -// printf("lights: %d\n",level->getLightsToUpdate()); - while(level->updateLights() ) - ; - __int64 st2 = System::currentTimeMillis(); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Entity tick %d",i); - // 4J added to stop ticking entities in levels when players are not in those levels. - // Note: now changed so that we also tick if there are entities to be removed, as this also happens as a result of calling tickEntities. If we don't do this, then the - // entities get removed at the first point that there is a player count in the level - this has been causing a problem when going from normal dimension -> nether -> normal, - // as the player is getting flagged as to be removed (from the normal dimension) when going to the nether, but Actually gets removed only when it returns - if( ( players->getPlayerCount(level) > 0) || ( level->hasEntitiesToRemove() ) ) - { + // #ifndef __PS3__ + static __int64 stc = 0; + __int64 st0 = System::currentTimeMillis(); + PIXBeginNamedEvent(0, "Level tick %d", i); + ((Level*)level)->tick(); + __int64 st1 = System::currentTimeMillis(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Update lights %d", i); + // 4J - used to be in a while loop, but we don't want the server + // locking up for a big chunk of time (could end up trying to + // process 1,000,000 lights...) Instead call this once, which will + // try and process up to 2000 lights per tick + // printf("lights: + //%d\n",level->getLightsToUpdate()); + while (level->updateLights()); + __int64 st2 = System::currentTimeMillis(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Entity tick %d", i); + // 4J added to stop ticking entities in levels when players are not + // in those levels. Note: now changed so that we also tick if there + // are entities to be removed, as this also happens as a result of + // calling tickEntities. If we don't do this, then the entities get + // removed at the first point that there is a player count in the + // level - this has been causing a problem when going from normal + // dimension -> nether -> normal, as the player is getting flagged + // as to be removed (from the normal dimension) when going to the + // nether, but Actually gets removed only when it returns + if ((players->getPlayerCount(level) > 0) || + (level->hasEntitiesToRemove())) { #ifdef __PSVITA__ - // AP - the PlayerList->viewDistance initially starts out at 3 to make starting a level speedy - // the problem with this is that spawned monsters are always generated on the edge of the known map - // which means they wont process (unless they are surrounded by 2 visible chunks). This means - // they wont checkDespawn so they are NEVER removed which results in monsters not spawning. - // This bit of hack will modify the view distance once the level is up and running. - int newViewDistance = 5; - level->getServer()->getPlayers()->setViewDistance(newViewDistance); - level->getTracker()->updateMaxRange(); - level->getChunkMap()->setRadius(level->getServer()->getPlayers()->getViewDistance()); + // AP - the PlayerList->viewDistance initially starts out at 3 + // to make starting a level speedy the problem with this is that + // spawned monsters are always generated on the edge of the + // known map which means they wont process (unless they are + // surrounded by 2 visible chunks). This means they wont + // checkDespawn so they are NEVER removed which results in + // monsters not spawning. This bit of hack will modify the view + // distance once the level is up and running. + int newViewDistance = 5; + level->getServer()->getPlayers()->setViewDistance( + newViewDistance); + level->getTracker()->updateMaxRange(); + level->getChunkMap()->setRadius( + level->getServer()->getPlayers()->getViewDistance()); #endif - level->tickEntities(); - } - PIXEndNamedEvent(); + level->tickEntities(); + } + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Entity tracker tick"); - level->getTracker()->tick(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Entity tracker tick"); + level->getTracker()->tick(); + PIXEndNamedEvent(); - __int64 st3 = System::currentTimeMillis(); -// printf(">>>>>>>>>>>>>>>>>>>>>> Tick %d %d %d : %d\n", st1 - st0, st2 - st1, st3 - st2, st0 - stc ); - stc = st0; -// #endif// __PS3__ + __int64 st3 = System::currentTimeMillis(); + // printf(">>>>>>>>>>>>>>>>>>>>>> Tick %d %d %d : + //%d\n", st1 - st0, st2 - st1, st3 - st2, st0 - stc ); + stc = st0; + // #endif// __PS3__ } } - Entity::tickExtraWandering(); // 4J added + Entity::tickExtraWandering(); // 4J added - PIXBeginNamedEvent(0,"Connection tick"); + PIXBeginNamedEvent(0, "Connection tick"); connection->tick(); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Players tick"); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Players tick"); players->tick(); - PIXEndNamedEvent(); + PIXEndNamedEvent(); - // 4J - removed + // 4J - removed #if 0 for (int i = 0; i < tickables.size(); i++) { tickables.get(i)-tick(); } #endif -// try { // 4J - removed try/catch - handleConsoleInputs(); -// } catch (Exception e) { -// logger.log(Level.WARNING, "Unexpected exception while parsing console command", e); -// } + // try { // 4J - removed try/catch + handleConsoleInputs(); + // } catch (Exception e) { + // logger.log(Level.WARNING, "Unexpected exception while parsing + // console command", e); + // } } -void MinecraftServer::handleConsoleInput(const std::wstring& msg, ConsoleInputSource *source) -{ - consoleInput.push_back(new ConsoleInput(msg, source)); +void MinecraftServer::handleConsoleInput(const std::wstring& msg, + ConsoleInputSource* source) { + consoleInput.push_back(new ConsoleInput(msg, source)); } -void MinecraftServer::handleConsoleInputs() -{ - while (consoleInput.size() > 0) - { - AUTO_VAR(it, consoleInput.begin()); - ConsoleInput *input = *it; - consoleInput.erase(it); -// commands->handleCommand(input); // 4J - removed - TODO - do we want equivalent of console commands? +void MinecraftServer::handleConsoleInputs() { + while (consoleInput.size() > 0) { + AUTO_VAR(it, consoleInput.begin()); + ConsoleInput* input = *it; + consoleInput.erase(it); + // commands->handleCommand(input); // 4J - removed + // - TODO - do we want equivalent of console commands? } } -void MinecraftServer::main(__int64 seed, void *lpParameter) -{ +void MinecraftServer::main(__int64 seed, void* lpParameter) { #if __PS3__ - ShutdownManager::HasStarted(ShutdownManager::eServerThread ); + ShutdownManager::HasStarted(ShutdownManager::eServerThread); #endif - server = new MinecraftServer(); - server->run(seed, lpParameter); - delete server; - server = NULL; - ShutdownManager::HasFinished(ShutdownManager::eServerThread ); + server = new MinecraftServer(); + server->run(seed, lpParameter); + delete server; + server = NULL; + ShutdownManager::HasFinished(ShutdownManager::eServerThread); } -void MinecraftServer::HaltServer(bool bPrimaryPlayerSignedOut) -{ - s_bServerHalted = true; - if( server != NULL ) - { - m_bPrimaryPlayerSignedOut=bPrimaryPlayerSignedOut; - server->halt(); - } +void MinecraftServer::HaltServer(bool bPrimaryPlayerSignedOut) { + s_bServerHalted = true; + if (server != NULL) { + m_bPrimaryPlayerSignedOut = bPrimaryPlayerSignedOut; + server->halt(); + } } -File *MinecraftServer::getFile(const std::wstring& name) -{ - return new File(name); +File* MinecraftServer::getFile(const std::wstring& name) { + return new File(name); } -void MinecraftServer::info(const std::wstring& string) -{ -} +void MinecraftServer::info(const std::wstring& string) {} -void MinecraftServer::warn(const std::wstring& string) -{ -} +void MinecraftServer::warn(const std::wstring& string) {} -std::wstring MinecraftServer::getConsoleName() -{ - return L"CONSOLE"; -} +std::wstring MinecraftServer::getConsoleName() { return L"CONSOLE"; } -ServerLevel *MinecraftServer::getLevel(int dimension) -{ - if (dimension == -1) return levels[1]; - else if (dimension == 1) return levels[2]; - else return levels[0]; +ServerLevel* MinecraftServer::getLevel(int dimension) { + if (dimension == -1) + return levels[1]; + else if (dimension == 1) + return levels[2]; + else + return levels[0]; } // 4J added -void MinecraftServer::setLevel(int dimension, ServerLevel *level) -{ - if (dimension == -1) levels[1] = level; - else if (dimension == 1) levels[2] = level; - else levels[0] = level; +void MinecraftServer::setLevel(int dimension, ServerLevel* level) { + if (dimension == -1) + levels[1] = level; + else if (dimension == 1) + levels[2] = level; + else + levels[0] = level; } // 4J Added -bool MinecraftServer::canSendOnSlowQueue(INetworkPlayer *player) -{ - if( player == NULL ) return false; +bool MinecraftServer::canSendOnSlowQueue(INetworkPlayer* player) { + if (player == NULL) return false; - int time = GetTickCount(); - if( player->GetSessionIndex() == s_slowQueuePlayerIndex && (time - s_slowQueueLastTime) > MINECRAFT_SERVER_SLOW_QUEUE_DELAY ) - { -// app.DebugPrintf("Slow queue OK for player #%d\n", player->GetSessionIndex()); - return true; - } + int time = GetTickCount(); + if (player->GetSessionIndex() == s_slowQueuePlayerIndex && + (time - s_slowQueueLastTime) > MINECRAFT_SERVER_SLOW_QUEUE_DELAY) { + // app.DebugPrintf("Slow queue OK for player #%d\n", + //player->GetSessionIndex()); + return true; + } - return false; + return false; } -void MinecraftServer::cycleSlowQueueIndex() -{ - if( !g_NetworkManager.IsInSession() ) return; +void MinecraftServer::cycleSlowQueueIndex() { + if (!g_NetworkManager.IsInSession()) return; - int startingIndex = s_slowQueuePlayerIndex; - INetworkPlayer *currentPlayer = NULL; - int currentPlayerCount = 0; - do - { - currentPlayerCount = g_NetworkManager.GetPlayerCount(); - if( startingIndex >= currentPlayerCount ) startingIndex = 0; - ++s_slowQueuePlayerIndex; + int startingIndex = s_slowQueuePlayerIndex; + INetworkPlayer* currentPlayer = NULL; + int currentPlayerCount = 0; + do { + currentPlayerCount = g_NetworkManager.GetPlayerCount(); + if (startingIndex >= currentPlayerCount) startingIndex = 0; + ++s_slowQueuePlayerIndex; - if( currentPlayerCount > 0 ) - { - s_slowQueuePlayerIndex %= currentPlayerCount; - // Fix for #9530 - NETWORKING: Attempting to fill a multiplayer game beyond capacity results in a softlock for the last players to join. - // The QNet session might be ending while we do this, so do a few more checks that the player is real - currentPlayer = g_NetworkManager.GetPlayerByIndex( s_slowQueuePlayerIndex ); - } - else - { - s_slowQueuePlayerIndex = 0; - } - } while ( g_NetworkManager.IsInSession() && - currentPlayerCount > 0 && - s_slowQueuePlayerIndex != startingIndex && - currentPlayer != NULL && - currentPlayer->IsLocal() - ); -// app.DebugPrintf("Cycled slow queue index to %d\n", s_slowQueuePlayerIndex); + if (currentPlayerCount > 0) { + s_slowQueuePlayerIndex %= currentPlayerCount; + // Fix for #9530 - NETWORKING: Attempting to fill a multiplayer game + // beyond capacity results in a softlock for the last players to + // join. The QNet session might be ending while we do this, so do a + // few more checks that the player is real + currentPlayer = + g_NetworkManager.GetPlayerByIndex(s_slowQueuePlayerIndex); + } else { + s_slowQueuePlayerIndex = 0; + } + } while (g_NetworkManager.IsInSession() && currentPlayerCount > 0 && + s_slowQueuePlayerIndex != startingIndex && currentPlayer != NULL && + currentPlayer->IsLocal()); + // app.DebugPrintf("Cycled slow queue index to %d\n", + //s_slowQueuePlayerIndex); } -// 4J added - sets up a vector of flags to indicate which entities (with small Ids) have been removed from the level, but are still haven't constructed a network packet -// to tell a remote client about it. These small Ids shouldn't be re-used. Most of the time this method shouldn't actually do anything, in which case it will return false -// and nothing is set up. -bool MinecraftServer::flagEntitiesToBeRemoved(unsigned int *flags) -{ - bool removedFound = false; - for( unsigned int i = 0; i < levels.length; i++ ) - { - ServerLevel *level = levels[i]; - if( level ) - { - level->flagEntitiesToBeRemoved( flags, &removedFound ); - } - } - return removedFound; +// 4J added - sets up a vector of flags to indicate which entities (with small +// Ids) have been removed from the level, but are still haven't constructed a +// network packet to tell a remote client about it. These small Ids shouldn't be +// re-used. Most of the time this method shouldn't actually do anything, in +// which case it will return false and nothing is set up. +bool MinecraftServer::flagEntitiesToBeRemoved(unsigned int* flags) { + bool removedFound = false; + for (unsigned int i = 0; i < levels.length; i++) { + ServerLevel* level = levels[i]; + if (level) { + level->flagEntitiesToBeRemoved(flags, &removedFound); + } + } + return removedFound; } diff --git a/Minecraft.Client/MinecraftServer.h b/Minecraft.Client/MinecraftServer.h index 4e9fd5895..597b3bab7 100644 --- a/Minecraft.Client/MinecraftServer.h +++ b/Minecraft.Client/MinecraftServer.h @@ -22,226 +22,265 @@ class CommandDispatcher; #define MINECRAFT_SERVER_SLOW_QUEUE_DELAY 250 -typedef struct _LoadSaveDataThreadParam -{ - void *data; - __int64 fileSize; - const std::wstring saveName; - _LoadSaveDataThreadParam(void *data, __int64 filesize, const std::wstring &saveName) : data( data ), fileSize( filesize ), saveName( saveName ) {} +typedef struct _LoadSaveDataThreadParam { + void* data; + __int64 fileSize; + const std::wstring saveName; + _LoadSaveDataThreadParam(void* data, __int64 filesize, + const std::wstring& saveName) + : data(data), fileSize(filesize), saveName(saveName) {} } LoadSaveDataThreadParam; -typedef struct _NetworkGameInitData -{ - __int64 seed; - LoadSaveDataThreadParam *saveData; - std::uint32_t settings; - LevelGenerationOptions *levelGen; - std::uint32_t texturePackId; - bool findSeed; - unsigned int xzSize; - unsigned char hellScale; - ESavePlatform savePlatform; +typedef struct _NetworkGameInitData { + __int64 seed; + LoadSaveDataThreadParam* saveData; + std::uint32_t settings; + LevelGenerationOptions* levelGen; + std::uint32_t texturePackId; + bool findSeed; + unsigned int xzSize; + unsigned char hellScale; + ESavePlatform savePlatform; - _NetworkGameInitData() - { - seed = 0; - saveData = NULL; - settings = 0; - levelGen = NULL; - texturePackId = 0; - findSeed = false; - xzSize = LEVEL_LEGACY_WIDTH; - hellScale = HELL_LEVEL_LEGACY_SCALE; - savePlatform = SAVE_FILE_PLATFORM_LOCAL; - } + _NetworkGameInitData() { + seed = 0; + saveData = NULL; + settings = 0; + levelGen = NULL; + texturePackId = 0; + findSeed = false; + xzSize = LEVEL_LEGACY_WIDTH; + hellScale = HELL_LEVEL_LEGACY_SCALE; + savePlatform = SAVE_FILE_PLATFORM_LOCAL; + } } NetworkGameInitData; - - -// 4J Stu - 1.0.1 updates the server to implement the ServerInterface class, but I don't think we will use any of the functions that defines so not implementing here -class MinecraftServer : public ConsoleInputSource -{ +// 4J Stu - 1.0.1 updates the server to implement the ServerInterface class, but +// I don't think we will use any of the functions that defines so not +// implementing here +class MinecraftServer : public ConsoleInputSource { public: - static const std::wstring VERSION; - static const int TICK_STATS_SPAN = SharedConstants::TICKS_PER_SECOND * 5; + static const std::wstring VERSION; + static const int TICK_STATS_SPAN = SharedConstants::TICKS_PER_SECOND * 5; -// static Logger logger = Logger.getLogger("Minecraft"); + // static Logger logger = Logger.getLogger("Minecraft"); static std::unordered_map ironTimers; private: - static const int DEFAULT_MINECRAFT_PORT = 25565; - static const int MS_PER_TICK = 1000 / SharedConstants::TICKS_PER_SECOND; + static const int DEFAULT_MINECRAFT_PORT = 25565; + static const int MS_PER_TICK = 1000 / SharedConstants::TICKS_PER_SECOND; - // 4J Stu - Added 1.0.1, Not needed - //std::wstring localIp; - //int port; + // 4J Stu - Added 1.0.1, Not needed + // std::wstring localIp; + // int port; public: - ServerConnection *connection; - Settings *settings; + ServerConnection* connection; + Settings* settings; ServerLevelArray levels; private: - PlayerList *players; + PlayerList* players; - // 4J Stu - Added 1.0.1, Not needed - //long[] tickTimes = new long[TICK_STATS_SPAN]; - //long[][] levelTickTimes; + // 4J Stu - Added 1.0.1, Not needed + // long[] tickTimes = new long[TICK_STATS_SPAN]; + // long[][] levelTickTimes; private: - ConsoleCommands *commands; + ConsoleCommands* commands; bool running; - bool m_bLoaded; + bool m_bLoaded; + public: - bool stopped; + bool stopped; int tickCount; public: - std::wstring progressStatus; + std::wstring progressStatus; int progress; + private: -// std::vector tickables = new ArrayList(); // 4J - removed - CommandDispatcher *commandDispatcher; - std::vector consoleInput; // 4J - was synchronizedList - TODO - investigate + // std::vector tickables = new ArrayList(); // 4J - + //removed + CommandDispatcher* commandDispatcher; + std::vector + consoleInput; // 4J - was synchronizedList - TODO - investigate public: bool onlineMode; bool animals; - bool npcs; + bool npcs; bool pvp; bool allowFlight; - std::wstring motd; - int maxBuildHeight; + std::wstring motd; + int maxBuildHeight; private: - // 4J Added - //int m_lastSentDifficulty; + // 4J Added + // int m_lastSentDifficulty; public: - // 4J Stu - This value should be incremented every time the list of players with friends-only UGC settings changes - // It is sent with PreLoginPacket and compared when it comes back in the LoginPacket - std::uint32_t m_ugcPlayersVersion; + // 4J Stu - This value should be incremented every time the list of players + // with friends-only UGC settings changes It is sent with PreLoginPacket and + // compared when it comes back in the LoginPacket + std::uint32_t m_ugcPlayersVersion; - // This value is used to store the texture pack id for the currently loaded world - std::uint32_t m_texturePackId; + // This value is used to store the texture pack id for the currently loaded + // world + std::uint32_t m_texturePackId; public: - MinecraftServer(); - ~MinecraftServer(); + MinecraftServer(); + ~MinecraftServer(); + private: - // 4J Added - LoadSaveDataThreadParam - bool initServer(__int64 seed, NetworkGameInitData *initData, std::uint32_t initSettings, bool findSeed); - void postProcessTerminate(ProgressRenderer *mcprogress); - bool loadLevel(LevelStorageSource *storageSource, const std::wstring& name, __int64 levelSeed, LevelType *pLevelType, NetworkGameInitData *initData); + // 4J Added - LoadSaveDataThreadParam + bool initServer(__int64 seed, NetworkGameInitData* initData, + std::uint32_t initSettings, bool findSeed); + void postProcessTerminate(ProgressRenderer* mcprogress); + bool loadLevel(LevelStorageSource* storageSource, const std::wstring& name, + __int64 levelSeed, LevelType* pLevelType, + NetworkGameInitData* initData); void setProgress(const std::wstring& status, int progress); void endProgress(); void saveAllChunks(); - void saveGameRules(); + void saveGameRules(); void stopServer(); public: - void setMaxBuildHeight(int maxBuildHeight); - int getMaxBuildHeight(); - PlayerList *getPlayers(); - void setPlayers(PlayerList *players); - ServerConnection *getConnection(); - bool isAnimals(); - void setAnimals(bool animals); - bool isNpcsEnabled(); - void setNpcsEnabled(bool npcs); - bool isPvpAllowed(); - void setPvpAllowed(bool pvp); - bool isFlightAllowed(); - void setFlightAllowed(bool allowFlight); - bool isNetherEnabled(); - bool isHardcore(); - CommandDispatcher *getCommandDispatcher(); + void setMaxBuildHeight(int maxBuildHeight); + int getMaxBuildHeight(); + PlayerList* getPlayers(); + void setPlayers(PlayerList* players); + ServerConnection* getConnection(); + bool isAnimals(); + void setAnimals(bool animals); + bool isNpcsEnabled(); + void setNpcsEnabled(bool npcs); + bool isPvpAllowed(); + void setPvpAllowed(bool pvp); + bool isFlightAllowed(); + void setFlightAllowed(bool allowFlight); + bool isNetherEnabled(); + bool isHardcore(); + CommandDispatcher* getCommandDispatcher(); public: - void halt(); - void run(__int64 seed, void *lpParameter); + void halt(); + void run(__int64 seed, void* lpParameter); - void broadcastStartSavingPacket(); - void broadcastStopSavingPacket(); + void broadcastStartSavingPacket(); + void broadcastStopSavingPacket(); private: - void tick(); -public: - void handleConsoleInput(const std::wstring& msg, ConsoleInputSource *source); - void handleConsoleInputs(); -// void addTickable(Tickable tickable); // 4J removed - static void main(__int64 seed, void *lpParameter); - static void HaltServer(bool bPrimaryPlayerSignedOut=false); + void tick(); - File *getFile(const std::wstring& name); +public: + void handleConsoleInput(const std::wstring& msg, + ConsoleInputSource* source); + void handleConsoleInputs(); + // void addTickable(Tickable tickable); // 4J removed + static void main(__int64 seed, void* lpParameter); + static void HaltServer(bool bPrimaryPlayerSignedOut = false); + + File* getFile(const std::wstring& name); void info(const std::wstring& string); void warn(const std::wstring& string); std::wstring getConsoleName(); - ServerLevel *getLevel(int dimension); - void setLevel(int dimension, ServerLevel *level); // 4J added - static MinecraftServer *getInstance() { return server; } // 4J added - static bool serverHalted() { return s_bServerHalted; } - static bool saveOnExitAnswered() { return s_bSaveOnExitAnswered; } - static void resetFlags() { s_bServerHalted = false; s_bSaveOnExitAnswered = false; } + ServerLevel* getLevel(int dimension); + void setLevel(int dimension, ServerLevel* level); // 4J added + static MinecraftServer* getInstance() { return server; } // 4J added + static bool serverHalted() { return s_bServerHalted; } + static bool saveOnExitAnswered() { return s_bSaveOnExitAnswered; } + static void resetFlags() { + s_bServerHalted = false; + s_bSaveOnExitAnswered = false; + } - bool flagEntitiesToBeRemoved(unsigned int *flags); // 4J added + bool flagEntitiesToBeRemoved(unsigned int* flags); // 4J added private: - //4J Added - static MinecraftServer *server; + // 4J Added + static MinecraftServer* server; - static bool setTimeOfDayAtEndOfTick; - static __int64 setTimeOfDay; - static bool setTimeAtEndOfTick; - static __int64 setTime; + static bool setTimeOfDayAtEndOfTick; + static __int64 setTimeOfDay; + static bool setTimeAtEndOfTick; + static __int64 setTime; - static bool m_bPrimaryPlayerSignedOut; // 4J-PB added to tell the stopserver not to save the game - another player may have signed in in their place, so ProfileManager.IsSignedIn isn't enough - static bool s_bServerHalted; // 4J Stu Added so that we can halt the server even before it's been created properly - static bool s_bSaveOnExitAnswered; // 4J Stu Added so that we only ask this question once when we exit + static bool + m_bPrimaryPlayerSignedOut; // 4J-PB added to tell the stopserver not to + // save the game - another player may have + // signed in in their place, so + // ProfileManager.IsSignedIn isn't enough + static bool s_bServerHalted; // 4J Stu Added so that we can halt the server + // even before it's been created properly + static bool s_bSaveOnExitAnswered; // 4J Stu Added so that we only ask this + // question once when we exit - // 4J - added so that we can have a separate thread for post processing chunks on level creation - static int runPostUpdate(void* lpParam); - C4JThread* m_postUpdateThread; - bool m_postUpdateTerminate; - class postProcessRequest - { - public: - int x, z; - ChunkSource *chunkSource; - postProcessRequest(int x, int z, ChunkSource *chunkSource) : x(x), z(z), chunkSource(chunkSource) {} - }; - std::vector m_postProcessRequests; - CRITICAL_SECTION m_postProcessCS; -public: - void addPostProcessRequest(ChunkSource *chunkSource, int x, int z); + // 4J - added so that we can have a separate thread for post processing + // chunks on level creation + static int runPostUpdate(void* lpParam); + C4JThread* m_postUpdateThread; + bool m_postUpdateTerminate; + class postProcessRequest { + public: + int x, z; + ChunkSource* chunkSource; + postProcessRequest(int x, int z, ChunkSource* chunkSource) + : x(x), z(z), chunkSource(chunkSource) {} + }; + std::vector m_postProcessRequests; + CRITICAL_SECTION m_postProcessCS; public: - static PlayerList *getPlayerList() { if( server != NULL ) return server->players; else return NULL; } - static void SetTimeOfDay(__int64 time) { setTimeOfDayAtEndOfTick = true; setTimeOfDay = time; } - static void SetTime(__int64 time) { setTimeAtEndOfTick = true; setTime = time; } - - C4JThread::Event* m_serverPausedEvent; -private: - // 4J Added - bool m_isServerPaused; + void addPostProcessRequest(ChunkSource* chunkSource, int x, int z); - // 4J Added - A static that stores the QNet index of the player that is next allowed to send a packet in the slow queue - static int s_slowQueuePlayerIndex; - static int s_slowQueueLastTime; public: - static bool s_slowQueuePacketSent; + static PlayerList* getPlayerList() { + if (server != NULL) + return server->players; + else + return NULL; + } + static void SetTimeOfDay(__int64 time) { + setTimeOfDayAtEndOfTick = true; + setTimeOfDay = time; + } + static void SetTime(__int64 time) { + setTimeAtEndOfTick = true; + setTime = time; + } - bool IsServerPaused() { return m_isServerPaused; } + C4JThread::Event* m_serverPausedEvent; private: - // 4J Added - bool m_saveOnExit; - bool m_suspending; + // 4J Added + bool m_isServerPaused; + + // 4J Added - A static that stores the QNet index of the player that is next + // allowed to send a packet in the slow queue + static int s_slowQueuePlayerIndex; + static int s_slowQueueLastTime; public: - //static int getSlowQueueIndex() { return s_slowQueuePlayerIndex; } - static bool canSendOnSlowQueue(INetworkPlayer *player); - static void cycleSlowQueueIndex(); + static bool s_slowQueuePacketSent; - void setSaveOnExit(bool save) { m_saveOnExit = save; s_bSaveOnExitAnswered = true; } - void Suspend(); - bool IsSuspending(); + bool IsServerPaused() { return m_isServerPaused; } - // 4J Stu - A load of functions were all added in 1.0.1 in the ServerInterface, but I don't think we need any of them +private: + // 4J Added + bool m_saveOnExit; + bool m_suspending; + +public: + // static int getSlowQueueIndex() { return s_slowQueuePlayerIndex; } + static bool canSendOnSlowQueue(INetworkPlayer* player); + static void cycleSlowQueueIndex(); + + void setSaveOnExit(bool save) { + m_saveOnExit = save; + s_bSaveOnExitAnswered = true; + } + void Suspend(); + bool IsSuspending(); + + // 4J Stu - A load of functions were all added in 1.0.1 in the + // ServerInterface, but I don't think we need any of them }; diff --git a/Minecraft.Client/Network/ClientConnection.cpp b/Minecraft.Client/Network/ClientConnection.cpp index d062fed55..deaad03f9 100644 --- a/Minecraft.Client/Network/ClientConnection.cpp +++ b/Minecraft.Client/Network/ClientConnection.cpp @@ -57,10 +57,10 @@ #include "../../Minecraft.World/Stats/GenericStats.h" #endif -ClientConnection::ClientConnection(Minecraft *minecraft, const std::wstring& ip, int port) -{ - // 4J Stu - No longer used as we use the socket version below. - assert(FALSE); +ClientConnection::ClientConnection(Minecraft* minecraft, const std::wstring& ip, + int port) { + // 4J Stu - No longer used as we use the socket version below. + assert(FALSE); #if 0 // 4J - added initiliasers random = new Random(); @@ -92,600 +92,630 @@ ClientConnection::ClientConnection(Minecraft *minecraft, const std::wstring& ip, #endif } -ClientConnection::ClientConnection(Minecraft *minecraft, Socket *socket, int iUserIndex /*= -1*/) -{ - // 4J - added initiliasers - random = new Random(); - done = false; +ClientConnection::ClientConnection(Minecraft* minecraft, Socket* socket, + int iUserIndex /*= -1*/) { + // 4J - added initiliasers + random = new Random(); + done = false; level = NULL; started = false; - savedDataStorage = new SavedDataStorage(NULL); - maxPlayers = 20; + savedDataStorage = new SavedDataStorage(NULL); + maxPlayers = 20; this->minecraft = minecraft; - if( iUserIndex < 0 ) - { - m_userIndex = ProfileManager.GetPrimaryPad(); - } - else - { - m_userIndex = iUserIndex; - } + if (iUserIndex < 0) { + m_userIndex = ProfileManager.GetPrimaryPad(); + } else { + m_userIndex = iUserIndex; + } - if( socket == NULL ) - { - socket = new Socket(); // 4J - Local connection - } + if (socket == NULL) { + socket = new Socket(); // 4J - Local connection + } - createdOk = socket->createdOk; - if( createdOk ) - { - connection = new Connection(socket, L"Client", this); - } - else - { - connection = NULL; - // TODO 4J Stu - This will cause issues since the session player owns the socket - //delete socket; - } + createdOk = socket->createdOk; + if (createdOk) { + connection = new Connection(socket, L"Client", this); + } else { + connection = NULL; + // TODO 4J Stu - This will cause issues since the session player owns + // the socket + // delete socket; + } } -ClientConnection::~ClientConnection() -{ - delete connection; - delete random; - delete savedDataStorage; +ClientConnection::~ClientConnection() { + delete connection; + delete random; + delete savedDataStorage; } -void ClientConnection::tick() -{ +void ClientConnection::tick() { if (!done) connection->tick(); connection->flush(); } -INetworkPlayer *ClientConnection::getNetworkPlayer() -{ - if( connection != NULL && connection->getSocket() != NULL) return connection->getSocket()->getPlayer(); - else return NULL; +INetworkPlayer* ClientConnection::getNetworkPlayer() { + if (connection != NULL && connection->getSocket() != NULL) + return connection->getSocket()->getPlayer(); + else + return NULL; } -void ClientConnection::handleLogin(std::shared_ptr packet) -{ +void ClientConnection::handleLogin(std::shared_ptr packet) { if (done) return; - PlayerUID OnlineXuid; - ProfileManager.GetXUID(m_userIndex,&OnlineXuid,true); // online xuid - MOJANG_DATA *pMojangData = NULL; - - if(!g_NetworkManager.IsLocalGame()) - { - pMojangData=app.GetMojangDataForXuid(OnlineXuid); - } + PlayerUID OnlineXuid; + ProfileManager.GetXUID(m_userIndex, &OnlineXuid, true); // online xuid + MOJANG_DATA* pMojangData = NULL; - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCLoginReceived * 100)/ (eCCConnected)); - } + if (!g_NetworkManager.IsLocalGame()) { + pMojangData = app.GetMojangDataForXuid(OnlineXuid); + } - // 4J-PB - load the local player skin (from the global title user storage area) if there is one - // the primary player on the host machine won't have a qnet player from the socket - INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); - int iUserID=-1; + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCLoginReceived * 100) / (eCCConnected)); + } - if( m_userIndex == ProfileManager.GetPrimaryPad() ) - { - iUserID=m_userIndex; + // 4J-PB - load the local player skin (from the global title user storage + // area) if there is one the primary player on the host machine won't have a + // qnet player from the socket + INetworkPlayer* networkPlayer = connection->getSocket()->getPlayer(); + int iUserID = -1; - TelemetryManager->SetMultiplayerInstanceId(packet->m_multiplayerInstanceId); - } - else - { - if(!networkPlayer->IsGuest() && networkPlayer->IsLocal()) - { - // find the pad number of this local player - for(int i=0;iSetMultiplayerInstanceId( + packet->m_multiplayerInstanceId); + } else { + if (!networkPlayer->IsGuest() && networkPlayer->IsLocal()) { + // find the pad number of this local player + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + INetworkPlayer* networkLocalPlayer = + g_NetworkManager.GetLocalPlayerByUserIndex(i); + if (networkLocalPlayer == networkPlayer) { + iUserID = i; + } + } + } + } - // if there's a special skin or cloak for this player, add it in - if(pMojangData) - { - // a skin? - if(pMojangData->wchSkin[0]!=0L) - { - std::wstring wstr=pMojangData->wchSkin; - // check the file is not already in - bRes=app.IsFileInMemoryTextures(wstr); - if(!bRes) - { + if (iUserID != -1) { + std::uint8_t* pBuffer = NULL; + unsigned int dwSize = 0; + bool bRes; + + // if there's a special skin or cloak for this player, add it in + if (pMojangData) { + // a skin? + if (pMojangData->wchSkin[0] != 0L) { + std::wstring wstr = pMojangData->wchSkin; + // check the file is not already in + bRes = app.IsFileInMemoryTextures(wstr); + if (!bRes) { #ifdef _XBOX - C4JStorage::ETMSStatus eTMSStatus; - eTMSStatus=StorageManager.ReadTMSFile(iUserID,C4JStorage::eGlobalStorage_Title,C4JStorage::eTMS_FileType_Graphic,pMojangData->wchSkin,&pBuffer, &dwSize); + C4JStorage::ETMSStatus eTMSStatus; + eTMSStatus = StorageManager.ReadTMSFile( + iUserID, C4JStorage::eGlobalStorage_Title, + C4JStorage::eTMS_FileType_Graphic, pMojangData->wchSkin, + &pBuffer, &dwSize); - bRes=(eTMSStatus==C4JStorage::ETMSStatus_Idle); + bRes = (eTMSStatus == C4JStorage::ETMSStatus_Idle); #endif - } + } - if(bRes) - { - app.AddMemoryTextureFile(wstr,pBuffer,dwSize); - } - } + if (bRes) { + app.AddMemoryTextureFile(wstr, pBuffer, dwSize); + } + } - // a cloak? - if(pMojangData->wchCape[0]!=0L) - { - std::wstring wstr=pMojangData->wchCape; - // check the file is not already in - bRes=app.IsFileInMemoryTextures(wstr); - if(!bRes) - { + // a cloak? + if (pMojangData->wchCape[0] != 0L) { + std::wstring wstr = pMojangData->wchCape; + // check the file is not already in + bRes = app.IsFileInMemoryTextures(wstr); + if (!bRes) { #ifdef _XBOX - C4JStorage::ETMSStatus eTMSStatus; - eTMSStatus=StorageManager.ReadTMSFile(iUserID,C4JStorage::eGlobalStorage_Title,C4JStorage::eTMS_FileType_Graphic,pMojangData->wchCape,&pBuffer, &dwSize); - bRes=(eTMSStatus==C4JStorage::ETMSStatus_Idle); + C4JStorage::ETMSStatus eTMSStatus; + eTMSStatus = StorageManager.ReadTMSFile( + iUserID, C4JStorage::eGlobalStorage_Title, + C4JStorage::eTMS_FileType_Graphic, pMojangData->wchCape, + &pBuffer, &dwSize); + bRes = (eTMSStatus == C4JStorage::ETMSStatus_Idle); #endif - } + } - if(bRes) - { - app.AddMemoryTextureFile(wstr,pBuffer,dwSize); - } - } - } + if (bRes) { + app.AddMemoryTextureFile(wstr, pBuffer, dwSize); + } + } + } - // If we're online, read the banned game list - app.ReadBannedList(iUserID); - // mark the level as not checked against banned levels - it'll be checked once the level starts - app.SetBanListCheck(iUserID,false); - } + // If we're online, read the banned game list + app.ReadBannedList(iUserID); + // mark the level as not checked against banned levels - it'll be + // checked once the level starts + app.SetBanListCheck(iUserID, false); + } - if( m_userIndex == ProfileManager.GetPrimaryPad() ) - { - if( app.GetTutorialMode() ) - { - minecraft->gameMode = new FullTutorialMode(ProfileManager.GetPrimaryPad(), minecraft, this); - } - // check if we're in the trial version - else if(ProfileManager.IsFullVersion()==false) - { - minecraft->gameMode = new TrialMode(ProfileManager.GetPrimaryPad(), minecraft, this); - } - else - { - MemSect(13); - minecraft->gameMode = new ConsoleGameMode(ProfileManager.GetPrimaryPad(), minecraft, this); - MemSect(0); - } + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + if (app.GetTutorialMode()) { + minecraft->gameMode = new FullTutorialMode( + ProfileManager.GetPrimaryPad(), minecraft, this); + } + // check if we're in the trial version + else if (ProfileManager.IsFullVersion() == false) { + minecraft->gameMode = + new TrialMode(ProfileManager.GetPrimaryPad(), minecraft, this); + } else { + MemSect(13); + minecraft->gameMode = new ConsoleGameMode( + ProfileManager.GetPrimaryPad(), minecraft, this); + MemSect(0); + } + Level* dimensionLevel = minecraft->getLevel(packet->dimension); + if (dimensionLevel == NULL) { + level = new MultiPlayerLevel( + this, + new LevelSettings( + packet->seed, GameType::byId(packet->gameType), false, + false, packet->m_newSeaLevel, packet->m_pLevelType, + packet->m_xzSize, packet->m_hellScale), + packet->dimension, packet->difficulty); - Level *dimensionLevel = minecraft->getLevel( packet->dimension ); - if( dimensionLevel == NULL ) - { - level = new MultiPlayerLevel(this, new LevelSettings(packet->seed, GameType::byId(packet->gameType), false, false, packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); + // 4J Stu - We want to share the SavedDataStorage between levels + int otherDimensionId = packet->dimension == 0 ? -1 : 0; + Level* activeLevel = minecraft->getLevel(otherDimensionId); + if (activeLevel != NULL) { + // Don't need to delete it here as it belongs to a client + // connection while will delete it when it's done + // if( level->savedDataStorage != NULL ) delete + // level->savedDataStorage; + level->savedDataStorage = activeLevel->savedDataStorage; + } - // 4J Stu - We want to share the SavedDataStorage between levels - int otherDimensionId = packet->dimension == 0 ? -1 : 0; - Level *activeLevel = minecraft->getLevel(otherDimensionId); - if( activeLevel != NULL ) - { - // Don't need to delete it here as it belongs to a client connection while will delete it when it's done - //if( level->savedDataStorage != NULL ) delete level->savedDataStorage; - level->savedDataStorage = activeLevel->savedDataStorage; - } + app.DebugPrintf("ClientConnection - DIFFICULTY --- %d\n", + packet->difficulty); + level->difficulty = packet->difficulty; // 4J Added + level->isClientSide = true; + minecraft->setLevel(level); + } - app.DebugPrintf("ClientConnection - DIFFICULTY --- %d\n",packet->difficulty); - level->difficulty = packet->difficulty; // 4J Added - level->isClientSide = true; - minecraft->setLevel(level); - } + minecraft->player->setPlayerIndex(packet->m_playerIndex); + minecraft->player->setCustomSkin(app.GetPlayerSkinId(m_userIndex)); + minecraft->player->setCustomCape(app.GetPlayerCapeId(m_userIndex)); - minecraft->player->setPlayerIndex( packet->m_playerIndex ); - minecraft->player->setCustomSkin( app.GetPlayerSkinId(m_userIndex) ); - minecraft->player->setCustomCape( app.GetPlayerCapeId(m_userIndex) ); + minecraft->createPrimaryLocalPlayer(ProfileManager.GetPrimaryPad()); + minecraft->player->dimension = packet->dimension; + // minecraft->setScreen(new ReceivingLevelScreen(this)); + minecraft->player->entityId = packet->clientVersion; - minecraft->createPrimaryLocalPlayer(ProfileManager.GetPrimaryPad()); + std::uint8_t networkSmallId = getSocket()->getSmallId(); + app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, + packet->m_uiGamePrivileges); + minecraft->player->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); - minecraft->player->dimension = packet->dimension; - //minecraft->setScreen(new ReceivingLevelScreen(this)); - minecraft->player->entityId = packet->clientVersion; + // Assume all privileges are on, so that the first message we see only + // indicates things that have been turned off + unsigned int startingPrivileges = 0; + Player::enableAllPlayerPrivileges(startingPrivileges, true); - std::uint8_t networkSmallId = getSocket()->getSmallId(); - app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, packet->m_uiGamePrivileges); - minecraft->player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); + if (networkPlayer->IsHost()) { + Player::setPlayerGamePrivilege( + startingPrivileges, Player::ePlayerGamePrivilege_HOST, 1); + } - // Assume all privileges are on, so that the first message we see only indicates things that have been turned off - unsigned int startingPrivileges = 0; - Player::enableAllPlayerPrivileges(startingPrivileges,true); + displayPrivilegeChanges(minecraft->player, startingPrivileges); - if(networkPlayer->IsHost()) - { - Player::setPlayerGamePrivilege(startingPrivileges, Player::ePlayerGamePrivilege_HOST,1); - } + // update the debugoptions + app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(), + app.GetGameSettingsDebugMask(-1, true)); + } else { + // 4J-PB - this isn't the level we want + // level = (MultiPlayerLevel *)minecraft->level; + level = (MultiPlayerLevel*)minecraft->getLevel(packet->dimension); + std::shared_ptr player; - displayPrivilegeChanges(minecraft->player,startingPrivileges); + if (level == NULL) { + int otherDimensionId = packet->dimension == 0 ? -1 : 0; + MultiPlayerLevel* activeLevel = + minecraft->getLevel(otherDimensionId); - // update the debugoptions - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),app.GetGameSettingsDebugMask(-1,true)); - } - else - { - // 4J-PB - this isn't the level we want - //level = (MultiPlayerLevel *)minecraft->level; - level = (MultiPlayerLevel *)minecraft->getLevel( packet->dimension ); - std::shared_ptr player; + if (activeLevel == NULL) { + otherDimensionId = packet->dimension == 0 + ? 1 + : (packet->dimension == -1 ? 1 : -1); + activeLevel = minecraft->getLevel(otherDimensionId); + } - if(level==NULL) - { - int otherDimensionId = packet->dimension == 0 ? -1 : 0; - MultiPlayerLevel *activeLevel = minecraft->getLevel(otherDimensionId); + MultiPlayerLevel* dimensionLevel = new MultiPlayerLevel( + this, + new LevelSettings( + packet->seed, GameType::byId(packet->gameType), false, + false, packet->m_newSeaLevel, packet->m_pLevelType, + packet->m_xzSize, packet->m_hellScale), + packet->dimension, packet->difficulty); - if(activeLevel == NULL) - { - otherDimensionId = packet->dimension == 0 ? 1 : (packet->dimension == -1 ? 1 : -1); - activeLevel = minecraft->getLevel(otherDimensionId); - } + dimensionLevel->savedDataStorage = activeLevel->savedDataStorage; - MultiPlayerLevel *dimensionLevel = new MultiPlayerLevel(this, new LevelSettings(packet->seed, GameType::byId(packet->gameType), false, false, packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); + dimensionLevel->difficulty = packet->difficulty; // 4J Added + dimensionLevel->isClientSide = true; + level = dimensionLevel; + // 4J Stu - At time of writing ProfileManager.GetGamertag() does not + // always return the correct name, if sign-ins are turned off while + // the player signed in. Using the qnetPlayer instead. need to have + // a level before create extra local player + MultiPlayerLevel* levelpassedin = (MultiPlayerLevel*)level; + player = minecraft->createExtraLocalPlayer( + m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, + packet->dimension, this, levelpassedin); - dimensionLevel->savedDataStorage = activeLevel->savedDataStorage; + // need to have a player before the setlevel + std::shared_ptr lastPlayer = + minecraft->player; + minecraft->player = minecraft->localplayers[m_userIndex]; + minecraft->setLevel(level); + minecraft->player = lastPlayer; + } else { + player = minecraft->createExtraLocalPlayer( + m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, + packet->dimension, this); + } - dimensionLevel->difficulty = packet->difficulty; // 4J Added - dimensionLevel->isClientSide = true; - level = dimensionLevel; - // 4J Stu - At time of writing ProfileManager.GetGamertag() does not always return the correct name, - // if sign-ins are turned off while the player signed in. Using the qnetPlayer instead. - // need to have a level before create extra local player - MultiPlayerLevel *levelpassedin=(MultiPlayerLevel *)level; - player = minecraft->createExtraLocalPlayer(m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, packet->dimension, this,levelpassedin); + // level->addClientConnection( this ); + player->dimension = packet->dimension; + player->entityId = packet->clientVersion; - // need to have a player before the setlevel - std::shared_ptr lastPlayer = minecraft->player; - minecraft->player = minecraft->localplayers[m_userIndex]; - minecraft->setLevel(level); - minecraft->player = lastPlayer; - } - else - { - player = minecraft->createExtraLocalPlayer(m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, packet->dimension, this); - } + player->setPlayerIndex(packet->m_playerIndex); + player->setCustomSkin(app.GetPlayerSkinId(m_userIndex)); + player->setCustomCape(app.GetPlayerCapeId(m_userIndex)); + std::uint8_t networkSmallId = getSocket()->getSmallId(); + app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, + packet->m_uiGamePrivileges); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + packet->m_uiGamePrivileges); - //level->addClientConnection( this ); - player->dimension = packet->dimension; - player->entityId = packet->clientVersion; + // Assume all privileges are on, so that the first message we see only + // indicates things that have been turned off + unsigned int startingPrivileges = 0; + Player::enableAllPlayerPrivileges(startingPrivileges, true); - player->setPlayerIndex( packet->m_playerIndex ); - player->setCustomSkin( app.GetPlayerSkinId(m_userIndex) ); - player->setCustomCape( app.GetPlayerCapeId(m_userIndex) ); - + displayPrivilegeChanges(minecraft->localplayers[m_userIndex], + startingPrivileges); + } - std::uint8_t networkSmallId = getSocket()->getSmallId(); - app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, packet->m_uiGamePrivileges); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); + maxPlayers = packet->maxPlayers; - // Assume all privileges are on, so that the first message we see only indicates things that have been turned off - unsigned int startingPrivileges = 0; - Player::enableAllPlayerPrivileges(startingPrivileges,true); + // need to have a player before the setLocalCreativeMode + std::shared_ptr lastPlayer = minecraft->player; + minecraft->player = minecraft->localplayers[m_userIndex]; + ((MultiPlayerGameMode*)minecraft->localgameModes[m_userIndex]) + ->setLocalMode(GameType::byId(packet->gameType)); + minecraft->player = lastPlayer; - displayPrivilegeChanges(minecraft->localplayers[m_userIndex],startingPrivileges); - } - - maxPlayers = packet->maxPlayers; - - // need to have a player before the setLocalCreativeMode - std::shared_ptr lastPlayer = minecraft->player; - minecraft->player = minecraft->localplayers[m_userIndex]; - ((MultiPlayerGameMode *)minecraft->localgameModes[m_userIndex])->setLocalMode(GameType::byId(packet->gameType)); - minecraft->player = lastPlayer; - - // make sure the UI offsets for this player are set correctly - if(iUserID!=-1) - { - ui.UpdateSelectedItemPos(iUserID); - } - - TelemetryManager->RecordLevelStart(m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); + // make sure the UI offsets for this player are set correctly + if (iUserID != -1) { + ui.UpdateSelectedItemPos(iUserID); + } + + TelemetryManager->RecordLevelStart( + m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, + Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, + app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); } -void ClientConnection::handleAddEntity(std::shared_ptr packet) -{ +void ClientConnection::handleAddEntity( + std::shared_ptr packet) { double x = packet->x / 32.0; double y = packet->y / 32.0; double z = packet->z / 32.0; std::shared_ptr e; - boolean setRot = true; + boolean setRot = true; - // 4J-PB - replacing this massive if nest with switch - switch(packet->type) - { - case AddEntityPacket::MINECART_RIDEABLE: - e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::RIDEABLE) ); - break; - case AddEntityPacket::MINECART_CHEST: - e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::CHEST) ); - break; + // 4J-PB - replacing this massive if nest with switch + switch (packet->type) { + case AddEntityPacket::MINECART_RIDEABLE: + e = std::shared_ptr( + new Minecart(level, x, y, z, Minecart::RIDEABLE)); + break; + case AddEntityPacket::MINECART_CHEST: + e = std::shared_ptr( + new Minecart(level, x, y, z, Minecart::CHEST)); + break; - case AddEntityPacket::MINECART_FURNACE: - e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::FURNACE) ); - break; + case AddEntityPacket::MINECART_FURNACE: + e = std::shared_ptr( + new Minecart(level, x, y, z, Minecart::FURNACE)); + break; - case AddEntityPacket::FISH_HOOK: - { - // 4J Stu - Brought forward from 1.4 to be able to drop XP from fishing - std::shared_ptr owner = getEntity(packet->data); + case AddEntityPacket::FISH_HOOK: { + // 4J Stu - Brought forward from 1.4 to be able to drop XP from + // fishing + std::shared_ptr owner = getEntity(packet->data); - // 4J - check all local players to find match - if( owner == NULL ) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->data ) - { - - owner = minecraft->localplayers[i]; - break; - } - } - } - } - std::shared_ptr player = std::dynamic_pointer_cast(owner); - if (player != NULL) - { - std::shared_ptr hook = std::shared_ptr( new FishingHook(level, x, y, z, player) ); - e = hook; - // 4J Stu - Move the player->fishing out of the ctor as we cannot reference 'this' - player->fishing = hook; - } - packet->data = 0; - } - break; - case AddEntityPacket::ARROW: - e = std::shared_ptr( new Arrow(level, x, y, z) ); - break; - case AddEntityPacket::SNOWBALL: - e = std::shared_ptr( new Snowball(level, x, y, z) ); - break; - case AddEntityPacket::ITEM_FRAME: - { - int ix=(int) x; - int iy=(int) y; - int iz = (int) z; - app.DebugPrintf("ClientConnection ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); - } - e = std::shared_ptr(new ItemFrame(level, (int) x, (int) y, (int) z, packet->data)); - packet->data = 0; - setRot = false; - break; - case AddEntityPacket::THROWN_ENDERPEARL: - e = std::shared_ptr( new ThrownEnderpearl(level, x, y, z) ); - break; - case AddEntityPacket::EYEOFENDERSIGNAL: - e = std::shared_ptr( new EyeOfEnderSignal(level, x, y, z) ); - break; - case AddEntityPacket::FIREBALL: - e = std::shared_ptr( new Fireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - break; - case AddEntityPacket::SMALL_FIREBALL: - e = std::shared_ptr( new SmallFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - break; - case AddEntityPacket::DRAGON_FIRE_BALL: - e = std::shared_ptr( new DragonFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - break; - case AddEntityPacket::EGG: - e = std::shared_ptr( new ThrownEgg(level, x, y, z) ); - break; - case AddEntityPacket::THROWN_POTION: - e = std::shared_ptr( new ThrownPotion(level, x, y, z, packet->data) ); - packet->data = 0; - break; - case AddEntityPacket::THROWN_EXPBOTTLE: - e = std::shared_ptr( new ThrownExpBottle(level, x, y, z) ); - packet->data = 0; - break; - case AddEntityPacket::BOAT: - e = std::shared_ptr( new Boat(level, x, y, z) ); - break; - case AddEntityPacket::PRIMED_TNT: - e = std::shared_ptr( new PrimedTnt(level, x, y, z) ); - break; - case AddEntityPacket::ENDER_CRYSTAL: - e = std::shared_ptr( new EnderCrystal(level, x, y, z) ); - break; - case AddEntityPacket::ITEM: - e = std::shared_ptr( new ItemEntity(level, x, y, z) ); - break; - case AddEntityPacket::FALLING: - e = std::shared_ptr( new FallingTile(level, x, y, z, packet->data & 0xFFFF, packet->data >> 16) ); - packet->data = 0; - break; - - - - } - /* if (packet->type == AddEntityPacket::MINECART_RIDEABLE) e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::RIDEABLE) ); - if (packet->type == AddEntityPacket::MINECART_CHEST) e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::CHEST) ); - if (packet->type == AddEntityPacket::MINECART_FURNACE) e = std::shared_ptr( new Minecart(level, x, y, z, Minecart::FURNACE) ); - if (packet->type == AddEntityPacket::FISH_HOOK) - { - // 4J Stu - Brought forward from 1.4 to be able to drop XP from fishing - std::shared_ptr owner = getEntity(packet->data); - - // 4J - check all local players to find match - if( owner == NULL ) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->data ) - { - - owner = minecraft->localplayers[i]; - break; - } - } - } - } - std::shared_ptr player = std::dynamic_pointer_cast(owner); - if (player != NULL) - { - std::shared_ptr hook = std::shared_ptr( new FishingHook(level, x, y, z, player) ); - e = hook; - // 4J Stu - Move the player->fishing out of the ctor as we cannot reference 'this' - player->fishing = hook; - } - packet->data = 0; - } - - if (packet->type == AddEntityPacket::ARROW) e = std::shared_ptr( new Arrow(level, x, y, z) ); - if (packet->type == AddEntityPacket::SNOWBALL) e = std::shared_ptr( new Snowball(level, x, y, z) ); - if (packet->type == AddEntityPacket::THROWN_ENDERPEARL) e = std::shared_ptr( new ThrownEnderpearl(level, x, y, z) ); - if (packet->type == AddEntityPacket::EYEOFENDERSIGNAL) e = std::shared_ptr( new EyeOfEnderSignal(level, x, y, z) ); - if (packet->type == AddEntityPacket::FIREBALL) - { - e = std::shared_ptr( new Fireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; + // 4J - check all local players to find match + if (owner == NULL) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == + packet->data) { + owner = minecraft->localplayers[i]; + break; + } + } + } + } + std::shared_ptr player = + std::dynamic_pointer_cast(owner); + if (player != NULL) { + std::shared_ptr hook = + std::shared_ptr( + new FishingHook(level, x, y, z, player)); + e = hook; + // 4J Stu - Move the player->fishing out of the ctor as we + // cannot reference 'this' + player->fishing = hook; + } + packet->data = 0; + } break; + case AddEntityPacket::ARROW: + e = std::shared_ptr(new Arrow(level, x, y, z)); + break; + case AddEntityPacket::SNOWBALL: + e = std::shared_ptr(new Snowball(level, x, y, z)); + break; + case AddEntityPacket::ITEM_FRAME: { + int ix = (int)x; + int iy = (int)y; + int iz = (int)z; + app.DebugPrintf("ClientConnection ITEM_FRAME xyz %d,%d,%d\n", ix, + iy, iz); + } + e = std::shared_ptr( + new ItemFrame(level, (int)x, (int)y, (int)z, packet->data)); + packet->data = 0; + setRot = false; + break; + case AddEntityPacket::THROWN_ENDERPEARL: + e = std::shared_ptr(new ThrownEnderpearl(level, x, y, z)); + break; + case AddEntityPacket::EYEOFENDERSIGNAL: + e = std::shared_ptr(new EyeOfEnderSignal(level, x, y, z)); + break; + case AddEntityPacket::FIREBALL: + e = std::shared_ptr( + new Fireball(level, x, y, z, packet->xa / 8000.0, + packet->ya / 8000.0, packet->za / 8000.0)); + packet->data = 0; + break; + case AddEntityPacket::SMALL_FIREBALL: + e = std::shared_ptr( + new SmallFireball(level, x, y, z, packet->xa / 8000.0, + packet->ya / 8000.0, packet->za / 8000.0)); + packet->data = 0; + break; + case AddEntityPacket::DRAGON_FIRE_BALL: + e = std::shared_ptr( + new DragonFireball(level, x, y, z, packet->xa / 8000.0, + packet->ya / 8000.0, packet->za / 8000.0)); + packet->data = 0; + break; + case AddEntityPacket::EGG: + e = std::shared_ptr(new ThrownEgg(level, x, y, z)); + break; + case AddEntityPacket::THROWN_POTION: + e = std::shared_ptr( + new ThrownPotion(level, x, y, z, packet->data)); + packet->data = 0; + break; + case AddEntityPacket::THROWN_EXPBOTTLE: + e = std::shared_ptr(new ThrownExpBottle(level, x, y, z)); + packet->data = 0; + break; + case AddEntityPacket::BOAT: + e = std::shared_ptr(new Boat(level, x, y, z)); + break; + case AddEntityPacket::PRIMED_TNT: + e = std::shared_ptr(new PrimedTnt(level, x, y, z)); + break; + case AddEntityPacket::ENDER_CRYSTAL: + e = std::shared_ptr(new EnderCrystal(level, x, y, z)); + break; + case AddEntityPacket::ITEM: + e = std::shared_ptr(new ItemEntity(level, x, y, z)); + break; + case AddEntityPacket::FALLING: + e = std::shared_ptr(new FallingTile( + level, x, y, z, packet->data & 0xFFFF, packet->data >> 16)); + packet->data = 0; + break; } - if (packet->type == AddEntityPacket::SMALL_FIREBALL) - { - e = std::shared_ptr( new SmallFireball(level, x, y, z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); - packet->data = 0; - } - if (packet->type == AddEntityPacket::EGG) e = std::shared_ptr( new ThrownEgg(level, x, y, z) ); - if (packet->type == AddEntityPacket::THROWN_POTION) - { - e = std::shared_ptr( new ThrownPotion(level, x, y, z, packet->data) ); - packet->data = 0; - } - if (packet->type == AddEntityPacket::THROWN_EXPBOTTLE) - { - e = std::shared_ptr( new ThrownExpBottle(level, x, y, z) ); - packet->data = 0; - } - if (packet->type == AddEntityPacket::BOAT) e = std::shared_ptr( new Boat(level, x, y, z) ); - if (packet->type == AddEntityPacket::PRIMED_TNT) e = std::shared_ptr( new PrimedTnt(level, x, y, z) ); - if (packet->type == AddEntityPacket::ENDER_CRYSTAL) e = std::shared_ptr( new EnderCrystal(level, x, y, z) ); - if (packet->type == AddEntityPacket::FALLING_SAND) e = std::shared_ptr( new FallingTile(level, x, y, z, Tile::sand->id) ); - if (packet->type == AddEntityPacket::FALLING_GRAVEL) e = std::shared_ptr( new FallingTile(level, x, y, z, Tile::gravel->id) ); - if (packet->type == AddEntityPacket::FALLING_EGG) e = std::shared_ptr( new FallingTile(level, x, y, z, Tile::dragonEgg_Id) ); + /* if (packet->type == AddEntityPacket::MINECART_RIDEABLE) e = + std::shared_ptr( new Minecart(level, x, y, z, Minecart::RIDEABLE) + ); if (packet->type == AddEntityPacket::MINECART_CHEST) e = + std::shared_ptr( new Minecart(level, x, y, z, Minecart::CHEST) ); + if (packet->type == AddEntityPacket::MINECART_FURNACE) e = + std::shared_ptr( new Minecart(level, x, y, z, Minecart::FURNACE) + ); if (packet->type == AddEntityPacket::FISH_HOOK) + { + // 4J Stu - Brought forward from 1.4 to be able to drop XP + from fishing std::shared_ptr owner = getEntity(packet->data); - */ + // 4J - check all local players to find match + if( owner == NULL ) + { + for( int i = 0; i < XUSER_MAX_COUNT; i++ ) + { + if( minecraft->localplayers[i] ) + { + if( + minecraft->localplayers[i]->entityId == packet->data ) + { - if (e != NULL) - { + owner = + minecraft->localplayers[i]; break; + } + } + } + } + std::shared_ptr player = + std::dynamic_pointer_cast(owner); if (player != NULL) + { + std::shared_ptr hook = + std::shared_ptr( new FishingHook(level, x, y, z, player) ); + e = hook; + // 4J Stu - Move the player->fishing out of the ctor + as we cannot reference 'this' player->fishing = hook; + } + packet->data = 0; + } + + if (packet->type == AddEntityPacket::ARROW) e = std::shared_ptr( + new Arrow(level, x, y, z) ); if (packet->type == + AddEntityPacket::SNOWBALL) e = std::shared_ptr( new + Snowball(level, x, y, z) ); if (packet->type == + AddEntityPacket::THROWN_ENDERPEARL) e = std::shared_ptr( new + ThrownEnderpearl(level, x, y, z) ); if (packet->type == + AddEntityPacket::EYEOFENDERSIGNAL) e = std::shared_ptr( new + EyeOfEnderSignal(level, x, y, z) ); if (packet->type == + AddEntityPacket::FIREBALL) + { + e = std::shared_ptr( new Fireball(level, x, y, z, packet->xa + / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); packet->data = 0; + } + if (packet->type == AddEntityPacket::SMALL_FIREBALL) + { + e = std::shared_ptr( new SmallFireball(level, x, y, + z, packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0) ); + packet->data = 0; + } + if (packet->type == AddEntityPacket::EGG) e = std::shared_ptr( + new ThrownEgg(level, x, y, z) ); if (packet->type == + AddEntityPacket::THROWN_POTION) + { + e = std::shared_ptr( new ThrownPotion(level, x, y, z, + packet->data) ); packet->data = 0; + } + if (packet->type == AddEntityPacket::THROWN_EXPBOTTLE) + { + e = std::shared_ptr( new ThrownExpBottle(level, x, y, + z) ); packet->data = 0; + } + if (packet->type == AddEntityPacket::BOAT) e = std::shared_ptr( + new Boat(level, x, y, z) ); if (packet->type == + AddEntityPacket::PRIMED_TNT) e = std::shared_ptr( new + PrimedTnt(level, x, y, z) ); if (packet->type == + AddEntityPacket::ENDER_CRYSTAL) e = std::shared_ptr( new + EnderCrystal(level, x, y, z) ); if (packet->type == + AddEntityPacket::FALLING_SAND) e = std::shared_ptr( new + FallingTile(level, x, y, z, Tile::sand->id) ); if (packet->type == + AddEntityPacket::FALLING_GRAVEL) e = std::shared_ptr( new + FallingTile(level, x, y, z, Tile::gravel->id) ); if (packet->type == + AddEntityPacket::FALLING_EGG) e = std::shared_ptr( new + FallingTile(level, x, y, z, Tile::dragonEgg_Id) ); + + */ + + if (e != NULL) { e->xp = packet->x; e->yp = packet->y; e->zp = packet->z; - float yRot = packet->yRot * 360 / 256.0f; - float xRot = packet->xRot * 360 / 256.0f; - e->yRotp = packet->yRot; - e->xRotp = packet->xRot; + float yRot = packet->yRot * 360 / 256.0f; + float xRot = packet->xRot * 360 / 256.0f; + e->yRotp = packet->yRot; + e->xRotp = packet->xRot; - if (setRot) - { - e->yRot = 0.0f; - e->xRot = 0.0f; - } + if (setRot) { + e->yRot = 0.0f; + e->xRot = 0.0f; + } - std::vector > *subEntities = e->getSubEntities(); - if (subEntities != NULL) - { - int offs = packet->id - e->entityId; - //for (int i = 0; i < subEntities.length; i++) - for(AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); ++it) - { - (*it)->entityId += offs; - //subEntities[i].entityId += offs; - //System.out.println(subEntities[i].entityId); - } - } + std::vector >* subEntities = + e->getSubEntities(); + if (subEntities != NULL) { + int offs = packet->id - e->entityId; + // for (int i = 0; i < subEntities.length; i++) + for (AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); + ++it) { + (*it)->entityId += offs; + // subEntities[i].entityId += offs; + // System.out.println(subEntities[i].entityId); + } + } - // Note - not doing this move for frame, as the ctor for these objects does some adjustments on the position based on direction to move the object out slightly from what it is attached to, and this just overwrites it - if( packet->type != AddEntityPacket::ITEM_FRAME ) - { - e->absMoveTo(x,y,z,yRot,xRot); - } + // Note - not doing this move for frame, as the ctor for these objects + // does some adjustments on the position based on direction to move the + // object out slightly from what it is attached to, and this just + // overwrites it + if (packet->type != AddEntityPacket::ITEM_FRAME) { + e->absMoveTo(x, y, z, yRot, xRot); + } e->entityId = packet->id; level->putEntity(packet->id, e); - if (packet->data > -1) // 4J - changed "no data" value to be -1, we can have a valid entity id of 0 - { - - if (packet->type == AddEntityPacket::ARROW) - { + if (packet->data > -1) // 4J - changed "no data" value to be -1, we can + // have a valid entity id of 0 + { + if (packet->type == AddEntityPacket::ARROW) { std::shared_ptr owner = getEntity(packet->data); - // 4J - check all local players to find match - if( owner == NULL ) - { - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->data ) - { - owner = minecraft->localplayers[i]; - break; - } - } - } - } + // 4J - check all local players to find match + if (owner == NULL) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == + packet->data) { + owner = minecraft->localplayers[i]; + break; + } + } + } + } - if (std::dynamic_pointer_cast(owner) != NULL) - { - std::dynamic_pointer_cast(e)->owner = std::dynamic_pointer_cast(owner); + if (std::dynamic_pointer_cast(owner) != NULL) { + std::dynamic_pointer_cast(e)->owner = + std::dynamic_pointer_cast(owner); } } - e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); + e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, + packet->za / 8000.0); } - } - + } } -void ClientConnection::handleAddExperienceOrb(std::shared_ptr packet) -{ - std::shared_ptr e = std::shared_ptr( new ExperienceOrb(level, packet->x / 32.0, packet->y / 32.0, packet->z / 32.0, packet->value) ); - e->xp = packet->x; - e->yp = packet->y; - e->zp = packet->z; - e->yRot = 0; - e->xRot = 0; - e->entityId = packet->id; - level->putEntity(packet->id, e); +void ClientConnection::handleAddExperienceOrb( + std::shared_ptr packet) { + std::shared_ptr e = std::shared_ptr( + new ExperienceOrb(level, packet->x / 32.0, packet->y / 32.0, + packet->z / 32.0, packet->value)); + e->xp = packet->x; + e->yp = packet->y; + e->zp = packet->z; + e->yRot = 0; + e->xRot = 0; + e->entityId = packet->id; + level->putEntity(packet->id, e); } -void ClientConnection::handleAddGlobalEntity(std::shared_ptr packet) -{ +void ClientConnection::handleAddGlobalEntity( + std::shared_ptr packet) { double x = packet->x / 32.0; double y = packet->y / 32.0; double z = packet->z / 32.0; - std::shared_ptr e;// = nullptr; - if (packet->type == AddGlobalEntityPacket::LIGHTNING) e = std::shared_ptr( new LightningBolt(level, x, y, z) ); - if (e != NULL) - { + std::shared_ptr e; // = nullptr; + if (packet->type == AddGlobalEntityPacket::LIGHTNING) + e = std::shared_ptr(new LightningBolt(level, x, y, z)); + if (e != NULL) { e->xp = packet->x; e->yp = packet->y; e->zp = packet->z; @@ -696,131 +726,149 @@ void ClientConnection::handleAddGlobalEntity(std::shared_ptr packet) -{ - std::shared_ptr painting = std::shared_ptr( new Painting(level, packet->x, packet->y, packet->z, packet->dir, packet->motive) ); +void ClientConnection::handleAddPainting( + std::shared_ptr packet) { + std::shared_ptr painting = std::shared_ptr(new Painting( + level, packet->x, packet->y, packet->z, packet->dir, packet->motive)); level->putEntity(packet->id, painting); } -void ClientConnection::handleSetEntityMotion(std::shared_ptr packet) -{ +void ClientConnection::handleSetEntityMotion( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; - e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); + e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, + packet->za / 8000.0); } -void ClientConnection::handleSetEntityData(std::shared_ptr packet) -{ +void ClientConnection::handleSetEntityData( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); - if (e != NULL && packet->getUnpackedData() != NULL) - { + if (e != NULL && packet->getUnpackedData() != NULL) { e->getEntityData()->assignValues(packet->getUnpackedData()); } } -void ClientConnection::handleAddPlayer(std::shared_ptr packet) -{ - // Some remote players could actually be local players that are already added - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - // need to use the XUID here - PlayerUID playerXUIDOnline = INVALID_XUID, playerXUIDOffline = INVALID_XUID; - ProfileManager.GetXUID(idx,&playerXUIDOnline,true); - ProfileManager.GetXUID(idx,&playerXUIDOffline,false); - if( (playerXUIDOnline != INVALID_XUID && ProfileManager.AreXUIDSEqual(playerXUIDOnline,packet->xuid) ) || - (playerXUIDOffline != INVALID_XUID && ProfileManager.AreXUIDSEqual(playerXUIDOffline,packet->xuid) ) ) - { - app.DebugPrintf("AddPlayerPacket received with XUID of local player\n"); - return; - } - } +void ClientConnection::handleAddPlayer( + std::shared_ptr packet) { + // Some remote players could actually be local players that are already + // added + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + // need to use the XUID here + PlayerUID playerXUIDOnline = INVALID_XUID, + playerXUIDOffline = INVALID_XUID; + ProfileManager.GetXUID(idx, &playerXUIDOnline, true); + ProfileManager.GetXUID(idx, &playerXUIDOffline, false); + if ((playerXUIDOnline != INVALID_XUID && + ProfileManager.AreXUIDSEqual(playerXUIDOnline, packet->xuid)) || + (playerXUIDOffline != INVALID_XUID && + ProfileManager.AreXUIDSEqual(playerXUIDOffline, packet->xuid))) { + app.DebugPrintf( + "AddPlayerPacket received with XUID of local player\n"); + return; + } + } double x = packet->x / 32.0; double y = packet->y / 32.0; double z = packet->z / 32.0; float yRot = packet->yRot * 360 / 256.0f; float xRot = packet->xRot * 360 / 256.0f; - std::shared_ptr player = std::shared_ptr( new RemotePlayer(minecraft->level, packet->name) ); + std::shared_ptr player = std::shared_ptr( + new RemotePlayer(minecraft->level, packet->name)); player->xo = player->xOld = player->xp = packet->x; player->yo = player->yOld = player->yp = packet->y; player->zo = player->zOld = player->zp = packet->z; - player->xRotp = packet->xRot; - player->yRotp = packet->yRot; - player->yHeadRot = packet->yHeadRot * 360 / 256.0f; - player->setXuid(packet->xuid); + player->xRotp = packet->xRot; + player->yRotp = packet->yRot; + player->yHeadRot = packet->yHeadRot * 360 / 256.0f; + player->setXuid(packet->xuid); #ifdef _DURANGO - // On Durango request player display name from network manager - INetworkPlayer *networkPlayer = g_NetworkManager.GetPlayerByXuid(player->getXuid()); - if (networkPlayer != NULL) player->displayName = networkPlayer->GetDisplayName(); + // On Durango request player display name from network manager + INetworkPlayer* networkPlayer = + g_NetworkManager.GetPlayerByXuid(player->getXuid()); + if (networkPlayer != NULL) + player->displayName = networkPlayer->GetDisplayName(); #else - // On all other platforms display name is just gamertag so don't check with the network manager - player->displayName = player->name; + // On all other platforms display name is just gamertag so don't check with + // the network manager + player->displayName = player->name; #endif - // printf("\t\t\t\t%d: Add player\n",packet->id,packet->yRot); + // printf("\t\t\t\t%d: Add player\n",packet->id,packet->yRot); int item = packet->carriedItem; - if (item == 0) - { - player->inventory->items[player->inventory->selected] = std::shared_ptr(); // NULL; - } - else - { - player->inventory->items[player->inventory->selected] = std::shared_ptr( new ItemInstance(item, 1, 0) ); + if (item == 0) { + player->inventory->items[player->inventory->selected] = + std::shared_ptr(); // NULL; + } else { + player->inventory->items[player->inventory->selected] = + std::shared_ptr(new ItemInstance(item, 1, 0)); } player->absMoveTo(x, y, z, yRot, xRot); - player->setPlayerIndex( packet->m_playerIndex ); - player->setCustomSkin( packet->m_skinId ); - player->setCustomCape( packet->m_capeId ); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); - - if(!player->customTextureUrl.empty() && player->customTextureUrl.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl)) - { - if( minecraft->addPendingClientTextureRequest(player->customTextureUrl) ) - { - app.DebugPrintf("Client sending TextureAndGeometryPacket to get custom skin %ls for player %ls\n",player->customTextureUrl.c_str(), player->name.c_str()); + player->setPlayerIndex(packet->m_playerIndex); + player->setCustomSkin(packet->m_skinId); + player->setCustomCape(packet->m_capeId); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + packet->m_uiGamePrivileges); - send(std::shared_ptr( new TextureAndGeometryPacket(player->customTextureUrl,NULL,0) ) ); - } - } - else if(!player->customTextureUrl.empty() && app.IsFileInMemoryTextures(player->customTextureUrl)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl,NULL,0); - } + if (!player->customTextureUrl.empty() && + player->customTextureUrl.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl)) { + if (minecraft->addPendingClientTextureRequest( + player->customTextureUrl)) { + app.DebugPrintf( + "Client sending TextureAndGeometryPacket to get custom skin " + "%ls for player %ls\n", + player->customTextureUrl.c_str(), player->name.c_str()); - app.DebugPrintf("Custom skin for player %ls is %ls\n",player->name.c_str(),player->customTextureUrl.c_str()); - - if(!player->customTextureUrl2.empty() && player->customTextureUrl2.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - if( minecraft->addPendingClientTextureRequest(player->customTextureUrl2) ) - { - app.DebugPrintf("Client sending texture packet to get custom cape %ls for player %ls\n",player->customTextureUrl2.c_str(), player->name.c_str()); - send(std::shared_ptr( new TexturePacket(player->customTextureUrl2,NULL,0) ) ); - } - } - else if(!player->customTextureUrl2.empty() && app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl2,NULL,0); - } + send(std::shared_ptr( + new TextureAndGeometryPacket(player->customTextureUrl, NULL, + 0))); + } + } else if (!player->customTextureUrl.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl, NULL, 0); + } - app.DebugPrintf("Custom cape for player %ls is %ls\n",player->name.c_str(),player->customTextureUrl2.c_str()); + app.DebugPrintf("Custom skin for player %ls is %ls\n", player->name.c_str(), + player->customTextureUrl.c_str()); + + if (!player->customTextureUrl2.empty() && + player->customTextureUrl2.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl2)) { + if (minecraft->addPendingClientTextureRequest( + player->customTextureUrl2)) { + app.DebugPrintf( + "Client sending texture packet to get custom cape %ls for " + "player %ls\n", + player->customTextureUrl2.c_str(), player->name.c_str()); + send(std::shared_ptr( + new TexturePacket(player->customTextureUrl2, NULL, 0))); + } + } else if (!player->customTextureUrl2.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl2)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl2, NULL, 0); + } + + app.DebugPrintf("Custom cape for player %ls is %ls\n", player->name.c_str(), + player->customTextureUrl2.c_str()); level->putEntity(packet->id, player); - std::vector > *unpackedData = packet->getUnpackedData(); - if (unpackedData != NULL) - { - player->getEntityData()->assignValues(unpackedData); - } - + std::vector >* unpackedData = + packet->getUnpackedData(); + if (unpackedData != NULL) { + player->getEntityData()->assignValues(unpackedData); + } } -void ClientConnection::handleTeleportEntity(std::shared_ptr packet) -{ +void ClientConnection::handleTeleportEntity( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; e->xp = packet->x; @@ -829,79 +877,82 @@ void ClientConnection::handleTeleportEntity(std::shared_ptrxp / 32.0; double y = e->yp / 32.0 + 1 / 64.0f; double z = e->zp / 32.0; - // 4J - make sure xRot stays within -90 -> 90 range - int ixRot = packet->xRot; - if( ixRot >= 128 ) ixRot -= 256; + // 4J - make sure xRot stays within -90 -> 90 range + int ixRot = packet->xRot; + if (ixRot >= 128) ixRot -= 256; float yRot = packet->yRot * 360 / 256.0f; float xRot = ixRot * 360 / 256.0f; - e->yRotp = packet->yRot; - e->xRotp = ixRot; + e->yRotp = packet->yRot; + e->xRotp = ixRot; -// printf("\t\t\t\t%d: Teleport to %d (lerp to %f)\n",packet->id,packet->yRot,yRot); + // printf("\t\t\t\t%d: Teleport to %d (lerp to + //%f)\n",packet->id,packet->yRot,yRot); e->lerpTo(x, y, z, yRot, xRot, 3); } -void ClientConnection::handleMoveEntity(std::shared_ptr packet) -{ +void ClientConnection::handleMoveEntity( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; e->xp += packet->xa; e->yp += packet->ya; e->zp += packet->za; double x = e->xp / 32.0; - // 4J - The original code did not add the 1/64.0f like the teleport above did, which caused minecarts to fall through the ground + // 4J - The original code did not add the 1/64.0f like the teleport above + // did, which caused minecarts to fall through the ground double y = e->yp / 32.0 + 1 / 64.0f; double z = e->zp / 32.0; - // 4J - have changed rotation to be relative here too - e->yRotp += packet->yRot; - e->xRotp += packet->xRot; - float yRot = ( e->yRotp * 360 ) / 256.0f; - float xRot = ( e->xRotp * 360 ) / 256.0f; -// float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; -// float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; + // 4J - have changed rotation to be relative here too + e->yRotp += packet->yRot; + e->xRotp += packet->xRot; + float yRot = (e->yRotp * 360) / 256.0f; + float xRot = (e->xRotp * 360) / 256.0f; + // float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; + // float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; e->lerpTo(x, y, z, yRot, xRot, 3); } -void ClientConnection::handleRotateMob(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->id); - if (e == NULL) return; - float yHeadRot = packet->yHeadRot * 360 / 256.f; - e->setYHeadRot(yHeadRot); +void ClientConnection::handleRotateMob( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->id); + if (e == NULL) return; + float yHeadRot = packet->yHeadRot * 360 / 256.f; + e->setYHeadRot(yHeadRot); } -void ClientConnection::handleMoveEntitySmall(std::shared_ptr packet) -{ +void ClientConnection::handleMoveEntitySmall( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; e->xp += packet->xa; e->yp += packet->ya; e->zp += packet->za; double x = e->xp / 32.0; - // 4J - The original code did not add the 1/64.0f like the teleport above did, which caused minecarts to fall through the ground + // 4J - The original code did not add the 1/64.0f like the teleport above + // did, which caused minecarts to fall through the ground double y = e->yp / 32.0 + 1 / 64.0f; double z = e->zp / 32.0; - // 4J - have changed rotation to be relative here too - e->yRotp += packet->yRot; - e->xRotp += packet->xRot; - float yRot = ( e->yRotp * 360 ) / 256.0f; - float xRot = ( e->xRotp * 360 ) / 256.0f; -// float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; -// float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; + // 4J - have changed rotation to be relative here too + e->yRotp += packet->yRot; + e->xRotp += packet->xRot; + float yRot = (e->yRotp * 360) / 256.0f; + float xRot = (e->xRotp * 360) / 256.0f; + // float yRot = packet->hasRot ? packet->yRot * 360 / 256.0f : e->yRot; + // float xRot = packet->hasRot ? packet->xRot * 360 / 256.0f : e->xRot; e->lerpTo(x, y, z, yRot, xRot, 3); } -void ClientConnection::handleRemoveEntity(std::shared_ptr packet) -{ - for (int i = 0; i < packet->ids.length; i++) - { - level->removeEntity(packet->ids[i]); - } +void ClientConnection::handleRemoveEntity( + std::shared_ptr packet) { + for (int i = 0; i < packet->ids.length; i++) { + level->removeEntity(packet->ids[i]); + } } -void ClientConnection::handleMovePlayer(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; //minecraft->player; +void ClientConnection::handleMovePlayer( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; // minecraft->player; double x = player->x; double y = player->y; @@ -909,14 +960,12 @@ void ClientConnection::handleMovePlayer(std::shared_ptr packet float yRot = player->yRot; float xRot = player->xRot; - if (packet->hasPos) - { + if (packet->hasPos) { x = packet->x; y = packet->y; z = packet->z; } - if (packet->hasRot) - { + if (packet->hasRot) { yRot = packet->yRot; xRot = packet->xRot; } @@ -929,2097 +978,2200 @@ void ClientConnection::handleMovePlayer(std::shared_ptr packet packet->z = player->z; packet->yView = player->y; connection->send(packet); - if (!started) - { - - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCConnected * 100)/ (eCCConnected)); - } + if (!started) { + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCConnected * 100) / (eCCConnected)); + } player->xo = player->x; player->yo = player->y; player->zo = player->z; - // 4J - added setting xOld/yOld/zOld here too, as otherwise at the start of the game we interpolate the player position from the origin to wherever its first position really is - player->xOld = player->x; - player->yOld = player->y; - player->zOld = player->z; + // 4J - added setting xOld/yOld/zOld here too, as otherwise at the start + // of the game we interpolate the player position from the origin to + // wherever its first position really is + player->xOld = player->x; + player->yOld = player->y; + player->zOld = player->z; started = true; minecraft->setScreen(NULL); - - // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players are spawned at incorrect places after re-joining previously saved and loaded "Mass Effect World". - // Move this check from Minecraft::createExtraLocalPlayer - // 4J-PB - can't call this when this function is called from the qnet thread (GetGameStarted will be false) - if(app.GetGameStarted()) - { - ui.CloseUIScenes(m_userIndex); - } - } + // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players + // are spawned at incorrect places after re-joining previously saved and + // loaded "Mass Effect World". Move this check from + // Minecraft::createExtraLocalPlayer 4J-PB - can't call this when this + // function is called from the qnet thread (GetGameStarted will be + // false) + if (app.GetGameStarted()) { + ui.CloseUIScenes(m_userIndex); + } + } } // 4J Added -void ClientConnection::handleChunkVisibilityArea(std::shared_ptr packet) -{ - for(int z = packet->m_minZ; z <= packet->m_maxZ; ++z) - for(int x = packet->m_minX; x <= packet->m_maxX; ++x) - level->setChunkVisible(x, z, true); +void ClientConnection::handleChunkVisibilityArea( + std::shared_ptr packet) { + for (int z = packet->m_minZ; z <= packet->m_maxZ; ++z) + for (int x = packet->m_minX; x <= packet->m_maxX; ++x) + level->setChunkVisible(x, z, true); } -void ClientConnection::handleChunkVisibility(std::shared_ptr packet) -{ - level->setChunkVisible(packet->x, packet->z, packet->visible); +void ClientConnection::handleChunkVisibility( + std::shared_ptr packet) { + level->setChunkVisible(packet->x, packet->z, packet->visible); } -void ClientConnection::handleChunkTilesUpdate(std::shared_ptr packet) -{ - // 4J - changed to encode level in packet - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->levels[packet->levelIdx]; - if( dimensionLevel ) - { - PIXBeginNamedEvent(0,"Handle chunk tiles update"); - LevelChunk *lc = dimensionLevel->getChunk(packet->xc, packet->zc); - int xo = packet->xc * 16; - int zo = packet->zc * 16; - // 4J Stu - Unshare before we make any changes incase the server is already another step ahead of us - // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. - // This is quite expensive to do, so only consider unsharing if this tile setting is going to actually - // change something - bool forcedUnshare = false; - for (int i = 0; i < packet->count; i++) - { - int pos = packet->positions[i]; - int tile = packet->blocks[i] & 0xff; - int data = packet->data[i]; +void ClientConnection::handleChunkTilesUpdate( + std::shared_ptr packet) { + // 4J - changed to encode level in packet + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->levels[packet->levelIdx]; + if (dimensionLevel) { + PIXBeginNamedEvent(0, "Handle chunk tiles update"); + LevelChunk* lc = dimensionLevel->getChunk(packet->xc, packet->zc); + int xo = packet->xc * 16; + int zo = packet->zc * 16; + // 4J Stu - Unshare before we make any changes incase the server is + // already another step ahead of us Fix for #7904 - Gameplay: Players + // can dupe torches by throwing them repeatedly into water. This is + // quite expensive to do, so only consider unsharing if this tile + // setting is going to actually change something + bool forcedUnshare = false; + for (int i = 0; i < packet->count; i++) { + int pos = packet->positions[i]; + int tile = packet->blocks[i] & 0xff; + int data = packet->data[i]; + int x = (pos >> 12) & 15; + int z = (pos >> 8) & 15; + int y = ((pos) & 255); - int x = (pos >> 12) & 15; - int z = (pos >> 8) & 15; - int y = ((pos) & 255); + // If this is going to actually change a tile, we'll need to unshare + int prevTile = lc->getTile(x, y, z); + if ((tile != prevTile && !forcedUnshare)) { + PIXBeginNamedEvent(0, "Chunk data unsharing\n"); + dimensionLevel->unshareChunkAt(xo, zo); + PIXEndNamedEvent(); + forcedUnshare = true; + } - // If this is going to actually change a tile, we'll need to unshare - int prevTile = lc->getTile(x, y, z); - if( ( tile != prevTile && !forcedUnshare ) ) - { - PIXBeginNamedEvent(0,"Chunk data unsharing\n"); - dimensionLevel->unshareChunkAt(xo,zo); - PIXEndNamedEvent(); - forcedUnshare = true; - } + // 4J - Changes now that lighting is done at the client side of + // things... Note - the java version now calls the doSetTileAndData + // method from the level here rather than the levelchunk, which + // ultimately ends up calling checkLight for the altered tile. For + // us this doesn't always work as when sharing tile data between a + // local server & client, the tile might not be considered to be + // being changed on the client as the server already has changed the + // shared data, and so the checkLight doesn't happen. Hence doing an + // explicit checkLight here instead. + lc->setTileAndData(x, y, z, tile, data); + dimensionLevel->checkLight(x + xo, y, z + zo); - // 4J - Changes now that lighting is done at the client side of things... - // Note - the java version now calls the doSetTileAndData method from the level here rather than the levelchunk, which ultimately ends up - // calling checkLight for the altered tile. For us this doesn't always work as when sharing tile data between a local server & client, the - // tile might not be considered to be being changed on the client as the server already has changed the shared data, and so the checkLight - // doesn't happen. Hence doing an explicit checkLight here instead. - lc->setTileAndData(x, y, z, tile, data); - dimensionLevel->checkLight(x + xo, y, z + zo); + dimensionLevel->clearResetRegion(x + xo, y, z + zo, x + xo, y, + z + zo); - dimensionLevel->clearResetRegion(x + xo, y, z + zo, x + xo, y, z + zo); + // Don't bother setting this to dirty if it isn't going to visually + // change - we get a lot of water changing from static to dynamic + // for instance + if (!(((prevTile == Tile::water_Id) && + (tile == Tile::calmWater_Id)) || + ((prevTile == Tile::calmWater_Id) && + (tile == Tile::water_Id)) || + ((prevTile == Tile::lava_Id) && + (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && + (tile == Tile::calmLava_Id)) || + ((prevTile == Tile::calmLava_Id) && + (tile == Tile::lava_Id)))) { + dimensionLevel->setTilesDirty(x + xo, y, z + zo, x + xo, y, + z + zo); + } - // Don't bother setting this to dirty if it isn't going to visually change - we get a lot of - // water changing from static to dynamic for instance - if(!( ( ( prevTile == Tile::water_Id ) && ( tile == Tile::calmWater_Id ) ) || - ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || - ( ( prevTile == Tile::lava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::calmLava_Id ) ) || - ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::lava_Id ) ) ) ) - { - dimensionLevel->setTilesDirty(x + xo, y, z + zo, x + xo, y, z + zo); - } + // 4J - remove any tite entities in this region which are associated + // with a tile that is now no longer a tile entity. Without doing + // this we end up with stray tile entities kicking round, which + // leads to a bug where chests can't be properly placed again in a + // location after (say) a chest being removed by TNT + dimensionLevel->removeUnusedTileEntitiesInRegion( + xo + x, y, zo + z, xo + x + 1, y + 1, zo + z + 1); + } + PIXBeginNamedEvent(0, "Chunk data sharing\n"); + dimensionLevel->shareChunkAt(xo, + zo); // 4J - added - only shares if chunks + // are same on server & client + PIXEndNamedEvent(); - // 4J - remove any tite entities in this region which are associated with a tile that is now no longer a tile entity. Without doing this we end up with stray - // tile entities kicking round, which leads to a bug where chests can't be properly placed again in a location after (say) a chest being removed by TNT - dimensionLevel->removeUnusedTileEntitiesInRegion(xo + x, y, zo + z, xo + x+1, y+1, zo + z+1); - } - PIXBeginNamedEvent(0,"Chunk data sharing\n"); - dimensionLevel->shareChunkAt(xo,zo); // 4J - added - only shares if chunks are same on server & client - PIXEndNamedEvent(); - - PIXEndNamedEvent(); - } + PIXEndNamedEvent(); + } } -void ClientConnection::handleBlockRegionUpdate(std::shared_ptr packet) -{ - // 4J - changed to encode level in packet - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->levels[packet->levelIdx]; - if( dimensionLevel ) - { - PIXBeginNamedEvent(0,"Handle block region update"); +void ClientConnection::handleBlockRegionUpdate( + std::shared_ptr packet) { + // 4J - changed to encode level in packet + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->levels[packet->levelIdx]; + if (dimensionLevel) { + PIXBeginNamedEvent(0, "Handle block region update"); - int y1 = packet->y + packet->ys; - if(packet->bIsFullChunk) - { - y1 = Level::maxBuildHeight; - if(packet->buffer.length > 0) LevelChunk::reorderBlocksAndDataToXZY(packet->y, packet->xs, packet->ys, packet->zs, &packet->buffer); - } - dimensionLevel->clearResetRegion(packet->x, packet->y, packet->z, packet->x + packet->xs - 1, y1 - 1, packet->z + packet->zs - 1); + int y1 = packet->y + packet->ys; + if (packet->bIsFullChunk) { + y1 = Level::maxBuildHeight; + if (packet->buffer.length > 0) + LevelChunk::reorderBlocksAndDataToXZY(packet->y, packet->xs, + packet->ys, packet->zs, + &packet->buffer); + } + dimensionLevel->clearResetRegion(packet->x, packet->y, packet->z, + packet->x + packet->xs - 1, y1 - 1, + packet->z + packet->zs - 1); - // Only full chunks send lighting information now - added flag to end of this call - dimensionLevel->setBlocksAndData(packet->x, packet->y, packet->z, packet->xs, packet->ys, packet->zs, packet->buffer, packet->bIsFullChunk); + // Only full chunks send lighting information now - added flag to end of + // this call + dimensionLevel->setBlocksAndData(packet->x, packet->y, packet->z, + packet->xs, packet->ys, packet->zs, + packet->buffer, packet->bIsFullChunk); -// OutputDebugString("END BRU\n"); + // OutputDebugString("END BRU\n"); - // 4J - remove any tite entities in this region which are associated with a tile that is now no longer a tile entity. Without doing this we end up with stray - // tile entities kicking round, which leads to a bug where chests can't be properly placed again in a location after (say) a chest being removed by TNT - dimensionLevel->removeUnusedTileEntitiesInRegion(packet->x, packet->y, packet->z, packet->x + packet->xs, y1, packet->z + packet->zs ); + // 4J - remove any tite entities in this region which are associated + // with a tile that is now no longer a tile entity. Without doing this + // we end up with stray tile entities kicking round, which leads to a + // bug where chests can't be properly placed again in a location after + // (say) a chest being removed by TNT + dimensionLevel->removeUnusedTileEntitiesInRegion( + packet->x, packet->y, packet->z, packet->x + packet->xs, y1, + packet->z + packet->zs); - // If this is a full packet for a chunk, make sure that the cache now considers that it has data for this chunk - this is used to determine whether to bother - // rendering mobs or not, so we don't have them in crazy positions before the data is there - if( packet->bIsFullChunk ) - { - dimensionLevel->dataReceivedForChunk( packet->x >> 4, packet->z >> 4 ); - } - PIXEndNamedEvent(); - } + // If this is a full packet for a chunk, make sure that the cache now + // considers that it has data for this chunk - this is used to determine + // whether to bother rendering mobs or not, so we don't have them in + // crazy positions before the data is there + if (packet->bIsFullChunk) { + dimensionLevel->dataReceivedForChunk(packet->x >> 4, + packet->z >> 4); + } + PIXEndNamedEvent(); + } } -void ClientConnection::handleTileUpdate(std::shared_ptr packet) -{ - // 4J added - using a block of 255 to signify that this is a packet for destroying a tile, where we need to inform the level renderer that we are about to do so. - // This is used in creative mode as the point where a tile is first destroyed at the client end of things. Packets formed like this are potentially sent from - // ServerPlayerGameMode::destroyBlock - bool destroyTilePacket = false; - if( packet->block == 255 ) - { - packet->block = 0; - destroyTilePacket = true; - } - // 4J - changed to encode level in packet - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->levels[packet->levelIdx]; - if( dimensionLevel ) - { - PIXBeginNamedEvent(0,"Handle tile update"); +void ClientConnection::handleTileUpdate( + std::shared_ptr packet) { + // 4J added - using a block of 255 to signify that this is a packet for + // destroying a tile, where we need to inform the level renderer that we are + // about to do so. This is used in creative mode as the point where a tile + // is first destroyed at the client end of things. Packets formed like this + // are potentially sent from ServerPlayerGameMode::destroyBlock + bool destroyTilePacket = false; + if (packet->block == 255) { + packet->block = 0; + destroyTilePacket = true; + } + // 4J - changed to encode level in packet + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->levels[packet->levelIdx]; + if (dimensionLevel) { + PIXBeginNamedEvent(0, "Handle tile update"); - if( g_NetworkManager.IsHost() ) - { - // 4J Stu - Unshare before we make any changes incase the server is already another step ahead of us - // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. - // This is quite expensive to do, so only consider unsharing if this tile setting is going to actually - // change something - int prevTile = dimensionLevel->getTile(packet->x, packet->y, packet->z); - int prevData = dimensionLevel->getData(packet->x, packet->y, packet->z); - if( packet->block != prevTile || packet->data != prevData ) - { - PIXBeginNamedEvent(0,"Chunk data unsharing\n"); - dimensionLevel->unshareChunkAt(packet->x,packet->z); - PIXEndNamedEvent(); - } - } + if (g_NetworkManager.IsHost()) { + // 4J Stu - Unshare before we make any changes incase the server is + // already another step ahead of us Fix for #7904 - Gameplay: + // Players can dupe torches by throwing them repeatedly into water. + // This is quite expensive to do, so only consider unsharing if this + // tile setting is going to actually change something + int prevTile = + dimensionLevel->getTile(packet->x, packet->y, packet->z); + int prevData = + dimensionLevel->getData(packet->x, packet->y, packet->z); + if (packet->block != prevTile || packet->data != prevData) { + PIXBeginNamedEvent(0, "Chunk data unsharing\n"); + dimensionLevel->unshareChunkAt(packet->x, packet->z); + PIXEndNamedEvent(); + } + } - // 4J - In creative mode, we don't update the tile locally then get it confirmed by the server - the first point that we know we are about to destroy a tile is here. Let - // the rendering side of thing know so we can synchronise collision with async render data upates. - if( destroyTilePacket ) - { - minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(dimensionLevel, packet->x, packet->y, packet->z); - } + // 4J - In creative mode, we don't update the tile locally then get it + // confirmed by the server - the first point that we know we are about + // to destroy a tile is here. Let the rendering side of thing know so we + // can synchronise collision with async render data upates. + if (destroyTilePacket) { + minecraft->levelRenderer->destroyedTileManager->destroyingTileAt( + dimensionLevel, packet->x, packet->y, packet->z); + } - PIXBeginNamedEvent(0,"Setting data\n"); - bool tileWasSet = dimensionLevel->doSetTileAndData(packet->x, packet->y, packet->z, packet->block, packet->data); + PIXBeginNamedEvent(0, "Setting data\n"); + bool tileWasSet = dimensionLevel->doSetTileAndData( + packet->x, packet->y, packet->z, packet->block, packet->data); - PIXEndNamedEvent(); + PIXEndNamedEvent(); - // 4J - remove any tite entities in this region which are associated with a tile that is now no longer a tile entity. Without doing this we end up with stray - // tile entities kicking round, which leads to a bug where chests can't be properly placed again in a location after (say) a chest being removed by TNT - dimensionLevel->removeUnusedTileEntitiesInRegion(packet->x, packet->y, packet->z, packet->x+1, packet->y+1, packet->z+1 ); + // 4J - remove any tite entities in this region which are associated + // with a tile that is now no longer a tile entity. Without doing this + // we end up with stray tile entities kicking round, which leads to a + // bug where chests can't be properly placed again in a location after + // (say) a chest being removed by TNT + dimensionLevel->removeUnusedTileEntitiesInRegion( + packet->x, packet->y, packet->z, packet->x + 1, packet->y + 1, + packet->z + 1); - PIXBeginNamedEvent(0,"Sharing data\n"); - dimensionLevel->shareChunkAt(packet->x,packet->z); // 4J - added - only shares if chunks are same on server & client - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Sharing data\n"); + dimensionLevel->shareChunkAt( + packet->x, packet->z); // 4J - added - only shares if chunks are + // same on server & client + PIXEndNamedEvent(); - PIXEndNamedEvent(); - } + PIXEndNamedEvent(); + } } -void ClientConnection::handleDisconnect(std::shared_ptr packet) -{ +void ClientConnection::handleDisconnect( + std::shared_ptr packet) { #ifdef __linux__ - // Linux fix: On local host connections, ignore DisconnectPacket. The singleplayer internal - // server should never disconnect itself. If we see this, it's likely stream desync reading - // garbage data as a DisconnectPacket. - if (connection && connection->getSocket() && connection->getSocket()->isLocal()) { - fprintf(stderr, "[CONN] Ignoring DisconnectPacket on local connection (reason=%d)\n", packet->reason); - return; - } + // Linux fix: On local host connections, ignore DisconnectPacket. The + // singleplayer internal server should never disconnect itself. If we see + // this, it's likely stream desync reading garbage data as a + // DisconnectPacket. + if (connection && connection->getSocket() && + connection->getSocket()->isLocal()) { + fprintf(stderr, + "[CONN] Ignoring DisconnectPacket on local connection " + "(reason=%d)\n", + packet->reason); + return; + } #endif - connection->close(DisconnectPacket::eDisconnect_Kicked); + connection->close(DisconnectPacket::eDisconnect_Kicked); done = true; - - Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->connectionDisconnected( m_userIndex , packet->reason ); - app.SetDisconnectReason( packet->reason ); - app.SetAction(m_userIndex,eAppAction_ExitWorld,(void *)TRUE); - //minecraft->setLevel(NULL); - //minecraft->setScreen(new DisconnectedScreen(L"disconnect.disconnected", L"disconnect.genericReason", &packet->reason)); + Minecraft* pMinecraft = Minecraft::GetInstance(); + pMinecraft->connectionDisconnected(m_userIndex, packet->reason); + app.SetDisconnectReason(packet->reason); + app.SetAction(m_userIndex, eAppAction_ExitWorld, (void*)TRUE); + // minecraft->setLevel(NULL); + // minecraft->setScreen(new DisconnectedScreen(L"disconnect.disconnected", + // L"disconnect.genericReason", &packet->reason)); } -void ClientConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) -{ +void ClientConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects) { if (done) return; done = true; - Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->connectionDisconnected( m_userIndex , reason ); + Minecraft* pMinecraft = Minecraft::GetInstance(); + pMinecraft->connectionDisconnected(m_userIndex, reason); - // 4J Stu - TU-1 hotfix - // Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost - // In the (now unlikely) event that the host connections times out, allow the player to save their game - if(g_NetworkManager.IsHost() && - (reason == DisconnectPacket::eDisconnect_TimeOut || reason == DisconnectPacket::eDisconnect_Overflow) && - m_userIndex == ProfileManager.GetPrimaryPad() && - !MinecraftServer::saveOnExitAnswered() ) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_EXITING_GAME, IDS_GENERIC_ERROR, uiIDA, 1, ProfileManager.GetPrimaryPad(),&ClientConnection::HostDisconnectReturned,NULL, app.GetStringTable()); - } - else - { - app.SetAction(m_userIndex,eAppAction_ExitWorld,(void *)TRUE); - } + // 4J Stu - TU-1 hotfix + // Fix for #13191 - The host of a game can get a message informing them that + // the connection to the server has been lost In the (now unlikely) event + // that the host connections times out, allow the player to save their game + if (g_NetworkManager.IsHost() && + (reason == DisconnectPacket::eDisconnect_TimeOut || + reason == DisconnectPacket::eDisconnect_Overflow) && + m_userIndex == ProfileManager.GetPrimaryPad() && + !MinecraftServer::saveOnExitAnswered()) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_EXITING_GAME, IDS_GENERIC_ERROR, uiIDA, 1, + ProfileManager.GetPrimaryPad(), + &ClientConnection::HostDisconnectReturned, NULL, + app.GetStringTable()); + } else { + app.SetAction(m_userIndex, eAppAction_ExitWorld, (void*)TRUE); + } - //minecraft->setLevel(NULL); - //minecraft->setScreen(new DisconnectedScreen(L"disconnect.lost", reason, reasonObjects)); + // minecraft->setLevel(NULL); + // minecraft->setScreen(new DisconnectedScreen(L"disconnect.lost", reason, + // reasonObjects)); } -void ClientConnection::sendAndDisconnect(std::shared_ptr packet) -{ +void ClientConnection::sendAndDisconnect(std::shared_ptr packet) { if (done) return; connection->send(packet); connection->sendAndQuit(); } -void ClientConnection::send(std::shared_ptr packet) -{ +void ClientConnection::send(std::shared_ptr packet) { if (done) return; connection->send(packet); } -void ClientConnection::handleTakeItemEntity(std::shared_ptr packet) -{ +void ClientConnection::handleTakeItemEntity( + std::shared_ptr packet) { std::shared_ptr from = getEntity(packet->itemId); - std::shared_ptr to = std::dynamic_pointer_cast(getEntity(packet->playerId)); + std::shared_ptr to = + std::dynamic_pointer_cast(getEntity(packet->playerId)); - // 4J - the original game could assume that if getEntity didn't find the player, it must be the local player. We - // need to search all local players - bool isLocalPlayer = false; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->playerId ) - { - isLocalPlayer = true; - to = minecraft->localplayers[i]; - break; - } - } - } + // 4J - the original game could assume that if getEntity didn't find the + // player, it must be the local player. We need to search all local players + bool isLocalPlayer = false; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == packet->playerId) { + isLocalPlayer = true; + to = minecraft->localplayers[i]; + break; + } + } + } - if (to == NULL) - { - // Don't know if this should ever really happen, but seems safest to try and remove the entity that has been collected even if we can't - // create a particle as we don't know what really collected it - level->removeEntity(packet->itemId); + if (to == NULL) { + // Don't know if this should ever really happen, but seems safest to try + // and remove the entity that has been collected even if we can't create + // a particle as we don't know what really collected it + level->removeEntity(packet->itemId); return; } - if (from != NULL) - { - // If this is a local player, then we only want to do processing for it if this connection is associated with the player it is for. In - // particular, we don't want to remove the item entity until we are processing it for the right connection, or else we won't have a valid - // "from" reference if we've already removed the item for an earlier processed connection - if( isLocalPlayer ) - { - std::shared_ptr player = std::dynamic_pointer_cast(to); + if (from != NULL) { + // If this is a local player, then we only want to do processing for it + // if this connection is associated with the player it is for. In + // particular, we don't want to remove the item entity until we are + // processing it for the right connection, or else we won't have a valid + // "from" reference if we've already removed the item for an earlier + // processed connection + if (isLocalPlayer) { + std::shared_ptr player = + std::dynamic_pointer_cast(to); - // 4J Stu - Fix for #10213 - UI: Local clients cannot progress through the tutorial normally. - // We only send this packet once if many local players can see the event, so make sure we update - // the tutorial for the player that actually picked up the item - int playerPad = player->GetXboxPad(); + // 4J Stu - Fix for #10213 - UI: Local clients cannot progress + // through the tutorial normally. We only send this packet once if + // many local players can see the event, so make sure we update the + // tutorial for the player that actually picked up the item + int playerPad = player->GetXboxPad(); - if( minecraft->localgameModes[playerPad] != NULL ) - { - // 4J-PB - add in the XP orb sound - if(from->GetType() == eTYPE_EXPERIENCEORB) - { - float fPitch=((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f; - app.DebugPrintf("XP Orb with pitch %f\n",fPitch); - level->playSound(from, eSoundType_RANDOM_ORB, 0.2f, fPitch); - } - else - { - level->playSound(from, eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); - } + if (minecraft->localgameModes[playerPad] != NULL) { + // 4J-PB - add in the XP orb sound + if (from->GetType() == eTYPE_EXPERIENCEORB) { + float fPitch = + ((random->nextFloat() - random->nextFloat()) * 0.7f + + 1.0f) * + 2.0f; + app.DebugPrintf("XP Orb with pitch %f\n", fPitch); + level->playSound(from, eSoundType_RANDOM_ORB, 0.2f, fPitch); + } else { + level->playSound( + from, eSoundType_RANDOM_POP, 0.2f, + ((random->nextFloat() - random->nextFloat()) * 0.7f + + 1.0f) * + 2.0f); + } - minecraft->particleEngine->add( std::shared_ptr( new TakeAnimationParticle(minecraft->level, from, to, -0.5f) ) ); - level->removeEntity(packet->itemId); - } - else - { - // Don't know if this should ever really happen, but seems safest to try and remove the entity that has been collected even if it - // somehow isn't an itementity - level->removeEntity(packet->itemId); - } - } - else - { - level->playSound(from, eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); - minecraft->particleEngine->add( std::shared_ptr( new TakeAnimationParticle(minecraft->level, from, to, -0.5f) ) ); - level->removeEntity(packet->itemId); - } + minecraft->particleEngine->add( + std::shared_ptr( + new TakeAnimationParticle(minecraft->level, from, to, + -0.5f))); + level->removeEntity(packet->itemId); + } else { + // Don't know if this should ever really happen, but seems + // safest to try and remove the entity that has been collected + // even if it somehow isn't an itementity + level->removeEntity(packet->itemId); + } + } else { + level->playSound( + from, eSoundType_RANDOM_POP, 0.2f, + ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * + 2.0f); + minecraft->particleEngine->add( + std::shared_ptr( + new TakeAnimationParticle(minecraft->level, from, to, + -0.5f))); + level->removeEntity(packet->itemId); + } + } +} + +void ClientConnection::handleChat(std::shared_ptr packet) { + std::wstring message; + int iPos; + bool displayOnGui = true; + + std::wstring playerDisplayName = L""; + std::wstring sourceDisplayName = L""; + + // On platforms other than Xbox One this just sets display name to gamertag + if (packet->m_stringArgs.size() >= 1) + playerDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[0]); + if (packet->m_stringArgs.size() >= 2) + sourceDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[1]); + + switch (packet->m_messageType) { + case ChatPacket::e_ChatBedOccupied: + message = app.GetString(IDS_TILE_BED_OCCUPIED); + break; + case ChatPacket::e_ChatBedNoSleep: + message = app.GetString(IDS_TILE_BED_NO_SLEEP); + break; + case ChatPacket::e_ChatBedNotValid: + message = app.GetString(IDS_TILE_BED_NOT_VALID); + break; + case ChatPacket::e_ChatBedNotSafe: + message = app.GetString(IDS_TILE_BED_NOTSAFE); + break; + case ChatPacket::e_ChatBedPlayerSleep: + message = app.GetString(IDS_TILE_BED_PLAYERSLEEP); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatBedMeSleep: + message = app.GetString(IDS_TILE_BED_MESLEEP); + break; + case ChatPacket::e_ChatPlayerJoinedGame: + message = app.GetString(IDS_PLAYER_JOINED); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatPlayerLeftGame: + message = app.GetString(IDS_PLAYER_LEFT); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatPlayerKickedFromGame: + message = app.GetString(IDS_PLAYER_KICKED); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatCannotPlaceLava: + displayOnGui = false; + app.SetGlobalXuiAction(eAppAction_DisplayLavaMessage); + break; + case ChatPacket::e_ChatDeathInFire: + message = app.GetString(IDS_DEATH_INFIRE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathOnFire: + message = app.GetString(IDS_DEATH_ONFIRE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathLava: + message = app.GetString(IDS_DEATH_LAVA); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathInWall: + message = app.GetString(IDS_DEATH_INWALL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathDrown: + message = app.GetString(IDS_DEATH_DROWN); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathStarve: + message = app.GetString(IDS_DEATH_STARVE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathCactus: + message = app.GetString(IDS_DEATH_CACTUS); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathFall: + message = app.GetString(IDS_DEATH_FALL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathOutOfWorld: + message = app.GetString(IDS_DEATH_OUTOFWORLD); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathGeneric: + message = app.GetString(IDS_DEATH_GENERIC); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathExplosion: + message = app.GetString(IDS_DEATH_EXPLOSION); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathMagic: + message = app.GetString(IDS_DEATH_MAGIC); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathAnvil: + message = app.GetString(IDS_DEATH_FALLING_ANVIL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathFallingBlock: + message = app.GetString(IDS_DEATH_FALLING_TILE); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathDragonBreath: + message = app.GetString(IDS_DEATH_DRAGON_BREATH); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatDeathMob: + message = app.GetString(IDS_DEATH_MOB); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + break; + case ChatPacket::e_ChatDeathPlayer: + message = app.GetString(IDS_DEATH_PLAYER); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + break; + case ChatPacket::e_ChatDeathArrow: + message = app.GetString(IDS_DEATH_ARROW); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathFireball: + message = app.GetString(IDS_DEATH_FIREBALL); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = + replaceAll(message, L"{*SOURCE*}", packet->m_stringArgs[1]); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathThrown: + message = app.GetString(IDS_DEATH_THROWN); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathIndirectMagic: + message = app.GetString(IDS_DEATH_INDIRECT_MAGIC); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatDeathThorns: + message = app.GetString(IDS_DEATH_THORNS); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*SOURCE*}", sourceDisplayName); + } else { + message = replaceAll( + message, L"{*SOURCE*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatPlayerEnteredEnd: + message = app.GetString(IDS_PLAYER_ENTERED_END); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + case ChatPacket::e_ChatPlayerLeftEnd: + message = app.GetString(IDS_PLAYER_LEFT_END); + iPos = message.find(L"%s"); + message.replace(iPos, 2, playerDisplayName); + break; + + case ChatPacket::e_ChatPlayerMaxEnemies: + message = app.GetString(IDS_MAX_ENEMIES_SPAWNED); + break; + // Spawn eggs + case ChatPacket::e_ChatPlayerMaxVillagers: + message = app.GetString(IDS_MAX_VILLAGERS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxPigsSheepCows: + message = app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxChickens: + message = app.GetString(IDS_MAX_CHICKENS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxSquid: + message = app.GetString(IDS_MAX_SQUID_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxMooshrooms: + message = app.GetString(IDS_MAX_MOOSHROOMS_SPAWNED); + break; + case ChatPacket::e_ChatPlayerMaxWolves: + message = app.GetString(IDS_MAX_WOLVES_SPAWNED); + break; + + // Breeding + case ChatPacket::e_ChatPlayerMaxBredPigsSheepCows: + message = app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED); + break; + case ChatPacket::e_ChatPlayerMaxBredChickens: + message = app.GetString(IDS_MAX_CHICKENS_BRED); + break; + case ChatPacket::e_ChatPlayerMaxBredMooshrooms: + message = app.GetString(IDS_MAX_MUSHROOMCOWS_BRED); + break; + + case ChatPacket::e_ChatPlayerMaxBredWolves: + message = app.GetString(IDS_MAX_WOLVES_BRED); + break; + + // can't shear the mooshroom + case ChatPacket::e_ChatPlayerCantShearMooshroom: + message = app.GetString(IDS_CANT_SHEAR_MOOSHROOM); + break; + + // Paintings/Item Frames + case ChatPacket::e_ChatPlayerMaxHangingEntities: + message = app.GetString(IDS_MAX_HANGINGENTITIES); + break; + // Enemy spawn eggs in peaceful + case ChatPacket::e_ChatPlayerCantSpawnInPeaceful: + message = app.GetString(IDS_CANT_SPAWN_IN_PEACEFUL); + break; + + // Enemy spawn eggs in peaceful + case ChatPacket::e_ChatPlayerMaxBoats: + message = app.GetString(IDS_MAX_BOATS); + break; + + case ChatPacket::e_ChatCommandTeleportSuccess: + message = app.GetString(IDS_COMMAND_TELEPORT_SUCCESS); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + if (packet->m_intArgs[0] == eTYPE_SERVERPLAYER) { + message = replaceAll(message, L"{*DESTINATION*}", + packet->m_stringArgs[1]); + } else { + message = replaceAll( + message, L"{*DESTINATION*}", + app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); + } + break; + case ChatPacket::e_ChatCommandTeleportMe: + message = app.GetString(IDS_COMMAND_TELEPORT_ME); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + case ChatPacket::e_ChatCommandTeleportToMe: + message = app.GetString(IDS_COMMAND_TELEPORT_TO_ME); + message = replaceAll(message, L"{*PLAYER*}", playerDisplayName); + break; + + default: + message = playerDisplayName; + break; } + // flag that a message is a death message + bool bIsDeathMessage = + (packet->m_messageType >= ChatPacket::e_ChatDeathInFire) && + (packet->m_messageType <= ChatPacket::e_ChatDeathDragonBreath); + + if (displayOnGui) + minecraft->gui->addMessage(message, m_userIndex, bIsDeathMessage); } -void ClientConnection::handleChat(std::shared_ptr packet) -{ - std::wstring message; - int iPos; - bool displayOnGui = true; - - std::wstring playerDisplayName = L""; - std::wstring sourceDisplayName = L""; - - // On platforms other than Xbox One this just sets display name to gamertag - if (packet->m_stringArgs.size() >= 1) playerDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[0]); - if (packet->m_stringArgs.size() >= 2) sourceDisplayName = GetDisplayNameByGamertag(packet->m_stringArgs[1]); - - switch(packet->m_messageType) - { - case ChatPacket::e_ChatBedOccupied: - message = app.GetString(IDS_TILE_BED_OCCUPIED); - break; - case ChatPacket::e_ChatBedNoSleep: - message = app.GetString(IDS_TILE_BED_NO_SLEEP); - break; - case ChatPacket::e_ChatBedNotValid: - message = app.GetString(IDS_TILE_BED_NOT_VALID); - break; - case ChatPacket::e_ChatBedNotSafe: - message = app.GetString(IDS_TILE_BED_NOTSAFE); - break; - case ChatPacket::e_ChatBedPlayerSleep: - message=app.GetString(IDS_TILE_BED_PLAYERSLEEP); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatBedMeSleep: - message=app.GetString(IDS_TILE_BED_MESLEEP); - break; - case ChatPacket::e_ChatPlayerJoinedGame: - message=app.GetString(IDS_PLAYER_JOINED); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatPlayerLeftGame: - message=app.GetString(IDS_PLAYER_LEFT); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatPlayerKickedFromGame: - message=app.GetString(IDS_PLAYER_KICKED); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatCannotPlaceLava: - displayOnGui = false; - app.SetGlobalXuiAction(eAppAction_DisplayLavaMessage); - break; - case ChatPacket::e_ChatDeathInFire: - message=app.GetString(IDS_DEATH_INFIRE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathOnFire: - message=app.GetString(IDS_DEATH_ONFIRE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathLava: - message=app.GetString(IDS_DEATH_LAVA); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathInWall: - message=app.GetString(IDS_DEATH_INWALL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathDrown: - message=app.GetString(IDS_DEATH_DROWN); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathStarve: - message=app.GetString(IDS_DEATH_STARVE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathCactus: - message=app.GetString(IDS_DEATH_CACTUS); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathFall: - message=app.GetString(IDS_DEATH_FALL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathOutOfWorld: - message=app.GetString(IDS_DEATH_OUTOFWORLD); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathGeneric: - message=app.GetString(IDS_DEATH_GENERIC); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathExplosion: - message=app.GetString(IDS_DEATH_EXPLOSION); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathMagic: - message=app.GetString(IDS_DEATH_MAGIC); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathAnvil: - message=app.GetString(IDS_DEATH_FALLING_ANVIL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathFallingBlock: - message=app.GetString(IDS_DEATH_FALLING_TILE); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathDragonBreath: - message=app.GetString(IDS_DEATH_DRAGON_BREATH); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatDeathMob: - message=app.GetString(IDS_DEATH_MOB); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - break; - case ChatPacket::e_ChatDeathPlayer: - message=app.GetString(IDS_DEATH_PLAYER); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - break; - case ChatPacket::e_ChatDeathArrow: - message=app.GetString(IDS_DEATH_ARROW); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathFireball: - message=app.GetString(IDS_DEATH_FIREBALL); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",packet->m_stringArgs[1]); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathThrown: - message=app.GetString(IDS_DEATH_THROWN); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathIndirectMagic: - message=app.GetString(IDS_DEATH_INDIRECT_MAGIC); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatDeathThorns: - message=app.GetString(IDS_DEATH_THORNS); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*SOURCE*}",sourceDisplayName); - } - else - { - message = replaceAll(message,L"{*SOURCE*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatPlayerEnteredEnd: - message=app.GetString(IDS_PLAYER_ENTERED_END); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - case ChatPacket::e_ChatPlayerLeftEnd: - message=app.GetString(IDS_PLAYER_LEFT_END); - iPos=message.find(L"%s"); - message.replace(iPos,2,playerDisplayName); - break; - - case ChatPacket::e_ChatPlayerMaxEnemies: - message=app.GetString(IDS_MAX_ENEMIES_SPAWNED); - break; - // Spawn eggs - case ChatPacket::e_ChatPlayerMaxVillagers: - message=app.GetString(IDS_MAX_VILLAGERS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxPigsSheepCows: - message=app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxChickens: - message=app.GetString(IDS_MAX_CHICKENS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxSquid: - message=app.GetString(IDS_MAX_SQUID_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxMooshrooms: - message=app.GetString(IDS_MAX_MOOSHROOMS_SPAWNED); - break; - case ChatPacket::e_ChatPlayerMaxWolves: - message=app.GetString(IDS_MAX_WOLVES_SPAWNED); - break; - - // Breeding - case ChatPacket::e_ChatPlayerMaxBredPigsSheepCows: - message=app.GetString(IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED); - break; - case ChatPacket::e_ChatPlayerMaxBredChickens: - message=app.GetString(IDS_MAX_CHICKENS_BRED); - break; - case ChatPacket::e_ChatPlayerMaxBredMooshrooms: - message=app.GetString(IDS_MAX_MUSHROOMCOWS_BRED); - break; - - case ChatPacket::e_ChatPlayerMaxBredWolves: - message=app.GetString(IDS_MAX_WOLVES_BRED); - break; - - // can't shear the mooshroom - case ChatPacket::e_ChatPlayerCantShearMooshroom: - message=app.GetString(IDS_CANT_SHEAR_MOOSHROOM); - break; - - // Paintings/Item Frames - case ChatPacket::e_ChatPlayerMaxHangingEntities: - message=app.GetString(IDS_MAX_HANGINGENTITIES); - break; - // Enemy spawn eggs in peaceful - case ChatPacket::e_ChatPlayerCantSpawnInPeaceful: - message=app.GetString(IDS_CANT_SPAWN_IN_PEACEFUL); - break; - - // Enemy spawn eggs in peaceful - case ChatPacket::e_ChatPlayerMaxBoats: - message=app.GetString(IDS_MAX_BOATS); - break; - - case ChatPacket::e_ChatCommandTeleportSuccess: - message=app.GetString(IDS_COMMAND_TELEPORT_SUCCESS); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - if(packet->m_intArgs[0] == eTYPE_SERVERPLAYER) - { - message = replaceAll(message,L"{*DESTINATION*}",packet->m_stringArgs[1]); - } - else - { - message = replaceAll(message,L"{*DESTINATION*}",app.getEntityName((eINSTANCEOF)packet->m_intArgs[0])); - } - break; - case ChatPacket::e_ChatCommandTeleportMe: - message=app.GetString(IDS_COMMAND_TELEPORT_ME); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - case ChatPacket::e_ChatCommandTeleportToMe: - message=app.GetString(IDS_COMMAND_TELEPORT_TO_ME); - message = replaceAll(message,L"{*PLAYER*}",playerDisplayName); - break; - - default: - message = playerDisplayName; - break; - } - - // flag that a message is a death message - bool bIsDeathMessage = (packet->m_messageType>=ChatPacket::e_ChatDeathInFire) && (packet->m_messageType<=ChatPacket::e_ChatDeathDragonBreath); - - if( displayOnGui ) minecraft->gui->addMessage(message,m_userIndex, bIsDeathMessage); -} - -void ClientConnection::handleAnimate(std::shared_ptr packet) -{ +void ClientConnection::handleAnimate(std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; - if (packet->action == AnimatePacket::SWING) - { + if (packet->action == AnimatePacket::SWING) { std::shared_ptr player = std::dynamic_pointer_cast(e); - if(player != NULL) player->swing(); - } - else if (packet->action == AnimatePacket::HURT) - { + if (player != NULL) player->swing(); + } else if (packet->action == AnimatePacket::HURT) { e->animateHurt(); - } - else if (packet->action == AnimatePacket::WAKE_UP) - { + } else if (packet->action == AnimatePacket::WAKE_UP) { std::shared_ptr player = std::dynamic_pointer_cast(e); - if(player != NULL) player->stopSleepInBed(false, false, false); + if (player != NULL) player->stopSleepInBed(false, false, false); + } else if (packet->action == AnimatePacket::RESPAWN) { + } else if (packet->action == AnimatePacket::CRITICAL_HIT) { + std::shared_ptr critParticle = + std::shared_ptr( + new CritParticle(minecraft->level, e)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); + } else if (packet->action == AnimatePacket::MAGIC_CRITICAL_HIT) { + std::shared_ptr critParticle = + std::shared_ptr( + new CritParticle(minecraft->level, e, eParticleType_magicCrit)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); + } else if (packet->action == AnimatePacket::EAT && + std::dynamic_pointer_cast(e) != NULL) { } - else if (packet->action == AnimatePacket::RESPAWN) - { - } - else if (packet->action == AnimatePacket::CRITICAL_HIT) - { - std::shared_ptr critParticle = std::shared_ptr( new CritParticle(minecraft->level, e) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add( critParticle ); - } - else if (packet->action == AnimatePacket::MAGIC_CRITICAL_HIT) - { - std::shared_ptr critParticle = std::shared_ptr( new CritParticle(minecraft->level, e, eParticleType_magicCrit) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add(critParticle); - } - else if (packet->action == AnimatePacket::EAT && std::dynamic_pointer_cast(e) != NULL) - { - } - } -void ClientConnection::handleEntityActionAtPosition(std::shared_ptr packet) -{ +void ClientConnection::handleEntityActionAtPosition( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->id); if (e == NULL) return; - if (packet->action == EntityActionAtPositionPacket::START_SLEEP) - { + if (packet->action == EntityActionAtPositionPacket::START_SLEEP) { std::shared_ptr player = std::dynamic_pointer_cast(e); player->startSleepInBed(packet->x, packet->y, packet->z); - if( player == minecraft->localplayers[m_userIndex] ) - { - TelemetryManager->RecordEnemyKilledOrOvercome(m_userIndex, 0, player->y, 0, 0, 0, 0, eTelemetryInGame_UseBed); - } + if (player == minecraft->localplayers[m_userIndex]) { + TelemetryManager->RecordEnemyKilledOrOvercome( + m_userIndex, 0, player->y, 0, 0, 0, 0, eTelemetryInGame_UseBed); + } } } -void ClientConnection::handlePreLogin(std::shared_ptr packet) -{ - fprintf(stderr, "[LOGIN-CLI] handlePreLogin entered, isHost=%d, userIdx=%d\n", (int)g_NetworkManager.IsHost(), m_userIndex); +void ClientConnection::handlePreLogin(std::shared_ptr packet) { + fprintf(stderr, + "[LOGIN-CLI] handlePreLogin entered, isHost=%d, userIdx=%d\n", + (int)g_NetworkManager.IsHost(), m_userIndex); #if 1 - // 4J - Check that we can play with all the players already in the game who have Friends-Only UGC set - bool canPlay = true; - bool canPlayLocal = true; - bool isAtLeastOneFriend = g_NetworkManager.IsHost(); - bool isFriendsWithHost = true; - bool cantPlayContentRestricted = false; - - if(!g_NetworkManager.IsHost()) - { - // set the game host settings - app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings); + // 4J - Check that we can play with all the players already in the game who + // have Friends-Only UGC set + bool canPlay = true; + bool canPlayLocal = true; + bool isAtLeastOneFriend = g_NetworkManager.IsHost(); + bool isFriendsWithHost = true; + bool cantPlayContentRestricted = false; - // 4J-PB - if we go straight in from the menus via an invite, we won't have the DLC info - if(app.GetTMSGlobalFileListRead()==false) - { - app.SetTMSAction(ProfileManager.GetPrimaryPad(),eTMSAction_TMSPP_RetrieveFiles_RunPlayGame); - } - } + if (!g_NetworkManager.IsHost()) { + // set the game host settings + app.SetGameHostOption(eGameHostOption_All, packet->m_serverSettings); + + // 4J-PB - if we go straight in from the menus via an invite, we won't + // have the DLC info + if (app.GetTMSGlobalFileListRead() == false) { + app.SetTMSAction(ProfileManager.GetPrimaryPad(), + eTMSAction_TMSPP_RetrieveFiles_RunPlayGame); + } + } #ifdef _XBOX - if(!g_NetworkManager.IsHost() && !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) - { - if(m_userIndex == ProfileManager.GetPrimaryPad() ) - { - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(ProfileManager.IsSignedIn(m_userIndex) && ProfileManager.IsGuest(idx)) - { - canPlay = false; - isFriendsWithHost = false; - } - else - { - PlayerUID playerXuid = INVALID_XUID; - if( ProfileManager.IsSignedInLive(idx) ) - { - ProfileManager.GetXUID(idx,&playerXuid,true); - } - if( playerXuid != INVALID_XUID ) - { - // Is this user friends with the host player? - int result = 0; - const unsigned int error = XUserAreUsersFriends(idx,&packet->m_playerXuids[packet->m_hostIndex],1,&result,NULL); - if(error == ERROR_SUCCESS && result == 0) - { - canPlay = false; - isFriendsWithHost = false; - } - } - } - if(!canPlay) break; - } - } - else - { - if(ProfileManager.IsSignedIn(m_userIndex) && ProfileManager.IsGuest(m_userIndex)) - { - canPlay = false; - isFriendsWithHost = false; - } - else - { - PlayerUID playerXuid = INVALID_XUID; - if( ProfileManager.IsSignedInLive(m_userIndex) ) - { - ProfileManager.GetXUID(m_userIndex,&playerXuid,true); - } - if( playerXuid != INVALID_XUID ) - { - // Is this user friends with the host player? - int result = 0; - const unsigned int error = XUserAreUsersFriends(m_userIndex,&packet->m_playerXuids[packet->m_hostIndex],1,&result,NULL); - if(error == ERROR_SUCCESS && result == 0) - { - canPlay = false; - isFriendsWithHost = false; - } - } - } - } - } + if (!g_NetworkManager.IsHost() && + !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) { + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (ProfileManager.IsSignedIn(m_userIndex) && + ProfileManager.IsGuest(idx)) { + canPlay = false; + isFriendsWithHost = false; + } else { + PlayerUID playerXuid = INVALID_XUID; + if (ProfileManager.IsSignedInLive(idx)) { + ProfileManager.GetXUID(idx, &playerXuid, true); + } + if (playerXuid != INVALID_XUID) { + // Is this user friends with the host player? + int result = 0; + const unsigned int error = XUserAreUsersFriends( + idx, &packet->m_playerXuids[packet->m_hostIndex], 1, + &result, NULL); + if (error == ERROR_SUCCESS && result == 0) { + canPlay = false; + isFriendsWithHost = false; + } + } + } + if (!canPlay) break; + } + } else { + if (ProfileManager.IsSignedIn(m_userIndex) && + ProfileManager.IsGuest(m_userIndex)) { + canPlay = false; + isFriendsWithHost = false; + } else { + PlayerUID playerXuid = INVALID_XUID; + if (ProfileManager.IsSignedInLive(m_userIndex)) { + ProfileManager.GetXUID(m_userIndex, &playerXuid, true); + } + if (playerXuid != INVALID_XUID) { + // Is this user friends with the host player? + int result = 0; + const unsigned int error = XUserAreUsersFriends( + m_userIndex, + &packet->m_playerXuids[packet->m_hostIndex], 1, &result, + NULL); + if (error == ERROR_SUCCESS && result == 0) { + canPlay = false; + isFriendsWithHost = false; + } + } + } + } + } - if( canPlay ) - { - for(std::uint8_t i = 0; i < packet->m_dwPlayerCount; ++i) - { - bool localPlayer = false; - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( ProfileManager.IsSignedInLive(idx) ) - { - // need to use the XUID here - PlayerUID playerXUID = INVALID_XUID; - if( !ProfileManager.IsGuest( idx ) ) - { - // Guest don't have an offline XUID as they cannot play offline, so use their online one - ProfileManager.GetXUID(idx,&playerXUID,true); - } - if( ProfileManager.AreXUIDSEqual(playerXUID,packet->m_playerXuids[i]) ) localPlayer = true; - } - else if (ProfileManager.IsSignedIn(idx)) - { - // If we aren't signed into live then they have to be a local player - localPlayer = true; - } - } - if(!localPlayer) - { - // First check our own permissions to see if we can play with this player - if(m_userIndex == ProfileManager.GetPrimaryPad() ) - { - canPlayLocal = ProfileManager.CanViewPlayerCreatedContent(m_userIndex,false,&packet->m_playerXuids[i],1); + if (canPlay) { + for (std::uint8_t i = 0; i < packet->m_dwPlayerCount; ++i) { + bool localPlayer = false; + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (ProfileManager.IsSignedInLive(idx)) { + // need to use the XUID here + PlayerUID playerXUID = INVALID_XUID; + if (!ProfileManager.IsGuest(idx)) { + // Guest don't have an offline XUID as they cannot play + // offline, so use their online one + ProfileManager.GetXUID(idx, &playerXUID, true); + } + if (ProfileManager.AreXUIDSEqual(playerXUID, + packet->m_playerXuids[i])) + localPlayer = true; + } else if (ProfileManager.IsSignedIn(idx)) { + // If we aren't signed into live then they have to be a + // local player + localPlayer = true; + } + } + if (!localPlayer) { + // First check our own permissions to see if we can play with + // this player + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + canPlayLocal = ProfileManager.CanViewPlayerCreatedContent( + m_userIndex, false, &packet->m_playerXuids[i], 1); - // 4J Stu - Everyone joining needs to have at least one friend in the game - // Local players are implied friends - if(!isAtLeastOneFriend) - { - int result = 0; - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( ProfileManager.IsSignedIn(idx) && !ProfileManager.IsGuest(idx) ) - { - const unsigned int error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,NULL); - if(error == ERROR_SUCCESS && result != 0) isAtLeastOneFriend = true; - } - } - } - } - else - { - // Friends with the primary player on this system - isAtLeastOneFriend = true; + // 4J Stu - Everyone joining needs to have at least one + // friend in the game Local players are implied friends + if (!isAtLeastOneFriend) { + int result = 0; + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; + ++idx) { + if (ProfileManager.IsSignedIn(idx) && + !ProfileManager.IsGuest(idx)) { + const unsigned int error = XUserAreUsersFriends( + idx, &packet->m_playerXuids[i], 1, &result, + NULL); + if (error == ERROR_SUCCESS && result != 0) + isAtLeastOneFriend = true; + } + } + } + } else { + // Friends with the primary player on this system + isAtLeastOneFriend = true; - canPlayLocal = ProfileManager.CanViewPlayerCreatedContent(m_userIndex,true,&packet->m_playerXuids[i],1); - } + canPlayLocal = ProfileManager.CanViewPlayerCreatedContent( + m_userIndex, true, &packet->m_playerXuids[i], 1); + } - // If we can play with them, then check if they can play with us - if( canPlayLocal && ( packet->m_friendsOnlyBits & (1<m_friendsOnlyBits & (1 << i))) { + // If this is the primary pad then check all local players + // against the list in the packet (this happens when joining + // the game for the first time) If not the primary pad, then + // just check against this index. It happens on joining at + // the start, but more importantly players trying to join + // during the game + bool thisQuadrantOnly = true; + if (m_userIndex == ProfileManager.GetPrimaryPad()) + thisQuadrantOnly = false; - int result = 0; - for(std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( (!thisQuadrantOnly || m_userIndex == idx) && ProfileManager.IsSignedIn(idx) && !ProfileManager.IsGuest(idx) ) - { - const unsigned int error = XUserAreUsersFriends(idx,&packet->m_playerXuids[i],1,&result,NULL); - if(error == ERROR_SUCCESS) canPlay &= (result != 0); - } - if(!canPlay) break; - } - } - if(!canPlay || !canPlayLocal) break; - } - } - } + int result = 0; + for (std::uint8_t idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if ((!thisQuadrantOnly || m_userIndex == idx) && + ProfileManager.IsSignedIn(idx) && + !ProfileManager.IsGuest(idx)) { + const unsigned int error = XUserAreUsersFriends( + idx, &packet->m_playerXuids[i], 1, &result, + NULL); + if (error == ERROR_SUCCESS) + canPlay &= (result != 0); + } + if (!canPlay) break; + } + } + if (!canPlay || !canPlayLocal) break; + } + } + } #else - // TODO - handle this kind of things for non-360 platforms - canPlay = true; - canPlayLocal = true; - isAtLeastOneFriend = true; - cantPlayContentRestricted= false; + // TODO - handle this kind of things for non-360 platforms + canPlay = true; + canPlayLocal = true; + isAtLeastOneFriend = true; + cantPlayContentRestricted = false; -#if ( defined __PS3__ || defined __ORBIS__ || defined __PSVITA__) +#if (defined __PS3__ || defined __ORBIS__ || defined __PSVITA__) - if(!g_NetworkManager.IsHost() && !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) - { - bool bChatRestricted=false; + if (!g_NetworkManager.IsHost() && + !app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) { + bool bChatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions( + m_userIndex, true, &bChatRestricted, NULL, NULL); - // Chat restricted orbis players can still play online + // Chat restricted orbis players can still play online #ifndef __ORBIS__ - canPlay = !bChatRestricted; + canPlay = !bChatRestricted; #endif - if(m_userIndex == ProfileManager.GetPrimaryPad() ) - { - // Is this user friends with the host player? - bool isFriend = true; - unsigned int friendCount = 0; + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + // Is this user friends with the host player? + bool isFriend = true; + unsigned int friendCount = 0; #ifdef __PS3__ - int ret = sceNpBasicGetFriendListEntryCount(&friendCount); + int ret = sceNpBasicGetFriendListEntryCount(&friendCount); #elif defined __PSVITA__ - sce::Toolkit::NP::Utilities::Future friendList; - int ret = -1; - if(!CGameNetworkManager::usingAdhocMode()) // we don't need to be friends in PSN for adhoc mode - { - int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist(&friendList, false); - if(ret == SCE_TOOLKIT_NP_SUCCESS) - { - if( friendList.hasResult() ) - { - friendCount = friendList.get()->size(); - } - } - } -#else // __ORBIS__ + sce::Toolkit::NP::Utilities::Future + friendList; + int ret = -1; + if (!CGameNetworkManager::usingAdhocMode()) // we don't need to be + // friends in PSN for + // adhoc mode + { + int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist( + &friendList, false); + if (ret == SCE_TOOLKIT_NP_SUCCESS) { + if (friendList.hasResult()) { + friendCount = friendList.get()->size(); + } + } + } +#else // __ORBIS__ - sce::Toolkit::NP::Utilities::Future friendList; + sce::Toolkit::NP::Utilities::Future + friendList; - sce::Toolkit::NP::FriendInfoRequest requestParam; - memset(&requestParam,0,sizeof(requestParam)); - requestParam.flag = SCE_TOOLKIT_NP_FRIENDS_LIST_ALL; - requestParam.limit = 0; - requestParam.offset = 0; - requestParam.userInfo.userId = ProfileManager.getUserID(ProfileManager.GetPrimaryPad()); + sce::Toolkit::NP::FriendInfoRequest requestParam; + memset(&requestParam, 0, sizeof(requestParam)); + requestParam.flag = SCE_TOOLKIT_NP_FRIENDS_LIST_ALL; + requestParam.limit = 0; + requestParam.offset = 0; + requestParam.userInfo.userId = + ProfileManager.getUserID(ProfileManager.GetPrimaryPad()); - int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist(&friendList, &requestParam, false); - if( ret == 0 ) - { - if( friendList.hasResult() ) - { - friendCount = friendList.get()->size(); - } - } + int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist( + &friendList, &requestParam, false); + if (ret == 0) { + if (friendList.hasResult()) { + friendCount = friendList.get()->size(); + } + } #endif - if( ret == 0 ) - { - isFriend = false; - SceNpId npid; - for( unsigned int i = 0; i < friendCount; i++ ) - { + if (ret == 0) { + isFriend = false; + SceNpId npid; + for (unsigned int i = 0; i < friendCount; i++) { #ifdef __PS3__ - ret = sceNpBasicGetFriendListEntry( i, &npid ); + ret = sceNpBasicGetFriendListEntry(i, &npid); #else - npid = friendList.get()->at(i).npid; + npid = friendList.get()->at(i).npid; #endif - if( ret == 0 ) - { - if(strcmp(npid.handle.data, packet->m_playerXuids[packet->m_hostIndex].getOnlineID()) == 0) - { - isFriend = true; - break; - } - } - } - } + if (ret == 0) { + if (strcmp(npid.handle.data, + packet->m_playerXuids[packet->m_hostIndex] + .getOnlineID()) == 0) { + isFriend = true; + break; + } + } + } + } - if( !isFriend ) - { - canPlay = FALSE; - isFriendsWithHost = FALSE; - } - } - } - // is it an online game, and a player has chat restricted? - else if(!g_NetworkManager.IsLocalGame()) - { - // if the player is chat restricted, then they can't play an online game - bool bChatRestricted=false; - bool bContentRestricted=false; + if (!isFriend) { + canPlay = FALSE; + isFriendsWithHost = FALSE; + } + } + } + // is it an online game, and a player has chat restricted? + else if (!g_NetworkManager.IsLocalGame()) { + // if the player is chat restricted, then they can't play an online game + bool bChatRestricted = false; + bool bContentRestricted = false; - // If this is a pre-login packet for the first player on the machine, then accumulate up these flags for everyone signed in. We can handle exiting the game - // much more cleanly at this point by exiting the level, rather than waiting for a prelogin packet for the other players, when we have to exit the player - // which seems to be very unstable at the point of starting up the game - if(m_userIndex == ProfileManager.GetPrimaryPad()) - { - ProfileManager.GetChatAndContentRestrictions(m_userIndex,false,&bChatRestricted,&bContentRestricted,NULL); - } - else - { - ProfileManager.GetChatAndContentRestrictions(m_userIndex,true,&bChatRestricted,&bContentRestricted,NULL); - } + // If this is a pre-login packet for the first player on the machine, + // then accumulate up these flags for everyone signed in. We can handle + // exiting the game much more cleanly at this point by exiting the + // level, rather than waiting for a prelogin packet for the other + // players, when we have to exit the player which seems to be very + // unstable at the point of starting up the game + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + ProfileManager.GetChatAndContentRestrictions( + m_userIndex, false, &bChatRestricted, &bContentRestricted, + NULL); + } else { + ProfileManager.GetChatAndContentRestrictions( + m_userIndex, true, &bChatRestricted, &bContentRestricted, NULL); + } - // Chat restricted orbis players can still play online + // Chat restricted orbis players can still play online #ifndef __ORBIS__ - canPlayLocal = !bChatRestricted; + canPlayLocal = !bChatRestricted; #endif - cantPlayContentRestricted = bContentRestricted ? 1 : 0; - } - + cantPlayContentRestricted = bContentRestricted ? 1 : 0; + } #endif #ifdef _XBOX_ONE - if(!g_NetworkManager.IsHost() && m_userIndex == ProfileManager.GetPrimaryPad()) - { - long long startTime = System::currentTimeMillis(); + if (!g_NetworkManager.IsHost() && + m_userIndex == ProfileManager.GetPrimaryPad()) { + long long startTime = System::currentTimeMillis(); - auto friendsXuids = DQRNetworkManager::GetFriends(); + auto friendsXuids = DQRNetworkManager::GetFriends(); - if (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) - { - // Check that the user has at least one friend in the game - isAtLeastOneFriend = false; + if (app.GetGameHostOption(eGameHostOption_FriendsOfFriends)) { + // Check that the user has at least one friend in the game + isAtLeastOneFriend = false; - for (int i = 0; i < friendsXuids->Size; i++) - { - auto friendsXuid = friendsXuids->GetAt(i); + for (int i = 0; i < friendsXuids->Size; i++) { + auto friendsXuid = friendsXuids->GetAt(i); - // Check this friend against each player, if we find them we have at least one friend - for (int j = 0; j < g_NetworkManager.GetPlayerCount(); j++) - { - Platform::String^ xboxUserId = ref new Platform::String(g_NetworkManager.GetPlayerByIndex(j)->GetUID().toString().data()); - if (friendsXuid == xboxUserId) - { - isAtLeastOneFriend = true; - break; - } - } - } + // Check this friend against each player, if we find them we + // have at least one friend + for (int j = 0; j < g_NetworkManager.GetPlayerCount(); j++) { + Platform::String ^ xboxUserId = ref new Platform::String( + g_NetworkManager.GetPlayerByIndex(j) + ->GetUID() + .toString() + .data()); + if (friendsXuid == xboxUserId) { + isAtLeastOneFriend = true; + break; + } + } + } - app.DebugPrintf("ClientConnection::handlePreLogin: User has at least one friend? %s\n", isAtLeastOneFriend ? "Yes" : "No"); - } - else - { - // Check that the user is friends with the host - bool isFriend = false; + app.DebugPrintf( + "ClientConnection::handlePreLogin: User has at least one " + "friend? %s\n", + isAtLeastOneFriend ? "Yes" : "No"); + } else { + // Check that the user is friends with the host + bool isFriend = false; - Platform::String^ hostXboxUserId = ref new Platform::String(g_NetworkManager.GetHostPlayer()->GetUID().toString().data()); + Platform::String ^ hostXboxUserId = ref new Platform::String( + g_NetworkManager.GetHostPlayer()->GetUID().toString().data()); - for (int i = 0; i < friendsXuids->Size; i++) - { - if (friendsXuids->GetAt(i) == hostXboxUserId) - { - isFriend = true; - break; - } - } + for (int i = 0; i < friendsXuids->Size; i++) { + if (friendsXuids->GetAt(i) == hostXboxUserId) { + isFriend = true; + break; + } + } - if( !isFriend ) - { - canPlay = FALSE; - isFriendsWithHost = FALSE; - } + if (!isFriend) { + canPlay = FALSE; + isFriendsWithHost = FALSE; + } - app.DebugPrintf("ClientConnection::handlePreLogin: User is friends with the host? %s\n", isFriendsWithHost ? "Yes" : "No"); - } + app.DebugPrintf( + "ClientConnection::handlePreLogin: User is friends with the " + "host? %s\n", + isFriendsWithHost ? "Yes" : "No"); + } - app.DebugPrintf("ClientConnection::handlePreLogin: Friendship checks took %i ms\n", System::currentTimeMillis() - startTime); - } + app.DebugPrintf( + "ClientConnection::handlePreLogin: Friendship checks took %i ms\n", + System::currentTimeMillis() - startTime); + } #endif -#endif // _XBOX +#endif // _XBOX - if(!canPlay || !canPlayLocal || !isAtLeastOneFriend || cantPlayContentRestricted) - { + if (!canPlay || !canPlayLocal || !isAtLeastOneFriend || + cantPlayContentRestricted) { #ifndef __PS3__ - DisconnectPacket::eDisconnectReason reason = DisconnectPacket::eDisconnect_NoUGC_Remote; + DisconnectPacket::eDisconnectReason reason = + DisconnectPacket::eDisconnect_NoUGC_Remote; #else - DisconnectPacket::eDisconnectReason reason = DisconnectPacket::eDisconnect_None; -#endif - if(m_userIndex == ProfileManager.GetPrimaryPad()) - { - if(!isFriendsWithHost) reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; - else if(!isAtLeastOneFriend) reason = DisconnectPacket::eDisconnect_NoFriendsInGame; - else if(!canPlayLocal) reason = DisconnectPacket::eDisconnect_NoUGC_AllLocal; - else if(cantPlayContentRestricted) reason = DisconnectPacket::eDisconnect_ContentRestricted_AllLocal; + DisconnectPacket::eDisconnectReason reason = + DisconnectPacket::eDisconnect_None; +#endif + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + if (!isFriendsWithHost) + reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; + else if (!isAtLeastOneFriend) + reason = DisconnectPacket::eDisconnect_NoFriendsInGame; + else if (!canPlayLocal) + reason = DisconnectPacket::eDisconnect_NoUGC_AllLocal; + else if (cantPlayContentRestricted) + reason = + DisconnectPacket::eDisconnect_ContentRestricted_AllLocal; - app.DebugPrintf("Exiting world on handling Pre-Login packet due UGC privileges: %d\n", reason); - app.SetDisconnectReason( reason ); - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_ExitWorld,(void *)TRUE); - } - else - { - if(!isFriendsWithHost) reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; - else if(!canPlayLocal) reason = DisconnectPacket::eDisconnect_NoUGC_Single_Local; - else if(cantPlayContentRestricted) reason = DisconnectPacket::eDisconnect_ContentRestricted_Single_Local; + app.DebugPrintf( + "Exiting world on handling Pre-Login packet due UGC " + "privileges: %d\n", + reason); + app.SetDisconnectReason(reason); + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ExitWorld, + (void*)TRUE); + } else { + if (!isFriendsWithHost) + reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; + else if (!canPlayLocal) + reason = DisconnectPacket::eDisconnect_NoUGC_Single_Local; + else if (cantPlayContentRestricted) + reason = DisconnectPacket:: + eDisconnect_ContentRestricted_Single_Local; - app.DebugPrintf("Exiting player %d on handling Pre-Login packet due UGC privileges: %d\n", m_userIndex, reason); - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - if(!isFriendsWithHost) ui.RequestMessageBox( IDS_CANTJOIN_TITLE, IDS_NOTALLOWED_FRIENDSOFFRIENDS, uiIDA,1,m_userIndex,NULL,NULL, app.GetStringTable()); - else ui.RequestMessageBox( IDS_CANTJOIN_TITLE, IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL, uiIDA,1,m_userIndex,NULL,NULL, app.GetStringTable()); + app.DebugPrintf( + "Exiting player %d on handling Pre-Login packet due UGC " + "privileges: %d\n", + m_userIndex, reason); + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + if (!isFriendsWithHost) + ui.RequestMessageBox( + IDS_CANTJOIN_TITLE, IDS_NOTALLOWED_FRIENDSOFFRIENDS, uiIDA, + 1, m_userIndex, NULL, NULL, app.GetStringTable()); + else + ui.RequestMessageBox( + IDS_CANTJOIN_TITLE, + IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL, uiIDA, + 1, m_userIndex, NULL, NULL, app.GetStringTable()); - app.SetDisconnectReason( reason ); + app.SetDisconnectReason(reason); - // 4J-PB - this locks up on the read and write threads not closing down, because they are trying to lock the incoming critsec when it's already locked by this thread -// Minecraft::GetInstance()->connectionDisconnected( m_userIndex , reason ); -// done = true; -// connection->flush(); -// connection->close(reason); -// app.SetAction(m_userIndex,eAppAction_ExitPlayer); + // 4J-PB - this locks up on the read and write threads not closing + // down, because they are trying to lock the incoming critsec when + // it's already locked by this thread + // Minecraft::GetInstance()->connectionDisconnected( + // m_userIndex , reason ); done = true; connection->flush(); + // connection->close(reason); + // app.SetAction(m_userIndex,eAppAction_ExitPlayer); - // 4J-PB - doing this instead - app.SetAction(m_userIndex,eAppAction_ExitPlayerPreLogin); - } - } - else - { - // Texture pack handling - // If we have the texture pack for the game, load it - // If we don't then send a packet to the host to request it. We need to send this before the LoginPacket so that it gets handled first, - // as once the LoginPacket is received on the client the game is close to starting - if(m_userIndex == ProfileManager.GetPrimaryPad()) - { - Minecraft *pMinecraft = Minecraft::GetInstance(); - if( pMinecraft->skins->selectTexturePackById(packet->m_texturePackId) ) - { - app.DebugPrintf("Selected texture pack %d from Pre-Login packet\n", packet->m_texturePackId); - } - else - { - app.DebugPrintf("Could not select texture pack %d from Pre-Login packet, requesting from host\n", packet->m_texturePackId); + // 4J-PB - doing this instead + app.SetAction(m_userIndex, eAppAction_ExitPlayerPreLogin); + } + } else { + // Texture pack handling + // If we have the texture pack for the game, load it + // If we don't then send a packet to the host to request it. We need to + // send this before the LoginPacket so that it gets handled first, as + // once the LoginPacket is received on the client the game is close to + // starting + if (m_userIndex == ProfileManager.GetPrimaryPad()) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->skins->selectTexturePackById( + packet->m_texturePackId)) { + app.DebugPrintf( + "Selected texture pack %d from Pre-Login packet\n", + packet->m_texturePackId); + } else { + app.DebugPrintf( + "Could not select texture pack %d from Pre-Login packet, " + "requesting from host\n", + packet->m_texturePackId); - // 4J-PB - we need to upsell the texture pack to the player - //app.SetAction(m_userIndex,eAppAction_TexturePackRequired); - // Let the player go into the game, and we'll check that they are using the right texture pack when in - } - } + // 4J-PB - we need to upsell the texture pack to the player + // app.SetAction(m_userIndex,eAppAction_TexturePackRequired); + // Let the player go into the game, and we'll check that they + // are using the right texture pack when in + } + } - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCPreLoginReceived * 100)/ (eCCConnected)); - } - // need to use the XUID here - PlayerUID offlineXUID = INVALID_XUID; - PlayerUID onlineXUID = INVALID_XUID; - if( ProfileManager.IsSignedInLive(m_userIndex) ) - { - // Guest don't have an offline XUID as they cannot play offline, so use their online one - ProfileManager.GetXUID(m_userIndex,&onlineXUID,true); - } + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCPreLoginReceived * 100) / (eCCConnected)); + } + // need to use the XUID here + PlayerUID offlineXUID = INVALID_XUID; + PlayerUID onlineXUID = INVALID_XUID; + if (ProfileManager.IsSignedInLive(m_userIndex)) { + // Guest don't have an offline XUID as they cannot play offline, so + // use their online one + ProfileManager.GetXUID(m_userIndex, &onlineXUID, true); + } #ifdef __PSVITA__ - if(CGameNetworkManager::usingAdhocMode() && onlineXUID.getOnlineID()[0] == 0) - { - // player doesn't have an online UID, set it from the player name - onlineXUID.setForAdhoc(); - } + if (CGameNetworkManager::usingAdhocMode() && + onlineXUID.getOnlineID()[0] == 0) { + // player doesn't have an online UID, set it from the player name + onlineXUID.setForAdhoc(); + } #endif - // On PS3, all non-signed in players (even guests) can get a useful offlineXUID -#if !(defined __PS3__ || defined _DURANGO ) - if( !ProfileManager.IsGuest( m_userIndex ) ) + // On PS3, all non-signed in players (even guests) can get a useful + // offlineXUID +#if !(defined __PS3__ || defined _DURANGO) + if (!ProfileManager.IsGuest(m_userIndex)) #endif - { - // All other players we use their offline XUID so that they can play the game offline - ProfileManager.GetXUID(m_userIndex,&offlineXUID,false); - } - bool allAllowed = false; - bool friendsAllowed = false; - ProfileManager.AllowedPlayerCreatedContent(m_userIndex,true,&allAllowed,&friendsAllowed); - fprintf(stderr, "[LOGIN] Sending LoginPacket: user=%ls netVer=%d userIdx=%d isHost=%d\n", - minecraft->user->name.c_str(), SharedConstants::NETWORK_PROTOCOL_VERSION, m_userIndex, (int)g_NetworkManager.IsHost()); - send( std::shared_ptr( new LoginPacket(minecraft->user->name, SharedConstants::NETWORK_PROTOCOL_VERSION, offlineXUID, onlineXUID, (!allAllowed && friendsAllowed), - packet->m_ugcPlayersVersion, app.GetPlayerSkinId(m_userIndex), app.GetPlayerCapeId(m_userIndex), ProfileManager.IsGuest( m_userIndex )))); - fprintf(stderr, "[LOGIN] LoginPacket sent successfully\n"); + { + // All other players we use their offline XUID so that they can play + // the game offline + ProfileManager.GetXUID(m_userIndex, &offlineXUID, false); + } + bool allAllowed = false; + bool friendsAllowed = false; + ProfileManager.AllowedPlayerCreatedContent( + m_userIndex, true, &allAllowed, &friendsAllowed); + fprintf(stderr, + "[LOGIN] Sending LoginPacket: user=%ls netVer=%d userIdx=%d " + "isHost=%d\n", + minecraft->user->name.c_str(), + SharedConstants::NETWORK_PROTOCOL_VERSION, m_userIndex, + (int)g_NetworkManager.IsHost()); + send(std::shared_ptr(new LoginPacket( + minecraft->user->name, SharedConstants::NETWORK_PROTOCOL_VERSION, + offlineXUID, onlineXUID, (!allAllowed && friendsAllowed), + packet->m_ugcPlayersVersion, app.GetPlayerSkinId(m_userIndex), + app.GetPlayerCapeId(m_userIndex), + ProfileManager.IsGuest(m_userIndex)))); + fprintf(stderr, "[LOGIN] LoginPacket sent successfully\n"); - if(!g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStagePercentage((eCCLoginSent * 100)/ (eCCConnected)); - } - } + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + (eCCLoginSent * 100) / (eCCConnected)); + } + } #else - // 4J - removed + // 4J - removed if (packet->loginKey.equals("-")) { - send(new LoginPacket(minecraft->user.name, SharedConstants.NETWORK_PROTOCOL_VERSION)); + send(new LoginPacket(minecraft->user.name, + SharedConstants.NETWORK_PROTOCOL_VERSION)); } else { try { - URL url = new URL("http://www.minecraft->net/game/joinserver.jsp?user=" + minecraft->user.name + "&sessionId=" + minecraft->user.sessionId + "&serverId=" + packet->loginKey); - BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); + URL url = + new URL("http://www.minecraft->net/game/joinserver.jsp?user=" + + minecraft->user.name + + "&sessionId=" + minecraft->user.sessionId + + "&serverId=" + packet->loginKey); + BufferedReader br = + new BufferedReader(new InputStreamReader(url.openStream())); String msg = br.readLine(); br.close(); if (msg.equalsIgnoreCase("ok")) { - send(new LoginPacket(minecraft->user.name, SharedConstants.NETWORK_PROTOCOL_VERSION)); + send(new LoginPacket(minecraft->user.name, + SharedConstants.NETWORK_PROTOCOL_VERSION)); } else { connection.close("disconnect.loginFailedInfo", msg); } } catch (Exception e) { e.printStackTrace(); - connection.close("disconnect.genericReason", "Internal client error: " + e.toString()); + connection.close("disconnect.genericReason", + "Internal client error: " + e.toString()); } } #endif } -void ClientConnection::close() -{ - // If it's already done, then we don't need to do anything here. And in fact trying to do something could cause a crash - if(done) return; +void ClientConnection::close() { + // If it's already done, then we don't need to do anything here. And in fact + // trying to do something could cause a crash + if (done) return; done = true; connection->flush(); - connection->close(DisconnectPacket::eDisconnect_Closed); + connection->close(DisconnectPacket::eDisconnect_Closed); } -void ClientConnection::handleAddMob(std::shared_ptr packet) -{ - double x = packet->x / 32.0; - double y = packet->y / 32.0; - double z = packet->z / 32.0; - float yRot = packet->yRot * 360 / 256.0f; - float xRot = packet->xRot * 360 / 256.0f; +void ClientConnection::handleAddMob(std::shared_ptr packet) { + double x = packet->x / 32.0; + double y = packet->y / 32.0; + double z = packet->z / 32.0; + float yRot = packet->yRot * 360 / 256.0f; + float xRot = packet->xRot * 360 / 256.0f; - std::shared_ptr mob = std::dynamic_pointer_cast(EntityIO::newById(packet->type, level)); - mob->xp = packet->x; - mob->yp = packet->y; - mob->zp = packet->z; - mob->yHeadRot = packet->yHeadRot * 360 / 256.0f; - mob->yRotp = packet->yRot; - mob->xRotp = packet->xRot; + std::shared_ptr mob = + std::dynamic_pointer_cast(EntityIO::newById(packet->type, level)); + mob->xp = packet->x; + mob->yp = packet->y; + mob->zp = packet->z; + mob->yHeadRot = packet->yHeadRot * 360 / 256.0f; + mob->yRotp = packet->yRot; + mob->xRotp = packet->xRot; - std::vector > *subEntities = mob->getSubEntities(); - if (subEntities != NULL) - { - int offs = packet->id - mob->entityId; - //for (int i = 0; i < subEntities.length; i++) - for(AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); ++it) - { - //subEntities[i].entityId += offs; - (*it)->entityId += offs; - } - } + std::vector >* subEntities = mob->getSubEntities(); + if (subEntities != NULL) { + int offs = packet->id - mob->entityId; + // for (int i = 0; i < subEntities.length; i++) + for (AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); + ++it) { + // subEntities[i].entityId += offs; + (*it)->entityId += offs; + } + } - mob->entityId = packet->id; + mob->entityId = packet->id; -// printf("\t\t\t\t%d: Add mob rot %d\n",packet->id,packet->yRot); + // printf("\t\t\t\t%d: Add mob rot %d\n",packet->id,packet->yRot); - mob->absMoveTo(x, y, z, yRot, xRot); - mob->xd = packet->xd / 8000.0f; - mob->yd = packet->yd / 8000.0f; - mob->zd = packet->zd / 8000.0f; - level->putEntity(packet->id, mob); + mob->absMoveTo(x, y, z, yRot, xRot); + mob->xd = packet->xd / 8000.0f; + mob->yd = packet->yd / 8000.0f; + mob->zd = packet->zd / 8000.0f; + level->putEntity(packet->id, mob); - std::vector > *unpackedData = packet->getUnpackedData(); - if (unpackedData != NULL) - { - mob->getEntityData()->assignValues(unpackedData); - } + std::vector >* unpackedData = + packet->getUnpackedData(); + if (unpackedData != NULL) { + mob->getEntityData()->assignValues(unpackedData); + } - // Fix for #65236 - TU8: Content: Gameplay: Magma Cubes' have strange hit boxes. - // 4J Stu - Slimes have a different BB depending on their size which is set in the entity data, so update the BB - if(mob->GetType() == eTYPE_SLIME || mob->GetType() == eTYPE_LAVASLIME) - { - std::shared_ptr slime = std::dynamic_pointer_cast(mob); - slime->setSize( slime->getSize() ); - } + // Fix for #65236 - TU8: Content: Gameplay: Magma Cubes' have strange hit + // boxes. 4J Stu - Slimes have a different BB depending on their size which + // is set in the entity data, so update the BB + if (mob->GetType() == eTYPE_SLIME || mob->GetType() == eTYPE_LAVASLIME) { + std::shared_ptr slime = std::dynamic_pointer_cast(mob); + slime->setSize(slime->getSize()); + } } -void ClientConnection::handleSetTime(std::shared_ptr packet) -{ - minecraft->level->setTime(packet->time); +void ClientConnection::handleSetTime(std::shared_ptr packet) { + minecraft->level->setTime(packet->time); } -void ClientConnection::handleSetSpawn(std::shared_ptr packet) -{ - //minecraft->player->setRespawnPosition(new Pos(packet->x, packet->y, packet->z)); - minecraft->localplayers[m_userIndex]->setRespawnPosition(new Pos(packet->x, packet->y, packet->z)); +void ClientConnection::handleSetSpawn( + std::shared_ptr packet) { + // minecraft->player->setRespawnPosition(new Pos(packet->x, packet->y, + // packet->z)); + minecraft->localplayers[m_userIndex]->setRespawnPosition( + new Pos(packet->x, packet->y, packet->z)); minecraft->level->getLevelData()->setSpawn(packet->x, packet->y, packet->z); - } -void ClientConnection::handleRidePacket(std::shared_ptr packet) -{ +void ClientConnection::handleRidePacket( + std::shared_ptr packet) { std::shared_ptr rider = getEntity(packet->riderId); std::shared_ptr ridden = getEntity(packet->riddenId); - std::shared_ptr boat = std::dynamic_pointer_cast(ridden); - //if (packet->riderId == minecraft->player->entityId) rider = minecraft->player; - if (packet->riderId == minecraft->localplayers[m_userIndex]->entityId) - { - rider = minecraft->localplayers[m_userIndex]; + std::shared_ptr boat = std::dynamic_pointer_cast(ridden); + // if (packet->riderId == minecraft->player->entityId) rider = + // minecraft->player; + if (packet->riderId == minecraft->localplayers[m_userIndex]->entityId) { + rider = minecraft->localplayers[m_userIndex]; - if (boat) boat->setDoLerp(false); - } - else if (boat) - { - boat->setDoLerp(true); - } + if (boat) boat->setDoLerp(false); + } else if (boat) { + boat->setDoLerp(true); + } if (rider == NULL) return; - rider->ride(ridden); + rider->ride(ridden); } -void ClientConnection::handleEntityEvent(std::shared_ptr packet) -{ +void ClientConnection::handleEntityEvent( + std::shared_ptr packet) { std::shared_ptr e = getEntity(packet->entityId); if (e != NULL) e->handleEntityEvent(packet->eventId); } -std::shared_ptr ClientConnection::getEntity(int entityId) -{ - //if (entityId == minecraft->player->entityId) - if(entityId == minecraft->localplayers[m_userIndex]->entityId) - { - //return minecraft->player; - return minecraft->localplayers[m_userIndex]; - } - return level->getEntity(entityId); +std::shared_ptr ClientConnection::getEntity(int entityId) { + // if (entityId == minecraft->player->entityId) + if (entityId == minecraft->localplayers[m_userIndex]->entityId) { + // return minecraft->player; + return minecraft->localplayers[m_userIndex]; + } + return level->getEntity(entityId); } -void ClientConnection::handleSetHealth(std::shared_ptr packet) -{ - //minecraft->player->hurtTo(packet->health); - minecraft->localplayers[m_userIndex]->hurtTo(packet->health,packet->damageSource); - minecraft->localplayers[m_userIndex]->getFoodData()->setFoodLevel(packet->food); - minecraft->localplayers[m_userIndex]->getFoodData()->setSaturation(packet->saturation); +void ClientConnection::handleSetHealth( + std::shared_ptr packet) { + // minecraft->player->hurtTo(packet->health); + minecraft->localplayers[m_userIndex]->hurtTo(packet->health, + packet->damageSource); + minecraft->localplayers[m_userIndex]->getFoodData()->setFoodLevel( + packet->food); + minecraft->localplayers[m_userIndex]->getFoodData()->setSaturation( + packet->saturation); - // We need food - if(packet->food < FoodConstants::HEAL_LEVEL - 1) - { - if(minecraft->localgameModes[m_userIndex] != NULL && !minecraft->localgameModes[m_userIndex]->hasInfiniteItems() ) - { - minecraft->localgameModes[m_userIndex]->getTutorial()->changeTutorialState(e_Tutorial_State_Food_Bar); - } - } + // We need food + if (packet->food < FoodConstants::HEAL_LEVEL - 1) { + if (minecraft->localgameModes[m_userIndex] != NULL && + !minecraft->localgameModes[m_userIndex]->hasInfiniteItems()) { + minecraft->localgameModes[m_userIndex] + ->getTutorial() + ->changeTutorialState(e_Tutorial_State_Food_Bar); + } + } } -void ClientConnection::handleSetExperience(std::shared_ptr packet) -{ - minecraft->localplayers[m_userIndex]->setExperienceValues(packet->experienceProgress, packet->totalExperience, packet->experienceLevel); +void ClientConnection::handleSetExperience( + std::shared_ptr packet) { + minecraft->localplayers[m_userIndex]->setExperienceValues( + packet->experienceProgress, packet->totalExperience, + packet->experienceLevel); } -void ClientConnection::handleTexture(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - // Server side also needs to store a list of those clients waiting to get a texture the server doesn't have yet - // so that it can send it out to them when it comes in +void ClientConnection::handleTexture(std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way Server side also needs to store a list of those clients waiting + // to get a texture the server doesn't have yet so that it can send it out + // to them when it comes in - if(packet->dataBytes==0) - { - // Request for texture + if (packet->dataBytes == 0) { + // Request for texture #ifndef _CONTENT_PACKAGE - wprintf(L"Client received request for custom texture %ls\n",packet->textureName.c_str()); + wprintf(L"Client received request for custom texture %ls\n", + packet->textureName.c_str()); #endif - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwBytes); - if(dwBytes!=0) - { - send( std::shared_ptr( new TexturePacket(packet->textureName,pbData,dwBytes) ) ); - } - } - else - { - // Response with texture data + if (dwBytes != 0) { + send(std::shared_ptr( + new TexturePacket(packet->textureName, pbData, dwBytes))); + } + } else { + // Response with texture data #ifndef _CONTENT_PACKAGE - wprintf(L"Client received custom texture %ls\n",packet->textureName.c_str()); + wprintf(L"Client received custom texture %ls\n", + packet->textureName.c_str()); #endif - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dataBytes); - Minecraft::GetInstance()->handleClientTextureReceived(packet->textureName); - } + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dataBytes); + Minecraft::GetInstance()->handleClientTextureReceived( + packet->textureName); + } } -void ClientConnection::handleTextureAndGeometry(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - // Server side also needs to store a list of those clients waiting to get a texture the server doesn't have yet - // so that it can send it out to them when it comes in +void ClientConnection::handleTextureAndGeometry( + std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way Server side also needs to store a list of those clients waiting + // to get a texture the server doesn't have yet so that it can send it out + // to them when it comes in - if(packet->dwTextureBytes==0) - { - // Request for texture + if (packet->dwTextureBytes == 0) { + // Request for texture #ifndef _CONTENT_PACKAGE - wprintf(L"Client received request for custom texture and geometry %ls\n",packet->textureName.c_str()); + wprintf( + L"Client received request for custom texture and geometry %ls\n", + packet->textureName.c_str()); #endif - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); - DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwBytes); + DLCSkinFile* pDLCSkinFile = + app.m_dlcManager.getSkinFile(packet->textureName); - if(dwBytes!=0) - { - if(pDLCSkinFile) - { - if(pDLCSkinFile->getAdditionalBoxesCount()!=0) - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes,pDLCSkinFile) ) ); - } - else - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes) ) ); - } - } - else - { - unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(packet->dwSkinID); + if (dwBytes != 0) { + if (pDLCSkinFile) { + if (pDLCSkinFile->getAdditionalBoxesCount() != 0) { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwBytes, + pDLCSkinFile))); + } else { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwBytes))); + } + } else { + unsigned int uiAnimOverrideBitmask = + app.GetAnimOverrideBitmask(packet->dwSkinID); - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwBytes,app.GetAdditionalSkinBoxes(packet->dwSkinID),uiAnimOverrideBitmask) ) ); - } - } - } - else - { - // Response with texture data + send(std::shared_ptr( + new TextureAndGeometryPacket( + packet->textureName, pbData, dwBytes, + app.GetAdditionalSkinBoxes(packet->dwSkinID), + uiAnimOverrideBitmask))); + } + } + } else { + // Response with texture data #ifndef _CONTENT_PACKAGE - wprintf(L"Client received custom TextureAndGeometry %ls\n",packet->textureName.c_str()); + wprintf(L"Client received custom TextureAndGeometry %ls\n", + packet->textureName.c_str()); #endif - // Add the texture data - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dwTextureBytes); - // Add the geometry data - if(packet->dwBoxC!=0) - { - app.SetAdditionalSkinBoxes(packet->dwSkinID,packet->BoxDataA,packet->dwBoxC); - } - // Add the anim override - app.SetAnimOverrideBitmask(packet->dwSkinID,packet->uiAnimOverrideBitmask); + // Add the texture data + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dwTextureBytes); + // Add the geometry data + if (packet->dwBoxC != 0) { + app.SetAdditionalSkinBoxes(packet->dwSkinID, packet->BoxDataA, + packet->dwBoxC); + } + // Add the anim override + app.SetAnimOverrideBitmask(packet->dwSkinID, + packet->uiAnimOverrideBitmask); - // clear out the pending texture request - Minecraft::GetInstance()->handleClientTextureReceived(packet->textureName); - } + // clear out the pending texture request + Minecraft::GetInstance()->handleClientTextureReceived( + packet->textureName); + } } -void ClientConnection::handleTextureChange(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->id); +void ClientConnection::handleTextureChange( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->id); + if (e == NULL) return; + std::shared_ptr player = std::dynamic_pointer_cast(e); if (e == NULL) return; - std::shared_ptr player = std::dynamic_pointer_cast(e); - if( e == NULL) return; - bool isLocalPlayer = false; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->id ) - { - isLocalPlayer = true; - break; - } - } - } - if(isLocalPlayer) return; + bool isLocalPlayer = false; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == packet->id) { + isLocalPlayer = true; + break; + } + } + } + if (isLocalPlayer) return; - switch(packet->action) - { - case TextureChangePacket::e_TextureChange_Skin: - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); + switch (packet->action) { + case TextureChangePacket::e_TextureChange_Skin: + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); #ifndef _CONTENT_PACKAGE - wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); + wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); #endif - break; - case TextureChangePacket::e_TextureChange_Cape: - player->setCustomCape( Player::getCapeIdFromPath( packet->path ) ); - //player->customTextureUrl2 = packet->path; + break; + case TextureChangePacket::e_TextureChange_Cape: + player->setCustomCape(Player::getCapeIdFromPath(packet->path)); + // player->customTextureUrl2 = packet->path; #ifndef _CONTENT_PACKAGE - wprintf(L"Cape for remote player %ls has changed to %ls\n", player->name.c_str(), player->customTextureUrl2.c_str() ); + wprintf(L"Cape for remote player %ls has changed to %ls\n", + player->name.c_str(), player->customTextureUrl2.c_str()); #endif - break; - } - - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( minecraft->addPendingClientTextureRequest(packet->path) ) - { + break; + } + + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (minecraft->addPendingClientTextureRequest(packet->path)) { #ifndef _CONTENT_PACKAGE - wprintf(L"handleTextureChange - Client sending texture packet to get custom skin %ls for player %ls\n",packet->path.c_str(), player->name.c_str()); + wprintf( + L"handleTextureChange - Client sending texture packet to get " + L"custom skin %ls for player %ls\n", + packet->path.c_str(), player->name.c_str()); #endif - send(std::shared_ptr( new TexturePacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - } + send(std::shared_ptr( + new TexturePacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + } } -void ClientConnection::handleTextureAndGeometryChange(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->id); - if (e == NULL) return; - std::shared_ptr player = std::dynamic_pointer_cast(e); - if( e == NULL) return; +void ClientConnection::handleTextureAndGeometryChange( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->id); + if (e == NULL) return; + std::shared_ptr player = std::dynamic_pointer_cast(e); + if (e == NULL) return; - bool isLocalPlayer = false; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( minecraft->localplayers[i] ) - { - if( minecraft->localplayers[i]->entityId == packet->id ) - { - isLocalPlayer = true; - break; - } - } - } - if(isLocalPlayer) return; + bool isLocalPlayer = false; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + if (minecraft->localplayers[i]->entityId == packet->id) { + isLocalPlayer = true; + break; + } + } + } + if (isLocalPlayer) return; - - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); #ifndef _CONTENT_PACKAGE - wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); + wprintf(L"Skin for remote player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); #endif - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( minecraft->addPendingClientTextureRequest(packet->path) ) - { + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (minecraft->addPendingClientTextureRequest(packet->path)) { #ifndef _CONTENT_PACKAGE - wprintf(L"handleTextureAndGeometryChange - Client sending TextureAndGeometryPacket to get custom skin %ls for player %ls\n",packet->path.c_str(), player->name.c_str()); + wprintf( + L"handleTextureAndGeometryChange - Client sending " + L"TextureAndGeometryPacket to get custom skin %ls for player " + L"%ls\n", + packet->path.c_str(), player->name.c_str()); #endif - send(std::shared_ptr( new TextureAndGeometryPacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - - } + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + } } -void ClientConnection::handleRespawn(std::shared_ptr packet) -{ - //if (packet->dimension != minecraft->player->dimension) - if( packet->dimension != minecraft->localplayers[m_userIndex]->dimension || packet->mapSeed != minecraft->localplayers[m_userIndex]->level->getSeed() ) - { - int oldDimension = minecraft->localplayers[m_userIndex]->dimension; +void ClientConnection::handleRespawn(std::shared_ptr packet) { + // if (packet->dimension != minecraft->player->dimension) + if (packet->dimension != minecraft->localplayers[m_userIndex]->dimension || + packet->mapSeed != + minecraft->localplayers[m_userIndex]->level->getSeed()) { + int oldDimension = minecraft->localplayers[m_userIndex]->dimension; started = false; - // Remove client connection from this level - level->removeClientConnection(this, false); + // Remove client connection from this level + level->removeClientConnection(this, false); - MultiPlayerLevel *dimensionLevel = (MultiPlayerLevel *)minecraft->getLevel( packet->dimension ); - if( dimensionLevel == NULL ) - { - dimensionLevel = new MultiPlayerLevel(this, new LevelSettings(packet->mapSeed, packet->playerGameType, false, minecraft->level->getLevelData()->isHardcore(), packet->m_newSeaLevel, packet->m_pLevelType, packet->m_xzSize, packet->m_hellScale), packet->dimension, packet->difficulty); + MultiPlayerLevel* dimensionLevel = + (MultiPlayerLevel*)minecraft->getLevel(packet->dimension); + if (dimensionLevel == NULL) { + dimensionLevel = new MultiPlayerLevel( + this, + new LevelSettings( + packet->mapSeed, packet->playerGameType, false, + minecraft->level->getLevelData()->isHardcore(), + packet->m_newSeaLevel, packet->m_pLevelType, + packet->m_xzSize, packet->m_hellScale), + packet->dimension, packet->difficulty); - // 4J Stu - We want to shared the savedDataStorage between both levels - //if( dimensionLevel->savedDataStorage != NULL ) - //{ - // Don't need to delete it here as it belongs to a client connection while will delete it when it's done - // delete dimensionLevel->savedDataStorage;+ - //} - dimensionLevel->savedDataStorage = level->savedDataStorage; + // 4J Stu - We want to shared the savedDataStorage between both + // levels + // if( dimensionLevel->savedDataStorage != NULL ) + //{ + // Don't need to delete it here as it belongs to a client connection + // while will delete it when it's done + // delete dimensionLevel->savedDataStorage;+ + //} + dimensionLevel->savedDataStorage = level->savedDataStorage; - dimensionLevel->difficulty = packet->difficulty; // 4J Added - app.DebugPrintf("dimensionLevel->difficulty - Difficulty = %d\n",packet->difficulty); + dimensionLevel->difficulty = packet->difficulty; // 4J Added + app.DebugPrintf("dimensionLevel->difficulty - Difficulty = %d\n", + packet->difficulty); - dimensionLevel->isClientSide = true; - } - else - { - dimensionLevel->addClientConnection(this); - } + dimensionLevel->isClientSide = true; + } else { + dimensionLevel->addClientConnection(this); + } - // Remove the player entity from the current level - level->removeEntity( std::shared_ptr(minecraft->localplayers[m_userIndex]) ); + // Remove the player entity from the current level + level->removeEntity( + std::shared_ptr(minecraft->localplayers[m_userIndex])); - level = dimensionLevel; - - // Whilst calling setLevel, make sure that minecraft::player is set up to be correct for this - // connection - std::shared_ptr lastPlayer = minecraft->player; - minecraft->player = minecraft->localplayers[m_userIndex]; - minecraft->setLevel(dimensionLevel); - minecraft->player = lastPlayer; + level = dimensionLevel; - TelemetryManager->RecordLevelExit(m_userIndex, eSen_LevelExitStatus_Succeeded); - - //minecraft->player->dimension = packet->dimension; - minecraft->localplayers[m_userIndex]->dimension = packet->dimension; - //minecraft->setScreen(new ReceivingLevelScreen(this)); -// minecraft->addPendingLocalConnection(m_userIndex, this); + // Whilst calling setLevel, make sure that minecraft::player is set up + // to be correct for this connection + std::shared_ptr lastPlayer = minecraft->player; + minecraft->player = minecraft->localplayers[m_userIndex]; + minecraft->setLevel(dimensionLevel); + minecraft->player = lastPlayer; + + TelemetryManager->RecordLevelExit(m_userIndex, + eSen_LevelExitStatus_Succeeded); + + // minecraft->player->dimension = packet->dimension; + minecraft->localplayers[m_userIndex]->dimension = packet->dimension; + // minecraft->setScreen(new ReceivingLevelScreen(this)); + // minecraft->addPendingLocalConnection(m_userIndex, this); #ifdef _XBOX - TelemetryManager->RecordLevelStart(m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); + TelemetryManager->RecordLevelStart( + m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, + Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, + app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); #endif - if( minecraft->localgameModes[m_userIndex] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_userIndex]; - gameMode->getTutorial()->showTutorialPopup(false); - } + if (minecraft->localgameModes[m_userIndex] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)minecraft->localgameModes[m_userIndex]; + gameMode->getTutorial()->showTutorialPopup(false); + } - // 4J-JEV: Fix for Durango #156334 - Content: UI: Rich Presence 'In the Nether' message is updating with a 3 to 10 minute delay. - minecraft->localplayers[m_userIndex]->updateRichPresence(); + // 4J-JEV: Fix for Durango #156334 - Content: UI: Rich Presence 'In the + // Nether' message is updating with a 3 to 10 minute delay. + minecraft->localplayers[m_userIndex]->updateRichPresence(); - ConnectionProgressParams *param = new ConnectionProgressParams(); - param->iPad = m_userIndex; - if( packet->dimension == -1) - { - param->stringId = IDS_PROGRESS_ENTERING_NETHER; - } - else if( oldDimension == -1) - { - param->stringId = IDS_PROGRESS_LEAVING_NETHER; - } - else if( packet->dimension == 1) - { - param->stringId = IDS_PROGRESS_ENTERING_END; - } - else if( oldDimension == 1) - { - param->stringId = IDS_PROGRESS_LEAVING_END; - } - param->showTooltips = false; - param->setFailTimer = false; + ConnectionProgressParams* param = new ConnectionProgressParams(); + param->iPad = m_userIndex; + if (packet->dimension == -1) { + param->stringId = IDS_PROGRESS_ENTERING_NETHER; + } else if (oldDimension == -1) { + param->stringId = IDS_PROGRESS_LEAVING_NETHER; + } else if (packet->dimension == 1) { + param->stringId = IDS_PROGRESS_ENTERING_END; + } else if (oldDimension == 1) { + param->stringId = IDS_PROGRESS_LEAVING_END; + } + param->showTooltips = false; + param->setFailTimer = false; - // 4J Stu - Fix for #13543 - Crash: Game crashes if entering a portal with the inventory menu open - ui.CloseUIScenes( m_userIndex ); + // 4J Stu - Fix for #13543 - Crash: Game crashes if entering a portal + // with the inventory menu open + ui.CloseUIScenes(m_userIndex); - if(app.GetLocalPlayerCount()>1) - { - ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); - } - else - { - ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); - } - - app.SetAction( m_userIndex, eAppAction_WaitForDimensionChangeComplete); + if (app.GetLocalPlayerCount() > 1) { + ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); + } else { + ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); + } + + app.SetAction(m_userIndex, eAppAction_WaitForDimensionChangeComplete); } - //minecraft->respawnPlayer(minecraft->player->GetXboxPad(),true, packet->dimension); - - // Wrap respawnPlayer call up in code to set & restore the player/gamemode etc. as some things - // in there assume that we are set up for the player that the respawn is coming in for - int oldIndex = minecraft->getLocalPlayerIdx(); - minecraft->setLocalPlayerIdx(m_userIndex); - minecraft->respawnPlayer(minecraft->localplayers[m_userIndex]->GetXboxPad(),packet->dimension,packet->m_newEntityId); - ((MultiPlayerGameMode *) minecraft->localgameModes[m_userIndex])->setLocalMode(packet->playerGameType); - minecraft->setLocalPlayerIdx(oldIndex); + // minecraft->respawnPlayer(minecraft->player->GetXboxPad(),true, + // packet->dimension); + + // Wrap respawnPlayer call up in code to set & restore the player/gamemode + // etc. as some things in there assume that we are set up for the player + // that the respawn is coming in for + int oldIndex = minecraft->getLocalPlayerIdx(); + minecraft->setLocalPlayerIdx(m_userIndex); + minecraft->respawnPlayer(minecraft->localplayers[m_userIndex]->GetXboxPad(), + packet->dimension, packet->m_newEntityId); + ((MultiPlayerGameMode*)minecraft->localgameModes[m_userIndex]) + ->setLocalMode(packet->playerGameType); + minecraft->setLocalPlayerIdx(oldIndex); } -void ClientConnection::handleExplosion(std::shared_ptr packet) -{ - if(!packet->m_bKnockbackOnly) - { - //app.DebugPrintf("Received ExplodePacket with explosion data\n"); - PIXBeginNamedEvent(0,"Handling explosion"); - Explosion *e = new Explosion(minecraft->level, nullptr, packet->x, packet->y, packet->z, packet->r); - PIXBeginNamedEvent(0,"Finalizing"); +void ClientConnection::handleExplosion(std::shared_ptr packet) { + if (!packet->m_bKnockbackOnly) { + // app.DebugPrintf("Received ExplodePacket with explosion data\n"); + PIXBeginNamedEvent(0, "Handling explosion"); + Explosion* e = new Explosion(minecraft->level, nullptr, packet->x, + packet->y, packet->z, packet->r); + PIXBeginNamedEvent(0, "Finalizing"); - // Fix for #81758 - TCR 006 BAS Non-Interactive Pause: TU9: Performance: Gameplay: After detonating bunch of TNT, game enters unresponsive state for couple of seconds. - // The changes we are making here have been decided by the server, so we don't need to add them to the vector that resets tiles changes made - // on the client as we KNOW that the server is matching these changes - MultiPlayerLevel *mpLevel = (MultiPlayerLevel *)minecraft->level; - mpLevel->enableResetChanges(false); - // 4J - now directly pass a pointer to the toBlow array in the packet rather than copying around - e->finalizeExplosion(true, &packet->toBlow); - mpLevel->enableResetChanges(true); - PIXEndNamedEvent(); - PIXEndNamedEvent(); - delete e; - } - else - { - //app.DebugPrintf("Received ExplodePacket with knockback only data\n"); - } + // Fix for #81758 - TCR 006 BAS Non-Interactive Pause: TU9: Performance: + // Gameplay: After detonating bunch of TNT, game enters unresponsive + // state for couple of seconds. The changes we are making here have been + // decided by the server, so we don't need to add them to the vector + // that resets tiles changes made on the client as we KNOW that the + // server is matching these changes + MultiPlayerLevel* mpLevel = (MultiPlayerLevel*)minecraft->level; + mpLevel->enableResetChanges(false); + // 4J - now directly pass a pointer to the toBlow array in the packet + // rather than copying around + e->finalizeExplosion(true, &packet->toBlow); + mpLevel->enableResetChanges(true); + PIXEndNamedEvent(); + PIXEndNamedEvent(); + delete e; + } else { + // app.DebugPrintf("Received ExplodePacket with knockback only data\n"); + } - //app.DebugPrintf("Adding knockback (%f,%f,%f) for player %d\n", packet->getKnockbackX(), packet->getKnockbackY(), packet->getKnockbackZ(), m_userIndex); - minecraft->localplayers[m_userIndex]->xd += packet->getKnockbackX(); - minecraft->localplayers[m_userIndex]->yd += packet->getKnockbackY(); - minecraft->localplayers[m_userIndex]->zd += packet->getKnockbackZ(); + // app.DebugPrintf("Adding knockback (%f,%f,%f) for player %d\n", + // packet->getKnockbackX(), packet->getKnockbackY(), + // packet->getKnockbackZ(), m_userIndex); + minecraft->localplayers[m_userIndex]->xd += packet->getKnockbackX(); + minecraft->localplayers[m_userIndex]->yd += packet->getKnockbackY(); + minecraft->localplayers[m_userIndex]->zd += packet->getKnockbackZ(); } -void ClientConnection::handleContainerOpen(std::shared_ptr packet) -{ - bool failed = false; - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - switch(packet->type) - { - case ContainerOpenPacket::CONTAINER: - { - if( player->openContainer(std::shared_ptr( new SimpleContainer(packet->title, packet->size) ))) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::FURNACE: - { - if( player->openFurnace(std::shared_ptr( new FurnaceTileEntity() )) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::BREWING_STAND: - { - if( player->openBrewingStand(std::shared_ptr( new BrewingStandTileEntity() )) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::TRAP: - { - if( player->openTrap(std::shared_ptr( new DispenserTileEntity() )) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::WORKBENCH: - { - if( player->startCrafting(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::ENCHANTMENT: - { - if( player->startEnchanting(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)) ) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::TRADER_NPC: - { - std::shared_ptr csm = std::shared_ptr(new ClientSideMerchant(player,packet->title)); - csm->createContainer(); - if(player->openTrading(csm)) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - case ContainerOpenPacket::REPAIR_TABLE: - { - if(player->startRepairing(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z))) - { - player->containerMenu->containerId = packet->containerId; - } - else - { - failed = true; - } - } - break; - }; +void ClientConnection::handleContainerOpen( + std::shared_ptr packet) { + bool failed = false; + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + switch (packet->type) { + case ContainerOpenPacket::CONTAINER: { + if (player->openContainer(std::shared_ptr( + new SimpleContainer(packet->title, packet->size)))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::FURNACE: { + if (player->openFurnace(std::shared_ptr( + new FurnaceTileEntity()))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::BREWING_STAND: { + if (player->openBrewingStand( + std::shared_ptr( + new BrewingStandTileEntity()))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::TRAP: { + if (player->openTrap(std::shared_ptr( + new DispenserTileEntity()))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::WORKBENCH: { + if (player->startCrafting(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::ENCHANTMENT: { + if (player->startEnchanting(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::TRADER_NPC: { + std::shared_ptr csm = + std::shared_ptr( + new ClientSideMerchant(player, packet->title)); + csm->createContainer(); + if (player->openTrading(csm)) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + case ContainerOpenPacket::REPAIR_TABLE: { + if (player->startRepairing(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z))) { + player->containerMenu->containerId = packet->containerId; + } else { + failed = true; + } + } break; + }; - if(failed) - { - // Failed - if we've got a non-inventory container currently here, close that, which locally should put us back - // to not having a container open, and should send a containerclose to the server so it doesn't have a container open. - // If we don't have a non-inventory container open, just send the packet, and again we ought to be in sync with the server. - if( player->containerMenu != player->inventoryMenu ) - { - ui.CloseUIScenes(m_userIndex); - } - else - { - send(std::shared_ptr(new ContainerClosePacket(packet->containerId))); - } - } + if (failed) { + // Failed - if we've got a non-inventory container currently here, close + // that, which locally should put us back to not having a container + // open, and should send a containerclose to the server so it doesn't + // have a container open. If we don't have a non-inventory container + // open, just send the packet, and again we ought to be in sync with the + // server. + if (player->containerMenu != player->inventoryMenu) { + ui.CloseUIScenes(m_userIndex); + } else { + send(std::shared_ptr( + new ContainerClosePacket(packet->containerId))); + } + } } -void ClientConnection::handleContainerSetSlot(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED ) - { +void ClientConnection::handleContainerSetSlot( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED) { player->inventory->setCarried(packet->item); - } - else - { - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) - { - // 4J Stu - Reworked a bit to fix a bug where things being collected while the creative menu was up replaced items in the creative menu - if(packet->slot >= 36 && packet->slot < 36 + 9) - { - std::shared_ptr lastItem = player->inventoryMenu->getSlot(packet->slot)->getItem(); - if (packet->item != NULL) - { - if (lastItem == NULL || lastItem->count < packet->item->count) - { - packet->item->popTime = Inventory::POP_TIME_DURATION; - } - } - } - player->inventoryMenu->setItem(packet->slot, packet->item); - } - else if (packet->containerId == player->containerMenu->containerId) - { + } else { + if (packet->containerId == + AbstractContainerMenu::CONTAINER_ID_INVENTORY) { + // 4J Stu - Reworked a bit to fix a bug where things being collected + // while the creative menu was up replaced items in the creative + // menu + if (packet->slot >= 36 && packet->slot < 36 + 9) { + std::shared_ptr lastItem = + player->inventoryMenu->getSlot(packet->slot)->getItem(); + if (packet->item != NULL) { + if (lastItem == NULL || + lastItem->count < packet->item->count) { + packet->item->popTime = Inventory::POP_TIME_DURATION; + } + } + } + player->inventoryMenu->setItem(packet->slot, packet->item); + } else if (packet->containerId == player->containerMenu->containerId) { player->containerMenu->setItem(packet->slot, packet->item); } } } -void ClientConnection::handleContainerAck(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - AbstractContainerMenu *menu = NULL; - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) - { +void ClientConnection::handleContainerAck( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + AbstractContainerMenu* menu = NULL; + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) { menu = player->inventoryMenu; - } - else if (packet->containerId == player->containerMenu->containerId) - { + } else if (packet->containerId == player->containerMenu->containerId) { menu = player->containerMenu; } - if (menu != NULL) - { - if (!packet->accepted) - { - send( std::shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, true) )); + if (menu != NULL) { + if (!packet->accepted) { + send(std::shared_ptr(new ContainerAckPacket( + packet->containerId, packet->uid, true))); } } } -void ClientConnection::handleContainerContent(std::shared_ptr packet) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) - { +void ClientConnection::handleContainerContent( + std::shared_ptr packet) { + std::shared_ptr player = + minecraft->localplayers[m_userIndex]; + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) { player->inventoryMenu->setAll(&packet->items); - } - else if (packet->containerId == player->containerMenu->containerId) - { + } else if (packet->containerId == player->containerMenu->containerId) { player->containerMenu->setAll(&packet->items); } } -void ClientConnection::handleSignUpdate(std::shared_ptr packet) -{ - app.DebugPrintf("ClientConnection::handleSignUpdate - "); - if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) - { - std::shared_ptr te = minecraft->level->getTileEntity(packet->x, packet->y, packet->z); +void ClientConnection::handleSignUpdate( + std::shared_ptr packet) { + app.DebugPrintf("ClientConnection::handleSignUpdate - "); + if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) { + std::shared_ptr te = + minecraft->level->getTileEntity(packet->x, packet->y, packet->z); - // 4J-PB - on a client connecting, the line below fails - if (std::dynamic_pointer_cast(te) != NULL) - { - std::shared_ptr ste = std::dynamic_pointer_cast(te); - for (int i = 0; i < MAX_SIGN_LINES; i++) - { - ste->SetMessage(i,packet->lines[i]); + // 4J-PB - on a client connecting, the line below fails + if (std::dynamic_pointer_cast(te) != NULL) { + std::shared_ptr ste = + std::dynamic_pointer_cast(te); + for (int i = 0; i < MAX_SIGN_LINES; i++) { + ste->SetMessage(i, packet->lines[i]); } - app.DebugPrintf("verified = %d\tCensored = %d\n",packet->m_bVerified,packet->m_bCensored); - ste->SetVerified(packet->m_bVerified); - ste->SetCensored(packet->m_bCensored); + app.DebugPrintf("verified = %d\tCensored = %d\n", + packet->m_bVerified, packet->m_bCensored); + ste->SetVerified(packet->m_bVerified); + ste->SetCensored(packet->m_bCensored); - ste->setChanged(); + ste->setChanged(); + } else { + app.DebugPrintf( + "std::dynamic_pointer_cast(te) == NULL\n"); } - else - { - app.DebugPrintf("std::dynamic_pointer_cast(te) == NULL\n"); - } + } else { + app.DebugPrintf("hasChunkAt failed\n"); } - else - { - app.DebugPrintf("hasChunkAt failed\n"); - } } -void ClientConnection::handleTileEntityData(std::shared_ptr packet) -{ - if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) - { - std::shared_ptr te = minecraft->level->getTileEntity(packet->x, packet->y, packet->z); +void ClientConnection::handleTileEntityData( + std::shared_ptr packet) { + if (minecraft->level->hasChunkAt(packet->x, packet->y, packet->z)) { + std::shared_ptr te = + minecraft->level->getTileEntity(packet->x, packet->y, packet->z); - if (te != NULL) - { - if (packet->type == TileEntityDataPacket::TYPE_MOB_SPAWNER && std::dynamic_pointer_cast(te) != NULL) - { - std::dynamic_pointer_cast(te)->load(packet->tag); - } - //else if (packet.type == TileEntityDataPacket.TYPE_ADV_COMMAND && (te instanceof CommandBlockEntity)) - //{ - // ((CommandBlockEntity) te).load(packet.tag); - //} - //else if (packet.type == TileEntityDataPacket.TYPE_BEACON && (te instanceof BeaconTileEntity)) - //{ - // ((BeaconTileEntity) te).load(packet.tag); - //} - else if (packet->type == TileEntityDataPacket::TYPE_SKULL && std::dynamic_pointer_cast(te) != NULL) - { - std::dynamic_pointer_cast(te)->load(packet->tag); - } - } - } + if (te != NULL) { + if (packet->type == TileEntityDataPacket::TYPE_MOB_SPAWNER && + std::dynamic_pointer_cast(te) != NULL) { + std::dynamic_pointer_cast(te)->load( + packet->tag); + } + // else if (packet.type == TileEntityDataPacket.TYPE_ADV_COMMAND && + // (te instanceof CommandBlockEntity)) + //{ + // ((CommandBlockEntity) te).load(packet.tag); + // } + // else if (packet.type == TileEntityDataPacket.TYPE_BEACON && (te + // instanceof BeaconTileEntity)) + //{ + // ((BeaconTileEntity) te).load(packet.tag); + // } + else if (packet->type == TileEntityDataPacket::TYPE_SKULL && + std::dynamic_pointer_cast(te) != NULL) { + std::dynamic_pointer_cast(te)->load( + packet->tag); + } + } + } } -void ClientConnection::handleContainerSetData(std::shared_ptr packet) -{ +void ClientConnection::handleContainerSetData( + std::shared_ptr packet) { onUnhandledPacket(packet); - if (minecraft->localplayers[m_userIndex]->containerMenu != NULL && minecraft->localplayers[m_userIndex]->containerMenu->containerId == packet->containerId) - { - minecraft->localplayers[m_userIndex]->containerMenu->setData(packet->id, packet->value); + if (minecraft->localplayers[m_userIndex]->containerMenu != NULL && + minecraft->localplayers[m_userIndex]->containerMenu->containerId == + packet->containerId) { + minecraft->localplayers[m_userIndex]->containerMenu->setData( + packet->id, packet->value); } } -void ClientConnection::handleSetEquippedItem(std::shared_ptr packet) -{ +void ClientConnection::handleSetEquippedItem( + std::shared_ptr packet) { std::shared_ptr entity = getEntity(packet->entity); - if (entity != NULL) - { - // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game - entity->setEquippedSlot(packet->slot, packet->getItem() ); + if (entity != NULL) { + // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer + // Encountered: TU7: Content: Art: Aura of enchanted item is not + // displayed for other players in online game + entity->setEquippedSlot(packet->slot, packet->getItem()); } } -void ClientConnection::handleContainerClose(std::shared_ptr packet) -{ - minecraft->localplayers[m_userIndex]->closeContainer(); +void ClientConnection::handleContainerClose( + std::shared_ptr packet) { + minecraft->localplayers[m_userIndex]->closeContainer(); } -void ClientConnection::handleTileEvent(std::shared_ptr packet) -{ - PIXBeginNamedEvent(0,"Handle tile event\n"); - minecraft->level->tileEvent(packet->x, packet->y, packet->z, packet->tile, packet->b0, packet->b1); - PIXEndNamedEvent(); +void ClientConnection::handleTileEvent( + std::shared_ptr packet) { + PIXBeginNamedEvent(0, "Handle tile event\n"); + minecraft->level->tileEvent(packet->x, packet->y, packet->z, packet->tile, + packet->b0, packet->b1); + PIXEndNamedEvent(); } -void ClientConnection::handleTileDestruction(std::shared_ptr packet) -{ - minecraft->level->destroyTileProgress(packet->getEntityId(), packet->getX(), packet->getY(), packet->getZ(), packet->getState()); +void ClientConnection::handleTileDestruction( + std::shared_ptr packet) { + minecraft->level->destroyTileProgress(packet->getEntityId(), packet->getX(), + packet->getY(), packet->getZ(), + packet->getState()); } -bool ClientConnection::canHandleAsyncPackets() -{ - return minecraft != NULL && minecraft->level != NULL && minecraft->localplayers[m_userIndex] != NULL && level != NULL; +bool ClientConnection::canHandleAsyncPackets() { + return minecraft != NULL && minecraft->level != NULL && + minecraft->localplayers[m_userIndex] != NULL && level != NULL; } -void ClientConnection::handleGameEvent(std::shared_ptr gameEventPacket) -{ +void ClientConnection::handleGameEvent( + std::shared_ptr gameEventPacket) { int event = gameEventPacket->_event; - int param = gameEventPacket->param; - if (event >= 0 && event < GameEventPacket::EVENT_LANGUAGE_ID_LENGTH) - { - if (GameEventPacket::EVENT_LANGUAGE_ID[event] > 0) // 4J - was NULL check - { - minecraft->localplayers[m_userIndex]->displayClientMessage(GameEventPacket::EVENT_LANGUAGE_ID[event]); + int param = gameEventPacket->param; + if (event >= 0 && event < GameEventPacket::EVENT_LANGUAGE_ID_LENGTH) { + if (GameEventPacket::EVENT_LANGUAGE_ID[event] > + 0) // 4J - was NULL check + { + minecraft->localplayers[m_userIndex]->displayClientMessage( + GameEventPacket::EVENT_LANGUAGE_ID[event]); } } - if (event == GameEventPacket::START_RAINING) - { + if (event == GameEventPacket::START_RAINING) { level->getLevelData()->setRaining(true); level->setRainLevel(1); - } - else if (event == GameEventPacket::STOP_RAINING) - { + } else if (event == GameEventPacket::STOP_RAINING) { level->getLevelData()->setRaining(false); level->setRainLevel(0); - } - else if (event == GameEventPacket::CHANGE_GAME_MODE) - { - minecraft->localgameModes[m_userIndex]->setLocalMode(GameType::byId(param)); - } - else if (event == GameEventPacket::WIN_GAME) - { - ui.SetWinUserIndex(static_cast(gameEventPacket->param)); - + } else if (event == GameEventPacket::CHANGE_GAME_MODE) { + minecraft->localgameModes[m_userIndex]->setLocalMode( + GameType::byId(param)); + } else if (event == GameEventPacket::WIN_GAME) { + ui.SetWinUserIndex(static_cast(gameEventPacket->param)); + #ifdef _XBOX - // turn off the gamertags in splitscreen for the primary player, since they are about to be made fullscreen - ui.HideAllGameUIElements(); + // turn off the gamertags in splitscreen for the primary player, since + // they are about to be made fullscreen + ui.HideAllGameUIElements(); - // Hide the other players scenes - ui.ShowOtherPlayersBaseScene(ProfileManager.GetPrimaryPad(), false); + // Hide the other players scenes + ui.ShowOtherPlayersBaseScene(ProfileManager.GetPrimaryPad(), false); - // This just allows it to be shown - if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); - // Temporarily make this scene fullscreen - CXuiSceneBase::SetPlayerBaseScenePosition( ProfileManager.GetPrimaryPad(), CXuiSceneBase::e_BaseScene_Fullscreen ); + // This just allows it to be shown + if (minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) + minecraft->localgameModes[ProfileManager.GetPrimaryPad()] + ->getTutorial() + ->showTutorialPopup(false); + // Temporarily make this scene fullscreen + CXuiSceneBase::SetPlayerBaseScenePosition( + ProfileManager.GetPrimaryPad(), + CXuiSceneBase::e_BaseScene_Fullscreen); - app.CloseXuiScenesAndNavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_EndPoem); + app.CloseXuiScenesAndNavigateToScene(ProfileManager.GetPrimaryPad(), + eUIScene_EndPoem); #else - app.DebugPrintf("handleGameEvent packet for WIN_GAME - %d\n", m_userIndex); - // This just allows it to be shown - if(minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) minecraft->localgameModes[ProfileManager.GetPrimaryPad()]->getTutorial()->showTutorialPopup(false); - ui.NavigateToScene(ProfileManager.GetPrimaryPad(), eUIScene_EndPoem, NULL, eUILayer_Scene, eUIGroup_Fullscreen); + app.DebugPrintf("handleGameEvent packet for WIN_GAME - %d\n", + m_userIndex); + // This just allows it to be shown + if (minecraft->localgameModes[ProfileManager.GetPrimaryPad()] != NULL) + minecraft->localgameModes[ProfileManager.GetPrimaryPad()] + ->getTutorial() + ->showTutorialPopup(false); + ui.NavigateToScene(ProfileManager.GetPrimaryPad(), eUIScene_EndPoem, + NULL, eUILayer_Scene, eUIGroup_Fullscreen); #endif - } - else if( event == GameEventPacket::START_SAVING ) - { - if(!g_NetworkManager.IsHost()) - { - // Move app started to here so that it happens immediately otherwise back-to-back START/STOP packets - // leave the client stuck in the loading screen - app.SetGameStarted(false); - app.SetAction( ProfileManager.GetPrimaryPad(), eAppAction_RemoteServerSave ); - } - } - else if( event == GameEventPacket::STOP_SAVING ) - { - if(!g_NetworkManager.IsHost() ) app.SetGameStarted(true); - } + } else if (event == GameEventPacket::START_SAVING) { + if (!g_NetworkManager.IsHost()) { + // Move app started to here so that it happens immediately otherwise + // back-to-back START/STOP packets leave the client stuck in the + // loading screen + app.SetGameStarted(false); + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_RemoteServerSave); + } + } else if (event == GameEventPacket::STOP_SAVING) { + if (!g_NetworkManager.IsHost()) app.SetGameStarted(true); + } } -void ClientConnection::handleComplexItemData(std::shared_ptr packet) -{ - if (packet->itemType == Item::map->id) - { - MapItem::getSavedData(packet->itemId, minecraft->level)->handleComplexItemData(packet->data); - } - else - { -// System.out.println("Unknown itemid: " + packet->itemId); // 4J removed - } +void ClientConnection::handleComplexItemData( + std::shared_ptr packet) { + if (packet->itemType == Item::map->id) { + MapItem::getSavedData(packet->itemId, minecraft->level) + ->handleComplexItemData(packet->data); + } else { + // System.out.println("Unknown itemid: " + packet->itemId); + //// 4J removed + } } +void ClientConnection::handleLevelEvent( + std::shared_ptr packet) { + switch (packet->type) { + case LevelEvent::SOUND_DRAGON_DEATH: { + Minecraft* pMinecraft = Minecraft::GetInstance(); + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + if (pMinecraft->localplayers[i] != NULL && + pMinecraft->localplayers[i]->level != NULL && + pMinecraft->localplayers[i]->level->dimension->id == 1) { + pMinecraft->localplayers[i]->awardStat( + GenericStats::completeTheEnd(), + GenericStats::param_noArgs()); + } + } + } + minecraft->level->levelEvent(packet->type, packet->x, packet->y, + packet->z, packet->data); - -void ClientConnection::handleLevelEvent(std::shared_ptr packet) -{ - switch(packet->type) - { - case LevelEvent::SOUND_DRAGON_DEATH: - { - Minecraft *pMinecraft = Minecraft::GetInstance(); - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - if(pMinecraft->localplayers[i] != NULL && pMinecraft->localplayers[i]->level != NULL && pMinecraft->localplayers[i]->level->dimension->id == 1) - { - pMinecraft->localplayers[i]->awardStat(GenericStats::completeTheEnd(),GenericStats::param_noArgs()); - } - } - } - minecraft->level->levelEvent(packet->type, packet->x, packet->y, packet->z, packet->data); - - break; - default: - minecraft->level->levelEvent(packet->type, packet->x, packet->y, packet->z, packet->data); - break; - } + break; + default: + minecraft->level->levelEvent(packet->type, packet->x, packet->y, + packet->z, packet->data); + break; + } } -void ClientConnection::handleAwardStat(std::shared_ptr packet) -{ - minecraft->localplayers[m_userIndex]->awardStatFromServer(GenericStats::stat(packet->statId), packet->getParamData()); +void ClientConnection::handleAwardStat( + std::shared_ptr packet) { + minecraft->localplayers[m_userIndex]->awardStatFromServer( + GenericStats::stat(packet->statId), packet->getParamData()); } -void ClientConnection::handleUpdateMobEffect(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->entityId); - if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; +void ClientConnection::handleUpdateMobEffect( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->entityId); + if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; - ( std::dynamic_pointer_cast(e) )->addEffect(new MobEffectInstance(packet->effectId, packet->effectDurationTicks, packet->effectAmplifier)); + (std::dynamic_pointer_cast(e)) + ->addEffect(new MobEffectInstance(packet->effectId, + packet->effectDurationTicks, + packet->effectAmplifier)); } -void ClientConnection::handleRemoveMobEffect(std::shared_ptr packet) -{ - std::shared_ptr e = getEntity(packet->entityId); - if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; +void ClientConnection::handleRemoveMobEffect( + std::shared_ptr packet) { + std::shared_ptr e = getEntity(packet->entityId); + if (e == NULL || std::dynamic_pointer_cast(e) == NULL) return; - ( std::dynamic_pointer_cast(e) )->removeEffectNoUpdate(packet->effectId); + (std::dynamic_pointer_cast(e))->removeEffectNoUpdate(packet->effectId); } -bool ClientConnection::isServerPacketListener() -{ - return false; -} +bool ClientConnection::isServerPacketListener() { return false; } -void ClientConnection::handlePlayerInfo(std::shared_ptr packet) -{ - unsigned int startingPrivileges = app.GetPlayerPrivileges(packet->m_networkSmallId); +void ClientConnection::handlePlayerInfo( + std::shared_ptr packet) { + unsigned int startingPrivileges = + app.GetPlayerPrivileges(packet->m_networkSmallId); - INetworkPlayer *networkPlayer = g_NetworkManager.GetPlayerBySmallId(packet->m_networkSmallId); + INetworkPlayer* networkPlayer = + g_NetworkManager.GetPlayerBySmallId(packet->m_networkSmallId); - if(networkPlayer != NULL && networkPlayer->IsHost()) - { - // Some settings should always be considered on for the host player - Player::enableAllPlayerPrivileges(startingPrivileges,true); - Player::setPlayerGamePrivilege(startingPrivileges,Player::ePlayerGamePrivilege_HOST,1); - } + if (networkPlayer != NULL && networkPlayer->IsHost()) { + // Some settings should always be considered on for the host player + Player::enableAllPlayerPrivileges(startingPrivileges, true); + Player::setPlayerGamePrivilege(startingPrivileges, + Player::ePlayerGamePrivilege_HOST, 1); + } - // 4J Stu - Repurposed this packet for player info that we want - app.UpdatePlayerInfo(packet->m_networkSmallId, packet->m_playerColourIndex, packet->m_playerPrivileges); + // 4J Stu - Repurposed this packet for player info that we want + app.UpdatePlayerInfo(packet->m_networkSmallId, packet->m_playerColourIndex, + packet->m_playerPrivileges); - std::shared_ptr entity = getEntity(packet->m_entityId); - if(entity != NULL && entity->GetType() == eTYPE_PLAYER) - { - std::shared_ptr player = std::dynamic_pointer_cast(entity); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_playerPrivileges); - } - if(networkPlayer != NULL && networkPlayer->IsLocal()) - { - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - std::shared_ptr localPlayer = minecraft->localplayers[i]; - if(localPlayer != NULL && localPlayer->connection != NULL && localPlayer->connection->getNetworkPlayer() == networkPlayer ) - { - localPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All,packet->m_playerPrivileges); - displayPrivilegeChanges(localPlayer,startingPrivileges); - break; - } - } - } + std::shared_ptr entity = getEntity(packet->m_entityId); + if (entity != NULL && entity->GetType() == eTYPE_PLAYER) { + std::shared_ptr player = + std::dynamic_pointer_cast(entity); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + packet->m_playerPrivileges); + } + if (networkPlayer != NULL && networkPlayer->IsLocal()) { + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + std::shared_ptr localPlayer = + minecraft->localplayers[i]; + if (localPlayer != NULL && localPlayer->connection != NULL && + localPlayer->connection->getNetworkPlayer() == networkPlayer) { + localPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_All, + packet->m_playerPrivileges); + displayPrivilegeChanges(localPlayer, startingPrivileges); + break; + } + } + } - // 4J Stu - I don't think we care about this, so not converting it (came from 1.8.2) + // 4J Stu - I don't think we care about this, so not converting it (came + // from 1.8.2) #if 0 PlayerInfo pi = playerInfoMap.get(packet.name); if (pi == null && packet.add) { @@ -3037,326 +3189,377 @@ void ClientConnection::handlePlayerInfo(std::shared_ptr packet #endif } - -void ClientConnection::displayPrivilegeChanges(std::shared_ptr player, unsigned int oldPrivileges) -{ - int userIndex = player->GetXboxPad(); - unsigned int newPrivileges = player->getAllPlayerGamePrivileges(); - Player::EPlayerGamePrivileges priv = (Player::EPlayerGamePrivileges)0; - bool privOn = false; - for(unsigned int i = 0; i < Player::ePlayerGamePrivilege_MAX; ++i) - { - priv = (Player::EPlayerGamePrivileges) i; - if( Player::getPlayerGamePrivilege(newPrivileges,priv) != Player::getPlayerGamePrivilege(oldPrivileges,priv)) - { - privOn = Player::getPlayerGamePrivilege(newPrivileges,priv); - std::wstring message = L""; - if(app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) - { - switch(priv) - { - case Player::ePlayerGamePrivilege_CannotMine: - if(privOn) message = app.GetString(IDS_PRIV_MINE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_MINE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotBuild: - if(privOn) message = app.GetString(IDS_PRIV_BUILD_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_BUILD_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches: - if(privOn) message = app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanUseContainers: - if(privOn) message = app.GetString(IDS_PRIV_USE_CONTAINERS_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_USE_CONTAINERS_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotAttackAnimals: - if(privOn) message = app.GetString(IDS_PRIV_ATTACK_ANIMAL_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_ATTACK_ANIMAL_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotAttackMobs: - if(privOn) message = app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CannotAttackPlayers: - if(privOn) message = app.GetString(IDS_PRIV_ATTACK_PLAYER_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_ATTACK_PLAYER_TOGGLE_OFF); - break; - default: - break; - }; - } - switch(priv) - { - case Player::ePlayerGamePrivilege_Op: - if(privOn) message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_OFF); - break; - default: - break; - }; - if(app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0) - { - switch(priv) - { - case Player::ePlayerGamePrivilege_CanFly: - if(privOn) message = app.GetString(IDS_PRIV_FLY_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_FLY_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_ClassicHunger: - if(privOn) message = app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_Invisible: - if(privOn) message = app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_Invulnerable: - if(privOn) message = app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanToggleInvisible: - if(privOn) message = app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanToggleFly: - if(privOn) message = app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanToggleClassicHunger: - if(privOn) message = app.GetString(IDS_PRIV_CAN_EXHAUSTION_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_EXHAUSTION_TOGGLE_OFF); - break; - case Player::ePlayerGamePrivilege_CanTeleport: - if(privOn) message = app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_ON); - else message = app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_OFF); - break; - default: - break; - }; - } - if(!message.empty()) minecraft->gui->addMessage(message,userIndex); - } - } +void ClientConnection::displayPrivilegeChanges( + std::shared_ptr player, + unsigned int oldPrivileges) { + int userIndex = player->GetXboxPad(); + unsigned int newPrivileges = player->getAllPlayerGamePrivileges(); + Player::EPlayerGamePrivileges priv = (Player::EPlayerGamePrivileges)0; + bool privOn = false; + for (unsigned int i = 0; i < Player::ePlayerGamePrivilege_MAX; ++i) { + priv = (Player::EPlayerGamePrivileges)i; + if (Player::getPlayerGamePrivilege(newPrivileges, priv) != + Player::getPlayerGamePrivilege(oldPrivileges, priv)) { + privOn = Player::getPlayerGamePrivilege(newPrivileges, priv); + std::wstring message = L""; + if (app.GetGameHostOption(eGameHostOption_TrustPlayers) == 0) { + switch (priv) { + case Player::ePlayerGamePrivilege_CannotMine: + if (privOn) + message = app.GetString(IDS_PRIV_MINE_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_MINE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotBuild: + if (privOn) + message = app.GetString(IDS_PRIV_BUILD_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_BUILD_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches: + if (privOn) + message = + app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_USE_DOORS_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanUseContainers: + if (privOn) + message = app.GetString( + IDS_PRIV_USE_CONTAINERS_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_USE_CONTAINERS_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotAttackAnimals: + if (privOn) + message = + app.GetString(IDS_PRIV_ATTACK_ANIMAL_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_ATTACK_ANIMAL_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotAttackMobs: + if (privOn) + message = + app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_ATTACK_MOB_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CannotAttackPlayers: + if (privOn) + message = + app.GetString(IDS_PRIV_ATTACK_PLAYER_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_ATTACK_PLAYER_TOGGLE_OFF); + break; + default: + break; + }; + } + switch (priv) { + case Player::ePlayerGamePrivilege_Op: + if (privOn) + message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_MODERATOR_TOGGLE_OFF); + break; + default: + break; + }; + if (app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0) { + switch (priv) { + case Player::ePlayerGamePrivilege_CanFly: + if (privOn) + message = app.GetString(IDS_PRIV_FLY_TOGGLE_ON); + else + message = app.GetString(IDS_PRIV_FLY_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_ClassicHunger: + if (privOn) + message = + app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_EXHAUSTION_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_Invisible: + if (privOn) + message = + app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_INVISIBLE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_Invulnerable: + if (privOn) + message = + app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanToggleInvisible: + if (privOn) + message = + app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_CAN_INVISIBLE_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanToggleFly: + if (privOn) + message = app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_CAN_FLY_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanToggleClassicHunger: + if (privOn) + message = app.GetString( + IDS_PRIV_CAN_EXHAUSTION_TOGGLE_ON); + else + message = app.GetString( + IDS_PRIV_CAN_EXHAUSTION_TOGGLE_OFF); + break; + case Player::ePlayerGamePrivilege_CanTeleport: + if (privOn) + message = + app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_ON); + else + message = + app.GetString(IDS_PRIV_CAN_TELEPORT_TOGGLE_OFF); + break; + default: + break; + }; + } + if (!message.empty()) + minecraft->gui->addMessage(message, userIndex); + } + } } -void ClientConnection::handleKeepAlive(std::shared_ptr packet) -{ - send(std::shared_ptr(new KeepAlivePacket(packet->id))); +void ClientConnection::handleKeepAlive( + std::shared_ptr packet) { + send(std::shared_ptr(new KeepAlivePacket(packet->id))); } -void ClientConnection::handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket) -{ - std::shared_ptr player = minecraft->localplayers[m_userIndex]; - player->abilities.flying = playerAbilitiesPacket->isFlying(); - player->abilities.instabuild = playerAbilitiesPacket->canInstabuild(); - player->abilities.invulnerable = playerAbilitiesPacket->isInvulnerable(); - player->abilities.mayfly = playerAbilitiesPacket->canFly(); - player->abilities.setFlyingSpeed(playerAbilitiesPacket->getFlyingSpeed()); +void ClientConnection::handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket) { + std::shared_ptr player = minecraft->localplayers[m_userIndex]; + player->abilities.flying = playerAbilitiesPacket->isFlying(); + player->abilities.instabuild = playerAbilitiesPacket->canInstabuild(); + player->abilities.invulnerable = playerAbilitiesPacket->isInvulnerable(); + player->abilities.mayfly = playerAbilitiesPacket->canFly(); + player->abilities.setFlyingSpeed(playerAbilitiesPacket->getFlyingSpeed()); } -void ClientConnection::handleSoundEvent(std::shared_ptr packet) -{ - minecraft->level->playLocalSound(packet->getX(), packet->getY(), packet->getZ(), packet->getSound(), packet->getVolume(), packet->getPitch()); +void ClientConnection::handleSoundEvent( + std::shared_ptr packet) { + minecraft->level->playLocalSound(packet->getX(), packet->getY(), + packet->getZ(), packet->getSound(), + packet->getVolume(), packet->getPitch()); } -void ClientConnection::handleCustomPayload(std::shared_ptr customPayloadPacket) -{ - if (CustomPayloadPacket::TRADER_LIST_PACKET.compare(customPayloadPacket->identifier) == 0) - { - ByteArrayInputStream bais(customPayloadPacket->data); - DataInputStream input(&bais); - int containerId = input.readInt(); - if (ui.IsSceneInStack(m_userIndex, eUIScene_TradingMenu) && containerId == minecraft->localplayers[m_userIndex]->containerMenu->containerId) - { - std::shared_ptr trader = nullptr; +void ClientConnection::handleCustomPayload( + std::shared_ptr customPayloadPacket) { + if (CustomPayloadPacket::TRADER_LIST_PACKET.compare( + customPayloadPacket->identifier) == 0) { + ByteArrayInputStream bais(customPayloadPacket->data); + DataInputStream input(&bais); + int containerId = input.readInt(); + if (ui.IsSceneInStack(m_userIndex, eUIScene_TradingMenu) && + containerId == minecraft->localplayers[m_userIndex] + ->containerMenu->containerId) { + std::shared_ptr trader = nullptr; #ifdef _XBOX - HXUIOBJ scene = app.GetCurrentScene(m_userIndex); - HXUICLASS thisClass = XuiFindClass( L"CXuiSceneTrading" ); - HXUICLASS objClass = XuiGetObjectClass( scene ); + HXUIOBJ scene = app.GetCurrentScene(m_userIndex); + HXUICLASS thisClass = XuiFindClass(L"CXuiSceneTrading"); + HXUICLASS objClass = XuiGetObjectClass(scene); - // Also returns TRUE if they are the same (which is what we want) - if( XuiClassDerivesFrom( objClass, thisClass ) ) - { - CXuiSceneTrading *screen; - HRESULT hr = XuiObjectFromHandle(scene, (void **) &screen); - if (FAILED(hr)) return; - trader = screen->getMerchant(); - } + // Also returns TRUE if they are the same (which is what we want) + if (XuiClassDerivesFrom(objClass, thisClass)) { + CXuiSceneTrading* screen; + HRESULT hr = XuiObjectFromHandle(scene, (void**)&screen); + if (FAILED(hr)) return; + trader = screen->getMerchant(); + } #else - UIScene *scene = ui.GetTopScene(m_userIndex, eUILayer_Scene); - UIScene_TradingMenu *screen = (UIScene_TradingMenu *)scene; - trader = screen->getMerchant(); + UIScene* scene = ui.GetTopScene(m_userIndex, eUILayer_Scene); + UIScene_TradingMenu* screen = (UIScene_TradingMenu*)scene; + trader = screen->getMerchant(); #endif - - MerchantRecipeList *recipeList = MerchantRecipeList::createFromStream(&input); - trader->overrideOffers(recipeList); - } - } + + MerchantRecipeList* recipeList = + MerchantRecipeList::createFromStream(&input); + trader->overrideOffers(recipeList); + } + } } -Connection *ClientConnection::getConnection() -{ - return connection; -} +Connection* ClientConnection::getConnection() { return connection; } // 4J Added -void ClientConnection::handleServerSettingsChanged(std::shared_ptr packet) -{ - if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) - { - app.SetGameHostOption(eGameHostOption_All, packet->data); - } - else if(packet->action==ServerSettingsChangedPacket::HOST_DIFFICULTY) - { - for(unsigned int i = 0; i < minecraft->levels.length; ++i) - { - if( minecraft->levels[i] != NULL ) - { - app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); - minecraft->levels[i]->difficulty = packet->data; - } - } - } - else - { - //options - //minecraft->options->SetGamertagSetting((packet->data==0)?false:true); - app.SetGameHostOption(eGameHostOption_Gamertags, packet->data); - } - +void ClientConnection::handleServerSettingsChanged( + std::shared_ptr packet) { + if (packet->action == ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) { + app.SetGameHostOption(eGameHostOption_All, packet->data); + } else if (packet->action == ServerSettingsChangedPacket::HOST_DIFFICULTY) { + for (unsigned int i = 0; i < minecraft->levels.length; ++i) { + if (minecraft->levels[i] != NULL) { + app.DebugPrintf( + "ClientConnection::handleServerSettingsChanged - " + "Difficulty = %d", + packet->data); + minecraft->levels[i]->difficulty = packet->data; + } + } + } else { + // options + // minecraft->options->SetGamertagSetting((packet->data==0)?false:true); + app.SetGameHostOption(eGameHostOption_Gamertags, packet->data); + } } -void ClientConnection::handleXZ(std::shared_ptr packet) -{ - if(packet->action==XZPacket::STRONGHOLD) - { - minecraft->levels[0]->getLevelData()->setXStronghold(packet->x); - minecraft->levels[0]->getLevelData()->setZStronghold(packet->z); - minecraft->levels[0]->getLevelData()->setHasStronghold(); - } +void ClientConnection::handleXZ(std::shared_ptr packet) { + if (packet->action == XZPacket::STRONGHOLD) { + minecraft->levels[0]->getLevelData()->setXStronghold(packet->x); + minecraft->levels[0]->getLevelData()->setZStronghold(packet->z); + minecraft->levels[0]->getLevelData()->setHasStronghold(); + } } -void ClientConnection::handleUpdateProgress(std::shared_ptr packet) -{ - if(!g_NetworkManager.IsHost() ) Minecraft::GetInstance()->progressRenderer->progressStagePercentage( packet->m_percentage ); +void ClientConnection::handleUpdateProgress( + std::shared_ptr packet) { + if (!g_NetworkManager.IsHost()) + Minecraft::GetInstance()->progressRenderer->progressStagePercentage( + packet->m_percentage); } -void ClientConnection::handleUpdateGameRuleProgressPacket(std::shared_ptr packet) -{ - const wchar_t *string = app.GetGameRulesString(packet->m_messageId); - if(string != NULL) - { - std::wstring message(string); - message = GameRuleDefinition::generateDescriptionString(packet->m_definitionType,message,packet->m_data.data,packet->m_data.length); - if(minecraft->localgameModes[m_userIndex]!=NULL) - { - minecraft->localgameModes[m_userIndex]->getTutorial()->setMessage(message, packet->m_icon, packet->m_auxValue); - } - } - // If this rule has a data tag associated with it, then we save that in user profile data - if(packet->m_dataTag > 0 && packet->m_dataTag <= 32) - { - app.DebugPrintf("handleUpdateGameRuleProgressPacket: Data tag is in range, so updating profile data\n"); - app.SetSpecialTutorialCompletionFlag(m_userIndex, packet->m_dataTag - 1); - } - delete [] packet->m_data.data; +void ClientConnection::handleUpdateGameRuleProgressPacket( + std::shared_ptr packet) { + const wchar_t* string = app.GetGameRulesString(packet->m_messageId); + if (string != NULL) { + std::wstring message(string); + message = GameRuleDefinition::generateDescriptionString( + packet->m_definitionType, message, packet->m_data.data, + packet->m_data.length); + if (minecraft->localgameModes[m_userIndex] != NULL) { + minecraft->localgameModes[m_userIndex]->getTutorial()->setMessage( + message, packet->m_icon, packet->m_auxValue); + } + } + // If this rule has a data tag associated with it, then we save that in user + // profile data + if (packet->m_dataTag > 0 && packet->m_dataTag <= 32) { + app.DebugPrintf( + "handleUpdateGameRuleProgressPacket: Data tag is in range, so " + "updating profile data\n"); + app.SetSpecialTutorialCompletionFlag(m_userIndex, + packet->m_dataTag - 1); + } + delete[] packet->m_data.data; } // 4J Stu - TU-1 hotfix -// Fix for #13191 - The host of a game can get a message informing them that the connection to the server has been lost -int ClientConnection::HostDisconnectReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) -{ - // 4J-PB - if they have a trial texture pack, they don't get to save the world - if(!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) - { - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - DLCTexturePack *pDLCTexPack=(DLCTexturePack *)tPack; +// Fix for #13191 - The host of a game can get a message informing them that the +// connection to the server has been lost +int ClientConnection::HostDisconnectReturned( + void* pParam, int iPad, C4JStorage::EMessageResult result) { + // 4J-PB - if they have a trial texture pack, they don't get to save the + // world + if (!Minecraft::GetInstance()->skins->isUsingDefaultSkin()) { + TexturePack* tPack = Minecraft::GetInstance()->skins->getSelected(); + DLCTexturePack* pDLCTexPack = (DLCTexturePack*)tPack; - DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack();//tPack->getDLCPack(); - if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { - // no upsell, we're about to quit - MinecraftServer::getInstance()->setSaveOnExit( false ); - // flag a app action of exit game - app.SetAction(iPad,eAppAction_ExitWorld); - } - } + DLCPack* pDLCPack = + pDLCTexPack->getDLCInfoParentPack(); // tPack->getDLCPack(); + if (!pDLCPack->hasPurchasedFile(DLCManager::e_DLCType_Texture, L"")) { + // no upsell, we're about to quit + MinecraftServer::getInstance()->setSaveOnExit(false); + // flag a app action of exit game + app.SetAction(iPad, eAppAction_ExitWorld); + } + } #if defined(_XBOX_ONE) || defined(__ORBIS__) - // Give the player the option to save their game - // does the save exist? - bool bSaveExists; - StorageManager.DoesSaveExist(&bSaveExists); - // 4J-PB - we check if the save exists inside the libs - // we need to ask if they are sure they want to overwrite the existing game - if(bSaveExists && StorageManager.GetSaveDisabled()) - { - unsigned int uiIDA[2]; - uiIDA[0]=IDS_CONFIRM_CANCEL; - uiIDA[1]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,NULL, app.GetStringTable()); - } - else + // Give the player the option to save their game + // does the save exist? + bool bSaveExists; + StorageManager.DoesSaveExist(&bSaveExists); + // 4J-PB - we check if the save exists inside the libs + // we need to ask if they are sure they want to overwrite the existing game + if (bSaveExists && StorageManager.GetSaveDisabled()) { + unsigned int uiIDA[2]; + uiIDA[0] = IDS_CONFIRM_CANCEL; + uiIDA[1] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, + 2, ProfileManager.GetPrimaryPad(), + &ClientConnection::ExitGameAndSaveReturned, NULL, + app.GetStringTable()); + } else #else - // Give the player the option to save their game - // does the save exist? - bool bSaveExists; - StorageManager.DoesSaveExist(&bSaveExists); - // 4J-PB - we check if the save exists inside the libs - // we need to ask if they are sure they want to overwrite the existing game - if(bSaveExists) - { - unsigned int uiIDA[2]; - uiIDA[0]=IDS_CONFIRM_CANCEL; - uiIDA[1]=IDS_CONFIRM_OK; - ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, 2, ProfileManager.GetPrimaryPad(),&ClientConnection::ExitGameAndSaveReturned,NULL, app.GetStringTable()); - } - else + // Give the player the option to save their game + // does the save exist? + bool bSaveExists; + StorageManager.DoesSaveExist(&bSaveExists); + // 4J-PB - we check if the save exists inside the libs + // we need to ask if they are sure they want to overwrite the existing game + if (bSaveExists) { + unsigned int uiIDA[2]; + uiIDA[0] = IDS_CONFIRM_CANCEL; + uiIDA[1] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_TITLE_SAVE_GAME, IDS_CONFIRM_SAVE_GAME, uiIDA, + 2, ProfileManager.GetPrimaryPad(), + &ClientConnection::ExitGameAndSaveReturned, NULL, + app.GetStringTable()); + } else #endif - { + { #if defined(_XBOX_ONE) || defined(__ORBIS__) - StorageManager.SetSaveDisabled(false); + StorageManager.SetSaveDisabled(false); #endif - MinecraftServer::getInstance()->setSaveOnExit( true ); - // flag a app action of exit game - app.SetAction(iPad,eAppAction_ExitWorld); - } + MinecraftServer::getInstance()->setSaveOnExit(true); + // flag a app action of exit game + app.SetAction(iPad, eAppAction_ExitWorld); + } - return 0; + return 0; } -int ClientConnection::ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) -{ - // results switched for this dialog - if(result==C4JStorage::EMessage_ResultDecline) - { - //INT saveOrCheckpointId = 0; - //bool validSave = StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); - //SentientManager.RecordLevelSaveOrCheckpoint(ProfileManager.GetPrimaryPad(), saveOrCheckpointId); +int ClientConnection::ExitGameAndSaveReturned( + void* pParam, int iPad, C4JStorage::EMessageResult result) { + // results switched for this dialog + if (result == C4JStorage::EMessage_ResultDecline) { + // INT saveOrCheckpointId = 0; + // bool validSave = + // StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); + // SentientManager.RecordLevelSaveOrCheckpoint(ProfileManager.GetPrimaryPad(), + // saveOrCheckpointId); #if defined(_XBOX_ONE) || defined(__ORBIS__) - StorageManager.SetSaveDisabled(false); + StorageManager.SetSaveDisabled(false); #endif - MinecraftServer::getInstance()->setSaveOnExit( true ); - } - else - { - MinecraftServer::getInstance()->setSaveOnExit( false ); - } - // flag a app action of exit game - app.SetAction(iPad,eAppAction_ExitWorld); - return 0; + MinecraftServer::getInstance()->setSaveOnExit(true); + } else { + MinecraftServer::getInstance()->setSaveOnExit(false); + } + // flag a app action of exit game + app.SetAction(iPad, eAppAction_ExitWorld); + return 0; } -// -std::wstring ClientConnection::GetDisplayNameByGamertag(std::wstring gamertag) -{ +// +std::wstring ClientConnection::GetDisplayNameByGamertag(std::wstring gamertag) { #ifdef _DURANGO - std::wstring displayName = g_NetworkManager.GetDisplayNameByGamertag(gamertag); - return displayName; + std::wstring displayName = + g_NetworkManager.GetDisplayNameByGamertag(gamertag); + return displayName; #else - return gamertag; + return gamertag; #endif } diff --git a/Minecraft.Client/Network/ClientConnection.h b/Minecraft.Client/Network/ClientConnection.h index f901e98fa..58d1dfd77 100644 --- a/Minecraft.Client/Network/ClientConnection.h +++ b/Minecraft.Client/Network/ClientConnection.h @@ -6,81 +6,97 @@ class SavedDataStorage; class Socket; class MultiplayerLocalPlayer; -class ClientConnection : public PacketListener -{ +class ClientConnection : public PacketListener { private: - enum eClientConnectionConnectingState - { - eCCPreLoginSent = 0, - eCCPreLoginReceived, - eCCLoginSent, - eCCLoginReceived, - eCCConnected - }; + enum eClientConnectionConnectingState { + eCCPreLoginSent = 0, + eCCPreLoginReceived, + eCCLoginSent, + eCCLoginReceived, + eCCConnected + }; + private: - bool done; - Connection *connection; + bool done; + Connection* connection; + public: - std::wstring message; - bool createdOk; // 4J added + std::wstring message; + bool createdOk; // 4J added private: - Minecraft *minecraft; - MultiPlayerLevel *level; + Minecraft* minecraft; + MultiPlayerLevel* level; bool started; - // 4J Stu - I don't think we are interested in the PlayerInfo data, so I'm not going to use it at the moment - //Map playerInfoMap = new HashMap(); + // 4J Stu - I don't think we are interested in the PlayerInfo data, so I'm + // not going to use it at the moment + // Map playerInfoMap = new HashMap(); public: - //List playerInfos = new ArrayList(); + // List playerInfos = new ArrayList(); - int maxPlayers; + int maxPlayers; public: - bool isStarted() { return started; } // 4J Added - bool isClosed() { return done; } // 4J Added - Socket *getSocket() { return connection->getSocket(); } // 4J Added + bool isStarted() { return started; } // 4J Added + bool isClosed() { return done; } // 4J Added + Socket* getSocket() { return connection->getSocket(); } // 4J Added private: - int m_userIndex; // 4J Added + int m_userIndex; // 4J Added public: - SavedDataStorage *savedDataStorage; - ClientConnection(Minecraft *minecraft, const std::wstring& ip, int port); - ClientConnection(Minecraft *minecraft, Socket *socket, int iUserIndex = -1); - ~ClientConnection(); + SavedDataStorage* savedDataStorage; + ClientConnection(Minecraft* minecraft, const std::wstring& ip, int port); + ClientConnection(Minecraft* minecraft, Socket* socket, int iUserIndex = -1); + ~ClientConnection(); void tick(); - INetworkPlayer *getNetworkPlayer(); + INetworkPlayer* getNetworkPlayer(); virtual void handleLogin(std::shared_ptr packet); virtual void handleAddEntity(std::shared_ptr packet); - virtual void handleAddExperienceOrb(std::shared_ptr packet); - virtual void handleAddGlobalEntity(std::shared_ptr packet); + virtual void handleAddExperienceOrb( + std::shared_ptr packet); + virtual void handleAddGlobalEntity( + std::shared_ptr packet); virtual void handleAddPainting(std::shared_ptr packet); - virtual void handleSetEntityMotion(std::shared_ptr packet); - virtual void handleSetEntityData(std::shared_ptr packet); + virtual void handleSetEntityMotion( + std::shared_ptr packet); + virtual void handleSetEntityData( + std::shared_ptr packet); virtual void handleAddPlayer(std::shared_ptr packet); - virtual void handleTeleportEntity(std::shared_ptr packet); + virtual void handleTeleportEntity( + std::shared_ptr packet); virtual void handleMoveEntity(std::shared_ptr packet); - virtual void handleRotateMob(std::shared_ptr packet); - virtual void handleMoveEntitySmall(std::shared_ptr packet); - virtual void handleRemoveEntity(std::shared_ptr packet); - virtual void handleMovePlayer(std::shared_ptr packet); + virtual void handleRotateMob(std::shared_ptr packet); + virtual void handleMoveEntitySmall( + std::shared_ptr packet); + virtual void handleRemoveEntity( + std::shared_ptr packet); + virtual void handleMovePlayer(std::shared_ptr packet); - Random *random; - - // 4J Added - virtual void handleChunkVisibilityArea(std::shared_ptr packet); + Random* random; - virtual void handleChunkVisibility(std::shared_ptr packet); - virtual void handleChunkTilesUpdate(std::shared_ptr packet); - virtual void handleBlockRegionUpdate(std::shared_ptr packet); + // 4J Added + virtual void handleChunkVisibilityArea( + std::shared_ptr packet); + + virtual void handleChunkVisibility( + std::shared_ptr packet); + virtual void handleChunkTilesUpdate( + std::shared_ptr packet); + virtual void handleBlockRegionUpdate( + std::shared_ptr packet); virtual void handleTileUpdate(std::shared_ptr packet); virtual void handleDisconnect(std::shared_ptr packet); - virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); + virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects); void sendAndDisconnect(std::shared_ptr packet); void send(std::shared_ptr packet); - virtual void handleTakeItemEntity(std::shared_ptr packet); + virtual void handleTakeItemEntity( + std::shared_ptr packet); virtual void handleChat(std::shared_ptr packet); virtual void handleAnimate(std::shared_ptr packet); - virtual void handleEntityActionAtPosition(std::shared_ptr packet); + virtual void handleEntityActionAtPosition( + std::shared_ptr packet); virtual void handlePreLogin(std::shared_ptr packet); void close(); virtual void handleAddMob(std::shared_ptr packet); @@ -88,53 +104,79 @@ public: virtual void handleSetSpawn(std::shared_ptr packet); virtual void handleRidePacket(std::shared_ptr packet); virtual void handleEntityEvent(std::shared_ptr packet); + private: - std::shared_ptr getEntity(int entityId); - std::wstring GetDisplayNameByGamertag(std::wstring gamertag); + std::shared_ptr getEntity(int entityId); + std::wstring GetDisplayNameByGamertag(std::wstring gamertag); + public: virtual void handleSetHealth(std::shared_ptr packet); - virtual void handleSetExperience(std::shared_ptr packet); + virtual void handleSetExperience( + std::shared_ptr packet); virtual void handleRespawn(std::shared_ptr packet); virtual void handleExplosion(std::shared_ptr packet); - virtual void handleContainerOpen(std::shared_ptr packet); - virtual void handleContainerSetSlot(std::shared_ptr packet); + virtual void handleContainerOpen( + std::shared_ptr packet); + virtual void handleContainerSetSlot( + std::shared_ptr packet); virtual void handleContainerAck(std::shared_ptr packet); - virtual void handleContainerContent(std::shared_ptr packet); + virtual void handleContainerContent( + std::shared_ptr packet); virtual void handleSignUpdate(std::shared_ptr packet); - virtual void handleTileEntityData(std::shared_ptr packet); - virtual void handleContainerSetData(std::shared_ptr packet); - virtual void handleSetEquippedItem(std::shared_ptr packet); - virtual void handleContainerClose(std::shared_ptr packet); + virtual void handleTileEntityData( + std::shared_ptr packet); + virtual void handleContainerSetData( + std::shared_ptr packet); + virtual void handleSetEquippedItem( + std::shared_ptr packet); + virtual void handleContainerClose( + std::shared_ptr packet); virtual void handleTileEvent(std::shared_ptr packet); - virtual void handleTileDestruction(std::shared_ptr packet); - virtual bool canHandleAsyncPackets(); - virtual void handleGameEvent(std::shared_ptr gameEventPacket); - virtual void handleComplexItemData(std::shared_ptr packet); + virtual void handleTileDestruction( + std::shared_ptr packet); + virtual bool canHandleAsyncPackets(); + virtual void handleGameEvent( + std::shared_ptr gameEventPacket); + virtual void handleComplexItemData( + std::shared_ptr packet); virtual void handleLevelEvent(std::shared_ptr packet); virtual void handleAwardStat(std::shared_ptr packet); - virtual void handleUpdateMobEffect(std::shared_ptr packet); - virtual void handleRemoveMobEffect(std::shared_ptr packet); - virtual bool isServerPacketListener(); - virtual void handlePlayerInfo(std::shared_ptr packet); - virtual void handleKeepAlive(std::shared_ptr packet); - virtual void handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket); - virtual void handleSoundEvent(std::shared_ptr packet); - virtual void handleCustomPayload(std::shared_ptr customPayloadPacket); - virtual Connection *getConnection(); + virtual void handleUpdateMobEffect( + std::shared_ptr packet); + virtual void handleRemoveMobEffect( + std::shared_ptr packet); + virtual bool isServerPacketListener(); + virtual void handlePlayerInfo(std::shared_ptr packet); + virtual void handleKeepAlive(std::shared_ptr packet); + virtual void handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket); + virtual void handleSoundEvent(std::shared_ptr packet); + virtual void handleCustomPayload( + std::shared_ptr customPayloadPacket); + virtual Connection* getConnection(); - // 4J Added - virtual void handleServerSettingsChanged(std::shared_ptr packet); - virtual void handleTexture(std::shared_ptr packet); - virtual void handleTextureAndGeometry(std::shared_ptr packet); - virtual void handleUpdateProgress(std::shared_ptr packet); + // 4J Added + virtual void handleServerSettingsChanged( + std::shared_ptr packet); + virtual void handleTexture(std::shared_ptr packet); + virtual void handleTextureAndGeometry( + std::shared_ptr packet); + virtual void handleUpdateProgress( + std::shared_ptr packet); - // 4J Added - static int HostDisconnectReturned(void *pParam,int iPad,C4JStorage::EMessageResult result); - static int ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage::EMessageResult result); - virtual void handleTextureChange(std::shared_ptr packet); - virtual void handleTextureAndGeometryChange(std::shared_ptr packet); - virtual void handleUpdateGameRuleProgressPacket(std::shared_ptr packet); - virtual void handleXZ(std::shared_ptr packet); + // 4J Added + static int HostDisconnectReturned(void* pParam, int iPad, + C4JStorage::EMessageResult result); + static int ExitGameAndSaveReturned(void* pParam, int iPad, + C4JStorage::EMessageResult result); + virtual void handleTextureChange( + std::shared_ptr packet); + virtual void handleTextureAndGeometryChange( + std::shared_ptr packet); + virtual void handleUpdateGameRuleProgressPacket( + std::shared_ptr packet); + virtual void handleXZ(std::shared_ptr packet); - void displayPrivilegeChanges(std::shared_ptr player, unsigned int oldPrivileges); + void displayPrivilegeChanges(std::shared_ptr player, + unsigned int oldPrivileges); }; diff --git a/Minecraft.Client/Network/MultiPlayerChunkCache.cpp b/Minecraft.Client/Network/MultiPlayerChunkCache.cpp index f4e3f7d0b..74648c2ad 100644 --- a/Minecraft.Client/Network/MultiPlayerChunkCache.cpp +++ b/Minecraft.Client/Network/MultiPlayerChunkCache.cpp @@ -10,297 +10,287 @@ #include "../../Minecraft.World/Blocks/Tile.h" #include "../../Minecraft.World/Level/WaterLevelChunk.h" -MultiPlayerChunkCache::MultiPlayerChunkCache(Level *level) -{ - XZSIZE = level->dimension->getXZSize(); // 4J Added - XZOFFSET = XZSIZE/2; // 4J Added - m_XZSize = XZSIZE; - hasData = new bool[XZSIZE * XZSIZE]; - memset(hasData, 0, sizeof(bool) * XZSIZE * XZSIZE); +MultiPlayerChunkCache::MultiPlayerChunkCache(Level* level) { + XZSIZE = level->dimension->getXZSize(); // 4J Added + XZOFFSET = XZSIZE / 2; // 4J Added + m_XZSize = XZSIZE; + hasData = new bool[XZSIZE * XZSIZE]; + memset(hasData, 0, sizeof(bool) * XZSIZE * XZSIZE); - emptyChunk = new EmptyLevelChunk(level, byteArray(16 * 16 * Level::maxBuildHeight), 0, 0); + emptyChunk = new EmptyLevelChunk( + level, byteArray(16 * 16 * Level::maxBuildHeight), 0, 0); - // For normal world dimension, create a chunk that can be used to create the illusion of infinite water at the edge of the world - if( level->dimension->id == 0 ) - { - byteArray bytes = byteArray(16 * 16 * 128); + // For normal world dimension, create a chunk that can be used to create the + // illusion of infinite water at the edge of the world + if (level->dimension->id == 0) { + byteArray bytes = byteArray(16 * 16 * 128); - // Superflat.... make grass, not water... - if(level->getLevelData()->getGenerator() == LevelType::lvl_flat) - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - unsigned char tileId = 0; - if( y == 3 ) tileId = Tile::grass_Id; - else if( y <= 2 ) tileId = Tile::dirt_Id; + // Superflat.... make grass, not water... + if (level->getLevelData()->getGenerator() == LevelType::lvl_flat) { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + unsigned char tileId = 0; + if (y == 3) + tileId = Tile::grass_Id; + else if (y <= 2) + tileId = Tile::dirt_Id; - bytes[x << 11 | z << 7 | y] = tileId; - } - } - else - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - unsigned char tileId = 0; - if( y <= ( level->getSeaLevel() - 10 ) ) tileId = Tile::rock_Id; - else if( y < level->getSeaLevel() ) tileId = Tile::calmWater_Id; + bytes[x << 11 | z << 7 | y] = tileId; + } + } else { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + unsigned char tileId = 0; + if (y <= (level->getSeaLevel() - 10)) + tileId = Tile::rock_Id; + else if (y < level->getSeaLevel()) + tileId = Tile::calmWater_Id; - bytes[x << 11 | z << 7 | y] = tileId; - } - } + bytes[x << 11 | z << 7 | y] = tileId; + } + } - waterChunk = new WaterLevelChunk(level, bytes, 0, 0); + waterChunk = new WaterLevelChunk(level, bytes, 0, 0); - delete[] bytes.data; + delete[] bytes.data; - if(level->getLevelData()->getGenerator() == LevelType::lvl_flat) - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - if( y >= 3 ) - { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); - } - } - } - else - { - for( int x = 0; x < 16; x++ ) - for( int y = 0; y < 128; y++ ) - for( int z = 0; z < 16; z++ ) - { - if( y >= ( level->getSeaLevel() - 1 ) ) - { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); - } - else - { - ((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,2); - } - } - } - } - else - { - waterChunk = NULL; - } + if (level->getLevelData()->getGenerator() == LevelType::lvl_flat) { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + if (y >= 3) { + ((WaterLevelChunk*)waterChunk) + ->setLevelChunkBrightness(LightLayer::Sky, x, y, + z, 15); + } + } + } else { + for (int x = 0; x < 16; x++) + for (int y = 0; y < 128; y++) + for (int z = 0; z < 16; z++) { + if (y >= (level->getSeaLevel() - 1)) { + ((WaterLevelChunk*)waterChunk) + ->setLevelChunkBrightness(LightLayer::Sky, x, y, + z, 15); + } else { + ((WaterLevelChunk*)waterChunk) + ->setLevelChunkBrightness(LightLayer::Sky, x, y, + z, 2); + } + } + } + } else { + waterChunk = NULL; + } - this->level = level; + this->level = level; - this->cache = new LevelChunk *[XZSIZE * XZSIZE]; - memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk *)); - InitializeCriticalSectionAndSpinCount(&m_csLoadCreate,4000); + this->cache = new LevelChunk*[XZSIZE * XZSIZE]; + memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*)); + InitializeCriticalSectionAndSpinCount(&m_csLoadCreate, 4000); } -MultiPlayerChunkCache::~MultiPlayerChunkCache() -{ - delete emptyChunk; - delete waterChunk; - delete cache; - delete hasData; +MultiPlayerChunkCache::~MultiPlayerChunkCache() { + delete emptyChunk; + delete waterChunk; + delete cache; + delete hasData; - AUTO_VAR(itEnd, loadedChunkList.end()); - for (AUTO_VAR(it, loadedChunkList.begin()); it != itEnd; it++) - delete *it; + AUTO_VAR(itEnd, loadedChunkList.end()); + for (AUTO_VAR(it, loadedChunkList.begin()); it != itEnd; it++) delete *it; - DeleteCriticalSection(&m_csLoadCreate); + DeleteCriticalSection(&m_csLoadCreate); } - -bool MultiPlayerChunkCache::hasChunk(int x, int z) -{ - // This cache always claims to have chunks, although it might actually just return empty data if it doesn't have anything - return true; +bool MultiPlayerChunkCache::hasChunk(int x, int z) { + // This cache always claims to have chunks, although it might actually just + // return empty data if it doesn't have anything + return true; } // 4J added - find out if we actually really do have a chunk in our cache -bool MultiPlayerChunkCache::reallyHasChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if we aren't, then consider that we do have that chunk as we'll be able to use the water chunk there - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return true; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return true; - int idx = ix * XZSIZE + iz; +bool MultiPlayerChunkCache::reallyHasChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level - if we aren't, then consider + // that we do have that chunk as we'll be able to use the water chunk there + if ((ix < 0) || (ix >= XZSIZE)) return true; + if ((iz < 0) || (iz >= XZSIZE)) return true; + int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - if( chunk == NULL ) - { - return false; - } - return hasData[idx]; + LevelChunk* chunk = cache[idx]; + if (chunk == NULL) { + return false; + } + return hasData[idx]; } -void MultiPlayerChunkCache::drop(int x, int z) -{ - // 4J Stu - We do want to drop any entities in the chunks, especially for the case when a player is dead as they will - // not get the RemoveEntity packet if an entity is removed. - LevelChunk *chunk = getChunk(x, z); - if (!chunk->isEmpty()) - { - // Added parameter here specifies that we don't want to delete tile entities, as they won't get recreated unless they've got update packets - // The tile entities are in general only created on the client by virtue of the chunk rebuild - chunk->unload(false); +void MultiPlayerChunkCache::drop(int x, int z) { + // 4J Stu - We do want to drop any entities in the chunks, especially for + // the case when a player is dead as they will not get the RemoveEntity + // packet if an entity is removed. + LevelChunk* chunk = getChunk(x, z); + if (!chunk->isEmpty()) { + // Added parameter here specifies that we don't want to delete tile + // entities, as they won't get recreated unless they've got update + // packets The tile entities are in general only created on the client + // by virtue of the chunk rebuild + chunk->unload(false); - // 4J - We just want to clear out the entities in the chunk, but everything else should be valid - chunk->loaded = true; + // 4J - We just want to clear out the entities in the chunk, but + // everything else should be valid + chunk->loaded = true; } } -LevelChunk *MultiPlayerChunkCache::create(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - LevelChunk *lastChunk = chunk; +LevelChunk* MultiPlayerChunkCache::create(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + if ((iz < 0) || (iz >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + int idx = ix * XZSIZE + iz; + LevelChunk* chunk = cache[idx]; + LevelChunk* lastChunk = chunk; - if( chunk == NULL ) - { - EnterCriticalSection(&m_csLoadCreate); + if (chunk == NULL) { + EnterCriticalSection(&m_csLoadCreate); - //LevelChunk *chunk; - if( g_NetworkManager.IsHost() ) // force here to disable sharing of data - { - // 4J-JEV: We are about to use shared data, abort if the server is stopped and the data is deleted. - if (MinecraftServer::getInstance()->serverHalted()) return NULL; + // LevelChunk *chunk; + if (g_NetworkManager.IsHost()) // force here to disable sharing of data + { + // 4J-JEV: We are about to use shared data, abort if the server is + // stopped and the data is deleted. + if (MinecraftServer::getInstance()->serverHalted()) return NULL; - // If we're the host, then don't create the chunk, share data from the server's copy + // If we're the host, then don't create the chunk, share data from + // the server's copy #ifdef _LARGE_WORLDS - LevelChunk *serverChunk = MinecraftServer::getInstance()->getLevel(level->dimension->id)->cache->getChunkLoadedOrUnloaded(x,z); + LevelChunk* serverChunk = + MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunkLoadedOrUnloaded(x, z); #else - LevelChunk *serverChunk = MinecraftServer::getInstance()->getLevel(level->dimension->id)->cache->getChunk(x,z); + LevelChunk* serverChunk = MinecraftServer::getInstance() + ->getLevel(level->dimension->id) + ->cache->getChunk(x, z); #endif - chunk = new LevelChunk(level, x, z, serverChunk); - // Let renderer know that this chunk has been created - it might have made render data from the EmptyChunk if it got to a chunk before the server sent it - level->setTilesDirty( x * 16 , 0 , z * 16 , x * 16 + 15, 127, z * 16 + 15); - hasData[idx] = true; - } - else - { - // Passing an empty array into the LevelChunk ctor, which it now detects and sets up the chunk as compressed & empty - byteArray bytes; + chunk = new LevelChunk(level, x, z, serverChunk); + // Let renderer know that this chunk has been created - it might + // have made render data from the EmptyChunk if it got to a chunk + // before the server sent it + level->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, 127, + z * 16 + 15); + hasData[idx] = true; + } else { + // Passing an empty array into the LevelChunk ctor, which it now + // detects and sets up the chunk as compressed & empty + byteArray bytes; - chunk = new LevelChunk(level, bytes, x, z); + chunk = new LevelChunk(level, bytes, x, z); - // 4J - changed to use new methods for lighting - chunk->setSkyLightDataAllBright(); -// Arrays::fill(chunk->skyLight->data, (uint8_t) 255); - } - - chunk->loaded = true; + // 4J - changed to use new methods for lighting + chunk->setSkyLightDataAllBright(); + // Arrays::fill(chunk->skyLight->data, (uint8_t) + //255); + } - LeaveCriticalSection(&m_csLoadCreate); + chunk->loaded = true; -#if ( defined _WIN64 || defined __LP64__ ) - if( InterlockedCompareExchangeRelease64((LONG64 *)&cache[idx],(LONG64)chunk,(LONG64)lastChunk) == (LONG64)lastChunk ) + LeaveCriticalSection(&m_csLoadCreate); + +#if (defined _WIN64 || defined __LP64__) + if (InterlockedCompareExchangeRelease64( + (LONG64*)&cache[idx], (LONG64)chunk, (LONG64)lastChunk) == + (LONG64)lastChunk) #else - if( InterlockedCompareExchangeRelease((LONG *)&cache[idx],(LONG)chunk,(LONG)lastChunk) == (LONG)lastChunk ) -#endif // _DURANGO - { - // If we're sharing with the server, we'll need to calculate our heightmap now, which isn't shared. If we aren't sharing with the server, - // then this will be calculated when the chunk data arrives. - if( g_NetworkManager.IsHost() ) - { - chunk->recalcHeightmapOnly(); - } + if (InterlockedCompareExchangeRelease((LONG*)&cache[idx], (LONG)chunk, + (LONG)lastChunk) == + (LONG)lastChunk) +#endif // _DURANGO + { + // If we're sharing with the server, we'll need to calculate our + // heightmap now, which isn't shared. If we aren't sharing with the + // server, then this will be calculated when the chunk data arrives. + if (g_NetworkManager.IsHost()) { + chunk->recalcHeightmapOnly(); + } - // Successfully updated the cache - EnterCriticalSection(&m_csLoadCreate); - loadedChunkList.push_back(chunk); - LeaveCriticalSection(&m_csLoadCreate); - } - else - { - // Something else must have updated the cache. Return that chunk and discard this one. This really shouldn't be happening - // in multiplayer - delete chunk; - return cache[idx]; - } + // Successfully updated the cache + EnterCriticalSection(&m_csLoadCreate); + loadedChunkList.push_back(chunk); + LeaveCriticalSection(&m_csLoadCreate); + } else { + // Something else must have updated the cache. Return that chunk and + // discard this one. This really shouldn't be happening in + // multiplayer + delete chunk; + return cache[idx]; + } - } - else - { - chunk->load(); - } + } else { + chunk->load(); + } - return chunk; + return chunk; } -LevelChunk *MultiPlayerChunkCache::getChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); - int idx = ix * XZSIZE + iz; +LevelChunk* MultiPlayerChunkCache::getChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + if ((iz < 0) || (iz >= XZSIZE)) + return (waterChunk ? waterChunk : emptyChunk); + int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - if( chunk == NULL ) - { - return emptyChunk; - } - else - { - return chunk; - } + LevelChunk* chunk = cache[idx]; + if (chunk == NULL) { + return emptyChunk; + } else { + return chunk; + } } -bool MultiPlayerChunkCache::save(bool force, ProgressListener *progressListener) -{ - return true; +bool MultiPlayerChunkCache::save(bool force, + ProgressListener* progressListener) { + return true; } -bool MultiPlayerChunkCache::tick() -{ - return false; +bool MultiPlayerChunkCache::tick() { return false; } + +bool MultiPlayerChunkCache::shouldSave() { return false; } + +void MultiPlayerChunkCache::postProcess(ChunkSource* parent, int x, int z) {} + +std::vector* MultiPlayerChunkCache::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + return NULL; } -bool MultiPlayerChunkCache::shouldSave() -{ - return false; +TilePos* MultiPlayerChunkCache::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return NULL; } -void MultiPlayerChunkCache::postProcess(ChunkSource *parent, int x, int z) -{ +std::wstring MultiPlayerChunkCache::gatherStats() { + EnterCriticalSection(&m_csLoadCreate); + int size = (int)loadedChunkList.size(); + LeaveCriticalSection(&m_csLoadCreate); + return L"MultiplayerChunkCache: " + _toString(size); } -std::vector *MultiPlayerChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - return NULL; -} - -TilePos *MultiPlayerChunkCache::findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z) -{ - return NULL; -} - -std::wstring MultiPlayerChunkCache::gatherStats() -{ - EnterCriticalSection(&m_csLoadCreate); - int size = (int)loadedChunkList.size(); - LeaveCriticalSection(&m_csLoadCreate); - return L"MultiplayerChunkCache: " + _toString(size); - -} - -void MultiPlayerChunkCache::dataReceived(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return; - int idx = ix * XZSIZE + iz; - hasData[idx] = true; +void MultiPlayerChunkCache::dataReceived(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return; + if ((iz < 0) || (iz >= XZSIZE)) return; + int idx = ix * XZSIZE + iz; + hasData[idx] = true; } \ No newline at end of file diff --git a/Minecraft.Client/Network/MultiPlayerChunkCache.h b/Minecraft.Client/Network/MultiPlayerChunkCache.h index a9df81eac..09710048d 100644 --- a/Minecraft.Client/Network/MultiPlayerChunkCache.h +++ b/Minecraft.Client/Network/MultiPlayerChunkCache.h @@ -3,45 +3,48 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h" #include "../../Minecraft.World/Level/RandomLevelSource.h" - class ServerChunkCache; -// 4J - various alterations here to make this thread safe, and operate as a fixed sized cache -class MultiPlayerChunkCache : public ChunkSource -{ - friend class LevelRenderer; +// 4J - various alterations here to make this thread safe, and operate as a +// fixed sized cache +class MultiPlayerChunkCache : public ChunkSource { + friend class LevelRenderer; + private: - LevelChunk *emptyChunk; - LevelChunk *waterChunk; + LevelChunk* emptyChunk; + LevelChunk* waterChunk; - std::vector loadedChunkList; + std::vector loadedChunkList; - LevelChunk **cache; - // 4J - added for multithreaded support - CRITICAL_SECTION m_csLoadCreate; - // 4J - size of cache is defined by size of one side - must be even - int XZSIZE; - int XZOFFSET; - bool *hasData; + LevelChunk** cache; + // 4J - added for multithreaded support + CRITICAL_SECTION m_csLoadCreate; + // 4J - size of cache is defined by size of one side - must be even + int XZSIZE; + int XZOFFSET; + bool* hasData; - Level *level; + Level* level; public: - MultiPlayerChunkCache(Level *level); - ~MultiPlayerChunkCache(); + MultiPlayerChunkCache(Level* level); + ~MultiPlayerChunkCache(); virtual bool hasChunk(int x, int z); - virtual bool reallyHasChunk(int x, int z); + virtual bool reallyHasChunk(int x, int z); virtual void drop(int x, int z); - virtual LevelChunk *create(int x, int z); - virtual LevelChunk *getChunk(int x, int z); - virtual bool save(bool force, ProgressListener *progressListener); + virtual LevelChunk* create(int x, int z); + virtual LevelChunk* getChunk(int x, int z); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); - virtual void postProcess(ChunkSource *parent, int x, int z); + virtual void postProcess(ChunkSource* parent, int x, int z); virtual std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z); - virtual void dataReceived(int x, int z); // 4J added + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); + virtual void dataReceived(int x, int z); // 4J added - virtual LevelChunk **getCache() { return cache; } // 4J added + virtual LevelChunk** getCache() { return cache; } // 4J added }; \ No newline at end of file diff --git a/Minecraft.Client/Network/PendingConnection.cpp b/Minecraft.Client/Network/PendingConnection.cpp index 80bc0f043..bd86e35e4 100644 --- a/Minecraft.Client/Network/PendingConnection.cpp +++ b/Minecraft.Client/Network/PendingConnection.cpp @@ -19,112 +19,108 @@ // #include "PS3/Network/NetworkPlayerSony.h" // #endif -Random *PendingConnection::random = new Random(); +Random* PendingConnection::random = new Random(); -PendingConnection::PendingConnection(MinecraftServer *server, Socket *socket, const std::wstring& id) -{ - // 4J - added initialisers - done = false; +PendingConnection::PendingConnection(MinecraftServer* server, Socket* socket, + const std::wstring& id) { + // 4J - added initialisers + done = false; _tick = 0; name = L""; acceptedLogin = nullptr; - loginKey = L""; + loginKey = L""; this->server = server; connection = new Connection(socket, id, this); connection->fakeLag = FAKE_LAG; } -PendingConnection::~PendingConnection() -{ - delete connection; -} +PendingConnection::~PendingConnection() { delete connection; } -void PendingConnection::tick() -{ - if (acceptedLogin != NULL) - { +void PendingConnection::tick() { + if (acceptedLogin != NULL) { this->handleAcceptedLogin(acceptedLogin); acceptedLogin = nullptr; } - if (_tick++ == MAX_TICKS_BEFORE_LOGIN) - { + if (_tick++ == MAX_TICKS_BEFORE_LOGIN) { disconnect(DisconnectPacket::eDisconnect_LoginTooLong); - } - else - { + } else { connection->tick(); } } -void PendingConnection::disconnect(DisconnectPacket::eDisconnectReason reason) -{ - // try { // 4J - removed try/catch -// logger.info("Disconnecting " + getName() + ": " + reason); - fprintf(stderr, "[PENDING] disconnect called with reason=%d at tick=%d\n", reason, _tick); - app.DebugPrintf("Pending connection disconnect: %d\n", reason ); - connection->send( std::shared_ptr( new DisconnectPacket(reason) ) ); - connection->sendAndQuit(); - done = true; -// } catch (Exception e) { -// e.printStackTrace(); -// } +void PendingConnection::disconnect(DisconnectPacket::eDisconnectReason reason) { + // try { // 4J - removed try/catch + // logger.info("Disconnecting " + getName() + ": " + reason); + fprintf(stderr, "[PENDING] disconnect called with reason=%d at tick=%d\n", + reason, _tick); + app.DebugPrintf("Pending connection disconnect: %d\n", reason); + connection->send( + std::shared_ptr(new DisconnectPacket(reason))); + connection->sendAndQuit(); + done = true; + // } catch (Exception e) { + // e.printStackTrace(); + // } } -void PendingConnection::handlePreLogin(std::shared_ptr packet) -{ - if (packet->m_netcodeVersion != MINECRAFT_NET_VERSION) - { - app.DebugPrintf("Netcode version is %d not equal to %d\n", packet->m_netcodeVersion, MINECRAFT_NET_VERSION); - if (packet->m_netcodeVersion > MINECRAFT_NET_VERSION) - { +void PendingConnection::handlePreLogin(std::shared_ptr packet) { + if (packet->m_netcodeVersion != MINECRAFT_NET_VERSION) { + app.DebugPrintf("Netcode version is %d not equal to %d\n", + packet->m_netcodeVersion, MINECRAFT_NET_VERSION); + if (packet->m_netcodeVersion > MINECRAFT_NET_VERSION) { disconnect(DisconnectPacket::eDisconnect_OutdatedServer); - } - else - { + } else { disconnect(DisconnectPacket::eDisconnect_OutdatedClient); } return; } -// printf("Server: handlePreLogin\n"); - name = packet->loginKey; // 4J Stu - Change from the login packet as we know better on client end during the pre-login packet - sendPreLoginResponse(); + // printf("Server: handlePreLogin\n"); + name = + packet->loginKey; // 4J Stu - Change from the login packet as we know + // better on client end during the pre-login packet + sendPreLoginResponse(); } -void PendingConnection::sendPreLoginResponse() -{ - // 4J Stu - Calculate the players with UGC privileges set - PlayerUID *ugcXuids = new PlayerUID[MINECRAFT_NET_MAX_PLAYERS]; - std::uint8_t ugcXuidCount = 0; - std::uint8_t hostIndex = 0; - std::uint8_t ugcFriendsOnlyBits = 0; - char szUniqueMapName[14]; +void PendingConnection::sendPreLoginResponse() { + // 4J Stu - Calculate the players with UGC privileges set + PlayerUID* ugcXuids = new PlayerUID[MINECRAFT_NET_MAX_PLAYERS]; + std::uint8_t ugcXuidCount = 0; + std::uint8_t hostIndex = 0; + std::uint8_t ugcFriendsOnlyBits = 0; + char szUniqueMapName[14]; - StorageManager.GetSaveUniqueFilename(szUniqueMapName); + StorageManager.GetSaveUniqueFilename(szUniqueMapName); - PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); - for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) - { - std::shared_ptr player = *it; - // If the offline Xuid is invalid but the online one is not then that's guest which we should ignore - // If the online Xuid is invalid but the offline one is not then we are definitely an offline game so dont care about UGC - - // PADDY - this is failing when a local player with chat restrictions joins an online game + PlayerList* playerList = MinecraftServer::getInstance()->getPlayers(); + for (AUTO_VAR(it, playerList->players.begin()); + it != playerList->players.end(); ++it) { + std::shared_ptr player = *it; + // If the offline Xuid is invalid but the online one is not then that's + // guest which we should ignore If the online Xuid is invalid but the + // offline one is not then we are definitely an offline game so dont + // care about UGC - if( player != NULL && player->connection->m_offlineXUID != INVALID_XUID && player->connection->m_onlineXUID != INVALID_XUID ) - { - if( player->connection->m_friendsOnlyUGC ) - { - ugcFriendsOnlyBits |= (1<connection->m_onlineXUID; + // PADDY - this is failing when a local player with chat restrictions + // joins an online game - if( player->connection->getNetworkPlayer() != NULL && player->connection->getNetworkPlayer()->IsHost() ) hostIndex = ugcXuidCount; + if (player != NULL && + player->connection->m_offlineXUID != INVALID_XUID && + player->connection->m_onlineXUID != INVALID_XUID) { + if (player->connection->m_friendsOnlyUGC) { + ugcFriendsOnlyBits |= (1 << ugcXuidCount); + } + // Need to use the online XUID otherwise friend checks will fail on + // the client + ugcXuids[ugcXuidCount] = player->connection->m_onlineXUID; - ++ugcXuidCount; - } - } + if (player->connection->getNetworkPlayer() != NULL && + player->connection->getNetworkPlayer()->IsHost()) + hostIndex = ugcXuidCount; + + ++ugcXuidCount; + } + } #if 0 if (false)// server->onlineMode) // 4J - removed @@ -134,47 +130,44 @@ void PendingConnection::sendPreLoginResponse() } else #endif - { - connection->send( std::shared_ptr( new PreLoginPacket(L"-", ugcXuids, ugcXuidCount, ugcFriendsOnlyBits, server->m_ugcPlayersVersion,szUniqueMapName,app.GetGameHostOption(eGameHostOption_All),hostIndex, server->m_texturePackId) ) ); + { + connection->send(std::shared_ptr( + new PreLoginPacket(L"-", ugcXuids, ugcXuidCount, ugcFriendsOnlyBits, + server->m_ugcPlayersVersion, szUniqueMapName, + app.GetGameHostOption(eGameHostOption_All), + hostIndex, server->m_texturePackId))); } } -void PendingConnection::handleLogin(std::shared_ptr packet) -{ - fprintf(stderr, "[LOGIN-SRV] handleLogin called! clientVersion=%d\n", packet->clientVersion); - //name = packet->userName; - if (packet->clientVersion != SharedConstants::NETWORK_PROTOCOL_VERSION) - { - app.DebugPrintf("Client version is %d not equal to %d\n", packet->clientVersion, SharedConstants::NETWORK_PROTOCOL_VERSION); - if (packet->clientVersion > SharedConstants::NETWORK_PROTOCOL_VERSION) - { +void PendingConnection::handleLogin(std::shared_ptr packet) { + fprintf(stderr, "[LOGIN-SRV] handleLogin called! clientVersion=%d\n", + packet->clientVersion); + // name = packet->userName; + if (packet->clientVersion != SharedConstants::NETWORK_PROTOCOL_VERSION) { + app.DebugPrintf("Client version is %d not equal to %d\n", + packet->clientVersion, + SharedConstants::NETWORK_PROTOCOL_VERSION); + if (packet->clientVersion > SharedConstants::NETWORK_PROTOCOL_VERSION) { disconnect(DisconnectPacket::eDisconnect_OutdatedServer); - } - else - { + } else { disconnect(DisconnectPacket::eDisconnect_OutdatedClient); } return; } - //if (true)// 4J removed !server->onlineMode) - bool sentDisconnect = false; + // if (true)// 4J removed !server->onlineMode) + bool sentDisconnect = false; - if( sentDisconnect ) - { - // Do nothing - } - else if( server->getPlayers()->isXuidBanned( packet->m_onlineXuid ) ) - { - disconnect(DisconnectPacket::eDisconnect_Banned); - } - else - { + if (sentDisconnect) { + // Do nothing + } else if (server->getPlayers()->isXuidBanned(packet->m_onlineXuid)) { + disconnect(DisconnectPacket::eDisconnect_Banned); + } else { handleAcceptedLogin(packet); } - //else - { - //4J - removed + // else + { + // 4J - removed #if 0 new Thread() { public void run() { @@ -197,75 +190,71 @@ void PendingConnection::handleLogin(std::shared_ptr packet) }.start(); #endif } - } -void PendingConnection::handleAcceptedLogin(std::shared_ptr packet) -{ - if(packet->m_ugcPlayersVersion != server->m_ugcPlayersVersion) - { - // Send the pre-login packet again with the new list of players - sendPreLoginResponse(); - return; - } +void PendingConnection::handleAcceptedLogin( + std::shared_ptr packet) { + if (packet->m_ugcPlayersVersion != server->m_ugcPlayersVersion) { + // Send the pre-login packet again with the new list of players + sendPreLoginResponse(); + return; + } - // Guests use the online xuid, everyone else uses the offline one - PlayerUID playerXuid = packet->m_offlineXuid; - if(playerXuid == INVALID_XUID) playerXuid = packet->m_onlineXuid; + // Guests use the online xuid, everyone else uses the offline one + PlayerUID playerXuid = packet->m_offlineXuid; + if (playerXuid == INVALID_XUID) playerXuid = packet->m_onlineXuid; - std::shared_ptr playerEntity = server->getPlayers()->getPlayerForLogin(this, name, playerXuid,packet->m_onlineXuid); - if (playerEntity != NULL) - { + std::shared_ptr playerEntity = + server->getPlayers()->getPlayerForLogin(this, name, playerXuid, + packet->m_onlineXuid); + if (playerEntity != NULL) { server->getPlayers()->placeNewPlayer(connection, playerEntity, packet); - connection = NULL; // We've moved responsibility for this over to the new PlayerConnection, NULL so we don't delete our reference to it here in our dtor + connection = NULL; // We've moved responsibility for this over to the + // new PlayerConnection, NULL so we don't delete our + // reference to it here in our dtor } done = true; - } -void PendingConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) -{ -// logger.info(getName() + " lost connection"); +void PendingConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects) { + // logger.info(getName() + " lost connection"); done = true; } -void PendingConnection::handleGetInfo(std::shared_ptr packet) -{ - //try { - //String message = server->motd + "§" + server->players->getPlayerCount() + "§" + server->players->getMaxPlayers(); - //connection->send(new DisconnectPacket(message)); - connection->send(std::shared_ptr(new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull) ) ); - connection->sendAndQuit(); - server->connection->removeSpamProtection(connection->getSocket()); - done = true; - //} catch (Exception e) { - // e.printStackTrace(); - //} +void PendingConnection::handleGetInfo(std::shared_ptr packet) { + // try { + // String message = server->motd + "§" + server->players->getPlayerCount() + + // "§" + server->players->getMaxPlayers(); connection->send(new + // DisconnectPacket(message)); + connection->send(std::shared_ptr( + new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull))); + connection->sendAndQuit(); + server->connection->removeSpamProtection(connection->getSocket()); + done = true; + //} catch (Exception e) { + // e.printStackTrace(); + //} } -void PendingConnection::handleKeepAlive(std::shared_ptr packet) -{ - // Ignore +void PendingConnection::handleKeepAlive( + std::shared_ptr packet) { + // Ignore } -void PendingConnection::onUnhandledPacket(std::shared_ptr packet) -{ - disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); +void PendingConnection::onUnhandledPacket(std::shared_ptr packet) { + disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); } -void PendingConnection::send(std::shared_ptr packet) -{ - connection->send(packet); +void PendingConnection::send(std::shared_ptr packet) { + connection->send(packet); } -std::wstring PendingConnection::getName() -{ - return L"Unimplemented"; -// if (name != null) return name + " [" + connection.getRemoteAddress().toString() + "]"; -// return connection.getRemoteAddress().toString(); +std::wstring PendingConnection::getName() { + return L"Unimplemented"; + // if (name != null) return name + " [" + + // connection.getRemoteAddress().toString() + "]"; return + // connection.getRemoteAddress().toString(); } -bool PendingConnection::isServerPacketListener() -{ - return true; -} +bool PendingConnection::isServerPacketListener() { return true; } diff --git a/Minecraft.Client/Network/PendingConnection.h b/Minecraft.Client/Network/PendingConnection.h index 1f79508ff..8ee23c434 100644 --- a/Minecraft.Client/Network/PendingConnection.h +++ b/Minecraft.Client/Network/PendingConnection.h @@ -6,43 +6,47 @@ class LoginPacket; class Connection; class Random; - -class PendingConnection : public PacketListener -{ +class PendingConnection : public PacketListener { private: - static const int FAKE_LAG = 0; - static const int MAX_TICKS_BEFORE_LOGIN = 20 * 30 * 10; // 10 minutes instead of 20 sec for Linux theres just no login yet + static const int FAKE_LAG = 0; + static const int MAX_TICKS_BEFORE_LOGIN = + 20 * 30 * + 10; // 10 minutes instead of 20 sec for Linux theres just no login yet -// public static Logger logger = Logger.getLogger("Minecraft"); - static Random *random; + // public static Logger logger = Logger.getLogger("Minecraft"); + static Random* random; public: - Connection *connection; + Connection* connection; + public: - bool done; + bool done; + private: - MinecraftServer *server; + MinecraftServer* server; int _tick; std::wstring name; std::shared_ptr acceptedLogin; std::wstring loginKey; public: - PendingConnection(MinecraftServer *server, Socket *socket, const std::wstring& id); - ~PendingConnection(); + PendingConnection(MinecraftServer* server, Socket* socket, + const std::wstring& id); + ~PendingConnection(); void tick(); void disconnect(DisconnectPacket::eDisconnectReason reason); virtual void handlePreLogin(std::shared_ptr packet); virtual void handleLogin(std::shared_ptr packet); virtual void handleAcceptedLogin(std::shared_ptr packet); - virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); - virtual void handleGetInfo(std::shared_ptr packet); - virtual void handleKeepAlive(std::shared_ptr packet); + virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects); + virtual void handleGetInfo(std::shared_ptr packet); + virtual void handleKeepAlive(std::shared_ptr packet); virtual void onUnhandledPacket(std::shared_ptr packet); void send(std::shared_ptr packet); std::wstring getName(); virtual bool isServerPacketListener(); private: - void sendPreLoginResponse(); + void sendPreLoginResponse(); }; \ No newline at end of file diff --git a/Minecraft.Client/Network/PlayerChunkMap.cpp b/Minecraft.Client/Network/PlayerChunkMap.cpp index 0f86fc0bf..95812270b 100644 --- a/Minecraft.Client/Network/PlayerChunkMap.cpp +++ b/Minecraft.Client/Network/PlayerChunkMap.cpp @@ -12,142 +12,153 @@ #include "../../Minecraft.World/Platform/System.h" #include "PlayerList.h" -PlayerChunkMap::PlayerChunk::PlayerChunk(int x, int z, PlayerChunkMap *pcm) : pos(x,z) -{ - // 4J - added initialisers - changes = 0; - changedTiles = shortArray(MAX_CHANGES_BEFORE_RESEND); - xChangeMin = xChangeMax = 0; - yChangeMin = yChangeMax = 0; - zChangeMin = zChangeMax = 0; - parent = pcm; // 4J added - ticksToNextRegionUpdate = 0; // 4J added - prioritised = false; // 4J added +PlayerChunkMap::PlayerChunk::PlayerChunk(int x, int z, PlayerChunkMap* pcm) + : pos(x, z) { + // 4J - added initialisers + changes = 0; + changedTiles = shortArray(MAX_CHANGES_BEFORE_RESEND); + xChangeMin = xChangeMax = 0; + yChangeMin = yChangeMax = 0; + zChangeMin = zChangeMax = 0; + parent = pcm; // 4J added + ticksToNextRegionUpdate = 0; // 4J added + prioritised = false; // 4J added parent->getLevel()->cache->create(x, z); - // 4J - added make sure our lights are up to date as soon as we make it. This is of particular concern for local clients, who have their data - // shared as soon as the chunkvisibilitypacket is sent, and so could potentially create render data for this chunk before it has been properly lit. - while( parent->getLevel()->updateLights() ) - ; + // 4J - added make sure our lights are up to date as soon as we make it. + // This is of particular concern for local clients, who have their data + // shared as soon as the chunkvisibilitypacket is sent, and so could + // potentially create render data for this chunk before it has been properly + // lit. + while (parent->getLevel()->updateLights()); } -PlayerChunkMap::PlayerChunk::~PlayerChunk() -{ - delete[] changedTiles.data; //4jcraft, changed to [] +PlayerChunkMap::PlayerChunk::~PlayerChunk() { + delete[] changedTiles.data; // 4jcraft, changed to [] } -// 4J added - construct an an array of flags that indicate which entities are still waiting to have network packets sent out to say that they have been removed -// If there aren't any entities to be flagged, this function does nothing. If there *are* entities to be added, uses the removedFound as an input to -// determine if the flag array has already been initialised at all - if it has been, then just adds flags to it; if it hasn't, then memsets the output -// flag array and adds to it for this ServerPlayer. -void PlayerChunkMap::flagEntitiesToBeRemoved(unsigned int *flags, bool *flagToBeRemoved) -{ - for(AUTO_VAR(it,players.begin()); it != players.end(); it++) - { - std::shared_ptr serverPlayer = *it; - serverPlayer->flagEntitiesToBeRemoved(flags, flagToBeRemoved); - } +// 4J added - construct an an array of flags that indicate which entities are +// still waiting to have network packets sent out to say that they have been +// removed If there aren't any entities to be flagged, this function does +// nothing. If there *are* entities to be added, uses the removedFound as an +// input to determine if the flag array has already been initialised at all - if +// it has been, then just adds flags to it; if it hasn't, then memsets the +// output flag array and adds to it for this ServerPlayer. +void PlayerChunkMap::flagEntitiesToBeRemoved(unsigned int* flags, + bool* flagToBeRemoved) { + for (AUTO_VAR(it, players.begin()); it != players.end(); it++) { + std::shared_ptr serverPlayer = *it; + serverPlayer->flagEntitiesToBeRemoved(flags, flagToBeRemoved); + } } -void PlayerChunkMap::PlayerChunk::add(std::shared_ptr player, bool sendPacket /*= true*/) -{ - //app.DebugPrintf("--- Adding player to chunk x=%d\tz=%d\n",x, z); - if (find(players.begin(),players.end(),player) != players.end()) - { - // 4J-PB - At the start of the game, lots of chunks are added, and we can then move into an area that is outside the diameter of our starting area, - // but is inside the area loaded at the start. - app.DebugPrintf("--- Adding player to chunk x=%d\t z=%d, but they are already in there!\n",pos.x, pos.z); - return; +void PlayerChunkMap::PlayerChunk::add(std::shared_ptr player, + bool sendPacket /*= true*/) { + // app.DebugPrintf("--- Adding player to chunk x=%d\tz=%d\n",x, z); + if (find(players.begin(), players.end(), player) != players.end()) { + // 4J-PB - At the start of the game, lots of chunks are added, and we + // can then move into an area that is outside the diameter of our + // starting area, but is inside the area loaded at the start. + app.DebugPrintf( + "--- Adding player to chunk x=%d\t z=%d, but they are already in " + "there!\n", + pos.x, pos.z); + return; - //assert(false); -// 4J - was throw new IllegalStateException("Failed to add player. " + player + " already is in chunk " + x + ", " + z); - } + // assert(false); + // 4J - was throw new IllegalStateException("Failed + // to add player. " + player + " already is in chunk " + x + ", " + z); + } player->seenChunks.insert(pos); - // 4J Added the sendPacket check. See PlayerChunkMap::add for the usage - if( sendPacket ) player->connection->send( std::shared_ptr( new ChunkVisibilityPacket(pos.x, pos.z, true) ) ); + // 4J Added the sendPacket check. See PlayerChunkMap::add for the usage + if (sendPacket) + player->connection->send(std::shared_ptr( + new ChunkVisibilityPacket(pos.x, pos.z, true))); - players.push_back(player); - - player->chunksToSend.push_back(pos); + players.push_back(player); + + player->chunksToSend.push_back(pos); #ifdef _LARGE_WORLDS - parent->getLevel()->cache->dontDrop(pos.x, pos.z); // 4J Added; + parent->getLevel()->cache->dontDrop(pos.x, pos.z); // 4J Added; #endif } -void PlayerChunkMap::PlayerChunk::remove(std::shared_ptr player) -{ - PlayerChunkMap::PlayerChunk *toDelete = NULL; +void PlayerChunkMap::PlayerChunk::remove(std::shared_ptr player) { + PlayerChunkMap::PlayerChunk* toDelete = NULL; - //app.DebugPrintf("--- PlayerChunkMap::PlayerChunk::remove x=%d\tz=%d\n",x,z); - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if ( it == players.end()) - { - app.DebugPrintf("--- INFO - Removing player from chunk x=%d\t z=%d, but they are not in that chunk!\n",pos.x, pos.z); + // app.DebugPrintf("--- PlayerChunkMap::PlayerChunk::remove + // x=%d\tz=%d\n",x,z); + AUTO_VAR(it, find(players.begin(), players.end(), player)); + if (it == players.end()) { + app.DebugPrintf( + "--- INFO - Removing player from chunk x=%d\t z=%d, but they are " + "not in that chunk!\n", + pos.x, pos.z); - return; - } + return; + } players.erase(it); - if (players.size() == 0) - { + if (players.size() == 0) { __int64 id = (pos.x + 0x7fffffffLL) | ((pos.z + 0x7fffffffLL) << 32); - AUTO_VAR(it, parent->chunks.find(id)); - if( it != parent->chunks.end() ) - { - toDelete = it->second; // Don't delete until the end of the function, as this might be this instance - parent->chunks.erase(it); - } - if (changes > 0) - { - AUTO_VAR(it, find(parent->changedChunks.begin(),parent->changedChunks.end(),this)); - parent->changedChunks.erase(it); + AUTO_VAR(it, parent->chunks.find(id)); + if (it != parent->chunks.end()) { + toDelete = it->second; // Don't delete until the end of the + // function, as this might be this instance + parent->chunks.erase(it); + } + if (changes > 0) { + AUTO_VAR(it, find(parent->changedChunks.begin(), + parent->changedChunks.end(), this)); + parent->changedChunks.erase(it); } parent->getLevel()->cache->drop(pos.x, pos.z); } player->chunksToSend.remove(pos); - // 4J - I don't think there's any point sending these anymore, as we don't need to unload chunks with fixed sized maps - // 4J - We do need to send these to unload entities in chunks when players are dead. If we do not and the entity is removed - // while they are dead, that entity will remain in the clients world - if (player->connection != NULL && player->seenChunks.find(pos) != player->seenChunks.end()) - { - INetworkPlayer *thisNetPlayer = player->connection->getNetworkPlayer(); - bool noOtherPlayersFound = true; - - if( thisNetPlayer != NULL ) - { - for( AUTO_VAR(it, players.begin()); it < players.end(); ++it ) - { - std::shared_ptr currPlayer = *it; - INetworkPlayer *currNetPlayer = currPlayer->connection->getNetworkPlayer(); - if( currNetPlayer != NULL && currNetPlayer->IsSameSystem( thisNetPlayer ) && currPlayer->seenChunks.find(pos) != currPlayer->seenChunks.end() ) - { - noOtherPlayersFound = false; - break; - } - } - if(noOtherPlayersFound) - { - //wprintf(L"Sending ChunkVisiblity packet false for chunk (%d,%d) to player %ls\n", x, z, player->name.c_str() ); - player->connection->send( std::shared_ptr( new ChunkVisibilityPacket(pos.x, pos.z, false) ) ); - } - } - else - { - //app.DebugPrintf("PlayerChunkMap::PlayerChunk::remove - QNetPlayer is NULL\n"); - } + // 4J - I don't think there's any point sending these anymore, as we don't + // need to unload chunks with fixed sized maps 4J - We do need to send these + // to unload entities in chunks when players are dead. If we do not and the + // entity is removed while they are dead, that entity will remain in the + // clients world + if (player->connection != NULL && + player->seenChunks.find(pos) != player->seenChunks.end()) { + INetworkPlayer* thisNetPlayer = player->connection->getNetworkPlayer(); + bool noOtherPlayersFound = true; + + if (thisNetPlayer != NULL) { + for (AUTO_VAR(it, players.begin()); it < players.end(); ++it) { + std::shared_ptr currPlayer = *it; + INetworkPlayer* currNetPlayer = + currPlayer->connection->getNetworkPlayer(); + if (currNetPlayer != NULL && + currNetPlayer->IsSameSystem(thisNetPlayer) && + currPlayer->seenChunks.find(pos) != + currPlayer->seenChunks.end()) { + noOtherPlayersFound = false; + break; + } + } + if (noOtherPlayersFound) { + // wprintf(L"Sending ChunkVisiblity packet false for chunk + // (%d,%d) to player %ls\n", x, z, player->name.c_str() ); + player->connection->send(std::shared_ptr( + new ChunkVisibilityPacket(pos.x, pos.z, false))); + } + } else { + // app.DebugPrintf("PlayerChunkMap::PlayerChunk::remove - QNetPlayer + // is NULL\n"); + } } - delete toDelete; + delete toDelete; } -void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) -{ - if (changes == 0) - { +void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) { + if (changes == 0) { parent->changedChunks.push_back(this); xChangeMin = xChangeMax = x; yChangeMin = yChangeMax = y; @@ -162,12 +173,10 @@ void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) if (zChangeMin > z) zChangeMin = z; if (zChangeMax < z) zChangeMax = z; - if (changes < MAX_CHANGES_BEFORE_RESEND) - { - short id = (short) ((x << 12) | (z << 8) | (y)); + if (changes < MAX_CHANGES_BEFORE_RESEND) { + short id = (short)((x << 12) | (z << 8) | (y)); - for (int i = 0; i < changes; i++) - { + for (int i = 0; i < changes; i++) { if (changedTiles[i] == id) return; } @@ -175,146 +184,143 @@ void PlayerChunkMap::PlayerChunk::tileChanged(int x, int y, int z) } } -// 4J added - make sure that any tile updates for the chunk at this location get prioritised for sending -void PlayerChunkMap::PlayerChunk::prioritiseTileChanges() -{ - prioritised = true; +// 4J added - make sure that any tile updates for the chunk at this location get +// prioritised for sending +void PlayerChunkMap::PlayerChunk::prioritiseTileChanges() { + prioritised = true; } -void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr packet) -{ - std::vector< std::shared_ptr > sentTo; - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr packet) { + std::vector > sentTo; + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; - // 4J - don't send to a player we've already sent this data to that shares the same machine. TileUpdatePacket, - // ChunkTilesUpdatePacket and SignUpdatePacket all used to limit themselves to sending once to each machine - // by only sending to the primary player on each machine. This was causing trouble for split screen - // as updates were only coming in for the region round this one player. Now these packets can be sent to any - // player, but we try to restrict the network impact this has by not resending to the one machine - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - } - } - } - } - if( dontSend ) - { - continue; - } + // 4J - don't send to a player we've already sent this data to that + // shares the same machine. TileUpdatePacket, ChunkTilesUpdatePacket and + // SignUpdatePacket all used to limit themselves to sending once to each + // machine by only sending to the primary player on each machine. This + // was causing trouble for split screen as updates were only coming in + // for the region round this one player. Now these packets can be sent + // to any player, but we try to restrict the network impact this has by + // not resending to the one machine + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + } + } + } + } + if (dontSend) { + continue; + } - // 4J Changed to get the flag index for the player before we send a packet. This flag is updated when we queue - // for send the first BlockRegionUpdatePacket for this chunk to that player/players system. Therefore there is no need to - // send tile updates or other updates until that has been sent - int flagIndex = ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); - if (player->seenChunks.find(pos) != player->seenChunks.end() && (player->connection->isLocal() || g_NetworkManager.SystemFlagGet(player->connection->getNetworkPlayer(),flagIndex) )) - { + // 4J Changed to get the flag index for the player before we send a + // packet. This flag is updated when we queue for send the first + // BlockRegionUpdatePacket for this chunk to that player/players system. + // Therefore there is no need to send tile updates or other updates + // until that has been sent + int flagIndex = + ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); + if (player->seenChunks.find(pos) != player->seenChunks.end() && + (player->connection->isLocal() || + g_NetworkManager.SystemFlagGet( + player->connection->getNetworkPlayer(), flagIndex))) { player->connection->send(packet); - sentTo.push_back(player); + sentTo.push_back(player); } } - // Now also check round all the players that are involved in this game. We also want to send the packet - // to them if their system hasn't received it already, but they have received the first BlockRegionUpdatePacket for this - // chunk + // Now also check round all the players that are involved in this game. We + // also want to send the packet to them if their system hasn't received it + // already, but they have received the first BlockRegionUpdatePacket for + // this chunk - // Make sure we are only doing this for BlockRegionUpdatePacket, ChunkTilesUpdatePacket and TileUpdatePacket. - // We'll be potentially sending to players who aren't on the same level as this packet is intended for, - // and only these 3 packets have so far been updated to be able to encode the level so they are robust - // enough to cope with this - if(!( ( packet->getId() == 51 ) || ( packet->getId() == 52 ) || ( packet->getId() == 53 ) ) ) - { - return; - } + // Make sure we are only doing this for BlockRegionUpdatePacket, + // ChunkTilesUpdatePacket and TileUpdatePacket. We'll be potentially sending + // to players who aren't on the same level as this packet is intended for, + // and only these 3 packets have so far been updated to be able to encode + // the level so they are robust enough to cope with this + if (!((packet->getId() == 51) || (packet->getId() == 52) || + (packet->getId() == 53))) { + return; + } - for( int i = 0; i < parent->level->getServer()->getPlayers()->players.size(); i++ ) - { - std::shared_ptr player = parent->level->getServer()->getPlayers()->players[i]; - // Don't worry about local players, they get all their updates through sharing level with the server anyway - if ( player->connection == NULL ) continue; - if( player->connection->isLocal() ) continue; + for (int i = 0; + i < parent->level->getServer()->getPlayers()->players.size(); i++) { + std::shared_ptr player = + parent->level->getServer()->getPlayers()->players[i]; + // Don't worry about local players, they get all their updates through + // sharing level with the server anyway + if (player->connection == NULL) continue; + if (player->connection->isLocal()) continue; - // Don't worry about this player if they haven't had this chunk yet (this flag will be the - // same for all players on the same system) - int flagIndex = ServerPlayer::getFlagIndexForChunk(pos,parent->dimension); - if(!g_NetworkManager.SystemFlagGet(player->connection->getNetworkPlayer(),flagIndex)) continue; + // Don't worry about this player if they haven't had this chunk yet + // (this flag will be the same for all players on the same system) + int flagIndex = + ServerPlayer::getFlagIndexForChunk(pos, parent->dimension); + if (!g_NetworkManager.SystemFlagGet( + player->connection->getNetworkPlayer(), flagIndex)) + continue; - // From here on the same rules as in the loop above - don't send it if we've already sent to the same system - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - } - } - } - } - if( !dontSend ) - { + // From here on the same rules as in the loop above - don't send it if + // we've already sent to the same system + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + } + } + } + } + if (!dontSend) { player->connection->send(packet); - sentTo.push_back(player); - } - } + sentTo.push_back(player); + } + } } -bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) -{ - bool didRegionUpdate = false; - ServerLevel *level = parent->getLevel(); - if( ticksToNextRegionUpdate > 0 ) ticksToNextRegionUpdate--; - if (changes == 0) - { - prioritised = false; - return false; - } - if (changes == 1) - { +bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) { + bool didRegionUpdate = false; + ServerLevel* level = parent->getLevel(); + if (ticksToNextRegionUpdate > 0) ticksToNextRegionUpdate--; + if (changes == 0) { + prioritised = false; + return false; + } + if (changes == 1) { int x = pos.x * 16 + xChangeMin; int y = yChangeMin; int z = pos.z * 16 + zChangeMin; - broadcast( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - if (level->isEntityTile(x, y, z)) - { + broadcast(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + if (level->isEntityTile(x, y, z)) { broadcast(level->getTileEntity(x, y, z)); } - } - else if (changes == MAX_CHANGES_BEFORE_RESEND) - { - // 4J added, to allow limiting of region update packets created - if( !prioritised ) - { - if( !allowRegionUpdate || ( ticksToNextRegionUpdate > 0 ) ) - { - return false; - } - } + } else if (changes == MAX_CHANGES_BEFORE_RESEND) { + // 4J added, to allow limiting of region update packets created + if (!prioritised) { + if (!allowRegionUpdate || (ticksToNextRegionUpdate > 0)) { + return false; + } + } yChangeMin = yChangeMin / 2 * 2; yChangeMax = (yChangeMax / 2 + 1) * 2; @@ -325,271 +331,241 @@ bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) int ys = yChangeMax - yChangeMin + 2; int zs = zChangeMax - zChangeMin + 1; - // Fix for buf #95007 : TCR #001 BAS Game Stability: TU12: Code: Compliance: More than 192 dropped items causes game to freeze or crash. - // Block region update packets can only encode ys in a range of 1 - 256 - if( ys > 256 ) ys = 256; + // Fix for buf #95007 : TCR #001 BAS Game Stability: TU12: Code: + // Compliance: More than 192 dropped items causes game to freeze or + // crash. Block region update packets can only encode ys in a range of 1 + // - 256 + if (ys > 256) ys = 256; - broadcast( std::shared_ptr( new BlockRegionUpdatePacket(xp, yp, zp, xs, ys, zs, level) ) ); - std::vector > *tes = level->getTileEntitiesInRegion(xp, yp, zp, xp + xs, yp + ys, zp + zs); - for (unsigned int i = 0; i < tes->size(); i++) - { + broadcast(std::shared_ptr( + new BlockRegionUpdatePacket(xp, yp, zp, xs, ys, zs, level))); + std::vector >* tes = + level->getTileEntitiesInRegion(xp, yp, zp, xp + xs, yp + ys, + zp + zs); + for (unsigned int i = 0; i < tes->size(); i++) { broadcast(tes->at(i)); } - delete tes; - ticksToNextRegionUpdate = MIN_TICKS_BETWEEN_REGION_UPDATE; - didRegionUpdate = true; - } - else - { - // 4J As we only get here if changes is less than MAX_CHANGES_BEFORE_RESEND (10) we only need to send a byte value in the packet - broadcast( std::shared_ptr( new ChunkTilesUpdatePacket(pos.x, pos.z, changedTiles, (uint8_t)changes, level) ) ); - for (int i = 0; i < changes; i++) - { + delete tes; + ticksToNextRegionUpdate = MIN_TICKS_BETWEEN_REGION_UPDATE; + didRegionUpdate = true; + } else { + // 4J As we only get here if changes is less than + // MAX_CHANGES_BEFORE_RESEND (10) we only need to send a byte value in + // the packet + broadcast( + std::shared_ptr(new ChunkTilesUpdatePacket( + pos.x, pos.z, changedTiles, (uint8_t)changes, level))); + for (int i = 0; i < changes; i++) { int x = pos.x * 16 + ((changedTiles[i] >> 12) & 15); int y = ((changedTiles[i]) & 255); int z = pos.z * 16 + ((changedTiles[i] >> 8) & 15); - if (level->isEntityTile(x, y, z)) - { -// System.out.println("Sending!"); + if (level->isEntityTile(x, y, z)) { + // System.out.println("Sending!"); broadcast(level->getTileEntity(x, y, z)); } } } changes = 0; - prioritised = false; - return didRegionUpdate; + prioritised = false; + return didRegionUpdate; } -void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr te) -{ - if (te != NULL) - { +void PlayerChunkMap::PlayerChunk::broadcast(std::shared_ptr te) { + if (te != NULL) { std::shared_ptr p = te->getUpdatePacket(); - if (p != NULL) - { + if (p != NULL) { broadcast(p); } } } -PlayerChunkMap::PlayerChunkMap(ServerLevel *level, int dimension, int radius) -{ - assert(radius <= MAX_VIEW_DISTANCE); - assert(radius >= MIN_VIEW_DISTANCE); +PlayerChunkMap::PlayerChunkMap(ServerLevel* level, int dimension, int radius) { + assert(radius <= MAX_VIEW_DISTANCE); + assert(radius >= MIN_VIEW_DISTANCE); this->radius = radius; this->level = level; - this->dimension = dimension; + this->dimension = dimension; } -PlayerChunkMap::~PlayerChunkMap() -{ - for( AUTO_VAR(it, chunks.begin()); it != chunks.end(); it++ ) - { - delete it->second; - } +PlayerChunkMap::~PlayerChunkMap() { + for (AUTO_VAR(it, chunks.begin()); it != chunks.end(); it++) { + delete it->second; + } } -ServerLevel *PlayerChunkMap::getLevel() -{ - return level; -} +ServerLevel* PlayerChunkMap::getLevel() { return level; } -void PlayerChunkMap::tick() -{ - // 4J - some changes here so that we only send one region update per tick. The chunks themselves also - // limit their resend rate to once every MIN_TICKS_BETWEEN_REGION_UPDATE ticks - bool regionUpdateSent = false; - for (unsigned int i = 0; i < changedChunks.size();) - { - regionUpdateSent |= changedChunks[i]->broadcastChanges(!regionUpdateSent); - // Changes will be 0 if the chunk actually sent something, in which case we can delete it from this array - if( changedChunks[i]->changes == 0 ) - { - changedChunks[i] = changedChunks.back(); - changedChunks.pop_back(); - } - else - { - // Limiting of some kind means we didn't send this chunk so move onto the next - i++; - } +void PlayerChunkMap::tick() { + // 4J - some changes here so that we only send one region update per tick. + // The chunks themselves also limit their resend rate to once every + // MIN_TICKS_BETWEEN_REGION_UPDATE ticks + bool regionUpdateSent = false; + for (unsigned int i = 0; i < changedChunks.size();) { + regionUpdateSent |= + changedChunks[i]->broadcastChanges(!regionUpdateSent); + // Changes will be 0 if the chunk actually sent something, in which case + // we can delete it from this array + if (changedChunks[i]->changes == 0) { + changedChunks[i] = changedChunks.back(); + changedChunks.pop_back(); + } else { + // Limiting of some kind means we didn't send this chunk so move + // onto the next + i++; + } } - for( unsigned int i = 0; i < players.size(); i++ ) - { - tickAddRequests(players[i]); - } + for (unsigned int i = 0; i < players.size(); i++) { + tickAddRequests(players[i]); + } - // 4J Stu - Added 1.1 but not relevant to us as we never no 0 players anyway, and don't think we should be dropping stuff - //if (players.isEmpty()) { - // ServerLevel level = server.getLevel(this.dimension); - // Dimension dimension = level.dimension; - // if (!dimension.mayRespawn()) { - // level.cache.dropAll(); - // } - //} + // 4J Stu - Added 1.1 but not relevant to us as we never no 0 players + // anyway, and don't think we should be dropping stuff + // if (players.isEmpty()) { + // ServerLevel level = server.getLevel(this.dimension); + // Dimension dimension = level.dimension; + // if (!dimension.mayRespawn()) { + // level.cache.dropAll(); + // } + //} } -bool PlayerChunkMap::hasChunk(int x, int z) -{ +bool PlayerChunkMap::hasChunk(int x, int z) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - return chunks.find(id) != chunks.end(); + return chunks.find(id) != chunks.end(); } -PlayerChunkMap::PlayerChunk *PlayerChunkMap::getChunk(int x, int z, bool create) -{ +PlayerChunkMap::PlayerChunk* PlayerChunkMap::getChunk(int x, int z, + bool create) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + AUTO_VAR(it, chunks.find(id)); - PlayerChunk *chunk = NULL; - if( it != chunks.end() ) - { - chunk = it->second; - } - else if ( create) - { + PlayerChunk* chunk = NULL; + if (it != chunks.end()) { + chunk = it->second; + } else if (create) { chunk = new PlayerChunk(x, z, this); chunks[id] = chunk; } - return chunk; + return chunk; } -// 4J - added. If a chunk exists, add a player to it straight away. If it doesn't exist, -// queue a request for it to be created. -void PlayerChunkMap::getChunkAndAddPlayer(int x, int z, std::shared_ptr player) -{ +// 4J - added. If a chunk exists, add a player to it straight away. If it +// doesn't exist, queue a request for it to be created. +void PlayerChunkMap::getChunkAndAddPlayer( + int x, int z, std::shared_ptr player) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + AUTO_VAR(it, chunks.find(id)); - if( it != chunks.end() ) - { - it->second->add(player); - } - else - { - addRequests.push_back(PlayerChunkAddRequest(x,z,player)); - } + if (it != chunks.end()) { + it->second->add(player); + } else { + addRequests.push_back(PlayerChunkAddRequest(x, z, player)); + } } -// 4J - added. If the chunk and player are in the queue to be added, remove from there. Otherwise -// attempt to remove from main chunk map. -void PlayerChunkMap::getChunkAndRemovePlayer(int x, int z, std::shared_ptr player) -{ - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++ ) - { - if( ( it->x == x ) && - ( it->z == z ) && - ( it->player == player ) ) - { - addRequests.erase(it); - return; - } - } +// 4J - added. If the chunk and player are in the queue to be added, remove from +// there. Otherwise attempt to remove from main chunk map. +void PlayerChunkMap::getChunkAndRemovePlayer( + int x, int z, std::shared_ptr player) { + for (AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++) { + if ((it->x == x) && (it->z == z) && (it->player == player)) { + addRequests.erase(it); + return; + } + } __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + AUTO_VAR(it, chunks.find(id)); - if( it != chunks.end() ) - { - it->second->remove(player); - } + if (it != chunks.end()) { + it->second->remove(player); + } } -// 4J - added - actually create & add player to a playerchunk, if there is one queued for this player. -void PlayerChunkMap::tickAddRequests(std::shared_ptr player) -{ - if( addRequests.size() ) - { - // Find the nearest chunk request to the player - int px = (int)player->x; - int pz = (int)player->z; - int minDistSq = -1; - - AUTO_VAR(itNearest, addRequests.end()); - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++ ) - { - if( it->player == player ) - { - int xm = ( it->x * 16 ) + 8; - int zm = ( it->z * 16 ) + 8; - int distSq = (xm - px) * (xm - px) + - (zm - pz) * (zm - pz); - if( ( minDistSq == -1 ) || ( distSq < minDistSq ) ) - { - minDistSq = distSq; - itNearest = it; - } - } - } +// 4J - added - actually create & add player to a playerchunk, if there is one +// queued for this player. +void PlayerChunkMap::tickAddRequests(std::shared_ptr player) { + if (addRequests.size()) { + // Find the nearest chunk request to the player + int px = (int)player->x; + int pz = (int)player->z; + int minDistSq = -1; - // If we found one at all, then do this one - if( itNearest != addRequests.end() ) - { - getChunk(itNearest->x, itNearest->z, true)->add(itNearest->player); - addRequests.erase(itNearest); - return; - } - } + AUTO_VAR(itNearest, addRequests.end()); + for (AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++) { + if (it->player == player) { + int xm = (it->x * 16) + 8; + int zm = (it->z * 16) + 8; + int distSq = (xm - px) * (xm - px) + (zm - pz) * (zm - pz); + if ((minDistSq == -1) || (distSq < minDistSq)) { + minDistSq = distSq; + itNearest = it; + } + } + } + + // If we found one at all, then do this one + if (itNearest != addRequests.end()) { + getChunk(itNearest->x, itNearest->z, true)->add(itNearest->player); + addRequests.erase(itNearest); + return; + } + } } -void PlayerChunkMap::broadcastTileUpdate(std::shared_ptr packet, int x, int y, int z) -{ +void PlayerChunkMap::broadcastTileUpdate(std::shared_ptr packet, int x, + int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) - { + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk != NULL) { chunk->broadcast(packet); } } -void PlayerChunkMap::tileChanged(int x, int y, int z) -{ +void PlayerChunkMap::tileChanged(int x, int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) - { + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk != NULL) { chunk->tileChanged(x & 15, y, z & 15); } } -bool PlayerChunkMap::isTrackingTile(int x, int y, int z) -{ +bool PlayerChunkMap::isTrackingTile(int x, int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if( chunk ) return true; - return false; + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk) return true; + return false; } -// 4J added - make sure that any tile updates for the chunk at this location get prioritised for sending -void PlayerChunkMap::prioritiseTileChanges(int x, int y, int z) -{ +// 4J added - make sure that any tile updates for the chunk at this location get +// prioritised for sending +void PlayerChunkMap::prioritiseTileChanges(int x, int y, int z) { int xc = x >> 4; int zc = z >> 4; - PlayerChunk *chunk = getChunk(xc, zc, false); - if (chunk != NULL) - { + PlayerChunk* chunk = getChunk(xc, zc, false); + if (chunk != NULL) { chunk->prioritiseTileChanges(); } } -void PlayerChunkMap::add(std::shared_ptr player) -{ - static int direction[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, {0, -1} }; +void PlayerChunkMap::add(std::shared_ptr player) { + static int direction[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; - int xc = (int) player->x >> 4; - int zc = (int) player->z >> 4; + int xc = (int)player->x >> 4; + int zc = (int)player->z >> 4; player->lastMoveX = player->x; player->lastMoveZ = player->z; -// for (int x = xc - radius; x <= xc + radius; x++) -// for (int z = zc - radius; z <= zc + radius; z++) { -// getChunk(x, z, true).add(player); -// } + // for (int x = xc - radius; x <= xc + radius; x++) + // for (int z = zc - radius; z <= zc + radius; z++) { + // getChunk(x, z, true).add(player); + // } // CraftBukkit start int facing = 0; @@ -600,30 +576,28 @@ void PlayerChunkMap::add(std::shared_ptr player) // Origin getChunk(xc, zc, true)->add(player, false); - // 4J Added so we send an area packet rather than one visibility packet per chunk - int minX, maxX, minZ, maxZ; - minX = maxX = xc; - minZ = maxZ = zc; + // 4J Added so we send an area packet rather than one visibility packet per + // chunk + int minX, maxX, minZ, maxZ; + minX = maxX = xc; + minZ = maxZ = zc; // All but the last leg - for (int legSize = 1; legSize <= size * 2; legSize++) - { - for (int leg = 0; leg < 2; leg++) - { - int *dir = direction[facing++ % 4]; + for (int legSize = 1; legSize <= size * 2; legSize++) { + for (int leg = 0; leg < 2; leg++) { + int* dir = direction[facing++ % 4]; - for (int k = 0; k < legSize; k++) - { + for (int k = 0; k < legSize; k++) { dx += dir[0]; dz += dir[1]; - int targetX, targetZ; - targetX = xc + dx; - targetZ = zc + dz; - if( targetX > maxX ) maxX = targetX; - if( targetX < minX ) minX = targetX; - if( targetZ > maxZ ) maxZ = targetZ; - if( targetZ < minZ ) minZ = targetZ; + int targetX, targetZ; + targetX = xc + dx; + targetZ = zc + dz; + if (targetX > maxX) maxX = targetX; + if (targetX < minX) minX = targetX; + if (targetZ > maxZ) maxZ = targetZ; + if (targetZ < minZ) minZ = targetZ; getChunk(targetX, targetZ, true)->add(player, false); } @@ -632,67 +606,59 @@ void PlayerChunkMap::add(std::shared_ptr player) // Final leg facing %= 4; - for (int k = 0; k < size * 2; k++) - { + for (int k = 0; k < size * 2; k++) { dx += direction[facing][0]; dz += direction[facing][1]; - int targetX, targetZ; - targetX = xc + dx; - targetZ = zc + dz; - if( targetX > maxX ) maxX = targetX; - if( targetX < minX ) minX = targetX; - if( targetZ > maxZ ) maxZ = targetZ; - if( targetZ < minZ ) minZ = targetZ; + int targetX, targetZ; + targetX = xc + dx; + targetZ = zc + dz; + if (targetX > maxX) maxX = targetX; + if (targetX < minX) minX = targetX; + if (targetZ > maxZ) maxZ = targetZ; + if (targetZ < minZ) minZ = targetZ; getChunk(targetX, targetZ, true)->add(player, false); } // CraftBukkit end - player->connection->send( std::shared_ptr( new ChunkVisibilityAreaPacket(minX, maxX, minZ, maxZ) ) ); + player->connection->send(std::shared_ptr( + new ChunkVisibilityAreaPacket(minX, maxX, minZ, maxZ))); #ifdef _LARGE_WORLDS - getLevel()->cache->dontDrop(xc,zc); + getLevel()->cache->dontDrop(xc, zc); #endif - players.push_back(player); - + players.push_back(player); } -void PlayerChunkMap::remove(std::shared_ptr player) -{ - int xc = ((int) player->lastMoveX) >> 4; - int zc = ((int) player->lastMoveZ) >> 4; +void PlayerChunkMap::remove(std::shared_ptr player) { + int xc = ((int)player->lastMoveX) >> 4; + int zc = ((int)player->lastMoveZ) >> 4; for (int x = xc - radius; x <= xc + radius; x++) - for (int z = zc - radius; z <= zc + radius; z++) - { - PlayerChunk *playerChunk = getChunk(x, z, false); + for (int z = zc - radius; z <= zc + radius; z++) { + PlayerChunk* playerChunk = getChunk(x, z, false); if (playerChunk != NULL) playerChunk->remove(player); } - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if( players.size() > 0 && it != players.end() ) - players.erase(find(players.begin(),players.end(),player)); - - // 4J - added - also remove any queued requests to be added to playerchunks here - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); ) - { - if( it->player == player ) - { - it = addRequests.erase(it); - } - else - { - ++it; - } - } + AUTO_VAR(it, find(players.begin(), players.end(), player)); + if (players.size() > 0 && it != players.end()) + players.erase(find(players.begin(), players.end(), player)); + // 4J - added - also remove any queued requests to be added to playerchunks + // here + for (AUTO_VAR(it, addRequests.begin()); it != addRequests.end();) { + if (it->player == player) { + it = addRequests.erase(it); + } else { + ++it; + } + } } -bool PlayerChunkMap::chunkInRange(int x, int z, int xc, int zc) -{ - // If the distance between x and xc +bool PlayerChunkMap::chunkInRange(int x, int z, int xc, int zc) { + // If the distance between x and xc int xd = x - xc; int zd = z - zc; if (xd < -radius || xd > radius) return false; @@ -700,101 +666,91 @@ bool PlayerChunkMap::chunkInRange(int x, int z, int xc, int zc) return true; } -// 4J - have changed this so that we queue requests to add the player to chunks if they -// need to be created, so that we aren't creating potentially 20 chunks per player per tick -void PlayerChunkMap::move(std::shared_ptr player) -{ - int xc = ((int) player->x) >> 4; - int zc = ((int) player->z) >> 4; +// 4J - have changed this so that we queue requests to add the player to chunks +// if they need to be created, so that we aren't creating potentially 20 chunks +// per player per tick +void PlayerChunkMap::move(std::shared_ptr player) { + int xc = ((int)player->x) >> 4; + int zc = ((int)player->z) >> 4; double _xd = player->lastMoveX - player->x; double _zd = player->lastMoveZ - player->z; double dist = _xd * _xd + _zd * _zd; if (dist < 8 * 8) return; - int last_xc = ((int) player->lastMoveX) >> 4; - int last_zc = ((int) player->lastMoveZ) >> 4; + int last_xc = ((int)player->lastMoveX) >> 4; + int last_zc = ((int)player->lastMoveZ) >> 4; int xd = xc - last_xc; int zd = zc - last_zc; if (xd == 0 && zd == 0) return; - for (int x = xc - radius; x <= xc + radius; x++) - for (int z = zc - radius; z <= zc + radius; z++) - { - if (!chunkInRange(x, z, last_xc, last_zc)) - { - // 4J - changed from separate getChunk & add so we can wrap these operations up and queue - getChunkAndAddPlayer(x, z, player); - } + for (int x = xc - radius; x <= xc + radius; x++) + for (int z = zc - radius; z <= zc + radius; z++) { + if (!chunkInRange(x, z, last_xc, last_zc)) { + // 4J - changed from separate getChunk & add so we can wrap + // these operations up and queue + getChunkAndAddPlayer(x, z, player); + } - if (!chunkInRange(x - xd, z - zd, xc, zc)) - { - // 4J - changed from separate getChunk & remove so we can wrap these operations up and queue - getChunkAndRemovePlayer(x - xd, z - zd, player); - } + if (!chunkInRange(x - xd, z - zd, xc, zc)) { + // 4J - changed from separate getChunk & remove so we can wrap + // these operations up and queue + getChunkAndRemovePlayer(x - xd, z - zd, player); + } } player->lastMoveX = player->x; player->lastMoveZ = player->z; } -int PlayerChunkMap::getMaxRange() -{ - return radius * 16 - 16; +int PlayerChunkMap::getMaxRange() { return radius * 16 - 16; } + +bool PlayerChunkMap::isPlayerIn(std::shared_ptr player, + int xChunk, int zChunk) { + PlayerChunk* chunk = getChunk(xChunk, zChunk, false); + + if (chunk == NULL) { + return false; + } else { + AUTO_VAR(it1, + find(chunk->players.begin(), chunk->players.end(), player)); + AUTO_VAR(it2, find(player->chunksToSend.begin(), + player->chunksToSend.end(), chunk->pos)); + return it1 != chunk->players.end() && it2 == player->chunksToSend.end(); + } + + // return chunk == NULL ? false : chunk->players->contains(player) && + // !player->chunksToSend->contains(chunk->pos); } -bool PlayerChunkMap::isPlayerIn(std::shared_ptr player, int xChunk, int zChunk) -{ - PlayerChunk *chunk = getChunk(xChunk, zChunk, false); - - if(chunk == NULL) - { - return false; - } - else - { - AUTO_VAR(it1, find(chunk->players.begin(), chunk->players.end(), player)); - AUTO_VAR(it2, find(player->chunksToSend.begin(), player->chunksToSend.end(), chunk->pos)); - return it1 != chunk->players.end() && it2 == player->chunksToSend.end(); - } - - //return chunk == NULL ? false : chunk->players->contains(player) && !player->chunksToSend->contains(chunk->pos); -} - -int PlayerChunkMap::convertChunkRangeToBlock(int radius) -{ - return radius * 16 - 16; +int PlayerChunkMap::convertChunkRangeToBlock(int radius) { + return radius * 16 - 16; } // AP added for Vita so the range can be increased once the level starts -void PlayerChunkMap::setRadius(int newRadius) -{ - if( radius != newRadius ) - { - PlayerList* players = level->getServer()->getPlayerList(); - for( int i = 0;i < players->players.size();i += 1 ) - { - std::shared_ptr player = players->players[i]; - if( player->level == level ) - { - int xc = ((int) player->x) >> 4; - int zc = ((int) player->z) >> 4; +void PlayerChunkMap::setRadius(int newRadius) { + if (radius != newRadius) { + PlayerList* players = level->getServer()->getPlayerList(); + for (int i = 0; i < players->players.size(); i += 1) { + std::shared_ptr player = players->players[i]; + if (player->level == level) { + int xc = ((int)player->x) >> 4; + int zc = ((int)player->z) >> 4; - for (int x = xc - newRadius; x <= xc + newRadius; x++) - for (int z = zc - newRadius; z <= zc + newRadius; z++) - { - // check if this chunk is outside the old radius area - if ( x < xc - radius || x > xc + radius || z < zc - radius || z > zc + radius ) - { - getChunkAndAddPlayer(x, z, player); - } - } - } - } + for (int x = xc - newRadius; x <= xc + newRadius; x++) + for (int z = zc - newRadius; z <= zc + newRadius; z++) { + // check if this chunk is outside the old radius area + if (x < xc - radius || x > xc + radius || + z < zc - radius || z > zc + radius) { + getChunkAndAddPlayer(x, z, player); + } + } + } + } - assert(radius <= MAX_VIEW_DISTANCE); - assert(radius >= MIN_VIEW_DISTANCE); - this->radius = newRadius; - } + assert(radius <= MAX_VIEW_DISTANCE); + assert(radius >= MIN_VIEW_DISTANCE); + this->radius = newRadius; + } } diff --git a/Minecraft.Client/Network/PlayerChunkMap.h b/Minecraft.Client/Network/PlayerChunkMap.h index 9c9df9f0f..61ace4de2 100644 --- a/Minecraft.Client/Network/PlayerChunkMap.h +++ b/Minecraft.Client/Network/PlayerChunkMap.h @@ -7,35 +7,34 @@ class MinecraftServer; class Packet; class TileEntity; - -class PlayerChunkMap -{ +class PlayerChunkMap { public: #ifdef _LARGE_WORLDS - static const int MAX_VIEW_DISTANCE = 30; + static const int MAX_VIEW_DISTANCE = 30; #else - static const int MAX_VIEW_DISTANCE = 15; + static const int MAX_VIEW_DISTANCE = 15; #endif - static const int MIN_VIEW_DISTANCE = 3; - static const int MAX_CHANGES_BEFORE_RESEND = 10; - static const int MIN_TICKS_BETWEEN_REGION_UPDATE = 10; + static const int MIN_VIEW_DISTANCE = 3; + static const int MAX_CHANGES_BEFORE_RESEND = 10; + static const int MIN_TICKS_BETWEEN_REGION_UPDATE = 10; - // 4J - added - class PlayerChunkAddRequest - { - public: - int x,z; - std::shared_ptr player; - PlayerChunkAddRequest(int x, int z, std::shared_ptr player ) : x(x), z(z), player(player) {} - }; + // 4J - added + class PlayerChunkAddRequest { + public: + int x, z; + std::shared_ptr player; + PlayerChunkAddRequest(int x, int z, + std::shared_ptr player) + : x(x), z(z), player(player) {} + }; - class PlayerChunk - { - friend class PlayerChunkMap; - private: - PlayerChunkMap *parent; // 4J added - std::vector > players; - //int x, z; + class PlayerChunk { + friend class PlayerChunkMap; + + private: + PlayerChunkMap* parent; // 4J added + std::vector > players; + // int x, z; ChunkPos pos; shortArray changedTiles; @@ -43,63 +42,73 @@ public: int xChangeMin, xChangeMax; int yChangeMin, yChangeMax; int zChangeMin, zChangeMax; - int ticksToNextRegionUpdate; // 4J added - bool prioritised; // 4J added + int ticksToNextRegionUpdate; // 4J added + bool prioritised; // 4J added - public: - PlayerChunk(int x, int z, PlayerChunkMap *pcm); - ~PlayerChunk(); + public: + PlayerChunk(int x, int z, PlayerChunkMap* pcm); + ~PlayerChunk(); - // 4J Added sendPacket param so we can aggregate the initial send into one much smaller packet + // 4J Added sendPacket param so we can aggregate the initial send into + // one much smaller packet void add(std::shared_ptr player, bool sendPacket = true); void remove(std::shared_ptr player); void tileChanged(int x, int y, int z); - void prioritiseTileChanges(); // 4J added + void prioritiseTileChanges(); // 4J added void broadcast(std::shared_ptr packet); - bool broadcastChanges(bool allowRegionUpdate); // 4J - added parm + bool broadcastChanges(bool allowRegionUpdate); // 4J - added parm - private: - void broadcast(std::shared_ptr te); + private: + void broadcast(std::shared_ptr te); }; public: - std::vector > players; - void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added + std::vector > players; + void flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound); // 4J added private: - std::unordered_map<__int64,PlayerChunk *,LongKeyHash,LongKeyEq> chunks; // 4J - was LongHashMap - std::vector changedChunks; - std::vector addRequests; // 4J added - void tickAddRequests(std::shared_ptr player); // 4J added + std::unordered_map<__int64, PlayerChunk*, LongKeyHash, LongKeyEq> + chunks; // 4J - was LongHashMap + std::vector changedChunks; + std::vector addRequests; // 4J added + void tickAddRequests(std::shared_ptr player); // 4J added - ServerLevel *level; + ServerLevel* level; int radius; - int dimension; + int dimension; public: - PlayerChunkMap(ServerLevel *level, int dimension, int radius); - ~PlayerChunkMap(); - ServerLevel *getLevel(); + PlayerChunkMap(ServerLevel* level, int dimension, int radius); + ~PlayerChunkMap(); + ServerLevel* getLevel(); void tick(); - bool hasChunk(int x, int z); + bool hasChunk(int x, int z); + private: - PlayerChunk *getChunk(int x, int z, bool create); - void getChunkAndAddPlayer(int x, int z, std::shared_ptr player); // 4J added - void getChunkAndRemovePlayer(int x, int z, std::shared_ptr player); // 4J added + PlayerChunk* getChunk(int x, int z, bool create); + void getChunkAndAddPlayer( + int x, int z, std::shared_ptr player); // 4J added + void getChunkAndRemovePlayer( + int x, int z, std::shared_ptr player); // 4J added public: - void broadcastTileUpdate(std::shared_ptr packet, int x, int y, int z); + void broadcastTileUpdate(std::shared_ptr packet, int x, int y, + int z); void tileChanged(int x, int y, int z); - bool isTrackingTile(int x, int y, int z); // 4J added - void prioritiseTileChanges(int x, int y, int z); // 4J added + bool isTrackingTile(int x, int y, int z); // 4J added + void prioritiseTileChanges(int x, int y, int z); // 4J added void add(std::shared_ptr player); void remove(std::shared_ptr player); -private: - bool chunkInRange(int x, int z, int xc, int zc); -public: - void move(std::shared_ptr player); - int getMaxRange(); - bool isPlayerIn(std::shared_ptr player, int xChunk, int zChunk); - static int convertChunkRangeToBlock(int radius); - // AP added for Vita - void setRadius(int newRadius); +private: + bool chunkInRange(int x, int z, int xc, int zc); + +public: + void move(std::shared_ptr player); + int getMaxRange(); + bool isPlayerIn(std::shared_ptr player, int xChunk, + int zChunk); + static int convertChunkRangeToBlock(int radius); + + // AP added for Vita + void setRadius(int newRadius); }; diff --git a/Minecraft.Client/Network/PlayerConnection.cpp b/Minecraft.Client/Network/PlayerConnection.cpp index b5b494e81..bc6a1be76 100644 --- a/Minecraft.Client/Network/PlayerConnection.cpp +++ b/Minecraft.Client/Network/PlayerConnection.cpp @@ -34,609 +34,617 @@ Random PlayerConnection::random; -PlayerConnection::PlayerConnection(MinecraftServer *server, Connection *connection, std::shared_ptr player) -{ - // 4J - added initialisers - done = false; - tickCount = 0; - aboveGroundTickCount = 0; - xLastOk = yLastOk = zLastOk = 0; - synched = true; - didTick = false; - lastKeepAliveId = 0; - lastKeepAliveTime = 0; - lastKeepAliveTick = 0; - chatSpamTickCount = 0; - dropSpamTickCount = 0; +PlayerConnection::PlayerConnection(MinecraftServer* server, + Connection* connection, + std::shared_ptr player) { + // 4J - added initialisers + done = false; + tickCount = 0; + aboveGroundTickCount = 0; + xLastOk = yLastOk = zLastOk = 0; + synched = true; + didTick = false; + lastKeepAliveId = 0; + lastKeepAliveTime = 0; + lastKeepAliveTick = 0; + chatSpamTickCount = 0; + dropSpamTickCount = 0; - this->server = server; - this->connection = connection; - connection->setListener(this); - this->player = player; -// player->connection = this; // 4J - moved out as we can't assign in a ctor - InitializeCriticalSection(&done_cs); + this->server = server; + this->connection = connection; + connection->setListener(this); + this->player = player; + // player->connection = this; // 4J - moved out as we can't + //assign in a ctor + InitializeCriticalSection(&done_cs); - m_bCloseOnTick = false; - m_bWasKicked = false; + m_bCloseOnTick = false; + m_bWasKicked = false; - m_friendsOnlyUGC = false; - m_offlineXUID = INVALID_XUID; - m_onlineXUID = INVALID_XUID; - m_bHasClientTickedOnce = false; + m_friendsOnlyUGC = false; + m_offlineXUID = INVALID_XUID; + m_onlineXUID = INVALID_XUID; + m_bHasClientTickedOnce = false; - setShowOnMaps(app.GetGameHostOption(eGameHostOption_Gamertags)!=0?true:false); + setShowOnMaps( + app.GetGameHostOption(eGameHostOption_Gamertags) != 0 ? true : false); } -PlayerConnection::~PlayerConnection() -{ - delete connection; - DeleteCriticalSection(&done_cs); +PlayerConnection::~PlayerConnection() { + delete connection; + DeleteCriticalSection(&done_cs); } -void PlayerConnection::tick() -{ - if( done ) return; +void PlayerConnection::tick() { + if (done) return; - if( m_bCloseOnTick ) - { - disconnect( DisconnectPacket::eDisconnect_Closed ); - return; - } + if (m_bCloseOnTick) { + disconnect(DisconnectPacket::eDisconnect_Closed); + return; + } - didTick = false; - tickCount++; - connection->tick(); - if(done) return; + didTick = false; + tickCount++; + connection->tick(); + if (done) return; - if ((tickCount - lastKeepAliveTick) > 20 * 1) - { - lastKeepAliveTick = tickCount; - lastKeepAliveTime = System::nanoTime() / 1000000; - lastKeepAliveId = random.nextInt(); - send( std::shared_ptr( new KeepAlivePacket(lastKeepAliveId) ) ); - } -// if (!didTick) { -// player->doTick(false); -// } - - if (chatSpamTickCount > 0) - { - chatSpamTickCount--; - } - if (dropSpamTickCount > 0) - { - dropSpamTickCount--; - } + if ((tickCount - lastKeepAliveTick) > 20 * 1) { + lastKeepAliveTick = tickCount; + lastKeepAliveTime = System::nanoTime() / 1000000; + lastKeepAliveId = random.nextInt(); + send(std::shared_ptr( + new KeepAlivePacket(lastKeepAliveId))); + } + // if (!didTick) { + // player->doTick(false); + // } + + if (chatSpamTickCount > 0) { + chatSpamTickCount--; + } + if (dropSpamTickCount > 0) { + dropSpamTickCount--; + } } -void PlayerConnection::disconnect(DisconnectPacket::eDisconnectReason reason) -{ - EnterCriticalSection(&done_cs); - if( done ) - { - LeaveCriticalSection(&done_cs); - return; - } +void PlayerConnection::disconnect(DisconnectPacket::eDisconnectReason reason) { + EnterCriticalSection(&done_cs); + if (done) { + LeaveCriticalSection(&done_cs); + return; + } - app.DebugPrintf("PlayerConnection disconect reason: %d\n", reason ); - player->disconnect(); + app.DebugPrintf("PlayerConnection disconect reason: %d\n", reason); + player->disconnect(); - // 4J Stu - Need to remove the player from the receiving list before their socket is NULLed so that we can find another player on their system - server->getPlayers()->removePlayerFromReceiving( player ); - send( std::shared_ptr( new DisconnectPacket(reason) )); - connection->sendAndQuit(); - // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( std::shared_ptr( new ChatPacket(L"§e" + player->name + L" left the game.") ) ); - if(getWasKicked()) - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); - } - else - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame) ) ); - } - - server->getPlayers()->remove(player); - done = true; - LeaveCriticalSection(&done_cs); + // 4J Stu - Need to remove the player from the receiving list before their + // socket is NULLed so that we can find another player on their system + server->getPlayers()->removePlayerFromReceiving(player); + send(std::shared_ptr(new DisconnectPacket(reason))); + connection->sendAndQuit(); + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // server->players->broadcastAll( std::shared_ptr( new + // ChatPacket(L"§e" + player->name + L" left the game.") ) ); + if (getWasKicked()) { + server->getPlayers()->broadcastAll( + std::shared_ptr(new ChatPacket( + player->name, ChatPacket::e_ChatPlayerKickedFromGame))); + } else { + server->getPlayers()->broadcastAll(std::shared_ptr( + new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame))); + } + + server->getPlayers()->remove(player); + done = true; + LeaveCriticalSection(&done_cs); } -void PlayerConnection::handlePlayerInput(std::shared_ptr packet) -{ - player->setPlayerInput(packet->getXa(), packet->getYa(), packet->isJumping(), packet->isSneaking(), packet->getXRot(), packet->getYRot()); +void PlayerConnection::handlePlayerInput( + std::shared_ptr packet) { + player->setPlayerInput(packet->getXa(), packet->getYa(), + packet->isJumping(), packet->isSneaking(), + packet->getXRot(), packet->getYRot()); } -void PlayerConnection::handleMovePlayer(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); +void PlayerConnection::handleMovePlayer( + std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); - didTick = true; - if(synched) m_bHasClientTickedOnce = true; + didTick = true; + if (synched) m_bHasClientTickedOnce = true; - if (player->wonGame) return; + if (player->wonGame) return; - if (!synched) - { - double yDiff = packet->y - yLastOk; - if (packet->x == xLastOk && yDiff * yDiff < 0.01 && packet->z == zLastOk) - { - synched = true; - } - } + if (!synched) { + double yDiff = packet->y - yLastOk; + if (packet->x == xLastOk && yDiff * yDiff < 0.01 && + packet->z == zLastOk) { + synched = true; + } + } - if (synched) - { - if (player->riding != NULL) - { - - float yRotT = player->yRot; - float xRotT = player->xRot; - player->riding->positionRider(); - double xt = player->x; - double yt = player->y; - double zt = player->z; - double xxa = 0; - double zza = 0; - if (packet->hasRot) - { - yRotT = packet->yRot; - xRotT = packet->xRot; - } - if (packet->hasPos && packet->y == -999 && packet->yView == -999) - { - // CraftBukkit start - if (abs(packet->x) > 1 || abs(packet->z) > 1) - { - //System.err.println(player.name + " was caught trying to crash the server with an invalid position."); + if (synched) { + if (player->riding != NULL) { + float yRotT = player->yRot; + float xRotT = player->xRot; + player->riding->positionRider(); + double xt = player->x; + double yt = player->y; + double zt = player->z; + double xxa = 0; + double zza = 0; + if (packet->hasRot) { + yRotT = packet->yRot; + xRotT = packet->xRot; + } + if (packet->hasPos && packet->y == -999 && packet->yView == -999) { + // CraftBukkit start + if (abs(packet->x) > 1 || abs(packet->z) > 1) { + // System.err.println(player.name + " was caught trying to + // crash the server with an invalid position."); #ifndef _CONTENT_PACKAGE - wprintf(L"%ls was caught trying to crash the server with an invalid position.", player->name.c_str()); + wprintf( + L"%ls was caught trying to crash the server with an " + L"invalid position.", + player->name.c_str()); #endif - disconnect(DisconnectPacket::eDisconnect_IllegalPosition);//"Nope!"); - return; - } - // CraftBukkit end - xxa = packet->x; - zza = packet->z; - } + disconnect(DisconnectPacket:: + eDisconnect_IllegalPosition); //"Nope!"); + return; + } + // CraftBukkit end + xxa = packet->x; + zza = packet->z; + } + player->onGround = packet->onGround; - player->onGround = packet->onGround; + player->doTick(false); + player->move(xxa, 0, zza); + player->absMoveTo(xt, yt, zt, yRotT, xRotT); + player->xd = xxa; + player->zd = zza; + if (player->riding != NULL) level->forceTick(player->riding, true); + if (player->riding != NULL) player->riding->positionRider(); + server->getPlayers()->move(player); + xLastOk = player->x; + yLastOk = player->y; + zLastOk = player->z; + ((Level*)level)->tick(player); - player->doTick(false); - player->move(xxa, 0, zza); - player->absMoveTo(xt, yt, zt, yRotT, xRotT); - player->xd = xxa; - player->zd = zza; - if (player->riding != NULL) level->forceTick(player->riding, true); - if (player->riding != NULL) player->riding->positionRider(); - server->getPlayers()->move(player); - xLastOk = player->x; - yLastOk = player->y; - zLastOk = player->z; - ((Level *)level)->tick(player); + return; + } - return; - } + if (player->isSleeping()) { + player->doTick(false); + player->absMoveTo(xLastOk, yLastOk, zLastOk, player->yRot, + player->xRot); + ((Level*)level)->tick(player); + return; + } - if (player->isSleeping()) - { - player->doTick(false); - player->absMoveTo(xLastOk, yLastOk, zLastOk, player->yRot, player->xRot); - ((Level *)level)->tick(player); - return; - } + double startY = player->y; + xLastOk = player->x; + yLastOk = player->y; + zLastOk = player->z; - double startY = player->y; - xLastOk = player->x; - yLastOk = player->y; - zLastOk = player->z; + double xt = player->x; + double yt = player->y; + double zt = player->z; + float yRotT = player->yRot; + float xRotT = player->xRot; - double xt = player->x; - double yt = player->y; - double zt = player->z; + if (packet->hasPos && packet->y == -999 && packet->yView == -999) { + packet->hasPos = false; + } - float yRotT = player->yRot; - float xRotT = player->xRot; + if (packet->hasPos) { + xt = packet->x; + yt = packet->y; + zt = packet->z; + double yd = packet->yView - packet->y; + if (!player->isSleeping() && (yd > 1.65 || yd < 0.1)) { + disconnect(DisconnectPacket::eDisconnect_IllegalStance); + // logger.warning(player->name + " had an illegal + // stance: " + yd); + return; + } + if (abs(packet->x) > 32000000 || abs(packet->z) > 32000000) { + disconnect(DisconnectPacket::eDisconnect_IllegalPosition); + return; + } + } + if (packet->hasRot) { + yRotT = packet->yRot; + xRotT = packet->xRot; + } - if (packet->hasPos && packet->y == -999 && packet->yView == -999) - { - packet->hasPos = false; - } + // 4J Stu Added to stop server player y pos being different than client + // when flying + if (player->abilities.mayfly || player->isAllowedToFly()) { + player->abilities.flying = packet->isFlying; + } else + player->abilities.flying = false; - if (packet->hasPos) - { - xt = packet->x; - yt = packet->y; - zt = packet->z; - double yd = packet->yView - packet->y; - if (!player->isSleeping() && (yd > 1.65 || yd < 0.1)) - { - disconnect(DisconnectPacket::eDisconnect_IllegalStance); -// logger.warning(player->name + " had an illegal stance: " + yd); - return; - } - if (abs(packet->x) > 32000000 || abs(packet->z) > 32000000) - { - disconnect(DisconnectPacket::eDisconnect_IllegalPosition); - return; - } - } - if (packet->hasRot) - { - yRotT = packet->yRot; - xRotT = packet->xRot; - } + player->doTick(false); + player->ySlideOffset = 0; + player->absMoveTo(xLastOk, yLastOk, zLastOk, yRotT, xRotT); - // 4J Stu Added to stop server player y pos being different than client when flying - if(player->abilities.mayfly || player->isAllowedToFly() ) - { - player->abilities.flying = packet->isFlying; - } - else player->abilities.flying = false; + if (!synched) return; - player->doTick(false); - player->ySlideOffset = 0; - player->absMoveTo(xLastOk, yLastOk, zLastOk, yRotT, xRotT); + double xDist = xt - player->x; + double yDist = yt - player->y; + double zDist = zt - player->z; - if (!synched) return; + double dist = xDist * xDist + yDist * yDist + zDist * zDist; - double xDist = xt - player->x; - double yDist = yt - player->y; - double zDist = zt - player->z; - - double dist = xDist * xDist + yDist * yDist + zDist * zDist; - - // 4J-PB - removing this one for now - /*if (dist > 100.0f) - { + // 4J-PB - removing this one for now + /*if (dist > 100.0f) + { // logger.warning(player->name + " moved too quickly!"); - disconnect(DisconnectPacket::eDisconnect_MovedTooQuickly); -// System.out.println("Moved too quickly at " + xt + ", " + yt + ", " + zt); -// teleport(player->x, player->y, player->z, player->yRot, player->xRot); - return; - } - */ + disconnect(DisconnectPacket::eDisconnect_MovedTooQuickly); +// System.out.println("Moved too quickly at " + xt + ", " + yt + +", " + zt); +// teleport(player->x, player->y, player->z, player->yRot, +player->xRot); return; + } + */ - float r = 1 / 16.0f; - bool oldOk = level->getCubes(player, player->bb->copy()->shrink(r, r, r))->empty(); + float r = 1 / 16.0f; + bool oldOk = + level->getCubes(player, player->bb->copy()->shrink(r, r, r)) + ->empty(); - if (player->onGround && !packet->onGround && yDist > 0) - { - // assume the player made a jump - player->causeFoodExhaustion(FoodConstants::EXHAUSTION_JUMP); - } + if (player->onGround && !packet->onGround && yDist > 0) { + // assume the player made a jump + player->causeFoodExhaustion(FoodConstants::EXHAUSTION_JUMP); + } - player->move(xDist, yDist, zDist); + player->move(xDist, yDist, zDist); - // 4J Stu - It is possible that we are no longer synched (eg By moving into an End Portal), so we should stop any further movement based on this packet - // Fix for #87764 - Code: Gameplay: Host cannot move and experiences End World Chunks flickering, while in Splitscreen Mode - // and Fix for #87788 - Code: Gameplay: Client cannot move and experiences End World Chunks flickering, while in Splitscreen Mode - if (!synched) return; + // 4J Stu - It is possible that we are no longer synched (eg By moving + // into an End Portal), so we should stop any further movement based on + // this packet Fix for #87764 - Code: Gameplay: Host cannot move and + // experiences End World Chunks flickering, while in Splitscreen Mode + // and Fix for #87788 - Code: Gameplay: Client cannot move and + // experiences End World Chunks flickering, while in Splitscreen Mode + if (!synched) return; - player->onGround = packet->onGround; - // Since server players don't call travel we check food exhaustion - // here - player->checkMovementStatistiscs(xDist, yDist, zDist); + player->onGround = packet->onGround; + // Since server players don't call travel we check food exhaustion + // here + player->checkMovementStatistiscs(xDist, yDist, zDist); - double oyDist = yDist; + double oyDist = yDist; - xDist = xt - player->x; - yDist = yt - player->y; + xDist = xt - player->x; + yDist = yt - player->y; - // 4J-PB - line below will always be true! - if (yDist > -0.5 || yDist < 0.5) - { - yDist = 0; - } - zDist = zt - player->z; - dist = xDist * xDist + yDist * yDist + zDist * zDist; - bool fail = false; - if (dist > 0.25 * 0.25 && !player->isSleeping() && !player->gameMode->isCreative() && !player->isAllowedToFly()) - { - fail = true; + // 4J-PB - line below will always be true! + if (yDist > -0.5 || yDist < 0.5) { + yDist = 0; + } + zDist = zt - player->z; + dist = xDist * xDist + yDist * yDist + zDist * zDist; + bool fail = false; + if (dist > 0.25 * 0.25 && !player->isSleeping() && + !player->gameMode->isCreative() && !player->isAllowedToFly()) { + fail = true; // logger.warning(player->name + " moved wrongly!"); // System.out.println("Got position " + xt + ", " + yt + ", " + zt); -// System.out.println("Expected " + player->x + ", " + player->y + ", " + player->z); +// System.out.println("Expected " + player->x + ", " + player->y + ", +// " + player->z); #ifndef _CONTENT_PACKAGE - wprintf(L"%ls moved wrongly!\n",player->name.c_str()); - app.DebugPrintf("Got position %f, %f, %f\n", xt,yt,zt); - app.DebugPrintf("Expected %f, %f, %f\n", player->x, player->y, player->z); + wprintf(L"%ls moved wrongly!\n", player->name.c_str()); + app.DebugPrintf("Got position %f, %f, %f\n", xt, yt, zt); + app.DebugPrintf("Expected %f, %f, %f\n", player->x, player->y, + player->z); #endif - } - player->absMoveTo(xt, yt, zt, yRotT, xRotT); + } + player->absMoveTo(xt, yt, zt, yRotT, xRotT); - bool newOk = level->getCubes(player, player->bb->copy()->shrink(r, r, r))->empty(); - if (oldOk && (fail || !newOk) && !player->isSleeping()) - { - teleport(xLastOk, yLastOk, zLastOk, yRotT, xRotT); - return; - } - AABB *testBox = player->bb->copy()->grow(r, r, r)->expand(0, -0.55, 0); - // && server.level.getCubes(player, testBox).size() == 0 - if (!server->isFlightAllowed() && !player->gameMode->isCreative() && !level->containsAnyBlocks(testBox) && !player->isAllowedToFly() ) - { - if (oyDist >= (-0.5f / 16.0f)) - { - aboveGroundTickCount++; - if (aboveGroundTickCount > 80) - { -// logger.warning(player->name + " was kicked for floating too long!"); + bool newOk = + level->getCubes(player, player->bb->copy()->shrink(r, r, r)) + ->empty(); + if (oldOk && (fail || !newOk) && !player->isSleeping()) { + teleport(xLastOk, yLastOk, zLastOk, yRotT, xRotT); + return; + } + AABB* testBox = player->bb->copy()->grow(r, r, r)->expand(0, -0.55, 0); + // && server.level.getCubes(player, testBox).size() == 0 + if (!server->isFlightAllowed() && !player->gameMode->isCreative() && + !level->containsAnyBlocks(testBox) && !player->isAllowedToFly()) { + if (oyDist >= (-0.5f / 16.0f)) { + aboveGroundTickCount++; + if (aboveGroundTickCount > 80) { +// logger.warning(player->name + " was kicked for floating +// too long!"); #ifndef _CONTENT_PACKAGE - wprintf(L"%ls was kicked for floating too long!\n", player->name.c_str()); + wprintf(L"%ls was kicked for floating too long!\n", + player->name.c_str()); #endif - disconnect(DisconnectPacket::eDisconnect_NoFlying); - return; - } - } - } - else - { - aboveGroundTickCount = 0; - } - - player->onGround = packet->onGround; - server->getPlayers()->move(player); - player->doCheckFallDamage(player->y - startY, packet->onGround); - } + disconnect(DisconnectPacket::eDisconnect_NoFlying); + return; + } + } + } else { + aboveGroundTickCount = 0; + } + player->onGround = packet->onGround; + server->getPlayers()->move(player); + player->doCheckFallDamage(player->y - startY, packet->onGround); + } } -void PlayerConnection::teleport(double x, double y, double z, float yRot, float xRot, bool sendPacket /*= true*/) -{ - synched = false; - xLastOk = x; - yLastOk = y; - zLastOk = z; - player->absMoveTo(x, y, z, yRot, xRot); - // 4J - note that 1.62 is added to the height here as the client connection that receives this will presume it represents y + heightOffset at that end - // This is different to the way that height is sent back to the server, where it represents the bottom of the player bounding volume - if(sendPacket) player->connection->send( std::shared_ptr( new MovePlayerPacket::PosRot(x, y + 1.62f, y, z, yRot, xRot, false, false) ) ); +void PlayerConnection::teleport(double x, double y, double z, float yRot, + float xRot, bool sendPacket /*= true*/) { + synched = false; + xLastOk = x; + yLastOk = y; + zLastOk = z; + player->absMoveTo(x, y, z, yRot, xRot); + // 4J - note that 1.62 is added to the height here as the client connection + // that receives this will presume it represents y + heightOffset at that + // end This is different to the way that height is sent back to the server, + // where it represents the bottom of the player bounding volume + if (sendPacket) + player->connection->send( + std::shared_ptr(new MovePlayerPacket::PosRot( + x, y + 1.62f, y, z, yRot, xRot, false, false))); } -void PlayerConnection::handlePlayerAction(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); +void PlayerConnection::handlePlayerAction( + std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); - if (packet->action == PlayerActionPacket::DROP_ITEM) - { - player->drop(); - return; - } - else if (packet->action == PlayerActionPacket::RELEASE_USE_ITEM) - { - player->releaseUsingItem(); - return; - } - // 4J Stu - We don't have ops, so just use the levels setting - bool canEditSpawn = level->canEditSpawn; // = level->dimension->id != 0 || server->players->isOp(player->name); - bool shouldVerifyLocation = false; - if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) shouldVerifyLocation = true; - if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) shouldVerifyLocation = true; + if (packet->action == PlayerActionPacket::DROP_ITEM) { + player->drop(); + return; + } else if (packet->action == PlayerActionPacket::RELEASE_USE_ITEM) { + player->releaseUsingItem(); + return; + } + // 4J Stu - We don't have ops, so just use the levels setting + bool canEditSpawn = + level->canEditSpawn; // = level->dimension->id != 0 || + // server->players->isOp(player->name); + bool shouldVerifyLocation = false; + if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) + shouldVerifyLocation = true; + if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) + shouldVerifyLocation = true; - int x = packet->x; - int y = packet->y; - int z = packet->z; - if (shouldVerifyLocation) - { - double xDist = player->x - (x + 0.5); - // there is a mismatch between the player's camera and the player's - // position, so add 1.5 blocks - double yDist = player->y - (y + 0.5) + 1.5; - double zDist = player->z - (z + 0.5); - double dist = xDist * xDist + yDist * yDist + zDist * zDist; - if (dist > 6 * 6) - { - return; - } - if (y >= server->getMaxBuildHeight()) - { - return; - } - } - Pos *spawnPos = level->getSharedSpawnPos(); - int xd = (int) Mth::abs((float)(x - spawnPos->x)); - int zd = (int) Mth::abs((float)(z - spawnPos->z)); - delete spawnPos; - if (xd > zd) zd = xd; - if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) - { - if (zd > 16 || canEditSpawn) player->gameMode->startDestroyBlock(x, y, z, packet->face); - else player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + int x = packet->x; + int y = packet->y; + int z = packet->z; + if (shouldVerifyLocation) { + double xDist = player->x - (x + 0.5); + // there is a mismatch between the player's camera and the player's + // position, so add 1.5 blocks + double yDist = player->y - (y + 0.5) + 1.5; + double zDist = player->z - (z + 0.5); + double dist = xDist * xDist + yDist * yDist + zDist * zDist; + if (dist > 6 * 6) { + return; + } + if (y >= server->getMaxBuildHeight()) { + return; + } + } + Pos* spawnPos = level->getSharedSpawnPos(); + int xd = (int)Mth::abs((float)(x - spawnPos->x)); + int zd = (int)Mth::abs((float)(z - spawnPos->z)); + delete spawnPos; + if (xd > zd) zd = xd; + if (packet->action == PlayerActionPacket::START_DESTROY_BLOCK) { + if (zd > 16 || canEditSpawn) + player->gameMode->startDestroyBlock(x, y, z, packet->face); + else + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); - } - else if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) - { - player->gameMode->stopDestroyBlock(x, y, z); - server->getPlayers()->prioritiseTileChanges(x, y, z, level->dimension->id); // 4J added - make sure that the update packets for this get prioritised over other general world updates - if (level->getTile(x, y, z) != 0) player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - } - else if (packet->action == PlayerActionPacket::ABORT_DESTROY_BLOCK) - { - player->gameMode->abortDestroyBlock(x, y, z); - if (level->getTile(x, y, z) != 0) player->connection->send(std::shared_ptr( new TileUpdatePacket(x, y, z, level))); - } - else if (packet->action == PlayerActionPacket::GET_UPDATED_BLOCK) - { - double xDist = player->x - (x + 0.5); - double yDist = player->y - (y + 0.5); - double zDist = player->z - (z + 0.5); - double dist = xDist * xDist + yDist * yDist + zDist * zDist; - if (dist < 16 * 16) - { - player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - } - } - - // 4J Stu - Don't change the levels state - //level->canEditSpawn = false; + } else if (packet->action == PlayerActionPacket::STOP_DESTROY_BLOCK) { + player->gameMode->stopDestroyBlock(x, y, z); + server->getPlayers()->prioritiseTileChanges( + x, y, z, + level->dimension + ->id); // 4J added - make sure that the update packets for this + // get prioritised over other general world updates + if (level->getTile(x, y, z) != 0) + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } else if (packet->action == PlayerActionPacket::ABORT_DESTROY_BLOCK) { + player->gameMode->abortDestroyBlock(x, y, z); + if (level->getTile(x, y, z) != 0) + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } else if (packet->action == PlayerActionPacket::GET_UPDATED_BLOCK) { + double xDist = player->x - (x + 0.5); + double yDist = player->y - (y + 0.5); + double zDist = player->z - (z + 0.5); + double dist = xDist * xDist + yDist * yDist + zDist * zDist; + if (dist < 16 * 16) { + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } + } + // 4J Stu - Don't change the levels state + // level->canEditSpawn = false; } -void PlayerConnection::handleUseItem(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); - std::shared_ptr item = player->inventory->getSelected(); - bool informClient = false; - int x = packet->getX(); - int y = packet->getY(); - int z = packet->getZ(); - int face = packet->getFace(); - - // 4J Stu - We don't have ops, so just use the levels setting - bool canEditSpawn = level->canEditSpawn; // = level->dimension->id != 0 || server->players->isOp(player->name); - if (packet->getFace() == 255) - { - if (item == NULL) return; - player->gameMode->useItem(player, level, item); - } - else if ((packet->getY() < server->getMaxBuildHeight() - 1) || (packet->getFace() != Facing::UP && packet->getY() < server->getMaxBuildHeight())) - { - Pos *spawnPos = level->getSharedSpawnPos(); - int xd = (int) Mth::abs((float)(x - spawnPos->x)); - int zd = (int) Mth::abs((float)(z - spawnPos->z)); - delete spawnPos; - if (xd > zd) zd = xd; - if (synched && player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) < 8 * 8) - { - if (zd > 16 || canEditSpawn) - { - player->gameMode->useItemOn(player, level, item, x, y, z, face, packet->getClickX(), packet->getClickY(), packet->getClickZ()); - } - } +void PlayerConnection::handleUseItem(std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); + std::shared_ptr item = player->inventory->getSelected(); + bool informClient = false; + int x = packet->getX(); + int y = packet->getY(); + int z = packet->getZ(); + int face = packet->getFace(); - informClient = true; - } - else - { - //player->connection->send(std::shared_ptr(new ChatPacket("\u00A77Height limit for building is " + server->maxBuildHeight))); - informClient = true; - } + // 4J Stu - We don't have ops, so just use the levels setting + bool canEditSpawn = + level->canEditSpawn; // = level->dimension->id != 0 || + // server->players->isOp(player->name); + if (packet->getFace() == 255) { + if (item == NULL) return; + player->gameMode->useItem(player, level, item); + } else if ((packet->getY() < server->getMaxBuildHeight() - 1) || + (packet->getFace() != Facing::UP && + packet->getY() < server->getMaxBuildHeight())) { + Pos* spawnPos = level->getSharedSpawnPos(); + int xd = (int)Mth::abs((float)(x - spawnPos->x)); + int zd = (int)Mth::abs((float)(z - spawnPos->z)); + delete spawnPos; + if (xd > zd) zd = xd; + if (synched && + player->distanceToSqr(x + 0.5, y + 0.5, z + 0.5) < 8 * 8) { + if (zd > 16 || canEditSpawn) { + player->gameMode->useItemOn( + player, level, item, x, y, z, face, packet->getClickX(), + packet->getClickY(), packet->getClickZ()); + } + } - if (informClient) - { + informClient = true; + } else { + // player->connection->send(std::shared_ptr(new + // ChatPacket("\u00A77Height limit for building is " + + // server->maxBuildHeight))); + informClient = true; + } - player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); + if (informClient) { + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); - if (face == 0) y--; - if (face == 1) y++; - if (face == 2) z--; - if (face == 3) z++; - if (face == 4) x--; - if (face == 5) x++; - - // 4J - Fixes an issue where pistons briefly disappear when retracting. The pistons themselves shouldn't have their change from being pistonBase_Id to pistonMovingPiece_Id - // directly sent to the client, as this will happen on the client as a result of it actioning (via a tile event) the retraction of the piston locally. However, by putting a switch - // beside a piston and then performing an action on the side of it facing a piston, the following line of code will send a TileUpdatePacket containing the change to pistonMovingPiece_Id - // to the client, and this packet is received before the piston retract action happens - when the piston retract then occurs, it doesn't work properly because the piston tile - // isn't what it is expecting. - if( level->getTile(x,y,z) != Tile::pistonMovingPiece_Id ) - { - player->connection->send( std::shared_ptr( new TileUpdatePacket(x, y, z, level) ) ); - } + if (face == 0) y--; + if (face == 1) y++; + if (face == 2) z--; + if (face == 3) z++; + if (face == 4) x--; + if (face == 5) x++; - } + // 4J - Fixes an issue where pistons briefly disappear when retracting. + // The pistons themselves shouldn't have their change from being + // pistonBase_Id to pistonMovingPiece_Id directly sent to the client, + // as this will happen on the client as a result of it actioning (via a + // tile event) the retraction of the piston locally. However, by putting + // a switch beside a piston and then performing an action on the side of + // it facing a piston, the following line of code will send a + // TileUpdatePacket containing the change to pistonMovingPiece_Id to the + // client, and this packet is received before the piston retract action + // happens - when the piston retract then occurs, it doesn't work + // properly because the piston tile isn't what it is expecting. + if (level->getTile(x, y, z) != Tile::pistonMovingPiece_Id) { + player->connection->send(std::shared_ptr( + new TileUpdatePacket(x, y, z, level))); + } + } - item = player->inventory->getSelected(); - if (item != NULL && item->count == 0) - { - player->inventory->items[player->inventory->selected] = nullptr; - item = nullptr; - } + item = player->inventory->getSelected(); + if (item != NULL && item->count == 0) { + player->inventory->items[player->inventory->selected] = nullptr; + item = nullptr; + } - if (item == NULL || item->getUseDuration() == 0) - { - player->ignoreSlotUpdateHack = true; - player->inventory->items[player->inventory->selected] = ItemInstance::clone(player->inventory->items[player->inventory->selected]); - Slot *s = player->containerMenu->getSlotFor(player->inventory, player->inventory->selected); - player->containerMenu->broadcastChanges(); - player->ignoreSlotUpdateHack = false; + if (item == NULL || item->getUseDuration() == 0) { + player->ignoreSlotUpdateHack = true; + player->inventory->items[player->inventory->selected] = + ItemInstance::clone( + player->inventory->items[player->inventory->selected]); + Slot* s = player->containerMenu->getSlotFor( + player->inventory, player->inventory->selected); + player->containerMenu->broadcastChanges(); + player->ignoreSlotUpdateHack = false; - if (!ItemInstance::matches(player->inventory->getSelected(), packet->getItem())) - { - send( std::shared_ptr( new ContainerSetSlotPacket(player->containerMenu->containerId, s->index, player->inventory->getSelected()) ) ); - } - } - - // 4J Stu - Don't change the levels state - //level->canEditSpawn = false; + if (!ItemInstance::matches(player->inventory->getSelected(), + packet->getItem())) { + send(std::shared_ptr( + new ContainerSetSlotPacket(player->containerMenu->containerId, + s->index, + player->inventory->getSelected()))); + } + } + // 4J Stu - Don't change the levels state + // level->canEditSpawn = false; } -void PlayerConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) -{ - EnterCriticalSection(&done_cs); - if( done ) return; -// logger.info(player.name + " lost connection: " + reason); - // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( std::shared_ptr( new ChatPacket(L"§e" + player->name + L" left the game.") ) ); - if(getWasKicked()) - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); - } - else - { - server->getPlayers()->broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame) ) ); - } - server->getPlayers()->remove(player); - done = true; - LeaveCriticalSection(&done_cs); +void PlayerConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects) { + EnterCriticalSection(&done_cs); + if (done) return; + // logger.info(player.name + " lost connection: " + reason); + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // server->players->broadcastAll( std::shared_ptr( new + // ChatPacket(L"§e" + player->name + L" left the game.") ) ); + if (getWasKicked()) { + server->getPlayers()->broadcastAll( + std::shared_ptr(new ChatPacket( + player->name, ChatPacket::e_ChatPlayerKickedFromGame))); + } else { + server->getPlayers()->broadcastAll(std::shared_ptr( + new ChatPacket(player->name, ChatPacket::e_ChatPlayerLeftGame))); + } + server->getPlayers()->remove(player); + done = true; + LeaveCriticalSection(&done_cs); } -void PlayerConnection::onUnhandledPacket(std::shared_ptr packet) -{ -// logger.warning(getClass() + " wasn't prepared to deal with a " + packet.getClass()); - disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); +void PlayerConnection::onUnhandledPacket(std::shared_ptr packet) { + // logger.warning(getClass() + " wasn't prepared to deal with a " + + // packet.getClass()); + disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket); } -void PlayerConnection::send(std::shared_ptr packet) -{ - if( connection->getSocket() != NULL ) - { - if( !server->getPlayers()->canReceiveAllPackets( player ) ) - { - // Check if we are allowed to send this packet type - if( !Packet::canSendToAnyClient(packet) ) - { - //wprintf(L"Not the systems primary player, so not sending them a packet : %ls / %d\n", player->name.c_str(), packet->getId() ); - return; - } - } - connection->send(packet); - } +void PlayerConnection::send(std::shared_ptr packet) { + if (connection->getSocket() != NULL) { + if (!server->getPlayers()->canReceiveAllPackets(player)) { + // Check if we are allowed to send this packet type + if (!Packet::canSendToAnyClient(packet)) { + // wprintf(L"Not the systems primary player, so not sending them + // a packet : %ls / %d\n", player->name.c_str(), packet->getId() + // ); + return; + } + } + connection->send(packet); + } } // 4J Added -void PlayerConnection::queueSend(std::shared_ptr packet) -{ - if( connection->getSocket() != NULL ) - { - if( !server->getPlayers()->canReceiveAllPackets( player ) ) - { - // Check if we are allowed to send this packet type - if( !Packet::canSendToAnyClient(packet) ) - { - //wprintf(L"Not the systems primary player, so not queueing them a packet : %ls\n", connection->getSocket()->getPlayer()->GetGamertag() ); - return; - } - } - connection->queueSend(packet); - } +void PlayerConnection::queueSend(std::shared_ptr packet) { + if (connection->getSocket() != NULL) { + if (!server->getPlayers()->canReceiveAllPackets(player)) { + // Check if we are allowed to send this packet type + if (!Packet::canSendToAnyClient(packet)) { + // wprintf(L"Not the systems primary player, so not queueing + // them a packet : %ls\n", + // connection->getSocket()->getPlayer()->GetGamertag() ); + return; + } + } + connection->queueSend(packet); + } } -void PlayerConnection::handleSetCarriedItem(std::shared_ptr packet) -{ - if (packet->slot < 0 || packet->slot >= Inventory::getSelectionSize()) - { -// logger.warning(player.name + " tried to set an invalid carried item"); - return; - } - player->inventory->selected = packet->slot; +void PlayerConnection::handleSetCarriedItem( + std::shared_ptr packet) { + if (packet->slot < 0 || packet->slot >= Inventory::getSelectionSize()) { + // logger.warning(player.name + " tried to set an invalid carried + // item"); + return; + } + player->inventory->selected = packet->slot; } -void PlayerConnection::handleChat(std::shared_ptr packet) -{ - // 4J - TODO +void PlayerConnection::handleChat(std::shared_ptr packet) { + // 4J - TODO #if 0 std::wstring message = packet->message; if (message.length() > SharedConstants::maxChatLength) @@ -670,756 +678,850 @@ void PlayerConnection::handleChat(std::shared_ptr packet) #endif } -void PlayerConnection::handleCommand(const std::wstring& message) -{ - // 4J - TODO +void PlayerConnection::handleCommand(const std::wstring& message) { + // 4J - TODO #if 0 server.getCommandDispatcher().performCommand(player, message); #endif } -void PlayerConnection::handleAnimate(std::shared_ptr packet) -{ - if (packet->action == AnimatePacket::SWING) - { - player->swing(); - } -} - -void PlayerConnection::handlePlayerCommand(std::shared_ptr packet) -{ - if (packet->action == PlayerCommandPacket::START_SNEAKING) - { - player->setSneaking(true); - } - else if (packet->action == PlayerCommandPacket::STOP_SNEAKING) - { - player->setSneaking(false); - } - else if (packet->action == PlayerCommandPacket::START_SPRINTING) - { - player->setSprinting(true); - } - else if (packet->action == PlayerCommandPacket::STOP_SPRINTING) - { - player->setSprinting(false); - } - else if (packet->action == PlayerCommandPacket::STOP_SLEEPING) - { - player->stopSleepInBed(false, true, true); - synched = false; - } - else if (packet->action == PlayerCommandPacket::START_IDLEANIM) - { - player->setIsIdle(true); - } - else if (packet->action == PlayerCommandPacket::STOP_IDLEANIM) - { - player->setIsIdle(false); - } - -} - -void PlayerConnection::setShowOnMaps(bool bVal) -{ - player->setShowOnMaps(bVal); -} - -void PlayerConnection::handleDisconnect(std::shared_ptr packet) -{ - // 4J Stu - Need to remove the player from the receiving list before their socket is NULLed so that we can find another player on their system - server->getPlayers()->removePlayerFromReceiving( player ); - connection->close(DisconnectPacket::eDisconnect_Quitting); -} - -int PlayerConnection::countDelayedPackets() -{ - return connection->countDelayedPackets(); -} - -void PlayerConnection::info(const std::wstring& string) -{ - // 4J-PB - removed, since it needs to be localised in the language the client is in - //send( std::shared_ptr( new ChatPacket(L"§7" + string) ) ); -} - -void PlayerConnection::warn(const std::wstring& string) -{ - // 4J-PB - removed, since it needs to be localised in the language the client is in - //send( std::shared_ptr( new ChatPacket(L"§9" + string) ) ); -} - -std::wstring PlayerConnection::getConsoleName() -{ - return player->name; -} - -void PlayerConnection::handleInteract(std::shared_ptr packet) -{ - ServerLevel *level = server->getLevel(player->dimension); - std::shared_ptr target = level->getEntity(packet->target); - - // Fix for #8218 - Gameplay: Attacking zombies from a different level often results in no hits being registered - // 4J Stu - If the client says that we hit something, then agree with it. The canSee can fail here as it checks - // a ray from head->head, but we may actually be looking at a different part of the entity that can be seen - // even though the ray is blocked. - if (target != NULL) // && player->canSee(target) && player->distanceToSqr(target) < 6 * 6) - { - //boole canSee = player->canSee(target); - //double maxDist = 6 * 6; - //if (!canSee) - //{ - // maxDist = 3 * 3; - //} - - //if (player->distanceToSqr(target) < maxDist) - //{ - if (packet->action == InteractPacket::INTERACT) - { - player->interact(target); - } - else if (packet->action == InteractPacket::ATTACK) - { - player->attack(target); - } - //} - } - -} - -bool PlayerConnection::canHandleAsyncPackets() -{ - return true; -} - -void PlayerConnection::handleTexture(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - - if(packet->dataBytes==0) - { - // Request for texture -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received request for custom texture %ls\n",packet->textureName.c_str()); -#endif - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); - - if(dwBytes!=0) - { - send( std::shared_ptr( new TexturePacket(packet->textureName,pbData,dwBytes) ) ); - } - else - { - m_texturesRequested.push_back( packet->textureName ); - } - } - else - { - // Response with texture data -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received custom texture %ls\n",packet->textureName.c_str()); -#endif - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dataBytes); - server->connection->handleTextureReceived(packet->textureName); - } -} - -void PlayerConnection::handleTextureAndGeometry(std::shared_ptr packet) -{ - // Both PlayerConnection and ClientConnection should handle this mostly the same way - - if(packet->dwTextureBytes==0) - { - // Request for texture and geometry -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received request for custom texture %ls\n",packet->textureName.c_str()); -#endif - std::uint8_t *pbData=NULL; - unsigned int dwTextureBytes=0; - app.GetMemFileDetails(packet->textureName,&pbData,&dwTextureBytes); - DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); - - if(dwTextureBytes!=0) - { - - if(pDLCSkinFile) - { - if(pDLCSkinFile->getAdditionalBoxesCount()!=0) - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes,pDLCSkinFile) ) ); - } - else - { - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes) ) ); - } - } - else - { - // we don't have the dlc skin, so retrieve the data from the app store - std::vector *pvSkinBoxes = app.GetAdditionalSkinBoxes(packet->dwSkinID); - unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(packet->dwSkinID); - - send( std::shared_ptr( new TextureAndGeometryPacket(packet->textureName,pbData,dwTextureBytes,pvSkinBoxes,uiAnimOverrideBitmask) ) ); - } - } - else - { - m_texturesRequested.push_back( packet->textureName ); - } - } - else - { - // Response with texture and geometry data -#ifndef _CONTENT_PACKAGE - wprintf(L"Server received custom texture %ls and geometry\n",packet->textureName.c_str()); -#endif - app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dwTextureBytes); - - // add the geometry to the app list - if(packet->dwBoxC!=0) - { -#ifndef _CONTENT_PACKAGE - wprintf(L"Adding skin boxes for skin id %X, box count %d\n",packet->dwSkinID,packet->dwBoxC); -#endif - app.SetAdditionalSkinBoxes(packet->dwSkinID,packet->BoxDataA,packet->dwBoxC); - } - // Add the anim override - app.SetAnimOverrideBitmask(packet->dwSkinID,packet->uiAnimOverrideBitmask); - - player->setCustomSkin(packet->dwSkinID); - - server->connection->handleTextureAndGeometryReceived(packet->textureName); - } -} - -void PlayerConnection::handleTextureReceived(const std::wstring &textureName) -{ - // This sends the server received texture out to any other players waiting for the data - AUTO_VAR(it, find( m_texturesRequested.begin(), m_texturesRequested.end(), textureName )); - if( it != m_texturesRequested.end() ) - { - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(textureName,&pbData,&dwBytes); - - if(dwBytes!=0) - { - send( std::shared_ptr( new TexturePacket(textureName,pbData,dwBytes) ) ); - m_texturesRequested.erase(it); - } - } -} - -void PlayerConnection::handleTextureAndGeometryReceived(const std::wstring &textureName) -{ - // This sends the server received texture out to any other players waiting for the data - AUTO_VAR(it, find( m_texturesRequested.begin(), m_texturesRequested.end(), textureName )); - if( it != m_texturesRequested.end() ) - { - std::uint8_t *pbData=NULL; - unsigned int dwTextureBytes=0; - app.GetMemFileDetails(textureName,&pbData,&dwTextureBytes); - DLCSkinFile *pDLCSkinFile=app.m_dlcManager.getSkinFile(textureName); - - if(dwTextureBytes!=0) - { - if(pDLCSkinFile && (pDLCSkinFile->getAdditionalBoxesCount()!=0)) - { - send( std::shared_ptr( new TextureAndGeometryPacket(textureName,pbData,dwTextureBytes,pDLCSkinFile) ) ); - } - else - { - // get the data from the app - std::uint32_t dwSkinID = app.getSkinIdFromPath(textureName); - std::vector *pvSkinBoxes = app.GetAdditionalSkinBoxes(dwSkinID); - unsigned int uiAnimOverrideBitmask= app.GetAnimOverrideBitmask(dwSkinID); - - send( std::shared_ptr( new TextureAndGeometryPacket(textureName,pbData,dwTextureBytes, pvSkinBoxes, uiAnimOverrideBitmask) ) ); - } - m_texturesRequested.erase(it); - } - } -} - -void PlayerConnection::handleTextureChange(std::shared_ptr packet) -{ - switch(packet->action) - { - case TextureChangePacket::e_TextureChange_Skin: - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); -#ifndef _CONTENT_PACKAGE - wprintf(L"Skin for server player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); -#endif - break; - case TextureChangePacket::e_TextureChange_Cape: - player->setCustomCape( Player::getCapeIdFromPath( packet->path ) ); - //player->customTextureUrl2 = packet->path; -#ifndef _CONTENT_PACKAGE - wprintf(L"Cape for server player %ls has changed to %ls\n", player->name.c_str(), player->customTextureUrl2.c_str() ); -#endif - break; - } - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( server->connection->addPendingTextureRequest(packet->path)) - { -#ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",packet->path.c_str(), player->name.c_str()); -#endif - send(std::shared_ptr( new TexturePacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - } - server->getPlayers()->broadcastAll( std::shared_ptr( new TextureChangePacket(player,packet->action,packet->path) ), player->dimension ); -} - -void PlayerConnection::handleTextureAndGeometryChange(std::shared_ptr packet) -{ - - player->setCustomSkin( app.getSkinIdFromPath( packet->path ) ); -#ifndef _CONTENT_PACKAGE - wprintf(L"PlayerConnection::handleTextureAndGeometryChange - Skin for server player %ls has changed to %ls (%d)\n", player->name.c_str(), player->customTextureUrl.c_str(), player->getPlayerDefaultSkin() ); -#endif - - - if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) - { - if( server->connection->addPendingTextureRequest(packet->path)) - { -#ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",packet->path.c_str(), player->name.c_str()); -#endif - send(std::shared_ptr( new TextureAndGeometryPacket(packet->path,NULL,0) ) ); - } - } - else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(packet->path,NULL,0); - - player->setCustomSkin(packet->dwSkinID); - - // If we already have the texture, then we already have the model parts too - //app.SetAdditionalSkinBoxes(packet->dwSkinID,) - //DebugBreak(); - } - server->getPlayers()->broadcastAll( std::shared_ptr( new TextureAndGeometryChangePacket(player,packet->path) ), player->dimension ); -} - -void PlayerConnection::handleServerSettingsChanged(std::shared_ptr packet) -{ - if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) - { - // Need to check that this player has permission to change each individual setting? - - INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator()) - { - app.SetGameHostOption(eGameHostOption_FireSpreads, app.GetGameHostOption(packet->data,eGameHostOption_FireSpreads)); - app.SetGameHostOption(eGameHostOption_TNT, app.GetGameHostOption(packet->data,eGameHostOption_TNT)); - - server->getPlayers()->broadcastAll( std::shared_ptr( new ServerSettingsChangedPacket( ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS,app.GetGameHostOption(eGameHostOption_All) ) ) ); - - // Update the QoS data - g_NetworkManager.UpdateAndSetGameSessionData(); - } - } -} - -void PlayerConnection::handleKickPlayer(std::shared_ptr packet) -{ - INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator()) - { - server->getPlayers()->kickPlayerByShortId(packet->m_networkSmallId); - } -} - -void PlayerConnection::handleGameCommand(std::shared_ptr packet) -{ - MinecraftServer::getInstance()->getCommandDispatcher()->performCommand(player, packet->command, packet->data); -} - -void PlayerConnection::handleClientCommand(std::shared_ptr packet) -{ - if (packet->action == ClientCommandPacket::PERFORM_RESPAWN) - { - if (player->wonGame) - { - player = server->getPlayers()->respawn(player, player->m_enteredEndExitPortal?0:player->dimension, true); - } - //else if (player.getLevel().getLevelData().isHardcore()) - //{ - // if (server.isSingleplayer() && player.name.equals(server.getSingleplayerName())) - // { - // player.connection.disconnect("You have died. Game over, man, it's game over!"); - // server.selfDestruct(); - // } - // else - // { - // BanEntry ban = new BanEntry(player.name); - // ban.setReason("Death in Hardcore"); - - // server.getPlayers().getBans().add(ban); - // player.connection.disconnect("You have died. Game over, man, it's game over!"); - // } - //} - else - { - if (player->getHealth() > 0) return; - player = server->getPlayers()->respawn(player, 0, false); - } - } -} - -void PlayerConnection::handleRespawn(std::shared_ptr packet) -{ -} - -void PlayerConnection::handleContainerClose(std::shared_ptr packet) -{ - player->doCloseContainer(); -} - -#ifndef _CONTENT_PACKAGE -void PlayerConnection::handleContainerSetSlot(std::shared_ptr packet) -{ - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED ) - { - player->inventory->setCarried(packet->item); +void PlayerConnection::handleAnimate(std::shared_ptr packet) { + if (packet->action == AnimatePacket::SWING) { + player->swing(); } - else - { - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY && packet->slot >= 36 && packet->slot < 36 + 9) - { - std::shared_ptr lastItem = player->inventoryMenu->getSlot(packet->slot)->getItem(); - if (packet->item != NULL) - { - if (lastItem == NULL || lastItem->count < packet->item->count) - { +} + +void PlayerConnection::handlePlayerCommand( + std::shared_ptr packet) { + if (packet->action == PlayerCommandPacket::START_SNEAKING) { + player->setSneaking(true); + } else if (packet->action == PlayerCommandPacket::STOP_SNEAKING) { + player->setSneaking(false); + } else if (packet->action == PlayerCommandPacket::START_SPRINTING) { + player->setSprinting(true); + } else if (packet->action == PlayerCommandPacket::STOP_SPRINTING) { + player->setSprinting(false); + } else if (packet->action == PlayerCommandPacket::STOP_SLEEPING) { + player->stopSleepInBed(false, true, true); + synched = false; + } else if (packet->action == PlayerCommandPacket::START_IDLEANIM) { + player->setIsIdle(true); + } else if (packet->action == PlayerCommandPacket::STOP_IDLEANIM) { + player->setIsIdle(false); + } +} + +void PlayerConnection::setShowOnMaps(bool bVal) { player->setShowOnMaps(bVal); } + +void PlayerConnection::handleDisconnect( + std::shared_ptr packet) { + // 4J Stu - Need to remove the player from the receiving list before their + // socket is NULLed so that we can find another player on their system + server->getPlayers()->removePlayerFromReceiving(player); + connection->close(DisconnectPacket::eDisconnect_Quitting); +} + +int PlayerConnection::countDelayedPackets() { + return connection->countDelayedPackets(); +} + +void PlayerConnection::info(const std::wstring& string) { + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // send( std::shared_ptr( new ChatPacket(L"§7" + string) ) ); +} + +void PlayerConnection::warn(const std::wstring& string) { + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // send( std::shared_ptr( new ChatPacket(L"§9" + string) ) ); +} + +std::wstring PlayerConnection::getConsoleName() { return player->name; } + +void PlayerConnection::handleInteract(std::shared_ptr packet) { + ServerLevel* level = server->getLevel(player->dimension); + std::shared_ptr target = level->getEntity(packet->target); + + // Fix for #8218 - Gameplay: Attacking zombies from a different level often + // results in no hits being registered 4J Stu - If the client says that we + // hit something, then agree with it. The canSee can fail here as it checks + // a ray from head->head, but we may actually be looking at a different part + // of the entity that can be seen even though the ray is blocked. + if (target != NULL) // && player->canSee(target) && + // player->distanceToSqr(target) < 6 * 6) + { + // boole canSee = player->canSee(target); + // double maxDist = 6 * 6; + // if (!canSee) + //{ + // maxDist = 3 * 3; + // } + + // if (player->distanceToSqr(target) < maxDist) + //{ + if (packet->action == InteractPacket::INTERACT) { + player->interact(target); + } else if (packet->action == InteractPacket::ATTACK) { + player->attack(target); + } + //} + } +} + +bool PlayerConnection::canHandleAsyncPackets() { return true; } + +void PlayerConnection::handleTexture(std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way + + if (packet->dataBytes == 0) { + // Request for texture +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received request for custom texture %ls\n", + packet->textureName.c_str()); +#endif + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwBytes); + + if (dwBytes != 0) { + send(std::shared_ptr( + new TexturePacket(packet->textureName, pbData, dwBytes))); + } else { + m_texturesRequested.push_back(packet->textureName); + } + } else { + // Response with texture data +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received custom texture %ls\n", + packet->textureName.c_str()); +#endif + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dataBytes); + server->connection->handleTextureReceived(packet->textureName); + } +} + +void PlayerConnection::handleTextureAndGeometry( + std::shared_ptr packet) { + // Both PlayerConnection and ClientConnection should handle this mostly the + // same way + + if (packet->dwTextureBytes == 0) { + // Request for texture and geometry +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received request for custom texture %ls\n", + packet->textureName.c_str()); +#endif + std::uint8_t* pbData = NULL; + unsigned int dwTextureBytes = 0; + app.GetMemFileDetails(packet->textureName, &pbData, &dwTextureBytes); + DLCSkinFile* pDLCSkinFile = + app.m_dlcManager.getSkinFile(packet->textureName); + + if (dwTextureBytes != 0) { + if (pDLCSkinFile) { + if (pDLCSkinFile->getAdditionalBoxesCount() != 0) { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwTextureBytes, + pDLCSkinFile))); + } else { + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, + pbData, dwTextureBytes))); + } + } else { + // we don't have the dlc skin, so retrieve the data from the app + // store + std::vector* pvSkinBoxes = + app.GetAdditionalSkinBoxes(packet->dwSkinID); + unsigned int uiAnimOverrideBitmask = + app.GetAnimOverrideBitmask(packet->dwSkinID); + + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->textureName, pbData, + dwTextureBytes, pvSkinBoxes, + uiAnimOverrideBitmask))); + } + } else { + m_texturesRequested.push_back(packet->textureName); + } + } else { + // Response with texture and geometry data +#ifndef _CONTENT_PACKAGE + wprintf(L"Server received custom texture %ls and geometry\n", + packet->textureName.c_str()); +#endif + app.AddMemoryTextureFile(packet->textureName, packet->pbData, + packet->dwTextureBytes); + + // add the geometry to the app list + if (packet->dwBoxC != 0) { +#ifndef _CONTENT_PACKAGE + wprintf(L"Adding skin boxes for skin id %X, box count %d\n", + packet->dwSkinID, packet->dwBoxC); +#endif + app.SetAdditionalSkinBoxes(packet->dwSkinID, packet->BoxDataA, + packet->dwBoxC); + } + // Add the anim override + app.SetAnimOverrideBitmask(packet->dwSkinID, + packet->uiAnimOverrideBitmask); + + player->setCustomSkin(packet->dwSkinID); + + server->connection->handleTextureAndGeometryReceived( + packet->textureName); + } +} + +void PlayerConnection::handleTextureReceived(const std::wstring& textureName) { + // This sends the server received texture out to any other players waiting + // for the data + AUTO_VAR(it, find(m_texturesRequested.begin(), m_texturesRequested.end(), + textureName)); + if (it != m_texturesRequested.end()) { + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(textureName, &pbData, &dwBytes); + + if (dwBytes != 0) { + send(std::shared_ptr( + new TexturePacket(textureName, pbData, dwBytes))); + m_texturesRequested.erase(it); + } + } +} + +void PlayerConnection::handleTextureAndGeometryReceived( + const std::wstring& textureName) { + // This sends the server received texture out to any other players waiting + // for the data + AUTO_VAR(it, find(m_texturesRequested.begin(), m_texturesRequested.end(), + textureName)); + if (it != m_texturesRequested.end()) { + std::uint8_t* pbData = NULL; + unsigned int dwTextureBytes = 0; + app.GetMemFileDetails(textureName, &pbData, &dwTextureBytes); + DLCSkinFile* pDLCSkinFile = app.m_dlcManager.getSkinFile(textureName); + + if (dwTextureBytes != 0) { + if (pDLCSkinFile && + (pDLCSkinFile->getAdditionalBoxesCount() != 0)) { + send(std::shared_ptr( + new TextureAndGeometryPacket( + textureName, pbData, dwTextureBytes, pDLCSkinFile))); + } else { + // get the data from the app + std::uint32_t dwSkinID = app.getSkinIdFromPath(textureName); + std::vector* pvSkinBoxes = + app.GetAdditionalSkinBoxes(dwSkinID); + unsigned int uiAnimOverrideBitmask = + app.GetAnimOverrideBitmask(dwSkinID); + + send(std::shared_ptr( + new TextureAndGeometryPacket(textureName, pbData, + dwTextureBytes, pvSkinBoxes, + uiAnimOverrideBitmask))); + } + m_texturesRequested.erase(it); + } + } +} + +void PlayerConnection::handleTextureChange( + std::shared_ptr packet) { + switch (packet->action) { + case TextureChangePacket::e_TextureChange_Skin: + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); +#ifndef _CONTENT_PACKAGE + wprintf(L"Skin for server player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); +#endif + break; + case TextureChangePacket::e_TextureChange_Cape: + player->setCustomCape(Player::getCapeIdFromPath(packet->path)); + // player->customTextureUrl2 = packet->path; +#ifndef _CONTENT_PACKAGE + wprintf(L"Cape for server player %ls has changed to %ls\n", + player->name.c_str(), player->customTextureUrl2.c_str()); +#endif + break; + } + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (server->connection->addPendingTextureRequest(packet->path)) { +#ifndef _CONTENT_PACKAGE + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + packet->path.c_str(), player->name.c_str()); +#endif + send(std::shared_ptr( + new TexturePacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + } + server->getPlayers()->broadcastAll( + std::shared_ptr( + new TextureChangePacket(player, packet->action, packet->path)), + player->dimension); +} + +void PlayerConnection::handleTextureAndGeometryChange( + std::shared_ptr packet) { + player->setCustomSkin(app.getSkinIdFromPath(packet->path)); +#ifndef _CONTENT_PACKAGE + wprintf( + L"PlayerConnection::handleTextureAndGeometryChange - Skin for server " + L"player %ls has changed to %ls (%d)\n", + player->name.c_str(), player->customTextureUrl.c_str(), + player->getPlayerDefaultSkin()); +#endif + + if (!packet->path.empty() && + packet->path.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(packet->path)) { + if (server->connection->addPendingTextureRequest(packet->path)) { +#ifndef _CONTENT_PACKAGE + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + packet->path.c_str(), player->name.c_str()); +#endif + send(std::shared_ptr( + new TextureAndGeometryPacket(packet->path, NULL, 0))); + } + } else if (!packet->path.empty() && + app.IsFileInMemoryTextures(packet->path)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(packet->path, NULL, 0); + + player->setCustomSkin(packet->dwSkinID); + + // If we already have the texture, then we already have the model parts + // too + // app.SetAdditionalSkinBoxes(packet->dwSkinID,) + // DebugBreak(); + } + server->getPlayers()->broadcastAll( + std::shared_ptr( + new TextureAndGeometryChangePacket(player, packet->path)), + player->dimension); +} + +void PlayerConnection::handleServerSettingsChanged( + std::shared_ptr packet) { + if (packet->action == ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS) { + // Need to check that this player has permission to change each + // individual setting? + + INetworkPlayer* networkPlayer = getNetworkPlayer(); + if ((networkPlayer != NULL && networkPlayer->IsHost()) || + player->isModerator()) { + app.SetGameHostOption( + eGameHostOption_FireSpreads, + app.GetGameHostOption(packet->data, + eGameHostOption_FireSpreads)); + app.SetGameHostOption( + eGameHostOption_TNT, + app.GetGameHostOption(packet->data, eGameHostOption_TNT)); + + server->getPlayers()->broadcastAll( + std::shared_ptr( + new ServerSettingsChangedPacket( + ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS, + app.GetGameHostOption(eGameHostOption_All)))); + + // Update the QoS data + g_NetworkManager.UpdateAndSetGameSessionData(); + } + } +} + +void PlayerConnection::handleKickPlayer( + std::shared_ptr packet) { + INetworkPlayer* networkPlayer = getNetworkPlayer(); + if ((networkPlayer != NULL && networkPlayer->IsHost()) || + player->isModerator()) { + server->getPlayers()->kickPlayerByShortId(packet->m_networkSmallId); + } +} + +void PlayerConnection::handleGameCommand( + std::shared_ptr packet) { + MinecraftServer::getInstance()->getCommandDispatcher()->performCommand( + player, packet->command, packet->data); +} + +void PlayerConnection::handleClientCommand( + std::shared_ptr packet) { + if (packet->action == ClientCommandPacket::PERFORM_RESPAWN) { + if (player->wonGame) { + player = server->getPlayers()->respawn( + player, player->m_enteredEndExitPortal ? 0 : player->dimension, + true); + } + // else if (player.getLevel().getLevelData().isHardcore()) + //{ + // if (server.isSingleplayer() && + //player.name.equals(server.getSingleplayerName())) + // { + // player.connection.disconnect("You have died. Game over, + //man, it's game over!"); server.selfDestruct(); + // } + // else + // { + // BanEntry ban = new BanEntry(player.name); + // ban.setReason("Death in Hardcore"); + + // server.getPlayers().getBans().add(ban); + // player.connection.disconnect("You have died. Game over, + //man, it's game over!"); + // } + //} + else { + if (player->getHealth() > 0) return; + player = server->getPlayers()->respawn(player, 0, false); + } + } +} + +void PlayerConnection::handleRespawn(std::shared_ptr packet) {} + +void PlayerConnection::handleContainerClose( + std::shared_ptr packet) { + player->doCloseContainer(); +} + +#ifndef _CONTENT_PACKAGE +void PlayerConnection::handleContainerSetSlot( + std::shared_ptr packet) { + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED) { + player->inventory->setCarried(packet->item); + } else { + if (packet->containerId == + AbstractContainerMenu::CONTAINER_ID_INVENTORY && + packet->slot >= 36 && packet->slot < 36 + 9) { + std::shared_ptr lastItem = + player->inventoryMenu->getSlot(packet->slot)->getItem(); + if (packet->item != NULL) { + if (lastItem == NULL || lastItem->count < packet->item->count) { packet->item->popTime = Inventory::POP_TIME_DURATION; } } - player->inventoryMenu->setItem(packet->slot, packet->item); - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; - } - else if (packet->containerId == player->containerMenu->containerId) - { + player->inventoryMenu->setItem(packet->slot, packet->item); + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; + } else if (packet->containerId == player->containerMenu->containerId) { player->containerMenu->setItem(packet->slot, packet->item); - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; } } } #endif -void PlayerConnection::handleContainerClick(std::shared_ptr packet) -{ - if (player->containerMenu->containerId == packet->containerId && player->containerMenu->isSynched(player)) - { - std::shared_ptr clicked = player->containerMenu->clicked(packet->slotNum, packet->buttonNum, packet->quickKey?AbstractContainerMenu::CLICK_QUICK_MOVE:AbstractContainerMenu::CLICK_PICKUP, player); +void PlayerConnection::handleContainerClick( + std::shared_ptr packet) { + if (player->containerMenu->containerId == packet->containerId && + player->containerMenu->isSynched(player)) { + std::shared_ptr clicked = player->containerMenu->clicked( + packet->slotNum, packet->buttonNum, + packet->quickKey ? AbstractContainerMenu::CLICK_QUICK_MOVE + : AbstractContainerMenu::CLICK_PICKUP, + player); - if (ItemInstance::matches(packet->item, clicked)) - { - // Yep, you sure did click what you claimed to click! - player->connection->send( std::shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, true) ) ); - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; - } - else - { - // No, you clicked the wrong thing! - expectedAcks[player->containerMenu->containerId] = packet->uid; - player->connection->send( std::shared_ptr( new ContainerAckPacket(packet->containerId, packet->uid, false) ) ); - player->containerMenu->setSynched(player, false); + if (ItemInstance::matches(packet->item, clicked)) { + // Yep, you sure did click what you claimed to click! + player->connection->send( + std::shared_ptr(new ContainerAckPacket( + packet->containerId, packet->uid, true))); + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; + } else { + // No, you clicked the wrong thing! + expectedAcks[player->containerMenu->containerId] = packet->uid; + player->connection->send( + std::shared_ptr(new ContainerAckPacket( + packet->containerId, packet->uid, false))); + player->containerMenu->setSynched(player, false); - std::vector > items; - for (unsigned int i = 0; i < player->containerMenu->slots->size(); i++) - { - items.push_back(player->containerMenu->slots->at(i)->getItem()); - } - player->refreshContainer(player->containerMenu, &items); - -// player.containerMenu.broadcastChanges(); - } - } + std::vector > items; + for (unsigned int i = 0; i < player->containerMenu->slots->size(); + i++) { + items.push_back(player->containerMenu->slots->at(i)->getItem()); + } + player->refreshContainer(player->containerMenu, &items); + // player.containerMenu.broadcastChanges(); + } + } } -void PlayerConnection::handleContainerButtonClick(std::shared_ptr packet) -{ - if (player->containerMenu->containerId == packet->containerId && player->containerMenu->isSynched(player)) - { - player->containerMenu->clickMenuButton(player, packet->buttonId); - player->containerMenu->broadcastChanges(); - } +void PlayerConnection::handleContainerButtonClick( + std::shared_ptr packet) { + if (player->containerMenu->containerId == packet->containerId && + player->containerMenu->isSynched(player)) { + player->containerMenu->clickMenuButton(player, packet->buttonId); + player->containerMenu->broadcastChanges(); + } } -void PlayerConnection::handleSetCreativeModeSlot(std::shared_ptr packet) -{ - if (player->gameMode->isCreative()) - { - bool drop = packet->slotNum < 0; - std::shared_ptr item = packet->item; +void PlayerConnection::handleSetCreativeModeSlot( + std::shared_ptr packet) { + if (player->gameMode->isCreative()) { + bool drop = packet->slotNum < 0; + std::shared_ptr item = packet->item; - if(item != NULL && item->id == Item::map_Id) - { - int mapScale = 3; + if (item != NULL && item->id == Item::map_Id) { + int mapScale = 3; #ifdef _LARGE_WORLDS - int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); - int centreXC = (int) (Math::round(player->x / scale) * scale); - int centreZC = (int) (Math::round(player->z / scale) * scale); + int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); + int centreXC = (int)(Math::round(player->x / scale) * scale); + int centreZC = (int)(Math::round(player->z / scale) * scale); #else - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - int centreXC = 0; - int centreZC = 0; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the + // world, since we can fit the whole world in our map + int centreXC = 0; + int centreZC = 0; #endif - item->setAuxValue( player->level->getAuxValueForMap(player->getXuid(), player->dimension, centreXC, centreZC, mapScale) ); + item->setAuxValue(player->level->getAuxValueForMap( + player->getXuid(), player->dimension, centreXC, centreZC, + mapScale)); - std::shared_ptr data = MapItem::getSavedData(item->getAuxValue(), player->level); - // 4J Stu - We only have one map per player per dimension, so don't reset the one that they have - // when a new one is created - wchar_t buf[64]; - swprintf(buf,64,L"map_%d", item->getAuxValue()); - std::wstring id = std::wstring(buf); - if( data == NULL ) - { - data = std::shared_ptr( new MapItemSavedData(id) ); - } - player->level->setSavedData(id, (std::shared_ptr ) data); + std::shared_ptr data = + MapItem::getSavedData(item->getAuxValue(), player->level); + // 4J Stu - We only have one map per player per dimension, so don't + // reset the one that they have when a new one is created + wchar_t buf[64]; + swprintf(buf, 64, L"map_%d", item->getAuxValue()); + std::wstring id = std::wstring(buf); + if (data == NULL) { + data = + std::shared_ptr(new MapItemSavedData(id)); + } + player->level->setSavedData(id, (std::shared_ptr)data); - data->scale = mapScale; - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - data->x = centreXC; - data->z = centreZC; - data->dimension = (std::uint8_t) player->level->dimension->id; - data->setDirty(); - } + data->scale = mapScale; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the + // world, since we can fit the whole world in our map + data->x = centreXC; + data->z = centreZC; + data->dimension = (std::uint8_t)player->level->dimension->id; + data->setDirty(); + } - bool validSlot = (packet->slotNum >= InventoryMenu::CRAFT_SLOT_START && packet->slotNum < (InventoryMenu::USE_ROW_SLOT_START + Inventory::getSelectionSize())); - bool validItem = item == NULL || (item->id < Item::items.length && item->id >= 0 && Item::items[item->id] != NULL); - bool validData = item == NULL || (item->getAuxValue() >= 0 && item->count > 0 && item->count <= 64); + bool validSlot = (packet->slotNum >= InventoryMenu::CRAFT_SLOT_START && + packet->slotNum < (InventoryMenu::USE_ROW_SLOT_START + + Inventory::getSelectionSize())); + bool validItem = + item == NULL || (item->id < Item::items.length && item->id >= 0 && + Item::items[item->id] != NULL); + bool validData = item == NULL || (item->getAuxValue() >= 0 && + item->count > 0 && item->count <= 64); - if (validSlot && validItem && validData) - { - if (item == NULL) - { - player->inventoryMenu->setItem(packet->slotNum, nullptr); - } - else - { - player->inventoryMenu->setItem(packet->slotNum, item ); - } - player->inventoryMenu->setSynched(player, true); - // player.slotChanged(player.inventoryMenu, packet.slotNum, player.inventoryMenu.getSlot(packet.slotNum).getItem()); - } - else if (drop && validItem && validData) - { - if (dropSpamTickCount < SharedConstants::TICKS_PER_SECOND * 10) - { - dropSpamTickCount += SharedConstants::TICKS_PER_SECOND; - // drop item - std::shared_ptr dropped = player->drop(item); - if (dropped != NULL) - { - dropped->setShortLifeTime(); - } - } - } + if (validSlot && validItem && validData) { + if (item == NULL) { + player->inventoryMenu->setItem(packet->slotNum, nullptr); + } else { + player->inventoryMenu->setItem(packet->slotNum, item); + } + player->inventoryMenu->setSynched(player, true); + // player.slotChanged(player.inventoryMenu, + // packet.slotNum, + // player.inventoryMenu.getSlot(packet.slotNum).getItem()); + } else if (drop && validItem && validData) { + if (dropSpamTickCount < SharedConstants::TICKS_PER_SECOND * 10) { + dropSpamTickCount += SharedConstants::TICKS_PER_SECOND; + // drop item + std::shared_ptr dropped = player->drop(item); + if (dropped != NULL) { + dropped->setShortLifeTime(); + } + } + } - if( item != NULL && item->id == Item::map_Id ) - { - // 4J Stu - Maps need to have their aux value update, so the client should always be assumed to be wrong - // This is how the Java works, as the client also incorrectly predicts the auxvalue of the mapItem - std::vector > items; - for (unsigned int i = 0; i < player->inventoryMenu->slots->size(); i++) - { - items.push_back(player->inventoryMenu->slots->at(i)->getItem()); - } - player->refreshContainer(player->inventoryMenu, &items); - } - } + if (item != NULL && item->id == Item::map_Id) { + // 4J Stu - Maps need to have their aux value update, so the client + // should always be assumed to be wrong This is how the Java works, + // as the client also incorrectly predicts the auxvalue of the + // mapItem + std::vector > items; + for (unsigned int i = 0; i < player->inventoryMenu->slots->size(); + i++) { + items.push_back(player->inventoryMenu->slots->at(i)->getItem()); + } + player->refreshContainer(player->inventoryMenu, &items); + } + } } -void PlayerConnection::handleContainerAck(std::shared_ptr packet) -{ - AUTO_VAR(it, expectedAcks.find(player->containerMenu->containerId)); +void PlayerConnection::handleContainerAck( + std::shared_ptr packet) { + AUTO_VAR(it, expectedAcks.find(player->containerMenu->containerId)); - if (it != expectedAcks.end() && packet->uid == it->second && player->containerMenu->containerId == packet->containerId && !player->containerMenu->isSynched(player)) - { - player->containerMenu->setSynched(player, true); - } + if (it != expectedAcks.end() && packet->uid == it->second && + player->containerMenu->containerId == packet->containerId && + !player->containerMenu->isSynched(player)) { + player->containerMenu->setSynched(player, true); + } } -void PlayerConnection::handleSignUpdate(std::shared_ptr packet) -{ - app.DebugPrintf("PlayerConnection::handleSignUpdate\n"); +void PlayerConnection::handleSignUpdate( + std::shared_ptr packet) { + app.DebugPrintf("PlayerConnection::handleSignUpdate\n"); - ServerLevel *level = server->getLevel(player->dimension); - if (level->hasChunkAt(packet->x, packet->y, packet->z)) - { - std::shared_ptr te = level->getTileEntity(packet->x, packet->y, packet->z); + ServerLevel* level = server->getLevel(player->dimension); + if (level->hasChunkAt(packet->x, packet->y, packet->z)) { + std::shared_ptr te = + level->getTileEntity(packet->x, packet->y, packet->z); - if (std::dynamic_pointer_cast(te) != NULL) - { - std::shared_ptr ste = std::dynamic_pointer_cast(te); - if (!ste->isEditable()) - { - server->warn(L"Player " + player->name + L" just tried to change non-editable sign"); - return; - } - } - - // 4J-JEV: Changed to allow characters to display as a []. - if (std::dynamic_pointer_cast(te) != NULL) - { - int x = packet->x; - int y = packet->y; - int z = packet->z; - std::shared_ptr ste = std::dynamic_pointer_cast(te); - for (int i = 0; i < 4; i++) - { - std::wstring lineText = packet->lines[i].substr(0,15); - ste->SetMessage( i, lineText ); - } - ste->SetVerified(false); - ste->setChanged(); - level->sendTileUpdated(x, y, z); - } - } + if (std::dynamic_pointer_cast(te) != NULL) { + std::shared_ptr ste = + std::dynamic_pointer_cast(te); + if (!ste->isEditable()) { + server->warn(L"Player " + player->name + + L" just tried to change non-editable sign"); + return; + } + } + // 4J-JEV: Changed to allow characters to display as a []. + if (std::dynamic_pointer_cast(te) != NULL) { + int x = packet->x; + int y = packet->y; + int z = packet->z; + std::shared_ptr ste = + std::dynamic_pointer_cast(te); + for (int i = 0; i < 4; i++) { + std::wstring lineText = packet->lines[i].substr(0, 15); + ste->SetMessage(i, lineText); + } + ste->SetVerified(false); + ste->setChanged(); + level->sendTileUpdated(x, y, z); + } + } } -void PlayerConnection::handleKeepAlive(std::shared_ptr packet) -{ - if (packet->id == lastKeepAliveId) - { - int time = (int) (System::nanoTime() / 1000000 - lastKeepAliveTime); - player->latency = (player->latency * 3 + time) / 4; - } +void PlayerConnection::handleKeepAlive( + std::shared_ptr packet) { + if (packet->id == lastKeepAliveId) { + int time = (int)(System::nanoTime() / 1000000 - lastKeepAliveTime); + player->latency = (player->latency * 3 + time) / 4; + } } -void PlayerConnection::handlePlayerInfo(std::shared_ptr packet) -{ - // Need to check that this player has permission to change each individual setting? +void PlayerConnection::handlePlayerInfo( + std::shared_ptr packet) { + // Need to check that this player has permission to change each individual + // setting? - INetworkPlayer *networkPlayer = getNetworkPlayer(); - if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator() ) - { - std::shared_ptr serverPlayer; - // Find the player being edited - for(AUTO_VAR(it, server->getPlayers()->players.begin()); it != server->getPlayers()->players.end(); ++it) - { - std::shared_ptr checkingPlayer = *it; - if(checkingPlayer->connection->getNetworkPlayer() != NULL && checkingPlayer->connection->getNetworkPlayer()->GetSmallId() == packet->m_networkSmallId) - { - serverPlayer = checkingPlayer; - break; - } - } + INetworkPlayer* networkPlayer = getNetworkPlayer(); + if ((networkPlayer != NULL && networkPlayer->IsHost()) || + player->isModerator()) { + std::shared_ptr serverPlayer; + // Find the player being edited + for (AUTO_VAR(it, server->getPlayers()->players.begin()); + it != server->getPlayers()->players.end(); ++it) { + std::shared_ptr checkingPlayer = *it; + if (checkingPlayer->connection->getNetworkPlayer() != NULL && + checkingPlayer->connection->getNetworkPlayer()->GetSmallId() == + packet->m_networkSmallId) { + serverPlayer = checkingPlayer; + break; + } + } - if(serverPlayer != NULL) - { - unsigned int origPrivs = serverPlayer->getAllPlayerGamePrivileges(); + if (serverPlayer != NULL) { + unsigned int origPrivs = serverPlayer->getAllPlayerGamePrivileges(); - bool trustPlayers = app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; - bool cheats = app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; - if(serverPlayer == player) - { - GameType *gameType = Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CreativeMode) ? GameType::CREATIVE : GameType::SURVIVAL; - gameType = LevelSettings::validateGameType(gameType->getId()); - if (serverPlayer->gameMode->getGameModeForPlayer() != gameType) - { + bool trustPlayers = + app.GetGameHostOption(eGameHostOption_TrustPlayers) != 0; + bool cheats = + app.GetGameHostOption(eGameHostOption_CheatsEnabled) != 0; + if (serverPlayer == player) { + GameType* gameType = + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CreativeMode) + ? GameType::CREATIVE + : GameType::SURVIVAL; + gameType = LevelSettings::validateGameType(gameType->getId()); + if (serverPlayer->gameMode->getGameModeForPlayer() != + gameType) { #ifndef _CONTENT_PACKAGE - wprintf(L"Setting %ls to game mode %d\n", serverPlayer->name.c_str(), gameType); + wprintf(L"Setting %ls to game mode %d\n", + serverPlayer->name.c_str(), gameType); #endif - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CreativeMode,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CreativeMode) ); - serverPlayer->gameMode->setGameModeForPlayer(gameType); - serverPlayer->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, gameType->getId()) )); - } - else - { + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CreativeMode, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CreativeMode)); + serverPlayer->gameMode->setGameModeForPlayer(gameType); + serverPlayer->connection->send( + std::shared_ptr(new GameEventPacket( + GameEventPacket::CHANGE_GAME_MODE, + gameType->getId()))); + } else { #ifndef _CONTENT_PACKAGE - wprintf(L"%ls already has game mode %d\n", serverPlayer->name.c_str(), gameType); + wprintf(L"%ls already has game mode %d\n", + serverPlayer->name.c_str(), gameType); #endif - } - if(cheats) - { - // Editing self - bool canBeInvisible = Player::getPlayerGamePrivilege(origPrivs, Player::ePlayerGamePrivilege_CanToggleInvisible) != 0; - if(canBeInvisible)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invisible,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_Invisible) ); - if(canBeInvisible)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_Invulnerable,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_Invulnerable) ); + } + if (cheats) { + // Editing self + bool canBeInvisible = + Player::getPlayerGamePrivilege( + origPrivs, + Player::ePlayerGamePrivilege_CanToggleInvisible) != + 0; + if (canBeInvisible) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_Invisible, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_Invisible)); + if (canBeInvisible) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_Invulnerable, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_Invulnerable)); - bool inCreativeMode = Player::getPlayerGamePrivilege(origPrivs,Player::ePlayerGamePrivilege_CreativeMode) != 0; - if(!inCreativeMode) - { - bool canFly = Player::getPlayerGamePrivilege(origPrivs,Player::ePlayerGamePrivilege_CanToggleFly); - bool canChangeHunger = Player::getPlayerGamePrivilege(origPrivs,Player::ePlayerGamePrivilege_CanToggleClassicHunger); + bool inCreativeMode = + Player::getPlayerGamePrivilege( + origPrivs, + Player::ePlayerGamePrivilege_CreativeMode) != 0; + if (!inCreativeMode) { + bool canFly = Player::getPlayerGamePrivilege( + origPrivs, + Player::ePlayerGamePrivilege_CanToggleFly); + bool canChangeHunger = Player::getPlayerGamePrivilege( + origPrivs, + Player:: + ePlayerGamePrivilege_CanToggleClassicHunger); - if(canFly)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanFly,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanFly) ); - if(canChangeHunger)serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_ClassicHunger,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_ClassicHunger) ); - } - } - } - else - { - // Editing someone else - if(!trustPlayers && !serverPlayer->connection->getNetworkPlayer()->IsHost()) - { - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotMine,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotMine) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotBuild,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotBuild) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotAttackPlayers,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotAttackPlayers) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotAttackAnimals,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotAttackAnimals) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanUseContainers,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanUseContainers) ); - } + if (canFly) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanFly, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanFly)); + if (canChangeHunger) + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_ClassicHunger, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_ClassicHunger)); + } + } + } else { + // Editing someone else + if (!trustPlayers && + !serverPlayer->connection->getNetworkPlayer()->IsHost()) { + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotMine, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotMine)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotBuild, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotBuild)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotAttackPlayers, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotAttackPlayers)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CannotAttackAnimals, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CannotAttackAnimals)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanUseDoorsAndSwitches, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_CanUseDoorsAndSwitches)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanUseContainers, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanUseContainers)); + } - if(networkPlayer->IsHost()) - { - if(cheats) - { - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanToggleInvisible,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanToggleInvisible) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanToggleFly,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanToggleFly) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanToggleClassicHunger,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanToggleClassicHunger) ); - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CanTeleport,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CanTeleport) ); - } - serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_Op,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_Op) ); - } - } + if (networkPlayer->IsHost()) { + if (cheats) { + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanToggleInvisible, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_CanToggleInvisible)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanToggleFly, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanToggleFly)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanToggleClassicHunger, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player:: + ePlayerGamePrivilege_CanToggleClassicHunger)); + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CanTeleport, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_CanTeleport)); + } + serverPlayer->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_Op, + Player::getPlayerGamePrivilege( + packet->m_playerPrivileges, + Player::ePlayerGamePrivilege_Op)); + } + } - server->getPlayers()->broadcastAll( std::shared_ptr( new PlayerInfoPacket( serverPlayer ) ) ); - } - } + server->getPlayers()->broadcastAll( + std::shared_ptr( + new PlayerInfoPacket(serverPlayer))); + } + } } -bool PlayerConnection::isServerPacketListener() -{ - return true; +bool PlayerConnection::isServerPacketListener() { return true; } + +void PlayerConnection::handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket) { + player->abilities.flying = + playerAbilitiesPacket->isFlying() && player->abilities.mayfly; } -void PlayerConnection::handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket) -{ - player->abilities.flying = playerAbilitiesPacket->isFlying() && player->abilities.mayfly; -} - -//void handleChatAutoComplete(ChatAutoCompletePacket packet) { +// void handleChatAutoComplete(ChatAutoCompletePacket packet) { // StringBuilder result = new StringBuilder(); -// for (String candidate : server.getAutoCompletions(player, packet.getMessage())) { -// if (result.length() > 0) result.append("\0"); +// for (String candidate : server.getAutoCompletions(player, +//packet.getMessage())) { if (result.length() > 0) result.append("\0"); // result.append(candidate); // } @@ -1427,13 +1529,13 @@ void PlayerConnection::handlePlayerAbilities(std::shared_ptr packet) +// void handleClientInformation(std::shared_ptr packet) //{ // player->updateOptions(packet); -//} +// } -void PlayerConnection::handleCustomPayload(std::shared_ptr customPayloadPacket) -{ +void PlayerConnection::handleCustomPayload( + std::shared_ptr customPayloadPacket) { #if 0 if (CustomPayloadPacket.CUSTOM_BOOK_PACKET.equals(customPayloadPacket.identifier)) { @@ -1473,245 +1575,267 @@ void PlayerConnection::handleCustomPayload(std::shared_ptr } else #endif - if (CustomPayloadPacket::TRADER_SELECTION_PACKET.compare(customPayloadPacket->identifier) == 0) - { - ByteArrayInputStream bais(customPayloadPacket->data); - DataInputStream input(&bais); - int selection = input.readInt(); + if (CustomPayloadPacket::TRADER_SELECTION_PACKET.compare( + customPayloadPacket->identifier) == 0) { + ByteArrayInputStream bais(customPayloadPacket->data); + DataInputStream input(&bais); + int selection = input.readInt(); - AbstractContainerMenu *menu = player->containerMenu; - if (dynamic_cast(menu)) - { - ((MerchantMenu *) menu)->setSelectionHint(selection); - } - } - else if (CustomPayloadPacket::SET_ITEM_NAME_PACKET.compare(customPayloadPacket->identifier) == 0) - { - RepairMenu *menu = dynamic_cast( player->containerMenu); - if (menu) - { - if (customPayloadPacket->data.data == NULL || customPayloadPacket->data.length < 1) - { - menu->setItemName(L""); - } - else - { - ByteArrayInputStream bais(customPayloadPacket->data); - DataInputStream dis(&bais); - std::wstring name = dis.readUTF(); - if (name.length() <= 30) - { - menu->setItemName(name); - } - } - } - } + AbstractContainerMenu* menu = player->containerMenu; + if (dynamic_cast(menu)) { + ((MerchantMenu*)menu)->setSelectionHint(selection); + } + } else if (CustomPayloadPacket::SET_ITEM_NAME_PACKET.compare( + customPayloadPacket->identifier) == 0) { + RepairMenu* menu = dynamic_cast(player->containerMenu); + if (menu) { + if (customPayloadPacket->data.data == NULL || + customPayloadPacket->data.length < 1) { + menu->setItemName(L""); + } else { + ByteArrayInputStream bais(customPayloadPacket->data); + DataInputStream dis(&bais); + std::wstring name = dis.readUTF(); + if (name.length() <= 30) { + menu->setItemName(name); + } + } + } + } } // 4J Added -void PlayerConnection::handleDebugOptions(std::shared_ptr packet) -{ - //Player player = std::dynamic_pointer_cast( player->shared_from_this() ); - player->SetDebugOptions(packet->m_uiVal); +void PlayerConnection::handleDebugOptions( + std::shared_ptr packet) { + // Player player = std::dynamic_pointer_cast( + // player->shared_from_this() ); + player->SetDebugOptions(packet->m_uiVal); } -void PlayerConnection::handleCraftItem(std::shared_ptr packet) -{ - int iRecipe = packet->recipe; +void PlayerConnection::handleCraftItem( + std::shared_ptr packet) { + int iRecipe = packet->recipe; - if(iRecipe == -1) - return; + if (iRecipe == -1) return; - Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); - std::shared_ptr pTempItemInst=pRecipeIngredientsRequired[iRecipe].pRecipy->assemble(nullptr); + Recipy::INGREDIENTS_REQUIRED* pRecipeIngredientsRequired = + Recipes::getInstance()->getRecipeIngredientsArray(); + std::shared_ptr pTempItemInst = + pRecipeIngredientsRequired[iRecipe].pRecipy->assemble(nullptr); - if(app.DebugSettingsOn() && (player->GetDebugOptions()&(1L<onCraftedBy(player->level, std::dynamic_pointer_cast( player->shared_from_this() ), pTempItemInst->count ); - if(player->inventory->add(pTempItemInst)==false ) - { - // no room in inventory, so throw it down - player->drop(pTempItemInst); - } - } - else - { + if (app.DebugSettingsOn() && + (player->GetDebugOptions() & (1L << eDebugSetting_CraftAnything))) { + pTempItemInst->onCraftedBy( + player->level, + std::dynamic_pointer_cast(player->shared_from_this()), + pTempItemInst->count); + if (player->inventory->add(pTempItemInst) == false) { + // no room in inventory, so throw it down + player->drop(pTempItemInst); + } + } else { + // TODO 4J Stu - Assume at the moment that the client can work this out + // for us... + // if(pRecipeIngredientsRequired[iRecipe].bCanMake) + //{ + pTempItemInst->onCraftedBy( + player->level, + std::dynamic_pointer_cast(player->shared_from_this()), + pTempItemInst->count); - - // TODO 4J Stu - Assume at the moment that the client can work this out for us... - //if(pRecipeIngredientsRequired[iRecipe].bCanMake) - //{ - pTempItemInst->onCraftedBy(player->level, std::dynamic_pointer_cast( player->shared_from_this() ), pTempItemInst->count ); + // and remove those resources from your inventory + for (int i = 0; i < pRecipeIngredientsRequired[iRecipe].iIngC; i++) { + for (int j = 0; j < pRecipeIngredientsRequired[iRecipe].iIngValA[i]; + j++) { + std::shared_ptr ingItemInst = nullptr; + // do we need to remove a specific aux value? + if (pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i] != + Recipes::ANY_AUX_VALUE) { + ingItemInst = player->inventory->getResourceItem( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i], + pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]); + player->inventory->removeResource( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i], + pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]); + } else { + ingItemInst = player->inventory->getResourceItem( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i]); + player->inventory->removeResource( + pRecipeIngredientsRequired[iRecipe].iIngIDA[i]); + } - // and remove those resources from your inventory - for(int i=0;i ingItemInst = nullptr; - // do we need to remove a specific aux value? - if(pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]!=Recipes::ANY_AUX_VALUE) - { - ingItemInst = player->inventory->getResourceItem( pRecipeIngredientsRequired[iRecipe].iIngIDA[i],pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i] ); - player->inventory->removeResource(pRecipeIngredientsRequired[iRecipe].iIngIDA[i],pRecipeIngredientsRequired[iRecipe].iIngAuxValA[i]); - } - else - { - ingItemInst = player->inventory->getResourceItem( pRecipeIngredientsRequired[iRecipe].iIngIDA[i] ); - player->inventory->removeResource(pRecipeIngredientsRequired[iRecipe].iIngIDA[i]); - } + // 4J Stu - Fix for #13097 - Bug: Milk Buckets are removed when + // crafting Cake + if (ingItemInst != NULL) { + if (ingItemInst->getItem()->hasCraftingRemainingItem()) { + // replace item with remaining result + player->inventory->add( + std::shared_ptr(new ItemInstance( + ingItemInst->getItem() + ->getCraftingRemainingItem()))); + } + } + } + } - // 4J Stu - Fix for #13097 - Bug: Milk Buckets are removed when crafting Cake - if (ingItemInst != NULL) - { - if (ingItemInst->getItem()->hasCraftingRemainingItem()) - { - // replace item with remaining result - player->inventory->add( std::shared_ptr( new ItemInstance(ingItemInst->getItem()->getCraftingRemainingItem()) ) ); - } + // 4J Stu - Fix for #13119 - We should add the item after we remove the + // ingredients + if (player->inventory->add(pTempItemInst) == false) { + // no room in inventory, so throw it down + player->drop(pTempItemInst); + } - } - } - } - - // 4J Stu - Fix for #13119 - We should add the item after we remove the ingredients - if(player->inventory->add(pTempItemInst)==false ) - { - // no room in inventory, so throw it down - player->drop(pTempItemInst); - } + if (pTempItemInst->id == Item::map_Id) { + // 4J Stu - Maps need to have their aux value update, so the client + // should always be assumed to be wrong This is how the Java works, + // as the client also incorrectly predicts the auxvalue of the + // mapItem + std::vector > items; + for (unsigned int i = 0; i < player->containerMenu->slots->size(); + i++) { + items.push_back(player->containerMenu->slots->at(i)->getItem()); + } + player->refreshContainer(player->containerMenu, &items); + } else { + // Do same hack as PlayerConnection::handleContainerClick does - do + // our broadcast of changes just now, but with a hack so it just + // thinks it has sent things but hasn't really. This will stop the + // client getting a message back confirming the current inventory + // items, which might then arrive after another local change has + // been made on the client and be stale. + player->ignoreSlotUpdateHack = true; + player->containerMenu->broadcastChanges(); + player->broadcastCarriedItem(); + player->ignoreSlotUpdateHack = false; + } + } - if( pTempItemInst->id == Item::map_Id ) - { - // 4J Stu - Maps need to have their aux value update, so the client should always be assumed to be wrong - // This is how the Java works, as the client also incorrectly predicts the auxvalue of the mapItem - std::vector > items; - for (unsigned int i = 0; i < player->containerMenu->slots->size(); i++) - { - items.push_back(player->containerMenu->slots->at(i)->getItem()); - } - player->refreshContainer(player->containerMenu, &items); - } - else - { - // Do same hack as PlayerConnection::handleContainerClick does - do our broadcast of changes just now, but with a hack so it just thinks it has sent - // things but hasn't really. This will stop the client getting a message back confirming the current inventory items, which might then arrive - // after another local change has been made on the client and be stale. - player->ignoreSlotUpdateHack = true; - player->containerMenu->broadcastChanges(); - player->broadcastCarriedItem(); - player->ignoreSlotUpdateHack = false; - } - } - - // handle achievements - switch(pTempItemInst->id ) - { - case Tile::workBench_Id: player->awardStat(GenericStats::buildWorkbench(), GenericStats::param_buildWorkbench()); break; - case Item::pickAxe_wood_Id: player->awardStat(GenericStats::buildPickaxe(), GenericStats::param_buildPickaxe()); break; - case Tile::furnace_Id: player->awardStat(GenericStats::buildFurnace(), GenericStats::param_buildFurnace()); break; - case Item::hoe_wood_Id: player->awardStat(GenericStats::buildHoe(), GenericStats::param_buildHoe()); break; - case Item::bread_Id: player->awardStat(GenericStats::makeBread(), GenericStats::param_makeBread()); break; - case Item::cake_Id: player->awardStat(GenericStats::bakeCake(), GenericStats::param_bakeCake()); break; - case Item::pickAxe_stone_Id: player->awardStat(GenericStats::buildBetterPickaxe(), GenericStats::param_buildBetterPickaxe()); break; - case Item::sword_wood_Id: player->awardStat(GenericStats::buildSword(), GenericStats::param_buildSword()); break; - case Tile::dispenser_Id: player->awardStat(GenericStats::dispenseWithThis(), GenericStats::param_dispenseWithThis()); break; - case Tile::enchantTable_Id: player->awardStat(GenericStats::enchantments(), GenericStats::param_enchantments()); break; - case Tile::bookshelf_Id: player->awardStat(GenericStats::bookcase(), GenericStats::param_bookcase()); break; - } - //} - // ELSE The server thinks the client was wrong... + // handle achievements + switch (pTempItemInst->id) { + case Tile::workBench_Id: + player->awardStat(GenericStats::buildWorkbench(), + GenericStats::param_buildWorkbench()); + break; + case Item::pickAxe_wood_Id: + player->awardStat(GenericStats::buildPickaxe(), + GenericStats::param_buildPickaxe()); + break; + case Tile::furnace_Id: + player->awardStat(GenericStats::buildFurnace(), + GenericStats::param_buildFurnace()); + break; + case Item::hoe_wood_Id: + player->awardStat(GenericStats::buildHoe(), + GenericStats::param_buildHoe()); + break; + case Item::bread_Id: + player->awardStat(GenericStats::makeBread(), + GenericStats::param_makeBread()); + break; + case Item::cake_Id: + player->awardStat(GenericStats::bakeCake(), + GenericStats::param_bakeCake()); + break; + case Item::pickAxe_stone_Id: + player->awardStat(GenericStats::buildBetterPickaxe(), + GenericStats::param_buildBetterPickaxe()); + break; + case Item::sword_wood_Id: + player->awardStat(GenericStats::buildSword(), + GenericStats::param_buildSword()); + break; + case Tile::dispenser_Id: + player->awardStat(GenericStats::dispenseWithThis(), + GenericStats::param_dispenseWithThis()); + break; + case Tile::enchantTable_Id: + player->awardStat(GenericStats::enchantments(), + GenericStats::param_enchantments()); + break; + case Tile::bookshelf_Id: + player->awardStat(GenericStats::bookcase(), + GenericStats::param_bookcase()); + break; + } + //} + // ELSE The server thinks the client was wrong... } +void PlayerConnection::handleTradeItem( + std::shared_ptr packet) { + if (player->containerMenu->containerId == packet->containerId) { + MerchantMenu* menu = (MerchantMenu*)player->containerMenu; -void PlayerConnection::handleTradeItem(std::shared_ptr packet) -{ - if (player->containerMenu->containerId == packet->containerId) - { - MerchantMenu *menu = (MerchantMenu *)player->containerMenu; + MerchantRecipeList* offers = menu->getMerchant()->getOffers(player); - MerchantRecipeList *offers = menu->getMerchant()->getOffers(player); + if (offers) { + int selectedShopItem = packet->offer; + if (selectedShopItem < offers->size()) { + MerchantRecipe* activeRecipe = offers->at(selectedShopItem); + if (!activeRecipe->isDeprecated()) { + // Do we have the ingredients? + std::shared_ptr buyAItem = + activeRecipe->getBuyAItem(); + std::shared_ptr buyBItem = + activeRecipe->getBuyBItem(); - if(offers) - { - int selectedShopItem = packet->offer; - if( selectedShopItem < offers->size() ) - { - MerchantRecipe *activeRecipe = offers->at(selectedShopItem); - if(!activeRecipe->isDeprecated()) - { - // Do we have the ingredients? - std::shared_ptr buyAItem = activeRecipe->getBuyAItem(); - std::shared_ptr buyBItem = activeRecipe->getBuyBItem(); + int buyAMatches = player->inventory->countMatches(buyAItem); + int buyBMatches = player->inventory->countMatches(buyBItem); + if ((buyAItem != NULL && buyAMatches >= buyAItem->count) && + (buyBItem == NULL || buyBMatches >= buyBItem->count)) { + menu->getMerchant()->notifyTrade(activeRecipe); - int buyAMatches = player->inventory->countMatches(buyAItem); - int buyBMatches = player->inventory->countMatches(buyBItem); - if( (buyAItem != NULL && buyAMatches >= buyAItem->count) && (buyBItem == NULL || buyBMatches >= buyBItem->count) ) - { - menu->getMerchant()->notifyTrade(activeRecipe); + // Remove the items we are purchasing with + player->inventory->removeResources(buyAItem); + player->inventory->removeResources(buyBItem); - // Remove the items we are purchasing with - player->inventory->removeResources(buyAItem); - player->inventory->removeResources(buyBItem); + // Add the item we have purchased + std::shared_ptr result = + activeRecipe->getSellItem()->copy(); - // Add the item we have purchased - std::shared_ptr result = activeRecipe->getSellItem()->copy(); - - // 4J JEV - Award itemsBought stat. - player->awardStat( - GenericStats::itemsBought(result->getItem()->id), - GenericStats::param_itemsBought( - result->getItem()->id, - result->getAuxValue(), - result->GetCount() - ) - ); - - if (!player->inventory->add(result)) - { - player->drop(result); - } - } - } - } - } - } + // 4J JEV - Award itemsBought stat. + player->awardStat( + GenericStats::itemsBought(result->getItem()->id), + GenericStats::param_itemsBought( + result->getItem()->id, result->getAuxValue(), + result->GetCount())); + + if (!player->inventory->add(result)) { + player->drop(result); + } + } + } + } + } + } } -INetworkPlayer *PlayerConnection::getNetworkPlayer() -{ - if( connection != NULL && connection->getSocket() != NULL) return connection->getSocket()->getPlayer(); - else return NULL; +INetworkPlayer* PlayerConnection::getNetworkPlayer() { + if (connection != NULL && connection->getSocket() != NULL) + return connection->getSocket()->getPlayer(); + else + return NULL; } -bool PlayerConnection::isLocal() -{ - if( connection->getSocket() == NULL ) - { - return false; - } - else - { - bool isLocal = connection->getSocket()->isLocal(); - return connection->getSocket()->isLocal(); - } +bool PlayerConnection::isLocal() { + if (connection->getSocket() == NULL) { + return false; + } else { + bool isLocal = connection->getSocket()->isLocal(); + return connection->getSocket()->isLocal(); + } } -bool PlayerConnection::isGuest() -{ - if( connection->getSocket() == NULL ) - { - return false; - } - else - { - INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); - bool isGuest = false; - if(networkPlayer != NULL) - { - isGuest = networkPlayer->IsGuest() == TRUE; - } - return isGuest; - } +bool PlayerConnection::isGuest() { + if (connection->getSocket() == NULL) { + return false; + } else { + INetworkPlayer* networkPlayer = connection->getSocket()->getPlayer(); + bool isGuest = false; + if (networkPlayer != NULL) { + isGuest = networkPlayer->IsGuest() == TRUE; + } + return isGuest; + } } diff --git a/Minecraft.Client/Network/PlayerConnection.h b/Minecraft.Client/Network/PlayerConnection.h index ae8ec4881..16c0e90dc 100644 --- a/Minecraft.Client/Network/PlayerConnection.h +++ b/Minecraft.Client/Network/PlayerConnection.h @@ -8,132 +8,152 @@ class Connection; class ServerPlayer; class INetworkPlayer; - - -class PlayerConnection : public PacketListener, public ConsoleInputSource -{ -// public static Logger logger = Logger.getLogger("Minecraft"); +class PlayerConnection : public PacketListener, public ConsoleInputSource { + // public static Logger logger = Logger.getLogger("Minecraft"); public: - Connection *connection; + Connection* connection; bool done; - CRITICAL_SECTION done_cs; + CRITICAL_SECTION done_cs; - // 4J Stu - Added this so that we can manage UGC privileges - PlayerUID m_offlineXUID, m_onlineXUID; - bool m_friendsOnlyUGC; + // 4J Stu - Added this so that we can manage UGC privileges + PlayerUID m_offlineXUID, m_onlineXUID; + bool m_friendsOnlyUGC; private: - MinecraftServer *server; + MinecraftServer* server; std::shared_ptr player; int tickCount; int aboveGroundTickCount; bool didTick; - int lastKeepAliveId; - __int64 lastKeepAliveTime; - static Random random; - __int64 lastKeepAliveTick; - int chatSpamTickCount; - int dropSpamTickCount; + int lastKeepAliveId; + __int64 lastKeepAliveTime; + static Random random; + __int64 lastKeepAliveTick; + int chatSpamTickCount; + int dropSpamTickCount; - bool m_bHasClientTickedOnce; + bool m_bHasClientTickedOnce; public: - PlayerConnection(MinecraftServer *server, Connection *connection, std::shared_ptr player); - ~PlayerConnection(); + PlayerConnection(MinecraftServer* server, Connection* connection, + std::shared_ptr player); + ~PlayerConnection(); void tick(); void disconnect(DisconnectPacket::eDisconnectReason reason); private: - double xLastOk, yLastOk, zLastOk; + double xLastOk, yLastOk, zLastOk; bool synched; public: - virtual void handlePlayerInput(std::shared_ptr packet); + virtual void handlePlayerInput(std::shared_ptr packet); virtual void handleMovePlayer(std::shared_ptr packet); - void teleport(double x, double y, double z, float yRot, float xRot, bool sendPacket = true); // 4J Added sendPacket param + void teleport(double x, double y, double z, float yRot, float xRot, + bool sendPacket = true); // 4J Added sendPacket param virtual void handlePlayerAction(std::shared_ptr packet); virtual void handleUseItem(std::shared_ptr packet); - virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); + virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, + void* reasonObjects); virtual void onUnhandledPacket(std::shared_ptr packet); void send(std::shared_ptr packet); - void queueSend(std::shared_ptr packet); // 4J Added - virtual void handleSetCarriedItem(std::shared_ptr packet); + void queueSend(std::shared_ptr packet); // 4J Added + virtual void handleSetCarriedItem( + std::shared_ptr packet); virtual void handleChat(std::shared_ptr packet); + private: - void handleCommand(const std::wstring& message); + void handleCommand(const std::wstring& message); + public: - virtual void handleAnimate(std::shared_ptr packet); - virtual void handlePlayerCommand(std::shared_ptr packet); + virtual void handleAnimate(std::shared_ptr packet); + virtual void handlePlayerCommand( + std::shared_ptr packet); virtual void handleDisconnect(std::shared_ptr packet); int countDelayedPackets(); virtual void info(const std::wstring& string); virtual void warn(const std::wstring& string); virtual std::wstring getConsoleName(); virtual void handleInteract(std::shared_ptr packet); - bool canHandleAsyncPackets(); - virtual void handleClientCommand(std::shared_ptr packet); + bool canHandleAsyncPackets(); + virtual void handleClientCommand( + std::shared_ptr packet); virtual void handleRespawn(std::shared_ptr packet); - virtual void handleContainerClose(std::shared_ptr packet); + virtual void handleContainerClose( + std::shared_ptr packet); private: - std::unordered_map expectedAcks; + std::unordered_map expectedAcks; public: - // 4J Stu - Handlers only valid in debug mode -#ifndef _CONTENT_PACKAGE - virtual void handleContainerSetSlot(std::shared_ptr packet); + // 4J Stu - Handlers only valid in debug mode +#ifndef _CONTENT_PACKAGE + virtual void handleContainerSetSlot( + std::shared_ptr packet); #endif - virtual void handleContainerClick(std::shared_ptr packet); - virtual void handleContainerButtonClick(std::shared_ptr packet); - virtual void handleSetCreativeModeSlot(std::shared_ptr packet); + virtual void handleContainerClick( + std::shared_ptr packet); + virtual void handleContainerButtonClick( + std::shared_ptr packet); + virtual void handleSetCreativeModeSlot( + std::shared_ptr packet); virtual void handleContainerAck(std::shared_ptr packet); virtual void handleSignUpdate(std::shared_ptr packet); - virtual void handleKeepAlive(std::shared_ptr packet); - virtual void handlePlayerInfo(std::shared_ptr packet); // 4J Added + virtual void handleKeepAlive(std::shared_ptr packet); + virtual void handlePlayerInfo( + std::shared_ptr packet); // 4J Added virtual bool isServerPacketListener(); - virtual void handlePlayerAbilities(std::shared_ptr playerAbilitiesPacket); - virtual void handleCustomPayload(std::shared_ptr customPayloadPacket); + virtual void handlePlayerAbilities( + std::shared_ptr playerAbilitiesPacket); + virtual void handleCustomPayload( + std::shared_ptr customPayloadPacket); - // 4J Added - virtual void handleCraftItem(std::shared_ptr packet); - virtual void handleTradeItem(std::shared_ptr packet); - virtual void handleDebugOptions(std::shared_ptr packet); - virtual void handleTexture(std::shared_ptr packet); - virtual void handleTextureAndGeometry(std::shared_ptr packet); - virtual void handleTextureChange(std::shared_ptr packet); - virtual void handleTextureAndGeometryChange(std::shared_ptr packet); - virtual void handleServerSettingsChanged(std::shared_ptr packet); - virtual void handleKickPlayer(std::shared_ptr packet); - virtual void handleGameCommand(std::shared_ptr packet); + // 4J Added + virtual void handleCraftItem(std::shared_ptr packet); + virtual void handleTradeItem(std::shared_ptr packet); + virtual void handleDebugOptions(std::shared_ptr packet); + virtual void handleTexture(std::shared_ptr packet); + virtual void handleTextureAndGeometry( + std::shared_ptr packet); + virtual void handleTextureChange( + std::shared_ptr packet); + virtual void handleTextureAndGeometryChange( + std::shared_ptr packet); + virtual void handleServerSettingsChanged( + std::shared_ptr packet); + virtual void handleKickPlayer(std::shared_ptr packet); + virtual void handleGameCommand(std::shared_ptr packet); - INetworkPlayer *getNetworkPlayer(); - bool isLocal(); - bool isGuest(); + INetworkPlayer* getNetworkPlayer(); + bool isLocal(); + bool isGuest(); - // 4J Added as we need to set this from outside sometimes - void setPlayer(std::shared_ptr player) { this->player = player; } - std::shared_ptr getPlayer() { return player; } + // 4J Added as we need to set this from outside sometimes + void setPlayer(std::shared_ptr player) { + this->player = player; + } + std::shared_ptr getPlayer() { return player; } - // 4J Added to signal a disconnect from another thread - void closeOnTick() { m_bCloseOnTick = true; } + // 4J Added to signal a disconnect from another thread + void closeOnTick() { m_bCloseOnTick = true; } - // 4J Added so that we can send on textures that get received after this connection requested them - void handleTextureReceived(const std::wstring &textureName); - void handleTextureAndGeometryReceived(const std::wstring &textureName); + // 4J Added so that we can send on textures that get received after this + // connection requested them + void handleTextureReceived(const std::wstring& textureName); + void handleTextureAndGeometryReceived(const std::wstring& textureName); - void setShowOnMaps(bool bVal); + void setShowOnMaps(bool bVal); - void setWasKicked() { m_bWasKicked = true; } - bool getWasKicked() { return m_bWasKicked; } + void setWasKicked() { m_bWasKicked = true; } + bool getWasKicked() { return m_bWasKicked; } - // 4J Added - bool hasClientTickedOnce() { return m_bHasClientTickedOnce; } + // 4J Added + bool hasClientTickedOnce() { return m_bHasClientTickedOnce; } private: - bool m_bCloseOnTick; - std::vector m_texturesRequested; + bool m_bCloseOnTick; + std::vector m_texturesRequested; - bool m_bWasKicked; + bool m_bWasKicked; }; diff --git a/Minecraft.Client/Network/PlayerInfo.h b/Minecraft.Client/Network/PlayerInfo.h index ba0f3413c..f31d59572 100644 --- a/Minecraft.Client/Network/PlayerInfo.h +++ b/Minecraft.Client/Network/PlayerInfo.h @@ -1,15 +1,12 @@ #pragma once - -class PlayerInfo -{ +class PlayerInfo { public: - std::wstring name; - int latency; + std::wstring name; + int latency; - PlayerInfo(const std::wstring &name) - { - this->name = name; - latency = 0; - } + PlayerInfo(const std::wstring& name) { + this->name = name; + latency = 0; + } }; \ No newline at end of file diff --git a/Minecraft.Client/Network/PlayerList.cpp b/Minecraft.Client/Network/PlayerList.cpp index 1f48183c8..9f32610d8 100644 --- a/Minecraft.Client/Network/PlayerList.cpp +++ b/Minecraft.Client/Network/PlayerList.cpp @@ -31,604 +31,692 @@ #include "../Platform/Common/Network/Sony/NetworkPlayerSony.h" #endif -// 4J - this class is fairly substantially altered as there didn't seem any point in porting code for banning, whitelisting, ops etc. +// 4J - this class is fairly substantially altered as there didn't seem any +// point in porting code for banning, whitelisting, ops etc. -PlayerList::PlayerList(MinecraftServer *server) -{ - playerIo = NULL; +PlayerList::PlayerList(MinecraftServer* server) { + playerIo = NULL; this->server = server; - sendAllPlayerInfoIn = 0; - overrideGameMode = NULL; - allowCheatsForAllPlayers = false; + sendAllPlayerInfoIn = 0; + overrideGameMode = NULL; + allowCheatsForAllPlayers = false; #ifdef __PSVITA__ - viewDistance = 3; + viewDistance = 3; #elif defined _LARGE_WORLDS - viewDistance = 16; + viewDistance = 16; #else - viewDistance = 10; + viewDistance = 10; #endif - //int viewDistance = server->settings->getInt(L"view-distance", 10); + // int viewDistance = server->settings->getInt(L"view-distance", 10); maxPlayers = server->settings->getInt(L"max-players", 20); doWhiteList = false; - - InitializeCriticalSection(&m_kickPlayersCS); - InitializeCriticalSection(&m_closePlayersCS); + + InitializeCriticalSection(&m_kickPlayersCS); + InitializeCriticalSection(&m_closePlayersCS); } -PlayerList::~PlayerList() -{ - for( AUTO_VAR(it, players.begin()); it < players.end(); it++ ) - { - (*it)->connection = nullptr; // Must remove reference to connection, or else there is a circular dependency - delete (*it)->gameMode; // Gamemode also needs deleted as it references back to this player - (*it)->gameMode = NULL; - } +PlayerList::~PlayerList() { + for (AUTO_VAR(it, players.begin()); it < players.end(); it++) { + (*it)->connection = nullptr; // Must remove reference to connection, or + // else there is a circular dependency + delete (*it)->gameMode; // Gamemode also needs deleted as it references + // back to this player + (*it)->gameMode = NULL; + } - DeleteCriticalSection(&m_kickPlayersCS); - DeleteCriticalSection(&m_closePlayersCS); + DeleteCriticalSection(&m_kickPlayersCS); + DeleteCriticalSection(&m_closePlayersCS); } -void PlayerList::placeNewPlayer(Connection *connection, std::shared_ptr player, std::shared_ptr packet) -{ - bool newPlayer = load(player); - player->setLevel(server->getLevel(player->dimension)); - player->gameMode->setLevel((ServerLevel *) player->level); +void PlayerList::placeNewPlayer(Connection* connection, + std::shared_ptr player, + std::shared_ptr packet) { + bool newPlayer = load(player); + player->setLevel(server->getLevel(player->dimension)); + player->gameMode->setLevel((ServerLevel*)player->level); - // Make sure these privileges are always turned off for the host player - INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); - if(networkPlayer != NULL && networkPlayer->IsHost()) - { - player->enableAllPlayerPrivileges(true); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_HOST,1); - } + // Make sure these privileges are always turned off for the host player + INetworkPlayer* networkPlayer = connection->getSocket()->getPlayer(); + if (networkPlayer != NULL && networkPlayer->IsHost()) { + player->enableAllPlayerPrivileges(true); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_HOST, 1); + } #if defined(__PS3__) || defined(__ORBIS__) - // PS3 networking library doesn't automatically assign PlayerUIDs to the network players for anything remote, so need to tell it what to set from the data in this packet now - if( !g_NetworkManager.IsLocalGame() ) - { - if( networkPlayer != NULL ) - { - ((NetworkPlayerSony *)networkPlayer)->SetUID( packet->m_onlineXuid ); - } - } + // PS3 networking library doesn't automatically assign PlayerUIDs to the + // network players for anything remote, so need to tell it what to set from + // the data in this packet now + if (!g_NetworkManager.IsLocalGame()) { + if (networkPlayer != NULL) { + ((NetworkPlayerSony*)networkPlayer)->SetUID(packet->m_onlineXuid); + } + } #endif - // 4J Stu - TU-1 hotfix - // Fix for #13150 - When a player loads/joins a game after saving/leaving in the nether, sometimes they are spawned on top of the nether and cannot mine down - validatePlayerSpawnPosition(player); + // 4J Stu - TU-1 hotfix + // Fix for #13150 - When a player loads/joins a game after saving/leaving in + // the nether, sometimes they are spawned on top of the nether and cannot + // mine down + validatePlayerSpawnPosition(player); -// logger.info(getName() + " logged in with entity id " + playerEntity.entityId + " at (" + playerEntity.x + ", " + playerEntity.y + ", " + playerEntity.z + ")"); + // logger.info(getName() + " logged in with entity id " + + // playerEntity.entityId + " at (" + playerEntity.x + ", " + + // playerEntity.y + ", " + playerEntity.z + ")"); - ServerLevel *level = server->getLevel(player->dimension); + ServerLevel* level = server->getLevel(player->dimension); - std::uint8_t playerIndex = 0; - { - bool usedIndexes[MINECRAFT_NET_MAX_PLAYERS]; - ZeroMemory( &usedIndexes, MINECRAFT_NET_MAX_PLAYERS * sizeof(bool) ); - for(AUTO_VAR(it, players.begin()); it < players.end(); ++it) - { - usedIndexes[ (int)(*it)->getPlayerIndex() ] = true; - } - for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) - { - if(!usedIndexes[i]) - { - playerIndex = i; - break; - } - } - } - player->setPlayerIndex( playerIndex ); - player->setCustomSkin( packet->m_playerSkinId ); - player->setCustomCape( packet->m_playerCapeId ); + std::uint8_t playerIndex = 0; + { + bool usedIndexes[MINECRAFT_NET_MAX_PLAYERS]; + ZeroMemory(&usedIndexes, MINECRAFT_NET_MAX_PLAYERS * sizeof(bool)); + for (AUTO_VAR(it, players.begin()); it < players.end(); ++it) { + usedIndexes[(int)(*it)->getPlayerIndex()] = true; + } + for (unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) { + if (!usedIndexes[i]) { + playerIndex = i; + break; + } + } + } + player->setPlayerIndex(playerIndex); + player->setCustomSkin(packet->m_playerSkinId); + player->setCustomCape(packet->m_playerCapeId); - // 4J-JEV: Moved this here so we can send player-model texture and geometry data. - std::shared_ptr playerConnection = std::shared_ptr(new PlayerConnection(server, connection, player)); - //player->connection = playerConnection; // Used to be assigned in PlayerConnection ctor but moved out so we can use std::shared_ptr + // 4J-JEV: Moved this here so we can send player-model texture and geometry + // data. + std::shared_ptr playerConnection = + std::shared_ptr( + new PlayerConnection(server, connection, player)); + // player->connection = playerConnection; // Used to be assigned in + // PlayerConnection ctor but moved out so we can use std::shared_ptr - if(newPlayer) - { - int mapScale = 3; + if (newPlayer) { + int mapScale = 3; #ifdef _LARGE_WORLDS - int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); - int centreXC = (int) (Math::round(player->x / scale) * scale); - int centreZC = (int) (Math::round(player->z / scale) * scale); + int scale = MapItemSavedData::MAP_SIZE * 2 * (1 << mapScale); + int centreXC = (int)(Math::round(player->x / scale) * scale); + int centreZC = (int)(Math::round(player->z / scale) * scale); #else - // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map - int centreXC = 0; - int centreZC = 0; + // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, + // since we can fit the whole world in our map + int centreXC = 0; + int centreZC = 0; #endif - // 4J Added - Give every player a map the first time they join a server - player->inventory->setItem( 9, std::shared_ptr( new ItemInstance(Item::map_Id, 1, level->getAuxValueForMap(player->getXuid(),0,centreXC, centreZC, mapScale ) ) ) ); - if(app.getGameRuleDefinitions() != NULL) - { - app.getGameRuleDefinitions()->postProcessPlayer(player); - } - } + // 4J Added - Give every player a map the first time they join a server + player->inventory->setItem( + 9, std::shared_ptr(new ItemInstance( + Item::map_Id, 1, + level->getAuxValueForMap(player->getXuid(), 0, centreXC, + centreZC, mapScale)))); + if (app.getGameRuleDefinitions() != NULL) { + app.getGameRuleDefinitions()->postProcessPlayer(player); + } + } - if(!player->customTextureUrl.empty() && player->customTextureUrl.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl)) - { - if( server->getConnection()->addPendingTextureRequest(player->customTextureUrl)) - { + if (!player->customTextureUrl.empty() && + player->customTextureUrl.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl)) { + if (server->getConnection()->addPendingTextureRequest( + player->customTextureUrl)) { #ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",player->customTextureUrl.c_str(), player->name.c_str()); + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + player->customTextureUrl.c_str(), player->name.c_str()); #endif - playerConnection->send(std::shared_ptr( new TextureAndGeometryPacket(player->customTextureUrl,NULL,0) ) ); - } - } - else if(!player->customTextureUrl.empty() && app.IsFileInMemoryTextures(player->customTextureUrl)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl,NULL,0); - } + playerConnection->send(std::shared_ptr( + new TextureAndGeometryPacket(player->customTextureUrl, NULL, + 0))); + } + } else if (!player->customTextureUrl.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl, NULL, 0); + } - if(!player->customTextureUrl2.empty() && player->customTextureUrl2.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - if( server->getConnection()->addPendingTextureRequest(player->customTextureUrl2)) - { + if (!player->customTextureUrl2.empty() && + player->customTextureUrl2.substr(0, 3).compare(L"def") != 0 && + !app.IsFileInMemoryTextures(player->customTextureUrl2)) { + if (server->getConnection()->addPendingTextureRequest( + player->customTextureUrl2)) { #ifndef _CONTENT_PACKAGE - wprintf(L"Sending texture packet to get custom skin %ls from player %ls\n",player->customTextureUrl2.c_str(), player->name.c_str()); + wprintf( + L"Sending texture packet to get custom skin %ls from player " + L"%ls\n", + player->customTextureUrl2.c_str(), player->name.c_str()); #endif - playerConnection->send(std::shared_ptr( new TexturePacket(player->customTextureUrl2,NULL,0) ) ); - } - } - else if(!player->customTextureUrl2.empty() && app.IsFileInMemoryTextures(player->customTextureUrl2)) - { - // Update the ref count on the memory texture data - app.AddMemoryTextureFile(player->customTextureUrl2,NULL,0); - } + playerConnection->send(std::shared_ptr( + new TexturePacket(player->customTextureUrl2, NULL, 0))); + } + } else if (!player->customTextureUrl2.empty() && + app.IsFileInMemoryTextures(player->customTextureUrl2)) { + // Update the ref count on the memory texture data + app.AddMemoryTextureFile(player->customTextureUrl2, NULL, 0); + } - player->setIsGuest( packet->m_isGuest ); + player->setIsGuest(packet->m_isGuest); - Pos *spawnPos = level->getSharedSpawnPos(); + Pos* spawnPos = level->getSharedSpawnPos(); - updatePlayerGameMode(player, nullptr, level); + updatePlayerGameMode(player, nullptr, level); - // Update the privileges with the correct game mode - GameType *gameType = Player::getPlayerGamePrivilege(player->getAllPlayerGamePrivileges(),Player::ePlayerGamePrivilege_CreativeMode) ? GameType::CREATIVE : GameType::SURVIVAL; - gameType = LevelSettings::validateGameType(gameType->getId()); - if (player->gameMode->getGameModeForPlayer() != gameType) - { - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CreativeMode,player->gameMode->getGameModeForPlayer()->getId() ); - } + // Update the privileges with the correct game mode + GameType* gameType = Player::getPlayerGamePrivilege( + player->getAllPlayerGamePrivileges(), + Player::ePlayerGamePrivilege_CreativeMode) + ? GameType::CREATIVE + : GameType::SURVIVAL; + gameType = LevelSettings::validateGameType(gameType->getId()); + if (player->gameMode->getGameModeForPlayer() != gameType) { + player->setPlayerGamePrivilege( + Player::ePlayerGamePrivilege_CreativeMode, + player->gameMode->getGameModeForPlayer()->getId()); + } - //std::shared_ptr playerConnection = std::shared_ptr(new PlayerConnection(server, connection, player)); - player->connection = playerConnection; // Used to be assigned in PlayerConnection ctor but moved out so we can use std::shared_ptr + // std::shared_ptr playerConnection = + // std::shared_ptr(new PlayerConnection(server, + // connection, player)); + player->connection = + playerConnection; // Used to be assigned in PlayerConnection ctor but + // moved out so we can use std::shared_ptr - // 4J Added to store UGC settings - playerConnection->m_friendsOnlyUGC = packet->m_friendsOnlyUGC; - playerConnection->m_offlineXUID = packet->m_offlineXuid; - playerConnection->m_onlineXUID = packet->m_onlineXuid; + // 4J Added to store UGC settings + playerConnection->m_friendsOnlyUGC = packet->m_friendsOnlyUGC; + playerConnection->m_offlineXUID = packet->m_offlineXuid; + playerConnection->m_onlineXUID = packet->m_onlineXuid; - // This player is now added to the list, so incrementing this value invalidates all previous PreLogin packets - if(packet->m_friendsOnlyUGC) ++server->m_ugcPlayersVersion; + // This player is now added to the list, so incrementing this value + // invalidates all previous PreLogin packets + if (packet->m_friendsOnlyUGC) ++server->m_ugcPlayersVersion; - addPlayerToReceiving( player ); + addPlayerToReceiving(player); - playerConnection->send( std::shared_ptr( new LoginPacket(L"", player->entityId, level->getLevelData()->getGenerator(), level->getSeed(), player->gameMode->getGameModeForPlayer()->getId(), - (std::uint8_t) level->dimension->id, (std::uint8_t) level->getMaxBuildHeight(), (std::uint8_t) getMaxPlayers(), - level->difficulty, TelemetryManager->GetMultiplayerInstanceID(), playerIndex, level->useNewSeaLevel(), player->getAllPlayerGamePrivileges(), - level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale() ) ) ); - playerConnection->send( std::shared_ptr( new SetSpawnPositionPacket(spawnPos->x, spawnPos->y, spawnPos->z) ) ); - playerConnection->send( std::shared_ptr( new PlayerAbilitiesPacket(&player->abilities)) ); - delete spawnPos; + playerConnection->send(std::shared_ptr(new LoginPacket( + L"", player->entityId, level->getLevelData()->getGenerator(), + level->getSeed(), player->gameMode->getGameModeForPlayer()->getId(), + (std::uint8_t)level->dimension->id, + (std::uint8_t)level->getMaxBuildHeight(), (std::uint8_t)getMaxPlayers(), + level->difficulty, TelemetryManager->GetMultiplayerInstanceID(), + playerIndex, level->useNewSeaLevel(), + player->getAllPlayerGamePrivileges(), + level->getLevelData()->getXZSize(), + level->getLevelData()->getHellScale()))); + playerConnection->send(std::shared_ptr( + new SetSpawnPositionPacket(spawnPos->x, spawnPos->y, spawnPos->z))); + playerConnection->send(std::shared_ptr( + new PlayerAbilitiesPacket(&player->abilities))); + delete spawnPos; - sendLevelInfo(player, level); + sendLevelInfo(player, level); - // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( std::shared_ptr( new ChatPacket(L"§e" + playerEntity->name + L" joined the game.") ) ); - broadcastAll( std::shared_ptr( new ChatPacket(player->name, ChatPacket::e_ChatPlayerJoinedGame) ) ); + // 4J-PB - removed, since it needs to be localised in the language the + // client is in + // server->players->broadcastAll( std::shared_ptr( new + // ChatPacket(L"§e" + playerEntity->name + L" joined the game.") ) ); + broadcastAll(std::shared_ptr( + new ChatPacket(player->name, ChatPacket::e_ChatPlayerJoinedGame))); - MemSect(14); - add(player); - MemSect(0); + MemSect(14); + add(player); + MemSect(0); - player->doTick(true, true, false); // 4J - added - force sending of the nearest chunk before the player is teleported, so we have somewhere to arrive on... - playerConnection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); + player->doTick( + true, true, + false); // 4J - added - force sending of the nearest chunk before the + // player is teleported, so we have somewhere to arrive on... + playerConnection->teleport(player->x, player->y, player->z, player->yRot, + player->xRot); - server->getConnection()->addPlayerConnection(playerConnection); - playerConnection->send( std::shared_ptr( new SetTimePacket(level->getTime()) ) ); + server->getConnection()->addPlayerConnection(playerConnection); + playerConnection->send( + std::shared_ptr(new SetTimePacket(level->getTime()))); - AUTO_VAR(activeEffects, player->getActiveEffects()); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; - playerConnection->send(std::shared_ptr( new UpdateMobEffectPacket(player->entityId, effect) ) ); - } + AUTO_VAR(activeEffects, player->getActiveEffects()); + for (AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); + ++it) { + MobEffectInstance* effect = *it; + playerConnection->send(std::shared_ptr( + new UpdateMobEffectPacket(player->entityId, effect))); + } - player->initMenu(); + player->initMenu(); - // If we are joining at the same time as someone in the end on this system is travelling through the win portal, - // then we should set our wonGame flag to true so that respawning works when the EndPoem is closed - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL ) - { - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) - { - std::shared_ptr servPlayer = *it; - INetworkPlayer *checkPlayer = servPlayer->connection->getNetworkPlayer(); - if(thisPlayer != checkPlayer && checkPlayer != NULL && thisPlayer->IsSameSystem( checkPlayer ) && servPlayer->wonGame ) - { - player->wonGame = true; - break; - } - } - } + // If we are joining at the same time as someone in the end on this system + // is travelling through the win portal, then we should set our wonGame flag + // to true so that respawning works when the EndPoem is closed + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer != NULL) { + for (AUTO_VAR(it, players.begin()); it != players.end(); ++it) { + std::shared_ptr servPlayer = *it; + INetworkPlayer* checkPlayer = + servPlayer->connection->getNetworkPlayer(); + if (thisPlayer != checkPlayer && checkPlayer != NULL && + thisPlayer->IsSameSystem(checkPlayer) && servPlayer->wonGame) { + player->wonGame = true; + break; + } + } + } } -void PlayerList::setLevel(ServerLevelArray levels) -{ - playerIo = levels[0]->getLevelStorage()->getPlayerIO(); +void PlayerList::setLevel(ServerLevelArray levels) { + playerIo = levels[0]->getLevelStorage()->getPlayerIO(); } -void PlayerList::changeDimension(std::shared_ptr player, ServerLevel *from) -{ - ServerLevel *to = player->getLevel(); +void PlayerList::changeDimension(std::shared_ptr player, + ServerLevel* from) { + ServerLevel* to = player->getLevel(); - if (from != NULL) from->getChunkMap()->remove(player); - to->getChunkMap()->add(player); + if (from != NULL) from->getChunkMap()->remove(player); + to->getChunkMap()->add(player); - to->cache->create(((int) player->x) >> 4, ((int) player->z) >> 4); + to->cache->create(((int)player->x) >> 4, ((int)player->z) >> 4); } -int PlayerList::getMaxRange() -{ - return PlayerChunkMap::convertChunkRangeToBlock(getViewDistance()); +int PlayerList::getMaxRange() { + return PlayerChunkMap::convertChunkRangeToBlock(getViewDistance()); } - // 4J Changed return val to bool to check if new player or loaded player -bool PlayerList::load(std::shared_ptr player) -{ - return playerIo->load(player); +// 4J Changed return val to bool to check if new player or loaded player +bool PlayerList::load(std::shared_ptr player) { + return playerIo->load(player); } -void PlayerList::save(std::shared_ptr player) -{ - playerIo->save(player); +void PlayerList::save(std::shared_ptr player) { + playerIo->save(player); } // 4J Stu - TU-1 hotifx -// Add this function to take some of the code from the PlayerList::add function with the fixes -// for checking spawn area, especially in the nether. These needed to be done in a different order from before -// Fix for #13150 - When a player loads/joins a game after saving/leaving in the nether, sometimes they are spawned on top of the nether and cannot mine down -void PlayerList::validatePlayerSpawnPosition(std::shared_ptr player) -{ - // 4J Stu - Some adjustments to make sure the current players position is correct - // Make sure that the player is on the ground, and in the centre x/z of the current column - app.DebugPrintf("Original pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); +// Add this function to take some of the code from the PlayerList::add function +// with the fixes for checking spawn area, especially in the nether. These +// needed to be done in a different order from before Fix for #13150 - When a +// player loads/joins a game after saving/leaving in the nether, sometimes they +// are spawned on top of the nether and cannot mine down +void PlayerList::validatePlayerSpawnPosition( + std::shared_ptr player) { + // 4J Stu - Some adjustments to make sure the current players position is + // correct Make sure that the player is on the ground, and in the centre x/z + // of the current column + app.DebugPrintf("Original pos is %f, %f, %f in dimension %d\n", player->x, + player->y, player->z, player->dimension); - double targetX = 0; - if(player->x < 0) targetX = Mth::ceil(player->x) - 0.5; - else targetX = Mth::floor(player->x) + 0.5; + double targetX = 0; + if (player->x < 0) + targetX = Mth::ceil(player->x) - 0.5; + else + targetX = Mth::floor(player->x) + 0.5; - double targetY = floor(player->y); + double targetY = floor(player->y); - double targetZ = 0; - if(player->z < 0) targetZ = Mth::ceil(player->z) - 0.5; - else targetZ = Mth::floor(player->z) + 0.5; + double targetZ = 0; + if (player->z < 0) + targetZ = Mth::ceil(player->z) - 0.5; + else + targetZ = Mth::floor(player->z) + 0.5; - player->setPos(targetX, targetY, targetZ); + player->setPos(targetX, targetY, targetZ); - app.DebugPrintf("New pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); + app.DebugPrintf("New pos is %f, %f, %f in dimension %d\n", player->x, + player->y, player->z, player->dimension); - ServerLevel *level = server->getLevel(player->dimension); - while (level->getCubes(player, player->bb)->size() != 0) - { + ServerLevel* level = server->getLevel(player->dimension); + while (level->getCubes(player, player->bb)->size() != 0) { player->setPos(player->x, player->y + 1, player->z); } - app.DebugPrintf("Final pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); + app.DebugPrintf("Final pos is %f, %f, %f in dimension %d\n", player->x, + player->y, player->z, player->dimension); - // 4J Stu - If we are in the nether and the above while loop has put us above the nether then we have a problem - // Finding a valid, safe spawn point is potentially computationally expensive (may have to hunt through a large part - // of the nether) so move the player to their spawn position in the overworld so that they do not lose their inventory - // 4J Stu - We also use this mechanism to force a spawn point in the overworld for players who were in the save when the reset nether option was applied - if(level->dimension->id == -1 && player->y > 125) - { - app.DebugPrintf("Player in the nether tried to spawn at y = %f, moving to overworld\n", player->y); - player->setLevel(server->getLevel(0)); - player->gameMode->setLevel(server->getLevel(0)); - player->dimension = 0; + // 4J Stu - If we are in the nether and the above while loop has put us + // above the nether then we have a problem Finding a valid, safe spawn point + // is potentially computationally expensive (may have to hunt through a + // large part of the nether) so move the player to their spawn position in + // the overworld so that they do not lose their inventory 4J Stu - We also + // use this mechanism to force a spawn point in the overworld for players + // who were in the save when the reset nether option was applied + if (level->dimension->id == -1 && player->y > 125) { + app.DebugPrintf( + "Player in the nether tried to spawn at y = %f, moving to " + "overworld\n", + player->y); + player->setLevel(server->getLevel(0)); + player->gameMode->setLevel(server->getLevel(0)); + player->dimension = 0; - level = server->getLevel(player->dimension); + level = server->getLevel(player->dimension); - Pos *levelSpawn = level->getSharedSpawnPos(); - player->setPos(levelSpawn->x, levelSpawn->y, levelSpawn->z); - delete levelSpawn; + Pos* levelSpawn = level->getSharedSpawnPos(); + player->setPos(levelSpawn->x, levelSpawn->y, levelSpawn->z); + delete levelSpawn; - Pos *bedPosition = player->getRespawnPosition(); - if (bedPosition != NULL) - { - Pos *respawnPosition = Player::checkBedValidRespawnPosition(server->getLevel(player->dimension), bedPosition); - if (respawnPosition != NULL) - { - player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, respawnPosition->z + 0.5f, 0, 0); - player->setRespawnPosition(bedPosition); - } - delete bedPosition; - } - while (level->getCubes(player, player->bb)->size() != 0) - { - player->setPos(player->x, player->y + 1, player->z); - } - - app.DebugPrintf("Updated pos is %f, %f, %f in dimension %d\n", player->x, player->y, player->z, player->dimension); - } + Pos* bedPosition = player->getRespawnPosition(); + if (bedPosition != NULL) { + Pos* respawnPosition = Player::checkBedValidRespawnPosition( + server->getLevel(player->dimension), bedPosition); + if (respawnPosition != NULL) { + player->moveTo(respawnPosition->x + 0.5f, + respawnPosition->y + 0.1f, + respawnPosition->z + 0.5f, 0, 0); + player->setRespawnPosition(bedPosition); + } + delete bedPosition; + } + while (level->getCubes(player, player->bb)->size() != 0) { + player->setPos(player->x, player->y + 1, player->z); + } + + app.DebugPrintf("Updated pos is %f, %f, %f in dimension %d\n", + player->x, player->y, player->z, player->dimension); + } } -void PlayerList::add(std::shared_ptr player) -{ - //broadcastAll(std::shared_ptr( new PlayerInfoPacket(player->name, true, 1000) ) ); - if( player->connection->getNetworkPlayer() ) - { - broadcastAll(std::shared_ptr( new PlayerInfoPacket( player ) ) ); - } +void PlayerList::add(std::shared_ptr player) { + // broadcastAll(std::shared_ptr( new + // PlayerInfoPacket(player->name, true, 1000) ) ); + if (player->connection->getNetworkPlayer()) { + broadcastAll( + std::shared_ptr(new PlayerInfoPacket(player))); + } players.push_back(player); - // 4J Added - addPlayerToReceiving(player); + // 4J Added + addPlayerToReceiving(player); // Ensure the area the player is spawning in is loaded! - ServerLevel *level = server->getLevel(player->dimension); + ServerLevel* level = server->getLevel(player->dimension); - // 4J Stu - TU-1 hotfix - // Fix for #13150 - When a player loads/joins a game after saving/leaving in the nether, sometimes they are spawned on top of the nether and cannot mine down - // Some code from here has been moved to the above validatePlayerSpawnPosition function + // 4J Stu - TU-1 hotfix + // Fix for #13150 - When a player loads/joins a game after saving/leaving in + // the nether, sometimes they are spawned on top of the nether and cannot + // mine down Some code from here has been moved to the above + // validatePlayerSpawnPosition function - // 4J Stu - Swapped these lines about so that we get the chunk visiblity packet way ahead of all the add tracked entity packets - // Fix for #9169 - ART : Sign text is replaced with the words “Awaiting approval”. + // 4J Stu - Swapped these lines about so that we get the chunk visiblity + // packet way ahead of all the add tracked entity packets Fix for #9169 - + // ART : Sign text is replaced with the words “Awaiting approval”. changeDimension(player, NULL); level->addEntity(player); - for (int i = 0; i < players.size(); i++) - { - std::shared_ptr op = players.at(i); - //player->connection->send(std::shared_ptr( new PlayerInfoPacket(op->name, true, op->latency) ) ); - if( op->connection->getNetworkPlayer() ) - { - player->connection->send(std::shared_ptr( new PlayerInfoPacket( op ) ) ); - } - } + for (int i = 0; i < players.size(); i++) { + std::shared_ptr op = players.at(i); + // player->connection->send(std::shared_ptr( new + // PlayerInfoPacket(op->name, true, op->latency) ) ); + if (op->connection->getNetworkPlayer()) { + player->connection->send( + std::shared_ptr(new PlayerInfoPacket(op))); + } + } - if(level->isAtLeastOnePlayerSleeping()) - { - std::shared_ptr firstSleepingPlayer = nullptr; - for (unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr thisPlayer = players[i]; - if(thisPlayer->isSleeping()) - { - if(firstSleepingPlayer == NULL) firstSleepingPlayer = thisPlayer; - thisPlayer->connection->send(std::shared_ptr( new ChatPacket(thisPlayer->name, ChatPacket::e_ChatBedMeSleep))); - } - } - player->connection->send(std::shared_ptr( new ChatPacket(firstSleepingPlayer->name, ChatPacket::e_ChatBedPlayerSleep))); - } + if (level->isAtLeastOnePlayerSleeping()) { + std::shared_ptr firstSleepingPlayer = nullptr; + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr thisPlayer = players[i]; + if (thisPlayer->isSleeping()) { + if (firstSleepingPlayer == NULL) + firstSleepingPlayer = thisPlayer; + thisPlayer->connection->send( + std::shared_ptr(new ChatPacket( + thisPlayer->name, ChatPacket::e_ChatBedMeSleep))); + } + } + player->connection->send(std::shared_ptr(new ChatPacket( + firstSleepingPlayer->name, ChatPacket::e_ChatBedPlayerSleep))); + } } -void PlayerList::move(std::shared_ptr player) -{ - player->getLevel()->getChunkMap()->move(player); +void PlayerList::move(std::shared_ptr player) { + player->getLevel()->getChunkMap()->move(player); } -void PlayerList::remove(std::shared_ptr player) -{ +void PlayerList::remove(std::shared_ptr player) { save(player); - //4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map - if(player->isGuest()) playerIo->deleteMapFilesForPlayer(player); - ServerLevel *level = player->getLevel(); + // 4J Stu - We don't want to save the map data for guests, so when we are + // sure that the player is gone delete the map + if (player->isGuest()) playerIo->deleteMapFilesForPlayer(player); + ServerLevel* level = player->getLevel(); level->removeEntity(player); level->getChunkMap()->remove(player); - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if( it != players.end() ) - { - players.erase(it); - } - //broadcastAll(std::shared_ptr( new PlayerInfoPacket(player->name, false, 9999) ) ); + AUTO_VAR(it, find(players.begin(), players.end(), player)); + if (it != players.end()) { + players.erase(it); + } + // broadcastAll(std::shared_ptr( new + // PlayerInfoPacket(player->name, false, 9999) ) ); - removePlayerFromReceiving(player); - player->connection = nullptr; // Must remove reference to connection, or else there is a circular dependency - delete player->gameMode; // Gamemode also needs deleted as it references back to this player - player->gameMode = NULL; + removePlayerFromReceiving(player); + player->connection = nullptr; // Must remove reference to connection, or + // else there is a circular dependency + delete player->gameMode; // Gamemode also needs deleted as it references + // back to this player + player->gameMode = NULL; - // 4J Stu - Save all the players currently in the game, which will also free up unused map id slots if required, and remove old players - saveAll(NULL,false); + // 4J Stu - Save all the players currently in the game, which will also free + // up unused map id slots if required, and remove old players + saveAll(NULL, false); } -std::shared_ptr PlayerList::getPlayerForLogin(PendingConnection *pendingConnection, const std::wstring& userName, PlayerUID xuid, PlayerUID onlineXuid) -{ - if (players.size() >= maxPlayers) - { +std::shared_ptr PlayerList::getPlayerForLogin( + PendingConnection* pendingConnection, const std::wstring& userName, + PlayerUID xuid, PlayerUID onlineXuid) { + if (players.size() >= maxPlayers) { pendingConnection->disconnect(DisconnectPacket::eDisconnect_ServerFull); return std::shared_ptr(); } - - std::shared_ptr player = std::shared_ptr(new ServerPlayer(server, server->getLevel(0), userName, new ServerPlayerGameMode(server->getLevel(0)) )); - player->gameMode->player = player; // 4J added as had to remove this assignment from ServerPlayer ctor - player->setXuid( xuid ); // 4J Added - player->setOnlineXuid( onlineXuid ); // 4J Added - // Work out the base server player settings - INetworkPlayer *networkPlayer = pendingConnection->connection->getSocket()->getPlayer(); - if(networkPlayer != NULL && !networkPlayer->IsHost()) - { - player->enableAllPlayerPrivileges( app.GetGameHostOption(eGameHostOption_TrustPlayers)>0 ); - } + std::shared_ptr player = std::shared_ptr( + new ServerPlayer(server, server->getLevel(0), userName, + new ServerPlayerGameMode(server->getLevel(0)))); + player->gameMode->player = player; // 4J added as had to remove this + // assignment from ServerPlayer ctor + player->setXuid(xuid); // 4J Added + player->setOnlineXuid(onlineXuid); // 4J Added - // 4J Added - LevelRuleset *serverRuleDefs = app.getGameRuleDefinitions(); - if(serverRuleDefs != NULL) - { - player->gameMode->setGameRules( GameRuleDefinition::generateNewGameRulesInstance(GameRulesInstance::eGameRulesInstanceType_ServerPlayer, serverRuleDefs, pendingConnection->connection) ); - } + // Work out the base server player settings + INetworkPlayer* networkPlayer = + pendingConnection->connection->getSocket()->getPlayer(); + if (networkPlayer != NULL && !networkPlayer->IsHost()) { + player->enableAllPlayerPrivileges( + app.GetGameHostOption(eGameHostOption_TrustPlayers) > 0); + } + + // 4J Added + LevelRuleset* serverRuleDefs = app.getGameRuleDefinitions(); + if (serverRuleDefs != NULL) { + player->gameMode->setGameRules( + GameRuleDefinition::generateNewGameRulesInstance( + GameRulesInstance::eGameRulesInstanceType_ServerPlayer, + serverRuleDefs, pendingConnection->connection)); + } return player; } -std::shared_ptr PlayerList::respawn(std::shared_ptr serverPlayer, int targetDimension, bool keepAllPlayerData) -{ - // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. - bool isPrimary = canReceiveAllPackets(serverPlayer); // Is this the primary player in its current dimension? - int oldDimension = serverPlayer->dimension; - bool isEmptying = ( targetDimension != oldDimension); // We're not emptying this dimension on this machine if this player is going back into the same dimension +std::shared_ptr PlayerList::respawn( + std::shared_ptr serverPlayer, int targetDimension, + bool keepAllPlayerData) { + // How we handle the entity tracker depends on whether we are the primary + // player currently, and whether there will be any player in the same system + // in the same dimension once we finish respawning. + bool isPrimary = canReceiveAllPackets( + serverPlayer); // Is this the primary player in its current dimension? + int oldDimension = serverPlayer->dimension; + bool isEmptying = + (targetDimension != + oldDimension); // We're not emptying this dimension on this machine if + // this player is going back into the same dimension - // Also consider if there is another player on this machine which is in the same dimension and can take over as primary player - if( isEmptying ) - { - INetworkPlayer *thisPlayer = serverPlayer->connection->getNetworkPlayer(); + // Also consider if there is another player on this machine which is in the + // same dimension and can take over as primary player + if (isEmptying) { + INetworkPlayer* thisPlayer = + serverPlayer->connection->getNetworkPlayer(); - for( unsigned int i = 0; i < players.size(); i++ ) - { - std::shared_ptr ep = players[i]; - if( ep == serverPlayer ) continue; - if( ep->dimension != oldDimension ) continue; + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr ep = players[i]; + if (ep == serverPlayer) continue; + if (ep->dimension != oldDimension) continue; - INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - // There's another player here in the same dimension - we're not the last one out - isEmptying = false; - } - } - } + INetworkPlayer* otherPlayer = ep->connection->getNetworkPlayer(); + if (otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer)) { + // There's another player here in the same dimension - we're not + // the last one out + isEmptying = false; + } + } + } - // Now we know where we stand, the actions to take are as follows: - // (1) if this isn't the primary player, then we just need to remove it from the entity tracker - // (2) if this Is the primary player then: - // (a) if isEmptying is true, then remove the player from the tracker, and send "remove entity" packets for anything seen (this is the original behaviour of the code) - // (b) if isEmptying is false, then we'll be transferring control of entity tracking to another player + // Now we know where we stand, the actions to take are as follows: + // (1) if this isn't the primary player, then we just need to remove it from + // the entity tracker (2) if this Is the primary player then: + // (a) if isEmptying is true, then remove the player from the + //tracker, and send "remove entity" packets for anything seen (this is the + //original behaviour of the code) (b) if isEmptying is false, then we'll be + //transferring control of entity tracking to another player - if( isPrimary ) - { - if( isEmptying ) - { - app.DebugPrintf("Emptying this dimension\n"); - serverPlayer->getLevel()->getTracker()->clear(serverPlayer); - } - else - { - app.DebugPrintf("Transferring... storing flags\n"); - serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); - } - } - else - { - app.DebugPrintf("Not primary player\n"); - serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); - } + if (isPrimary) { + if (isEmptying) { + app.DebugPrintf("Emptying this dimension\n"); + serverPlayer->getLevel()->getTracker()->clear(serverPlayer); + } else { + app.DebugPrintf("Transferring... storing flags\n"); + serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); + } + } else { + app.DebugPrintf("Not primary player\n"); + serverPlayer->getLevel()->getTracker()->removeEntity(serverPlayer); + } - serverPlayer->getLevel()->getChunkMap()->remove(serverPlayer); - AUTO_VAR(it, find(players.begin(),players.end(),serverPlayer)); - if( it != players.end() ) - { - players.erase(it); - } - server->getLevel(serverPlayer->dimension)->removeEntityImmediately(serverPlayer); + serverPlayer->getLevel()->getChunkMap()->remove(serverPlayer); + AUTO_VAR(it, find(players.begin(), players.end(), serverPlayer)); + if (it != players.end()) { + players.erase(it); + } + server->getLevel(serverPlayer->dimension) + ->removeEntityImmediately(serverPlayer); - Pos *bedPosition = serverPlayer->getRespawnPosition(); + Pos* bedPosition = serverPlayer->getRespawnPosition(); - removePlayerFromReceiving(serverPlayer); + removePlayerFromReceiving(serverPlayer); serverPlayer->dimension = targetDimension; - EDefaultSkins skin = serverPlayer->getPlayerDefaultSkin(); - std::uint8_t playerIndex = serverPlayer->getPlayerIndex(); + EDefaultSkins skin = serverPlayer->getPlayerDefaultSkin(); + std::uint8_t playerIndex = serverPlayer->getPlayerIndex(); - PlayerUID playerXuid = serverPlayer->getXuid(); - PlayerUID playerOnlineXuid = serverPlayer->getOnlineXuid(); - - std::shared_ptr player = std::shared_ptr(new ServerPlayer(server, server->getLevel(serverPlayer->dimension), serverPlayer->name, new ServerPlayerGameMode(server->getLevel(serverPlayer->dimension)))); - player->restoreFrom(serverPlayer, keepAllPlayerData); - if (keepAllPlayerData) - { - // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal replaces the Player's currently held item with the first one from the Quickbar - player->inventory->selected = serverPlayer->inventory->selected; - } - player->gameMode->player = player; // 4J added as had to remove this assignment from ServerPlayer ctor - player->setXuid( playerXuid ); // 4J Added - player->setOnlineXuid( playerOnlineXuid ); // 4J Added + PlayerUID playerXuid = serverPlayer->getXuid(); + PlayerUID playerOnlineXuid = serverPlayer->getOnlineXuid(); - // 4J Stu - Don't reuse the id. If we do, then the player can be re-added after being removed, but the add packet gets sent before the remove packet - //player->entityId = serverPlayer->entityId; + std::shared_ptr player = std::shared_ptr( + new ServerPlayer(server, server->getLevel(serverPlayer->dimension), + serverPlayer->name, + new ServerPlayerGameMode( + server->getLevel(serverPlayer->dimension)))); + player->restoreFrom(serverPlayer, keepAllPlayerData); + if (keepAllPlayerData) { + // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal + // replaces the Player's currently held item with the first one from the + // Quickbar + player->inventory->selected = serverPlayer->inventory->selected; + } + player->gameMode->player = player; // 4J added as had to remove this + // assignment from ServerPlayer ctor + player->setXuid(playerXuid); // 4J Added + player->setOnlineXuid(playerOnlineXuid); // 4J Added + + // 4J Stu - Don't reuse the id. If we do, then the player can be re-added + // after being removed, but the add packet gets sent before the remove + // packet + // player->entityId = serverPlayer->entityId; player->connection = serverPlayer->connection; - player->setPlayerDefaultSkin( skin ); - player->setIsGuest( serverPlayer->isGuest() ); - player->setPlayerIndex( playerIndex ); - player->setCustomSkin( serverPlayer->getCustomSkin() ); - player->setCustomCape( serverPlayer->getCustomCape() ); - player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, serverPlayer->getAllPlayerGamePrivileges()); - player->gameMode->setGameRules( serverPlayer->gameMode->getGameRules() ); - player->dimension = targetDimension; + player->setPlayerDefaultSkin(skin); + player->setIsGuest(serverPlayer->isGuest()); + player->setPlayerIndex(playerIndex); + player->setCustomSkin(serverPlayer->getCustomSkin()); + player->setCustomCape(serverPlayer->getCustomCape()); + player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, + serverPlayer->getAllPlayerGamePrivileges()); + player->gameMode->setGameRules(serverPlayer->gameMode->getGameRules()); + player->dimension = targetDimension; - // 4J Stu - Added this as we need to know earlier if the player is the player for this connection so that - // we can work out if they are the primary for the system and can receive all packets - player->connection->setPlayer( player ); + // 4J Stu - Added this as we need to know earlier if the player is the + // player for this connection so that we can work out if they are the + // primary for the system and can receive all packets + player->connection->setPlayer(player); - addPlayerToReceiving(player); + addPlayerToReceiving(player); - ServerLevel *level = server->getLevel(serverPlayer->dimension); + ServerLevel* level = server->getLevel(serverPlayer->dimension); - // reset the player's game mode (first pick from old, then copy level if - // necessary) - updatePlayerGameMode(player, serverPlayer, level); + // reset the player's game mode (first pick from old, then copy level if + // necessary) + updatePlayerGameMode(player, serverPlayer, level); - if(serverPlayer->wonGame && targetDimension == oldDimension && serverPlayer->getHealth() > 0) - { - // If the player is still alive and respawning to the same dimension, they are just being added back from someone else viewing the Win screen - player->moveTo(serverPlayer->x, serverPlayer->y, serverPlayer->z, serverPlayer->yRot, serverPlayer->xRot); - if(bedPosition != NULL) - { - player->setRespawnPosition(bedPosition); - delete bedPosition; - } - // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal replaces the Player's currently held item with the first one from the Quickbar - player->inventory->selected = serverPlayer->inventory->selected; - } - else if (bedPosition != NULL) - { - Pos *respawnPosition = Player::checkBedValidRespawnPosition(server->getLevel(serverPlayer->dimension), bedPosition); - if (respawnPosition != NULL) - { - player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, respawnPosition->z + 0.5f, 0, 0); + if (serverPlayer->wonGame && targetDimension == oldDimension && + serverPlayer->getHealth() > 0) { + // If the player is still alive and respawning to the same dimension, + // they are just being added back from someone else viewing the Win + // screen + player->moveTo(serverPlayer->x, serverPlayer->y, serverPlayer->z, + serverPlayer->yRot, serverPlayer->xRot); + if (bedPosition != NULL) { player->setRespawnPosition(bedPosition); + delete bedPosition; } - else - { - player->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::NO_RESPAWN_BED_AVAILABLE, 0) ) ); + // Fix for #81759 - TU9: Content: Gameplay: Entering The End Exit Portal + // replaces the Player's currently held item with the first one from the + // Quickbar + player->inventory->selected = serverPlayer->inventory->selected; + } else if (bedPosition != NULL) { + Pos* respawnPosition = Player::checkBedValidRespawnPosition( + server->getLevel(serverPlayer->dimension), bedPosition); + if (respawnPosition != NULL) { + player->moveTo(respawnPosition->x + 0.5f, respawnPosition->y + 0.1f, + respawnPosition->z + 0.5f, 0, 0); + player->setRespawnPosition(bedPosition); + } else { + player->connection->send( + std::shared_ptr(new GameEventPacket( + GameEventPacket::NO_RESPAWN_BED_AVAILABLE, 0))); } - delete bedPosition; + delete bedPosition; } // Ensure the area the player is spawning in is loaded! - level->cache->create(((int) player->x) >> 4, ((int) player->z) >> 4); + level->cache->create(((int)player->x) >> 4, ((int)player->z) >> 4); - while (!level->getCubes(player, player->bb)->empty()) - { + while (!level->getCubes(player, player->bb)->empty()) { player->setPos(player->x, player->y + 1, player->z); } - player->connection->send( std::shared_ptr( new RespawnPacket((char) player->dimension, player->level->getSeed(), player->level->getMaxBuildHeight(), - player->gameMode->getGameModeForPlayer(), level->difficulty, level->getLevelData()->getGenerator(), - player->level->useNewSeaLevel(), player->entityId, level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale()) ) ); - player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); + player->connection->send(std::shared_ptr(new RespawnPacket( + (char)player->dimension, player->level->getSeed(), + player->level->getMaxBuildHeight(), + player->gameMode->getGameModeForPlayer(), level->difficulty, + level->getLevelData()->getGenerator(), player->level->useNewSeaLevel(), + player->entityId, level->getLevelData()->getXZSize(), + level->getLevelData()->getHellScale()))); + player->connection->teleport(player->x, player->y, player->z, player->yRot, + player->xRot); - if(keepAllPlayerData) - { - std::vector *activeEffects = player->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; + if (keepAllPlayerData) { + std::vector* activeEffects = + player->getActiveEffects(); + for (AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); + ++it) { + MobEffectInstance* effect = *it; - player->connection->send(std::shared_ptr( new UpdateMobEffectPacket(player->entityId, effect) ) ); - } - delete activeEffects; - player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); - } + player->connection->send(std::shared_ptr( + new UpdateMobEffectPacket(player->entityId, effect))); + } + delete activeEffects; + player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); + } sendLevelInfo(player, level); @@ -638,365 +726,354 @@ std::shared_ptr PlayerList::respawn(std::shared_ptr player->initMenu(); - // 4J-JEV - Dying before this point in the tutorial is pretty annoying, - // making sure to remove health/hunger and give you back your meat. - if( Minecraft::GetInstance()->isTutorial() - && (!Minecraft::GetInstance()->gameMode->getTutorial()->isStateCompleted(e_Tutorial_State_Food_Bar)) ) - { - app.getGameRuleDefinitions()->postProcessPlayer(player); - } + // 4J-JEV - Dying before this point in the tutorial is pretty annoying, + // making sure to remove health/hunger and give you back your meat. + if (Minecraft::GetInstance()->isTutorial() && + (!Minecraft::GetInstance()->gameMode->getTutorial()->isStateCompleted( + e_Tutorial_State_Food_Bar))) { + app.getGameRuleDefinitions()->postProcessPlayer(player); + } - if( oldDimension == 1 && player->dimension != 1 ) - { - player->displayClientMessage(IDS_PLAYER_LEFT_END); - } + if (oldDimension == 1 && player->dimension != 1) { + player->displayClientMessage(IDS_PLAYER_LEFT_END); + } return player; - } -void PlayerList::toggleDimension(std::shared_ptr player, int targetDimension) -{ - int lastDimension = player->dimension; - // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. - bool isPrimary = canReceiveAllPackets(player); // Is this the primary player in its current dimension? - bool isEmptying = true; +void PlayerList::toggleDimension(std::shared_ptr player, + int targetDimension) { + int lastDimension = player->dimension; + // How we handle the entity tracker depends on whether we are the primary + // player currently, and whether there will be any player in the same system + // in the same dimension once we finish respawning. + bool isPrimary = canReceiveAllPackets( + player); // Is this the primary player in its current dimension? + bool isEmptying = true; - // Also consider if there is another player on this machine which is in the same dimension and can take over as primary player - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); + // Also consider if there is another player on this machine which is in the + // same dimension and can take over as primary player + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); - for( unsigned int i = 0; i < players.size(); i++ ) - { - std::shared_ptr ep = players[i]; - if( ep == player ) continue; - if( ep->dimension != lastDimension ) continue; + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr ep = players[i]; + if (ep == player) continue; + if (ep->dimension != lastDimension) continue; - INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - // There's another player here in the same dimension - we're not the last one out - isEmptying = false; - } - } + INetworkPlayer* otherPlayer = ep->connection->getNetworkPlayer(); + if (otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer)) { + // There's another player here in the same dimension - we're not the + // last one out + isEmptying = false; + } + } + // Now we know where we stand, the actions to take are as follows: + // (1) if this isn't the primary player, then we just need to remove it from + // the entity tracker (2) if this Is the primary player then: + // (a) if isEmptying is true, then remove the player from the + //tracker, and send "remove entity" packets for anything seen (this is the + //original behaviour of the code) (b) if isEmptying is false, then we'll be + //transferring control of entity tracking to another player - // Now we know where we stand, the actions to take are as follows: - // (1) if this isn't the primary player, then we just need to remove it from the entity tracker - // (2) if this Is the primary player then: - // (a) if isEmptying is true, then remove the player from the tracker, and send "remove entity" packets for anything seen (this is the original behaviour of the code) - // (b) if isEmptying is false, then we'll be transferring control of entity tracking to another player + if (isPrimary) { + if (isEmptying) { + app.DebugPrintf("Toggle... Emptying this dimension\n"); + player->getLevel()->getTracker()->clear(player); + } else { + app.DebugPrintf("Toggle... transferring\n"); + player->getLevel()->getTracker()->removeEntity(player); + } + } else { + app.DebugPrintf("Toggle... Not primary player\n"); + player->getLevel()->getTracker()->removeEntity(player); + } - if( isPrimary ) - { - if( isEmptying ) - { - app.DebugPrintf("Toggle... Emptying this dimension\n"); - player->getLevel()->getTracker()->clear(player); - } - else - { - app.DebugPrintf("Toggle... transferring\n"); - player->getLevel()->getTracker()->removeEntity(player); - } - } - else - { - app.DebugPrintf("Toggle... Not primary player\n"); - player->getLevel()->getTracker()->removeEntity(player); - } + ServerLevel* oldLevel = server->getLevel(player->dimension); - ServerLevel *oldLevel = server->getLevel(player->dimension); + // 4J Stu - Do this much earlier so we don't end up unloading chunks in the + // wrong dimension + player->getLevel()->getChunkMap()->remove(player); - // 4J Stu - Do this much earlier so we don't end up unloading chunks in the wrong dimension - player->getLevel()->getChunkMap()->remove(player); - - if(player->dimension != 1 && targetDimension == 1) - { - player->displayClientMessage(IDS_PLAYER_ENTERED_END); - } - else if( player->dimension == 1 ) - { - player->displayClientMessage(IDS_PLAYER_LEFT_END); - } + if (player->dimension != 1 && targetDimension == 1) { + player->displayClientMessage(IDS_PLAYER_ENTERED_END); + } else if (player->dimension == 1) { + player->displayClientMessage(IDS_PLAYER_LEFT_END); + } player->dimension = targetDimension; - ServerLevel *newLevel = server->getLevel(player->dimension); + ServerLevel* newLevel = server->getLevel(player->dimension); - // 4J Stu - Fix for #46423 - TU5: Art: Code: No burning animation visible after entering The Nether while burning - player->clearFire(); // Stop burning if travelling through a portal + // 4J Stu - Fix for #46423 - TU5: Art: Code: No burning animation visible + // after entering The Nether while burning + player->clearFire(); // Stop burning if travelling through a portal - // 4J Stu Added so that we remove entities from the correct level, after the respawn packet we will be in the wrong level - player->flushEntitiesToRemove(); + // 4J Stu Added so that we remove entities from the correct level, after the + // respawn packet we will be in the wrong level + player->flushEntitiesToRemove(); - player->connection->send( std::shared_ptr( new RespawnPacket((char) player->dimension, newLevel->getSeed(), newLevel->getMaxBuildHeight(), - player->gameMode->getGameModeForPlayer(), newLevel->difficulty, newLevel->getLevelData()->getGenerator(), - newLevel->useNewSeaLevel(), player->entityId, newLevel->getLevelData()->getXZSize(), newLevel->getLevelData()->getHellScale()) ) ); + player->connection->send(std::shared_ptr(new RespawnPacket( + (char)player->dimension, newLevel->getSeed(), + newLevel->getMaxBuildHeight(), player->gameMode->getGameModeForPlayer(), + newLevel->difficulty, newLevel->getLevelData()->getGenerator(), + newLevel->useNewSeaLevel(), player->entityId, + newLevel->getLevelData()->getXZSize(), + newLevel->getLevelData()->getHellScale()))); oldLevel->removeEntityImmediately(player); player->removed = false; double xt = player->x; double zt = player->z; - double scale = newLevel->getLevelData()->getHellScale(); // 4J Scale was 8 but this is all we can fit in - if (player->dimension == -1) - { + double scale = + newLevel->getLevelData() + ->getHellScale(); // 4J Scale was 8 but this is all we can fit in + if (player->dimension == -1) { xt /= scale; zt /= scale; player->moveTo(xt, player->y, zt, player->yRot, player->xRot); - if (player->isAlive()) - { + if (player->isAlive()) { oldLevel->tick(player, false); } - } - else if (player->dimension == 0) - { + } else if (player->dimension == 0) { xt *= scale; zt *= scale; player->moveTo(xt, player->y, zt, player->yRot, player->xRot); - if (player->isAlive()) - { + if (player->isAlive()) { + oldLevel->tick(player, false); + } + } else { + Pos* p = newLevel->getDimensionSpecificSpawn(); + + xt = p->x; + player->y = p->y; + zt = p->z; + delete p; + player->moveTo(xt, player->y, zt, 90, 0); + if (player->isAlive()) { oldLevel->tick(player, false); } } - else - { - Pos *p = newLevel->getDimensionSpecificSpawn(); - xt = p->x; - player->y = p->y; - zt = p->z; - delete p; - player->moveTo(xt, player->y, zt, 90, 0); - if (player->isAlive()) - { - oldLevel->tick(player, false); - } - } - - removePlayerFromReceiving(player, false, lastDimension); - addPlayerToReceiving(player); - - if (lastDimension == 1) - { - } - else - { - xt = (double) Mth::clamp((int) xt, -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128); - zt = (double) Mth::clamp((int) zt, -Level::MAX_LEVEL_SIZE + 128, Level::MAX_LEVEL_SIZE - 128); - if (player->isAlive()) - { - newLevel->addEntity(player); - player->moveTo(xt, player->y, zt, player->yRot, player->xRot); - newLevel->tick(player, false); - newLevel->cache->autoCreate = true; - (new PortalForcer())->force(newLevel, player); - newLevel->cache->autoCreate = false; - } - } + removePlayerFromReceiving(player, false, lastDimension); + addPlayerToReceiving(player); + if (lastDimension == 1) { + } else { + xt = (double)Mth::clamp((int)xt, -Level::MAX_LEVEL_SIZE + 128, + Level::MAX_LEVEL_SIZE - 128); + zt = (double)Mth::clamp((int)zt, -Level::MAX_LEVEL_SIZE + 128, + Level::MAX_LEVEL_SIZE - 128); + if (player->isAlive()) { + newLevel->addEntity(player); + player->moveTo(xt, player->y, zt, player->yRot, player->xRot); + newLevel->tick(player, false); + newLevel->cache->autoCreate = true; + (new PortalForcer())->force(newLevel, player); + newLevel->cache->autoCreate = false; + } + } player->setLevel(newLevel); changeDimension(player, oldLevel); - player->gameMode->setLevel(newLevel); + player->gameMode->setLevel(newLevel); - // Resend the teleport if we haven't yet sent the chunk they will land on - if( !g_NetworkManager.SystemFlagGet(player->connection->getNetworkPlayer(),ServerPlayer::getFlagIndexForChunk( ChunkPos(player->xChunk,player->zChunk), player->level->dimension->id ) ) ) - { - player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot, false); - // Force sending of the current chunk - player->doTick(true, true, true); - } - - player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); + // Resend the teleport if we haven't yet sent the chunk they will land on + if (!g_NetworkManager.SystemFlagGet( + player->connection->getNetworkPlayer(), + ServerPlayer::getFlagIndexForChunk( + ChunkPos(player->xChunk, player->zChunk), + player->level->dimension->id))) { + player->connection->teleport(player->x, player->y, player->z, + player->yRot, player->xRot, false); + // Force sending of the current chunk + player->doTick(true, true, true); + } - // 4J Stu - Fix for #64683 - Customer Encountered: TU7: Content: Gameplay: Potion effects are removed after using the Nether Portal - std::vector *activeEffects = player->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; + player->connection->teleport(player->x, player->y, player->z, player->yRot, + player->xRot); - player->connection->send(std::shared_ptr( new UpdateMobEffectPacket(player->entityId, effect) ) ); - } - delete activeEffects; - player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); + // 4J Stu - Fix for #64683 - Customer Encountered: TU7: Content: Gameplay: + // Potion effects are removed after using the Nether Portal + std::vector* activeEffects = player->getActiveEffects(); + for (AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); + ++it) { + MobEffectInstance* effect = *it; + + player->connection->send(std::shared_ptr( + new UpdateMobEffectPacket(player->entityId, effect))); + } + delete activeEffects; + player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); sendLevelInfo(player, newLevel); sendAllPlayerInfo(player); } -void PlayerList::tick() -{ - // 4J - brought changes to how often this is sent forward from 1.2.3 - if (++sendAllPlayerInfoIn > SEND_PLAYER_INFO_INTERVAL) - { +void PlayerList::tick() { + // 4J - brought changes to how often this is sent forward from 1.2.3 + if (++sendAllPlayerInfoIn > SEND_PLAYER_INFO_INTERVAL) { sendAllPlayerInfoIn = 0; } - if (sendAllPlayerInfoIn < players.size()) - { - std::shared_ptr op = players[sendAllPlayerInfoIn]; - //broadcastAll(std::shared_ptr( new PlayerInfoPacket(op->name, true, op->latency) ) ); - if( op->connection->getNetworkPlayer() ) - { - broadcastAll(std::shared_ptr( new PlayerInfoPacket( op ) ) ); - } - } + if (sendAllPlayerInfoIn < players.size()) { + std::shared_ptr op = players[sendAllPlayerInfoIn]; + // broadcastAll(std::shared_ptr( new + // PlayerInfoPacket(op->name, true, op->latency) ) ); + if (op->connection->getNetworkPlayer()) { + broadcastAll( + std::shared_ptr(new PlayerInfoPacket(op))); + } + } - EnterCriticalSection(&m_closePlayersCS); - while(!m_smallIdsToClose.empty()) - { - std::uint8_t smallId = m_smallIdsToClose.front(); - m_smallIdsToClose.pop_front(); + EnterCriticalSection(&m_closePlayersCS); + while (!m_smallIdsToClose.empty()) { + std::uint8_t smallId = m_smallIdsToClose.front(); + m_smallIdsToClose.pop_front(); - std::shared_ptr player = nullptr; + std::shared_ptr player = nullptr; - for(unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr p = players.at(i); - // 4J Stu - May be being a bit overprotective with all the NULL checks, but adding late in TU7 so want to be safe - if (p != NULL && p->connection != NULL && p->connection->connection != NULL && p->connection->connection->getSocket() != NULL && p->connection->connection->getSocket()->getSmallId() == smallId ) - { - player = p; - break; - } - } + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr p = players.at(i); + // 4J Stu - May be being a bit overprotective with all the NULL + // checks, but adding late in TU7 so want to be safe + if (p != NULL && p->connection != NULL && + p->connection->connection != NULL && + p->connection->connection->getSocket() != NULL && + p->connection->connection->getSocket()->getSmallId() == + smallId) { + player = p; + break; + } + } - if (player != NULL) - { - player->connection->disconnect( DisconnectPacket::eDisconnect_Closed ); - } - } - LeaveCriticalSection(&m_closePlayersCS); + if (player != NULL) { + player->connection->disconnect( + DisconnectPacket::eDisconnect_Closed); + } + } + LeaveCriticalSection(&m_closePlayersCS); - EnterCriticalSection(&m_kickPlayersCS); - while(!m_smallIdsToKick.empty()) - { - std::uint8_t smallId = m_smallIdsToKick.front(); - m_smallIdsToKick.pop_front(); - INetworkPlayer *selectedPlayer = g_NetworkManager.GetPlayerBySmallId(smallId); - if( selectedPlayer != NULL ) - { - if( selectedPlayer->IsLocal() != TRUE ) - { -//#ifdef _XBOX - PlayerUID xuid = selectedPlayer->GetUID(); - // Kick this player from the game - std::shared_ptr player = nullptr; + EnterCriticalSection(&m_kickPlayersCS); + while (!m_smallIdsToKick.empty()) { + std::uint8_t smallId = m_smallIdsToKick.front(); + m_smallIdsToKick.pop_front(); + INetworkPlayer* selectedPlayer = + g_NetworkManager.GetPlayerBySmallId(smallId); + if (selectedPlayer != NULL) { + if (selectedPlayer->IsLocal() != TRUE) { + // #ifdef _XBOX + PlayerUID xuid = selectedPlayer->GetUID(); + // Kick this player from the game + std::shared_ptr player = nullptr; - for(unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr p = players.at(i); - PlayerUID playersXuid = p->getOnlineXuid(); - if (p != NULL && ProfileManager.AreXUIDSEqual(playersXuid, xuid ) ) - { - player = p; - break; - } - } + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr p = players.at(i); + PlayerUID playersXuid = p->getOnlineXuid(); + if (p != NULL && + ProfileManager.AreXUIDSEqual(playersXuid, xuid)) { + player = p; + break; + } + } - if (player != NULL) - { - m_bannedXuids.push_back( player->getOnlineXuid() ); - // 4J Stu - If we have kicked a player, make sure that they have no privileges if they later try to join the world when trust players is off - player->enableAllPlayerPrivileges( false ); - player->connection->setWasKicked(); - player->connection->send( std::shared_ptr( new DisconnectPacket(DisconnectPacket::eDisconnect_Kicked) )); - } -//#endif - } - } - } - LeaveCriticalSection(&m_kickPlayersCS); + if (player != NULL) { + m_bannedXuids.push_back(player->getOnlineXuid()); + // 4J Stu - If we have kicked a player, make sure that they + // have no privileges if they later try to join the world + // when trust players is off + player->enableAllPlayerPrivileges(false); + player->connection->setWasKicked(); + player->connection->send( + std::shared_ptr(new DisconnectPacket( + DisconnectPacket::eDisconnect_Kicked))); + } + // #endif + } + } + } + LeaveCriticalSection(&m_kickPlayersCS); - // Check our receiving players, and if they are dead see if we can replace them - for(unsigned int dim = 0; dim < 2; ++dim) - { - for(unsigned int i = 0; i < receiveAllPlayers[dim].size(); ++i) - { - std::shared_ptr currentPlayer = receiveAllPlayers[dim][i]; - if(currentPlayer->removed) - { - std::shared_ptr newPlayer = findAlivePlayerOnSystem(currentPlayer); - if(newPlayer != NULL) - { - receiveAllPlayers[dim][i] = newPlayer; - app.DebugPrintf("Replacing primary player %ls with %ls in dimension %d\n", currentPlayer->name.c_str(), newPlayer->name.c_str(), dim); - } - } - } - } + // Check our receiving players, and if they are dead see if we can replace + // them + for (unsigned int dim = 0; dim < 2; ++dim) { + for (unsigned int i = 0; i < receiveAllPlayers[dim].size(); ++i) { + std::shared_ptr currentPlayer = + receiveAllPlayers[dim][i]; + if (currentPlayer->removed) { + std::shared_ptr newPlayer = + findAlivePlayerOnSystem(currentPlayer); + if (newPlayer != NULL) { + receiveAllPlayers[dim][i] = newPlayer; + app.DebugPrintf( + "Replacing primary player %ls with %ls in dimension " + "%d\n", + currentPlayer->name.c_str(), newPlayer->name.c_str(), + dim); + } + } + } + } } -bool PlayerList::isTrackingTile(int x, int y, int z, int dimension) -{ - return server->getLevel(dimension)->getChunkMap()->isTrackingTile(x, y, z); +bool PlayerList::isTrackingTile(int x, int y, int z, int dimension) { + return server->getLevel(dimension)->getChunkMap()->isTrackingTile(x, y, z); } -// 4J added - make sure that any tile updates for the chunk at this location get prioritised for sending -void PlayerList::prioritiseTileChanges(int x, int y, int z, int dimension) -{ - server->getLevel(dimension)->getChunkMap()->prioritiseTileChanges(x, y, z); +// 4J added - make sure that any tile updates for the chunk at this location get +// prioritised for sending +void PlayerList::prioritiseTileChanges(int x, int y, int z, int dimension) { + server->getLevel(dimension)->getChunkMap()->prioritiseTileChanges(x, y, z); } -void PlayerList::broadcastAll(std::shared_ptr packet) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerList::broadcastAll(std::shared_ptr packet) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; player->connection->send(packet); } } -void PlayerList::broadcastAll(std::shared_ptr packet, int dimension) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerList::broadcastAll(std::shared_ptr packet, int dimension) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; if (player->dimension == dimension) player->connection->send(packet); } } -std::wstring PlayerList::getPlayerNames() -{ +std::wstring PlayerList::getPlayerNames() { std::wstring msg; - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { if (i > 0) msg += L", "; msg += players[i]->name; } return msg; } -bool PlayerList::isWhiteListed(const std::wstring& name) -{ - return true; -} +bool PlayerList::isWhiteListed(const std::wstring& name) { return true; } -bool PlayerList::isOp(const std::wstring& name) -{ - return false; -} +bool PlayerList::isOp(const std::wstring& name) { return false; } -bool PlayerList::isOp(std::shared_ptr player) -{ - bool cheatsEnabled = app.GetGameHostOption(eGameHostOption_CheatsEnabled); +bool PlayerList::isOp(std::shared_ptr player) { + bool cheatsEnabled = app.GetGameHostOption(eGameHostOption_CheatsEnabled); #ifdef _DEBUG_MENUS_ENABLED - cheatsEnabled = cheatsEnabled || app.GetUseDPadForDebug(); + cheatsEnabled = cheatsEnabled || app.GetUseDPadForDebug(); #endif - INetworkPlayer *networkPlayer = player->connection->getNetworkPlayer(); - bool isOp = cheatsEnabled && (player->isModerator() || (networkPlayer != NULL && networkPlayer->IsHost())); - return isOp; + INetworkPlayer* networkPlayer = player->connection->getNetworkPlayer(); + bool isOp = + cheatsEnabled && (player->isModerator() || + (networkPlayer != NULL && networkPlayer->IsHost())); + return isOp; } -std::shared_ptr PlayerList::getPlayer(const std::wstring& name) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +std::shared_ptr PlayerList::getPlayer(const std::wstring& name) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; - if (p->name == name) // 4J - used to be case insensitive (using equalsIgnoreCase) - imagine we'll be shifting to XUIDs anyway - { + if (p->name == + name) // 4J - used to be case insensitive (using equalsIgnoreCase) + // - imagine we'll be shifting to XUIDs anyway + { return p; } } @@ -1004,83 +1081,77 @@ std::shared_ptr PlayerList::getPlayer(const std::wstring& name) } // 4J Added -std::shared_ptr PlayerList::getPlayer(PlayerUID uid) -{ - for (unsigned int i = 0; i < players.size(); i++) - { +std::shared_ptr PlayerList::getPlayer(PlayerUID uid) { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; - if (p->getXuid() == uid || p->getOnlineXuid() == uid) // 4J - used to be case insensitive (using equalsIgnoreCase) - imagine we'll be shifting to XUIDs anyway - { + if (p->getXuid() == uid || + p->getOnlineXuid() == uid) // 4J - used to be case insensitive + // (using equalsIgnoreCase) - imagine + // we'll be shifting to XUIDs anyway + { return p; } } return nullptr; } -void PlayerList::sendMessage(const std::wstring& name, const std::wstring& message) -{ +void PlayerList::sendMessage(const std::wstring& name, + const std::wstring& message) { std::shared_ptr player = getPlayer(name); - if (player != NULL) - { - player->connection->send( std::shared_ptr( new ChatPacket(message) ) ); + if (player != NULL) { + player->connection->send( + std::shared_ptr(new ChatPacket(message))); } } -void PlayerList::broadcast(double x, double y, double z, double range, int dimension, std::shared_ptr packet) -{ - broadcast(nullptr, x, y, z, range, dimension, packet); +void PlayerList::broadcast(double x, double y, double z, double range, + int dimension, std::shared_ptr packet) { + broadcast(nullptr, x, y, z, range, dimension, packet); } -void PlayerList::broadcast(std::shared_ptr except, double x, double y, double z, double range, int dimension, std::shared_ptr packet) -{ - // 4J - altered so that we don't send to the same machine more than once. Add the source player to the machines we have "sent" to as it doesn't need to go to that - // machine either - std::vector< std::shared_ptr > sentTo; - if( except != NULL ) - { - sentTo.push_back(std::dynamic_pointer_cast(except)); - } +void PlayerList::broadcast(std::shared_ptr except, double x, double y, + double z, double range, int dimension, + std::shared_ptr packet) { + // 4J - altered so that we don't send to the same machine more than once. + // Add the source player to the machines we have "sent" to as it doesn't + // need to go to that machine either + std::vector > sentTo; + if (except != NULL) { + sentTo.push_back(std::dynamic_pointer_cast(except)); + } - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; if (p == except) continue; if (p->dimension != dimension) continue; - // 4J - don't send to the same machine more than once - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer = p->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - } - } - } - } - if( dontSend ) - { - continue; - } - + // 4J - don't send to the same machine more than once + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = p->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + } + } + } + } + if (dontSend) { + continue; + } double xd = x - p->x; double yd = y - p->y; double zd = z - p->z; - if (xd * xd + yd * yd + zd * zd < range * range) - { -#if 0 // _DEBUG + if (xd * xd + yd * yd + zd * zd < range * range) { +#if 0 // _DEBUG std::shared_ptr SoundPacket= std::dynamic_pointer_cast(packet); if(SoundPacket) @@ -1092,364 +1163,343 @@ void PlayerList::broadcast(std::shared_ptr except, double x, double y, d } #endif p->connection->send(packet); - sentTo.push_back( p ); + sentTo.push_back(p); } } - } -void PlayerList::broadcastToAllOps(const std::wstring& message) -{ - std::shared_ptr chatPacket = std::shared_ptr( new ChatPacket(message) ); - for (unsigned int i = 0; i < players.size(); i++) - { +void PlayerList::broadcastToAllOps(const std::wstring& message) { + std::shared_ptr chatPacket = + std::shared_ptr(new ChatPacket(message)); + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr p = players[i]; - if (isOp(p->name)) - { + if (isOp(p->name)) { p->connection->send(chatPacket); } } } -bool PlayerList::sendTo(const std::wstring& name, std::shared_ptr packet) -{ +bool PlayerList::sendTo(const std::wstring& name, + std::shared_ptr packet) { std::shared_ptr player = getPlayer(name); - if (player != NULL) - { + if (player != NULL) { player->connection->send(packet); return true; } return false; } -void PlayerList::saveAll(ProgressListener *progressListener, bool bDeleteGuestMaps /*= false*/) -{ - if(progressListener != NULL) progressListener->progressStart(IDS_PROGRESS_SAVING_PLAYERS); - // 4J - playerIo can be NULL if we have have to exit a game really early on due to network failure - if(playerIo) - { - playerIo->saveAllCachedData(); - for (unsigned int i = 0; i < players.size(); i++) - { - playerIo->save(players[i]); - - //4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map - if(bDeleteGuestMaps && players[i]->isGuest()) playerIo->deleteMapFilesForPlayer(players[i]); +void PlayerList::saveAll(ProgressListener* progressListener, + bool bDeleteGuestMaps /*= false*/) { + if (progressListener != NULL) + progressListener->progressStart(IDS_PROGRESS_SAVING_PLAYERS); + // 4J - playerIo can be NULL if we have have to exit a game really early on + // due to network failure + if (playerIo) { + playerIo->saveAllCachedData(); + for (unsigned int i = 0; i < players.size(); i++) { + playerIo->save(players[i]); - if(progressListener != NULL) progressListener->progressStagePercentage((i * 100)/ ((int)players.size())); - } - playerIo->clearOldPlayerFiles(); - playerIo->saveMapIdLookup(); - } -} + // 4J Stu - We don't want to save the map data for guests, so when + // we are sure that the player is gone delete the map + if (bDeleteGuestMaps && players[i]->isGuest()) + playerIo->deleteMapFilesForPlayer(players[i]); -void PlayerList::whiteList(const std::wstring& playerName) -{ -} - -void PlayerList::blackList(const std::wstring& playerName) -{ -} - -void PlayerList::reloadWhitelist() -{ -} - -void PlayerList::sendLevelInfo(std::shared_ptr player, ServerLevel *level) -{ - player->connection->send( std::shared_ptr( new SetTimePacket(level->getTime()) ) ); - if (level->isRaining()) - { - player->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::START_RAINING, 0) ) ); + if (progressListener != NULL) + progressListener->progressStagePercentage( + (i * 100) / ((int)players.size())); + } + playerIo->clearOldPlayerFiles(); + playerIo->saveMapIdLookup(); } - else - { - // 4J Stu - Fix for #44836 - Customer Encountered: Out of Sync Weather [A-10] - // If it was raining when the player left the level, and is now not raining we need to make sure that state is updated - player->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::STOP_RAINING, 0) ) ); - } - - // send the stronghold position if there is one - if((level->dimension->id==0) && level->getLevelData()->getHasStronghold()) - { - player->connection->send( std::shared_ptr( new XZPacket(XZPacket::STRONGHOLD,level->getLevelData()->getXStronghold(),level->getLevelData()->getZStronghold()) ) ); - } } -void PlayerList::sendAllPlayerInfo(std::shared_ptr player) -{ +void PlayerList::whiteList(const std::wstring& playerName) {} + +void PlayerList::blackList(const std::wstring& playerName) {} + +void PlayerList::reloadWhitelist() {} + +void PlayerList::sendLevelInfo(std::shared_ptr player, + ServerLevel* level) { + player->connection->send( + std::shared_ptr(new SetTimePacket(level->getTime()))); + if (level->isRaining()) { + player->connection->send(std::shared_ptr( + new GameEventPacket(GameEventPacket::START_RAINING, 0))); + } else { + // 4J Stu - Fix for #44836 - Customer Encountered: Out of Sync Weather + // [A-10] If it was raining when the player left the level, and is now + // not raining we need to make sure that state is updated + player->connection->send(std::shared_ptr( + new GameEventPacket(GameEventPacket::STOP_RAINING, 0))); + } + + // send the stronghold position if there is one + if ((level->dimension->id == 0) && + level->getLevelData()->getHasStronghold()) { + player->connection->send(std::shared_ptr(new XZPacket( + XZPacket::STRONGHOLD, level->getLevelData()->getXStronghold(), + level->getLevelData()->getZStronghold()))); + } +} + +void PlayerList::sendAllPlayerInfo(std::shared_ptr player) { player->refreshContainer(player->inventoryMenu); player->resetSentInfo(); } -int PlayerList::getPlayerCount() -{ - return (int)players.size(); +int PlayerList::getPlayerCount() { return (int)players.size(); } + +int PlayerList::getPlayerCount(ServerLevel* level) { + int count = 0; + + for (AUTO_VAR(it, players.begin()); it != players.end(); ++it) { + if ((*it)->level == level) ++count; + } + + return count; } -int PlayerList::getPlayerCount(ServerLevel *level) -{ - int count = 0; +int PlayerList::getMaxPlayers() { return maxPlayers; } - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) - { - if( (*it)->level == level ) ++count; - } +MinecraftServer* PlayerList::getServer() { return server; } - return count; +int PlayerList::getViewDistance() { return viewDistance; } + +void PlayerList::setOverrideGameMode(GameType* gameMode) { + this->overrideGameMode = gameMode; } -int PlayerList::getMaxPlayers() -{ - return maxPlayers; +void PlayerList::updatePlayerGameMode(std::shared_ptr newPlayer, + std::shared_ptr oldPlayer, + Level* level) { + // reset the player's game mode (first pick from old, then copy level if + // necessary) + if (oldPlayer != NULL) { + newPlayer->gameMode->setGameModeForPlayer( + oldPlayer->gameMode->getGameModeForPlayer()); + } else if (overrideGameMode != NULL) { + newPlayer->gameMode->setGameModeForPlayer(overrideGameMode); + } + newPlayer->gameMode->updateGameMode(level->getLevelData()->getGameType()); } -MinecraftServer *PlayerList::getServer() -{ - return server; +void PlayerList::setAllowCheatsForAllPlayers(bool allowCommands) { + this->allowCheatsForAllPlayers = allowCommands; } -int PlayerList::getViewDistance() -{ - return viewDistance; +std::shared_ptr PlayerList::findAlivePlayerOnSystem( + std::shared_ptr player) { + int dimIndex, playerDim; + dimIndex = playerDim = player->dimension; + if (dimIndex == -1) + dimIndex = 1; + else if (dimIndex == 1) + dimIndex = 2; + + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer != NULL) { + for (AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) { + std::shared_ptr newPlayer = *itP; + + INetworkPlayer* otherPlayer = + newPlayer->connection->getNetworkPlayer(); + + if (!newPlayer->removed && newPlayer != player && + newPlayer->dimension == playerDim && otherPlayer != NULL && + otherPlayer->IsSameSystem(thisPlayer)) { + return newPlayer; + } + } + } + + return nullptr; } -void PlayerList::setOverrideGameMode(GameType *gameMode) -{ - this->overrideGameMode = gameMode; -} - -void PlayerList::updatePlayerGameMode(std::shared_ptr newPlayer, std::shared_ptr oldPlayer, Level *level) -{ - - // reset the player's game mode (first pick from old, then copy level if - // necessary) - if (oldPlayer != NULL) - { - newPlayer->gameMode->setGameModeForPlayer(oldPlayer->gameMode->getGameModeForPlayer()); - } - else if (overrideGameMode != NULL) - { - newPlayer->gameMode->setGameModeForPlayer(overrideGameMode); - } - newPlayer->gameMode->updateGameMode(level->getLevelData()->getGameType()); -} - -void PlayerList::setAllowCheatsForAllPlayers(bool allowCommands) -{ - this->allowCheatsForAllPlayers = allowCommands; -} - -std::shared_ptr PlayerList::findAlivePlayerOnSystem(std::shared_ptr player) -{ - int dimIndex, playerDim; - dimIndex = playerDim = player->dimension; - if( dimIndex == -1 ) dimIndex = 1; - else if( dimIndex == 1) dimIndex = 2; - - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL ) - { - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) - { - std::shared_ptr newPlayer = *itP; - - INetworkPlayer *otherPlayer = newPlayer->connection->getNetworkPlayer(); - - if( !newPlayer->removed && - newPlayer != player && - newPlayer->dimension == playerDim && - otherPlayer != NULL && - otherPlayer->IsSameSystem( thisPlayer ) - ) - { - return newPlayer; - } - } - } - - return nullptr; -} - -void PlayerList::removePlayerFromReceiving(std::shared_ptr player, bool usePlayerDimension /*= true*/, int dimension /*= 0*/) -{ - int dimIndex, playerDim; - dimIndex = playerDim = usePlayerDimension ? player->dimension : dimension; - if( dimIndex == -1 ) dimIndex = 1; - else if( dimIndex == 1) dimIndex = 2; +void PlayerList::removePlayerFromReceiving(std::shared_ptr player, + bool usePlayerDimension /*= true*/, + int dimension /*= 0*/) { + int dimIndex, playerDim; + dimIndex = playerDim = usePlayerDimension ? player->dimension : dimension; + if (dimIndex == -1) + dimIndex = 1; + else if (dimIndex == 1) + dimIndex = 2; #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Requesting remove player %ls as primary in dimension %d\n", player->name.c_str(), dimIndex); + app.DebugPrintf("Requesting remove player %ls as primary in dimension %d\n", + player->name.c_str(), dimIndex); #endif - bool playerRemoved = false; + bool playerRemoved = false; - AUTO_VAR(it, find( receiveAllPlayers[dimIndex].begin(), receiveAllPlayers[dimIndex].end(), player)); - if( it != receiveAllPlayers[dimIndex].end() ) - { + AUTO_VAR(it, find(receiveAllPlayers[dimIndex].begin(), + receiveAllPlayers[dimIndex].end(), player)); + if (it != receiveAllPlayers[dimIndex].end()) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Removing player %ls as primary in dimension %d\n", player->name.c_str(), dimIndex); + app.DebugPrintf( + "Remove: Removing player %ls as primary in dimension %d\n", + player->name.c_str(), dimIndex); #endif - receiveAllPlayers[dimIndex].erase(it); - playerRemoved = true; - } + receiveAllPlayers[dimIndex].erase(it); + playerRemoved = true; + } - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL && playerRemoved ) - { - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) - { - std::shared_ptr newPlayer = *itP; + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); + if (thisPlayer != NULL && playerRemoved) { + for (AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) { + std::shared_ptr newPlayer = *itP; - INetworkPlayer *otherPlayer = newPlayer->connection->getNetworkPlayer(); + INetworkPlayer* otherPlayer = + newPlayer->connection->getNetworkPlayer(); - if( newPlayer != player && - newPlayer->dimension == playerDim && - otherPlayer != NULL && - otherPlayer->IsSameSystem( thisPlayer ) - ) - { + if (newPlayer != player && newPlayer->dimension == playerDim && + otherPlayer != NULL && otherPlayer->IsSameSystem(thisPlayer)) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Adding player %ls as primary in dimension %d\n", newPlayer->name.c_str(), dimIndex); + app.DebugPrintf( + "Remove: Adding player %ls as primary in dimension %d\n", + newPlayer->name.c_str(), dimIndex); #endif - receiveAllPlayers[dimIndex].push_back( newPlayer ); - break; - } - } - } - else if( thisPlayer == NULL ) - { + receiveAllPlayers[dimIndex].push_back(newPlayer); + break; + } + } + } else if (thisPlayer == NULL) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Qnet player for %ls was NULL so re-checking all players\n", player->name.c_str() ); + app.DebugPrintf( + "Remove: Qnet player for %ls was NULL so re-checking all players\n", + player->name.c_str()); #endif - // 4J Stu - Something went wrong, or possibly the QNet player left before we got here. - // Re-check all active players and make sure they have someone on their system to receive all packets - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) - { - std::shared_ptr newPlayer = *itP; - INetworkPlayer *checkingPlayer = newPlayer->connection->getNetworkPlayer(); + // 4J Stu - Something went wrong, or possibly the QNet player left + // before we got here. Re-check all active players and make sure they + // have someone on their system to receive all packets + for (AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) { + std::shared_ptr newPlayer = *itP; + INetworkPlayer* checkingPlayer = + newPlayer->connection->getNetworkPlayer(); - if( checkingPlayer != NULL ) - { - int newPlayerDim = 0; - if( newPlayer->dimension == -1 ) newPlayerDim = 1; - else if( newPlayer->dimension == 1) newPlayerDim = 2; - bool foundPrimary = false; - for(AUTO_VAR(it, receiveAllPlayers[newPlayerDim].begin()); it != receiveAllPlayers[newPlayerDim].end(); ++it) - { - std::shared_ptr primaryPlayer = *it; - INetworkPlayer *primPlayer = primaryPlayer->connection->getNetworkPlayer(); - if(primPlayer != NULL && checkingPlayer->IsSameSystem( primPlayer ) ) - { - foundPrimary = true; - break; - } - } - if(!foundPrimary) - { + if (checkingPlayer != NULL) { + int newPlayerDim = 0; + if (newPlayer->dimension == -1) + newPlayerDim = 1; + else if (newPlayer->dimension == 1) + newPlayerDim = 2; + bool foundPrimary = false; + for (AUTO_VAR(it, receiveAllPlayers[newPlayerDim].begin()); + it != receiveAllPlayers[newPlayerDim].end(); ++it) { + std::shared_ptr primaryPlayer = *it; + INetworkPlayer* primPlayer = + primaryPlayer->connection->getNetworkPlayer(); + if (primPlayer != NULL && + checkingPlayer->IsSameSystem(primPlayer)) { + foundPrimary = true; + break; + } + } + if (!foundPrimary) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Remove: Adding player %ls as primary in dimension %d\n", newPlayer->name.c_str(), newPlayerDim); + app.DebugPrintf( + "Remove: Adding player %ls as primary in dimension " + "%d\n", + newPlayer->name.c_str(), newPlayerDim); #endif - receiveAllPlayers[newPlayerDim].push_back( newPlayer ); - } - } - } - } + receiveAllPlayers[newPlayerDim].push_back(newPlayer); + } + } + } + } } -void PlayerList::addPlayerToReceiving(std::shared_ptr player) -{ - int playerDim = 0; - if( player->dimension == -1 ) playerDim = 1; - else if( player->dimension == 1) playerDim = 2; +void PlayerList::addPlayerToReceiving(std::shared_ptr player) { + int playerDim = 0; + if (player->dimension == -1) + playerDim = 1; + else if (player->dimension == 1) + playerDim = 2; #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Requesting add player %ls as primary in dimension %d\n", player->name.c_str(), playerDim); + app.DebugPrintf("Requesting add player %ls as primary in dimension %d\n", + player->name.c_str(), playerDim); #endif - bool shouldAddPlayer = true; + bool shouldAddPlayer = true; - INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); + INetworkPlayer* thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { + if (thisPlayer == NULL) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Add: Qnet player for player %ls is NULL so not adding them\n", player->name.c_str() ); + app.DebugPrintf( + "Add: Qnet player for player %ls is NULL so not adding them\n", + player->name.c_str()); #endif - shouldAddPlayer = false; - } - else - { - for(AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); it != receiveAllPlayers[playerDim].end(); ++it) - { - std::shared_ptr oldPlayer = *it; - INetworkPlayer *checkingPlayer = oldPlayer->connection->getNetworkPlayer(); - if(checkingPlayer != NULL && checkingPlayer->IsSameSystem( thisPlayer ) ) - { - shouldAddPlayer = false; - break; - } - } - } - - if( shouldAddPlayer ) - { + shouldAddPlayer = false; + } else { + for (AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); + it != receiveAllPlayers[playerDim].end(); ++it) { + std::shared_ptr oldPlayer = *it; + INetworkPlayer* checkingPlayer = + oldPlayer->connection->getNetworkPlayer(); + if (checkingPlayer != NULL && + checkingPlayer->IsSameSystem(thisPlayer)) { + shouldAddPlayer = false; + break; + } + } + } + + if (shouldAddPlayer) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Add: Adding player %ls as primary in dimension %d\n", player->name.c_str(), playerDim); + app.DebugPrintf("Add: Adding player %ls as primary in dimension %d\n", + player->name.c_str(), playerDim); #endif - receiveAllPlayers[playerDim].push_back( player ); - } + receiveAllPlayers[playerDim].push_back(player); + } } -bool PlayerList::canReceiveAllPackets(std::shared_ptr player) -{ - int playerDim = 0; - if( player->dimension == -1 ) playerDim = 1; - else if( player->dimension == 1) playerDim = 2; - for(AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); it != receiveAllPlayers[playerDim].end(); ++it) - { - std::shared_ptr newPlayer = *it; - if(newPlayer == player) - { - return true; - } - } - return false; +bool PlayerList::canReceiveAllPackets(std::shared_ptr player) { + int playerDim = 0; + if (player->dimension == -1) + playerDim = 1; + else if (player->dimension == 1) + playerDim = 2; + for (AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); + it != receiveAllPlayers[playerDim].end(); ++it) { + std::shared_ptr newPlayer = *it; + if (newPlayer == player) { + return true; + } + } + return false; } -void PlayerList::kickPlayerByShortId(std::uint8_t networkSmallId) -{ - EnterCriticalSection(&m_kickPlayersCS); - m_smallIdsToKick.push_back(networkSmallId); - LeaveCriticalSection(&m_kickPlayersCS); +void PlayerList::kickPlayerByShortId(std::uint8_t networkSmallId) { + EnterCriticalSection(&m_kickPlayersCS); + m_smallIdsToKick.push_back(networkSmallId); + LeaveCriticalSection(&m_kickPlayersCS); } -void PlayerList::closePlayerConnectionBySmallId(std::uint8_t networkSmallId) -{ - EnterCriticalSection(&m_closePlayersCS); - m_smallIdsToClose.push_back(networkSmallId); - LeaveCriticalSection(&m_closePlayersCS); +void PlayerList::closePlayerConnectionBySmallId(std::uint8_t networkSmallId) { + EnterCriticalSection(&m_closePlayersCS); + m_smallIdsToClose.push_back(networkSmallId); + LeaveCriticalSection(&m_closePlayersCS); } -bool PlayerList::isXuidBanned(PlayerUID xuid) -{ - if( xuid == INVALID_XUID ) return false; +bool PlayerList::isXuidBanned(PlayerUID xuid) { + if (xuid == INVALID_XUID) return false; - bool banned = false; + bool banned = false; - for( AUTO_VAR(it, m_bannedXuids.begin()); it != m_bannedXuids.end(); ++it ) - { - if( ProfileManager.AreXUIDSEqual( xuid, *it ) ) - { - banned = true; - break; - } - } + for (AUTO_VAR(it, m_bannedXuids.begin()); it != m_bannedXuids.end(); ++it) { + if (ProfileManager.AreXUIDSEqual(xuid, *it)) { + banned = true; + break; + } + } - return banned; + return banned; } // AP added for Vita so the range can be increased once the level starts -void PlayerList::setViewDistance(int newViewDistance) -{ - viewDistance = newViewDistance; +void PlayerList::setViewDistance(int newViewDistance) { + viewDistance = newViewDistance; } diff --git a/Minecraft.Client/Network/PlayerList.h b/Minecraft.Client/Network/PlayerList.h index 50a00ea91..d810bcebe 100644 --- a/Minecraft.Client/Network/PlayerList.h +++ b/Minecraft.Client/Network/PlayerList.h @@ -15,114 +15,136 @@ class ProgressListener; class GameType; class LoginPacket; - - -class PlayerList -{ +class PlayerList { private: - static const int SEND_PLAYER_INFO_INTERVAL = 20 * 10; // 4J - brought forward from 1.2.3 -// public static Logger logger = Logger.getLogger("Minecraft"); + static const int SEND_PLAYER_INFO_INTERVAL = + 20 * 10; // 4J - brought forward from 1.2.3 + // public static Logger logger = Logger.getLogger("Minecraft"); public: - std::vector > players; + std::vector > players; private: - MinecraftServer *server; + MinecraftServer* server; unsigned int maxPlayers; - // 4J Added - std::vector m_bannedXuids; - std::deque m_smallIdsToKick; - CRITICAL_SECTION m_kickPlayersCS; - std::deque m_smallIdsToClose; - CRITICAL_SECTION m_closePlayersCS; -/* 4J - removed - Set bans = new HashSet(); - Set ipBans = new HashSet(); - Set ops = new HashSet(); - Set whitelist = new HashSet(); - File banFile, ipBanFile, opFile, whiteListFile; - */ - PlayerIO *playerIo; + // 4J Added + std::vector m_bannedXuids; + std::deque m_smallIdsToKick; + CRITICAL_SECTION m_kickPlayersCS; + std::deque m_smallIdsToClose; + CRITICAL_SECTION m_closePlayersCS; + /* 4J - removed + Set bans = new HashSet(); + Set ipBans = new HashSet(); + Set ops = new HashSet(); + Set whitelist = new HashSet(); + File banFile, ipBanFile, opFile, whiteListFile; + */ + PlayerIO* playerIo; bool doWhiteList; - GameType *overrideGameMode; - bool allowCheatsForAllPlayers; - int viewDistance; + GameType* overrideGameMode; + bool allowCheatsForAllPlayers; + int viewDistance; - int sendAllPlayerInfoIn; + int sendAllPlayerInfoIn; + + // 4J Added to maintain which players in which dimensions can receive all + // packet types + std::vector > receiveAllPlayers[3]; - // 4J Added to maintain which players in which dimensions can receive all packet types - std::vector > receiveAllPlayers[3]; private: - std::shared_ptr findAlivePlayerOnSystem(std::shared_ptr currentPlayer); + std::shared_ptr findAlivePlayerOnSystem( + std::shared_ptr currentPlayer); public: - void removePlayerFromReceiving(std::shared_ptr player, bool usePlayerDimension = true, int dimension = 0); - void addPlayerToReceiving(std::shared_ptr player); - bool canReceiveAllPackets(std::shared_ptr player); + void removePlayerFromReceiving(std::shared_ptr player, + bool usePlayerDimension = true, + int dimension = 0); + void addPlayerToReceiving(std::shared_ptr player); + bool canReceiveAllPackets(std::shared_ptr player); public: - PlayerList(MinecraftServer *server); - ~PlayerList(); - void placeNewPlayer(Connection *connection, std::shared_ptr player, std::shared_ptr packet); + PlayerList(MinecraftServer* server); + ~PlayerList(); + void placeNewPlayer(Connection* connection, + std::shared_ptr player, + std::shared_ptr packet); void setLevel(ServerLevelArray levels); - void changeDimension(std::shared_ptr player, ServerLevel *from); + void changeDimension(std::shared_ptr player, + ServerLevel* from); int getMaxRange(); - bool load(std::shared_ptr player); // 4J Changed return val to bool to check if new player or loaded player + bool load(std::shared_ptr + player); // 4J Changed return val to bool to check if new + // player or loaded player protected: - void save(std::shared_ptr player); + void save(std::shared_ptr player); + public: - void validatePlayerSpawnPosition(std::shared_ptr player); // 4J Added + void validatePlayerSpawnPosition( + std::shared_ptr player); // 4J Added void add(std::shared_ptr player); void move(std::shared_ptr player); void remove(std::shared_ptr player); - std::shared_ptr getPlayerForLogin(PendingConnection *pendingConnection, const std::wstring& userName, PlayerUID xuid, PlayerUID OnlineXuid); - std::shared_ptr respawn(std::shared_ptr serverPlayer, int targetDimension, bool keepAllPlayerData); - void toggleDimension(std::shared_ptr player, int targetDimension); + std::shared_ptr getPlayerForLogin( + PendingConnection* pendingConnection, const std::wstring& userName, + PlayerUID xuid, PlayerUID OnlineXuid); + std::shared_ptr respawn( + std::shared_ptr serverPlayer, int targetDimension, + bool keepAllPlayerData); + void toggleDimension(std::shared_ptr player, + int targetDimension); void tick(); - bool isTrackingTile(int x, int y, int z, int dimension); // 4J added - void prioritiseTileChanges(int x, int y, int z, int dimension); // 4J added + bool isTrackingTile(int x, int y, int z, int dimension); // 4J added + void prioritiseTileChanges(int x, int y, int z, int dimension); // 4J added void broadcastAll(std::shared_ptr packet); void broadcastAll(std::shared_ptr packet, int dimension); std::wstring getPlayerNames(); public: - bool isWhiteListed(const std::wstring& name); + bool isWhiteListed(const std::wstring& name); bool isOp(const std::wstring& name); - bool isOp(std::shared_ptr player); // 4J Added + bool isOp(std::shared_ptr player); // 4J Added std::shared_ptr getPlayer(const std::wstring& name); - std::shared_ptr getPlayer(PlayerUID uid); + std::shared_ptr getPlayer(PlayerUID uid); void sendMessage(const std::wstring& name, const std::wstring& message); - void broadcast(double x, double y, double z, double range, int dimension, std::shared_ptr packet); - void broadcast(std::shared_ptr except, double x, double y, double z, double range, int dimension, std::shared_ptr packet); + void broadcast(double x, double y, double z, double range, int dimension, + std::shared_ptr packet); + void broadcast(std::shared_ptr except, double x, double y, double z, + double range, int dimension, std::shared_ptr packet); void broadcastToAllOps(const std::wstring& message); bool sendTo(const std::wstring& name, std::shared_ptr packet); - // 4J Added ProgressListener *progressListener param and bDeleteGuestMaps param - void saveAll(ProgressListener *progressListener, bool bDeleteGuestMaps = false); + // 4J Added ProgressListener *progressListener param and bDeleteGuestMaps + // param + void saveAll(ProgressListener* progressListener, + bool bDeleteGuestMaps = false); void whiteList(const std::wstring& playerName); void blackList(const std::wstring& playerName); -// Set getWhiteList(); / 4J removed + // Set getWhiteList(); / 4J removed void reloadWhitelist(); - void sendLevelInfo(std::shared_ptr player, ServerLevel *level); + void sendLevelInfo(std::shared_ptr player, + ServerLevel* level); void sendAllPlayerInfo(std::shared_ptr player); - int getPlayerCount(); - int getPlayerCount(ServerLevel *level); // 4J Added - int getMaxPlayers(); - MinecraftServer *getServer(); - int getViewDistance(); - void setOverrideGameMode(GameType *gameMode); + int getPlayerCount(); + int getPlayerCount(ServerLevel* level); // 4J Added + int getMaxPlayers(); + MinecraftServer* getServer(); + int getViewDistance(); + void setOverrideGameMode(GameType* gameMode); private: - void updatePlayerGameMode(std::shared_ptr newPlayer, std::shared_ptr oldPlayer, Level *level); + void updatePlayerGameMode(std::shared_ptr newPlayer, + std::shared_ptr oldPlayer, + Level* level); public: - void setAllowCheatsForAllPlayers(bool allowCommands); + void setAllowCheatsForAllPlayers(bool allowCommands); - // 4J Added - void kickPlayerByShortId(std::uint8_t networkSmallId); - void closePlayerConnectionBySmallId(std::uint8_t networkSmallId); - bool isXuidBanned(PlayerUID xuid); - // AP added for Vita so the range can be increased once the level starts - void setViewDistance(int newViewDistance); + // 4J Added + void kickPlayerByShortId(std::uint8_t networkSmallId); + void closePlayerConnectionBySmallId(std::uint8_t networkSmallId); + bool isXuidBanned(PlayerUID xuid); + // AP added for Vita so the range can be increased once the level starts + void setViewDistance(int newViewDistance); }; diff --git a/Minecraft.Client/Network/ServerChunkCache.cpp b/Minecraft.Client/Network/ServerChunkCache.cpp index e05c890b1..09d4f6ce3 100644 --- a/Minecraft.Client/Network/ServerChunkCache.cpp +++ b/Minecraft.Client/Network/ServerChunkCache.cpp @@ -12,956 +12,1014 @@ #include "../../Minecraft.World/IO/Streams/Compression.h" #include "../../Minecraft.World/Level/Storage/OldChunkStorage.h" -ServerChunkCache::ServerChunkCache(ServerLevel *level, ChunkStorage *storage, ChunkSource *source) -{ - XZSIZE = source->m_XZSize; // 4J Added - XZOFFSET = XZSIZE/2; // 4J Added +ServerChunkCache::ServerChunkCache(ServerLevel* level, ChunkStorage* storage, + ChunkSource* source) { + XZSIZE = source->m_XZSize; // 4J Added + XZOFFSET = XZSIZE / 2; // 4J Added - autoCreate = false; // 4J added - - emptyChunk = new EmptyLevelChunk(level, byteArray( Level::CHUNK_TILE_COUNT ), 0, 0); + autoCreate = false; // 4J added + + emptyChunk = + new EmptyLevelChunk(level, byteArray(Level::CHUNK_TILE_COUNT), 0, 0); this->level = level; this->storage = storage; this->source = source; - this->m_XZSize = source->m_XZSize; + this->m_XZSize = source->m_XZSize; - this->cache = new LevelChunk *[XZSIZE * XZSIZE]; - memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk *)); + this->cache = new LevelChunk*[XZSIZE * XZSIZE]; + memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*)); #ifdef _LARGE_WORLDS - m_unloadedCache = new LevelChunk *[XZSIZE * XZSIZE]; - memset(m_unloadedCache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk *)); + m_unloadedCache = new LevelChunk*[XZSIZE * XZSIZE]; + memset(m_unloadedCache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*)); #endif - InitializeCriticalSectionAndSpinCount(&m_csLoadCreate,4000); + InitializeCriticalSectionAndSpinCount(&m_csLoadCreate, 4000); } // 4J-PB added -ServerChunkCache::~ServerChunkCache() -{ - delete emptyChunk; - delete cache; - delete source; +ServerChunkCache::~ServerChunkCache() { + delete emptyChunk; + delete cache; + delete source; #ifdef _LARGE_WORLDS - for(unsigned int i = 0; i < XZSIZE * XZSIZE; ++i) - { - delete m_unloadedCache[i]; - } - delete m_unloadedCache; + for (unsigned int i = 0; i < XZSIZE * XZSIZE; ++i) { + delete m_unloadedCache[i]; + } + delete m_unloadedCache; #endif - AUTO_VAR(itEnd, m_loadedChunkList.end()); - for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) - delete *it; - DeleteCriticalSection(&m_csLoadCreate); + AUTO_VAR(itEnd, m_loadedChunkList.end()); + for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) delete *it; + DeleteCriticalSection(&m_csLoadCreate); } -bool ServerChunkCache::hasChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - // 4J Stu - Request for chunks outside the range always return an emptyChunk, so just return true here to say we have it - // If we return false entities less than 2 chunks from the edge do not tick properly due to them requiring a certain radius - // of chunks around them when they tick - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return true; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return true; - int idx = ix * XZSIZE + iz; - LevelChunk *lc = cache[idx]; - if( lc == NULL ) return false; - return true; +bool ServerChunkCache::hasChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + // 4J Stu - Request for chunks outside the range always return an + // emptyChunk, so just return true here to say we have it If we return false + // entities less than 2 chunks from the edge do not tick properly due to + // them requiring a certain radius of chunks around them when they tick + if ((ix < 0) || (ix >= XZSIZE)) return true; + if ((iz < 0) || (iz >= XZSIZE)) return true; + int idx = ix * XZSIZE + iz; + LevelChunk* lc = cache[idx]; + if (lc == NULL) return false; + return true; } -std::vector *ServerChunkCache::getLoadedChunkList() -{ - return &m_loadedChunkList; +std::vector* ServerChunkCache::getLoadedChunkList() { + return &m_loadedChunkList; } -void ServerChunkCache::drop(int x, int z) -{ - // 4J - we're not dropping things anymore now that we have a fixed sized cache +void ServerChunkCache::drop(int x, int z) { + // 4J - we're not dropping things anymore now that we have a fixed sized + // cache #ifdef _LARGE_WORLDS - bool canDrop = false; -// if (level->dimension->mayRespawn()) -// { -// Pos *spawnPos = level->getSharedSpawnPos(); -// int xd = x * 16 + 8 - spawnPos->x; -// int zd = z * 16 + 8 - spawnPos->z; -// delete spawnPos; -// int r = 128; -// if (xd < -r || xd > r || zd < -r || zd > r) -// { -// canDrop = true; -//} -// } -// else - { - canDrop = true; - } - if(canDrop) - { - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return; - int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; + bool canDrop = false; + // if (level->dimension->mayRespawn()) + // { + // Pos *spawnPos = level->getSharedSpawnPos(); + // int xd = x * 16 + 8 - spawnPos->x; + // int zd = z * 16 + 8 - spawnPos->z; + // delete spawnPos; + // int r = 128; + // if (xd < -r || xd > r || zd < -r || zd > r) + // { + // canDrop = true; + //} + // } + // else + { + canDrop = true; + } + if (canDrop) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return; + if ((iz < 0) || (iz >= XZSIZE)) return; + int idx = ix * XZSIZE + iz; + LevelChunk* chunk = cache[idx]; - if(chunk) - { - m_toDrop.push_back(chunk); - } - } + if (chunk) { + m_toDrop.push_back(chunk); + } + } #endif } -void ServerChunkCache::dropAll() -{ +void ServerChunkCache::dropAll() { #ifdef _LARGE_WORLDS - for (LevelChunk *chunk : m_loadedChunkList) - { - drop(chunk->x, chunk->z); -} + for (LevelChunk* chunk : m_loadedChunkList) { + drop(chunk->x, chunk->z); + } #endif } // 4J - this is the original (and virtual) interface to create -LevelChunk *ServerChunkCache::create(int x, int z) -{ - return create(x, z, false); +LevelChunk* ServerChunkCache::create(int x, int z) { + return create(x, z, false); } -LevelChunk *ServerChunkCache::create(int x, int z, bool asyncPostProcess) // 4J - added extra parameter +LevelChunk* ServerChunkCache::create( + int x, int z, bool asyncPostProcess) // 4J - added extra parameter { - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return emptyChunk; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return emptyChunk; - int idx = ix * XZSIZE + iz; + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return emptyChunk; + if ((iz < 0) || (iz >= XZSIZE)) return emptyChunk; + int idx = ix * XZSIZE + iz; - LevelChunk *chunk = cache[idx]; - LevelChunk *lastChunk = chunk; + LevelChunk* chunk = cache[idx]; + LevelChunk* lastChunk = chunk; - if( ( chunk == NULL ) || ( chunk->x != x ) || ( chunk->z != z ) ) - { - EnterCriticalSection(&m_csLoadCreate); + if ((chunk == NULL) || (chunk->x != x) || (chunk->z != z)) { + EnterCriticalSection(&m_csLoadCreate); chunk = load(x, z); - if (chunk == NULL) - { - if (source == NULL) - { + if (chunk == NULL) { + if (source == NULL) { chunk = emptyChunk; - } - else - { + } else { chunk = source->getChunk(x, z); } } - if (chunk != NULL) - { - chunk->load(); - } + if (chunk != NULL) { + chunk->load(); + } - LeaveCriticalSection(&m_csLoadCreate); + LeaveCriticalSection(&m_csLoadCreate); -#if ( defined _WIN64 || defined __LP64__ ) - if( InterlockedCompareExchangeRelease64((LONG64 *)&cache[idx],(LONG64)chunk,(LONG64)lastChunk) == (LONG64)lastChunk ) +#if (defined _WIN64 || defined __LP64__) + if (InterlockedCompareExchangeRelease64( + (LONG64*)&cache[idx], (LONG64)chunk, (LONG64)lastChunk) == + (LONG64)lastChunk) #else - if( InterlockedCompareExchangeRelease((LONG *)&cache[idx],(LONG)chunk,(LONG)lastChunk) == (LONG)lastChunk ) -#endif // _DURANGO - { - // Successfully updated the cache - EnterCriticalSection(&m_csLoadCreate); - // 4J - added - this will run a recalcHeightmap if source is a randomlevelsource, which has been split out from source::getChunk so that - // we are doing it after the chunk has been added to the cache - otherwise a lot of the lighting fails as lights aren't added if the chunk - // they are in fail ServerChunkCache::hasChunk. - source->lightChunk(chunk); + if (InterlockedCompareExchangeRelease((LONG*)&cache[idx], (LONG)chunk, + (LONG)lastChunk) == + (LONG)lastChunk) +#endif // _DURANGO + { + // Successfully updated the cache + EnterCriticalSection(&m_csLoadCreate); + // 4J - added - this will run a recalcHeightmap if source is a + // randomlevelsource, which has been split out from source::getChunk + // so that we are doing it after the chunk has been added to the + // cache - otherwise a lot of the lighting fails as lights aren't + // added if the chunk they are in fail ServerChunkCache::hasChunk. + source->lightChunk(chunk); - updatePostProcessFlags( x, z ); + updatePostProcessFlags(x, z); - m_loadedChunkList.push_back(chunk); + m_loadedChunkList.push_back(chunk); - // 4J - If post-processing is to be async, then let the server know about requests rather than processing directly here. Note that - // these hasChunk() checks appear to be incorrect - the chunks checked by these map out as: - // - // 1. 2. 3. 4. - // oxx xxo ooo ooo - // oPx Poo oox xoo - // ooo ooo oPx Pxo - // - // where P marks the chunk that is being considered for postprocessing, and x marks chunks that needs to be loaded. It would seem that the - // chunks which need to be loaded should stay the same relative to the chunk to be processed, but the hasChunk checks in 3 cases check again - // the chunk which is to be processed itself rather than (what I presume to be) the correct position. - // Don't think we should change in case it alters level creation. + // 4J - If post-processing is to be async, then let the server know + // about requests rather than processing directly here. Note that + // these hasChunk() checks appear to be incorrect - the chunks + // checked by these map out as: + // + // 1. 2. 3. 4. + // oxx xxo ooo ooo + // oPx Poo oox xoo + // ooo ooo oPx Pxo + // + // where P marks the chunk that is being considered for + // postprocessing, and x marks chunks that needs to be loaded. It + // would seem that the chunks which need to be loaded should stay + // the same relative to the chunk to be processed, but the hasChunk + // checks in 3 cases check again the chunk which is to be processed + // itself rather than (what I presume to be) the correct position. + // Don't think we should change in case it alters level creation. - if( asyncPostProcess ) - { - // 4J Stu - TODO This should also be calling the same code as chunk->checkPostProcess, but then we cannot guarantee we are in the server add the post-process request - if ( ( (chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == 0) && hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x + 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x, z); - if (hasChunk(x - 1, z) && ((getChunk(x - 1, z)->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) == 0 ) && hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && hasChunk(x - 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x - 1, z); - if (hasChunk(x, z - 1) && ((getChunk(x, z - 1)->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) == 0 ) && hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x + 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x, z - 1); - if (hasChunk(x - 1, z - 1) && ((getChunk(x - 1, z - 1)->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) == 0 ) && hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && hasChunk(x - 1, z)) MinecraftServer::getInstance()->addPostProcessRequest(this, x - 1, z - 1); - } - else - { - chunk->checkPostProcess(this, this, x, z); - } + if (asyncPostProcess) { + // 4J Stu - TODO This should also be calling the same code as + // chunk->checkPostProcess, but then we cannot guarantee we are + // in the server add the post-process request + if (((chunk->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x + 1, z + 1) && hasChunk(x, z + 1) && + hasChunk(x + 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest(this, + x, z); + if (hasChunk(x - 1, z) && + ((getChunk(x - 1, z)->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x - 1, z + 1) && hasChunk(x, z + 1) && + hasChunk(x - 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest( + this, x - 1, z); + if (hasChunk(x, z - 1) && + ((getChunk(x, z - 1)->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x + 1, z - 1) && hasChunk(x, z - 1) && + hasChunk(x + 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest( + this, x, z - 1); + if (hasChunk(x - 1, z - 1) && + ((getChunk(x - 1, z - 1)->terrainPopulated & + LevelChunk::sTerrainPopulatedFromHere) == 0) && + hasChunk(x - 1, z - 1) && hasChunk(x, z - 1) && + hasChunk(x - 1, z)) + MinecraftServer::getInstance()->addPostProcessRequest( + this, x - 1, z - 1); + } else { + chunk->checkPostProcess(this, this, x, z); + } - // 4J - Now try and fix up any chests that were saved pre-1.8.2. We don't want to do this to this particular chunk as we don't know if all its neighbours are loaded yet, and we - // need the neighbours to be able to work out the facing direction for the chests. Therefore process any neighbouring chunk that loading this chunk would be the last neighbour for. - // 5 cases illustrated below, where P is the chunk to be processed, T is this chunk, and x are other chunks that need to be checked for being present + // 4J - Now try and fix up any chests that were saved pre-1.8.2. We + // don't want to do this to this particular chunk as we don't know + // if all its neighbours are loaded yet, and we need the neighbours + // to be able to work out the facing direction for the chests. + // Therefore process any neighbouring chunk that loading this chunk + // would be the last neighbour for. 5 cases illustrated below, where + // P is the chunk to be processed, T is this chunk, and x are other + // chunks that need to be checked for being present - // 1. 2. 3. 4. 5. - // ooooo ooxoo ooooo ooooo ooooo - // oxooo oxPxo oooxo ooooo ooxoo - // xPToo ooToo ooTPx ooToo oxPxo (in 5th case P and T are same) - // oxooo ooooo oooxo oxPxo ooxoo - // ooooo ooooo ooooo ooxoo ooooo + // 1. 2. 3. 4. 5. + // ooooo ooxoo ooooo ooooo ooooo + // oxooo oxPxo oooxo ooooo ooxoo + // xPToo ooToo ooTPx ooToo oxPxo (in 5th case P and T are + // same) oxooo ooooo oooxo oxPxo ooxoo ooooo ooooo + // ooooo ooxoo ooooo - if( hasChunk( x - 1, z ) && hasChunk( x - 2, z ) && hasChunk( x - 1, z + 1 ) && hasChunk( x - 1, z - 1 ) ) chunk->checkChests( this, x - 1, z ); - if( hasChunk( x, z + 1) && hasChunk( x , z + 2 ) && hasChunk( x - 1, z + 1 ) && hasChunk( x + 1, z + 1 ) ) chunk->checkChests( this, x, z + 1); - if( hasChunk( x + 1, z ) && hasChunk( x + 2, z ) && hasChunk( x + 1, z + 1 ) && hasChunk( x + 1, z - 1 ) ) chunk->checkChests( this, x + 1, z ); - if( hasChunk( x, z - 1) && hasChunk( x , z - 2 ) && hasChunk( x - 1, z - 1 ) && hasChunk( x + 1, z - 1 ) ) chunk->checkChests( this, x, z - 1); - if( hasChunk( x - 1, z ) && hasChunk( x + 1, z ) && hasChunk ( x, z - 1 ) && hasChunk( x, z + 1 ) ) chunk->checkChests( this, x, z ); + if (hasChunk(x - 1, z) && hasChunk(x - 2, z) && + hasChunk(x - 1, z + 1) && hasChunk(x - 1, z - 1)) + chunk->checkChests(this, x - 1, z); + if (hasChunk(x, z + 1) && hasChunk(x, z + 2) && + hasChunk(x - 1, z + 1) && hasChunk(x + 1, z + 1)) + chunk->checkChests(this, x, z + 1); + if (hasChunk(x + 1, z) && hasChunk(x + 2, z) && + hasChunk(x + 1, z + 1) && hasChunk(x + 1, z - 1)) + chunk->checkChests(this, x + 1, z); + if (hasChunk(x, z - 1) && hasChunk(x, z - 2) && + hasChunk(x - 1, z - 1) && hasChunk(x + 1, z - 1)) + chunk->checkChests(this, x, z - 1); + if (hasChunk(x - 1, z) && hasChunk(x + 1, z) && + hasChunk(x, z - 1) && hasChunk(x, z + 1)) + chunk->checkChests(this, x, z); - LeaveCriticalSection(&m_csLoadCreate); - } - else - { - // Something else must have updated the cache. Return that chunk and discard this one - chunk->unload(true); - delete chunk; - return cache[idx]; - } + LeaveCriticalSection(&m_csLoadCreate); + } else { + // Something else must have updated the cache. Return that chunk and + // discard this one + chunk->unload(true); + delete chunk; + return cache[idx]; + } } #ifdef __PS3__ - Sleep(1); -#endif // __PS3__ + Sleep(1); +#endif // __PS3__ return chunk; - } -// 4J Stu - Split out this function so that we get a chunk without loading entities -// This is used when sharing server chunk data on the main thread -LevelChunk *ServerChunkCache::getChunk(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return emptyChunk; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return emptyChunk; - int idx = ix * XZSIZE + iz; +// 4J Stu - Split out this function so that we get a chunk without loading +// entities This is used when sharing server chunk data on the main thread +LevelChunk* ServerChunkCache::getChunk(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return emptyChunk; + if ((iz < 0) || (iz >= XZSIZE)) return emptyChunk; + int idx = ix * XZSIZE + iz; - LevelChunk *lc = cache[idx]; - if( lc ) - { - return lc; - } + LevelChunk* lc = cache[idx]; + if (lc) { + return lc; + } - if( level->isFindingSpawn || autoCreate ) - { - return create(x, z); - } + if (level->isFindingSpawn || autoCreate) { + return create(x, z); + } - return emptyChunk; + return emptyChunk; } #ifdef _LARGE_WORLDS -// 4J added - this special variation on getChunk also checks the unloaded chunk cache. It is called on a host machine from the client-side level when: -// (1) Trying to determine whether the client blocks and data are the same as those on the server, so we can start sharing them -// (2) Trying to resync the lighting data from the server to the client -// As such it is really important that we don't return emptyChunk in these situations, when we actually still have the block/data/lighting in the unloaded cache -LevelChunk *ServerChunkCache::getChunkLoadedOrUnloaded(int x, int z) -{ - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - // Check we're in range of the stored level - if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return emptyChunk; - if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return emptyChunk; - int idx = ix * XZSIZE + iz; +// 4J added - this special variation on getChunk also checks the unloaded chunk +// cache. It is called on a host machine from the client-side level when: (1) +// Trying to determine whether the client blocks and data are the same as those +// on the server, so we can start sharing them (2) Trying to resync the lighting +// data from the server to the client As such it is really important that we +// don't return emptyChunk in these situations, when we actually still have the +// block/data/lighting in the unloaded cache +LevelChunk* ServerChunkCache::getChunkLoadedOrUnloaded(int x, int z) { + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + // Check we're in range of the stored level + if ((ix < 0) || (ix >= XZSIZE)) return emptyChunk; + if ((iz < 0) || (iz >= XZSIZE)) return emptyChunk; + int idx = ix * XZSIZE + iz; - LevelChunk *lc = cache[idx]; - if( lc ) - { - return lc; - } + LevelChunk* lc = cache[idx]; + if (lc) { + return lc; + } - lc = m_unloadedCache[idx]; - if( lc ) - { - return lc; -} + lc = m_unloadedCache[idx]; + if (lc) { + return lc; + } - if( level->isFindingSpawn || autoCreate ) - { - return create(x, z); - } + if (level->isFindingSpawn || autoCreate) { + return create(x, z); + } - return emptyChunk; + return emptyChunk; } #endif // 4J Added // #ifdef _LARGE_WORLDS -void ServerChunkCache::dontDrop(int x, int z) -{ - LevelChunk *chunk = getChunk(x,z); - m_toDrop.erase(std::remove(m_toDrop.begin(), m_toDrop.end(), chunk), m_toDrop.end()); +void ServerChunkCache::dontDrop(int x, int z) { + LevelChunk* chunk = getChunk(x, z); + m_toDrop.erase(std::remove(m_toDrop.begin(), m_toDrop.end(), chunk), + m_toDrop.end()); } #endif -LevelChunk *ServerChunkCache::load(int x, int z) -{ +LevelChunk* ServerChunkCache::load(int x, int z) { if (storage == NULL) return NULL; - LevelChunk *levelChunk = NULL; + LevelChunk* levelChunk = NULL; #ifdef _LARGE_WORLDS - int ix = x + XZOFFSET; - int iz = z + XZOFFSET; - int idx = ix * XZSIZE + iz; - levelChunk = m_unloadedCache[idx]; - m_unloadedCache[idx] = NULL; - if(levelChunk == NULL) + int ix = x + XZOFFSET; + int iz = z + XZOFFSET; + int idx = ix * XZSIZE + iz; + levelChunk = m_unloadedCache[idx]; + m_unloadedCache[idx] = NULL; + if (levelChunk == NULL) #endif - { - levelChunk = storage->load(level, x, z); - } - if (levelChunk != NULL) - { + { + levelChunk = storage->load(level, x, z); + } + if (levelChunk != NULL) { levelChunk->lastSaveTime = level->getTime(); } return levelChunk; } -void ServerChunkCache::saveEntities(LevelChunk *levelChunk) -{ +void ServerChunkCache::saveEntities(LevelChunk* levelChunk) { if (storage == NULL) return; storage->saveEntities(level, levelChunk); } -void ServerChunkCache::save(LevelChunk *levelChunk) -{ - if (storage == NULL) return; +void ServerChunkCache::save(LevelChunk* levelChunk) { + if (storage == NULL) return; - levelChunk->lastSaveTime = level->getTime(); - storage->save(level, levelChunk); + levelChunk->lastSaveTime = level->getTime(); + storage->save(level, levelChunk); } // 4J added -void ServerChunkCache::updatePostProcessFlag(short flag, int x, int z, int xo, int zo, LevelChunk *lc) -{ - if( hasChunk( x + xo, z + zo ) ) - { - LevelChunk *lc2 = getChunk(x + xo, z + zo); - if( lc2 != emptyChunk ) // Will only be empty chunk of this is the edge (we've already checked hasChunk so won't just be a missing chunk) - { - if( lc2->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) - { - lc->terrainPopulated |= flag; - } - } - else - { - // The edge - always consider as post-processed - lc->terrainPopulated |= flag; - } - } +void ServerChunkCache::updatePostProcessFlag(short flag, int x, int z, int xo, + int zo, LevelChunk* lc) { + if (hasChunk(x + xo, z + zo)) { + LevelChunk* lc2 = getChunk(x + xo, z + zo); + if (lc2 != emptyChunk) // Will only be empty chunk of this is the edge + // (we've already checked hasChunk so won't just + // be a missing chunk) + { + if (lc2->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) { + lc->terrainPopulated |= flag; + } + } else { + // The edge - always consider as post-processed + lc->terrainPopulated |= flag; + } + } } -// 4J added - normally we try and set these flags when a chunk is post-processed. However, when setting in a north or easterly direction the -// affected chunks might not themselves exist, so we need to check the flags also when creating new chunks. -void ServerChunkCache::updatePostProcessFlags(int x, int z) -{ - LevelChunk *lc = getChunk(x, z); - if( lc != emptyChunk ) - { - // First check if any of our neighbours are post-processed, that should affect OUR flags - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromS, x, z, 0, -1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromSW, x, z, -1, -1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromW, x, z, -1, 0, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromNW, x, z, -1, 1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromN, x, z, 0, 1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromNE, x, z, 1, 1, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromE, x, z, 1, 0, lc ); - updatePostProcessFlag( LevelChunk::sTerrainPopulatedFromSE, x, z, 1, -1, lc ); +// 4J added - normally we try and set these flags when a chunk is +// post-processed. However, when setting in a north or easterly direction the +// affected chunks might not themselves exist, so we need to check the flags +// also when creating new chunks. +void ServerChunkCache::updatePostProcessFlags(int x, int z) { + LevelChunk* lc = getChunk(x, z); + if (lc != emptyChunk) { + // First check if any of our neighbours are post-processed, that should + // affect OUR flags + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromS, x, z, 0, -1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromSW, x, z, -1, -1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromW, x, z, -1, 0, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromNW, x, z, -1, 1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromN, x, z, 0, 1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromNE, x, z, 1, 1, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromE, x, z, 1, 0, + lc); + updatePostProcessFlag(LevelChunk::sTerrainPopulatedFromSE, x, z, 1, -1, + lc); - // Then, if WE are post-processed, check that our neighbour's flags are also set - if( lc->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere ) - { - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, z - 1 ); - } - } + // Then, if WE are post-processed, check that our neighbour's flags are + // also set + if (lc->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) { + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, + z - 1); + } + } - flagPostProcessComplete(0, x, z); + flagPostProcessComplete(0, x, z); } -// 4J added - add a flag to a chunk to say that one of its neighbours has completed post-processing. If this completes the set of -// chunks which can actually set tile tiles in this chunk (sTerrainPopulatedAllAffecting), then this is a good point to compress this chunk. -// If this completes the set of all 8 neighbouring chunks that have been fully post-processed, then this is a good time to fix up some -// lighting things that need all the tiles to be in place in the region into which they might propagate. -void ServerChunkCache::flagPostProcessComplete(short flag, int x, int z) -{ - // Set any extra flags for this chunk to indicate which neighbours have now had their post-processing done - if( !hasChunk(x, z) ) return; +// 4J added - add a flag to a chunk to say that one of its neighbours has +// completed post-processing. If this completes the set of chunks which can +// actually set tile tiles in this chunk (sTerrainPopulatedAllAffecting), then +// this is a good point to compress this chunk. If this completes the set of all +// 8 neighbouring chunks that have been fully post-processed, then this is a +// good time to fix up some lighting things that need all the tiles to be in +// place in the region into which they might propagate. +void ServerChunkCache::flagPostProcessComplete(short flag, int x, int z) { + // Set any extra flags for this chunk to indicate which neighbours have now + // had their post-processing done + if (!hasChunk(x, z)) return; - LevelChunk *lc = level->getChunk( x, z ); - if( lc == emptyChunk ) return; + LevelChunk* lc = level->getChunk(x, z); + if (lc == emptyChunk) return; - lc->terrainPopulated |= flag; + lc->terrainPopulated |= flag; - // Are all neighbouring chunks which could actually place tiles on this chunk complete? (This is ones to W, SW, S) - if( ( lc->terrainPopulated & LevelChunk::sTerrainPopulatedAllAffecting ) == LevelChunk::sTerrainPopulatedAllAffecting ) - { - // Do the compression of data & lighting at this point - PIXBeginNamedEvent(0,"Compressing lighting/blocks"); + // Are all neighbouring chunks which could actually place tiles on this + // chunk complete? (This is ones to W, SW, S) + if ((lc->terrainPopulated & LevelChunk::sTerrainPopulatedAllAffecting) == + LevelChunk::sTerrainPopulatedAllAffecting) { + // Do the compression of data & lighting at this point + PIXBeginNamedEvent(0, "Compressing lighting/blocks"); - // Check, using lower blocks as a reference, if we've already compressed - no point doing this multiple times, which - // otherwise we will do as we aren't checking for the flags transitioning in the if statement we're in here - if( !lc->isLowerBlockStorageCompressed() ) - lc->compressBlocks(); - if( !lc->isLowerBlockLightStorageCompressed() ) - lc->compressLighting(); - if( !lc->isLowerDataStorageCompressed() ) - lc->compressData(); - - PIXEndNamedEvent(); - } + // Check, using lower blocks as a reference, if we've already compressed + // - no point doing this multiple times, which otherwise we will do as + // we aren't checking for the flags transitioning in the if statement + // we're in here + if (!lc->isLowerBlockStorageCompressed()) lc->compressBlocks(); + if (!lc->isLowerBlockLightStorageCompressed()) lc->compressLighting(); + if (!lc->isLowerDataStorageCompressed()) lc->compressData(); - // Are all neighbouring chunks And this one now post-processed? - if( lc->terrainPopulated == LevelChunk::sTerrainPopulatedAllNeighbours ) - { - // Special lighting patching for schematics first - app.processSchematicsLighting(lc); + PIXEndNamedEvent(); + } - // This would be a good time to fix up any lighting for this chunk since all the geometry that could affect it should now be in place - PIXBeginNamedEvent(0,"Recheck gaps"); - if( lc->level->dimension->id != 1 ) - { - lc->recheckGaps(true); - } - PIXEndNamedEvent(); + // Are all neighbouring chunks And this one now post-processed? + if (lc->terrainPopulated == LevelChunk::sTerrainPopulatedAllNeighbours) { + // Special lighting patching for schematics first + app.processSchematicsLighting(lc); - // Do a checkLight on any tiles which are lava. - PIXBeginNamedEvent(0,"Light lava (this)"); - lc->lightLava(); - PIXEndNamedEvent(); + // This would be a good time to fix up any lighting for this chunk since + // all the geometry that could affect it should now be in place + PIXBeginNamedEvent(0, "Recheck gaps"); + if (lc->level->dimension->id != 1) { + lc->recheckGaps(true); + } + PIXEndNamedEvent(); - // Flag as now having this post-post-processing stage completed - lc->terrainPopulated |= LevelChunk::sTerrainPostPostProcessed; - } + // Do a checkLight on any tiles which are lava. + PIXBeginNamedEvent(0, "Light lava (this)"); + lc->lightLava(); + PIXEndNamedEvent(); + + // Flag as now having this post-post-processing stage completed + lc->terrainPopulated |= LevelChunk::sTerrainPostPostProcessed; + } } -void ServerChunkCache::postProcess(ChunkSource *parent, int x, int z ) -{ - LevelChunk *chunk = getChunk(x, z); - if ( (chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == 0 ) - { - if (source != NULL) - { - PIXBeginNamedEvent(0,"Main post processing"); +void ServerChunkCache::postProcess(ChunkSource* parent, int x, int z) { + LevelChunk* chunk = getChunk(x, z); + if ((chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == + 0) { + if (source != NULL) { + PIXBeginNamedEvent(0, "Main post processing"); source->postProcess(parent, x, z); - PIXEndNamedEvent(); + PIXEndNamedEvent(); chunk->markUnsaved(); } - // Flag not only this chunk as being post-processed, but also all the chunks that this post-processing might affect. We can guarantee that these - // chunks exist as that's determined before post-processing can even run - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromHere; + // Flag not only this chunk as being post-processed, but also all the + // chunks that this post-processing might affect. We can guarantee that + // these chunks exist as that's determined before post-processing can + // even run + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromHere; - // If we are an edge chunk, fill in missing flags from sides that will never post-process - if(x == -XZOFFSET) // Furthest west - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; - } - if(x == (XZOFFSET - 1 )) // Furthest east - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromE; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; - } - if(z == -XZOFFSET) // Furthest south - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromS; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; - } - if(z == (XZOFFSET - 1)) // Furthest north - { - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromN; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; - chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; - } + // If we are an edge chunk, fill in missing flags from sides that will + // never post-process + if (x == -XZOFFSET) // Furthest west + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; + } + if (x == (XZOFFSET - 1)) // Furthest east + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromE; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; + } + if (z == -XZOFFSET) // Furthest south + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromS; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromSE; + } + if (z == (XZOFFSET - 1)) // Furthest north + { + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromN; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNW; + chunk->terrainPopulated |= LevelChunk::sTerrainPopulatedFromNE; + } - // Set flags for post-processing being complete for neighbouring chunks. This also performs actions if this post-processing completes - // a full set of post-processing flags for one of these neighbours. - flagPostProcessComplete(0, x, z ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, z + 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, z + 0 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, z - 1 ); - flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, z - 1 ); + // Set flags for post-processing being complete for neighbouring chunks. + // This also performs actions if this post-processing completes a full + // set of post-processing flags for one of these neighbours. + flagPostProcessComplete(0, x, z); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromW, x + 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSW, x + 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromS, x + 0, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromSE, x - 1, + z + 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromE, x - 1, + z + 0); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNE, x - 1, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromN, x + 0, + z - 1); + flagPostProcessComplete(LevelChunk::sTerrainPopulatedFromNW, x + 1, + z - 1); } } // 4J Added for suspend -bool ServerChunkCache::saveAllEntities() -{ - PIXBeginNamedEvent(0, "Save all entities"); +bool ServerChunkCache::saveAllEntities() { + PIXBeginNamedEvent(0, "Save all entities"); - PIXBeginNamedEvent(0, "saving to NBT"); - EnterCriticalSection(&m_csLoadCreate); - for(AUTO_VAR(it,m_loadedChunkList.begin()); it != m_loadedChunkList.end(); ++it) - { - storage->saveEntities(level, *it); - } - LeaveCriticalSection(&m_csLoadCreate); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "saving to NBT"); + EnterCriticalSection(&m_csLoadCreate); + for (AUTO_VAR(it, m_loadedChunkList.begin()); it != m_loadedChunkList.end(); + ++it) { + storage->saveEntities(level, *it); + } + LeaveCriticalSection(&m_csLoadCreate); + PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Flushing"); - storage->flush(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Flushing"); + storage->flush(); + PIXEndNamedEvent(); - PIXEndNamedEvent(); - return true; + PIXEndNamedEvent(); + return true; } -bool ServerChunkCache::save(bool force, ProgressListener *progressListener) -{ - EnterCriticalSection(&m_csLoadCreate); +bool ServerChunkCache::save(bool force, ProgressListener* progressListener) { + EnterCriticalSection(&m_csLoadCreate); int saves = 0; - // 4J - added this to support progressListner - int count = 0; - if (progressListener != NULL) - { + // 4J - added this to support progressListner + int count = 0; + if (progressListener != NULL) { AUTO_VAR(itEnd, m_loadedChunkList.end()); - for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) - { - LevelChunk *chunk = *it; - if (chunk->shouldSave(force)) - { + for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) { + LevelChunk* chunk = *it; + if (chunk->shouldSave(force)) { count++; } } } int cc = 0; - bool maxSavesReached = false; + bool maxSavesReached = false; - if(!force) - { - //app.DebugPrintf("Unsaved chunks = %d\n", level->getUnsavedChunkCount() ); - // Single threaded implementation for small saves - for (unsigned int i = 0; i < m_loadedChunkList.size(); i++) - { - LevelChunk *chunk = m_loadedChunkList[i]; + if (!force) { + // app.DebugPrintf("Unsaved chunks = %d\n", + // level->getUnsavedChunkCount() ); + // Single threaded implementation for small saves + for (unsigned int i = 0; i < m_loadedChunkList.size(); i++) { + LevelChunk* chunk = m_loadedChunkList[i]; #ifndef SPLIT_SAVES - if (force && !chunk->dontSave) saveEntities(chunk); + if (force && !chunk->dontSave) saveEntities(chunk); #endif - if (chunk->shouldSave(force)) - { - save(chunk); - chunk->setUnsaved(false); - if (++saves == MAX_SAVES && !force) - { - LeaveCriticalSection(&m_csLoadCreate); - return false; - } + if (chunk->shouldSave(force)) { + save(chunk); + chunk->setUnsaved(false); + if (++saves == MAX_SAVES && !force) { + LeaveCriticalSection(&m_csLoadCreate); + return false; + } - // 4J - added this to support progressListener - if (progressListener != NULL) - { - if (++cc % 10 == 0) - { - progressListener->progressStagePercentage(cc * 100 / count); - } - } - } - } - } - else - { -#if 1 //_LARGE_WORLDS - // 4J Stu - We have multiple for threads for all saving as part of the storage, so use that rather than new threads here + // 4J - added this to support progressListener + if (progressListener != NULL) { + if (++cc % 10 == 0) { + progressListener->progressStagePercentage(cc * 100 / + count); + } + } + } + } + } else { +#if 1 //_LARGE_WORLDS + // 4J Stu - We have multiple for threads for all saving as part of the + // storage, so use that rather than new threads here - // Created a roughly sorted list to match the order that the files were created in McRegionChunkStorage::McRegionChunkStorage. - // This is to minimise the amount of data that needs to be moved round when creating a new level. + // Created a roughly sorted list to match the order that the files were + // created in McRegionChunkStorage::McRegionChunkStorage. This is to + // minimise the amount of data that needs to be moved round when + // creating a new level. - std::vector sortedChunkList; + std::vector sortedChunkList; - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && + (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } - // Push all the chunks to be saved to the compression threads - for (unsigned int i = 0; i < sortedChunkList.size();++i) - { - LevelChunk *chunk = sortedChunkList[i]; - if (force && !chunk->dontSave) saveEntities(chunk); - if (chunk->shouldSave(force)) - { - save(chunk); - chunk->setUnsaved(false); - if (++saves == MAX_SAVES && !force) - { - LeaveCriticalSection(&m_csLoadCreate); - return false; - } + // Push all the chunks to be saved to the compression threads + for (unsigned int i = 0; i < sortedChunkList.size(); ++i) { + LevelChunk* chunk = sortedChunkList[i]; + if (force && !chunk->dontSave) saveEntities(chunk); + if (chunk->shouldSave(force)) { + save(chunk); + chunk->setUnsaved(false); + if (++saves == MAX_SAVES && !force) { + LeaveCriticalSection(&m_csLoadCreate); + return false; + } - // 4J - added this to support progressListener - if (progressListener != NULL) - { - if (++cc % 10 == 0) - { - progressListener->progressStagePercentage(cc * 100 / count); - } - } - } - // Wait if we are building up too big a queue of chunks to be written - on PS3 this has been seen to cause so much data to be queued that we run out of - // out of memory when saving after exploring a full map - storage->WaitIfTooManyQueuedChunks(); - } + // 4J - added this to support progressListener + if (progressListener != NULL) { + if (++cc % 10 == 0) { + progressListener->progressStagePercentage(cc * 100 / + count); + } + } + } + // Wait if we are building up too big a queue of chunks to be + // written - on PS3 this has been seen to cause so much data to be + // queued that we run out of out of memory when saving after + // exploring a full map + storage->WaitIfTooManyQueuedChunks(); + } - // Wait for the storage threads to be complete - storage->WaitForAll(); + // Wait for the storage threads to be complete + storage->WaitForAll(); #else - // Multithreaded implementation for larger saves + // Multithreaded implementation for larger saves - C4JThread::Event *wakeEvent[3]; // This sets off the threads that are waiting to continue - C4JThread::Event *notificationEvent[3]; // These are signalled by the threads to let us know they are complete - C4JThread *saveThreads[3]; - SaveThreadData threadData[3]; - ZeroMemory(&threadData[0], sizeof(SaveThreadData)); - ZeroMemory(&threadData[1], sizeof(SaveThreadData)); - ZeroMemory(&threadData[2], sizeof(SaveThreadData)); + C4JThread::Event* wakeEvent[3]; // This sets off the threads that are + // waiting to continue + C4JThread::Event* + notificationEvent[3]; // These are signalled by the threads to let + // us know they are complete + C4JThread* saveThreads[3]; + SaveThreadData threadData[3]; + ZeroMemory(&threadData[0], sizeof(SaveThreadData)); + ZeroMemory(&threadData[1], sizeof(SaveThreadData)); + ZeroMemory(&threadData[2], sizeof(SaveThreadData)); - for(unsigned int i = 0; i < 3; ++i) - { - saveThreads[i] = NULL; - - threadData[i].cache = this; + for (unsigned int i = 0; i < 3; ++i) { + saveThreads[i] = NULL; - wakeEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); - threadData[i].wakeEvent = wakeEvent[i]; - - notificationEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); - threadData[i].notificationEvent = notificationEvent[i]; + threadData[i].cache = this; - if(i==0) threadData[i].useSharedThreadStorage = true; - else threadData[i].useSharedThreadStorage = false; - } + wakeEvent[i] = + new C4JThread::Event(); // CreateEvent(NULL,FALSE,FALSE,NULL); + threadData[i].wakeEvent = wakeEvent[i]; - LevelChunk *chunk = NULL; - std::uint8_t workingThreads; - bool chunkSet = false; + notificationEvent[i] = + new C4JThread::Event(); // CreateEvent(NULL,FALSE,FALSE,NULL); + threadData[i].notificationEvent = notificationEvent[i]; - // Created a roughly sorted list to match the order that the files were created in McRegionChunkStorage::McRegionChunkStorage. - // This is to minimise the amount of data that needs to be moved round when creating a new level. + if (i == 0) + threadData[i].useSharedThreadStorage = true; + else + threadData[i].useSharedThreadStorage = false; + } - std::vector sortedChunkList; + LevelChunk* chunk = NULL; + std::uint8_t workingThreads; + bool chunkSet = false; - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z < 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x >= 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - for( int i = 0; i < m_loadedChunkList.size(); i++ ) - { - if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); - } - - for (unsigned int i = 0; i < sortedChunkList.size();) - { - workingThreads = 0; - PIXBeginNamedEvent(0,"Setting tasks for save threads\n"); - for(unsigned int j = 0; j < 3; ++j) - { - chunkSet = false; + // Created a roughly sorted list to match the order that the files were + // created in McRegionChunkStorage::McRegionChunkStorage. This is to + // minimise the amount of data that needs to be moved round when + // creating a new level. - while(!chunkSet && i < sortedChunkList.size()) - { - chunk = sortedChunkList[i]; + std::vector sortedChunkList; - threadData[j].saveEntities = (force && !chunk->dontSave); + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && (m_loadedChunkList[i]->z < 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x >= 0) && + (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } + for (int i = 0; i < m_loadedChunkList.size(); i++) { + if ((m_loadedChunkList[i]->x < 0) && (m_loadedChunkList[i]->z >= 0)) + sortedChunkList.push_back(m_loadedChunkList[i]); + } - if (chunk->shouldSave(force) || threadData[j].saveEntities) - { - chunkSet = true; - ++workingThreads; + for (unsigned int i = 0; i < sortedChunkList.size();) { + workingThreads = 0; + PIXBeginNamedEvent(0, "Setting tasks for save threads\n"); + for (unsigned int j = 0; j < 3; ++j) { + chunkSet = false; - threadData[j].chunkToSave = chunk; + while (!chunkSet && i < sortedChunkList.size()) { + chunk = sortedChunkList[i]; - //app.DebugPrintf("Chunk to save set for thread %d\n", j); + threadData[j].saveEntities = (force && !chunk->dontSave); - if(saveThreads[j] == NULL) - { - char threadName[256]; - sprintf(threadName,"Save thread %d\n",j); - SetThreadName(0, threadName); + if (chunk->shouldSave(force) || + threadData[j].saveEntities) { + chunkSet = true; + ++workingThreads; - //saveThreads[j] = CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); - saveThreads[j] = new C4JThread(runSaveThreadProc,(void *)&threadData[j],threadName); + threadData[j].chunkToSave = chunk; + // app.DebugPrintf("Chunk to save set for thread %d\n", + // j); - //app.DebugPrintf("Created new thread: %s\n",threadName); + if (saveThreads[j] == NULL) { + char threadName[256]; + sprintf(threadName, "Save thread %d\n", j); + SetThreadName(0, threadName); - // Threads 1,3 and 5 are generally idle so use them (this call waits on thread 2) - if(j == 0) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_A); //XSetThreadProcessor( saveThreads[j], 1); - else if(j == 1) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_B); //XSetThreadProcessor( saveThreads[j], 3); - else if(j == 2) saveThreads[j]->SetProcessor(CPU_CORE_SAVE_THREAD_C); //XSetThreadProcessor( saveThreads[j], 5); + // saveThreads[j] = + // CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]); + saveThreads[j] = new C4JThread( + runSaveThreadProc, (void*)&threadData[j], + threadName); - //ResumeThread( saveThreads[j] ); - saveThreads[j]->Run(); - } + // app.DebugPrintf("Created new thread: + // %s\n",threadName); - if (++saves == MAX_SAVES && !force) - { - maxSavesReached = true; - break; + // Threads 1,3 and 5 are generally idle so use them + // (this call waits on thread 2) + if (j == 0) + saveThreads[j]->SetProcessor( + CPU_CORE_SAVE_THREAD_A); // XSetThreadProcessor( + // saveThreads[j], + // 1); + else if (j == 1) + saveThreads[j]->SetProcessor( + CPU_CORE_SAVE_THREAD_B); // XSetThreadProcessor( + // saveThreads[j], + // 3); + else if (j == 2) + saveThreads[j]->SetProcessor( + CPU_CORE_SAVE_THREAD_C); // XSetThreadProcessor( + // saveThreads[j], + // 5); - //LeaveCriticalSection(&m_csLoadCreate); - // TODO Should we be returning from here? Probably not - //return false; - } + // ResumeThread( saveThreads[j] ); + saveThreads[j]->Run(); + } - // 4J - added this to support progressListener - if (progressListener != NULL) - { - if (count > 0 && ++cc % 10 == 0) - { - progressListener->progressStagePercentage(cc * 100 / count); - } - } - } + if (++saves == MAX_SAVES && !force) { + maxSavesReached = true; + break; - ++i; - } + // LeaveCriticalSection(&m_csLoadCreate); + // TODO Should we be returning from here? Probably + // not + // return false; + } - if( !chunkSet ) - { - threadData[j].chunkToSave = NULL; - //app.DebugPrintf("No chunk to save set for thread %d\n",j); - } - } - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Waking save threads\n"); - // Start the worker threads going - for(unsigned int k = 0; k < 3; ++k) - { - //app.DebugPrintf("Waking save thread %d\n",k); - threadData[k].wakeEvent->Set(); //SetEvent(threadData[k].wakeEvent); - } - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Waiting for completion of save threads\n"); - //app.DebugPrintf("Waiting for %d save thread(s) to complete\n", workingThreads); + // 4J - added this to support progressListener + if (progressListener != NULL) { + if (count > 0 && ++cc % 10 == 0) { + progressListener->progressStagePercentage( + cc * 100 / count); + } + } + } - // Wait for the worker threads to complete - //WaitForMultipleObjects(workingThreads,notificationEvent,TRUE,INFINITE); - // 4J Stu - TODO This isn't ideal as it's not a perfect re-implmentation of the Xbox behaviour - for(unsigned int k = 0; k < workingThreads; ++k) - { - threadData[k].notificationEvent->WaitForSignal(INFINITE); - } - PIXEndNamedEvent(); - if( maxSavesReached ) break; - } + ++i; + } - //app.DebugPrintf("Clearing up worker threads\n"); - // Stop all the worker threads by giving them nothing to process then telling them to start - unsigned char validThreads = 0; - for(unsigned int i = 0; i < 3; ++i) - { - //app.DebugPrintf("Settings chunk to NULL for save thread %d\n", i); - threadData[i].chunkToSave = NULL; + if (!chunkSet) { + threadData[j].chunkToSave = NULL; + // app.DebugPrintf("No chunk to save set for thread + // %d\n",j); + } + } + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Waking save threads\n"); + // Start the worker threads going + for (unsigned int k = 0; k < 3; ++k) { + // app.DebugPrintf("Waking save thread %d\n",k); + threadData[k] + .wakeEvent->Set(); // SetEvent(threadData[k].wakeEvent); + } + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Waiting for completion of save threads\n"); + // app.DebugPrintf("Waiting for %d save thread(s) to complete\n", + // workingThreads); - //app.DebugPrintf("Setting wake event for save thread %d\n",i); - threadData[i].wakeEvent->Set(); //SetEvent(threadData[i].wakeEvent); + // Wait for the worker threads to complete + // WaitForMultipleObjects(workingThreads,notificationEvent,TRUE,INFINITE); + // 4J Stu - TODO This isn't ideal as it's not a perfect + // re-implmentation of the Xbox behaviour + for (unsigned int k = 0; k < workingThreads; ++k) { + threadData[k].notificationEvent->WaitForSignal(INFINITE); + } + PIXEndNamedEvent(); + if (maxSavesReached) break; + } - if(saveThreads[i] != NULL) ++validThreads; - } + // app.DebugPrintf("Clearing up worker threads\n"); + // Stop all the worker threads by giving them nothing to process then + // telling them to start + unsigned char validThreads = 0; + for (unsigned int i = 0; i < 3; ++i) { + // app.DebugPrintf("Settings chunk to NULL for save thread %d\n", + // i); + threadData[i].chunkToSave = NULL; - //WaitForMultipleObjects(validThreads,saveThreads,TRUE,INFINITE); - // 4J Stu - TODO This isn't ideal as it's not a perfect re-implmentation of the Xbox behaviour - for(unsigned int k = 0; k < validThreads; ++k) - { - saveThreads[k]->WaitForCompletion(INFINITE);; - } + // app.DebugPrintf("Setting wake event for save thread %d\n",i); + threadData[i] + .wakeEvent->Set(); // SetEvent(threadData[i].wakeEvent); - for(unsigned int i = 0; i < 3; ++i) - { - //app.DebugPrintf("Closing handles for save thread %d\n", i); - delete threadData[i].wakeEvent; //CloseHandle(threadData[i].wakeEvent); - delete threadData[i].notificationEvent; //CloseHandle(threadData[i].notificationEvent); - delete saveThreads[i]; //CloseHandle(saveThreads[i]); - } + if (saveThreads[i] != NULL) ++validThreads; + } + + // WaitForMultipleObjects(validThreads,saveThreads,TRUE,INFINITE); + // 4J Stu - TODO This isn't ideal as it's not a perfect + // re-implmentation of the Xbox behaviour + for (unsigned int k = 0; k < validThreads; ++k) { + saveThreads[k]->WaitForCompletion(INFINITE); + ; + } + + for (unsigned int i = 0; i < 3; ++i) { + // app.DebugPrintf("Closing handles for save thread %d\n", i); + delete threadData[i] + .wakeEvent; // CloseHandle(threadData[i].wakeEvent); + delete threadData[i] + .notificationEvent; // CloseHandle(threadData[i].notificationEvent); + delete saveThreads[i]; // CloseHandle(saveThreads[i]); + } #endif - } + } - if (force) - { - if (storage == NULL) - { - LeaveCriticalSection(&m_csLoadCreate); - return true; - } + if (force) { + if (storage == NULL) { + LeaveCriticalSection(&m_csLoadCreate); + return true; + } storage->flush(); } - LeaveCriticalSection(&m_csLoadCreate); + LeaveCriticalSection(&m_csLoadCreate); return !maxSavesReached; - } -bool ServerChunkCache::tick() -{ - if (!level->noSave) - { +bool ServerChunkCache::tick() { + if (!level->noSave) { #ifdef _LARGE_WORLDS - for (int i = 0; i < 100; i++) - { - if (!m_toDrop.empty()) - { - LevelChunk *chunk = m_toDrop.front(); - if(!chunk->isUnloaded()) - { - save(chunk); - saveEntities(chunk); - chunk->unload(true); + for (int i = 0; i < 100; i++) { + if (!m_toDrop.empty()) { + LevelChunk* chunk = m_toDrop.front(); + if (!chunk->isUnloaded()) { + save(chunk); + saveEntities(chunk); + chunk->unload(true); - //loadedChunks.remove(cp); - //loadedChunkList.remove(chunk); - AUTO_VAR(it, std::find( m_loadedChunkList.begin(), m_loadedChunkList.end(), chunk) ); - if(it != m_loadedChunkList.end()) m_loadedChunkList.erase(it); + // loadedChunks.remove(cp); + // loadedChunkList.remove(chunk); + AUTO_VAR(it, std::find(m_loadedChunkList.begin(), + m_loadedChunkList.end(), chunk)); + if (it != m_loadedChunkList.end()) + m_loadedChunkList.erase(it); - int ix = chunk->x + XZOFFSET; - int iz = chunk->z + XZOFFSET; - int idx = ix * XZSIZE + iz; - m_unloadedCache[idx] = chunk; - cache[idx] = NULL; - } - m_toDrop.pop_front(); - } - } + int ix = chunk->x + XZOFFSET; + int iz = chunk->z + XZOFFSET; + int idx = ix * XZSIZE + iz; + m_unloadedCache[idx] = chunk; + cache[idx] = NULL; + } + m_toDrop.pop_front(); + } + } #endif if (storage != NULL) storage->tick(); } return source->tick(); - } -bool ServerChunkCache::shouldSave() -{ - return !level->noSave; +bool ServerChunkCache::shouldSave() { return !level->noSave; } + +std::wstring ServerChunkCache::gatherStats() { + return L"ServerChunkCache: "; // + _toString(loadedChunks.size()) + L" + // Drop: " + _toString(toDrop.size()); } -std::wstring ServerChunkCache::gatherStats() -{ - return L"ServerChunkCache: ";// + _toString(loadedChunks.size()) + L" Drop: " + _toString(toDrop.size()); +std::vector* ServerChunkCache::getMobsAt( + MobCategory* mobCategory, int x, int y, int z) { + return source->getMobsAt(mobCategory, x, y, z); } -std::vector *ServerChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) -{ - return source->getMobsAt(mobCategory, x, y, z); +TilePos* ServerChunkCache::findNearestMapFeature( + Level* level, const std::wstring& featureName, int x, int y, int z) { + return source->findNearestMapFeature(level, featureName, x, y, z); } -TilePos *ServerChunkCache::findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z) -{ - return source->findNearestMapFeature(level, featureName, x, y, z); -} - -int ServerChunkCache::runSaveThreadProc(void *lpParam) -{ - SaveThreadData *params = static_cast(lpParam); - - if(params->useSharedThreadStorage) - { - Compression::UseDefaultThreadStorage(); - OldChunkStorage::UseDefaultThreadStorage(); - } - else - { - Compression::CreateNewThreadStorage(); - OldChunkStorage::CreateNewThreadStorage(); - } - - // Wait for the producer thread to tell us to start - params->wakeEvent->WaitForSignal(INFINITE); //WaitForSingleObject(params->wakeEvent,INFINITE); - - //app.DebugPrintf("Save thread has started\n"); - - while(params->chunkToSave != NULL) - { - PIXBeginNamedEvent(0,"Saving entities"); - //app.DebugPrintf("Save thread has started processing a chunk\n"); - if (params->saveEntities) params->cache->saveEntities(params->chunkToSave); - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Saving chunk"); - - params->cache->save(params->chunkToSave); - params->chunkToSave->setUnsaved(false); - - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Notifying and waiting for next chunk"); - - // Inform the producer thread that we are done with this chunk - params->notificationEvent->Set(); //SetEvent(params->notificationEvent); - - //app.DebugPrintf("Save thread has alerted producer that it is complete\n"); - - // Wait for the producer thread to tell us to go again - params->wakeEvent->WaitForSignal(INFINITE); //WaitForSingleObject(params->wakeEvent,INFINITE); - PIXEndNamedEvent(); - } - - //app.DebugPrintf("Thread is exiting as it has no chunk to process\n"); - - if(!params->useSharedThreadStorage) - { - Compression::ReleaseThreadStorage(); - OldChunkStorage::ReleaseThreadStorage(); - } - - return 0; +int ServerChunkCache::runSaveThreadProc(void* lpParam) { + SaveThreadData* params = static_cast(lpParam); + + if (params->useSharedThreadStorage) { + Compression::UseDefaultThreadStorage(); + OldChunkStorage::UseDefaultThreadStorage(); + } else { + Compression::CreateNewThreadStorage(); + OldChunkStorage::CreateNewThreadStorage(); + } + + // Wait for the producer thread to tell us to start + params->wakeEvent->WaitForSignal( + INFINITE); // WaitForSingleObject(params->wakeEvent,INFINITE); + + // app.DebugPrintf("Save thread has started\n"); + + while (params->chunkToSave != NULL) { + PIXBeginNamedEvent(0, "Saving entities"); + // app.DebugPrintf("Save thread has started processing a chunk\n"); + if (params->saveEntities) + params->cache->saveEntities(params->chunkToSave); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Saving chunk"); + + params->cache->save(params->chunkToSave); + params->chunkToSave->setUnsaved(false); + + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Notifying and waiting for next chunk"); + + // Inform the producer thread that we are done with this chunk + params->notificationEvent + ->Set(); // SetEvent(params->notificationEvent); + + // app.DebugPrintf("Save thread has alerted producer that it is + // complete\n"); + + // Wait for the producer thread to tell us to go again + params->wakeEvent->WaitForSignal( + INFINITE); // WaitForSingleObject(params->wakeEvent,INFINITE); + PIXEndNamedEvent(); + } + + // app.DebugPrintf("Thread is exiting as it has no chunk to process\n"); + + if (!params->useSharedThreadStorage) { + Compression::ReleaseThreadStorage(); + OldChunkStorage::ReleaseThreadStorage(); + } + + return 0; } diff --git a/Minecraft.Client/Network/ServerChunkCache.h b/Minecraft.Client/Network/ServerChunkCache.h index e127ccd71..c086728a0 100644 --- a/Minecraft.Client/Network/ServerChunkCache.h +++ b/Minecraft.Client/Network/ServerChunkCache.h @@ -8,94 +8,99 @@ class ServerLevel; -class ServerChunkCache : public ChunkSource -{ +class ServerChunkCache : public ChunkSource { +private: + // std::unordered_set toDrop; +private: + LevelChunk* emptyChunk; + ChunkSource* source; + ChunkStorage* storage; + +public: + bool autoCreate; private: -// std::unordered_set toDrop; -private: - LevelChunk *emptyChunk; - ChunkSource *source; - ChunkStorage *storage; -public: - bool autoCreate; -private: - LevelChunk **cache; - std::vector m_loadedChunkList; - ServerLevel *level; + LevelChunk** cache; + std::vector m_loadedChunkList; + ServerLevel* level; #ifdef _LARGE_WORLDS - std::deque m_toDrop; - LevelChunk **m_unloadedCache; + std::deque m_toDrop; + LevelChunk** m_unloadedCache; #endif - // 4J - added for multithreaded support - CRITICAL_SECTION m_csLoadCreate; - // 4J - size of cache is defined by size of one side - must be even - int XZSIZE; - int XZOFFSET; + // 4J - added for multithreaded support + CRITICAL_SECTION m_csLoadCreate; + // 4J - size of cache is defined by size of one side - must be even + int XZSIZE; + int XZOFFSET; public: - ServerChunkCache(ServerLevel *level, ChunkStorage *storage, ChunkSource *source); - virtual ~ServerChunkCache(); + ServerChunkCache(ServerLevel* level, ChunkStorage* storage, + ChunkSource* source); + virtual ~ServerChunkCache(); virtual bool hasChunk(int x, int z); - std::vector *getLoadedChunkList(); + std::vector* getLoadedChunkList(); void drop(int x, int z); - void dropAll(); - virtual LevelChunk *create(int x, int z); - LevelChunk *create(int x, int z, bool asyncPostProcess ); // 4J added - virtual LevelChunk *getChunk(int x, int z); -#ifdef _LARGE_WORLDS - LevelChunk *getChunkLoadedOrUnloaded(int x, int z); // 4J added + void dropAll(); + virtual LevelChunk* create(int x, int z); + LevelChunk* create(int x, int z, bool asyncPostProcess); // 4J added + virtual LevelChunk* getChunk(int x, int z); +#ifdef _LARGE_WORLDS + LevelChunk* getChunkLoadedOrUnloaded(int x, int z); // 4J added #endif - virtual LevelChunk **getCache() { return cache; } // 4J added + virtual LevelChunk** getCache() { return cache; } // 4J added - // 4J-JEV Added; Remove chunk from the toDrop queue. -#ifdef _LARGE_WORLDS - void dontDrop(int x, int z); + // 4J-JEV Added; Remove chunk from the toDrop queue. +#ifdef _LARGE_WORLDS + void dontDrop(int x, int z); #endif private: - LevelChunk *load(int x, int z); - void saveEntities(LevelChunk *levelChunk); - void save(LevelChunk *levelChunk); + LevelChunk* load(int x, int z); + void saveEntities(LevelChunk* levelChunk); + void save(LevelChunk* levelChunk); - void updatePostProcessFlag(short flag, int x, int z, int xo, int zo, LevelChunk *lc); // 4J added - void updatePostProcessFlags(int x, int z); // 4J added - void flagPostProcessComplete(short flag, int x, int z); // 4J added + void updatePostProcessFlag(short flag, int x, int z, int xo, int zo, + LevelChunk* lc); // 4J added + void updatePostProcessFlags(int x, int z); // 4J added + void flagPostProcessComplete(short flag, int x, int z); // 4J added public: - virtual void postProcess(ChunkSource *parent, int x, int z); - + virtual void postProcess(ChunkSource* parent, int x, int z); private: #ifdef _LARGE_WORLDS - static const int MAX_SAVES = 20; + static const int MAX_SAVES = 20; #else - // 4J Stu - Was 24, but lowering it drastically so that we can trickle save chunks - static const int MAX_SAVES = 1; + // 4J Stu - Was 24, but lowering it drastically so that we can trickle save + // chunks + static const int MAX_SAVES = 1; #endif public: - virtual bool saveAllEntities(); - virtual bool save(bool force, ProgressListener *progressListener); + virtual bool saveAllEntities(); + virtual bool save(bool force, ProgressListener* progressListener); virtual bool tick(); virtual bool shouldSave(); virtual std::wstring gatherStats(); - virtual std::vector *getMobsAt(MobCategory *mobCategory, int x, int y, int z); - virtual TilePos *findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z); + virtual std::vector* getMobsAt( + MobCategory* mobCategory, int x, int y, int z); + virtual TilePos* findNearestMapFeature(Level* level, + const std::wstring& featureName, + int x, int y, int z); private: - typedef struct _SaveThreadData - { - ServerChunkCache *cache; - LevelChunk *chunkToSave; - bool saveEntities; - bool useSharedThreadStorage; - C4JThread::Event *notificationEvent; - C4JThread::Event *wakeEvent; // This is a handle to the one fired by the producer thread - } SaveThreadData; + typedef struct _SaveThreadData { + ServerChunkCache* cache; + LevelChunk* chunkToSave; + bool saveEntities; + bool useSharedThreadStorage; + C4JThread::Event* notificationEvent; + C4JThread::Event* wakeEvent; // This is a handle to the one fired by + // the producer thread + } SaveThreadData; public: - static int runSaveThreadProc(void *lpParam); + static int runSaveThreadProc(void* lpParam); }; diff --git a/Minecraft.Client/Network/ServerCommandDispatcher.cpp b/Minecraft.Client/Network/ServerCommandDispatcher.cpp index 205c0f51f..6d86fd41c 100644 --- a/Minecraft.Client/Network/ServerCommandDispatcher.cpp +++ b/Minecraft.Client/Network/ServerCommandDispatcher.cpp @@ -7,69 +7,72 @@ #include "../Commands/TeleportCommand.h" #include "ServerCommandDispatcher.h" -ServerCommandDispatcher::ServerCommandDispatcher() -{ - addCommand(new TimeCommand()); - addCommand(new GameModeCommand()); - addCommand(new DefaultGameModeCommand()); - addCommand(new KillCommand()); - addCommand(new ToggleDownfallCommand()); - addCommand(new ExperienceCommand()); - addCommand(new TeleportCommand()); - addCommand(new GiveItemCommand()); - addCommand(new EnchantItemCommand()); - //addCommand(new EmoteCommand()); - //addCommand(new ShowSeedCommand()); - //addCommand(new HelpCommand()); - //addCommand(new DebugCommand()); - //addCommand(new MessageCommand()); +ServerCommandDispatcher::ServerCommandDispatcher() { + addCommand(new TimeCommand()); + addCommand(new GameModeCommand()); + addCommand(new DefaultGameModeCommand()); + addCommand(new KillCommand()); + addCommand(new ToggleDownfallCommand()); + addCommand(new ExperienceCommand()); + addCommand(new TeleportCommand()); + addCommand(new GiveItemCommand()); + addCommand(new EnchantItemCommand()); + // addCommand(new EmoteCommand()); + // addCommand(new ShowSeedCommand()); + // addCommand(new HelpCommand()); + // addCommand(new DebugCommand()); + // addCommand(new MessageCommand()); - //if (MinecraftServer::getInstance()->isDedicatedServer()) - //{ - // addCommand(new OpCommand()); - // addCommand(new DeOpCommand()); - // addCommand(new StopCommand()); - // addCommand(new SaveAllCommand()); - // addCommand(new SaveOffCommand()); - // addCommand(new SaveOnCommand()); - // addCommand(new BanIpCommand()); - // addCommand(new PardonIpCommand()); - // addCommand(new BanPlayerCommand()); - // addCommand(new ListBansCommand()); - // addCommand(new PardonPlayerCommand()); - // addCommand(new KickCommand()); - // addCommand(new ListPlayersCommand()); - // addCommand(new BroadcastCommand()); - // addCommand(new WhitelistCommand()); - //} - //else - //{ - // addCommand(new PublishLocalServerCommand()); - //} + // if (MinecraftServer::getInstance()->isDedicatedServer()) + //{ + // addCommand(new OpCommand()); + // addCommand(new DeOpCommand()); + // addCommand(new StopCommand()); + // addCommand(new SaveAllCommand()); + // addCommand(new SaveOffCommand()); + // addCommand(new SaveOnCommand()); + // addCommand(new BanIpCommand()); + // addCommand(new PardonIpCommand()); + // addCommand(new BanPlayerCommand()); + // addCommand(new ListBansCommand()); + // addCommand(new PardonPlayerCommand()); + // addCommand(new KickCommand()); + // addCommand(new ListPlayersCommand()); + // addCommand(new BroadcastCommand()); + // addCommand(new WhitelistCommand()); + // } + // else + //{ + // addCommand(new PublishLocalServerCommand()); + // } - // addCommand(new ServerTempDebugCommand()); + // addCommand(new ServerTempDebugCommand()); - Command::setLogger(this); + Command::setLogger(this); } -void ServerCommandDispatcher::logAdminCommand(std::shared_ptr source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message, int customData, const std::wstring& additionalMessage) -{ - PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); - //for (Player player : MinecraftServer.getInstance().getPlayers().players) - for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) - { - std::shared_ptr player = *it; - if (player != source && playerList->isOp(player)) - { - // TODO: Change chat packet to be able to send more bits of data - // 4J Stu - Take this out until we can add the name of the player performing the action. Also if the target is a mod then maybe don't need the message? - //player->sendMessage(message, messageType, customData, additionalMessage); - //player->sendMessage("\u00A77\u00A7o[" + source.getName() + ": " + player.localize(message, args) + "]"); - } - } +void ServerCommandDispatcher::logAdminCommand( + std::shared_ptr source, int type, + ChatPacket::EChatPacketMessage messageType, const std::wstring& message, + int customData, const std::wstring& additionalMessage) { + PlayerList* playerList = MinecraftServer::getInstance()->getPlayers(); + // for (Player player : MinecraftServer.getInstance().getPlayers().players) + for (AUTO_VAR(it, playerList->players.begin()); + it != playerList->players.end(); ++it) { + std::shared_ptr player = *it; + if (player != source && playerList->isOp(player)) { + // TODO: Change chat packet to be able to send more bits of data + // 4J Stu - Take this out until we can add the name of the player + // performing the action. Also if the target is a mod then maybe + // don't need the message? + // player->sendMessage(message, messageType, customData, + // additionalMessage); player->sendMessage("\u00A77\u00A7o[" + + // source.getName() + ": " + player.localize(message, args) + "]"); + } + } - if ((type & LOGTYPE_DONT_SHOW_TO_SELF) != LOGTYPE_DONT_SHOW_TO_SELF) - { - source->sendMessage(message, messageType, customData, additionalMessage); - } + if ((type & LOGTYPE_DONT_SHOW_TO_SELF) != LOGTYPE_DONT_SHOW_TO_SELF) { + source->sendMessage(message, messageType, customData, + additionalMessage); + } } \ No newline at end of file diff --git a/Minecraft.Client/Network/ServerCommandDispatcher.h b/Minecraft.Client/Network/ServerCommandDispatcher.h index 8f5261914..bd3906018 100644 --- a/Minecraft.Client/Network/ServerCommandDispatcher.h +++ b/Minecraft.Client/Network/ServerCommandDispatcher.h @@ -3,9 +3,12 @@ #include "../../Minecraft.World/Commands/CommandDispatcher.h" #include "../../Minecraft.World/Commands/AdminLogCommand.h" -class ServerCommandDispatcher : public CommandDispatcher, public AdminLogCommand -{ +class ServerCommandDispatcher : public CommandDispatcher, + public AdminLogCommand { public: - ServerCommandDispatcher(); - void logAdminCommand(std::shared_ptr source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message = L"", int customData = -1, const std::wstring& additionalMessage = L""); + ServerCommandDispatcher(); + void logAdminCommand(std::shared_ptr source, int type, + ChatPacket::EChatPacketMessage messageType, + const std::wstring& message = L"", int customData = -1, + const std::wstring& additionalMessage = L""); }; \ No newline at end of file diff --git a/Minecraft.Client/Network/ServerConnection.cpp b/Minecraft.Client/Network/ServerConnection.cpp index bef81d0d6..65801536b 100644 --- a/Minecraft.Client/Network/ServerConnection.cpp +++ b/Minecraft.Client/Network/ServerConnection.cpp @@ -9,196 +9,187 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../Level/MultiPlayerLevel.h" -ServerConnection::ServerConnection(MinecraftServer *server) -{ - // 4J - added initialiser - connectionCounter = 0; - InitializeCriticalSection(&pending_cs); +ServerConnection::ServerConnection(MinecraftServer* server) { + // 4J - added initialiser + connectionCounter = 0; + InitializeCriticalSection(&pending_cs); - this->server = server; + this->server = server; } -ServerConnection::~ServerConnection() -{ - DeleteCriticalSection(&pending_cs); +ServerConnection::~ServerConnection() { DeleteCriticalSection(&pending_cs); } + +// 4J - added to handle incoming connections, to replace thread that original +// used to have +void ServerConnection::NewIncomingSocket(Socket* socket) { + std::shared_ptr unconnectedClient = + std::shared_ptr(new PendingConnection( + server, socket, + L"Connection #" + _toString(connectionCounter++))); + handleConnection(unconnectedClient); } -// 4J - added to handle incoming connections, to replace thread that original used to have -void ServerConnection::NewIncomingSocket(Socket *socket) -{ - std::shared_ptr unconnectedClient = std::shared_ptr(new PendingConnection(server, socket, L"Connection #" + _toString(connectionCounter++))); - handleConnection(unconnectedClient); +void ServerConnection::addPlayerConnection( + std::shared_ptr uc) { + players.push_back(uc); } -void ServerConnection::addPlayerConnection(std::shared_ptr uc) -{ - players.push_back(uc); +void ServerConnection::handleConnection(std::shared_ptr uc) { + EnterCriticalSection(&pending_cs); + pending.push_back(uc); + LeaveCriticalSection(&pending_cs); } -void ServerConnection::handleConnection(std::shared_ptr uc) -{ - EnterCriticalSection(&pending_cs); - pending.push_back(uc); - LeaveCriticalSection(&pending_cs); -} - -void ServerConnection::stop() -{ - EnterCriticalSection(&pending_cs); - for (unsigned int i = 0; i < pending.size(); i++) - { +void ServerConnection::stop() { + EnterCriticalSection(&pending_cs); + for (unsigned int i = 0; i < pending.size(); i++) { std::shared_ptr uc = pending[i]; uc->connection->close(DisconnectPacket::eDisconnect_Closed); } - LeaveCriticalSection(&pending_cs); + LeaveCriticalSection(&pending_cs); - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; player->connection->close(DisconnectPacket::eDisconnect_Closed); } } -void ServerConnection::tick() -{ - { - // MGH - changed this so that the the CS lock doesn't cover the tick (was causing a lockup when 2 players tried to join) - EnterCriticalSection(&pending_cs); - std::vector< std::shared_ptr > tempPending = pending; - LeaveCriticalSection(&pending_cs); +void ServerConnection::tick() { + { + // MGH - changed this so that the the CS lock doesn't cover the tick + // (was causing a lockup when 2 players tried to join) + EnterCriticalSection(&pending_cs); + std::vector > tempPending = pending; + LeaveCriticalSection(&pending_cs); - for (unsigned int i = 0; i < tempPending.size(); i++) - { - std::shared_ptr uc = tempPending[i]; - // try { // 4J - removed try/catch - uc->tick(); - // } catch (Exception e) { - // uc.disconnect("Internal server error"); - // logger.log(Level.WARNING, "Failed to handle packet: " + e, e); - // } - if(uc->connection != NULL) uc->connection->flush(); - } - } + for (unsigned int i = 0; i < tempPending.size(); i++) { + std::shared_ptr uc = tempPending[i]; + // try { // 4J - removed try/catch + uc->tick(); + // } catch (Exception e) { + // uc.disconnect("Internal server error"); + // logger.log(Level.WARNING, "Failed to handle packet: " + // + e, e); + // } + if (uc->connection != NULL) uc->connection->flush(); + } + } - // now remove from the pending list - EnterCriticalSection(&pending_cs); - for (unsigned int i = 0; i < pending.size(); i++) - if (pending[i]->done) - { - pending.erase(pending.begin()+i); - i--; - } - LeaveCriticalSection(&pending_cs); + // now remove from the pending list + EnterCriticalSection(&pending_cs); + for (unsigned int i = 0; i < pending.size(); i++) + if (pending[i]->done) { + pending.erase(pending.begin() + i); + i--; + } + LeaveCriticalSection(&pending_cs); - for (unsigned int i = 0; i < players.size(); i++) - { + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; - std::shared_ptr serverPlayer = player->getPlayer(); - if( serverPlayer ) - { - serverPlayer->doChunkSendingTick(false); - } -// try { // 4J - removed try/catch - player->tick(); -// } catch (Exception e) { -// logger.log(Level.WARNING, "Failed to handle packet: " + e, e); -// player.disconnect("Internal server error"); -// } - if (player->done) - { - players.erase(players.begin()+i); - i--; + std::shared_ptr serverPlayer = player->getPlayer(); + if (serverPlayer) { + serverPlayer->doChunkSendingTick(false); + } + // try { // 4J - removed try/catch + player->tick(); + // } catch (Exception e) { + // logger.log(Level.WARNING, "Failed to handle packet: " + e, + // e); player.disconnect("Internal server error"); + // } + if (player->done) { + players.erase(players.begin() + i); + i--; } player->connection->flush(); } - } -bool ServerConnection::addPendingTextureRequest(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it == m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.push_back(textureName); - return true; - } +bool ServerConnection::addPendingTextureRequest( + const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it == m_pendingTextureRequests.end()) { + m_pendingTextureRequests.push_back(textureName); + return true; + } - // 4J Stu - We want to request this texture from everyone, if we have a duplicate it's most likely because the first person we asked for it didn't have it - // eg They selected a skin then deleted the skin pack. The side effect of this change is that in certain cases we can send a few more requests, and receive - // a few more responses if people join with the same skin in a short space of time - return true; + // 4J Stu - We want to request this texture from everyone, if we have a + // duplicate it's most likely because the first person we asked for it + // didn't have it eg They selected a skin then deleted the skin pack. The + // side effect of this change is that in certain cases we can send a few + // more requests, and receive a few more responses if people join with the + // same skin in a short space of time + return true; } -void ServerConnection::handleTextureReceived(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.erase(it); - } - for (unsigned int i = 0; i < players.size(); i++) - { +void ServerConnection::handleTextureReceived(const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it != m_pendingTextureRequests.end()) { + m_pendingTextureRequests.erase(it); + } + for (unsigned int i = 0; i < players.size(); i++) { std::shared_ptr player = players[i]; - if (!player->done) - { - player->handleTextureReceived(textureName); + if (!player->done) { + player->handleTextureReceived(textureName); } } } -void ServerConnection::handleTextureAndGeometryReceived(const std::wstring &textureName) -{ - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) - { - m_pendingTextureRequests.erase(it); - } - for (unsigned int i = 0; i < players.size(); i++) - { - std::shared_ptr player = players[i]; - if (!player->done) - { - player->handleTextureAndGeometryReceived(textureName); - } - } +void ServerConnection::handleTextureAndGeometryReceived( + const std::wstring& textureName) { + AUTO_VAR(it, find(m_pendingTextureRequests.begin(), + m_pendingTextureRequests.end(), textureName)); + if (it != m_pendingTextureRequests.end()) { + m_pendingTextureRequests.erase(it); + } + for (unsigned int i = 0; i < players.size(); i++) { + std::shared_ptr player = players[i]; + if (!player->done) { + player->handleTextureAndGeometryReceived(textureName); + } + } } -void ServerConnection::handleServerSettingsChanged(std::shared_ptr packet) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); +void ServerConnection::handleServerSettingsChanged( + std::shared_ptr packet) { + Minecraft* pMinecraft = Minecraft::GetInstance(); - if(packet->action==ServerSettingsChangedPacket::HOST_DIFFICULTY) - { - for(unsigned int i = 0; i < pMinecraft->levels.length; ++i) - { - if( pMinecraft->levels[i] != NULL ) - { - app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); - pMinecraft->levels[i]->difficulty = packet->data; - } - } - } -// else if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS)// options -// { -// app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings) -// } -// else -// { -// unsigned char ucData=(unsigned char)packet->data; -// if(ucData&1) -// { -// // hide gamertags -// pMinecraft->options->SetGamertagSetting(true); -// } -// else -// { -// pMinecraft->options->SetGamertagSetting(false); -// } -// -// for (unsigned int i = 0; i < players.size(); i++) -// { -// std::shared_ptr playerconnection = players[i]; -// playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting()); -// } -// } + if (packet->action == ServerSettingsChangedPacket::HOST_DIFFICULTY) { + for (unsigned int i = 0; i < pMinecraft->levels.length; ++i) { + if (pMinecraft->levels[i] != NULL) { + app.DebugPrintf( + "ClientConnection::handleServerSettingsChanged - " + "Difficulty = %d", + packet->data); + pMinecraft->levels[i]->difficulty = packet->data; + } + } + } + // else + // if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS)// + // options + // { + // app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings) + // } + // else + // { + // unsigned char ucData=(unsigned char)packet->data; + // if(ucData&1) + // { + // // hide gamertags + // pMinecraft->options->SetGamertagSetting(true); + // } + // else + // { + // pMinecraft->options->SetGamertagSetting(false); + // } + // + // for (unsigned int i = 0; i < players.size(); i++) + // { + // std::shared_ptr playerconnection = + // players[i]; + // playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting()); + // } + // } } \ No newline at end of file diff --git a/Minecraft.Client/Network/ServerConnection.h b/Minecraft.Client/Network/ServerConnection.h index 501315756..77a341df9 100644 --- a/Minecraft.Client/Network/ServerConnection.h +++ b/Minecraft.Client/Network/ServerConnection.h @@ -5,45 +5,52 @@ class MinecraftServer; class Socket; class ServerSettingsChangedPacket; - - -class ServerConnection -{ -// public static Logger logger = Logger.getLogger("Minecraft"); +class ServerConnection { + // public static Logger logger = Logger.getLogger("Minecraft"); private: -// ServerSocket serverSocket; -// private Thread listenThread; + // ServerSocket serverSocket; + // private Thread listenThread; public: - volatile bool running; + volatile bool running; + private: - int connectionCounter; + int connectionCounter; + private: - CRITICAL_SECTION pending_cs; // 4J added - std::vector< std::shared_ptr > pending; - std::vector< std::shared_ptr > players; + CRITICAL_SECTION pending_cs; // 4J added + std::vector > pending; + std::vector > players; - // 4J - When the server requests a texture, it should add it to here while we are waiting for it - std::vector m_pendingTextureRequests; -public: - MinecraftServer *server; + // 4J - When the server requests a texture, it should add it to here while + // we are waiting for it + std::vector m_pendingTextureRequests; public: - ServerConnection(MinecraftServer *server); // 4J - removed params InetAddress address, int port); - ~ServerConnection(); - void NewIncomingSocket(Socket *socket); // 4J - added + MinecraftServer* server; - void removeSpamProtection(Socket *socket) { }// 4J Stu - Not implemented as not required +public: + ServerConnection( + MinecraftServer* + server); // 4J - removed params InetAddress address, int port); + ~ServerConnection(); + void NewIncomingSocket(Socket* socket); // 4J - added + + void removeSpamProtection(Socket* socket) { + } // 4J Stu - Not implemented as not required void addPlayerConnection(std::shared_ptr uc); + private: - void handleConnection(std::shared_ptr uc); + void handleConnection(std::shared_ptr uc); + public: - void stop(); + void stop(); void tick(); - // 4J Added - bool addPendingTextureRequest(const std::wstring &textureName); - void handleTextureReceived(const std::wstring &textureName); - void handleTextureAndGeometryReceived(const std::wstring &textureName); - void handleServerSettingsChanged(std::shared_ptr packet); + // 4J Added + bool addPendingTextureRequest(const std::wstring& textureName); + void handleTextureReceived(const std::wstring& textureName); + void handleTextureAndGeometryReceived(const std::wstring& textureName); + void handleServerSettingsChanged( + std::shared_ptr packet); }; diff --git a/Minecraft.Client/Network/ServerInterface.h b/Minecraft.Client/Network/ServerInterface.h index 883b2106d..55f692c4f 100644 --- a/Minecraft.Client/Network/ServerInterface.h +++ b/Minecraft.Client/Network/ServerInterface.h @@ -1,29 +1,29 @@ #pragma once - -class ServerInterface -{ - virtual int getConfigInt(const std::wstring &name, int defaultValue) = 0; - virtual std::wstring getConfigString(const std::wstring &name, const std::wstring &defaultValue) = 0; - virtual bool getConfigBoolean(const std::wstring &name, bool defaultValue) = 0; - virtual void setProperty(std::wstring &propertyName, void *value) = 0; - virtual void configSave() = 0; - virtual std::wstring getConfigPath() = 0; - virtual std::wstring getServerIp() = 0; - virtual int getServerPort() = 0; - virtual std::wstring getServerName() = 0; - virtual std::wstring getServerVersion() = 0; - virtual int getPlayerCount() = 0; - virtual int getMaxPlayers() = 0; - virtual std::wstring[] getPlayerNames() = 0; - virtual std::wstring getWorldName() = 0; - virtual std::wstring getPluginNames() = 0; - virtual void disablePlugin() = 0; - virtual std::wstring runCommand(const std::wstring &command) = 0; - virtual bool isDebugging() = 0; - // Logging - virtual void info(const std::wstring &string) = 0; - virtual void warn(const std::wstring &string) = 0; - virtual void error(const std::wstring &string) = 0; - virtual void debug(const std::wstring &string) = 0; +class ServerInterface { + virtual int getConfigInt(const std::wstring& name, int defaultValue) = 0; + virtual std::wstring getConfigString(const std::wstring& name, + const std::wstring& defaultValue) = 0; + virtual bool getConfigBoolean(const std::wstring& name, + bool defaultValue) = 0; + virtual void setProperty(std::wstring& propertyName, void* value) = 0; + virtual void configSave() = 0; + virtual std::wstring getConfigPath() = 0; + virtual std::wstring getServerIp() = 0; + virtual int getServerPort() = 0; + virtual std::wstring getServerName() = 0; + virtual std::wstring getServerVersion() = 0; + virtual int getPlayerCount() = 0; + virtual int getMaxPlayers() = 0; + virtual std::wstring[] getPlayerNames() = 0; + virtual std::wstring getWorldName() = 0; + virtual std::wstring getPluginNames() = 0; + virtual void disablePlugin() = 0; + virtual std::wstring runCommand(const std::wstring& command) = 0; + virtual bool isDebugging() = 0; + // Logging + virtual void info(const std::wstring& string) = 0; + virtual void warn(const std::wstring& string) = 0; + virtual void error(const std::wstring& string) = 0; + virtual void debug(const std::wstring& string) = 0; }; \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c index 96fe64b4e..b3407dfb4 100644 --- a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c +++ b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.c @@ -22,16 +22,15 @@ #define false 0 // Iggy GDraw support functions - normally in the Iggy library, stubbed here -void * IggyGDrawMallocAnnotated(SINTa size, const char *file, int line) { - (void)file; (void)line; +void* IggyGDrawMallocAnnotated(SINTa size, const char* file, int line) { + (void)file; + (void)line; return malloc((size_t)size); } -void IggyGDrawFree(void *ptr) { - free(ptr); -} +void IggyGDrawFree(void* ptr) { free(ptr); } -void IggyGDrawSendWarning(Iggy *f, char const *message, ...) { +void IggyGDrawSendWarning(Iggy* f, char const* message, ...) { (void)f; va_list args; va_start(args, message); @@ -41,8 +40,9 @@ void IggyGDrawSendWarning(Iggy *f, char const *message, ...) { va_end(args); } -void IggyDiscardVertexBufferCallback(void *owner, void *buf) { - (void)owner; (void)buf; +void IggyDiscardVertexBufferCallback(void* owner, void* buf) { + (void)owner; + (void)buf; } /////////////////////////////////////////////////////////////////////////////// @@ -55,61 +55,67 @@ void IggyDiscardVertexBufferCallback(void *owner, void *buf) { // The shared code calls them by name and the real functions are used directly. // -#define GDRAW_GL_EXTENSION_LIST \ -/* identifier import procname */ \ -/* GL_ARB_vertex_buffer_object */ \ -GLE(GenBuffers, "GenBuffersARB", GENBUFFERSARB) \ -GLE(DeleteBuffers, "DeleteBuffersARB", DELETEBUFFERSARB) \ -GLE(BindBuffer, "BindBufferARB", BINDBUFFERARB) \ -GLE(BufferData, "BufferDataARB", BUFFERDATAARB) \ -GLE(MapBuffer, "MapBufferARB", MAPBUFFERARB) \ -GLE(UnmapBuffer, "UnmapBufferARB", UNMAPBUFFERARB) \ -GLE(VertexAttribPointer, "VertexAttribPointerARB", VERTEXATTRIBPOINTERARB) \ -GLE(EnableVertexAttribArray, "EnableVertexAttribArrayARB", ENABLEVERTEXATTRIBARRAYARB) \ -GLE(DisableVertexAttribArray, "DisableVertexAttribArrayARB", DISABLEVERTEXATTRIBARRAYARB) \ -/* GL_ARB_shader_objects */ \ -GLE(CreateShader, "CreateShaderObjectARB", CREATESHADEROBJECTARB) \ -GLE(DeleteShader, "DeleteObjectARB", DELETEOBJECTARB) \ -GLE(ShaderSource, "ShaderSourceARB", SHADERSOURCEARB) \ -GLE(CompileShader, "CompileShaderARB", COMPILESHADERARB) \ -GLE(GetShaderiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ -GLE(GetShaderInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ -GLE(CreateProgram, "CreateProgramObjectARB", CREATEPROGRAMOBJECTARB) \ -GLE(DeleteProgram, "DeleteObjectARB", DELETEOBJECTARB) \ -GLE(AttachShader, "AttachObjectARB", ATTACHOBJECTARB) \ -GLE(LinkProgram, "LinkProgramARB", LINKPROGRAMARB) \ -GLE(GetUniformLocation, "GetUniformLocationARB", GETUNIFORMLOCATIONARB) \ -GLE(UseProgram, "UseProgramObjectARB", USEPROGRAMOBJECTARB) \ -GLE(GetProgramiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ -GLE(GetProgramInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ -GLE(Uniform1i, "Uniform1iARB", UNIFORM1IARB) \ -GLE(Uniform4f, "Uniform4fARB", UNIFORM4FARB) \ -GLE(Uniform4fv, "Uniform4fvARB", UNIFORM4FVARB) \ -/* GL_ARB_vertex_shader */ \ -GLE(BindAttribLocation, "BindAttribLocationARB", BINDATTRIBLOCATIONARB) \ -/* Missing from WGL but needed by shared code */ \ -GLE(Uniform1f, "Uniform1fARB", UNIFORM1FARB) \ -/* GL_EXT_framebuffer_object */ \ -GLE(GenRenderbuffers, "GenRenderbuffersEXT", GENRENDERBUFFERSEXT) \ -GLE(DeleteRenderbuffers, "DeleteRenderbuffersEXT", DELETERENDERBUFFERSEXT) \ -GLE(BindRenderbuffer, "BindRenderbufferEXT", BINDRENDERBUFFEREXT) \ -GLE(RenderbufferStorage, "RenderbufferStorageEXT", RENDERBUFFERSTORAGEEXT) \ -GLE(GenFramebuffers, "GenFramebuffersEXT", GENFRAMEBUFFERSEXT) \ -GLE(DeleteFramebuffers, "DeleteFramebuffersEXT", DELETEFRAMEBUFFERSEXT) \ -GLE(BindFramebuffer, "BindFramebufferEXT", BINDFRAMEBUFFEREXT) \ -GLE(CheckFramebufferStatus, "CheckFramebufferStatusEXT", CHECKFRAMEBUFFERSTATUSEXT) \ -GLE(FramebufferRenderbuffer, "FramebufferRenderbufferEXT", FRAMEBUFFERRENDERBUFFEREXT) \ -GLE(FramebufferTexture2D, "FramebufferTexture2DEXT", FRAMEBUFFERTEXTURE2DEXT) \ -GLE(GenerateMipmap, "GenerateMipmapEXT", GENERATEMIPMAPEXT) \ -/* GL_EXT_framebuffer_blit */ \ -GLE(BlitFramebuffer, "BlitFramebufferEXT", BLITFRAMEBUFFEREXT) \ -/* GL_EXT_framebuffer_multisample */ \ -GLE(RenderbufferStorageMultisample, "RenderbufferStorageMultisampleEXT",RENDERBUFFERSTORAGEMULTISAMPLEEXT) \ -/* */ +#define GDRAW_GL_EXTENSION_LIST \ + /* identifier import procname */ \ + /* GL_ARB_vertex_buffer_object */ \ + GLE(GenBuffers, "GenBuffersARB", GENBUFFERSARB) \ + GLE(DeleteBuffers, "DeleteBuffersARB", DELETEBUFFERSARB) \ + GLE(BindBuffer, "BindBufferARB", BINDBUFFERARB) \ + GLE(BufferData, "BufferDataARB", BUFFERDATAARB) \ + GLE(MapBuffer, "MapBufferARB", MAPBUFFERARB) \ + GLE(UnmapBuffer, "UnmapBufferARB", UNMAPBUFFERARB) \ + GLE(VertexAttribPointer, "VertexAttribPointerARB", VERTEXATTRIBPOINTERARB) \ + GLE(EnableVertexAttribArray, "EnableVertexAttribArrayARB", \ + ENABLEVERTEXATTRIBARRAYARB) \ + GLE(DisableVertexAttribArray, "DisableVertexAttribArrayARB", \ + DISABLEVERTEXATTRIBARRAYARB) \ + /* GL_ARB_shader_objects */ \ + GLE(CreateShader, "CreateShaderObjectARB", CREATESHADEROBJECTARB) \ + GLE(DeleteShader, "DeleteObjectARB", DELETEOBJECTARB) \ + GLE(ShaderSource, "ShaderSourceARB", SHADERSOURCEARB) \ + GLE(CompileShader, "CompileShaderARB", COMPILESHADERARB) \ + GLE(GetShaderiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ + GLE(GetShaderInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ + GLE(CreateProgram, "CreateProgramObjectARB", CREATEPROGRAMOBJECTARB) \ + GLE(DeleteProgram, "DeleteObjectARB", DELETEOBJECTARB) \ + GLE(AttachShader, "AttachObjectARB", ATTACHOBJECTARB) \ + GLE(LinkProgram, "LinkProgramARB", LINKPROGRAMARB) \ + GLE(GetUniformLocation, "GetUniformLocationARB", GETUNIFORMLOCATIONARB) \ + GLE(UseProgram, "UseProgramObjectARB", USEPROGRAMOBJECTARB) \ + GLE(GetProgramiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ + GLE(GetProgramInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ + GLE(Uniform1i, "Uniform1iARB", UNIFORM1IARB) \ + GLE(Uniform4f, "Uniform4fARB", UNIFORM4FARB) \ + GLE(Uniform4fv, "Uniform4fvARB", UNIFORM4FVARB) \ + /* GL_ARB_vertex_shader */ \ + GLE(BindAttribLocation, "BindAttribLocationARB", BINDATTRIBLOCATIONARB) \ + /* Missing from WGL but needed by shared code */ \ + GLE(Uniform1f, "Uniform1fARB", UNIFORM1FARB) \ + /* GL_EXT_framebuffer_object */ \ + GLE(GenRenderbuffers, "GenRenderbuffersEXT", GENRENDERBUFFERSEXT) \ + GLE(DeleteRenderbuffers, "DeleteRenderbuffersEXT", DELETERENDERBUFFERSEXT) \ + GLE(BindRenderbuffer, "BindRenderbufferEXT", BINDRENDERBUFFEREXT) \ + GLE(RenderbufferStorage, "RenderbufferStorageEXT", RENDERBUFFERSTORAGEEXT) \ + GLE(GenFramebuffers, "GenFramebuffersEXT", GENFRAMEBUFFERSEXT) \ + GLE(DeleteFramebuffers, "DeleteFramebuffersEXT", DELETEFRAMEBUFFERSEXT) \ + GLE(BindFramebuffer, "BindFramebufferEXT", BINDFRAMEBUFFEREXT) \ + GLE(CheckFramebufferStatus, "CheckFramebufferStatusEXT", \ + CHECKFRAMEBUFFERSTATUSEXT) \ + GLE(FramebufferRenderbuffer, "FramebufferRenderbufferEXT", \ + FRAMEBUFFERRENDERBUFFEREXT) \ + GLE(FramebufferTexture2D, "FramebufferTexture2DEXT", \ + FRAMEBUFFERTEXTURE2DEXT) \ + GLE(GenerateMipmap, "GenerateMipmapEXT", GENERATEMIPMAPEXT) \ + /* GL_EXT_framebuffer_blit */ \ + GLE(BlitFramebuffer, "BlitFramebufferEXT", BLITFRAMEBUFFEREXT) \ + /* GL_EXT_framebuffer_multisample */ \ + GLE(RenderbufferStorageMultisample, "RenderbufferStorageMultisampleEXT", \ + RENDERBUFFERSTORAGEMULTISAMPLEEXT) \ + /* */ -#define gdraw_GLx_(id) gdraw_GL_##id -#define GDRAW_GLx_(id) GDRAW_GL_##id -#define GDRAW_SHADERS "gdraw_gl_shaders.inl" +#define gdraw_GLx_(id) gdraw_GL_##id +#define GDRAW_GLx_(id) GDRAW_GL_##id +#define GDRAW_SHADERS "gdraw_gl_shaders.inl" // On Linux, GLhandleARB is void* (not GLuint) but the shader functions // actually return/take GLuint values. Use GLuint as our handle type, @@ -123,20 +129,18 @@ typedef gdraw_gl_resourcetype gdraw_resourcetype; GDRAW_GL_EXTENSION_LIST #undef GLE -static void load_extensions(void) -{ - #define GLE(id, import, procname) gl##id = (PFNGL##procname##PROC) SDL_GL_GetProcAddress("gl" import); +static void load_extensions(void) { +#define GLE(id, import, procname) \ + gl##id = (PFNGL##procname##PROC)SDL_GL_GetProcAddress("gl" import); GDRAW_GL_EXTENSION_LIST - #undef GLE +#undef GLE } -static void clear_renderstate_platform_specific(void) -{ +static void clear_renderstate_platform_specific(void) { glDisable(GL_ALPHA_TEST); } -static void error_msg_platform_specific(const char *msg) -{ +static void error_msg_platform_specific(const char* msg) { fprintf(stderr, "[GDraw GL] %s\n", msg); } @@ -151,7 +155,10 @@ static void error_msg_platform_specific(const char *msg) #ifdef RR_BREAK #undef RR_BREAK #endif -#define RR_BREAK() do { fprintf(stderr, "[GDraw] RR_BREAK suppressed (GL error)\n"); } while(0) +#define RR_BREAK() \ + do { \ + fprintf(stderr, "[GDraw] RR_BREAK suppressed (GL error)\n"); \ + } while (0) #include "../../../Windows64/Iggy/gdraw/gdraw_gl_shared.inl" @@ -160,32 +167,42 @@ static void error_msg_platform_specific(const char *msg) // Initialization and platform-specific functionality // -GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) -{ +GDrawFunctions* gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) { static const TextureFormatDesc tex_formats[] = { - { IFT_FORMAT_rgba_8888, 1, 1, 4, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_rgba_4444_LE, 1, 1, 2, GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 }, - { IFT_FORMAT_rgba_5551_LE, 1, 1, 2, GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 }, - { IFT_FORMAT_la_88, 1, 1, 2, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_la_44, 1, 1, 1, GL_LUMINANCE4_ALPHA4, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_i_8, 1, 1, 1, GL_INTENSITY8, GL_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_i_4, 1, 1, 1, GL_INTENSITY4, GL_ALPHA, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_l_8, 1, 1, 1, GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_l_4, 1, 1, 1, GL_LUMINANCE4, GL_LUMINANCE, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_DXT1, 4, 4, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_DXT3, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0, GL_UNSIGNED_BYTE }, - { IFT_FORMAT_DXT5, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0, GL_UNSIGNED_BYTE }, - { 0, 0, 0, 0, 0, 0, 0 }, + {IFT_FORMAT_rgba_8888, 1, 1, 4, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE}, + {IFT_FORMAT_rgba_4444_LE, 1, 1, 2, GL_RGBA4, GL_RGBA, + GL_UNSIGNED_SHORT_4_4_4_4}, + {IFT_FORMAT_rgba_5551_LE, 1, 1, 2, GL_RGB5_A1, GL_RGBA, + GL_UNSIGNED_SHORT_5_5_5_1}, + {IFT_FORMAT_la_88, 1, 1, 2, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_la_44, 1, 1, 1, GL_LUMINANCE4_ALPHA4, GL_LUMINANCE_ALPHA, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_i_8, 1, 1, 1, GL_INTENSITY8, GL_ALPHA, GL_UNSIGNED_BYTE}, + {IFT_FORMAT_i_4, 1, 1, 1, GL_INTENSITY4, GL_ALPHA, GL_UNSIGNED_BYTE}, + {IFT_FORMAT_l_8, 1, 1, 1, GL_LUMINANCE8, GL_LUMINANCE, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_l_4, 1, 1, 1, GL_LUMINANCE4, GL_LUMINANCE, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_DXT1, 4, 4, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_DXT3, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0, + GL_UNSIGNED_BYTE}, + {IFT_FORMAT_DXT5, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0, + GL_UNSIGNED_BYTE}, + {0, 0, 0, 0, 0, 0, 0}, }; - GDrawFunctions *funcs; - const char *s; + GDrawFunctions* funcs; + const char* s; GLint n; // check for the extensions we need - s = (const char *) glGetString(GL_EXTENSIONS); + s = (const char*)glGetString(GL_EXTENSIONS); if (s == NULL) { - fprintf(stderr, "[GDraw GL] glGetString(GL_EXTENSIONS) returned NULL - GL context not current?\n"); + fprintf(stderr, + "[GDraw GL] glGetString(GL_EXTENSIONS) returned NULL - GL " + "context not current?\n"); assert(s != NULL); return NULL; } @@ -199,8 +216,7 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) !hasext(s, "GL_EXT_framebuffer_object") || !hasext(s, "GL_ARB_shader_objects") || !hasext(s, "GL_ARB_vertex_shader") || - !hasext(s, "GL_ARB_fragment_shader")) - { + !hasext(s, "GL_ARB_fragment_shader")) { fprintf(stderr, "[GDraw GL] Required GL extensions not available\n"); return NULL; } @@ -211,17 +227,17 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) load_extensions(); funcs = create_context(w, h); - if (!funcs) - return NULL; + if (!funcs) return NULL; gdraw->tex_formats = tex_formats; // check for optional extensions - gdraw->has_mapbuffer = true; // part of core VBO extension on regular GL - gdraw->has_depth24 = true; // we just assume. - gdraw->has_texture_max_level = true; // core on regular GL + gdraw->has_mapbuffer = true; // part of core VBO extension on regular GL + gdraw->has_depth24 = true; // we just assume. + gdraw->has_texture_max_level = true; // core on regular GL - if (hasext(s, "GL_EXT_packed_depth_stencil")) gdraw->has_packed_depth_stencil = true; + if (hasext(s, "GL_EXT_packed_depth_stencil")) + gdraw->has_packed_depth_stencil = true; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &n); gdraw->has_conditional_non_power_of_two = n < 8192; @@ -234,7 +250,9 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) opengl_check(); - fprintf(stderr, "[GDraw GL] Context created successfully (%dx%d, msaa=%d)\n", w, h, msaa_samples); + fprintf(stderr, + "[GDraw GL] Context created successfully (%dx%d, msaa=%d)\n", w, h, + msaa_samples); return funcs; } @@ -243,14 +261,15 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) // 4J-specific custom draw functions // -void gdraw_GL_BeginCustomDraw_4J(IggyCustomDrawCallbackRegion *region, F32 *matrix) -{ +void gdraw_GL_BeginCustomDraw_4J(IggyCustomDrawCallbackRegion* region, + F32* matrix) { // Same as BeginCustomDraw but uses different depth param clear_renderstate(); - gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, depth_from_id(0), 1); + gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, + depth_from_id(0), 1); } -void gdraw_GL_CalculateCustomDraw_4J(IggyCustomDrawCallbackRegion *region, F32 *matrix) -{ +void gdraw_GL_CalculateCustomDraw_4J(IggyCustomDrawCallbackRegion* region, + F32* matrix) { gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, 0.0f, 0); } diff --git a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h index 7210565d2..cd8cc8281 100644 --- a/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h +++ b/Minecraft.Client/Platform/Linux/Iggy/gdraw/gdraw_glfw.h @@ -8,35 +8,49 @@ extern "C" { #endif -typedef enum gdraw_gl_resourcetype -{ - GDRAW_GL_RESOURCE_rendertarget, - GDRAW_GL_RESOURCE_texture, - GDRAW_GL_RESOURCE_vertexbuffer, +typedef enum gdraw_gl_resourcetype { + GDRAW_GL_RESOURCE_rendertarget, + GDRAW_GL_RESOURCE_texture, + GDRAW_GL_RESOURCE_vertexbuffer, - GDRAW_GL_RESOURCE__count, + GDRAW_GL_RESOURCE__count, } gdraw_gl_resourcetype; struct IggyCustomDrawCallbackRegion; -extern int gdraw_GL_SetResourceLimits(gdraw_gl_resourcetype type, S32 num_handles, S32 num_bytes); -extern GDrawFunctions * gdraw_GL_CreateContext(S32 min_w, S32 min_h, S32 msaa_samples); +extern int gdraw_GL_SetResourceLimits(gdraw_gl_resourcetype type, + S32 num_handles, S32 num_bytes); +extern GDrawFunctions* gdraw_GL_CreateContext(S32 min_w, S32 min_h, + S32 msaa_samples); extern void gdraw_GL_DestroyContext(void); -extern void gdraw_GL_SetTileOrigin(S32 vx, S32 vy, unsigned int framebuffer); // framebuffer=FBO handle, or 0 for main frame buffer +extern void gdraw_GL_SetTileOrigin( + S32 vx, S32 vy, + unsigned int + framebuffer); // framebuffer=FBO handle, or 0 for main frame buffer extern void gdraw_GL_NoMoreGDrawThisFrame(void); -extern GDrawTexture *gdraw_GL_WrappedTextureCreate(S32 gl_texture_handle, S32 width, S32 height, int has_mipmaps); -extern void gdraw_GL_WrappedTextureChange(GDrawTexture *tex, S32 new_gl_texture_handle, S32 new_width, S32 new_height, int new_has_mipmaps); -extern void gdraw_GL_WrappedTextureDestroy(GDrawTexture *tex); +extern GDrawTexture* gdraw_GL_WrappedTextureCreate(S32 gl_texture_handle, + S32 width, S32 height, + int has_mipmaps); +extern void gdraw_GL_WrappedTextureChange(GDrawTexture* tex, + S32 new_gl_texture_handle, + S32 new_width, S32 new_height, + int new_has_mipmaps); +extern void gdraw_GL_WrappedTextureDestroy(GDrawTexture* tex); -extern void gdraw_GL_BeginCustomDraw(struct IggyCustomDrawCallbackRegion *region, float *matrix); -extern void gdraw_GL_EndCustomDraw(struct IggyCustomDrawCallbackRegion *region); +extern void gdraw_GL_BeginCustomDraw( + struct IggyCustomDrawCallbackRegion* region, float* matrix); +extern void gdraw_GL_EndCustomDraw(struct IggyCustomDrawCallbackRegion* region); -extern void gdraw_GL_CalculateCustomDraw_4J(struct IggyCustomDrawCallbackRegion *region, float *matrix); -extern void gdraw_GL_BeginCustomDraw_4J(struct IggyCustomDrawCallbackRegion *region, float *matrix); +extern void gdraw_GL_CalculateCustomDraw_4J( + struct IggyCustomDrawCallbackRegion* region, float* matrix); +extern void gdraw_GL_BeginCustomDraw_4J( + struct IggyCustomDrawCallbackRegion* region, float* matrix); -extern GDrawTexture * gdraw_GL_MakeTextureFromResource(unsigned char *resource_file, S32 resource_len, IggyFileTextureRaw *texture); -extern void gdraw_GL_DestroyTextureFromResource(GDrawTexture *tex); +extern GDrawTexture* gdraw_GL_MakeTextureFromResource( + unsigned char* resource_file, S32 resource_len, + IggyFileTextureRaw* texture); +extern void gdraw_GL_DestroyTextureFromResource(GDrawTexture* tex); #ifdef __cplusplus } diff --git a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp index ebb870584..3c82b10a2 100644 --- a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp +++ b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.cpp @@ -2,4 +2,6 @@ #include "LinuxLeaderboardManager.h" -LeaderboardManager *LeaderboardManager::m_instance = new LinuxLeaderboardManager(); //Singleton instance of the LeaderboardManager \ No newline at end of file +LeaderboardManager* LeaderboardManager::m_instance = + new LinuxLeaderboardManager(); // Singleton instance of the + // LeaderboardManager \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h index 50696c37d..641622381 100644 --- a/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h +++ b/Minecraft.Client/Platform/Linux/Leaderboards/LinuxLeaderboardManager.h @@ -2,35 +2,50 @@ #include "../../Common/Leaderboards/LeaderboardManager.h" -class LinuxLeaderboardManager : public LeaderboardManager -{ +class LinuxLeaderboardManager : public LeaderboardManager { public: - virtual void Tick() {} + virtual void Tick() {} - //Open a session - virtual bool OpenSession() { return true; } + // Open a session + virtual bool OpenSession() { return true; } - //Close a session - virtual void CloseSession() {} + // Close a session + virtual void CloseSession() {} - //Delete a session - virtual void DeleteSession() {} + // Delete a session + virtual void DeleteSession() {} - //Write the given stats - //This is called synchronously and will not free any memory allocated for views when it is done + // Write the given stats + // This is called synchronously and will not free any memory allocated for + // views when it is done - virtual bool WriteStats(unsigned int viewCount, ViewIn views) { return false; } + virtual bool WriteStats(unsigned int viewCount, ViewIn views) { + return false; + } - virtual bool ReadStats_Friends(LeaderboardReadListener *callback, int difficulty, EStatsType type, PlayerUID myUID) { return false; } - virtual bool ReadStats_MyScore(LeaderboardReadListener *callback, int difficulty, EStatsType type, PlayerUID myUID, unsigned int readCount) { return false; } - virtual bool ReadStats_TopRank(LeaderboardReadListener *callback, int difficulty, EStatsType type, unsigned int startIndex, unsigned int readCount) { return false; } + virtual bool ReadStats_Friends(LeaderboardReadListener* callback, + int difficulty, EStatsType type, + PlayerUID myUID) { + return false; + } + virtual bool ReadStats_MyScore(LeaderboardReadListener* callback, + int difficulty, EStatsType type, + PlayerUID myUID, unsigned int readCount) { + return false; + } + virtual bool ReadStats_TopRank(LeaderboardReadListener* callback, + int difficulty, EStatsType type, + unsigned int startIndex, + unsigned int readCount) { + return false; + } - //Perform a flush of the stats - virtual void FlushStats() {} + // Perform a flush of the stats + virtual void FlushStats() {} - //Cancel the current operation - virtual void CancelOperation() {} + // Cancel the current operation + virtual void CancelOperation() {} - //Is the leaderboard manager idle. - virtual bool isIdle() { return true; } + // Is the leaderboard manager idle. + virtual bool isIdle() { return true; } }; diff --git a/Minecraft.Client/Platform/Linux/LinuxGL.cpp b/Minecraft.Client/Platform/Linux/LinuxGL.cpp index 29d312b35..fd4919b0b 100644 --- a/Minecraft.Client/Platform/Linux/LinuxGL.cpp +++ b/Minecraft.Client/Platform/Linux/LinuxGL.cpp @@ -9,96 +9,81 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "../../Minecraft.World/IO/Streams/ByteBuffer.h" - -int glGenTextures() -{ - GLuint id = 0; - ::glGenTextures(1, &id); - return (int)id; +int glGenTextures() { + GLuint id = 0; + ::glGenTextures(1, &id); + return (int)id; } -void glGenTextures(IntBuffer *buf) -{ - GLuint id = 0; - ::glGenTextures(1, &id); - buf->put((int)id); - buf->flip(); +void glGenTextures(IntBuffer* buf) { + GLuint id = 0; + ::glGenTextures(1, &id); + buf->put((int)id); + buf->flip(); } -void glDeleteTextures(int id) -{ - GLuint uid = (GLuint)id; - ::glDeleteTextures(1, &uid); +void glDeleteTextures(int id) { + GLuint uid = (GLuint)id; + ::glDeleteTextures(1, &uid); } -void glDeleteTextures(IntBuffer *buf) -{ - int id = buf->get(0); - GLuint uid = (GLuint)id; - ::glDeleteTextures(1, &uid); +void glDeleteTextures(IntBuffer* buf) { + int id = buf->get(0); + GLuint uid = (GLuint)id; + ::glDeleteTextures(1, &uid); } -void glLight(int light, int pname, FloatBuffer *params) -{ - ::glLightfv((GLenum)light, (GLenum)pname, params->_getDataPointer()); +void glLight(int light, int pname, FloatBuffer* params) { + ::glLightfv((GLenum)light, (GLenum)pname, params->_getDataPointer()); } -void glLightModel(int pname, FloatBuffer *params) -{ - ::glLightModelfv((GLenum)pname, params->_getDataPointer()); +void glLightModel(int pname, FloatBuffer* params) { + ::glLightModelfv((GLenum)pname, params->_getDataPointer()); } -void glGetFloat(int pname, FloatBuffer *params) -{ - ::glGetFloatv((GLenum)pname, params->_getDataPointer()); +void glGetFloat(int pname, FloatBuffer* params) { + ::glGetFloatv((GLenum)pname, params->_getDataPointer()); } -void glTexGen(int coord, int pname, FloatBuffer *params) -{ - ::glTexGenfv((GLenum)coord, (GLenum)pname, params->_getDataPointer()); +void glTexGen(int coord, int pname, FloatBuffer* params) { + ::glTexGenfv((GLenum)coord, (GLenum)pname, params->_getDataPointer()); } -void glFog(int pname, FloatBuffer *params) -{ - ::glFogfv((GLenum)pname, params->_getDataPointer()); +void glFog(int pname, FloatBuffer* params) { + ::glFogfv((GLenum)pname, params->_getDataPointer()); } -void glTexCoordPointer(int size, int type, FloatBuffer *pointer) -{ - ::glTexCoordPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); +void glTexCoordPointer(int size, int type, FloatBuffer* pointer) { + ::glTexCoordPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); } -void glNormalPointer(int type, ByteBuffer *pointer) -{ - ::glNormalPointer((GLenum)type, 0, pointer->getBuffer()); +void glNormalPointer(int type, ByteBuffer* pointer) { + ::glNormalPointer((GLenum)type, 0, pointer->getBuffer()); } -void glColorPointer(int size, bool normalized, int stride, ByteBuffer *pointer) -{ - (void)normalized; - ::glColorPointer(size, GL_UNSIGNED_BYTE, stride, pointer->getBuffer()); +void glColorPointer(int size, bool normalized, int stride, + ByteBuffer* pointer) { + (void)normalized; + ::glColorPointer(size, GL_UNSIGNED_BYTE, stride, pointer->getBuffer()); } -void glVertexPointer(int size, int type, FloatBuffer *pointer) -{ - ::glVertexPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); +void glVertexPointer(int size, int type, FloatBuffer* pointer) { + ::glVertexPointer(size, (GLenum)type, 0, pointer->_getDataPointer()); } -void glEndList(int) -{ - ::glEndList(); +void glEndList(int) { ::glEndList(); } + +void glTexImage2D(int target, int level, int internalformat, int width, + int height, int border, int format, int type, + ByteBuffer* pixels) { + void* data = pixels ? pixels->getBuffer() : nullptr; + ::glTexImage2D((GLenum)target, level, internalformat, width, height, border, + (GLenum)format, (GLenum)type, data); } -void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer *pixels) -{ - void *data = pixels ? pixels->getBuffer() : nullptr; - ::glTexImage2D((GLenum)target, level, internalformat, width, height, border, (GLenum)format, (GLenum)type, data); -} - -void glCallLists(IntBuffer *lists) -{ - int count = lists->limit() - lists->position(); - ::glCallLists(count, GL_INT, lists->getBuffer()); +void glCallLists(IntBuffer* lists) { + int count = lists->limit() - lists->position(); + ::glCallLists(count, GL_INT, lists->getBuffer()); } static PFNGLGENQUERIESARBPROC _glGenQueriesARB = nullptr; @@ -107,55 +92,52 @@ static PFNGLENDQUERYARBPROC _glEndQueryARB = nullptr; static PFNGLGETQUERYOBJECTUIVARBPROC _glGetQueryObjectuivARB = nullptr; static bool _queriesInitialized = false; -static void initQueryFuncs() -{ - if (_queriesInitialized) return; - _queriesInitialized = true; - _glGenQueriesARB = (PFNGLGENQUERIESARBPROC)dlsym(RTLD_DEFAULT, "glGenQueriesARB"); - _glBeginQueryARB = (PFNGLBEGINQUERYARBPROC)dlsym(RTLD_DEFAULT, "glBeginQueryARB"); - _glEndQueryARB = (PFNGLENDQUERYARBPROC)dlsym(RTLD_DEFAULT, "glEndQueryARB"); - _glGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)dlsym(RTLD_DEFAULT, "glGetQueryObjectuivARB"); +static void initQueryFuncs() { + if (_queriesInitialized) return; + _queriesInitialized = true; + _glGenQueriesARB = + (PFNGLGENQUERIESARBPROC)dlsym(RTLD_DEFAULT, "glGenQueriesARB"); + _glBeginQueryARB = + (PFNGLBEGINQUERYARBPROC)dlsym(RTLD_DEFAULT, "glBeginQueryARB"); + _glEndQueryARB = (PFNGLENDQUERYARBPROC)dlsym(RTLD_DEFAULT, "glEndQueryARB"); + _glGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)dlsym( + RTLD_DEFAULT, "glGetQueryObjectuivARB"); } -void glGenQueriesARB(IntBuffer *buf) -{ - initQueryFuncs(); - if (_glGenQueriesARB) - { - GLuint id = 0; - _glGenQueriesARB(1, &id); - buf->put((int)id); - buf->flip(); - } +void glGenQueriesARB(IntBuffer* buf) { + initQueryFuncs(); + if (_glGenQueriesARB) { + GLuint id = 0; + _glGenQueriesARB(1, &id); + buf->put((int)id); + buf->flip(); + } } -void glBeginQueryARB(int target, int id) -{ - initQueryFuncs(); - if (_glBeginQueryARB) _glBeginQueryARB((GLenum)target, (GLuint)id); +void glBeginQueryARB(int target, int id) { + initQueryFuncs(); + if (_glBeginQueryARB) _glBeginQueryARB((GLenum)target, (GLuint)id); } -void glEndQueryARB(int target) -{ - initQueryFuncs(); - if (_glEndQueryARB) _glEndQueryARB((GLenum)target); +void glEndQueryARB(int target) { + initQueryFuncs(); + if (_glEndQueryARB) _glEndQueryARB((GLenum)target); } -void glGetQueryObjectuARB(int id, int pname, IntBuffer *params) -{ - initQueryFuncs(); - if (_glGetQueryObjectuivARB) - { - GLuint val = 0; - _glGetQueryObjectuivARB((GLuint)id, (GLenum)pname, &val); - params->put((int)val); - params->flip(); - } +void glGetQueryObjectuARB(int id, int pname, IntBuffer* params) { + initQueryFuncs(); + if (_glGetQueryObjectuivARB) { + GLuint val = 0; + _glGetQueryObjectuivARB((GLuint)id, (GLenum)pname, &val); + params->put((int)val); + params->flip(); + } } -void glReadPixels(int x, int y, int width, int height, int format, int type, ByteBuffer *pixels) -{ - ::glReadPixels(x, y, width, height, (GLenum)format, (GLenum)type, pixels->getBuffer()); +void glReadPixels(int x, int y, int width, int height, int format, int type, + ByteBuffer* pixels) { + ::glReadPixels(x, y, width, height, (GLenum)format, (GLenum)type, + pixels->getBuffer()); } #endif diff --git a/Minecraft.Client/Linux/LinuxGL.h b/Minecraft.Client/Platform/Linux/LinuxGL.h similarity index 50% rename from Minecraft.Client/Linux/LinuxGL.h rename to Minecraft.Client/Platform/Linux/LinuxGL.h index ccdf4553f..2d8ab33fb 100644 --- a/Minecraft.Client/Linux/LinuxGL.h +++ b/Minecraft.Client/Platform/Linux/LinuxGL.h @@ -9,31 +9,31 @@ class FloatBuffer; class IntBuffer; class ByteBuffer; -void glGenTextures(IntBuffer *); +void glGenTextures(IntBuffer*); int glGenTextures(); -void glDeleteTextures(IntBuffer *); -void glLight(int, int, FloatBuffer *); -void glLightModel(int, FloatBuffer *); -void glGetFloat(int a, FloatBuffer *b); +void glDeleteTextures(IntBuffer*); +void glLight(int, int, FloatBuffer*); +void glLightModel(int, FloatBuffer*); +void glGetFloat(int a, FloatBuffer* b); void glTexCoordPointer(int, int, int, int); -void glTexCoordPointer(int, int, FloatBuffer *); +void glTexCoordPointer(int, int, FloatBuffer*); void glNormalPointer(int, int, int); -void glNormalPointer(int, ByteBuffer *); -void glColorPointer(int, bool, int, ByteBuffer *); +void glNormalPointer(int, ByteBuffer*); +void glColorPointer(int, bool, int, ByteBuffer*); void glColorPointer(int, int, int, int); void glVertexPointer(int, int, int, int); -void glVertexPointer(int, int, FloatBuffer *); +void glVertexPointer(int, int, FloatBuffer*); void glNewList(int, int); void glEndList(int vertexCount = 0); -void glTexImage2D(int, int, int, int, int, int, int, int, ByteBuffer *); -void glCallLists(IntBuffer *); -void glGenQueriesARB(IntBuffer *); +void glTexImage2D(int, int, int, int, int, int, int, int, ByteBuffer*); +void glCallLists(IntBuffer*); +void glGenQueriesARB(IntBuffer*); void glBeginQueryARB(int, int); void glEndQueryARB(int); -void glGetQueryObjectuARB(int, int, IntBuffer *); -void glFog(int, FloatBuffer *); -void glTexGen(int, int, FloatBuffer *); -void glReadPixels(int, int, int, int, int, int, ByteBuffer *); +void glGetQueryObjectuARB(int, int, IntBuffer*); +void glFog(int, FloatBuffer*); +void glTexGen(int, int, FloatBuffer*); +void glReadPixels(int, int, int, int, int, int, ByteBuffer*); void glTexGeni(int, int, int); void glMultiTexCoord2f(int, float, float); void glClientActiveTexture(int); diff --git a/Minecraft.Client/Platform/Linux/Linux_App.cpp b/Minecraft.Client/Platform/Linux/Linux_App.cpp index 332537d07..0193d2840 100644 --- a/Minecraft.Client/Platform/Linux/Linux_App.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_App.cpp @@ -13,64 +13,55 @@ CConsoleMinecraftApp app; -#define CONTEXT_GAME_STATE 0 +#define CONTEXT_GAME_STATE 0 -CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() -{ +CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() {} + +void CConsoleMinecraftApp::SetRichPresenceContext(int iPad, int contextId) { + ProfileManager.SetRichPresenceContextValue(iPad, CONTEXT_GAME_STATE, + contextId); } -void CConsoleMinecraftApp::SetRichPresenceContext(int iPad, int contextId) -{ - ProfileManager.SetRichPresenceContextValue(iPad,CONTEXT_GAME_STATE,contextId); -} - -void CConsoleMinecraftApp::StoreLaunchData() -{ -} -void CConsoleMinecraftApp::ExitGame() -{ -} -void CConsoleMinecraftApp::FatalLoadError() -{ - app.DebugPrintf("CConsoleMinecraftApp::FatalLoadError - asserting 0 and dying...\n"); +void CConsoleMinecraftApp::StoreLaunchData() {} +void CConsoleMinecraftApp::ExitGame() {} +void CConsoleMinecraftApp::FatalLoadError() { + app.DebugPrintf( + "CConsoleMinecraftApp::FatalLoadError - asserting 0 and dying...\n"); assert(0); } -void CConsoleMinecraftApp::CaptureSaveThumbnail() -{ -} -void CConsoleMinecraftApp::GetSaveThumbnail(std::uint8_t **thumbnailData, unsigned int *thumbnailSize) -{ -} -void CConsoleMinecraftApp::ReleaseSaveThumbnail() -{ -} +void CConsoleMinecraftApp::CaptureSaveThumbnail() {} +void CConsoleMinecraftApp::GetSaveThumbnail(std::uint8_t** thumbnailData, + unsigned int* thumbnailSize) {} +void CConsoleMinecraftApp::ReleaseSaveThumbnail() {} -void CConsoleMinecraftApp::GetScreenshot(int iPad, std::uint8_t **screenshotData, unsigned int *screenshotSize) -{ -} +void CConsoleMinecraftApp::GetScreenshot(int iPad, + std::uint8_t** screenshotData, + unsigned int* screenshotSize) {} -void CConsoleMinecraftApp::TemporaryCreateGameStart() -{ - ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit +void CConsoleMinecraftApp::TemporaryCreateGameStart() { + ////////////////////////////////////////////////////////////////////////////////////////////// + ///From CScene_Main::OnInit app.setLevelGenerationOptions(NULL); // From CScene_Main::RunPlayGame - Minecraft *pMinecraft=Minecraft::GetInstance(); + Minecraft* pMinecraft = Minecraft::GetInstance(); app.ReleaseSaveThumbnail(); ProfileManager.SetLockedProfile(0); pMinecraft->user->name = L"Windows"; app.ApplyGameSettingsChanged(0); - ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameJoinLoad::OnInit + ////////////////////////////////////////////////////////////////////////////////////////////// + ///From CScene_MultiGameJoinLoad::OnInit MinecraftServer::resetFlags(); // From CScene_MultiGameJoinLoad::OnNotifyPressEx - app.SetTutorialMode( false ); + app.SetTutorialMode(false); app.SetCorruptSaveDeleted(false); - ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameCreate::CreateGame + ////////////////////////////////////////////////////////////////////////////////////////////// + ///From CScene_MultiGameCreate::CreateGame app.ClearTerrainFeaturePosition(); std::wstring wWorldName = L"TestWorld"; @@ -79,60 +70,62 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() StorageManager.SetSaveTitle(wWorldName.c_str()); bool isFlat = false; - __int64 seedValue = 0; // BiomeSource::findSeed(isFlat?LevelType::lvl_flat:LevelType::lvl_normal); // 4J - was (new Random())->nextLong() - now trying to actually find a seed to suit our requirements + __int64 seedValue = + 0; // BiomeSource::findSeed(isFlat?LevelType::lvl_flat:LevelType::lvl_normal); + // // 4J - was (new Random())->nextLong() - now trying to actually + // find a seed to suit our requirements - NetworkGameInitData *param = new NetworkGameInitData(); + NetworkGameInitData* param = new NetworkGameInitData(); param->seed = seedValue; param->saveData = NULL; - app.SetGameHostOption(eGameHostOption_Difficulty,0); - app.SetGameHostOption(eGameHostOption_FriendsOfFriends,0); - app.SetGameHostOption(eGameHostOption_Gamertags,1); - app.SetGameHostOption(eGameHostOption_BedrockFog,1); + app.SetGameHostOption(eGameHostOption_Difficulty, 0); + app.SetGameHostOption(eGameHostOption_FriendsOfFriends, 0); + app.SetGameHostOption(eGameHostOption_Gamertags, 1); + app.SetGameHostOption(eGameHostOption_BedrockFog, 1); - app.SetGameHostOption(eGameHostOption_GameType,GameType::CREATIVE->getId() ); // LevelSettings::GAMETYPE_SURVIVAL - app.SetGameHostOption(eGameHostOption_LevelType, 0 ); - app.SetGameHostOption(eGameHostOption_Structures, 1 ); - app.SetGameHostOption(eGameHostOption_BonusChest, 0 ); + app.SetGameHostOption( + eGameHostOption_GameType, + GameType::CREATIVE->getId()); // LevelSettings::GAMETYPE_SURVIVAL + app.SetGameHostOption(eGameHostOption_LevelType, 0); + app.SetGameHostOption(eGameHostOption_Structures, 1); + app.SetGameHostOption(eGameHostOption_BonusChest, 0); app.SetGameHostOption(eGameHostOption_PvP, 1); - app.SetGameHostOption(eGameHostOption_TrustPlayers, 1 ); - app.SetGameHostOption(eGameHostOption_FireSpreads, 1 ); - app.SetGameHostOption(eGameHostOption_TNT, 1 ); + app.SetGameHostOption(eGameHostOption_TrustPlayers, 1); + app.SetGameHostOption(eGameHostOption_FireSpreads, 1); + app.SetGameHostOption(eGameHostOption_TNT, 1); app.SetGameHostOption(eGameHostOption_HostCanFly, 1); app.SetGameHostOption(eGameHostOption_HostCanChangeHunger, 1); - app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1 ); + app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1); - param->settings = app.GetGameHostOption( eGameHostOption_All ); + param->settings = app.GetGameHostOption(eGameHostOption_All); g_NetworkManager.FakeLocalPlayerJoined(); - LoadingInputParams *loadingParams = new LoadingInputParams(); + LoadingInputParams* loadingParams = new LoadingInputParams(); loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; loadingParams->lpParam = (LPVOID)param; // Reset the autosave time app.SetAutosaveTimerTime(); - C4JThread* thread = new C4JThread(loadingParams->func, loadingParams->lpParam, "RunNetworkGame"); + C4JThread* thread = new C4JThread(loadingParams->func, + loadingParams->lpParam, "RunNetworkGame"); thread->Run(); } -int CConsoleMinecraftApp::GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT) -{ +int CConsoleMinecraftApp::GetLocalTMSFileIndex(WCHAR* wchTMSFile, + bool bFilenameIncludesExtension, + eFileExtensionType eEXT) { return -1; } -int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile) -{ +int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR* wchTMSFile) { return -1; } + +int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR* wchTMSFile, + eFileExtensionType eExt) { return -1; } -int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile, eFileExtensionType eExt) -{ - return -1; -} - -void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) -{ -} +void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) {} diff --git a/Minecraft.Client/Platform/Linux/Linux_App.h b/Minecraft.Client/Platform/Linux/Linux_App.h index f15afd928..bdbe65d95 100644 --- a/Minecraft.Client/Platform/Linux/Linux_App.h +++ b/Minecraft.Client/Platform/Linux/Linux_App.h @@ -1,34 +1,38 @@ #pragma once -class CConsoleMinecraftApp : public CMinecraftApp -{ +class CConsoleMinecraftApp : public CMinecraftApp { public: - CConsoleMinecraftApp(); + CConsoleMinecraftApp(); - virtual void SetRichPresenceContext(int iPad, int contextId); + virtual void SetRichPresenceContext(int iPad, int contextId); - virtual void StoreLaunchData(); - virtual void ExitGame(); - virtual void FatalLoadError(); + virtual void StoreLaunchData(); + virtual void ExitGame(); + virtual void FatalLoadError(); - virtual void CaptureSaveThumbnail(); - virtual void GetSaveThumbnail(std::uint8_t **thumbnailData, unsigned int *thumbnailSize); - virtual void ReleaseSaveThumbnail(); - virtual void GetScreenshot(int iPad, std::uint8_t **screenshotData, unsigned int *screenshotSize); + virtual void CaptureSaveThumbnail(); + virtual void GetSaveThumbnail(std::uint8_t** thumbnailData, + unsigned int* thumbnailSize); + virtual void ReleaseSaveThumbnail(); + virtual void GetScreenshot(int iPad, std::uint8_t** screenshotData, + unsigned int* screenshotSize); - virtual int LoadLocalTMSFile(WCHAR *wchTMSFile); - virtual int LoadLocalTMSFile(WCHAR *wchTMSFile, eFileExtensionType eExt); + virtual int LoadLocalTMSFile(WCHAR* wchTMSFile); + virtual int LoadLocalTMSFile(WCHAR* wchTMSFile, eFileExtensionType eExt); - virtual void FreeLocalTMSFiles(eTMSFileType eType); - virtual int GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT=eFileExtensionType_PNG); + virtual void FreeLocalTMSFiles(eTMSFileType eType); + virtual int GetLocalTMSFileIndex( + WCHAR* wchTMSFile, bool bFilenameIncludesExtension, + eFileExtensionType eEXT = eFileExtensionType_PNG); - // BANNED LEVEL LIST - virtual void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false) {} + // BANNED LEVEL LIST + virtual void ReadBannedList(int iPad, eTMSAction action = (eTMSAction)0, + bool bCallback = false) {} - C4JStringTable *GetStringTable() { return NULL;} + C4JStringTable* GetStringTable() { return NULL; } - // original code - virtual void TemporaryCreateGameStart(); + // original code + virtual void TemporaryCreateGameStart(); }; extern CConsoleMinecraftApp app; diff --git a/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp b/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp index 14729679c..58087546d 100644 --- a/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_Minecraft.cpp @@ -4,7 +4,7 @@ #include "../../../Minecraft.World/Platform/stdafx.h" #include -//#include +// #include #include #if defined(__linux__) && defined(__GLIBC__) #include @@ -12,20 +12,29 @@ #include static void sigsegv_handler(int sig) { const char msg[] = "\n=== SIGNAL CAUGHT: "; - write(STDERR_FILENO, msg, sizeof(msg)-1); + write(STDERR_FILENO, msg, sizeof(msg) - 1); char signum[8]; int len = 0; int s = sig; - if (s == 0) { signum[len++] = '0'; } - else { char tmp[8]; int tl = 0; while(s > 0) { tmp[tl++] = '0' + (s%10); s /= 10; } for(int i = tl-1; i >= 0; i--) signum[len++] = tmp[i]; } + if (s == 0) { + signum[len++] = '0'; + } else { + char tmp[8]; + int tl = 0; + while (s > 0) { + tmp[tl++] = '0' + (s % 10); + s /= 10; + } + for (int i = tl - 1; i >= 0; i--) signum[len++] = tmp[i]; + } write(STDERR_FILENO, signum, len); const char msg1b[] = " ===\n"; - write(STDERR_FILENO, msg1b, sizeof(msg1b)-1); - void *array[64]; + write(STDERR_FILENO, msg1b, sizeof(msg1b) - 1); + void* array[64]; int size = backtrace(array, 64); backtrace_symbols_fd(array, size, STDERR_FILENO); const char msg2[] = "=== END BACKTRACE ===\n"; - write(STDERR_FILENO, msg2, sizeof(msg2)-1); + write(STDERR_FILENO, msg2, sizeof(msg2) - 1); _exit(139); } #endif @@ -49,10 +58,10 @@ static void sigsegv_handler(int sig) { #include "../../../Minecraft.World/Util/ThreadName.h" #include "../../GameState/StatsCounter.h" #include "../../UI/Screens/ConnectScreen.h" -//#include "../Durango/Social/SocialManager.h" -//#include "../Common/Leaderboards/LeaderboardManager.h" -//#include "../Common/XUI/XUI_Scene_Container.h" -//#include "NetworkManager.h" +// #include "../Durango/Social/SocialManager.h" +// #include "../Common/Leaderboards/LeaderboardManager.h" +// #include "../Common/XUI/XUI_Scene_Container.h" +// #include "NetworkManager.h" #include "../../Rendering/Tesselator.h" #include "../../GameState/Options.h" #include "../Orbis/Sentient/SentientManager.h" @@ -65,195 +74,348 @@ static void sigsegv_handler(int sig) { // #include "../Orbis/Network/Orbis_NPToolkit.h" // #include "../Orbis/Network/SonyVoiceChat_Orbis.h" -#define THEME_NAME "584111F70AAAAAAA" -#define THEME_FILESIZE 2797568 +#define THEME_NAME "584111F70AAAAAAA" +#define THEME_FILESIZE 2797568 -//#define THREE_MB 3145728 // minimum save size (checking for this on a selected device) -//#define FIVE_MB 5242880 // minimum save size (checking for this on a selected device) -//#define FIFTY_TWO_MB (1024*1024*52) // Maximum TCR space required for a save (checking for this on a selected device) -#define FIFTY_ONE_MB (1000000*51) // Maximum TCR space required for a save is 52MB (checking for this on a selected device) +// #define THREE_MB 3145728 // minimum save size (checking for this on a +// selected device) #define FIVE_MB 5242880 // minimum save size (checking for +// this on a selected device) #define FIFTY_TWO_MB (1024*1024*52) // Maximum TCR +// space required for a save (checking for this on a selected device) +#define FIFTY_ONE_MB \ + (1000000 * 51) // Maximum TCR space required for a save is 52MB (checking + // for this on a selected device) -//#define PROFILE_VERSION 3 // new version for the interim bug fix 166 TU -#define NUM_PROFILE_VALUES 5 +// #define PROFILE_VERSION 3 // new version for the interim bug fix 166 TU +#define NUM_PROFILE_VALUES 5 #define NUM_PROFILE_SETTINGS 4 -DWORD dwProfileSettingsA[NUM_PROFILE_VALUES]= -{ - #ifdef _XBOX +DWORD dwProfileSettingsA[NUM_PROFILE_VALUES] = { +#ifdef _XBOX XPROFILE_OPTION_CONTROLLER_VIBRATION, XPROFILE_GAMER_YAXIS_INVERSION, XPROFILE_GAMER_CONTROL_SENSITIVITY, XPROFILE_GAMER_ACTION_MOVEMENT_CONTROL, XPROFILE_TITLE_SPECIFIC1, - #else - 0,0,0,0,0 - #endif +#else + 0, 0, 0, 0, 0 +#endif }; //------------------------------------------------------------------------------------- -// Time Since fAppTime is a float, we need to keep the quadword app time -// as a LARGE_INTEGER so that we don't lose precision after running -// for a long time. +// Time Since fAppTime is a float, we need to keep the quadword app +// time +// as a LARGE_INTEGER so that we don't lose precision after +// running for a long time. //------------------------------------------------------------------------------------- // functions for storing and converting rich presence strings from wchar to utf8 -uint8_t * AddRichPresenceString(int iID); +uint8_t* AddRichPresenceString(int iID); void FreeRichPresenceStrings(); BOOL g_bWidescreen = TRUE; - -void DefineActions(void) -{ - // The app needs to define the actions required, and the possible mappings for these +void DefineActions(void) { + // The app needs to define the actions required, and the possible mappings + // for these // Split into Menu actions, and in-game actions - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_A, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_B, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_X, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_Y, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OK, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_CANCEL, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_UP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_DOWN, _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_LEFT, _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_PAGEUP, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_PAGEDOWN, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_LEFT_SCROLL, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_PAUSEMENU, _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_A, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_B, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_X, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_Y, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OK, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_CANCEL, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_UP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_DOWN, + _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_LEFT, + _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_0, ACTION_MENU_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_PAGEUP, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_PAGEDOWN, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_LEFT_SCROLL, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_PAUSEMENU, + _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_STICK_PRESS, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_PRESS, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_OTHER_STICK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_STICK_PRESS, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_PRESS, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, ACTION_MENU_OTHER_STICK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_JUMP, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_FORWARD, _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_BACKWARD, _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LEFT, _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RIGHT, _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LOOK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_USE, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_ACTION, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_LEFT_SCROLL, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_INVENTORY, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_PAUSEMENU, _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DROP, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_SNEAK_TOGGLE, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_JUMP, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_FORWARD, + _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_BACKWARD, + _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LEFT, + _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_RIGHT, + _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LOOK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_USE, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_ACTION, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_LEFT_SCROLL, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_INVENTORY, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_PAUSEMENU, + _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DROP, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_SNEAK_TOGGLE, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_CRAFTING, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, + MINECRAFT_ACTION_RENDER_THIRD_PERSON, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_GAME_INFO, + _360_JOY_BUTTON_BACK); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_LEFT, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_UP, + _360_JOY_BUTTON_DPAD_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_0, MINECRAFT_ACTION_DPAD_DOWN, + _360_JOY_BUTTON_DPAD_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_A, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_B, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_X, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_Y, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OK, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_CANCEL, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_UP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_DOWN, _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_LEFT, _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_PAGEUP, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_PAGEDOWN, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_LEFT_SCROLL, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_PAUSEMENU, _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_A, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_B, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_X, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_Y, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OK, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_CANCEL, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_UP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_DOWN, + _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_LEFT, + _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_1, ACTION_MENU_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_PAGEUP, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_PAGEDOWN, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_LEFT_SCROLL, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_PAUSEMENU, + _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_STICK_PRESS, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_PRESS, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_OTHER_STICK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_STICK_PRESS, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_PRESS, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, ACTION_MENU_OTHER_STICK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_JUMP, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_FORWARD, _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_BACKWARD, _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LEFT, _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_RIGHT, _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LOOK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_USE, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_ACTION, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_RIGHT_SCROLL, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_LEFT_SCROLL, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_INVENTORY, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_PAUSEMENU, _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DROP, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_SNEAK_TOGGLE, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_JUMP, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_FORWARD, + _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_BACKWARD, + _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LEFT, + _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_RIGHT, + _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LOOK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_USE, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_ACTION, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_RIGHT_SCROLL, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_LEFT_SCROLL, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_INVENTORY, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_PAUSEMENU, + _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DROP, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_SNEAK_TOGGLE, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_CRAFTING, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, + MINECRAFT_ACTION_RENDER_THIRD_PERSON, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_GAME_INFO, + _360_JOY_BUTTON_BACK); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_LEFT, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_UP, + _360_JOY_BUTTON_DPAD_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_1, MINECRAFT_ACTION_DPAD_DOWN, + _360_JOY_BUTTON_DPAD_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_A, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_B, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_X, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_Y, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OK, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_CANCEL, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_UP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_DOWN, _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_LEFT, _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_PAGEUP, _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_PAGEDOWN, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_RIGHT_SCROLL, _360_JOY_BUTTON_RB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_LEFT_SCROLL, _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_A, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_B, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_X, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_Y, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OK, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_CANCEL, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_UP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_DOWN, + _360_JOY_BUTTON_DPAD_DOWN | _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_LEFT, + _360_JOY_BUTTON_DPAD_LEFT | _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT | _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps( + MAP_STYLE_2, ACTION_MENU_PAGEUP, + _360_JOY_BUTTON_DPAD_UP | _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_PAGEDOWN, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_RIGHT_SCROLL, + _360_JOY_BUTTON_RB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_LEFT_SCROLL, + _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_JUMP, _360_JOY_BUTTON_LT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_FORWARD, _360_JOY_BUTTON_LSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_BACKWARD, _360_JOY_BUTTON_LSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LEFT, _360_JOY_BUTTON_LSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_RIGHT, _360_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LOOK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_USE, _360_JOY_BUTTON_RT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_ACTION, _360_JOY_BUTTON_A); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_RIGHT_SCROLL, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_LEFT_SCROLL, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_INVENTORY, _360_JOY_BUTTON_Y); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_PAUSEMENU, _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DROP, _360_JOY_BUTTON_B); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_SNEAK_TOGGLE, _360_JOY_BUTTON_LB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_PAUSEMENU, _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_JUMP, + _360_JOY_BUTTON_LT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_FORWARD, + _360_JOY_BUTTON_LSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_BACKWARD, + _360_JOY_BUTTON_LSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LEFT, + _360_JOY_BUTTON_LSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_RIGHT, + _360_JOY_BUTTON_LSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LOOK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_USE, + _360_JOY_BUTTON_RT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_ACTION, + _360_JOY_BUTTON_A); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_RIGHT_SCROLL, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_LEFT_SCROLL, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_INVENTORY, + _360_JOY_BUTTON_Y); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_PAUSEMENU, + _360_JOY_BUTTON_START); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DROP, + _360_JOY_BUTTON_B); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_SNEAK_TOGGLE, + _360_JOY_BUTTON_LB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_CRAFTING, + _360_JOY_BUTTON_X); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, + MINECRAFT_ACTION_RENDER_THIRD_PERSON, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_GAME_INFO, + _360_JOY_BUTTON_BACK); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_PAUSEMENU, + _360_JOY_BUTTON_START); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_STICK_PRESS, _360_JOY_BUTTON_LTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_PRESS, _360_JOY_BUTTON_RTHUMB); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_UP, _360_JOY_BUTTON_RSTICK_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_DOWN, _360_JOY_BUTTON_RSTICK_DOWN); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_LEFT, _360_JOY_BUTTON_RSTICK_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_OTHER_STICK_RIGHT, _360_JOY_BUTTON_RSTICK_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_STICK_PRESS, + _360_JOY_BUTTON_LTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_PRESS, + _360_JOY_BUTTON_RTHUMB); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_UP, + _360_JOY_BUTTON_RSTICK_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_DOWN, + _360_JOY_BUTTON_RSTICK_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_LEFT, + _360_JOY_BUTTON_RSTICK_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, ACTION_MENU_OTHER_STICK_RIGHT, + _360_JOY_BUTTON_RSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_LEFT, + _360_JOY_BUTTON_DPAD_LEFT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_RIGHT, + _360_JOY_BUTTON_DPAD_RIGHT); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_UP, + _360_JOY_BUTTON_DPAD_UP); + InputManager.SetGameJoypadMaps(MAP_STYLE_2, MINECRAFT_ACTION_DPAD_DOWN, + _360_JOY_BUTTON_DPAD_DOWN); } #if 0 @@ -299,29 +461,27 @@ pd3dPP, ppDevice ); } #endif -//#define MEMORY_TRACKING +// #define MEMORY_TRACKING #ifdef MEMORY_TRACKING void ResetMem(); void DumpMem(); void MemPixStuff(); #else -void MemSect(int sect) -{ -} +void MemSect(int sect) {} #endif #ifndef __linux__ -HINSTANCE g_hInst = NULL; -HWND g_hWnd = NULL; -D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; -D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; -ID3D11Device* g_pd3dDevice = NULL; -ID3D11DeviceContext* g_pImmediateContext = NULL; -IDXGISwapChain* g_pSwapChain = NULL; +HINSTANCE g_hInst = NULL; +HWND g_hWnd = NULL; +D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; +D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; +ID3D11Device* g_pd3dDevice = NULL; +ID3D11DeviceContext* g_pImmediateContext = NULL; +IDXGISwapChain* g_pSwapChain = NULL; ID3D11RenderTargetView* g_pRenderTargetView = NULL; ID3D11DepthStencilView* g_pDepthStencilView = NULL; -ID3D11Texture2D* g_pDepthStencilBuffer = NULL; +ID3D11Texture2D* g_pDepthStencilBuffer = NULL; // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) @@ -333,20 +493,18 @@ ID3D11Texture2D* g_pDepthStencilBuffer = NULL; // WM_DESTROY - post a quit message and return // // -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ +LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; - switch (message) - { + switch (message) { case WM_COMMAND: - wmId = LOWORD(wParam); + wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: - switch (wmId) - { + switch (wmId) { case IDM_EXIT: DestroyWindow(hWnd); break; @@ -354,43 +512,41 @@ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) return DefWindowProc(hWnd, message, wParam, lParam); } break; - case WM_PAINT: - hdc = BeginPaint(hWnd, &ps); - // TODO: Add any drawing code here... - EndPaint(hWnd, &ps); - break; - case WM_DESTROY: - PostQuitMessage(0); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + // TODO: Add any drawing code here... + EndPaint(hWnd, &ps); + break; + case WM_DESTROY: + PostQuitMessage(0); + break; + default: + return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } - // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // -ATOM MyRegisterClass(HINSTANCE hInstance) -{ +ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = WndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = hInstance; - wcex.hIcon = LoadIcon(hInstance, "Minecraft"); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); - wcex.lpszMenuName = "Minecraft"; - wcex.lpszClassName = "MinecraftClass"; - wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = LoadIcon(hInstance, "Minecraft"); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wcex.lpszMenuName = "Minecraft"; + wcex.lpszClassName = "MinecraftClass"; + wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } @@ -405,15 +561,14 @@ ATOM MyRegisterClass(HINSTANCE hInstance) // In this function, we save the instance handle in a global variable and // create and display the main program window. // -BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) -{ - g_hInst = hInstance; // Store instance handle in our global variable +BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { + g_hInst = hInstance; // Store instance handle in our global variable g_hWnd = CreateWindow("MinecraftClass", "Minecraft", WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); + CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, + hInstance, NULL); - if (!g_hWnd) - { + if (!g_hWnd) { return FALSE; } @@ -423,42 +578,38 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) return TRUE; } - //-------------------------------------------------------------------------------------- // Create Direct3D device and swap chain //-------------------------------------------------------------------------------------- -HRESULT InitDevice() -{ +HRESULT InitDevice() { HRESULT hr = S_OK; RECT rc; - GetClientRect( g_hWnd, &rc ); + GetClientRect(g_hWnd, &rc); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; - #ifdef _DEBUG +#ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; - #endif +#endif - D3D_DRIVER_TYPE driverTypes[] = - { + D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; - UINT numDriverTypes = ARRAYSIZE( driverTypes ); + UINT numDriverTypes = ARRAYSIZE(driverTypes); - D3D_FEATURE_LEVEL featureLevels[] = - { + D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; - UINT numFeatureLevels = ARRAYSIZE( featureLevels ); + UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; - ZeroMemory( &sd, sizeof( sd ) ); + ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; @@ -471,22 +622,22 @@ HRESULT InitDevice() sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; - for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) - { + for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; + driverTypeIndex++) { g_driverType = driverTypes[driverTypeIndex]; - hr = D3D11CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, - D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext ); - if( HRESULT_SUCCEEDED( hr ) ) - break; + hr = D3D11CreateDeviceAndSwapChain( + NULL, g_driverType, NULL, createDeviceFlags, featureLevels, + numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, + &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext); + if (HRESULT_SUCCEEDED(hr)) break; } - if( FAILED( hr ) ) - return hr; + if (FAILED(hr)) return hr; // Create a render target view ID3D11Texture2D* pBackBuffer = NULL; - hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); - if( FAILED( hr ) ) - return hr; + hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), + (LPVOID*)&pBackBuffer); + if (FAILED(hr)) return hr; // Create a depth stencil buffer D3D11_TEXTURE2D_DESC descDepth; @@ -502,21 +653,24 @@ HRESULT InitDevice() descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; - hr = g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer); + hr = + g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer); D3D11_DEPTH_STENCIL_VIEW_DESC descDSView; descDSView.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDSView.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSView.Texture2D.MipSlice = 0; - hr = g_pd3dDevice->CreateDepthStencilView(g_pDepthStencilBuffer, &descDSView, &g_pDepthStencilView); + hr = g_pd3dDevice->CreateDepthStencilView( + g_pDepthStencilBuffer, &descDSView, &g_pDepthStencilView); - hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView ); + hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, + &g_pRenderTargetView); pBackBuffer->Release(); - if( FAILED( hr ) ) - return hr; + if (FAILED(hr)) return hr; - g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView ); + g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, + g_pDepthStencilView); // Setup the viewport D3D11_VIEWPORT vp; @@ -526,54 +680,48 @@ HRESULT InitDevice() vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; - g_pImmediateContext->RSSetViewports( 1, &vp ); + g_pImmediateContext->RSSetViewports(1, &vp); RenderManager.Initialise(g_pd3dDevice, g_pSwapChain); return S_OK; } - //-------------------------------------------------------------------------------------- // Render the frame //-------------------------------------------------------------------------------------- -void Render() -{ +void Render() { // Just clear the backbuffer - float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; //red,green,blue,alpha + float ClearColor[4] = {0.0f, 0.125f, 0.3f, 1.0f}; // red,green,blue,alpha - g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, ClearColor ); - g_pSwapChain->Present( 0, 0 ); + g_pImmediateContext->ClearRenderTargetView(g_pRenderTargetView, ClearColor); + g_pSwapChain->Present(0, 0); } - //-------------------------------------------------------------------------------------- // Clean up the objects we've created //-------------------------------------------------------------------------------------- -void CleanupDevice() -{ - if( g_pImmediateContext ) g_pImmediateContext->ClearState(); +void CleanupDevice() { + if (g_pImmediateContext) g_pImmediateContext->ClearState(); - if( g_pRenderTargetView ) g_pRenderTargetView->Release(); - if( g_pSwapChain ) g_pSwapChain->Release(); - if( g_pImmediateContext ) g_pImmediateContext->Release(); - if( g_pd3dDevice ) g_pd3dDevice->Release(); + if (g_pRenderTargetView) g_pRenderTargetView->Release(); + if (g_pSwapChain) g_pSwapChain->Release(); + if (g_pImmediateContext) g_pImmediateContext->Release(); + if (g_pd3dDevice) g_pd3dDevice->Release(); } #endif -int StartMinecraftThreadProc( void* lpParameter ) -{ +int StartMinecraftThreadProc(void* lpParameter) { Vec3::UseDefaultThreadStorage(); AABB::UseDefaultThreadStorage(); - Tesselator::CreateNewThreadStorage(1024*1024); + Tesselator::CreateNewThreadStorage(1024 * 1024); RenderManager.InitialiseContext(); - Minecraft::start(std::wstring(),std::wstring()); + Minecraft::start(std::wstring(), std::wstring()); delete Tesselator::getInstance(); return 0; } -int main(int argc, const char *argv[] ) -{ +int main(int argc, const char* argv[]) { #if defined(__linux__) && defined(__GLIBC__) struct sigaction sa; sa.sa_handler = sigsegv_handler; @@ -602,13 +750,11 @@ int main(int argc, const char *argv[] ) reqH = atoi(argv[++i]); } } - if (reqW > 0 && reqH > 0) - RenderManager.SetWindowSize(reqW, reqH); - if (fs) - RenderManager.SetFullscreen(true); + if (reqW > 0 && reqH > 0) RenderManager.SetWindowSize(reqW, reqH); + if (fs) RenderManager.SetFullscreen(true); } - #if 0 +#if 0 // Main message loop MSG msg = {0}; while( WM_QUIT != msg.message ) @@ -627,13 +773,14 @@ Render(); return (int) msg.wParam; #endif -static bool bTrialTimerDisplayed=true; + static bool bTrialTimerDisplayed = true; #ifdef MEMORY_TRACKING -ResetMem(); -MEMORYSTATUS memStat; -GlobalMemoryStatus(&memStat); -printf("RESETMEM start: Avail. phys %d\n",memStat.dwAvailPhys/(1024*1024)); + ResetMem(); + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); + printf("RESETMEM start: Avail. phys %d\n", + memStat.dwAvailPhys / (1024 * 1024)); #endif #if 0 @@ -661,180 +808,188 @@ return -1; #endif -RenderManager.Initialise(); + RenderManager.Initialise(); -// Read the file containing the product codes -app.DebugPrintf("---ReadProductCodes()\n"); + // Read the file containing the product codes + app.DebugPrintf("---ReadProductCodes()\n"); -app.loadMediaArchive(); -app.loadStringTable(); + app.loadMediaArchive(); + app.loadStringTable(); // fuck you ui.init(1920, 1080); -// storage manager is needed for the trial key check -StorageManager.Init(0,app.GetString(IDS_DEFAULT_SAVENAME),(char*)"savegame.dat",FIFTY_ONE_MB,&CConsoleMinecraftApp::DisplaySavingMessage,(LPVOID)&app,(char*)""); + // storage manager is needed for the trial key check + StorageManager.Init(0, app.GetString(IDS_DEFAULT_SAVENAME), + (char*)"savegame.dat", FIFTY_ONE_MB, + &CConsoleMinecraftApp::DisplaySavingMessage, + (LPVOID)&app, (char*)""); -//////////////// -// Initialise // -//////////////// + //////////////// + // Initialise // + //////////////// -app.InitTime(); + app.InitTime(); -// Set the number of possible joypad layouts that the user can switch between, and the number of actions -InputManager.Initialise(1,5,MINECRAFT_ACTION_MAX, ACTION_MAX_MENU); + // Set the number of possible joypad layouts that the user can switch + // between, and the number of actions + InputManager.Initialise(1, 5, MINECRAFT_ACTION_MAX, ACTION_MAX_MENU); -// Set the default joypad action mappings for Minecraft -DefineActions(); -InputManager.SetJoypadMapVal(0,0); -InputManager.SetKeyRepeatRate(0.3f,0.2f); + // Set the default joypad action mappings for Minecraft + DefineActions(); + InputManager.SetJoypadMapVal(0, 0); + InputManager.SetKeyRepeatRate(0.3f, 0.2f); -// Initialise the profile manager with the game Title ID, Offer ID, a profile version number, and the number of profile values and settings + // Initialise the profile manager with the game Title ID, Offer ID, a + // profile version number, and the number of profile values and settings -ProfileManager.Initialise(TITLEID_MINECRAFT, - app.m_dwOfferID, - PROFILE_VERSION_10, - NUM_PROFILE_VALUES, - NUM_PROFILE_SETTINGS, - dwProfileSettingsA, - app.GAME_DEFINED_PROFILE_DATA_BYTES*XUSER_MAX_COUNT, - &app.uiGameDefinedDataChangedBitmask -); + ProfileManager.Initialise( + TITLEID_MINECRAFT, app.m_dwOfferID, PROFILE_VERSION_10, + NUM_PROFILE_VALUES, NUM_PROFILE_SETTINGS, dwProfileSettingsA, + app.GAME_DEFINED_PROFILE_DATA_BYTES * XUSER_MAX_COUNT, + &app.uiGameDefinedDataChangedBitmask); -// set a function to be called when there's a sign in change, so we can exit a level if the primary player signs out -ProfileManager.SetSignInChangeCallback(&CConsoleMinecraftApp::SignInChangeCallback, &app); + // set a function to be called when there's a sign in change, so we can exit + // a level if the primary player signs out + ProfileManager.SetSignInChangeCallback( + &CConsoleMinecraftApp::SignInChangeCallback, &app); -// Set a callback for when there is a read error on profile data -//StorageManager.SetProfileReadErrorCallback(&CConsoleMinecraftApp::ProfileReadErrorCallback, &app); + // Set a callback for when there is a read error on profile data + // StorageManager.SetProfileReadErrorCallback(&CConsoleMinecraftApp::ProfileReadErrorCallback, + // &app); + // QNet needs to be setup after profile manager, as we do not want its + // Notify listener to handle XN_SYS_SIGNINCHANGED notifications. This does + // mean that we need to have a callback in the ProfileManager for + // XN_LIVE_INVITE_ACCEPTED for QNet. -// QNet needs to be setup after profile manager, as we do not want its Notify listener to handle -// XN_SYS_SIGNINCHANGED notifications. This does mean that we need to have a callback in the -// ProfileManager for XN_LIVE_INVITE_ACCEPTED for QNet. - -g_NetworkManager.Initialise(); - -// debug switch to trial version -ProfileManager.SetDebugFullOverride(true); -// Initialise TLS for tesselator, for this main thread -Tesselator::CreateNewThreadStorage(1024*1024); -// Initialise TLS for AABB and Vec3 pools, for this main thread -AABB::CreateNewThreadStorage(); -Vec3::CreateNewThreadStorage(); -IntCache::CreateNewThreadStorage(); -Compression::CreateNewThreadStorage(); -OldChunkStorage::CreateNewThreadStorage(); -Level::enableLightingCache(); -Tile::CreateNewThreadStorage(); - -Minecraft::main(); - -// Minecraft::main () used to call Minecraft::Start, but this takes ~2.5 seconds, so now running this in another thread -// so we can do some basic renderer calls whilst it is happening. This is at attempt to stop getting TRC failure on SubmitDone taking > 5 seconds on boot -C4JThread *minecraftThread = new C4JThread(&StartMinecraftThreadProc, NULL, "Running minecraft start"); -minecraftThread->Run(); -do -{ - RenderManager.StartFrame(); - Sleep(20); - RenderManager.Present(); -} while (minecraftThread->isRunning()); -delete minecraftThread; - -// Re-acquire the GL context in the main thread. -// StartMinecraftThreadProc calls InitialiseContext() which moves the context -// to the init thread for texture loading; we must reclaim it here before -// any further OpenGL calls in the main render loop. -RenderManager.InitialiseContext(); - -Minecraft *pMinecraft=Minecraft::GetInstance(); - -app.InitGameSettings(); - -app.InitialiseTips(); -while (!RenderManager.ShouldClose()) { -RenderManager.StartFrame(); -app.UpdateTime(); -PIXBeginNamedEvent(0,"Input manager tick"); -InputManager.Tick(); -PIXEndNamedEvent(); -PIXBeginNamedEvent(0,"Profile manager tick"); -ProfileManager.Tick(); -PIXEndNamedEvent(); -PIXBeginNamedEvent(0,"Storage manager tick"); -StorageManager.Tick(); -PIXEndNamedEvent(); -PIXBeginNamedEvent(0,"Render manager tick"); -RenderManager.Tick(); -PIXEndNamedEvent(); - -// Tick the social networking manager. -PIXBeginNamedEvent(0,"Social network manager tick"); -// CSocialManager::Instance()->Tick(); -PIXEndNamedEvent(); - -// Tick sentient. -PIXBeginNamedEvent(0,"Sentient tick"); -MemSect(37); -// SentientManager.Tick(); -MemSect(0); -PIXEndNamedEvent(); - -PIXBeginNamedEvent(0,"Network manager do work #1"); -g_NetworkManager.DoWork(); -PIXEndNamedEvent(); - -// Render game graphics. -// On Linux, always call run_middle() so mc->screen (TitleScreen etc.) renders -// even when the game session has not yet started (Iggy Flash UI is unavailable). -pMinecraft->run_middle(); -if(app.GetGameStarted()) -{ - app.SetAppPaused( g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()) ); -} -else -{ - MemSect(28); - pMinecraft->soundEngine->tick(NULL, 0.0f); - MemSect(0); - pMinecraft->textures->tick(true,false); - IntCache::Reset(); - if( app.GetReallyChangingSessionType() ) - { - pMinecraft->tickAllConnections(); // Added to stop timing out when we are waiting after converting to an offline game - } -} -pMinecraft->soundEngine->playMusicTick(); - -static bool bInitnet=false; - -if(bInitnet) -{ g_NetworkManager.Initialise(); -} + + // debug switch to trial version + ProfileManager.SetDebugFullOverride(true); + // Initialise TLS for tesselator, for this main thread + Tesselator::CreateNewThreadStorage(1024 * 1024); + // Initialise TLS for AABB and Vec3 pools, for this main thread + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Compression::CreateNewThreadStorage(); + OldChunkStorage::CreateNewThreadStorage(); + Level::enableLightingCache(); + Tile::CreateNewThreadStorage(); + + Minecraft::main(); + + // Minecraft::main () used to call Minecraft::Start, but this takes ~2.5 + // seconds, so now running this in another thread so we can do some basic + // renderer calls whilst it is happening. This is at attempt to stop getting + // TRC failure on SubmitDone taking > 5 seconds on boot + C4JThread* minecraftThread = new C4JThread(&StartMinecraftThreadProc, NULL, + "Running minecraft start"); + minecraftThread->Run(); + do { + RenderManager.StartFrame(); + Sleep(20); + RenderManager.Present(); + } while (minecraftThread->isRunning()); + delete minecraftThread; + + // Re-acquire the GL context in the main thread. + // StartMinecraftThreadProc calls InitialiseContext() which moves the + // context to the init thread for texture loading; we must reclaim it here + // before any further OpenGL calls in the main render loop. + RenderManager.InitialiseContext(); + + Minecraft* pMinecraft = Minecraft::GetInstance(); + + app.InitGameSettings(); + + app.InitialiseTips(); + while (!RenderManager.ShouldClose()) { + RenderManager.StartFrame(); + app.UpdateTime(); + PIXBeginNamedEvent(0, "Input manager tick"); + InputManager.Tick(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Profile manager tick"); + ProfileManager.Tick(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Storage manager tick"); + StorageManager.Tick(); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Render manager tick"); + RenderManager.Tick(); + PIXEndNamedEvent(); + + // Tick the social networking manager. + PIXBeginNamedEvent(0, "Social network manager tick"); + // CSocialManager::Instance()->Tick(); + PIXEndNamedEvent(); + + // Tick sentient. + PIXBeginNamedEvent(0, "Sentient tick"); + MemSect(37); + // SentientManager.Tick(); + MemSect(0); + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Network manager do work #1"); + g_NetworkManager.DoWork(); + PIXEndNamedEvent(); + + // Render game graphics. + // On Linux, always call run_middle() so mc->screen (TitleScreen etc.) + // renders even when the game session has not yet started (Iggy Flash UI + // is unavailable). + pMinecraft->run_middle(); + if (app.GetGameStarted()) { + app.SetAppPaused( + g_NetworkManager.IsLocalGame() && + g_NetworkManager.GetPlayerCount() == 1 && + ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad())); + } else { + MemSect(28); + pMinecraft->soundEngine->tick(NULL, 0.0f); + MemSect(0); + pMinecraft->textures->tick(true, false); + IntCache::Reset(); + if (app.GetReallyChangingSessionType()) { + pMinecraft + ->tickAllConnections(); // Added to stop timing out when we + // are waiting after converting to + // an offline game + } + } + pMinecraft->soundEngine->playMusicTick(); + + static bool bInitnet = false; + + if (bInitnet) { + g_NetworkManager.Initialise(); + } #ifdef MEMORY_TRACKING -static bool bResetMemTrack = false; -static bool bDumpMemTrack = false; + static bool bResetMemTrack = false; + static bool bDumpMemTrack = false; -MemPixStuff(); + MemPixStuff(); -if( bResetMemTrack ) -{ - ResetMem(); - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); - printf("RESETMEM: Avail. phys %d\n",memStat.dwAvailPhys/(1024*1024)); - bResetMemTrack = false; -} + if (bResetMemTrack) { + ResetMem(); + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); + printf("RESETMEM: Avail. phys %d\n", + memStat.dwAvailPhys / (1024 * 1024)); + bResetMemTrack = false; + } -if( bDumpMemTrack ) -{ - DumpMem(); - bDumpMemTrack = false; - MEMORYSTATUS memStat; - GlobalMemoryStatus(&memStat); - printf("DUMPMEM: Avail. phys %d\n",memStat.dwAvailPhys/(1024*1024)); - printf("Renderer used: %d\n",RenderManager.CBuffSize(-1)); -} + if (bDumpMemTrack) { + DumpMem(); + bDumpMemTrack = false; + MEMORYSTATUS memStat; + GlobalMemoryStatus(&memStat); + printf("DUMPMEM: Avail. phys %d\n", + memStat.dwAvailPhys / (1024 * 1024)); + printf("Renderer used: %d\n", RenderManager.CBuffSize(-1)); + } #endif #if 0 static bool bDumpTextureUsage = false; @@ -844,8 +999,8 @@ RenderManager.TextureGetStats(); bDumpTextureUsage = false; } #endif -ui.tick(); -ui.render(); + ui.tick(); + ui.render(); #if 0 app.HandleButtonPresses(); @@ -886,51 +1041,47 @@ pDevice->SetSamplerState(0,SamplerStateModes[i],SamplerStateA[i]); RenderManager.Set_matrixDirty(); #endif -// Present the frame. -RenderManager.Present(); + // Present the frame. + RenderManager.Present(); -ui.CheckMenuDisplayed(); -PIXBeginNamedEvent(0,"Profile load check"); -// has the game defined profile data been changed (by a profile load) -if(app.uiGameDefinedDataChangedBitmask!=0) -{ - void *pData; - for(int i=0;istats[i]->clear(); + pMinecraft->stats[i]->parse(pData); + } } - else - { - // force debug mask off - app.ActionDebugMask(i,true); - } - #endif - // clear the stats first - there could have beena signout and sign back in in the menus - // need to clear the player stats - can't assume it'll be done in setlevel - we may not be in the game - pMinecraft->stats[ i ]->clear(); - pMinecraft->stats[i]->parse(pData); + + // clear the flag + app.uiGameDefinedDataChangedBitmask = 0; } + PIXEndNamedEvent(); - } - - // clear the flag - app.uiGameDefinedDataChangedBitmask=0; -} -PIXEndNamedEvent(); - -PIXBeginNamedEvent(0,"Network manager do work #2"); -g_NetworkManager.DoWork(); -PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Network manager do work #2"); + g_NetworkManager.DoWork(); + PIXEndNamedEvent(); #if 0 PIXBeginNamedEvent(0,"Misc extra xui"); @@ -938,143 +1089,136 @@ PIXBeginNamedEvent(0,"Misc extra xui"); hr = XuiTimersRun(); #endif -// Any threading type things to deal with from the xui side? -app.HandleXuiActions(); + // Any threading type things to deal with from the xui side? + app.HandleXuiActions(); #if 0 PIXEndNamedEvent(); #endif -// 4J-PB - Update the trial timer display if we are in the trial version -if(!ProfileManager.IsFullVersion()) -{ - // display the trial timer - if(app.GetGameStarted()) - { - // 4J-PB - if the game is paused, add the elapsed time to the trial timer count so it doesn't tick down - if(app.IsAppPaused()) - { - app.UpdateTrialPausedTimer(); + // 4J-PB - Update the trial timer display if we are in the trial version + if (!ProfileManager.IsFullVersion()) { + // display the trial timer + if (app.GetGameStarted()) { + // 4J-PB - if the game is paused, add the elapsed time to the + // trial timer count so it doesn't tick down + if (app.IsAppPaused()) { + app.UpdateTrialPausedTimer(); + } + ui.UpdateTrialTimer(ProfileManager.GetPrimaryPad()); + } + } else { + // need to turn off the trial timer if it was on , and we've + // unlocked the full version + if (bTrialTimerDisplayed) { + ui.ShowTrialTimer(false); + bTrialTimerDisplayed = false; + } } - ui.UpdateTrialTimer(ProfileManager.GetPrimaryPad()); - } -} -else -{ - // need to turn off the trial timer if it was on , and we've unlocked the full version - if(bTrialTimerDisplayed) - { - ui.ShowTrialTimer(false); - bTrialTimerDisplayed=false; - } -} -// Fix for #7318 - Title crashes after short soak in the leaderboards menu -// A memory leak was caused because the icon renderer kept creating new Vec3's because the pool wasn't reset -Vec3::resetPool(); -} // end game loop + // Fix for #7318 - Title crashes after short soak in the leaderboards + // menu A memory leak was caused because the icon renderer kept creating + // new Vec3's because the pool wasn't reset + Vec3::resetPool(); + } // end game loop - // Graceful shutdown: destroy GL context and GLFW before any C++ dtors run. - // Without this, static/global destructors that touch GL objects cause SIGSEGV. - RenderManager.Shutdown(); - _exit(0); -} // end main + // Graceful shutdown: destroy GL context and GLFW before any C++ dtors run. + // Without this, static/global destructors that touch GL objects cause + // SIGSEGV. + RenderManager.Shutdown(); + _exit(0); +} // end main // Free resources, unregister custom classes, and exit. // app.Uninit(); // g_pd3dDevice->Release(); - -std::vector vRichPresenceStrings; +std::vector vRichPresenceStrings; // convert std::wstring to UTF-8 string // wchar_t is 32bit on all Linux systems, and interpreted as UTF-32 -// the code base stores all strings internally as UCS-2 (16bit, subset of UTF-16), -// which, scince it only stores BMP code points, is trivially convertable -// to UTF-32 as well as UTF-16. hence this parser simply parses UTF-32 +// the code base stores all strings internally as UCS-2 (16bit, subset of +// UTF-16), which, scince it only stores BMP code points, is trivially +// convertable to UTF-32 as well as UTF-16. hence this parser simply parses +// UTF-32 // all implementations of libc (including glibc, musl, uClibc...) implement -// wchar_t as 4byte/32bit (scince around 1999), it would break the libc ABI, +// wchar_t as 4byte/32bit (scince around 1999), it would break the libc ABI, // if this ever will get changed, hence this assert -static_assert( sizeof(wchar_t) == 4, "Linux with non 32bit wchar_t"); +static_assert(sizeof(wchar_t) == 4, "Linux with non 32bit wchar_t"); -std::string wstring_to_utf8 (const std::wstring& str) -{ - std::string result; - // preallocation, so it will never need to resize. - // same allocation size as for the 4byte wstring representation. - // it well get destructed instantly, in the function that it gets called from - result.reserve(str.size() * 4); +std::string wstring_to_utf8(const std::wstring& str) { + std::string result; + // preallocation, so it will never need to resize. + // same allocation size as for the 4byte wstring representation. + // it well get destructed instantly, in the function that it gets called + // from + result.reserve(str.size() * 4); - for (size_t i = 0; i < str.size(); ++i) { - uint32_t cp = static_cast(str[i]); + for (size_t i = 0; i < str.size(); ++i) { + uint32_t cp = static_cast(str[i]); - // outside of valid unicode range or preserved UTF-16 surrogate pairs (just in case) - if (cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) { - cp = 0xFFFD; // unicode replacement character - } + // outside of valid unicode range or preserved UTF-16 surrogate pairs + // (just in case) + if (cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) { + cp = 0xFFFD; // unicode replacement character + } - if (cp < 0x80) { - // ASCII - result += static_cast(cp); - // extract multibyte unicode into multiple bytes of UTF-8 - } else if (cp < 0x800) { - result += static_cast(0xC0 | (cp >> 6)); - result += static_cast(0x80 | (cp & 0x3F)); - } else if (cp < 0x10000) { - result += static_cast(0xE0 | (cp >> 12)); - result += static_cast(0x80 | ((cp >> 6) & 0x3F)); - result += static_cast(0x80 | (cp & 0x3F)); - } else { - result += static_cast(0xF0 | (cp >> 18)); - result += static_cast(0x80 | ((cp >> 12) & 0x3F)); - result += static_cast(0x80 | ((cp >> 6) & 0x3F)); - result += static_cast(0x80 | (cp & 0x3F)); - } - } + if (cp < 0x80) { + // ASCII + result += static_cast(cp); + // extract multibyte unicode into multiple bytes of UTF-8 + } else if (cp < 0x800) { + result += static_cast(0xC0 | (cp >> 6)); + result += static_cast(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + result += static_cast(0xE0 | (cp >> 12)); + result += static_cast(0x80 | ((cp >> 6) & 0x3F)); + result += static_cast(0x80 | (cp & 0x3F)); + } else { + result += static_cast(0xF0 | (cp >> 18)); + result += static_cast(0x80 | ((cp >> 12) & 0x3F)); + result += static_cast(0x80 | ((cp >> 6) & 0x3F)); + result += static_cast(0x80 | (cp & 0x3F)); + } + } - return result; + return result; } -uint8_t *mallocAndCreateUTF8ArrayFromString(int iID) -{ - LPCWSTR wchString=app.GetString(iID); +uint8_t* mallocAndCreateUTF8ArrayFromString(int iID) { + LPCWSTR wchString = app.GetString(iID); std::wstring srcString = wchString; std::string dstString = wstring_to_utf8(srcString); - int dst_len = dstString.size()+1; - uint8_t *strUtf8=(uint8_t *)malloc(dst_len); + int dst_len = dstString.size() + 1; + uint8_t* strUtf8 = (uint8_t*)malloc(dst_len); memcpy(strUtf8, dstString.c_str(), dst_len); return strUtf8; } -uint8_t * AddRichPresenceString(int iID) -{ - uint8_t *strUtf8 = mallocAndCreateUTF8ArrayFromString(iID); - if( strUtf8 != NULL ) - { +uint8_t* AddRichPresenceString(int iID) { + uint8_t* strUtf8 = mallocAndCreateUTF8ArrayFromString(iID); + if (strUtf8 != NULL) { vRichPresenceStrings.push_back(strUtf8); } return strUtf8; } -void FreeRichPresenceStrings() -{ - uint8_t *strUtf8; - for(int i=0;i allocCounts; +std::unordered_map allocCounts; bool trackEnable = false; bool trackStarted = false; volatile size_t sizeCheckMin = 1160; @@ -1083,11 +1227,9 @@ volatile int sectCheck = 48; CRITICAL_SECTION memCS; DWORD tlsIdx; -LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) -{ - if( !trackStarted ) - { - void *p = XMemAllocDefault(dwSize,dwAllocAttributes); +LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) { + if (!trackStarted) { + void* p = XMemAllocDefault(dwSize, dwAllocAttributes); size_t realSize = XMemSizeDefault(p, dwAllocAttributes); totalAllocGen += realSize; return p; @@ -1095,26 +1237,24 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) EnterCriticalSection(&memCS); - void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); - size_t realSize = XMemSizeDefault(p,dwAllocAttributes) - 16; + void* p = XMemAllocDefault(dwSize + 16, dwAllocAttributes); + size_t realSize = XMemSizeDefault(p, dwAllocAttributes) - 16; - if( trackEnable ) - { - #if 1 - int sect = ((int) TlsGetValue(tlsIdx)) & 0x3f; - *(((unsigned char *)p)+realSize) = sect; + if (trackEnable) { +#if 1 + int sect = ((int)TlsGetValue(tlsIdx)) & 0x3f; + *(((unsigned char*)p) + realSize) = sect; - if( ( realSize >= sizeCheckMin ) && ( realSize <= sizeCheckMax ) && ( ( sect == sectCheck ) || ( sectCheck == -1 ) ) ) - { + if ((realSize >= sizeCheckMin) && (realSize <= sizeCheckMax) && + ((sect == sectCheck) || (sectCheck == -1))) { app.DebugPrintf("Found one\n"); } - #endif +#endif - if( p ) - { + if (p) { totalAllocGen += realSize; trackEnable = false; - int key = ( sect << 26 ) | realSize; + int key = (sect << 26) | realSize; int oldCount = allocCounts[key]; allocCounts[key] = oldCount + 1; @@ -1127,86 +1267,74 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) return p; } -void* operator new (size_t size) -{ - return (unsigned char *)XMemAlloc(size,MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_HEAP)); +void* operator new(size_t size) { + return (unsigned char*)XMemAlloc( + size, MAKE_XALLOC_ATTRIBUTES( + 0, FALSE, TRUE, FALSE, 0, XALLOC_PHYSICAL_ALIGNMENT_DEFAULT, + XALLOC_MEMPROTECT_READWRITE, FALSE, XALLOC_MEMTYPE_HEAP)); } -void operator delete (void *p) -{ - XMemFree(p,MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_HEAP)); +void operator delete(void* p) { + XMemFree(p, MAKE_XALLOC_ATTRIBUTES( + 0, FALSE, TRUE, FALSE, 0, XALLOC_PHYSICAL_ALIGNMENT_DEFAULT, + XALLOC_MEMPROTECT_READWRITE, FALSE, XALLOC_MEMTYPE_HEAP)); } -void WINAPI XMemFree(PVOID pAddress, DWORD dwAllocAttributes) -{ +void WINAPI XMemFree(PVOID pAddress, DWORD dwAllocAttributes) { bool special = false; - if( dwAllocAttributes == 0 ) - { - dwAllocAttributes = MAKE_XALLOC_ATTRIBUTES(0,FALSE,TRUE,FALSE,0,XALLOC_PHYSICAL_ALIGNMENT_DEFAULT,XALLOC_MEMPROTECT_READWRITE,FALSE,XALLOC_MEMTYPE_HEAP); + if (dwAllocAttributes == 0) { + dwAllocAttributes = MAKE_XALLOC_ATTRIBUTES( + 0, FALSE, TRUE, FALSE, 0, XALLOC_PHYSICAL_ALIGNMENT_DEFAULT, + XALLOC_MEMPROTECT_READWRITE, FALSE, XALLOC_MEMTYPE_HEAP); special = true; } - if(!trackStarted ) - { + if (!trackStarted) { size_t realSize = XMemSizeDefault(pAddress, dwAllocAttributes); XMemFreeDefault(pAddress, dwAllocAttributes); totalAllocGen -= realSize; return; } EnterCriticalSection(&memCS); - if( pAddress ) - { + if (pAddress) { size_t realSize = XMemSizeDefault(pAddress, dwAllocAttributes) - 16; - if(trackEnable) - { - int sect = *(((unsigned char *)pAddress)+realSize); + if (trackEnable) { + int sect = *(((unsigned char*)pAddress) + realSize); totalAllocGen -= realSize; trackEnable = false; - int key = ( sect << 26 ) | realSize; + int key = (sect << 26) | realSize; int oldCount = allocCounts[key]; allocCounts[key] = oldCount - 1; trackEnable = true; - } XMemFreeDefault(pAddress, dwAllocAttributes); } LeaveCriticalSection(&memCS); } -SIZE_T WINAPI XMemSize( - PVOID pAddress, - DWORD dwAllocAttributes -) -{ - if( trackStarted ) - { +SIZE_T WINAPI XMemSize(PVOID pAddress, DWORD dwAllocAttributes) { + if (trackStarted) { return XMemSizeDefault(pAddress, dwAllocAttributes) - 16; - } - else - { + } else { return XMemSizeDefault(pAddress, dwAllocAttributes); } } - -void DumpMem() -{ +void DumpMem() { int totalLeak = 0; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) - { - if(it->second > 0 ) - { - app.DebugPrintf("%d %d %d %d\n",( it->first >> 26 ) & 0x3f,it->first & 0x03ffffff, it->second, (it->first & 0x03ffffff) * it->second); - totalLeak += ( it->first & 0x03ffffff ) * it->second; + for (AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++) { + if (it->second > 0) { + app.DebugPrintf("%d %d %d %d\n", (it->first >> 26) & 0x3f, + it->first & 0x03ffffff, it->second, + (it->first & 0x03ffffff) * it->second); + totalLeak += (it->first & 0x03ffffff) * it->second; } } - app.DebugPrintf("Total %d\n",totalLeak); + app.DebugPrintf("Total %d\n", totalLeak); } -void ResetMem() -{ - if( !trackStarted ) - { +void ResetMem() { + if (!trackStarted) { trackEnable = true; trackStarted = true; totalAllocGen = 0; @@ -1220,44 +1348,38 @@ void ResetMem() LeaveCriticalSection(&memCS); } -void MemSect(int section) -{ +void MemSect(int section) { unsigned int value = (unsigned int)TlsGetValue(tlsIdx); - if( section == 0 ) // pop + if (section == 0) // pop { value = (value >> 6) & 0x03ffffff; - } - else - { + } else { value = (value << 6) | section; } TlsSetValue(tlsIdx, (LPVOID)value); } -void MemPixStuff() -{ +void MemPixStuff() { const int MAX_SECT = 46; int totals[MAX_SECT] = {0}; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) - { - if(it->second > 0 ) - { - int sect = ( it->first >> 26 ) & 0x3f; + for (AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++) { + if (it->second > 0) { + int sect = (it->first >> 26) & 0x3f; int bytes = it->first & 0x03ffffff; totals[sect] += bytes * it->second; } } unsigned int allSectsTotal = 0; - for( int i = 0; i < MAX_SECT; i++ ) - { + for (int i = 0; i < MAX_SECT; i++) { allSectsTotal += totals[i]; - PIXAddNamedCounter(((float)totals[i])/1024.0f,"MemSect%d",i); + PIXAddNamedCounter(((float)totals[i]) / 1024.0f, "MemSect%d", i); } - PIXAddNamedCounter(((float)allSectsTotal)/(4096.0f),"MemSect total pages"); + PIXAddNamedCounter(((float)allSectsTotal) / (4096.0f), + "MemSect total pages"); } #endif diff --git a/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp b/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp index cd0866a57..1077d1921 100644 --- a/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_ShutdownManager.cpp @@ -8,6 +8,9 @@ void ShutdownManager::StartShutdown() {} void ShutdownManager::MainThreadHandleShutdown() {} void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/) {} -void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/, C4JThread::EventArray * /*eventArray*/) {} -bool ShutdownManager::ShouldRun(ShutdownManager::EThreadId /*threadId*/) { return true; } +void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/, + C4JThread::EventArray* /*eventArray*/) {} +bool ShutdownManager::ShouldRun(ShutdownManager::EThreadId /*threadId*/) { + return true; +} void ShutdownManager::HasFinished(ShutdownManager::EThreadId /*threadId*/) {} diff --git a/Minecraft.Client/Platform/Linux/Linux_UIController.cpp b/Minecraft.Client/Platform/Linux/Linux_UIController.cpp index 4e4fe1c58..8a9d09eed 100644 --- a/Minecraft.Client/Platform/Linux/Linux_UIController.cpp +++ b/Minecraft.Client/Platform/Linux/Linux_UIController.cpp @@ -12,115 +12,105 @@ ConsoleUIController ui; -void ConsoleUIController::init(S32 w, S32 h) -{ +void ConsoleUIController::init(S32 w, S32 h) { #ifdef _ENABLEIGGY - // Shared init - preInit(w, h); + // Shared init + preInit(w, h); - //init - gdraw_funcs = gdraw_GL_CreateContext(w, h, 0); + // init + gdraw_funcs = gdraw_GL_CreateContext(w, h, 0); - if (!gdraw_funcs) - { - app.DebugPrintf("Failed to initialise GDraw GL!\n"); - fprintf(stderr, "[Linux_UIController] Failed to initialise GDraw GL!\n"); - // nott fatal for now - } - else - { + if (!gdraw_funcs) { + app.DebugPrintf("Failed to initialise GDraw GL!\n"); + fprintf(stderr, + "[Linux_UIController] Failed to initialise GDraw GL!\n"); + // nott fatal for now + } else { + gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_vertexbuffer, 5000, + 16 * 1024 * 1024); + gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_texture, 5000, + 128 * 1024 * 1024); + gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_rendertarget, 10, + 32 * 1024 * 1024); - gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_vertexbuffer, 5000, 16 * 1024 * 1024); - gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_texture, 5000, 128 * 1024 * 1024); - gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_rendertarget, 10, 32 * 1024 * 1024); + IggySetGDraw(gdraw_funcs); + } - IggySetGDraw(gdraw_funcs); - } - - postInit(); + postInit(); #endif } -void ConsoleUIController::render() -{ +void ConsoleUIController::render() { #ifdef _ENABLEIGGY - if (!gdraw_funcs) - return; + if (!gdraw_funcs) return; - gdraw_GL_SetTileOrigin(0, 0, 0); + gdraw_GL_SetTileOrigin(0, 0, 0); - // render - renderScenes(); + // render + renderScenes(); - gdraw_GL_NoMoreGDrawThisFrame(); + gdraw_GL_NoMoreGDrawThisFrame(); #endif } -void ConsoleUIController::beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion *region, CustomDrawData *customDrawRegion) -{ - gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); +void ConsoleUIController::beginIggyCustomDraw4J( + IggyCustomDrawCallbackRegion* region, CustomDrawData* customDrawRegion) { + gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); } -CustomDrawData *ConsoleUIController::setupCustomDraw(UIScene *scene, IggyCustomDrawCallbackRegion *region) -{ - CustomDrawData *customDrawRegion = new CustomDrawData(); - customDrawRegion->x0 = region->x0; - customDrawRegion->x1 = region->x1; - customDrawRegion->y0 = region->y0; - customDrawRegion->y1 = region->y1; +CustomDrawData* ConsoleUIController::setupCustomDraw( + UIScene* scene, IggyCustomDrawCallbackRegion* region) { + CustomDrawData* customDrawRegion = new CustomDrawData(); + customDrawRegion->x0 = region->x0; + customDrawRegion->x1 = region->x1; + customDrawRegion->y0 = region->y0; + customDrawRegion->y1 = region->y1; - - gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); + gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); - setupCustomDrawGameStateAndMatrices(scene, customDrawRegion); + setupCustomDrawGameStateAndMatrices(scene, customDrawRegion); - return customDrawRegion; + return customDrawRegion; } -CustomDrawData *ConsoleUIController::calculateCustomDraw(IggyCustomDrawCallbackRegion *region) -{ - CustomDrawData *customDrawRegion = new CustomDrawData(); - customDrawRegion->x0 = region->x0; - customDrawRegion->x1 = region->x1; - customDrawRegion->y0 = region->y0; - customDrawRegion->y1 = region->y1; +CustomDrawData* ConsoleUIController::calculateCustomDraw( + IggyCustomDrawCallbackRegion* region) { + CustomDrawData* customDrawRegion = new CustomDrawData(); + customDrawRegion->x0 = region->x0; + customDrawRegion->x1 = region->x1; + customDrawRegion->y0 = region->y0; + customDrawRegion->y1 = region->y1; - gdraw_GL_CalculateCustomDraw_4J(region, customDrawRegion->mat); + gdraw_GL_CalculateCustomDraw_4J(region, customDrawRegion->mat); - return customDrawRegion; + return customDrawRegion; } -void ConsoleUIController::endCustomDraw(IggyCustomDrawCallbackRegion *region) -{ - endCustomDrawGameStateAndMatrices(); +void ConsoleUIController::endCustomDraw(IggyCustomDrawCallbackRegion* region) { + endCustomDrawGameStateAndMatrices(); - gdraw_GL_EndCustomDraw(region); + gdraw_GL_EndCustomDraw(region); } -void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) -{ - gdraw_GL_SetTileOrigin(xPos, yPos, 0); +void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) { + gdraw_GL_SetTileOrigin(xPos, yPos, 0); } -GDrawTexture *ConsoleUIController::getSubstitutionTexture(int textureId) -{ - // todo impl - return nullptr; +GDrawTexture* ConsoleUIController::getSubstitutionTexture(int textureId) { + // todo impl + return nullptr; } -void ConsoleUIController::destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle) -{ - if (handle) - gdraw_GL_WrappedTextureDestroy(handle); +void ConsoleUIController::destroySubstitutionTexture(void* destroyCallBackData, + GDrawTexture* handle) { + if (handle) gdraw_GL_WrappedTextureDestroy(handle); } -void ConsoleUIController::shutdown() -{ +void ConsoleUIController::shutdown() { #ifdef _ENABLEIGGY - if (gdraw_funcs) - { - gdraw_GL_DestroyContext(); - gdraw_funcs = nullptr; - } + if (gdraw_funcs) { + gdraw_GL_DestroyContext(); + gdraw_funcs = nullptr; + } #endif } \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Linux_UIController.h b/Minecraft.Client/Platform/Linux/Linux_UIController.h index 6ed6934b0..aac328809 100644 --- a/Minecraft.Client/Platform/Linux/Linux_UIController.h +++ b/Minecraft.Client/Platform/Linux/Linux_UIController.h @@ -2,26 +2,29 @@ #include "../Common/UI/UIController.h" -class ConsoleUIController : public UIController -{ +class ConsoleUIController : public UIController { public: - void init(S32 w, S32 h); + void init(S32 w, S32 h); - void render(); - void beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion *region, CustomDrawData *customDrawRegion); - virtual CustomDrawData *setupCustomDraw(UIScene *scene, IggyCustomDrawCallbackRegion *region); - virtual CustomDrawData *calculateCustomDraw(IggyCustomDrawCallbackRegion *region); - virtual void endCustomDraw(IggyCustomDrawCallbackRegion *region); + void render(); + void beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion* region, + CustomDrawData* customDrawRegion); + virtual CustomDrawData* setupCustomDraw( + UIScene* scene, IggyCustomDrawCallbackRegion* region); + virtual CustomDrawData* calculateCustomDraw( + IggyCustomDrawCallbackRegion* region); + virtual void endCustomDraw(IggyCustomDrawCallbackRegion* region); protected: - virtual void setTileOrigin(S32 xPos, S32 yPos); + virtual void setTileOrigin(S32 xPos, S32 yPos); public: - GDrawTexture *getSubstitutionTexture(int textureId); - void destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle); + GDrawTexture* getSubstitutionTexture(int textureId); + void destroySubstitutionTexture(void* destroyCallBackData, + GDrawTexture* handle); public: - void shutdown(); + void shutdown(); }; extern ConsoleUIController ui; \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Social/SocialManager.h b/Minecraft.Client/Platform/Linux/Social/SocialManager.h index 278fb91a9..b225d8a39 100644 --- a/Minecraft.Client/Platform/Linux/Social/SocialManager.h +++ b/Minecraft.Client/Platform/Linux/Social/SocialManager.h @@ -5,17 +5,11 @@ #ifndef _SOCIAL_MANAGER_H #define _SOCIAL_MANAGER_H -enum ESocialNetwork -{ - eFacebook = 0, - eNumSocialNetworks -}; +enum ESocialNetwork { eFacebook = 0, eNumSocialNetworks }; -class CSocialManager -{ +class CSocialManager { public: - static CSocialManager* Instance() - { + static CSocialManager* Instance() { static CSocialManager s_instance; return &s_instance; } @@ -23,21 +17,21 @@ public: void Initialise() {} void Tick() {} - bool RefreshPostingCapability() { return false; } - bool IsTitleAllowedToPostAnything() { return false; } - bool IsTitleAllowedToPostImages() { return false; } - bool IsTitleAllowedToPostLinks() { return false; } - bool AreAllUsersAllowedToPostImages() { return false; } + bool RefreshPostingCapability() { return false; } + bool IsTitleAllowedToPostAnything() { return false; } + bool IsTitleAllowedToPostImages() { return false; } + bool IsTitleAllowedToPostLinks() { return false; } + bool AreAllUsersAllowedToPostImages() { return false; } - bool PostLinkToSocialNetwork( ESocialNetwork, DWORD, bool ) { return false; } - bool PostImageToSocialNetwork( ESocialNetwork, DWORD, bool ) { return false; } + bool PostLinkToSocialNetwork(ESocialNetwork, DWORD, bool) { return false; } + bool PostImageToSocialNetwork(ESocialNetwork, DWORD, bool) { return false; } - void SetSocialPostText( const WCHAR*, const WCHAR*, const WCHAR* ) {} + void SetSocialPostText(const WCHAR*, const WCHAR*, const WCHAR*) {} private: CSocialManager() {} - CSocialManager( const CSocialManager& ); - CSocialManager& operator=( const CSocialManager& ); + CSocialManager(const CSocialManager&); + CSocialManager& operator=(const CSocialManager&); }; -#endif // _SOCIAL_MANAGER_H +#endif // _SOCIAL_MANAGER_H diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h index cfde54c6c..f70026843 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXCollision.h @@ -11,334 +11,413 @@ #include "DirectXMath.h" -namespace DirectX -{ +namespace DirectX { - enum ContainmentType - { - DISJOINT = 0, - INTERSECTS = 1, - CONTAINS = 2 - }; +enum ContainmentType { DISJOINT = 0, INTERSECTS = 1, CONTAINS = 2 }; - enum PlaneIntersectionType - { - FRONT = 0, - INTERSECTING = 1, - BACK = 2 - }; +enum PlaneIntersectionType { FRONT = 0, INTERSECTING = 1, BACK = 2 }; - struct BoundingBox; - struct BoundingOrientedBox; - struct BoundingFrustum; +struct BoundingBox; +struct BoundingOrientedBox; +struct BoundingFrustum; #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4324 4820) - // C4324: alignment padding warnings - // C4820: Off by default noise +#pragma warning(disable : 4324 4820) +// C4324: alignment padding warnings +// C4820: Off by default noise #endif - //------------------------------------------------------------------------------------- - // Bounding sphere - //------------------------------------------------------------------------------------- - struct BoundingSphere - { - XMFLOAT3 Center; // Center of the sphere. - float Radius; // Radius of the sphere. - - // Creators - BoundingSphere() noexcept : Center(0, 0, 0), Radius(1.f) {} - - BoundingSphere(const BoundingSphere&) = default; - BoundingSphere& operator=(const BoundingSphere&) = default; - - BoundingSphere(BoundingSphere&&) = default; - BoundingSphere& operator=(BoundingSphere&&) = default; - - constexpr BoundingSphere(_In_ const XMFLOAT3& center, _In_ float radius) noexcept - : Center(center), Radius(radius) {} - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - // Transform the sphere - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-sphere test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-sphere test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-sphere test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test sphere against six planes (see BoundingFrustum::GetPlanes) - - // Static methods - static void CreateMerged(_Out_ BoundingSphere& Out, _In_ const BoundingSphere& S1, _In_ const BoundingSphere& S2) noexcept; - - static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, _In_ const BoundingBox& box) noexcept; - static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, _In_ const BoundingOrientedBox& box) noexcept; - - static void CreateFromPoints(_Out_ BoundingSphere& Out, _In_ size_t Count, - _In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; - - static void CreateFromFrustum(_Out_ BoundingSphere& Out, _In_ const BoundingFrustum& fr) noexcept; - }; - - //------------------------------------------------------------------------------------- - // Axis-aligned bounding box - //------------------------------------------------------------------------------------- - struct BoundingBox - { - static constexpr size_t CORNER_COUNT = 8; - - XMFLOAT3 Center; // Center of the box. - XMFLOAT3 Extents; // Distance from the center to each side. - - // Creators - BoundingBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f) {} - - BoundingBox(const BoundingBox&) = default; - BoundingBox& operator=(const BoundingBox&) = default; - - BoundingBox(BoundingBox&&) = default; - BoundingBox& operator=(BoundingBox&&) = default; - - constexpr BoundingBox(_In_ const XMFLOAT3& center, _In_ const XMFLOAT3& extents) noexcept - : Center(center), Extents(extents) {} - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - - void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; - // Gets the 8 corners of the box - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-Box test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-box test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-Box test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test box against six planes (see BoundingFrustum::GetPlanes) - - // Static methods - static void CreateMerged(_Out_ BoundingBox& Out, _In_ const BoundingBox& b1, _In_ const BoundingBox& b2) noexcept; - - static void CreateFromSphere(_Out_ BoundingBox& Out, _In_ const BoundingSphere& sh) noexcept; - - static void XM_CALLCONV CreateFromPoints(_Out_ BoundingBox& Out, _In_ FXMVECTOR pt1, _In_ FXMVECTOR pt2) noexcept; - static void CreateFromPoints(_Out_ BoundingBox& Out, _In_ size_t Count, - _In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; - }; - - //------------------------------------------------------------------------------------- - // Oriented bounding box - //------------------------------------------------------------------------------------- - struct BoundingOrientedBox - { - static constexpr size_t CORNER_COUNT = 8; - - XMFLOAT3 Center; // Center of the box. - XMFLOAT3 Extents; // Distance from the center to each side. - XMFLOAT4 Orientation; // Unit quaternion representing rotation (box -> world). - - // Creators - BoundingOrientedBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f), Orientation(0, 0, 0, 1.f) {} - - BoundingOrientedBox(const BoundingOrientedBox&) = default; - BoundingOrientedBox& operator=(const BoundingOrientedBox&) = default; - - BoundingOrientedBox(BoundingOrientedBox&&) = default; - BoundingOrientedBox& operator=(BoundingOrientedBox&&) = default; - - constexpr BoundingOrientedBox(_In_ const XMFLOAT3& center, _In_ const XMFLOAT3& extents, _In_ const XMFLOAT4& orientation) noexcept - : Center(center), Extents(extents), Orientation(orientation) {} - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - - void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; - // Gets the 8 corners of the box - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-OrientedBox test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-OrientedBox test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-OrientedBox test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test OrientedBox against six planes (see BoundingFrustum::GetPlanes) - - // Static methods - static void CreateFromBoundingBox(_Out_ BoundingOrientedBox& Out, _In_ const BoundingBox& box) noexcept; - - static void CreateFromPoints(_Out_ BoundingOrientedBox& Out, _In_ size_t Count, - _In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; - }; - - //------------------------------------------------------------------------------------- - // Bounding frustum - //------------------------------------------------------------------------------------- - struct BoundingFrustum - { - static constexpr size_t CORNER_COUNT = 8; - - XMFLOAT3 Origin; // Origin of the frustum (and projection). - XMFLOAT4 Orientation; // Quaternion representing rotation. - - float RightSlope; // Positive X (X/Z) - float LeftSlope; // Negative X - float TopSlope; // Positive Y (Y/Z) - float BottomSlope; // Negative Y - float Near, Far; // Z of the near plane and far plane. - - // Creators - BoundingFrustum() noexcept : - Origin(0, 0, 0), Orientation(0, 0, 0, 1.f), RightSlope(1.f), LeftSlope(-1.f), - TopSlope(1.f), BottomSlope(-1.f), Near(0), Far(1.f) {} - - BoundingFrustum(const BoundingFrustum&) = default; - BoundingFrustum& operator=(const BoundingFrustum&) = default; - - BoundingFrustum(BoundingFrustum&&) = default; - BoundingFrustum& operator=(BoundingFrustum&&) = default; - - constexpr BoundingFrustum(_In_ const XMFLOAT3& origin, _In_ const XMFLOAT4& orientation, - _In_ float rightSlope, _In_ float leftSlope, _In_ float topSlope, _In_ float bottomSlope, - _In_ float nearPlane, _In_ float farPlane) noexcept - : Origin(origin), Orientation(orientation), - RightSlope(rightSlope), LeftSlope(leftSlope), TopSlope(topSlope), BottomSlope(bottomSlope), - Near(nearPlane), Far(farPlane) {} - BoundingFrustum(_In_ CXMMATRIX Projection, bool rhcoords = false) noexcept; - - // Methods - void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ FXMMATRIX M) const noexcept; - void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; - - void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; - // Gets the 8 corners of the frustum - - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; - ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - ContainmentType Contains(_In_ const BoundingSphere& sp) const noexcept; - ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; - ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; - // Frustum-Frustum test - - bool Intersects(_In_ const BoundingSphere& sh) const noexcept; - bool Intersects(_In_ const BoundingBox& box) const noexcept; - bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; - bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; - // Triangle-Frustum test - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; - // Plane-Frustum test - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR rayOrigin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; - // Ray-Frustum test - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, - _In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; - // Test frustum against six planes (see BoundingFrustum::GetPlanes) - - void GetPlanes(_Out_opt_ XMVECTOR* NearPlane, _Out_opt_ XMVECTOR* FarPlane, _Out_opt_ XMVECTOR* RightPlane, - _Out_opt_ XMVECTOR* LeftPlane, _Out_opt_ XMVECTOR* TopPlane, _Out_opt_ XMVECTOR* BottomPlane) const noexcept; - // Create 6 Planes representation of Frustum - - // Static methods - static void XM_CALLCONV CreateFromMatrix(_Out_ BoundingFrustum& Out, _In_ FXMMATRIX Projection, bool rhcoords = false) noexcept; - }; - - //----------------------------------------------------------------------------- - // Triangle intersection testing routines. - //----------------------------------------------------------------------------- - namespace TriangleTests - { - bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _In_ FXMVECTOR V0, _In_ GXMVECTOR V1, _In_ HXMVECTOR V2, _Out_ float& Dist) noexcept; - // Ray-Triangle - - bool XM_CALLCONV Intersects(_In_ FXMVECTOR A0, _In_ FXMVECTOR A1, _In_ FXMVECTOR A2, _In_ GXMVECTOR B0, _In_ HXMVECTOR B1, _In_ HXMVECTOR B2) noexcept; - // Triangle-Triangle - - PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, _In_ GXMVECTOR Plane) noexcept; - // Plane-Triangle - - ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, +//------------------------------------------------------------------------------------- +// Bounding sphere +//------------------------------------------------------------------------------------- +struct BoundingSphere { + XMFLOAT3 Center; // Center of the sphere. + float Radius; // Radius of the sphere. + + // Creators + BoundingSphere() noexcept : Center(0, 0, 0), Radius(1.f) {} + + BoundingSphere(const BoundingSphere&) = default; + BoundingSphere& operator=(const BoundingSphere&) = default; + + BoundingSphere(BoundingSphere&&) = default; + BoundingSphere& operator=(BoundingSphere&&) = default; + + constexpr BoundingSphere(_In_ const XMFLOAT3& center, + _In_ float radius) noexcept + : Center(center), Radius(radius) {} + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + // Transform the sphere + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-sphere test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-sphere test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-sphere test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test sphere against six planes (see BoundingFrustum::GetPlanes) + + // Static methods + static void CreateMerged(_Out_ BoundingSphere& Out, + _In_ const BoundingSphere& S1, + _In_ const BoundingSphere& S2) noexcept; + + static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, + _In_ const BoundingBox& box) noexcept; + static void CreateFromBoundingBox( + _Out_ BoundingSphere& Out, + _In_ const BoundingOrientedBox& box) noexcept; + + static void CreateFromPoints(_Out_ BoundingSphere& Out, _In_ size_t Count, + _In_reads_bytes_(sizeof(XMFLOAT3) + + Stride * (Count - 1)) + const XMFLOAT3* pPoints, + _In_ size_t Stride) noexcept; + + static void CreateFromFrustum(_Out_ BoundingSphere& Out, + _In_ const BoundingFrustum& fr) noexcept; +}; + +//------------------------------------------------------------------------------------- +// Axis-aligned bounding box +//------------------------------------------------------------------------------------- +struct BoundingBox { + static constexpr size_t CORNER_COUNT = 8; + + XMFLOAT3 Center; // Center of the box. + XMFLOAT3 Extents; // Distance from the center to each side. + + // Creators + BoundingBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f) {} + + BoundingBox(const BoundingBox&) = default; + BoundingBox& operator=(const BoundingBox&) = default; + + BoundingBox(BoundingBox&&) = default; + BoundingBox& operator=(BoundingBox&&) = default; + + constexpr BoundingBox(_In_ const XMFLOAT3& center, + _In_ const XMFLOAT3& extents) noexcept + : Center(center), Extents(extents) {} + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingBox& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + + void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; + // Gets the 8 corners of the box + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-Box test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-box test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-Box test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test box against six planes (see BoundingFrustum::GetPlanes) + + // Static methods + static void CreateMerged(_Out_ BoundingBox& Out, _In_ const BoundingBox& b1, + _In_ const BoundingBox& b2) noexcept; + + static void CreateFromSphere(_Out_ BoundingBox& Out, + _In_ const BoundingSphere& sh) noexcept; + + static void XM_CALLCONV CreateFromPoints(_Out_ BoundingBox& Out, + _In_ FXMVECTOR pt1, + _In_ FXMVECTOR pt2) noexcept; + static void CreateFromPoints(_Out_ BoundingBox& Out, _In_ size_t Count, + _In_reads_bytes_(sizeof(XMFLOAT3) + + Stride * (Count - 1)) + const XMFLOAT3* pPoints, + _In_ size_t Stride) noexcept; +}; + +//------------------------------------------------------------------------------------- +// Oriented bounding box +//------------------------------------------------------------------------------------- +struct BoundingOrientedBox { + static constexpr size_t CORNER_COUNT = 8; + + XMFLOAT3 Center; // Center of the box. + XMFLOAT3 Extents; // Distance from the center to each side. + XMFLOAT4 + Orientation; // Unit quaternion representing rotation (box -> world). + + // Creators + BoundingOrientedBox() noexcept + : Center(0, 0, 0), Extents(1.f, 1.f, 1.f), Orientation(0, 0, 0, 1.f) {} + + BoundingOrientedBox(const BoundingOrientedBox&) = default; + BoundingOrientedBox& operator=(const BoundingOrientedBox&) = default; + + BoundingOrientedBox(BoundingOrientedBox&&) = default; + BoundingOrientedBox& operator=(BoundingOrientedBox&&) = default; + + constexpr BoundingOrientedBox(_In_ const XMFLOAT3& center, + _In_ const XMFLOAT3& extents, + _In_ const XMFLOAT4& orientation) noexcept + : Center(center), Extents(extents), Orientation(orientation) {} + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + + void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; + // Gets the 8 corners of the box + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-OrientedBox test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-OrientedBox test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-OrientedBox test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test OrientedBox against six planes (see BoundingFrustum::GetPlanes) + + // Static methods + static void CreateFromBoundingBox(_Out_ BoundingOrientedBox& Out, + _In_ const BoundingBox& box) noexcept; + + static void CreateFromPoints(_Out_ BoundingOrientedBox& Out, + _In_ size_t Count, + _In_reads_bytes_(sizeof(XMFLOAT3) + + Stride * (Count - 1)) + const XMFLOAT3* pPoints, + _In_ size_t Stride) noexcept; +}; + +//------------------------------------------------------------------------------------- +// Bounding frustum +//------------------------------------------------------------------------------------- +struct BoundingFrustum { + static constexpr size_t CORNER_COUNT = 8; + + XMFLOAT3 Origin; // Origin of the frustum (and projection). + XMFLOAT4 Orientation; // Quaternion representing rotation. + + float RightSlope; // Positive X (X/Z) + float LeftSlope; // Negative X + float TopSlope; // Positive Y (Y/Z) + float BottomSlope; // Negative Y + float Near, Far; // Z of the near plane and far plane. + + // Creators + BoundingFrustum() noexcept + : Origin(0, 0, 0), + Orientation(0, 0, 0, 1.f), + RightSlope(1.f), + LeftSlope(-1.f), + TopSlope(1.f), + BottomSlope(-1.f), + Near(0), + Far(1.f) {} + + BoundingFrustum(const BoundingFrustum&) = default; + BoundingFrustum& operator=(const BoundingFrustum&) = default; + + BoundingFrustum(BoundingFrustum&&) = default; + BoundingFrustum& operator=(BoundingFrustum&&) = default; + + constexpr BoundingFrustum(_In_ const XMFLOAT3& origin, + _In_ const XMFLOAT4& orientation, + _In_ float rightSlope, _In_ float leftSlope, + _In_ float topSlope, _In_ float bottomSlope, + _In_ float nearPlane, + _In_ float farPlane) noexcept + : Origin(origin), + Orientation(orientation), + RightSlope(rightSlope), + LeftSlope(leftSlope), + TopSlope(topSlope), + BottomSlope(bottomSlope), + Near(nearPlane), + Far(farPlane) {} + BoundingFrustum(_In_ CXMMATRIX Projection, bool rhcoords = false) noexcept; + + // Methods + void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, + _In_ FXMMATRIX M) const noexcept; + void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ float Scale, + _In_ FXMVECTOR Rotation, + _In_ FXMVECTOR Translation) const noexcept; + + void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; + // Gets the 8 corners of the frustum + + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; + ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + ContainmentType Contains(_In_ const BoundingSphere& sp) const noexcept; + ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; + ContainmentType Contains( + _In_ const BoundingOrientedBox& box) const noexcept; + ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; + // Frustum-Frustum test + + bool Intersects(_In_ const BoundingSphere& sh) const noexcept; + bool Intersects(_In_ const BoundingBox& box) const noexcept; + bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; + bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) const noexcept; + // Triangle-Frustum test + + PlaneIntersectionType XM_CALLCONV + Intersects(_In_ FXMVECTOR Plane) const noexcept; + // Plane-Frustum test + + bool XM_CALLCONV Intersects(_In_ FXMVECTOR rayOrigin, + _In_ FXMVECTOR Direction, + _Out_ float& Dist) const noexcept; + // Ray-Frustum test + + ContainmentType XM_CALLCONV + ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, + _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3, + _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; + // Test frustum against six planes (see BoundingFrustum::GetPlanes) + + void GetPlanes(_Out_opt_ XMVECTOR* NearPlane, _Out_opt_ XMVECTOR* FarPlane, + _Out_opt_ XMVECTOR* RightPlane, + _Out_opt_ XMVECTOR* LeftPlane, _Out_opt_ XMVECTOR* TopPlane, + _Out_opt_ XMVECTOR* BottomPlane) const noexcept; + // Create 6 Planes representation of Frustum + + // Static methods + static void XM_CALLCONV CreateFromMatrix(_Out_ BoundingFrustum& Out, + _In_ FXMMATRIX Projection, + bool rhcoords = false) noexcept; +}; + +//----------------------------------------------------------------------------- +// Triangle intersection testing routines. +//----------------------------------------------------------------------------- +namespace TriangleTests { +bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, + _In_ FXMVECTOR V0, _In_ GXMVECTOR V1, + _In_ HXMVECTOR V2, _Out_ float& Dist) noexcept; +// Ray-Triangle + +bool XM_CALLCONV Intersects(_In_ FXMVECTOR A0, _In_ FXMVECTOR A1, + _In_ FXMVECTOR A2, _In_ GXMVECTOR B0, + _In_ HXMVECTOR B1, _In_ HXMVECTOR B2) noexcept; +// Triangle-Triangle + +PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR V0, + _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2, + _In_ GXMVECTOR Plane) noexcept; +// Plane-Triangle + +ContainmentType XM_CALLCONV +ContainedBy(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, _In_ GXMVECTOR Plane0, _In_ HXMVECTOR Plane1, _In_ HXMVECTOR Plane2, - _In_ CXMVECTOR Plane3, _In_ CXMVECTOR Plane4, _In_ CXMVECTOR Plane5) noexcept; - // Test a triangle against six planes at once (see BoundingFrustum::GetPlanes) - } + _In_ CXMVECTOR Plane3, _In_ CXMVECTOR Plane4, + _In_ CXMVECTOR Plane5) noexcept; +// Test a triangle against six planes at once (see BoundingFrustum::GetPlanes) +} // namespace TriangleTests #ifdef _MSC_VER #pragma warning(pop) #endif - /**************************************************************************** - * - * Implementation - * - ****************************************************************************/ +/**************************************************************************** + * + * Implementation + * + ****************************************************************************/ #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4068 4365 4616 6001) - // C4068/4616: ignore unknown pragmas - // C4365: Off by default noise - // C6001: False positives +// C4068/4616: ignore unknown pragmas +// C4365: Off by default noise +// C6001: False positives #endif #ifdef _PREFAST_ @@ -366,5 +445,4 @@ namespace DirectX #pragma warning(pop) #endif -} // namespace DirectX - +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h index 962971e39..30bd3d852 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXColors.h @@ -11,302 +11,490 @@ #include "DirectXMath.h" -namespace DirectX -{ +namespace DirectX { - namespace Colors - { - // Standard colors (Red/Green/Blue/Alpha) in sRGB colorspace - XMGLOBALCONST XMVECTORF32 AliceBlue = { { { 0.941176534f, 0.972549081f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 AntiqueWhite = { { { 0.980392218f, 0.921568692f, 0.843137324f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aqua = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aquamarine = { { { 0.498039246f, 1.f, 0.831372619f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Azure = { { { 0.941176534f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Beige = { { { 0.960784376f, 0.960784376f, 0.862745166f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Bisque = { { { 1.f, 0.894117713f, 0.768627524f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Black = { { { 0.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { { { 1.f, 0.921568692f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Blue = { { { 0.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlueViolet = { { { 0.541176498f, 0.168627456f, 0.886274576f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Brown = { { { 0.647058845f, 0.164705887f, 0.164705887f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BurlyWood = { { { 0.870588303f, 0.721568644f, 0.529411793f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CadetBlue = { { { 0.372549027f, 0.619607866f, 0.627451003f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chartreuse = { { { 0.498039246f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chocolate = { { { 0.823529482f, 0.411764741f, 0.117647067f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Coral = { { { 1.f, 0.498039246f, 0.313725501f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CornflowerBlue = { { { 0.392156899f, 0.584313750f, 0.929411829f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cornsilk = { { { 1.f, 0.972549081f, 0.862745166f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Crimson = { { { 0.862745166f, 0.078431375f, 0.235294133f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cyan = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkBlue = { { { 0.f, 0.f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkCyan = { { { 0.f, 0.545098066f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { { { 0.721568644f, 0.525490224f, 0.043137256f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGray = { { { 0.662745118f, 0.662745118f, 0.662745118f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGreen = { { { 0.f, 0.392156899f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkKhaki = { { { 0.741176486f, 0.717647076f, 0.419607878f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkMagenta = { { { 0.545098066f, 0.f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { { { 0.333333343f, 0.419607878f, 0.184313729f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrange = { { { 1.f, 0.549019635f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrchid = { { { 0.600000024f, 0.196078449f, 0.800000072f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkRed = { { { 0.545098066f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSalmon = { { { 0.913725555f, 0.588235319f, 0.478431404f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { { { 0.560784340f, 0.737254918f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { { { 0.282352954f, 0.239215702f, 0.545098066f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateGray = { { { 0.184313729f, 0.309803933f, 0.309803933f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkTurquoise = { { { 0.f, 0.807843208f, 0.819607913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkViolet = { { { 0.580392182f, 0.f, 0.827451050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepPink = { { { 1.f, 0.078431375f, 0.576470613f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepSkyBlue = { { { 0.f, 0.749019623f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DimGray = { { { 0.411764741f, 0.411764741f, 0.411764741f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DodgerBlue = { { { 0.117647067f, 0.564705908f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Firebrick = { { { 0.698039234f, 0.133333340f, 0.133333340f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 FloralWhite = { { { 1.f, 0.980392218f, 0.941176534f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 ForestGreen = { { { 0.133333340f, 0.545098066f, 0.133333340f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Fuchsia = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gainsboro = { { { 0.862745166f, 0.862745166f, 0.862745166f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GhostWhite = { { { 0.972549081f, 0.972549081f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gold = { { { 1.f, 0.843137324f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Goldenrod = { { { 0.854902029f, 0.647058845f, 0.125490203f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gray = { { { 0.501960814f, 0.501960814f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Green = { { { 0.f, 0.501960814f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GreenYellow = { { { 0.678431392f, 1.f, 0.184313729f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Honeydew = { { { 0.941176534f, 1.f, 0.941176534f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 HotPink = { { { 1.f, 0.411764741f, 0.705882370f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 IndianRed = { { { 0.803921640f, 0.360784322f, 0.360784322f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Indigo = { { { 0.294117659f, 0.f, 0.509803951f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Ivory = { { { 1.f, 1.f, 0.941176534f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Khaki = { { { 0.941176534f, 0.901960850f, 0.549019635f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lavender = { { { 0.901960850f, 0.901960850f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LavenderBlush = { { { 1.f, 0.941176534f, 0.960784376f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LawnGreen = { { { 0.486274540f, 0.988235354f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LemonChiffon = { { { 1.f, 0.980392218f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightBlue = { { { 0.678431392f, 0.847058892f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCoral = { { { 0.941176534f, 0.501960814f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCyan = { { { 0.878431439f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { { { 0.980392218f, 0.980392218f, 0.823529482f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGray = { { { 0.827451050f, 0.827451050f, 0.827451050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGreen = { { { 0.564705908f, 0.933333397f, 0.564705908f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightPink = { { { 1.f, 0.713725507f, 0.756862819f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSalmon = { { { 1.f, 0.627451003f, 0.478431404f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSeaGreen = { { { 0.125490203f, 0.698039234f, 0.666666687f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSkyBlue = { { { 0.529411793f, 0.807843208f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSlateGray = { { { 0.466666698f, 0.533333361f, 0.600000024f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSteelBlue = { { { 0.690196097f, 0.768627524f, 0.870588303f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightYellow = { { { 1.f, 1.f, 0.878431439f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lime = { { { 0.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LimeGreen = { { { 0.196078449f, 0.803921640f, 0.196078449f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Linen = { { { 0.980392218f, 0.941176534f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Magenta = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Maroon = { { { 0.501960814f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumAquamarine = { { { 0.400000036f, 0.803921640f, 0.666666687f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumBlue = { { { 0.f, 0.f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumOrchid = { { { 0.729411781f, 0.333333343f, 0.827451050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumPurple = { { { 0.576470613f, 0.439215720f, 0.858823597f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { { { 0.235294133f, 0.701960802f, 0.443137288f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { { { 0.482352972f, 0.407843173f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { { { 0.f, 0.980392218f, 0.603921592f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumTurquoise = { { { 0.282352954f, 0.819607913f, 0.800000072f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumVioletRed = { { { 0.780392230f, 0.082352944f, 0.521568656f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MidnightBlue = { { { 0.098039225f, 0.098039225f, 0.439215720f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MintCream = { { { 0.960784376f, 1.f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MistyRose = { { { 1.f, 0.894117713f, 0.882353008f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Moccasin = { { { 1.f, 0.894117713f, 0.709803939f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 NavajoWhite = { { { 1.f, 0.870588303f, 0.678431392f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Navy = { { { 0.f, 0.f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OldLace = { { { 0.992156923f, 0.960784376f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Olive = { { { 0.501960814f, 0.501960814f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OliveDrab = { { { 0.419607878f, 0.556862772f, 0.137254909f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orange = { { { 1.f, 0.647058845f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OrangeRed = { { { 1.f, 0.270588249f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orchid = { { { 0.854902029f, 0.439215720f, 0.839215755f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { { { 0.933333397f, 0.909803987f, 0.666666687f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGreen = { { { 0.596078455f, 0.984313786f, 0.596078455f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleTurquoise = { { { 0.686274529f, 0.933333397f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleVioletRed = { { { 0.858823597f, 0.439215720f, 0.576470613f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PapayaWhip = { { { 1.f, 0.937254965f, 0.835294187f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PeachPuff = { { { 1.f, 0.854902029f, 0.725490212f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Peru = { { { 0.803921640f, 0.521568656f, 0.247058839f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Pink = { { { 1.f, 0.752941251f, 0.796078503f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Plum = { { { 0.866666734f, 0.627451003f, 0.866666734f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PowderBlue = { { { 0.690196097f, 0.878431439f, 0.901960850f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Purple = { { { 0.501960814f, 0.f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Red = { { { 1.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RosyBrown = { { { 0.737254918f, 0.560784340f, 0.560784340f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RoyalBlue = { { { 0.254901975f, 0.411764741f, 0.882353008f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SaddleBrown = { { { 0.545098066f, 0.270588249f, 0.074509807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Salmon = { { { 0.980392218f, 0.501960814f, 0.447058856f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SandyBrown = { { { 0.956862807f, 0.643137276f, 0.376470625f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaGreen = { { { 0.180392161f, 0.545098066f, 0.341176480f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaShell = { { { 1.f, 0.960784376f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Sienna = { { { 0.627451003f, 0.321568638f, 0.176470593f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Silver = { { { 0.752941251f, 0.752941251f, 0.752941251f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SkyBlue = { { { 0.529411793f, 0.807843208f, 0.921568692f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateBlue = { { { 0.415686309f, 0.352941185f, 0.803921640f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateGray = { { { 0.439215720f, 0.501960814f, 0.564705908f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Snow = { { { 1.f, 0.980392218f, 0.980392218f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SpringGreen = { { { 0.f, 1.f, 0.498039246f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SteelBlue = { { { 0.274509817f, 0.509803951f, 0.705882370f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tan = { { { 0.823529482f, 0.705882370f, 0.549019635f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Teal = { { { 0.f, 0.501960814f, 0.501960814f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Thistle = { { { 0.847058892f, 0.749019623f, 0.847058892f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tomato = { { { 1.f, 0.388235331f, 0.278431386f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Transparent = { { { 0.f, 0.f, 0.f, 0.f } } }; - XMGLOBALCONST XMVECTORF32 Turquoise = { { { 0.250980407f, 0.878431439f, 0.815686345f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Violet = { { { 0.933333397f, 0.509803951f, 0.933333397f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Wheat = { { { 0.960784376f, 0.870588303f, 0.701960802f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 White = { { { 1.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 WhiteSmoke = { { { 0.960784376f, 0.960784376f, 0.960784376f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Yellow = { { { 1.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 YellowGreen = { { { 0.603921592f, 0.803921640f, 0.196078449f, 1.f } } }; +namespace Colors { +// Standard colors (Red/Green/Blue/Alpha) in sRGB colorspace +XMGLOBALCONST XMVECTORF32 AliceBlue = { + {{0.941176534f, 0.972549081f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 AntiqueWhite = { + {{0.980392218f, 0.921568692f, 0.843137324f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aqua = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aquamarine = { + {{0.498039246f, 1.f, 0.831372619f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Azure = {{{0.941176534f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Beige = { + {{0.960784376f, 0.960784376f, 0.862745166f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Bisque = {{{1.f, 0.894117713f, 0.768627524f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Black = {{{0.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { + {{1.f, 0.921568692f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Blue = {{{0.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlueViolet = { + {{0.541176498f, 0.168627456f, 0.886274576f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Brown = { + {{0.647058845f, 0.164705887f, 0.164705887f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BurlyWood = { + {{0.870588303f, 0.721568644f, 0.529411793f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CadetBlue = { + {{0.372549027f, 0.619607866f, 0.627451003f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chartreuse = {{{0.498039246f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chocolate = { + {{0.823529482f, 0.411764741f, 0.117647067f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Coral = {{{1.f, 0.498039246f, 0.313725501f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CornflowerBlue = { + {{0.392156899f, 0.584313750f, 0.929411829f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cornsilk = {{{1.f, 0.972549081f, 0.862745166f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Crimson = { + {{0.862745166f, 0.078431375f, 0.235294133f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cyan = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkBlue = {{{0.f, 0.f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkCyan = {{{0.f, 0.545098066f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { + {{0.721568644f, 0.525490224f, 0.043137256f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGray = { + {{0.662745118f, 0.662745118f, 0.662745118f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGreen = {{{0.f, 0.392156899f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkKhaki = { + {{0.741176486f, 0.717647076f, 0.419607878f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkMagenta = { + {{0.545098066f, 0.f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { + {{0.333333343f, 0.419607878f, 0.184313729f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrange = {{{1.f, 0.549019635f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrchid = { + {{0.600000024f, 0.196078449f, 0.800000072f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkRed = {{{0.545098066f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSalmon = { + {{0.913725555f, 0.588235319f, 0.478431404f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { + {{0.560784340f, 0.737254918f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { + {{0.282352954f, 0.239215702f, 0.545098066f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateGray = { + {{0.184313729f, 0.309803933f, 0.309803933f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkTurquoise = { + {{0.f, 0.807843208f, 0.819607913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkViolet = { + {{0.580392182f, 0.f, 0.827451050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepPink = {{{1.f, 0.078431375f, 0.576470613f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepSkyBlue = {{{0.f, 0.749019623f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DimGray = { + {{0.411764741f, 0.411764741f, 0.411764741f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DodgerBlue = { + {{0.117647067f, 0.564705908f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Firebrick = { + {{0.698039234f, 0.133333340f, 0.133333340f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 FloralWhite = { + {{1.f, 0.980392218f, 0.941176534f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 ForestGreen = { + {{0.133333340f, 0.545098066f, 0.133333340f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Fuchsia = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gainsboro = { + {{0.862745166f, 0.862745166f, 0.862745166f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GhostWhite = { + {{0.972549081f, 0.972549081f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gold = {{{1.f, 0.843137324f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Goldenrod = { + {{0.854902029f, 0.647058845f, 0.125490203f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gray = { + {{0.501960814f, 0.501960814f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Green = {{{0.f, 0.501960814f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GreenYellow = { + {{0.678431392f, 1.f, 0.184313729f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Honeydew = {{{0.941176534f, 1.f, 0.941176534f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 HotPink = {{{1.f, 0.411764741f, 0.705882370f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 IndianRed = { + {{0.803921640f, 0.360784322f, 0.360784322f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Indigo = {{{0.294117659f, 0.f, 0.509803951f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Ivory = {{{1.f, 1.f, 0.941176534f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Khaki = { + {{0.941176534f, 0.901960850f, 0.549019635f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lavender = { + {{0.901960850f, 0.901960850f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LavenderBlush = { + {{1.f, 0.941176534f, 0.960784376f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LawnGreen = { + {{0.486274540f, 0.988235354f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LemonChiffon = { + {{1.f, 0.980392218f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightBlue = { + {{0.678431392f, 0.847058892f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCoral = { + {{0.941176534f, 0.501960814f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCyan = {{{0.878431439f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { + {{0.980392218f, 0.980392218f, 0.823529482f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGray = { + {{0.827451050f, 0.827451050f, 0.827451050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGreen = { + {{0.564705908f, 0.933333397f, 0.564705908f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightPink = { + {{1.f, 0.713725507f, 0.756862819f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSalmon = { + {{1.f, 0.627451003f, 0.478431404f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSeaGreen = { + {{0.125490203f, 0.698039234f, 0.666666687f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSkyBlue = { + {{0.529411793f, 0.807843208f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSlateGray = { + {{0.466666698f, 0.533333361f, 0.600000024f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSteelBlue = { + {{0.690196097f, 0.768627524f, 0.870588303f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightYellow = {{{1.f, 1.f, 0.878431439f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lime = {{{0.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LimeGreen = { + {{0.196078449f, 0.803921640f, 0.196078449f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Linen = { + {{0.980392218f, 0.941176534f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Magenta = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Maroon = {{{0.501960814f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumAquamarine = { + {{0.400000036f, 0.803921640f, 0.666666687f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumBlue = {{{0.f, 0.f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumOrchid = { + {{0.729411781f, 0.333333343f, 0.827451050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumPurple = { + {{0.576470613f, 0.439215720f, 0.858823597f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { + {{0.235294133f, 0.701960802f, 0.443137288f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { + {{0.482352972f, 0.407843173f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { + {{0.f, 0.980392218f, 0.603921592f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumTurquoise = { + {{0.282352954f, 0.819607913f, 0.800000072f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumVioletRed = { + {{0.780392230f, 0.082352944f, 0.521568656f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MidnightBlue = { + {{0.098039225f, 0.098039225f, 0.439215720f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MintCream = { + {{0.960784376f, 1.f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MistyRose = { + {{1.f, 0.894117713f, 0.882353008f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Moccasin = {{{1.f, 0.894117713f, 0.709803939f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 NavajoWhite = { + {{1.f, 0.870588303f, 0.678431392f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Navy = {{{0.f, 0.f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OldLace = { + {{0.992156923f, 0.960784376f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Olive = {{{0.501960814f, 0.501960814f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OliveDrab = { + {{0.419607878f, 0.556862772f, 0.137254909f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orange = {{{1.f, 0.647058845f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OrangeRed = {{{1.f, 0.270588249f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orchid = { + {{0.854902029f, 0.439215720f, 0.839215755f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { + {{0.933333397f, 0.909803987f, 0.666666687f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGreen = { + {{0.596078455f, 0.984313786f, 0.596078455f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleTurquoise = { + {{0.686274529f, 0.933333397f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleVioletRed = { + {{0.858823597f, 0.439215720f, 0.576470613f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PapayaWhip = { + {{1.f, 0.937254965f, 0.835294187f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PeachPuff = { + {{1.f, 0.854902029f, 0.725490212f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Peru = { + {{0.803921640f, 0.521568656f, 0.247058839f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Pink = {{{1.f, 0.752941251f, 0.796078503f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Plum = { + {{0.866666734f, 0.627451003f, 0.866666734f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PowderBlue = { + {{0.690196097f, 0.878431439f, 0.901960850f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Purple = {{{0.501960814f, 0.f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Red = {{{1.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RosyBrown = { + {{0.737254918f, 0.560784340f, 0.560784340f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RoyalBlue = { + {{0.254901975f, 0.411764741f, 0.882353008f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SaddleBrown = { + {{0.545098066f, 0.270588249f, 0.074509807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Salmon = { + {{0.980392218f, 0.501960814f, 0.447058856f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SandyBrown = { + {{0.956862807f, 0.643137276f, 0.376470625f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaGreen = { + {{0.180392161f, 0.545098066f, 0.341176480f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaShell = {{{1.f, 0.960784376f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Sienna = { + {{0.627451003f, 0.321568638f, 0.176470593f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Silver = { + {{0.752941251f, 0.752941251f, 0.752941251f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SkyBlue = { + {{0.529411793f, 0.807843208f, 0.921568692f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateBlue = { + {{0.415686309f, 0.352941185f, 0.803921640f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateGray = { + {{0.439215720f, 0.501960814f, 0.564705908f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Snow = {{{1.f, 0.980392218f, 0.980392218f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SpringGreen = {{{0.f, 1.f, 0.498039246f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SteelBlue = { + {{0.274509817f, 0.509803951f, 0.705882370f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tan = { + {{0.823529482f, 0.705882370f, 0.549019635f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Teal = {{{0.f, 0.501960814f, 0.501960814f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Thistle = { + {{0.847058892f, 0.749019623f, 0.847058892f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tomato = {{{1.f, 0.388235331f, 0.278431386f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Transparent = {{{0.f, 0.f, 0.f, 0.f}}}; +XMGLOBALCONST XMVECTORF32 Turquoise = { + {{0.250980407f, 0.878431439f, 0.815686345f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Violet = { + {{0.933333397f, 0.509803951f, 0.933333397f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Wheat = { + {{0.960784376f, 0.870588303f, 0.701960802f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 White = {{{1.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 WhiteSmoke = { + {{0.960784376f, 0.960784376f, 0.960784376f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Yellow = {{{1.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 YellowGreen = { + {{0.603921592f, 0.803921640f, 0.196078449f, 1.f}}}; - } // namespace Colors +} // namespace Colors - namespace ColorsLinear - { - // Standard colors (Red/Green/Blue/Alpha) in linear colorspace - XMGLOBALCONST XMVECTORF32 AliceBlue = { { { 0.871367335f, 0.938685894f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 AntiqueWhite = { { { 0.955973506f, 0.830770075f, 0.679542601f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aqua = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Aquamarine = { { { 0.212230787f, 1.f, 0.658374965f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Azure = { { { 0.871367335f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Beige = { { { 0.913098991f, 0.913098991f, 0.715693772f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Bisque = { { { 1.f, 0.775822461f, 0.552011609f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Black = { { { 0.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { { { 1.f, 0.830770075f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Blue = { { { 0.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BlueViolet = { { { 0.254152179f, 0.024157630f, 0.760524750f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Brown = { { { 0.376262218f, 0.023153365f, 0.023153365f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 BurlyWood = { { { 0.730461001f, 0.479320228f, 0.242281199f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CadetBlue = { { { 0.114435382f, 0.341914445f, 0.351532698f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chartreuse = { { { 0.212230787f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Chocolate = { { { 0.644479871f, 0.141263321f, 0.012983031f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Coral = { { { 1.f, 0.212230787f, 0.080219828f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 CornflowerBlue = { { { 0.127437726f, 0.300543845f, 0.846873462f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cornsilk = { { { 1.f, 0.938685894f, 0.715693772f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Crimson = { { { 0.715693772f, 0.006995410f, 0.045186214f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Cyan = { { { 0.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkBlue = { { { 0.f, 0.f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkCyan = { { { 0.f, 0.258182913f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { { { 0.479320228f, 0.238397658f, 0.003346536f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGray = { { { 0.396755308f, 0.396755308f, 0.396755308f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkGreen = { { { 0.f, 0.127437726f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkKhaki = { { { 0.508881450f, 0.473531544f, 0.147027299f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkMagenta = { { { 0.258182913f, 0.f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { { { 0.090841733f, 0.147027299f, 0.028426038f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrange = { { { 1.f, 0.262250721f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkOrchid = { { { 0.318546832f, 0.031896040f, 0.603827536f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkRed = { { { 0.258182913f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSalmon = { { { 0.814846814f, 0.304987371f, 0.194617867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { { { 0.274677366f, 0.502886593f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { { { 0.064803280f, 0.046665095f, 0.258182913f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkSlateGray = { { { 0.028426038f, 0.078187428f, 0.078187428f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkTurquoise = { { { 0.f, 0.617206752f, 0.637597024f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DarkViolet = { { { 0.296138316f, 0.f, 0.651405811f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepPink = { { { 1.f, 0.006995410f, 0.291770697f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DeepSkyBlue = { { { 0.f, 0.520995677f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DimGray = { { { 0.141263321f, 0.141263321f, 0.141263321f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 DodgerBlue = { { { 0.012983031f, 0.278894335f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Firebrick = { { { 0.445201248f, 0.015996292f, 0.015996292f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 FloralWhite = { { { 1.f, 0.955973506f, 0.871367335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 ForestGreen = { { { 0.015996292f, 0.258182913f, 0.015996292f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Fuchsia = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gainsboro = { { { 0.715693772f, 0.715693772f, 0.715693772f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GhostWhite = { { { 0.938685894f, 0.938685894f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gold = { { { 1.f, 0.679542601f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Goldenrod = { { { 0.701102138f, 0.376262218f, 0.014443844f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Gray = { { { 0.215860531f, 0.215860531f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Green = { { { 0.f, 0.215860531f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 GreenYellow = { { { 0.417885154f, 1.f, 0.028426038f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Honeydew = { { { 0.871367335f, 1.f, 0.871367335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 HotPink = { { { 1.f, 0.141263321f, 0.456411064f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 IndianRed = { { { 0.610495746f, 0.107023112f, 0.107023112f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Indigo = { { { 0.070360109f, 0.f, 0.223227978f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Ivory = { { { 1.f, 1.f, 0.871367335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Khaki = { { { 0.871367335f, 0.791298151f, 0.262250721f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lavender = { { { 0.791298151f, 0.791298151f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LavenderBlush = { { { 1.f, 0.871367335f, 0.913098991f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LawnGreen = { { { 0.201556295f, 0.973445475f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LemonChiffon = { { { 1.f, 0.955973506f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightBlue = { { { 0.417885154f, 0.686685443f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCoral = { { { 0.871367335f, 0.215860531f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightCyan = { { { 0.745404482f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { { { 0.955973506f, 0.955973506f, 0.644479871f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGray = { { { 0.651405811f, 0.651405811f, 0.651405811f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightGreen = { { { 0.278894335f, 0.854992807f, 0.278894335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightPink = { { { 1.f, 0.467783839f, 0.533276618f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSalmon = { { { 1.f, 0.351532698f, 0.194617867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSeaGreen = { { { 0.014443844f, 0.445201248f, 0.401977867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSkyBlue = { { { 0.242281199f, 0.617206752f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSlateGray = { { { 0.184475034f, 0.246201396f, 0.318546832f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightSteelBlue = { { { 0.434153706f, 0.552011609f, 0.730461001f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LightYellow = { { { 1.f, 1.f, 0.745404482f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Lime = { { { 0.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 LimeGreen = { { { 0.031896040f, 0.610495746f, 0.031896040f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Linen = { { { 0.955973506f, 0.871367335f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Magenta = { { { 1.f, 0.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Maroon = { { { 0.215860531f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumAquamarine = { { { 0.132868364f, 0.610495746f, 0.401977867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumBlue = { { { 0.f, 0.f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumOrchid = { { { 0.491020888f, 0.090841733f, 0.651405811f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumPurple = { { { 0.291770697f, 0.162029430f, 0.708376050f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { { { 0.045186214f, 0.450785846f, 0.165132239f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { { { 0.198069349f, 0.138431653f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { { { 0.f, 0.955973506f, 0.323143244f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumTurquoise = { { { 0.064803280f, 0.637597024f, 0.603827536f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MediumVioletRed = { { { 0.571125031f, 0.007499032f, 0.234550655f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MidnightBlue = { { { 0.009721218f, 0.009721218f, 0.162029430f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MintCream = { { { 0.913098991f, 1.f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 MistyRose = { { { 1.f, 0.775822461f, 0.752942443f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Moccasin = { { { 1.f, 0.775822461f, 0.462077051f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 NavajoWhite = { { { 1.f, 0.730461001f, 0.417885154f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Navy = { { { 0.f, 0.f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OldLace = { { { 0.982250869f, 0.913098991f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Olive = { { { 0.215860531f, 0.215860531f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OliveDrab = { { { 0.147027299f, 0.270497859f, 0.016807375f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orange = { { { 1.f, 0.376262218f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 OrangeRed = { { { 1.f, 0.059511241f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Orchid = { { { 0.701102138f, 0.162029430f, 0.672443330f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { { { 0.854992807f, 0.806952477f, 0.401977867f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleGreen = { { { 0.313988745f, 0.964686573f, 0.313988745f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleTurquoise = { { { 0.428690553f, 0.854992807f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PaleVioletRed = { { { 0.708376050f, 0.162029430f, 0.291770697f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PapayaWhip = { { { 1.f, 0.863157392f, 0.665387452f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PeachPuff = { { { 1.f, 0.701102138f, 0.485149980f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Peru = { { { 0.610495746f, 0.234550655f, 0.049706575f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Pink = { { { 1.f, 0.527115345f, 0.597202003f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Plum = { { { 0.723055363f, 0.351532698f, 0.723055363f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 PowderBlue = { { { 0.434153706f, 0.745404482f, 0.791298151f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Purple = { { { 0.215860531f, 0.f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Red = { { { 1.f, 0.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RosyBrown = { { { 0.502886593f, 0.274677366f, 0.274677366f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 RoyalBlue = { { { 0.052860655f, 0.141263321f, 0.752942443f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SaddleBrown = { { { 0.258182913f, 0.059511241f, 0.006512091f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Salmon = { { { 0.955973506f, 0.215860531f, 0.168269455f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SandyBrown = { { { 0.904661357f, 0.371237785f, 0.116970696f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaGreen = { { { 0.027320892f, 0.258182913f, 0.095307484f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SeaShell = { { { 1.f, 0.913098991f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Sienna = { { { 0.351532698f, 0.084376216f, 0.026241222f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Silver = { { { 0.527115345f, 0.527115345f, 0.527115345f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SkyBlue = { { { 0.242281199f, 0.617206752f, 0.830770075f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateBlue = { { { 0.144128501f, 0.102241747f, 0.610495746f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SlateGray = { { { 0.162029430f, 0.215860531f, 0.278894335f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Snow = { { { 1.f, 0.955973506f, 0.955973506f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SpringGreen = { { { 0.f, 1.f, 0.212230787f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 SteelBlue = { { { 0.061246071f, 0.223227978f, 0.456411064f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tan = { { { 0.644479871f, 0.456411064f, 0.262250721f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Teal = { { { 0.f, 0.215860531f, 0.215860531f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Thistle = { { { 0.686685443f, 0.520995677f, 0.686685443f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Tomato = { { { 1.f, 0.124771863f, 0.063010029f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Transparent = { { { 0.f, 0.f, 0.f, 0.f } } }; - XMGLOBALCONST XMVECTORF32 Turquoise = { { { 0.051269468f, 0.745404482f, 0.630757332f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Violet = { { { 0.854992807f, 0.223227978f, 0.854992807f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Wheat = { { { 0.913098991f, 0.730461001f, 0.450785846f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 White = { { { 1.f, 1.f, 1.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 WhiteSmoke = { { { 0.913098991f, 0.913098991f, 0.913098991f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 Yellow = { { { 1.f, 1.f, 0.f, 1.f } } }; - XMGLOBALCONST XMVECTORF32 YellowGreen = { { { 0.323143244f, 0.610495746f, 0.031896040f, 1.f } } }; +namespace ColorsLinear { +// Standard colors (Red/Green/Blue/Alpha) in linear colorspace +XMGLOBALCONST XMVECTORF32 AliceBlue = { + {{0.871367335f, 0.938685894f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 AntiqueWhite = { + {{0.955973506f, 0.830770075f, 0.679542601f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aqua = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Aquamarine = { + {{0.212230787f, 1.f, 0.658374965f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Azure = {{{0.871367335f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Beige = { + {{0.913098991f, 0.913098991f, 0.715693772f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Bisque = {{{1.f, 0.775822461f, 0.552011609f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Black = {{{0.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { + {{1.f, 0.830770075f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Blue = {{{0.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BlueViolet = { + {{0.254152179f, 0.024157630f, 0.760524750f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Brown = { + {{0.376262218f, 0.023153365f, 0.023153365f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 BurlyWood = { + {{0.730461001f, 0.479320228f, 0.242281199f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CadetBlue = { + {{0.114435382f, 0.341914445f, 0.351532698f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chartreuse = {{{0.212230787f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Chocolate = { + {{0.644479871f, 0.141263321f, 0.012983031f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Coral = {{{1.f, 0.212230787f, 0.080219828f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 CornflowerBlue = { + {{0.127437726f, 0.300543845f, 0.846873462f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cornsilk = {{{1.f, 0.938685894f, 0.715693772f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Crimson = { + {{0.715693772f, 0.006995410f, 0.045186214f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Cyan = {{{0.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkBlue = {{{0.f, 0.f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkCyan = {{{0.f, 0.258182913f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { + {{0.479320228f, 0.238397658f, 0.003346536f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGray = { + {{0.396755308f, 0.396755308f, 0.396755308f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkGreen = {{{0.f, 0.127437726f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkKhaki = { + {{0.508881450f, 0.473531544f, 0.147027299f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkMagenta = { + {{0.258182913f, 0.f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { + {{0.090841733f, 0.147027299f, 0.028426038f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrange = {{{1.f, 0.262250721f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkOrchid = { + {{0.318546832f, 0.031896040f, 0.603827536f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkRed = {{{0.258182913f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSalmon = { + {{0.814846814f, 0.304987371f, 0.194617867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { + {{0.274677366f, 0.502886593f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { + {{0.064803280f, 0.046665095f, 0.258182913f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkSlateGray = { + {{0.028426038f, 0.078187428f, 0.078187428f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkTurquoise = { + {{0.f, 0.617206752f, 0.637597024f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DarkViolet = { + {{0.296138316f, 0.f, 0.651405811f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepPink = {{{1.f, 0.006995410f, 0.291770697f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DeepSkyBlue = {{{0.f, 0.520995677f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DimGray = { + {{0.141263321f, 0.141263321f, 0.141263321f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 DodgerBlue = { + {{0.012983031f, 0.278894335f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Firebrick = { + {{0.445201248f, 0.015996292f, 0.015996292f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 FloralWhite = { + {{1.f, 0.955973506f, 0.871367335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 ForestGreen = { + {{0.015996292f, 0.258182913f, 0.015996292f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Fuchsia = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gainsboro = { + {{0.715693772f, 0.715693772f, 0.715693772f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GhostWhite = { + {{0.938685894f, 0.938685894f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gold = {{{1.f, 0.679542601f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Goldenrod = { + {{0.701102138f, 0.376262218f, 0.014443844f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Gray = { + {{0.215860531f, 0.215860531f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Green = {{{0.f, 0.215860531f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 GreenYellow = { + {{0.417885154f, 1.f, 0.028426038f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Honeydew = {{{0.871367335f, 1.f, 0.871367335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 HotPink = {{{1.f, 0.141263321f, 0.456411064f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 IndianRed = { + {{0.610495746f, 0.107023112f, 0.107023112f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Indigo = {{{0.070360109f, 0.f, 0.223227978f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Ivory = {{{1.f, 1.f, 0.871367335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Khaki = { + {{0.871367335f, 0.791298151f, 0.262250721f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lavender = { + {{0.791298151f, 0.791298151f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LavenderBlush = { + {{1.f, 0.871367335f, 0.913098991f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LawnGreen = { + {{0.201556295f, 0.973445475f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LemonChiffon = { + {{1.f, 0.955973506f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightBlue = { + {{0.417885154f, 0.686685443f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCoral = { + {{0.871367335f, 0.215860531f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightCyan = {{{0.745404482f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { + {{0.955973506f, 0.955973506f, 0.644479871f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGray = { + {{0.651405811f, 0.651405811f, 0.651405811f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightGreen = { + {{0.278894335f, 0.854992807f, 0.278894335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightPink = { + {{1.f, 0.467783839f, 0.533276618f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSalmon = { + {{1.f, 0.351532698f, 0.194617867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSeaGreen = { + {{0.014443844f, 0.445201248f, 0.401977867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSkyBlue = { + {{0.242281199f, 0.617206752f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSlateGray = { + {{0.184475034f, 0.246201396f, 0.318546832f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightSteelBlue = { + {{0.434153706f, 0.552011609f, 0.730461001f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LightYellow = {{{1.f, 1.f, 0.745404482f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Lime = {{{0.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 LimeGreen = { + {{0.031896040f, 0.610495746f, 0.031896040f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Linen = { + {{0.955973506f, 0.871367335f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Magenta = {{{1.f, 0.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Maroon = {{{0.215860531f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumAquamarine = { + {{0.132868364f, 0.610495746f, 0.401977867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumBlue = {{{0.f, 0.f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumOrchid = { + {{0.491020888f, 0.090841733f, 0.651405811f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumPurple = { + {{0.291770697f, 0.162029430f, 0.708376050f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { + {{0.045186214f, 0.450785846f, 0.165132239f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { + {{0.198069349f, 0.138431653f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { + {{0.f, 0.955973506f, 0.323143244f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumTurquoise = { + {{0.064803280f, 0.637597024f, 0.603827536f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MediumVioletRed = { + {{0.571125031f, 0.007499032f, 0.234550655f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MidnightBlue = { + {{0.009721218f, 0.009721218f, 0.162029430f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MintCream = { + {{0.913098991f, 1.f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 MistyRose = { + {{1.f, 0.775822461f, 0.752942443f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Moccasin = {{{1.f, 0.775822461f, 0.462077051f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 NavajoWhite = { + {{1.f, 0.730461001f, 0.417885154f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Navy = {{{0.f, 0.f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OldLace = { + {{0.982250869f, 0.913098991f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Olive = {{{0.215860531f, 0.215860531f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OliveDrab = { + {{0.147027299f, 0.270497859f, 0.016807375f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orange = {{{1.f, 0.376262218f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 OrangeRed = {{{1.f, 0.059511241f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Orchid = { + {{0.701102138f, 0.162029430f, 0.672443330f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { + {{0.854992807f, 0.806952477f, 0.401977867f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleGreen = { + {{0.313988745f, 0.964686573f, 0.313988745f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleTurquoise = { + {{0.428690553f, 0.854992807f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PaleVioletRed = { + {{0.708376050f, 0.162029430f, 0.291770697f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PapayaWhip = { + {{1.f, 0.863157392f, 0.665387452f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PeachPuff = { + {{1.f, 0.701102138f, 0.485149980f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Peru = { + {{0.610495746f, 0.234550655f, 0.049706575f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Pink = {{{1.f, 0.527115345f, 0.597202003f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Plum = { + {{0.723055363f, 0.351532698f, 0.723055363f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 PowderBlue = { + {{0.434153706f, 0.745404482f, 0.791298151f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Purple = {{{0.215860531f, 0.f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Red = {{{1.f, 0.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RosyBrown = { + {{0.502886593f, 0.274677366f, 0.274677366f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 RoyalBlue = { + {{0.052860655f, 0.141263321f, 0.752942443f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SaddleBrown = { + {{0.258182913f, 0.059511241f, 0.006512091f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Salmon = { + {{0.955973506f, 0.215860531f, 0.168269455f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SandyBrown = { + {{0.904661357f, 0.371237785f, 0.116970696f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaGreen = { + {{0.027320892f, 0.258182913f, 0.095307484f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SeaShell = {{{1.f, 0.913098991f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Sienna = { + {{0.351532698f, 0.084376216f, 0.026241222f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Silver = { + {{0.527115345f, 0.527115345f, 0.527115345f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SkyBlue = { + {{0.242281199f, 0.617206752f, 0.830770075f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateBlue = { + {{0.144128501f, 0.102241747f, 0.610495746f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SlateGray = { + {{0.162029430f, 0.215860531f, 0.278894335f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Snow = {{{1.f, 0.955973506f, 0.955973506f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SpringGreen = {{{0.f, 1.f, 0.212230787f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 SteelBlue = { + {{0.061246071f, 0.223227978f, 0.456411064f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tan = { + {{0.644479871f, 0.456411064f, 0.262250721f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Teal = {{{0.f, 0.215860531f, 0.215860531f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Thistle = { + {{0.686685443f, 0.520995677f, 0.686685443f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Tomato = {{{1.f, 0.124771863f, 0.063010029f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Transparent = {{{0.f, 0.f, 0.f, 0.f}}}; +XMGLOBALCONST XMVECTORF32 Turquoise = { + {{0.051269468f, 0.745404482f, 0.630757332f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Violet = { + {{0.854992807f, 0.223227978f, 0.854992807f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Wheat = { + {{0.913098991f, 0.730461001f, 0.450785846f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 White = {{{1.f, 1.f, 1.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 WhiteSmoke = { + {{0.913098991f, 0.913098991f, 0.913098991f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 Yellow = {{{1.f, 1.f, 0.f, 1.f}}}; +XMGLOBALCONST XMVECTORF32 YellowGreen = { + {{0.323143244f, 0.610495746f, 0.031896040f, 1.f}}}; - } // namespace ColorsLinear - -} // namespace DirectX +} // namespace ColorsLinear +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h index b11c37c6e..0beb3a724 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXMath.h @@ -19,7 +19,10 @@ #error DirectX Math requires Visual C++ 2017 or later. #endif -#if defined(_MSC_VER) && !defined(_M_ARM) && !defined(_M_ARM64) && !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) && (!_MANAGED) && (!_M_CEE) && (!defined(_M_IX86_FP) || (_M_IX86_FP > 1)) && !defined(_XM_NO_INTRINSICS_) && !defined(_XM_VECTORCALL_) +#if defined(_MSC_VER) && !defined(_M_ARM) && !defined(_M_ARM64) && \ + !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) && (!_MANAGED) && \ + (!_M_CEE) && (!defined(_M_IX86_FP) || (_M_IX86_FP > 1)) && \ + !defined(_XM_NO_INTRINSICS_) && !defined(_XM_VECTORCALL_) #define _XM_VECTORCALL_ 1 #endif @@ -35,25 +38,31 @@ #if (__cplusplus >= 201402L) #define XM_DEPRECATED [[deprecated]] #elif defined(__GNUC__) -#define XM_DEPRECATED __attribute__ ((deprecated)) +#define XM_DEPRECATED __attribute__((deprecated)) #else -#define XM_DEPRECATED __declspec(deprecated("This is deprecated and will be removed in a future version.")) +#define XM_DEPRECATED \ + __declspec(deprecated( \ + "This is deprecated and will be removed in a future version.")) #endif #endif -#if !defined(_XM_AVX2_INTRINSICS_) && defined(__AVX2__) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_AVX2_INTRINSICS_) && defined(__AVX2__) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_AVX2_INTRINSICS_ #endif -#if !defined(_XM_FMA3_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_FMA3_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_FMA3_INTRINSICS_ #endif -#if !defined(_XM_F16C_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_F16C_INTRINSICS_) && defined(_XM_AVX2_INTRINSICS_) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_F16C_INTRINSICS_ #endif -#if !defined(_XM_F16C_INTRINSICS_) && defined(__F16C__) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_F16C_INTRINSICS_) && defined(__F16C__) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_F16C_INTRINSICS_ #endif @@ -65,7 +74,8 @@ #define _XM_AVX_INTRINSICS_ #endif -#if !defined(_XM_AVX_INTRINSICS_) && defined(__AVX__) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_AVX_INTRINSICS_) && defined(__AVX__) && \ + !defined(_XM_NO_INTRINSICS_) #define _XM_AVX_INTRINSICS_ #endif @@ -81,27 +91,34 @@ #define _XM_SSE_INTRINSICS_ #endif -#if !defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) -#if (defined(_M_IX86) || defined(_M_X64) || __i386__ || __x86_64__) && !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) +#if !defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_SSE_INTRINSICS_) && \ + !defined(_XM_NO_INTRINSICS_) +#if (defined(_M_IX86) || defined(_M_X64) || __i386__ || __x86_64__) && \ + !defined(_M_HYBRID_X86_ARM64) && !defined(_M_ARM64EC) #define _XM_SSE_INTRINSICS_ -#elif defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || __arm__ || __aarch64__ +#elif defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || __arm__ || __aarch64__ #define _XM_ARM_NEON_INTRINSICS_ #elif !defined(_XM_NO_INTRINSICS_) #error DirectX Math does not support this target #endif -#endif // !_XM_ARM_NEON_INTRINSICS_ && !_XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // !_XM_ARM_NEON_INTRINSICS_ && !_XM_SSE_INTRINSICS_ && + // !_XM_NO_INTRINSICS_ -#if defined(_XM_SSE_INTRINSICS_) && defined(_MSC_VER) && (_MSC_VER >= 1920) && !defined(__clang__) && !defined(_XM_SVML_INTRINSICS_) && !defined(_XM_DISABLE_INTEL_SVML_) +#if defined(_XM_SSE_INTRINSICS_) && defined(_MSC_VER) && (_MSC_VER >= 1920) && \ + !defined(__clang__) && !defined(_XM_SVML_INTRINSICS_) && \ + !defined(_XM_DISABLE_INTEL_SVML_) #define _XM_SVML_INTRINSICS_ #endif -#if !defined(_XM_NO_XMVECTOR_OVERLOADS_) && (defined(__clang__) || defined(__GNUC__)) && !defined(_XM_NO_INTRINSICS_) +#if !defined(_XM_NO_XMVECTOR_OVERLOADS_) && \ + (defined(__clang__) || defined(__GNUC__)) && !defined(_XM_NO_INTRINSICS_) #define _XM_NO_XMVECTOR_OVERLOADS_ #endif #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4514 4820) +#pragma warning(disable : 4514 4820) // C4514/4820: Off by default noise #endif #include @@ -124,7 +141,8 @@ #pragma warning(pop) #endif -#if (defined(__clang__) || defined(__GNUC__)) && (__x86_64__ || __i386__) && !defined(__MINGW32__) +#if (defined(__clang__) || defined(__GNUC__)) && (__x86_64__ || __i386__) && \ + !defined(__MINGW32__) #include #endif @@ -145,13 +163,14 @@ #endif #elif defined(_XM_ARM_NEON_INTRINSICS_) -#if defined(_MSC_VER) && !defined(__clang__) && (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC)) +#if defined(_MSC_VER) && !defined(__clang__) && \ + (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC)) #include #else #include #endif #endif -#endif // !_XM_NO_INTRINSICS_ +#endif // !_XM_NO_INTRINSICS_ #include "sal.h" #include @@ -170,8 +189,8 @@ #define XM_ALIGNED_DATA(x) alignas(x) #define XM_ALIGNED_STRUCT(x) struct alignas(x) #elif defined(__GNUC__) -#define XM_ALIGNED_DATA(x) __attribute__ ((aligned(x))) -#define XM_ALIGNED_STRUCT(x) struct __attribute__ ((aligned(x))) +#define XM_ALIGNED_DATA(x) __attribute__((aligned(x))) +#define XM_ALIGNED_STRUCT(x) struct __attribute__((aligned(x))) #else #define XM_ALIGNED_DATA(x) __declspec(align(x)) #define XM_ALIGNED_STRUCT(x) __declspec(align(x)) struct @@ -190,57 +209,57 @@ #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) #if defined(_XM_NO_MOVNT_) -#define XM_STREAM_PS( p, a ) _mm_store_ps((p), (a)) -#define XM256_STREAM_PS( p, a ) _mm256_store_ps((p), (a)) +#define XM_STREAM_PS(p, a) _mm_store_ps((p), (a)) +#define XM256_STREAM_PS(p, a) _mm256_store_ps((p), (a)) #define XM_SFENCE() #else -#define XM_STREAM_PS( p, a ) _mm_stream_ps((p), (a)) -#define XM256_STREAM_PS( p, a ) _mm256_stream_ps((p), (a)) +#define XM_STREAM_PS(p, a) _mm_stream_ps((p), (a)) +#define XM256_STREAM_PS(p, a) _mm256_stream_ps((p), (a)) #define XM_SFENCE() _mm_sfence() #endif #if defined(_XM_FMA3_INTRINSICS_) -#define XM_FMADD_PS( a, b, c ) _mm_fmadd_ps((a), (b), (c)) -#define XM_FNMADD_PS( a, b, c ) _mm_fnmadd_ps((a), (b), (c)) +#define XM_FMADD_PS(a, b, c) _mm_fmadd_ps((a), (b), (c)) +#define XM_FNMADD_PS(a, b, c) _mm_fnmadd_ps((a), (b), (c)) #else -#define XM_FMADD_PS( a, b, c ) _mm_add_ps(_mm_mul_ps((a), (b)), (c)) -#define XM_FNMADD_PS( a, b, c ) _mm_sub_ps((c), _mm_mul_ps((a), (b))) +#define XM_FMADD_PS(a, b, c) _mm_add_ps(_mm_mul_ps((a), (b)), (c)) +#define XM_FNMADD_PS(a, b, c) _mm_sub_ps((c), _mm_mul_ps((a), (b))) #endif #if defined(_XM_AVX_INTRINSICS_) && defined(_XM_FAVOR_INTEL_) -#define XM_PERMUTE_PS( v, c ) _mm_permute_ps((v), c ) +#define XM_PERMUTE_PS(v, c) _mm_permute_ps((v), c) #else -#define XM_PERMUTE_PS( v, c ) _mm_shuffle_ps((v), (v), c ) +#define XM_PERMUTE_PS(v, c) _mm_shuffle_ps((v), (v), c) #endif #if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ < 11) -#define XM_LOADU_SI16( p ) _mm_cvtsi32_si128(*reinterpret_cast(p)) +#define XM_LOADU_SI16(p) \ + _mm_cvtsi32_si128(*reinterpret_cast(p)) #else -#define XM_LOADU_SI16( p ) _mm_loadu_si16(p) +#define XM_LOADU_SI16(p) _mm_loadu_si16(p) #endif -#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ #if defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) #if defined(__clang__) || defined(__GNUC__) -#define XM_PREFETCH( a ) __builtin_prefetch(a) +#define XM_PREFETCH(a) __builtin_prefetch(a) #elif defined(_MSC_VER) -#define XM_PREFETCH( a ) __prefetch(a) +#define XM_PREFETCH(a) __prefetch(a) #else -#define XM_PREFETCH( a ) +#define XM_PREFETCH(a) #endif -#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ -namespace DirectX -{ +namespace DirectX { - /**************************************************************************** - * - * Constant definitions - * - ****************************************************************************/ +/**************************************************************************** + * + * Constant definitions + * + ****************************************************************************/ #if defined(__XNAMATH_H__) && defined(XM_PI) #undef XM_PI @@ -266,47 +285,47 @@ namespace DirectX #undef XM_CACHE_LINE_SIZE #endif - constexpr float XM_PI = 3.141592654f; - constexpr float XM_2PI = 6.283185307f; - constexpr float XM_1DIVPI = 0.318309886f; - constexpr float XM_1DIV2PI = 0.159154943f; - constexpr float XM_PIDIV2 = 1.570796327f; - constexpr float XM_PIDIV4 = 0.785398163f; +constexpr float XM_PI = 3.141592654f; +constexpr float XM_2PI = 6.283185307f; +constexpr float XM_1DIVPI = 0.318309886f; +constexpr float XM_1DIV2PI = 0.159154943f; +constexpr float XM_PIDIV2 = 1.570796327f; +constexpr float XM_PIDIV4 = 0.785398163f; - constexpr uint32_t XM_SELECT_0 = 0x00000000; - constexpr uint32_t XM_SELECT_1 = 0xFFFFFFFF; +constexpr uint32_t XM_SELECT_0 = 0x00000000; +constexpr uint32_t XM_SELECT_1 = 0xFFFFFFFF; - constexpr uint32_t XM_PERMUTE_0X = 0; - constexpr uint32_t XM_PERMUTE_0Y = 1; - constexpr uint32_t XM_PERMUTE_0Z = 2; - constexpr uint32_t XM_PERMUTE_0W = 3; - constexpr uint32_t XM_PERMUTE_1X = 4; - constexpr uint32_t XM_PERMUTE_1Y = 5; - constexpr uint32_t XM_PERMUTE_1Z = 6; - constexpr uint32_t XM_PERMUTE_1W = 7; +constexpr uint32_t XM_PERMUTE_0X = 0; +constexpr uint32_t XM_PERMUTE_0Y = 1; +constexpr uint32_t XM_PERMUTE_0Z = 2; +constexpr uint32_t XM_PERMUTE_0W = 3; +constexpr uint32_t XM_PERMUTE_1X = 4; +constexpr uint32_t XM_PERMUTE_1Y = 5; +constexpr uint32_t XM_PERMUTE_1Z = 6; +constexpr uint32_t XM_PERMUTE_1W = 7; - constexpr uint32_t XM_SWIZZLE_X = 0; - constexpr uint32_t XM_SWIZZLE_Y = 1; - constexpr uint32_t XM_SWIZZLE_Z = 2; - constexpr uint32_t XM_SWIZZLE_W = 3; +constexpr uint32_t XM_SWIZZLE_X = 0; +constexpr uint32_t XM_SWIZZLE_Y = 1; +constexpr uint32_t XM_SWIZZLE_Z = 2; +constexpr uint32_t XM_SWIZZLE_W = 3; - constexpr uint32_t XM_CRMASK_CR6 = 0x000000F0; - constexpr uint32_t XM_CRMASK_CR6TRUE = 0x00000080; - constexpr uint32_t XM_CRMASK_CR6FALSE = 0x00000020; - constexpr uint32_t XM_CRMASK_CR6BOUNDS = XM_CRMASK_CR6FALSE; +constexpr uint32_t XM_CRMASK_CR6 = 0x000000F0; +constexpr uint32_t XM_CRMASK_CR6TRUE = 0x00000080; +constexpr uint32_t XM_CRMASK_CR6FALSE = 0x00000020; +constexpr uint32_t XM_CRMASK_CR6BOUNDS = XM_CRMASK_CR6FALSE; -#if defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || __arm__ || __aarch64__ - constexpr size_t XM_CACHE_LINE_SIZE = 128; +#if defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || __arm__ || __aarch64__ +constexpr size_t XM_CACHE_LINE_SIZE = 128; #else - constexpr size_t XM_CACHE_LINE_SIZE = 64; +constexpr size_t XM_CACHE_LINE_SIZE = 64; #endif - - /**************************************************************************** - * - * Macros - * - ****************************************************************************/ +/**************************************************************************** + * + * Macros + * + ****************************************************************************/ #if defined(__XNAMATH_H__) && defined(XMComparisonAllTrue) #undef XMComparisonAllTrue @@ -318,35 +337,52 @@ namespace DirectX #undef XMComparisonAnyOutOfBounds #endif - // Unit conversion +// Unit conversion - constexpr float XMConvertToRadians(float fDegrees) noexcept { return fDegrees * (XM_PI / 180.0f); } - constexpr float XMConvertToDegrees(float fRadians) noexcept { return fRadians * (180.0f / XM_PI); } +constexpr float XMConvertToRadians(float fDegrees) noexcept { + return fDegrees * (XM_PI / 180.0f); +} +constexpr float XMConvertToDegrees(float fRadians) noexcept { + return fRadians * (180.0f / XM_PI); +} - // Condition register evaluation proceeding a recording (R) comparison +// Condition register evaluation proceeding a recording (R) comparison - constexpr bool XMComparisonAllTrue(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6TRUE) == XM_CRMASK_CR6TRUE; } - constexpr bool XMComparisonAnyTrue(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6FALSE) != XM_CRMASK_CR6FALSE; } - constexpr bool XMComparisonAllFalse(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6FALSE) == XM_CRMASK_CR6FALSE; } - constexpr bool XMComparisonAnyFalse(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6TRUE) != XM_CRMASK_CR6TRUE; } - constexpr bool XMComparisonMixed(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6) == 0; } - constexpr bool XMComparisonAllInBounds(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6BOUNDS) == XM_CRMASK_CR6BOUNDS; } - constexpr bool XMComparisonAnyOutOfBounds(uint32_t CR) noexcept { return (CR & XM_CRMASK_CR6BOUNDS) != XM_CRMASK_CR6BOUNDS; } +constexpr bool XMComparisonAllTrue(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6TRUE) == XM_CRMASK_CR6TRUE; +} +constexpr bool XMComparisonAnyTrue(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6FALSE) != XM_CRMASK_CR6FALSE; +} +constexpr bool XMComparisonAllFalse(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6FALSE) == XM_CRMASK_CR6FALSE; +} +constexpr bool XMComparisonAnyFalse(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6TRUE) != XM_CRMASK_CR6TRUE; +} +constexpr bool XMComparisonMixed(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6) == 0; +} +constexpr bool XMComparisonAllInBounds(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6BOUNDS) == XM_CRMASK_CR6BOUNDS; +} +constexpr bool XMComparisonAnyOutOfBounds(uint32_t CR) noexcept { + return (CR & XM_CRMASK_CR6BOUNDS) != XM_CRMASK_CR6BOUNDS; +} - - /**************************************************************************** - * - * Data types - * - ****************************************************************************/ +/**************************************************************************** + * + * Data types + * + ****************************************************************************/ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4068 4201 4365 4324 4820) - // C4068: ignore unknown pragmas - // C4201: nonstandard extension used : nameless struct/union - // C4365: Off by default noise - // C4324/4820: padding warnings +#pragma warning(disable : 4068 4201 4365 4324 4820) +// C4068: ignore unknown pragmas +// C4201: nonstandard extension used : nameless struct/union +// C4365: Off by default noise +// C4324/4820: padding warnings #endif #ifdef _PREFAST_ @@ -356,470 +392,500 @@ namespace DirectX //------------------------------------------------------------------------------ #if defined(_XM_NO_INTRINSICS_) - struct __vector4 - { - union - { - float vector4_f32[4]; - uint32_t vector4_u32[4]; - }; +struct __vector4 { + union { + float vector4_f32[4]; + uint32_t vector4_u32[4]; }; -#endif // _XM_NO_INTRINSICS_ +}; +#endif // _XM_NO_INTRINSICS_ - //------------------------------------------------------------------------------ - // Vector intrinsic: Four 32 bit floating point components aligned on a 16 byte - // boundary and mapped to hardware vector registers +//------------------------------------------------------------------------------ +// Vector intrinsic: Four 32 bit floating point components aligned on a 16 byte +// boundary and mapped to hardware vector registers #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - using XMVECTOR = __m128; +using XMVECTOR = __m128; #elif defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - using XMVECTOR = float32x4_t; +using XMVECTOR = float32x4_t; #else - using XMVECTOR = __vector4; +using XMVECTOR = __vector4; #endif - // Fix-up for (1st-3rd) XMVECTOR parameters that are pass-in-register for x86, ARM, ARM64, and vector call; by reference otherwise -#if ( defined(_M_IX86) || defined(_M_ARM) || defined(_M_ARM64) || _XM_VECTORCALL_ || __i386__ || __arm__ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMVECTOR FXMVECTOR; +// Fix-up for (1st-3rd) XMVECTOR parameters that are pass-in-register for x86, +// ARM, ARM64, and vector call; by reference otherwise +#if (defined(_M_IX86) || defined(_M_ARM) || defined(_M_ARM64) || \ + _XM_VECTORCALL_ || __i386__ || __arm__ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMVECTOR FXMVECTOR; #else - typedef const XMVECTOR& FXMVECTOR; +typedef const XMVECTOR& FXMVECTOR; #endif - // Fix-up for (4th) XMVECTOR parameter to pass in-register for ARM, ARM64, and vector call; by reference otherwise -#if ( defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || _XM_VECTORCALL_ || __arm__ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMVECTOR GXMVECTOR; +// Fix-up for (4th) XMVECTOR parameter to pass in-register for ARM, ARM64, and +// vector call; by reference otherwise +#if (defined(_M_ARM) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || _XM_VECTORCALL_ || __arm__ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMVECTOR GXMVECTOR; #else - typedef const XMVECTOR& GXMVECTOR; +typedef const XMVECTOR& GXMVECTOR; #endif - // Fix-up for (5th & 6th) XMVECTOR parameter to pass in-register for ARM64 and vector call; by reference otherwise -#if ( defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMVECTOR HXMVECTOR; +// Fix-up for (5th & 6th) XMVECTOR parameter to pass in-register for ARM64 and +// vector call; by reference otherwise +#if (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMVECTOR HXMVECTOR; #else - typedef const XMVECTOR& HXMVECTOR; +typedef const XMVECTOR& HXMVECTOR; #endif - // Fix-up for (7th+) XMVECTOR parameters to pass by reference - typedef const XMVECTOR& CXMVECTOR; +// Fix-up for (7th+) XMVECTOR parameters to pass by reference +typedef const XMVECTOR& CXMVECTOR; - //------------------------------------------------------------------------------ - // Conversion types for constants - XM_ALIGNED_STRUCT(16) XMVECTORF32 - { - union - { - float f[4]; - XMVECTOR v; - }; - - inline operator XMVECTOR() const noexcept { return v; } - inline operator const float* () const noexcept { return f; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +//------------------------------------------------------------------------------ +// Conversion types for constants +XM_ALIGNED_STRUCT(16) XMVECTORF32 { + union { + float f[4]; + XMVECTOR v; }; - XM_ALIGNED_STRUCT(16) XMVECTORI32 - { - union - { - int32_t i[4]; - XMVECTOR v; - }; + inline operator XMVECTOR() const noexcept { return v; } + inline operator const float*() const noexcept { return f; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; - inline operator XMVECTOR() const noexcept { return v; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +XM_ALIGNED_STRUCT(16) XMVECTORI32 { + union { + int32_t i[4]; + XMVECTOR v; }; - XM_ALIGNED_STRUCT(16) XMVECTORU8 - { - union - { - uint8_t u[16]; - XMVECTOR v; - }; + inline operator XMVECTOR() const noexcept { return v; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; - inline operator XMVECTOR() const noexcept { return v; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +XM_ALIGNED_STRUCT(16) XMVECTORU8 { + union { + uint8_t u[16]; + XMVECTOR v; }; - XM_ALIGNED_STRUCT(16) XMVECTORU32 - { - union - { - uint32_t u[4]; - XMVECTOR v; - }; + inline operator XMVECTOR() const noexcept { return v; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; - inline operator XMVECTOR() const noexcept { return v; } - #ifdef _XM_NO_INTRINSICS_ - #elif defined(_XM_SSE_INTRINSICS_) - inline operator __m128i() const noexcept { return _mm_castps_si128(v); } - inline operator __m128d() const noexcept { return _mm_castps_pd(v); } - #elif defined(_XM_ARM_NEON_INTRINSICS_) && (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) - inline operator int32x4_t() const noexcept { return vreinterpretq_s32_f32(v); } - inline operator uint32x4_t() const noexcept { return vreinterpretq_u32_f32(v); } - #endif +XM_ALIGNED_STRUCT(16) XMVECTORU32 { + union { + uint32_t u[4]; + XMVECTOR v; }; - //------------------------------------------------------------------------------ - // Vector operators + inline operator XMVECTOR() const noexcept { return v; } +#ifdef _XM_NO_INTRINSICS_ +#elif defined(_XM_SSE_INTRINSICS_) + inline operator __m128i() const noexcept { return _mm_castps_si128(v); } + inline operator __m128d() const noexcept { return _mm_castps_pd(v); } +#elif defined(_XM_ARM_NEON_INTRINSICS_) && \ + (defined(__GNUC__) || defined(_ARM64_DISTINCT_NEON_TYPES)) + inline operator int32x4_t() const noexcept { + return vreinterpretq_s32_f32(v); + } + inline operator uint32x4_t() const noexcept { + return vreinterpretq_u32_f32(v); + } +#endif +}; + +//------------------------------------------------------------------------------ +// Vector operators #ifndef _XM_NO_XMVECTOR_OVERLOADS_ - XMVECTOR XM_CALLCONV operator+ (FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV operator- (FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV operator+(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV operator-(FXMVECTOR V) noexcept; - XMVECTOR& XM_CALLCONV operator+= (XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& XM_CALLCONV operator-= (XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& XM_CALLCONV operator*= (XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& XM_CALLCONV operator/= (XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator+=(XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator-=(XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator*=(XMVECTOR& V1, FXMVECTOR V2) noexcept; +XMVECTOR& XM_CALLCONV operator/=(XMVECTOR& V1, FXMVECTOR V2) noexcept; - XMVECTOR& operator*= (XMVECTOR& V, float S) noexcept; - XMVECTOR& operator/= (XMVECTOR& V, float S) noexcept; +XMVECTOR& operator*=(XMVECTOR& V, float S) noexcept; +XMVECTOR& operator/=(XMVECTOR& V, float S) noexcept; - XMVECTOR XM_CALLCONV operator+ (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator- (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator* (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator/ (FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV operator* (FXMVECTOR V, float S) noexcept; - XMVECTOR XM_CALLCONV operator* (float S, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV operator/ (FXMVECTOR V, float S) noexcept; +XMVECTOR XM_CALLCONV operator+(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator-(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator*(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator/(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV operator*(FXMVECTOR V, float S) noexcept; +XMVECTOR XM_CALLCONV operator*(float S, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV operator/(FXMVECTOR V, float S) noexcept; #endif /* !_XM_NO_XMVECTOR_OVERLOADS_ */ - //------------------------------------------------------------------------------ - // Matrix type: Sixteen 32 bit floating point components aligned on a - // 16 byte boundary and mapped to four hardware vector registers +//------------------------------------------------------------------------------ +// Matrix type: Sixteen 32 bit floating point components aligned on a +// 16 byte boundary and mapped to four hardware vector registers - struct XMMATRIX; +struct XMMATRIX; - // Fix-up for (1st) XMMATRIX parameter to pass in-register for ARM64 and vector call; by reference otherwise -#if ( defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__ ) && !defined(_XM_NO_INTRINSICS_) - typedef const XMMATRIX FXMMATRIX; +// Fix-up for (1st) XMMATRIX parameter to pass in-register for ARM64 and vector +// call; by reference otherwise +#if (defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || \ + defined(_M_ARM64EC) || _XM_VECTORCALL_ || __aarch64__) && \ + !defined(_XM_NO_INTRINSICS_) +typedef const XMMATRIX FXMMATRIX; #else - typedef const XMMATRIX& FXMMATRIX; +typedef const XMMATRIX& FXMMATRIX; #endif - // Fix-up for (2nd+) XMMATRIX parameters to pass by reference - typedef const XMMATRIX& CXMMATRIX; +// Fix-up for (2nd+) XMMATRIX parameters to pass by reference +typedef const XMMATRIX& CXMMATRIX; #ifdef _XM_NO_INTRINSICS_ - struct XMMATRIX - #else - XM_ALIGNED_STRUCT(16) XMMATRIX - #endif - { - #ifdef _XM_NO_INTRINSICS_ - union - { - XMVECTOR r[4]; - struct - { - float _11, _12, _13, _14; - float _21, _22, _23, _24; - float _31, _32, _33, _34; - float _41, _42, _43, _44; - }; - float m[4][4]; - }; - #else +struct XMMATRIX +#else +XM_ALIGNED_STRUCT(16) +XMMATRIX +#endif +{ +#ifdef _XM_NO_INTRINSICS_ + union { XMVECTOR r[4]; - #endif - - XMMATRIX() = default; - - XMMATRIX(const XMMATRIX&) = default; - - #if defined(_MSC_VER) && (_MSC_FULL_VER < 191426431) - XMMATRIX& operator= (const XMMATRIX& M) noexcept { r[0] = M.r[0]; r[1] = M.r[1]; r[2] = M.r[2]; r[3] = M.r[3]; return *this; } - #else - XMMATRIX& operator=(const XMMATRIX&) = default; - - XMMATRIX(XMMATRIX&&) = default; - XMMATRIX& operator=(XMMATRIX&&) = default; - #endif - - constexpr XMMATRIX(FXMVECTOR R0, FXMVECTOR R1, FXMVECTOR R2, CXMVECTOR R3) noexcept : r{ R0,R1,R2,R3 } {} - XMMATRIX(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23, - float m30, float m31, float m32, float m33) noexcept; - explicit XMMATRIX(_In_reads_(16) const float* pArray) noexcept; - - #ifdef _XM_NO_INTRINSICS_ - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - #endif - - XMMATRIX operator+ () const noexcept { return *this; } - XMMATRIX operator- () const noexcept; - - XMMATRIX& XM_CALLCONV operator+= (FXMMATRIX M) noexcept; - XMMATRIX& XM_CALLCONV operator-= (FXMMATRIX M) noexcept; - XMMATRIX& XM_CALLCONV operator*= (FXMMATRIX M) noexcept; - XMMATRIX& operator*= (float S) noexcept; - XMMATRIX& operator/= (float S) noexcept; - - XMMATRIX XM_CALLCONV operator+ (FXMMATRIX M) const noexcept; - XMMATRIX XM_CALLCONV operator- (FXMMATRIX M) const noexcept; - XMMATRIX XM_CALLCONV operator* (FXMMATRIX M) const noexcept; - XMMATRIX operator* (float S) const noexcept; - XMMATRIX operator/ (float S) const noexcept; - - friend XMMATRIX XM_CALLCONV operator* (float S, FXMMATRIX M) noexcept; + struct { + float _11, _12, _13, _14; + float _21, _22, _23, _24; + float _31, _32, _33, _34; + float _41, _42, _43, _44; + }; + float m[4][4]; }; +#else + XMVECTOR r[4]; +#endif - //------------------------------------------------------------------------------ - // 2D Vector; 32 bit floating point components - struct XMFLOAT2 - { - float x; - float y; + XMMATRIX() = default; - XMFLOAT2() = default; + XMMATRIX(const XMMATRIX&) = default; - XMFLOAT2(const XMFLOAT2&) = default; - XMFLOAT2& operator=(const XMFLOAT2&) = default; +#if defined(_MSC_VER) && (_MSC_FULL_VER < 191426431) + XMMATRIX& operator=(const XMMATRIX& M) noexcept { + r[0] = M.r[0]; + r[1] = M.r[1]; + r[2] = M.r[2]; + r[3] = M.r[3]; + return *this; + } +#else + XMMATRIX& operator=(const XMMATRIX&) = default; - XMFLOAT2(XMFLOAT2&&) = default; - XMFLOAT2& operator=(XMFLOAT2&&) = default; + XMMATRIX(XMMATRIX&&) = default; + XMMATRIX& operator=(XMMATRIX&&) = default; +#endif - constexpr XMFLOAT2(float _x, float _y) noexcept : x(_x), y(_y) {} - explicit XMFLOAT2(_In_reads_(2) const float* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} + constexpr XMMATRIX(FXMVECTOR R0, FXMVECTOR R1, FXMVECTOR R2, + CXMVECTOR R3) noexcept + : r{R0, R1, R2, R3} {} + XMMATRIX(float m00, float m01, float m02, float m03, float m10, float m11, + float m12, float m13, float m20, float m21, float m22, float m23, + float m30, float m31, float m32, float m33) noexcept; + explicit XMMATRIX(_In_reads_(16) const float* pArray) noexcept; - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT2&) const = default; - auto operator <=> (const XMFLOAT2&) const = default; - #endif - }; +#ifdef _XM_NO_INTRINSICS_ + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } +#endif - // 2D Vector; 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT2A : public XMFLOAT2 - { - using XMFLOAT2::XMFLOAT2; - }; + XMMATRIX operator+() const noexcept { return *this; } + XMMATRIX operator-() const noexcept; - //------------------------------------------------------------------------------ - // 2D Vector; 32 bit signed integer components - struct XMINT2 - { - int32_t x; - int32_t y; + XMMATRIX& XM_CALLCONV operator+=(FXMMATRIX M) noexcept; + XMMATRIX& XM_CALLCONV operator-=(FXMMATRIX M) noexcept; + XMMATRIX& XM_CALLCONV operator*=(FXMMATRIX M) noexcept; + XMMATRIX& operator*=(float S) noexcept; + XMMATRIX& operator/=(float S) noexcept; - XMINT2() = default; + XMMATRIX XM_CALLCONV operator+(FXMMATRIX M) const noexcept; + XMMATRIX XM_CALLCONV operator-(FXMMATRIX M) const noexcept; + XMMATRIX XM_CALLCONV operator*(FXMMATRIX M) const noexcept; + XMMATRIX operator*(float S) const noexcept; + XMMATRIX operator/(float S) const noexcept; - XMINT2(const XMINT2&) = default; - XMINT2& operator=(const XMINT2&) = default; + friend XMMATRIX XM_CALLCONV operator*(float S, FXMMATRIX M) noexcept; +}; - XMINT2(XMINT2&&) = default; - XMINT2& operator=(XMINT2&&) = default; +//------------------------------------------------------------------------------ +// 2D Vector; 32 bit floating point components +struct XMFLOAT2 { + float x; + float y; - constexpr XMINT2(int32_t _x, int32_t _y) noexcept : x(_x), y(_y) {} - explicit XMINT2(_In_reads_(2) const int32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} + XMFLOAT2() = default; - #if (__cplusplus >= 202002L) - bool operator == (const XMINT2&) const = default; - auto operator <=> (const XMINT2&) const = default; - #endif - }; + XMFLOAT2(const XMFLOAT2&) = default; + XMFLOAT2& operator=(const XMFLOAT2&) = default; - // 2D Vector; 32 bit unsigned integer components - struct XMUINT2 - { - uint32_t x; - uint32_t y; + XMFLOAT2(XMFLOAT2&&) = default; + XMFLOAT2& operator=(XMFLOAT2&&) = default; - XMUINT2() = default; + constexpr XMFLOAT2(float _x, float _y) noexcept : x(_x), y(_y) {} + explicit XMFLOAT2(_In_reads_(2) const float* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} - XMUINT2(const XMUINT2&) = default; - XMUINT2& operator=(const XMUINT2&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT2&) const = default; + auto operator<=>(const XMFLOAT2&) const = default; +#endif +}; - XMUINT2(XMUINT2&&) = default; - XMUINT2& operator=(XMUINT2&&) = default; +// 2D Vector; 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT2A : public XMFLOAT2 { using XMFLOAT2::XMFLOAT2; }; - constexpr XMUINT2(uint32_t _x, uint32_t _y) noexcept : x(_x), y(_y) {} - explicit XMUINT2(_In_reads_(2) const uint32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} +//------------------------------------------------------------------------------ +// 2D Vector; 32 bit signed integer components +struct XMINT2 { + int32_t x; + int32_t y; - #if (__cplusplus >= 202002L) - bool operator == (const XMUINT2&) const = default; - auto operator <=> (const XMUINT2&) const = default; - #endif - }; + XMINT2() = default; - //------------------------------------------------------------------------------ - // 3D Vector; 32 bit floating point components - struct XMFLOAT3 - { - float x; - float y; - float z; + XMINT2(const XMINT2&) = default; + XMINT2& operator=(const XMINT2&) = default; - XMFLOAT3() = default; + XMINT2(XMINT2&&) = default; + XMINT2& operator=(XMINT2&&) = default; - XMFLOAT3(const XMFLOAT3&) = default; - XMFLOAT3& operator=(const XMFLOAT3&) = default; + constexpr XMINT2(int32_t _x, int32_t _y) noexcept : x(_x), y(_y) {} + explicit XMINT2(_In_reads_(2) const int32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} - XMFLOAT3(XMFLOAT3&&) = default; - XMFLOAT3& operator=(XMFLOAT3&&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMINT2&) const = default; + auto operator<=>(const XMINT2&) const = default; +#endif +}; - constexpr XMFLOAT3(float _x, float _y, float _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMFLOAT3(_In_reads_(3) const float* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - }; +// 2D Vector; 32 bit unsigned integer components +struct XMUINT2 { + uint32_t x; + uint32_t y; - // 3D Vector; 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT3A : public XMFLOAT3 - { - using XMFLOAT3::XMFLOAT3; - }; + XMUINT2() = default; - //------------------------------------------------------------------------------ - // 3D Vector; 32 bit signed integer components - struct XMINT3 - { - int32_t x; - int32_t y; - int32_t z; + XMUINT2(const XMUINT2&) = default; + XMUINT2& operator=(const XMUINT2&) = default; - XMINT3() = default; + XMUINT2(XMUINT2&&) = default; + XMUINT2& operator=(XMUINT2&&) = default; - XMINT3(const XMINT3&) = default; - XMINT3& operator=(const XMINT3&) = default; + constexpr XMUINT2(uint32_t _x, uint32_t _y) noexcept : x(_x), y(_y) {} + explicit XMUINT2(_In_reads_(2) const uint32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} - XMINT3(XMINT3&&) = default; - XMINT3& operator=(XMINT3&&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMUINT2&) const = default; + auto operator<=>(const XMUINT2&) const = default; +#endif +}; - constexpr XMINT3(int32_t _x, int32_t _y, int32_t _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMINT3(_In_reads_(3) const int32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} +//------------------------------------------------------------------------------ +// 3D Vector; 32 bit floating point components +struct XMFLOAT3 { + float x; + float y; + float z; - #if (__cplusplus >= 202002L) - bool operator == (const XMINT3&) const = default; - auto operator <=> (const XMINT3&) const = default; - #endif - }; + XMFLOAT3() = default; - // 3D Vector; 32 bit unsigned integer components - struct XMUINT3 - { - uint32_t x; - uint32_t y; - uint32_t z; + XMFLOAT3(const XMFLOAT3&) = default; + XMFLOAT3& operator=(const XMFLOAT3&) = default; - XMUINT3() = default; + XMFLOAT3(XMFLOAT3&&) = default; + XMFLOAT3& operator=(XMFLOAT3&&) = default; - XMUINT3(const XMUINT3&) = default; - XMUINT3& operator=(const XMUINT3&) = default; + constexpr XMFLOAT3(float _x, float _y, float _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMFLOAT3(_In_reads_(3) const float* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} +}; - XMUINT3(XMUINT3&&) = default; - XMUINT3& operator=(XMUINT3&&) = default; +// 3D Vector; 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT3A : public XMFLOAT3 { using XMFLOAT3::XMFLOAT3; }; - constexpr XMUINT3(uint32_t _x, uint32_t _y, uint32_t _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMUINT3(_In_reads_(3) const uint32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} +//------------------------------------------------------------------------------ +// 3D Vector; 32 bit signed integer components +struct XMINT3 { + int32_t x; + int32_t y; + int32_t z; - #if (__cplusplus >= 202002L) - bool operator == (const XMUINT3&) const = default; - auto operator <=> (const XMUINT3&) const = default; - #endif - }; + XMINT3() = default; - //------------------------------------------------------------------------------ - // 4D Vector; 32 bit floating point components - struct XMFLOAT4 - { - float x; - float y; - float z; - float w; + XMINT3(const XMINT3&) = default; + XMINT3& operator=(const XMINT3&) = default; - XMFLOAT4() = default; + XMINT3(XMINT3&&) = default; + XMINT3& operator=(XMINT3&&) = default; - XMFLOAT4(const XMFLOAT4&) = default; - XMFLOAT4& operator=(const XMFLOAT4&) = default; + constexpr XMINT3(int32_t _x, int32_t _y, int32_t _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMINT3(_In_reads_(3) const int32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - XMFLOAT4(XMFLOAT4&&) = default; - XMFLOAT4& operator=(XMFLOAT4&&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMINT3&) const = default; + auto operator<=>(const XMINT3&) const = default; +#endif +}; - constexpr XMFLOAT4(float _x, float _y, float _z, float _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMFLOAT4(_In_reads_(4) const float* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} +// 3D Vector; 32 bit unsigned integer components +struct XMUINT3 { + uint32_t x; + uint32_t y; + uint32_t z; - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT4&) const = default; - auto operator <=> (const XMFLOAT4&) const = default; - #endif - }; + XMUINT3() = default; - // 4D Vector; 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT4A : public XMFLOAT4 - { - using XMFLOAT4::XMFLOAT4; - }; + XMUINT3(const XMUINT3&) = default; + XMUINT3& operator=(const XMUINT3&) = default; - //------------------------------------------------------------------------------ - // 4D Vector; 32 bit signed integer components - struct XMINT4 - { - int32_t x; - int32_t y; - int32_t z; - int32_t w; + XMUINT3(XMUINT3&&) = default; + XMUINT3& operator=(XMUINT3&&) = default; - XMINT4() = default; + constexpr XMUINT3(uint32_t _x, uint32_t _y, uint32_t _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMUINT3(_In_reads_(3) const uint32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - XMINT4(const XMINT4&) = default; - XMINT4& operator=(const XMINT4&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMUINT3&) const = default; + auto operator<=>(const XMUINT3&) const = default; +#endif +}; - XMINT4(XMINT4&&) = default; - XMINT4& operator=(XMINT4&&) = default; +//------------------------------------------------------------------------------ +// 4D Vector; 32 bit floating point components +struct XMFLOAT4 { + float x; + float y; + float z; + float w; - constexpr XMINT4(int32_t _x, int32_t _y, int32_t _z, int32_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMINT4(_In_reads_(4) const int32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMFLOAT4() = default; - #if (__cplusplus >= 202002L) - bool operator == (const XMINT4&) const = default; - auto operator <=> (const XMINT4&) const = default; - #endif - }; + XMFLOAT4(const XMFLOAT4&) = default; + XMFLOAT4& operator=(const XMFLOAT4&) = default; - // 4D Vector; 32 bit unsigned integer components - struct XMUINT4 - { - uint32_t x; - uint32_t y; - uint32_t z; - uint32_t w; + XMFLOAT4(XMFLOAT4&&) = default; + XMFLOAT4& operator=(XMFLOAT4&&) = default; - XMUINT4() = default; + constexpr XMFLOAT4(float _x, float _y, float _z, float _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMFLOAT4(_In_reads_(4) const float* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUINT4(const XMUINT4&) = default; - XMUINT4& operator=(const XMUINT4&) = default; +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT4&) const = default; + auto operator<=>(const XMFLOAT4&) const = default; +#endif +}; - XMUINT4(XMUINT4&&) = default; - XMUINT4& operator=(XMUINT4&&) = default; +// 4D Vector; 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT4A : public XMFLOAT4 { using XMFLOAT4::XMFLOAT4; }; - constexpr XMUINT4(uint32_t _x, uint32_t _y, uint32_t _z, uint32_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUINT4(_In_reads_(4) const uint32_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} +//------------------------------------------------------------------------------ +// 4D Vector; 32 bit signed integer components +struct XMINT4 { + int32_t x; + int32_t y; + int32_t z; + int32_t w; - #if (__cplusplus >= 202002L) - bool operator == (const XMUINT4&) const = default; - auto operator <=> (const XMUINT4&) const = default; - #endif - }; + XMINT4() = default; + + XMINT4(const XMINT4&) = default; + XMINT4& operator=(const XMINT4&) = default; + + XMINT4(XMINT4&&) = default; + XMINT4& operator=(XMINT4&&) = default; + + constexpr XMINT4(int32_t _x, int32_t _y, int32_t _z, int32_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMINT4(_In_reads_(4) const int32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + +#if (__cplusplus >= 202002L) + bool operator==(const XMINT4&) const = default; + auto operator<=>(const XMINT4&) const = default; +#endif +}; + +// 4D Vector; 32 bit unsigned integer components +struct XMUINT4 { + uint32_t x; + uint32_t y; + uint32_t z; + uint32_t w; + + XMUINT4() = default; + + XMUINT4(const XMUINT4&) = default; + XMUINT4& operator=(const XMUINT4&) = default; + + XMUINT4(XMUINT4&&) = default; + XMUINT4& operator=(XMUINT4&&) = default; + + constexpr XMUINT4(uint32_t _x, uint32_t _y, uint32_t _z, + uint32_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUINT4(_In_reads_(4) const uint32_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + +#if (__cplusplus >= 202002L) + bool operator==(const XMUINT4&) const = default; + auto operator<=>(const XMUINT4&) const = default; +#endif +}; #ifdef __clang__ #pragma clang diagnostic push @@ -829,197 +895,229 @@ namespace DirectX #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" #endif - //------------------------------------------------------------------------------ - // 3x3 Matrix: 32 bit floating point components - struct XMFLOAT3X3 - { - union - { - struct - { - float _11, _12, _13; - float _21, _22, _23; - float _31, _32, _33; - }; - float m[3][3]; +//------------------------------------------------------------------------------ +// 3x3 Matrix: 32 bit floating point components +struct XMFLOAT3X3 { + union { + struct { + float _11, _12, _13; + float _21, _22, _23; + float _31, _32, _33; }; - - XMFLOAT3X3() = default; - - XMFLOAT3X3(const XMFLOAT3X3&) = default; - XMFLOAT3X3& operator=(const XMFLOAT3X3&) = default; - - XMFLOAT3X3(XMFLOAT3X3&&) = default; - XMFLOAT3X3& operator=(XMFLOAT3X3&&) = default; - - constexpr XMFLOAT3X3(float m00, float m01, float m02, - float m10, float m11, float m12, - float m20, float m21, float m22) noexcept - : _11(m00), _12(m01), _13(m02), - _21(m10), _22(m11), _23(m12), - _31(m20), _32(m21), _33(m22) - {} - explicit XMFLOAT3X3(_In_reads_(9) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT3X3&) const = default; - auto operator <=> (const XMFLOAT3X3&) const = default; - #endif + float m[3][3]; }; - //------------------------------------------------------------------------------ - // 4x3 Row-major Matrix: 32 bit floating point components - struct XMFLOAT4X3 - { - union - { - struct - { - float _11, _12, _13; - float _21, _22, _23; - float _31, _32, _33; - float _41, _42, _43; - }; - float m[4][3]; - float f[12]; + XMFLOAT3X3() = default; + + XMFLOAT3X3(const XMFLOAT3X3&) = default; + XMFLOAT3X3& operator=(const XMFLOAT3X3&) = default; + + XMFLOAT3X3(XMFLOAT3X3&&) = default; + XMFLOAT3X3& operator=(XMFLOAT3X3&&) = default; + + constexpr XMFLOAT3X3(float m00, float m01, float m02, float m10, float m11, + float m12, float m20, float m21, float m22) noexcept + : _11(m00), + _12(m01), + _13(m02), + _21(m10), + _22(m11), + _23(m12), + _31(m20), + _32(m21), + _33(m22) {} + explicit XMFLOAT3X3(_In_reads_(9) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT3X3&) const = default; + auto operator<=>(const XMFLOAT3X3&) const = default; +#endif +}; + +//------------------------------------------------------------------------------ +// 4x3 Row-major Matrix: 32 bit floating point components +struct XMFLOAT4X3 { + union { + struct { + float _11, _12, _13; + float _21, _22, _23; + float _31, _32, _33; + float _41, _42, _43; }; - - XMFLOAT4X3() = default; - - XMFLOAT4X3(const XMFLOAT4X3&) = default; - XMFLOAT4X3& operator=(const XMFLOAT4X3&) = default; - - XMFLOAT4X3(XMFLOAT4X3&&) = default; - XMFLOAT4X3& operator=(XMFLOAT4X3&&) = default; - - constexpr XMFLOAT4X3(float m00, float m01, float m02, - float m10, float m11, float m12, - float m20, float m21, float m22, - float m30, float m31, float m32) noexcept - : _11(m00), _12(m01), _13(m02), - _21(m10), _22(m11), _23(m12), - _31(m20), _32(m21), _33(m22), - _41(m30), _42(m31), _43(m32) - {} - explicit XMFLOAT4X3(_In_reads_(12) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT4X3&) const = default; - auto operator <=> (const XMFLOAT4X3&) const = default; - #endif + float m[4][3]; + float f[12]; }; - // 4x3 Row-major Matrix: 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT4X3A : public XMFLOAT4X3 - { - using XMFLOAT4X3::XMFLOAT4X3; - }; + XMFLOAT4X3() = default; - //------------------------------------------------------------------------------ - // 3x4 Column-major Matrix: 32 bit floating point components - struct XMFLOAT3X4 - { - union - { - struct - { - float _11, _12, _13, _14; - float _21, _22, _23, _24; - float _31, _32, _33, _34; - }; - float m[3][4]; - float f[12]; + XMFLOAT4X3(const XMFLOAT4X3&) = default; + XMFLOAT4X3& operator=(const XMFLOAT4X3&) = default; + + XMFLOAT4X3(XMFLOAT4X3&&) = default; + XMFLOAT4X3& operator=(XMFLOAT4X3&&) = default; + + constexpr XMFLOAT4X3(float m00, float m01, float m02, float m10, float m11, + float m12, float m20, float m21, float m22, float m30, + float m31, float m32) noexcept + : _11(m00), + _12(m01), + _13(m02), + _21(m10), + _22(m11), + _23(m12), + _31(m20), + _32(m21), + _33(m22), + _41(m30), + _42(m31), + _43(m32) {} + explicit XMFLOAT4X3(_In_reads_(12) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT4X3&) const = default; + auto operator<=>(const XMFLOAT4X3&) const = default; +#endif +}; + +// 4x3 Row-major Matrix: 32 bit floating point components aligned on a 16 byte +// boundary +XM_ALIGNED_STRUCT(16) XMFLOAT4X3A : public XMFLOAT4X3 { + using XMFLOAT4X3::XMFLOAT4X3; +}; + +//------------------------------------------------------------------------------ +// 3x4 Column-major Matrix: 32 bit floating point components +struct XMFLOAT3X4 { + union { + struct { + float _11, _12, _13, _14; + float _21, _22, _23, _24; + float _31, _32, _33, _34; }; - - XMFLOAT3X4() = default; - - XMFLOAT3X4(const XMFLOAT3X4&) = default; - XMFLOAT3X4& operator=(const XMFLOAT3X4&) = default; - - XMFLOAT3X4(XMFLOAT3X4&&) = default; - XMFLOAT3X4& operator=(XMFLOAT3X4&&) = default; - - constexpr XMFLOAT3X4(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23) noexcept - : _11(m00), _12(m01), _13(m02), _14(m03), - _21(m10), _22(m11), _23(m12), _24(m13), - _31(m20), _32(m21), _33(m22), _34(m23) - {} - explicit XMFLOAT3X4(_In_reads_(12) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT3X4&) const = default; - auto operator <=> (const XMFLOAT3X4&) const = default; - #endif + float m[3][4]; + float f[12]; }; - // 3x4 Column-major Matrix: 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT3X4A : public XMFLOAT3X4 - { - using XMFLOAT3X4::XMFLOAT3X4; - }; + XMFLOAT3X4() = default; - //------------------------------------------------------------------------------ - // 4x4 Matrix: 32 bit floating point components - struct XMFLOAT4X4 - { - union - { - struct - { - float _11, _12, _13, _14; - float _21, _22, _23, _24; - float _31, _32, _33, _34; - float _41, _42, _43, _44; - }; - float m[4][4]; + XMFLOAT3X4(const XMFLOAT3X4&) = default; + XMFLOAT3X4& operator=(const XMFLOAT3X4&) = default; + + XMFLOAT3X4(XMFLOAT3X4&&) = default; + XMFLOAT3X4& operator=(XMFLOAT3X4&&) = default; + + constexpr XMFLOAT3X4(float m00, float m01, float m02, float m03, float m10, + float m11, float m12, float m13, float m20, float m21, + float m22, float m23) noexcept + : _11(m00), + _12(m01), + _13(m02), + _14(m03), + _21(m10), + _22(m11), + _23(m12), + _24(m13), + _31(m20), + _32(m21), + _33(m22), + _34(m23) {} + explicit XMFLOAT3X4(_In_reads_(12) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT3X4&) const = default; + auto operator<=>(const XMFLOAT3X4&) const = default; +#endif +}; + +// 3x4 Column-major Matrix: 32 bit floating point components aligned on a 16 +// byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT3X4A : public XMFLOAT3X4 { + using XMFLOAT3X4::XMFLOAT3X4; +}; + +//------------------------------------------------------------------------------ +// 4x4 Matrix: 32 bit floating point components +struct XMFLOAT4X4 { + union { + struct { + float _11, _12, _13, _14; + float _21, _22, _23, _24; + float _31, _32, _33, _34; + float _41, _42, _43, _44; }; - - XMFLOAT4X4() = default; - - XMFLOAT4X4(const XMFLOAT4X4&) = default; - XMFLOAT4X4& operator=(const XMFLOAT4X4&) = default; - - XMFLOAT4X4(XMFLOAT4X4&&) = default; - XMFLOAT4X4& operator=(XMFLOAT4X4&&) = default; - - constexpr XMFLOAT4X4(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23, - float m30, float m31, float m32, float m33) noexcept - : _11(m00), _12(m01), _13(m02), _14(m03), - _21(m10), _22(m11), _23(m12), _24(m13), - _31(m20), _32(m21), _33(m22), _34(m23), - _41(m30), _42(m31), _43(m32), _44(m33) - {} - explicit XMFLOAT4X4(_In_reads_(16) const float* pArray) noexcept; - - float operator() (size_t Row, size_t Column) const noexcept { return m[Row][Column]; } - float& operator() (size_t Row, size_t Column) noexcept { return m[Row][Column]; } - - #if (__cplusplus >= 202002L) - bool operator == (const XMFLOAT4X4&) const = default; - auto operator <=> (const XMFLOAT4X4&) const = default; - #endif + float m[4][4]; }; - // 4x4 Matrix: 32 bit floating point components aligned on a 16 byte boundary - XM_ALIGNED_STRUCT(16) XMFLOAT4X4A : public XMFLOAT4X4 - { - using XMFLOAT4X4::XMFLOAT4X4; - }; + XMFLOAT4X4() = default; - //////////////////////////////////////////////////////////////////////////////// + XMFLOAT4X4(const XMFLOAT4X4&) = default; + XMFLOAT4X4& operator=(const XMFLOAT4X4&) = default; + + XMFLOAT4X4(XMFLOAT4X4&&) = default; + XMFLOAT4X4& operator=(XMFLOAT4X4&&) = default; + + constexpr XMFLOAT4X4(float m00, float m01, float m02, float m03, float m10, + float m11, float m12, float m13, float m20, float m21, + float m22, float m23, float m30, float m31, float m32, + float m33) noexcept + : _11(m00), + _12(m01), + _13(m02), + _14(m03), + _21(m10), + _22(m11), + _23(m12), + _24(m13), + _31(m20), + _32(m21), + _33(m22), + _34(m23), + _41(m30), + _42(m31), + _43(m32), + _44(m33) {} + explicit XMFLOAT4X4(_In_reads_(16) const float* pArray) noexcept; + + float operator()(size_t Row, size_t Column) const noexcept { + return m[Row][Column]; + } + float& operator()(size_t Row, size_t Column) noexcept { + return m[Row][Column]; + } + +#if (__cplusplus >= 202002L) + bool operator==(const XMFLOAT4X4&) const = default; + auto operator<=>(const XMFLOAT4X4&) const = default; +#endif +}; + +// 4x4 Matrix: 32 bit floating point components aligned on a 16 byte boundary +XM_ALIGNED_STRUCT(16) XMFLOAT4X4A : public XMFLOAT4X4 { + using XMFLOAT4X4::XMFLOAT4X4; +}; + +//////////////////////////////////////////////////////////////////////////////// #ifdef __clang__ #pragma clang diagnostic pop @@ -1037,10 +1135,14 @@ namespace DirectX * ****************************************************************************/ - XMVECTOR XM_CALLCONV XMConvertVectorIntToFloat(FXMVECTOR VInt, uint32_t DivExponent) noexcept; - XMVECTOR XM_CALLCONV XMConvertVectorFloatToInt(FXMVECTOR VFloat, uint32_t MulExponent) noexcept; - XMVECTOR XM_CALLCONV XMConvertVectorUIntToFloat(FXMVECTOR VUInt, uint32_t DivExponent) noexcept; - XMVECTOR XM_CALLCONV XMConvertVectorFloatToUInt(FXMVECTOR VFloat, uint32_t MulExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorIntToFloat(FXMVECTOR VInt, + uint32_t DivExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorFloatToInt(FXMVECTOR VFloat, + uint32_t MulExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorUIntToFloat(FXMVECTOR VUInt, + uint32_t DivExponent) noexcept; +XMVECTOR XM_CALLCONV XMConvertVectorFloatToUInt(FXMVECTOR VFloat, + uint32_t MulExponent) noexcept; #if defined(__XNAMATH_H__) && defined(XMVectorSetBinaryConstant) #undef XMVectorSetBinaryConstant @@ -1048,169 +1150,232 @@ namespace DirectX #undef XMVectorSplatConstantInt #endif - XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, uint32_t C2, uint32_t C3) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatConstant(int32_t IntConstant, uint32_t DivExponent) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatConstantInt(int32_t IntConstant) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, + uint32_t C2, + uint32_t C3) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatConstant(int32_t IntConstant, + uint32_t DivExponent) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatConstantInt(int32_t IntConstant) noexcept; - /**************************************************************************** - * - * Load operations - * - ****************************************************************************/ +/**************************************************************************** + * + * Load operations + * + ****************************************************************************/ - XMVECTOR XM_CALLCONV XMLoadInt(_In_ const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat(_In_ const float* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt(_In_ const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat(_In_ const float* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt2(_In_reads_(2) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt2A(_In_reads_(2) const uint32_t* PSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat2(_In_ const XMFLOAT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat2A(_In_ const XMFLOAT2A* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadSInt2(_In_ const XMINT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUInt2(_In_ const XMUINT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt2(_In_reads_(2) const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt2A(_In_reads_(2) + const uint32_t* PSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat2(_In_ const XMFLOAT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat2A(_In_ const XMFLOAT2A* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadSInt2(_In_ const XMINT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUInt2(_In_ const XMUINT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt3(_In_reads_(3) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt3A(_In_reads_(3) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3(_In_ const XMFLOAT3* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3A(_In_ const XMFLOAT3A* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadSInt3(_In_ const XMINT3* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUInt3(_In_ const XMUINT3* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt3(_In_reads_(3) const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt3A(_In_reads_(3) + const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3(_In_ const XMFLOAT3* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3A(_In_ const XMFLOAT3A* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadSInt3(_In_ const XMINT3* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUInt3(_In_ const XMUINT3* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt4(_In_reads_(4) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadInt4A(_In_reads_(4) const uint32_t* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat4(_In_ const XMFLOAT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat4A(_In_ const XMFLOAT4A* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadSInt4(_In_ const XMINT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUInt4(_In_ const XMUINT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt4(_In_reads_(4) const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadInt4A(_In_reads_(4) + const uint32_t* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat4(_In_ const XMFLOAT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat4A(_In_ const XMFLOAT4A* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadSInt4(_In_ const XMINT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUInt4(_In_ const XMUINT4* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat3x3(_In_ const XMFLOAT3X3* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x3(_In_ const XMFLOAT4X3* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x3A(_In_ const XMFLOAT4X3A* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat3x4(_In_ const XMFLOAT3X4* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat3x4A(_In_ const XMFLOAT3X4A* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x4(_In_ const XMFLOAT4X4* pSource) noexcept; - XMMATRIX XM_CALLCONV XMLoadFloat4x4A(_In_ const XMFLOAT4X4A* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat3x3(_In_ const XMFLOAT3X3* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x3(_In_ const XMFLOAT4X3* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x3A(_In_ const XMFLOAT4X3A* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat3x4(_In_ const XMFLOAT3X4* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat3x4A(_In_ const XMFLOAT3X4A* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x4(_In_ const XMFLOAT4X4* pSource) noexcept; +XMMATRIX XM_CALLCONV XMLoadFloat4x4A(_In_ const XMFLOAT4X4A* pSource) noexcept; - /**************************************************************************** - * - * Store operations - * - ****************************************************************************/ +/**************************************************************************** + * + * Store operations + * + ****************************************************************************/ - void XM_CALLCONV XMStoreInt(_Out_ uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat(_Out_ float* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt(_Out_ uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat(_Out_ float* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt2(_Out_writes_(2) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt2A(_Out_writes_(2) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat2(_Out_ XMFLOAT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat2A(_Out_ XMFLOAT2A* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreSInt2(_Out_ XMINT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUInt2(_Out_ XMUINT2* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt2(_Out_writes_(2) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt2A(_Out_writes_(2) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat2(_Out_ XMFLOAT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat2A(_Out_ XMFLOAT2A* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreSInt2(_Out_ XMINT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUInt2(_Out_ XMUINT2* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt3(_Out_writes_(3) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt3A(_Out_writes_(3) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3(_Out_ XMFLOAT3* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3A(_Out_ XMFLOAT3A* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreSInt3(_Out_ XMINT3* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUInt3(_Out_ XMUINT3* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt3(_Out_writes_(3) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt3A(_Out_writes_(3) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3(_Out_ XMFLOAT3* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3A(_Out_ XMFLOAT3A* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreSInt3(_Out_ XMINT3* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUInt3(_Out_ XMUINT3* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt4(_Out_writes_(4) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreInt4A(_Out_writes_(4) uint32_t* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat4(_Out_ XMFLOAT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat4A(_Out_ XMFLOAT4A* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreSInt4(_Out_ XMINT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUInt4(_Out_ XMUINT4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt4(_Out_writes_(4) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreInt4A(_Out_writes_(4) uint32_t* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat4(_Out_ XMFLOAT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat4A(_Out_ XMFLOAT4A* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreSInt4(_Out_ XMINT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUInt4(_Out_ XMUINT4* pDestination, + _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3x3(_Out_ XMFLOAT3X3* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x3(_Out_ XMFLOAT4X3* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x3A(_Out_ XMFLOAT4X3A* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat3x4(_Out_ XMFLOAT3X4* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat3x4A(_Out_ XMFLOAT3X4A* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x4(_Out_ XMFLOAT4X4* pDestination, _In_ FXMMATRIX M) noexcept; - void XM_CALLCONV XMStoreFloat4x4A(_Out_ XMFLOAT4X4A* pDestination, _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat3x3(_Out_ XMFLOAT3X3* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x3(_Out_ XMFLOAT4X3* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x3A(_Out_ XMFLOAT4X3A* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat3x4(_Out_ XMFLOAT3X4* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat3x4A(_Out_ XMFLOAT3X4A* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x4(_Out_ XMFLOAT4X4* pDestination, + _In_ FXMMATRIX M) noexcept; +void XM_CALLCONV XMStoreFloat4x4A(_Out_ XMFLOAT4X4A* pDestination, + _In_ FXMMATRIX M) noexcept; - /**************************************************************************** - * - * General vector operations - * - ****************************************************************************/ +/**************************************************************************** + * + * General vector operations + * + ****************************************************************************/ - XMVECTOR XM_CALLCONV XMVectorZero() noexcept; - XMVECTOR XM_CALLCONV XMVectorSet(float x, float y, float z, float w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetInt(uint32_t x, uint32_t y, uint32_t z, uint32_t w) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicate(float Value) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicatePtr(_In_ const float* pValue) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicateInt(uint32_t Value) noexcept; - XMVECTOR XM_CALLCONV XMVectorReplicateIntPtr(_In_ const uint32_t* pValue) noexcept; - XMVECTOR XM_CALLCONV XMVectorTrueInt() noexcept; - XMVECTOR XM_CALLCONV XMVectorFalseInt() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatX(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatY(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatZ(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatW(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatOne() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatInfinity() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatQNaN() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatEpsilon() noexcept; - XMVECTOR XM_CALLCONV XMVectorSplatSignMask() noexcept; +XMVECTOR XM_CALLCONV XMVectorZero() noexcept; +XMVECTOR XM_CALLCONV XMVectorSet(float x, float y, float z, float w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetInt(uint32_t x, uint32_t y, uint32_t z, + uint32_t w) noexcept; +XMVECTOR XM_CALLCONV XMVectorReplicate(float Value) noexcept; +XMVECTOR XM_CALLCONV XMVectorReplicatePtr(_In_ const float* pValue) noexcept; +XMVECTOR XM_CALLCONV XMVectorReplicateInt(uint32_t Value) noexcept; +XMVECTOR XM_CALLCONV +XMVectorReplicateIntPtr(_In_ const uint32_t* pValue) noexcept; +XMVECTOR XM_CALLCONV XMVectorTrueInt() noexcept; +XMVECTOR XM_CALLCONV XMVectorFalseInt() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatX(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatY(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatZ(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatW(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatOne() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatInfinity() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatQNaN() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatEpsilon() noexcept; +XMVECTOR XM_CALLCONV XMVectorSplatSignMask() noexcept; - float XM_CALLCONV XMVectorGetByIndex(FXMVECTOR V, size_t i) noexcept; - float XM_CALLCONV XMVectorGetX(FXMVECTOR V) noexcept; - float XM_CALLCONV XMVectorGetY(FXMVECTOR V) noexcept; - float XM_CALLCONV XMVectorGetZ(FXMVECTOR V) noexcept; - float XM_CALLCONV XMVectorGetW(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetByIndex(FXMVECTOR V, size_t i) noexcept; +float XM_CALLCONV XMVectorGetX(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetY(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetZ(FXMVECTOR V) noexcept; +float XM_CALLCONV XMVectorGetW(FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetByIndexPtr(_Out_ float* f, _In_ FXMVECTOR V, _In_ size_t i) noexcept; - void XM_CALLCONV XMVectorGetXPtr(_Out_ float* x, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetYPtr(_Out_ float* y, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetZPtr(_Out_ float* z, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetWPtr(_Out_ float* w, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetByIndexPtr(_Out_ float* f, _In_ FXMVECTOR V, + _In_ size_t i) noexcept; +void XM_CALLCONV XMVectorGetXPtr(_Out_ float* x, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetYPtr(_Out_ float* y, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetZPtr(_Out_ float* z, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetWPtr(_Out_ float* w, _In_ FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntByIndex(FXMVECTOR V, size_t i) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntX(FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntY(FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntZ(FXMVECTOR V) noexcept; - uint32_t XM_CALLCONV XMVectorGetIntW(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntByIndex(FXMVECTOR V, size_t i) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntX(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntY(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntZ(FXMVECTOR V) noexcept; +uint32_t XM_CALLCONV XMVectorGetIntW(FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntByIndexPtr(_Out_ uint32_t* x, _In_ FXMVECTOR V, _In_ size_t i) noexcept; - void XM_CALLCONV XMVectorGetIntXPtr(_Out_ uint32_t* x, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntYPtr(_Out_ uint32_t* y, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntZPtr(_Out_ uint32_t* z, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorGetIntWPtr(_Out_ uint32_t* w, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntByIndexPtr(_Out_ uint32_t* x, _In_ FXMVECTOR V, + _In_ size_t i) noexcept; +void XM_CALLCONV XMVectorGetIntXPtr(_Out_ uint32_t* x, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntYPtr(_Out_ uint32_t* y, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntZPtr(_Out_ uint32_t* z, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorGetIntWPtr(_Out_ uint32_t* w, + _In_ FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetByIndex(FXMVECTOR V, float f, size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetX(FXMVECTOR V, float x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetY(FXMVECTOR V, float y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetZ(FXMVECTOR V, float z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetW(FXMVECTOR V, float w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetByIndex(FXMVECTOR V, float f, + size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetX(FXMVECTOR V, float x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetY(FXMVECTOR V, float y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetZ(FXMVECTOR V, float z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetW(FXMVECTOR V, float w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetByIndexPtr(_In_ FXMVECTOR V, _In_ const float* f, _In_ size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetXPtr(_In_ FXMVECTOR V, _In_ const float* x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetYPtr(_In_ FXMVECTOR V, _In_ const float* y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetZPtr(_In_ FXMVECTOR V, _In_ const float* z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetWPtr(_In_ FXMVECTOR V, _In_ const float* w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetByIndexPtr(_In_ FXMVECTOR V, + _In_ const float* f, + _In_ size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetXPtr(_In_ FXMVECTOR V, + _In_ const float* x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetYPtr(_In_ FXMVECTOR V, + _In_ const float* y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetZPtr(_In_ FXMVECTOR V, + _In_ const float* z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetWPtr(_In_ FXMVECTOR V, + _In_ const float* w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntByIndex(FXMVECTOR V, uint32_t x, size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntX(FXMVECTOR V, uint32_t x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntY(FXMVECTOR V, uint32_t y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntZ(FXMVECTOR V, uint32_t z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntW(FXMVECTOR V, uint32_t w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntByIndex(FXMVECTOR V, uint32_t x, + size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntX(FXMVECTOR V, uint32_t x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntY(FXMVECTOR V, uint32_t y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntZ(FXMVECTOR V, uint32_t z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntW(FXMVECTOR V, uint32_t w) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntByIndexPtr(_In_ FXMVECTOR V, _In_ const uint32_t* x, _In_ size_t i) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntXPtr(_In_ FXMVECTOR V, _In_ const uint32_t* x) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntYPtr(_In_ FXMVECTOR V, _In_ const uint32_t* y) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntZPtr(_In_ FXMVECTOR V, _In_ const uint32_t* z) noexcept; - XMVECTOR XM_CALLCONV XMVectorSetIntWPtr(_In_ FXMVECTOR V, _In_ const uint32_t* w) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntByIndexPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* x, + _In_ size_t i) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntXPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* x) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntYPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* y) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntZPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* z) noexcept; +XMVECTOR XM_CALLCONV XMVectorSetIntWPtr(_In_ FXMVECTOR V, + _In_ const uint32_t* w) noexcept; #if defined(__XNAMATH_H__) && defined(XMVectorSwizzle) #undef XMVectorSwizzle #endif - XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V, uint32_t E0, uint32_t E1, uint32_t E2, uint32_t E3) noexcept; - XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, FXMVECTOR V2, uint32_t PermuteX, uint32_t PermuteY, uint32_t PermuteZ, uint32_t PermuteW) noexcept; - XMVECTOR XM_CALLCONV XMVectorSelectControl(uint32_t VectorIndex0, uint32_t VectorIndex1, uint32_t VectorIndex2, uint32_t VectorIndex3) noexcept; - XMVECTOR XM_CALLCONV XMVectorSelect(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Control) noexcept; - XMVECTOR XM_CALLCONV XMVectorMergeXY(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMergeZW(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V, uint32_t E0, uint32_t E1, + uint32_t E2, uint32_t E3) noexcept; +XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, FXMVECTOR V2, + uint32_t PermuteX, uint32_t PermuteY, + uint32_t PermuteZ, + uint32_t PermuteW) noexcept; +XMVECTOR XM_CALLCONV XMVectorSelectControl(uint32_t VectorIndex0, + uint32_t VectorIndex1, + uint32_t VectorIndex2, + uint32_t VectorIndex3) noexcept; +XMVECTOR XM_CALLCONV XMVectorSelect(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Control) noexcept; +XMVECTOR XM_CALLCONV XMVectorMergeXY(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMergeZW(FXMVECTOR V1, FXMVECTOR V2) noexcept; #if defined(__XNAMATH_H__) && defined(XMVectorShiftLeft) #undef XMVectorShiftLeft @@ -1219,791 +1384,1308 @@ namespace DirectX #undef XMVectorInsert #endif - XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, FXMVECTOR V2, uint32_t Elements) noexcept; - XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V, uint32_t Elements) noexcept; - XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V, uint32_t Elements) noexcept; - XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, FXMVECTOR VS, uint32_t VSLeftRotateElements, - uint32_t Select0, uint32_t Select1, uint32_t Select2, uint32_t Select3) noexcept; - - XMVECTOR XM_CALLCONV XMVectorEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorEqualR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorEqualIntR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - XMVECTOR XM_CALLCONV XMVectorNotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreaterR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorGreaterOrEqualR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorLess(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorLessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorInBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - XMVECTOR XM_CALLCONV XMVectorInBoundsR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, _In_ FXMVECTOR Bounds) noexcept; - - XMVECTOR XM_CALLCONV XMVectorIsNaN(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorIsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVectorMin(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMax(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorRound(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTruncate(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorFloor(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCeiling(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorClamp(FXMVECTOR V, FXMVECTOR Min, FXMVECTOR Max) noexcept; - XMVECTOR XM_CALLCONV XMVectorSaturate(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVectorAndInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorAndCInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorOrInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorXorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - - XMVECTOR XM_CALLCONV XMVectorNegate(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorAdd(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorSum(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorAddAngles(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorSubtract(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorSubtractAngles(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMultiply(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorMultiplyAdd(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR V3) noexcept; - XMVECTOR XM_CALLCONV XMVectorDivide(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorNegativeMultiplySubtract(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR V3) noexcept; - XMVECTOR XM_CALLCONV XMVectorScale(FXMVECTOR V, float ScaleFactor) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocalEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSqrtEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSqrt(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocalSqrtEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorReciprocalSqrt(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExp2(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExp10(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExpE(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorExp(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLog2(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLog10(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLogE(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorLog(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorPow(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorAbs(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorMod(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVectorModAngles(FXMVECTOR Angles) noexcept; - XMVECTOR XM_CALLCONV XMVectorSin(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSinEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCos(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCosEst(FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorSinCos(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMVectorSinCosEst(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, _In_ FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTan(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTanEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorSinH(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorCosH(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorTanH(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorASin(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorASinEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorACos(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorACosEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorATan(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorATanEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVectorATan2(FXMVECTOR Y, FXMVECTOR X) noexcept; - XMVECTOR XM_CALLCONV XMVectorATan2Est(FXMVECTOR Y, FXMVECTOR X) noexcept; - XMVECTOR XM_CALLCONV XMVectorLerp(FXMVECTOR V0, FXMVECTOR V1, float t) noexcept; - XMVECTOR XM_CALLCONV XMVectorLerpV(FXMVECTOR V0, FXMVECTOR V1, FXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMVectorHermite(FXMVECTOR Position0, FXMVECTOR Tangent0, FXMVECTOR Position1, GXMVECTOR Tangent1, float t) noexcept; - XMVECTOR XM_CALLCONV XMVectorHermiteV(FXMVECTOR Position0, FXMVECTOR Tangent0, FXMVECTOR Position1, GXMVECTOR Tangent1, HXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMVectorCatmullRom(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, GXMVECTOR Position3, float t) noexcept; - XMVECTOR XM_CALLCONV XMVectorCatmullRomV(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, GXMVECTOR Position3, HXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMVectorBaryCentric(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, float f, float g) noexcept; - XMVECTOR XM_CALLCONV XMVectorBaryCentricV(FXMVECTOR Position0, FXMVECTOR Position1, FXMVECTOR Position2, GXMVECTOR F, HXMVECTOR G) noexcept; - - /**************************************************************************** - * - * 2D vector operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMVector2Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2NearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMVector2NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector2GreaterOrEqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector2InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - - bool XM_CALLCONV XMVector2IsNaN(FXMVECTOR V) noexcept; - bool XM_CALLCONV XMVector2IsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVector2Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector2Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector2LengthSq(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2ReciprocalLengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2ReciprocalLength(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2LengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2Length(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2NormalizeEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2Normalize(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2ClampLength(FXMVECTOR V, float LengthMin, float LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector2ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, FXMVECTOR LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector2Reflect(FXMVECTOR Incident, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector2Refract(FXMVECTOR Incident, FXMVECTOR Normal, float RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector2RefractV(FXMVECTOR Incident, FXMVECTOR Normal, FXMVECTOR RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector2Orthogonal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormalsEst(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormals(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector2AngleBetweenVectors(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector2LinePointDistance(FXMVECTOR LinePoint1, FXMVECTOR LinePoint2, FXMVECTOR Point) noexcept; - XMVECTOR XM_CALLCONV XMVector2IntersectLine(FXMVECTOR Line1Point1, FXMVECTOR Line1Point2, FXMVECTOR Line2Point1, GXMVECTOR Line2Point2) noexcept; - XMVECTOR XM_CALLCONV XMVector2Transform(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT4* XM_CALLCONV XMVector2TransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) const XMFLOAT2* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector2TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT2* XM_CALLCONV XMVector2TransformCoordStream(_Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) XMFLOAT2* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) const XMFLOAT2* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector2TransformNormal(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT2* XM_CALLCONV XMVector2TransformNormalStream(_Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) XMFLOAT2* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) const XMFLOAT2* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - - /**************************************************************************** - * - * 3D vector operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMVector3Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3NearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMVector3NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector3GreaterOrEqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector3InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - - bool XM_CALLCONV XMVector3IsNaN(FXMVECTOR V) noexcept; - bool XM_CALLCONV XMVector3IsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVector3Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector3Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector3LengthSq(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3ReciprocalLengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3ReciprocalLength(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3LengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3Length(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3NormalizeEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3Normalize(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3ClampLength(FXMVECTOR V, float LengthMin, float LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector3ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, FXMVECTOR LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector3Reflect(FXMVECTOR Incident, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector3Refract(FXMVECTOR Incident, FXMVECTOR Normal, float RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector3RefractV(FXMVECTOR Incident, FXMVECTOR Normal, FXMVECTOR RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector3Orthogonal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormalsEst(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormals(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector3AngleBetweenVectors(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector3LinePointDistance(FXMVECTOR LinePoint1, FXMVECTOR LinePoint2, FXMVECTOR Point) noexcept; - void XM_CALLCONV XMVector3ComponentsFromNormal(_Out_ XMVECTOR* pParallel, _Out_ XMVECTOR* pPerpendicular, _In_ FXMVECTOR V, _In_ FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector3Rotate(FXMVECTOR V, FXMVECTOR RotationQuaternion) noexcept; - XMVECTOR XM_CALLCONV XMVector3InverseRotate(FXMVECTOR V, FXMVECTOR RotationQuaternion) noexcept; - XMVECTOR XM_CALLCONV XMVector3Transform(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT4* XM_CALLCONV XMVector3TransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector3TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3TransformCoordStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector3TransformNormal(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3TransformNormalStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - XMVECTOR XM_CALLCONV XMVector3Project(FXMVECTOR V, float ViewportX, float ViewportY, float ViewportWidth, float ViewportHeight, float ViewportMinZ, float ViewportMaxZ, - FXMMATRIX Projection, CXMMATRIX View, CXMMATRIX World) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3ProjectStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, - _In_ float ViewportX, _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, _In_ float ViewportMinZ, _In_ float ViewportMaxZ, - _In_ FXMMATRIX Projection, _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; - XMVECTOR XM_CALLCONV XMVector3Unproject(FXMVECTOR V, float ViewportX, float ViewportY, float ViewportWidth, float ViewportHeight, float ViewportMinZ, float ViewportMaxZ, - FXMMATRIX Projection, CXMMATRIX View, CXMMATRIX World) noexcept; - XMFLOAT3* XM_CALLCONV XMVector3UnprojectStream(_Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) XMFLOAT3* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) const XMFLOAT3* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, - _In_ float ViewportX, _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, _In_ float ViewportMinZ, _In_ float ViewportMaxZ, - _In_ FXMMATRIX Projection, _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; - - /**************************************************************************** - * - * 4D vector operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMVector4Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4NearEqual(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMVector4NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - uint32_t XM_CALLCONV XMVector4GreaterOrEqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; - bool XM_CALLCONV XMVector4InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; - - bool XM_CALLCONV XMVector4IsNaN(FXMVECTOR V) noexcept; - bool XM_CALLCONV XMVector4IsInfinite(FXMVECTOR V) noexcept; - - XMVECTOR XM_CALLCONV XMVector4Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector4Cross(FXMVECTOR V1, FXMVECTOR V2, FXMVECTOR V3) noexcept; - XMVECTOR XM_CALLCONV XMVector4LengthSq(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4ReciprocalLengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4ReciprocalLength(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4LengthEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4Length(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4NormalizeEst(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4Normalize(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4ClampLength(FXMVECTOR V, float LengthMin, float LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector4ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, FXMVECTOR LengthMax) noexcept; - XMVECTOR XM_CALLCONV XMVector4Reflect(FXMVECTOR Incident, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMVector4Refract(FXMVECTOR Incident, FXMVECTOR Normal, float RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector4RefractV(FXMVECTOR Incident, FXMVECTOR Normal, FXMVECTOR RefractionIndex) noexcept; - XMVECTOR XM_CALLCONV XMVector4Orthogonal(FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormalsEst(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormals(FXMVECTOR N1, FXMVECTOR N2) noexcept; - XMVECTOR XM_CALLCONV XMVector4AngleBetweenVectors(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMVector4Transform(FXMVECTOR V, FXMMATRIX M) noexcept; - XMFLOAT4* XM_CALLCONV XMVector4TransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (VectorCount - 1)) const XMFLOAT4* pInputStream, - _In_ size_t InputStride, _In_ size_t VectorCount, _In_ FXMMATRIX M) noexcept; - - /**************************************************************************** - * - * Matrix operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMMatrixIsNaN(FXMMATRIX M) noexcept; - bool XM_CALLCONV XMMatrixIsInfinite(FXMMATRIX M) noexcept; - bool XM_CALLCONV XMMatrixIsIdentity(FXMMATRIX M) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixMultiply(FXMMATRIX M1, CXMMATRIX M2) noexcept; - XMMATRIX XM_CALLCONV XMMatrixMultiplyTranspose(FXMMATRIX M1, CXMMATRIX M2) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTranspose(FXMMATRIX M) noexcept; - XMMATRIX XM_CALLCONV XMMatrixInverse(_Out_opt_ XMVECTOR* pDeterminant, _In_ FXMMATRIX M) noexcept; - XMMATRIX XM_CALLCONV XMMatrixVectorTensorProduct(FXMVECTOR V1, FXMVECTOR V2) noexcept; - XMVECTOR XM_CALLCONV XMMatrixDeterminant(FXMMATRIX M) noexcept; - - _Success_(return) - bool XM_CALLCONV XMMatrixDecompose(_Out_ XMVECTOR* outScale, _Out_ XMVECTOR* outRotQuat, _Out_ XMVECTOR* outTrans, _In_ FXMMATRIX M) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixIdentity() noexcept; - XMMATRIX XM_CALLCONV XMMatrixSet(float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23, - float m30, float m31, float m32, float m33) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTranslation(float OffsetX, float OffsetY, float OffsetZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTranslationFromVector(FXMVECTOR Offset) noexcept; - XMMATRIX XM_CALLCONV XMMatrixScaling(float ScaleX, float ScaleY, float ScaleZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixScalingFromVector(FXMVECTOR Scale) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationX(float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationY(float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationZ(float Angle) noexcept; - - // Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) - XMMATRIX XM_CALLCONV XMMatrixRotationRollPitchYaw(float Pitch, float Yaw, float Roll) noexcept; - - // Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis (Angles.z) - XMMATRIX XM_CALLCONV XMMatrixRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixRotationNormal(FXMVECTOR NormalAxis, float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationAxis(FXMVECTOR Axis, float Angle) noexcept; - XMMATRIX XM_CALLCONV XMMatrixRotationQuaternion(FXMVECTOR Quaternion) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTransformation2D(FXMVECTOR ScalingOrigin, float ScalingOrientation, FXMVECTOR Scaling, - FXMVECTOR RotationOrigin, float Rotation, GXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixTransformation(FXMVECTOR ScalingOrigin, FXMVECTOR ScalingOrientationQuaternion, FXMVECTOR Scaling, - GXMVECTOR RotationOrigin, HXMVECTOR RotationQuaternion, HXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixAffineTransformation2D(FXMVECTOR Scaling, FXMVECTOR RotationOrigin, float Rotation, FXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixAffineTransformation(FXMVECTOR Scaling, FXMVECTOR RotationOrigin, FXMVECTOR RotationQuaternion, GXMVECTOR Translation) noexcept; - XMMATRIX XM_CALLCONV XMMatrixReflect(FXMVECTOR ReflectionPlane) noexcept; - XMMATRIX XM_CALLCONV XMMatrixShadow(FXMVECTOR ShadowPlane, FXMVECTOR LightPosition) noexcept; - - XMMATRIX XM_CALLCONV XMMatrixLookAtLH(FXMVECTOR EyePosition, FXMVECTOR FocusPosition, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixLookAtRH(FXMVECTOR EyePosition, FXMVECTOR FocusPosition, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixLookToLH(FXMVECTOR EyePosition, FXMVECTOR EyeDirection, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixLookToRH(FXMVECTOR EyePosition, FXMVECTOR EyeDirection, FXMVECTOR UpDirection) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveLH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveRH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovLH(float FovAngleY, float AspectRatio, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovRH(float FovAngleY, float AspectRatio, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterLH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterRH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicLH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicRH(float ViewWidth, float ViewHeight, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterLH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterRH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ, float FarZ) noexcept; - - - /**************************************************************************** - * - * Quaternion operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMQuaternionEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - bool XM_CALLCONV XMQuaternionNotEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - - bool XM_CALLCONV XMQuaternionIsNaN(FXMVECTOR Q) noexcept; - bool XM_CALLCONV XMQuaternionIsInfinite(FXMVECTOR Q) noexcept; - bool XM_CALLCONV XMQuaternionIsIdentity(FXMVECTOR Q) noexcept; - - XMVECTOR XM_CALLCONV XMQuaternionDot(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionMultiply(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionLengthSq(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionReciprocalLength(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionLength(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionNormalizeEst(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionNormalize(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionConjugate(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionInverse(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionLn(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionExp(FXMVECTOR Q) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSlerp(FXMVECTOR Q0, FXMVECTOR Q1, float t) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSlerpV(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR T) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSquad(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, GXMVECTOR Q3, float t) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionSquadV(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, GXMVECTOR Q3, HXMVECTOR T) noexcept; - void XM_CALLCONV XMQuaternionSquadSetup(_Out_ XMVECTOR* pA, _Out_ XMVECTOR* pB, _Out_ XMVECTOR* pC, _In_ FXMVECTOR Q0, _In_ FXMVECTOR Q1, _In_ FXMVECTOR Q2, _In_ GXMVECTOR Q3) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionBaryCentric(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, float f, float g) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionBaryCentricV(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, GXMVECTOR F, HXMVECTOR G) noexcept; - - XMVECTOR XM_CALLCONV XMQuaternionIdentity() noexcept; - - // Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) - XMVECTOR XM_CALLCONV XMQuaternionRotationRollPitchYaw(float Pitch, float Yaw, float Roll) noexcept; - - // Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis (Angles.z) - XMVECTOR XM_CALLCONV XMQuaternionRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; - - XMVECTOR XM_CALLCONV XMQuaternionRotationNormal(FXMVECTOR NormalAxis, float Angle) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionRotationAxis(FXMVECTOR Axis, float Angle) noexcept; - XMVECTOR XM_CALLCONV XMQuaternionRotationMatrix(FXMMATRIX M) noexcept; - - void XM_CALLCONV XMQuaternionToAxisAngle(_Out_ XMVECTOR* pAxis, _Out_ float* pAngle, _In_ FXMVECTOR Q) noexcept; - - /**************************************************************************** - * - * Plane operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMPlaneEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; - bool XM_CALLCONV XMPlaneNearEqual(FXMVECTOR P1, FXMVECTOR P2, FXMVECTOR Epsilon) noexcept; - bool XM_CALLCONV XMPlaneNotEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; - - bool XM_CALLCONV XMPlaneIsNaN(FXMVECTOR P) noexcept; - bool XM_CALLCONV XMPlaneIsInfinite(FXMVECTOR P) noexcept; - - XMVECTOR XM_CALLCONV XMPlaneDot(FXMVECTOR P, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMPlaneDotCoord(FXMVECTOR P, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMPlaneDotNormal(FXMVECTOR P, FXMVECTOR V) noexcept; - XMVECTOR XM_CALLCONV XMPlaneNormalizeEst(FXMVECTOR P) noexcept; - XMVECTOR XM_CALLCONV XMPlaneNormalize(FXMVECTOR P) noexcept; - XMVECTOR XM_CALLCONV XMPlaneIntersectLine(FXMVECTOR P, FXMVECTOR LinePoint1, FXMVECTOR LinePoint2) noexcept; - void XM_CALLCONV XMPlaneIntersectPlane(_Out_ XMVECTOR* pLinePoint1, _Out_ XMVECTOR* pLinePoint2, _In_ FXMVECTOR P1, _In_ FXMVECTOR P2) noexcept; - - // Transforms a plane given an inverse transpose matrix - XMVECTOR XM_CALLCONV XMPlaneTransform(FXMVECTOR P, FXMMATRIX ITM) noexcept; - - // Transforms an array of planes given an inverse transpose matrix - XMFLOAT4* XM_CALLCONV XMPlaneTransformStream(_Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (PlaneCount - 1)) XMFLOAT4* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (PlaneCount - 1)) const XMFLOAT4* pInputStream, - _In_ size_t InputStride, _In_ size_t PlaneCount, _In_ FXMMATRIX ITM) noexcept; - - XMVECTOR XM_CALLCONV XMPlaneFromPointNormal(FXMVECTOR Point, FXMVECTOR Normal) noexcept; - XMVECTOR XM_CALLCONV XMPlaneFromPoints(FXMVECTOR Point1, FXMVECTOR Point2, FXMVECTOR Point3) noexcept; - - /**************************************************************************** - * - * Color operations - * - ****************************************************************************/ - - bool XM_CALLCONV XMColorEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorNotEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorGreater(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorGreaterOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorLess(FXMVECTOR C1, FXMVECTOR C2) noexcept; - bool XM_CALLCONV XMColorLessOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; - - bool XM_CALLCONV XMColorIsNaN(FXMVECTOR C) noexcept; - bool XM_CALLCONV XMColorIsInfinite(FXMVECTOR C) noexcept; - - XMVECTOR XM_CALLCONV XMColorNegative(FXMVECTOR C) noexcept; - XMVECTOR XM_CALLCONV XMColorModulate(FXMVECTOR C1, FXMVECTOR C2) noexcept; - XMVECTOR XM_CALLCONV XMColorAdjustSaturation(FXMVECTOR C, float Saturation) noexcept; - XMVECTOR XM_CALLCONV XMColorAdjustContrast(FXMVECTOR C, float Contrast) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToHSL(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorHSLToRGB(FXMVECTOR hsl) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToHSV(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorHSVToRGB(FXMVECTOR hsv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToYUV(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorYUVToRGB(FXMVECTOR yuv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToYUV_HD(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorYUVToRGB_HD(FXMVECTOR yuv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToYUV_UHD(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorYUVToRGB_UHD(FXMVECTOR yuv) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToXYZ(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorXYZToRGB(FXMVECTOR xyz) noexcept; - - XMVECTOR XM_CALLCONV XMColorXYZToSRGB(FXMVECTOR xyz) noexcept; - XMVECTOR XM_CALLCONV XMColorSRGBToXYZ(FXMVECTOR srgb) noexcept; - - XMVECTOR XM_CALLCONV XMColorRGBToSRGB(FXMVECTOR rgb) noexcept; - XMVECTOR XM_CALLCONV XMColorSRGBToRGB(FXMVECTOR srgb) noexcept; - - - /**************************************************************************** - * - * Miscellaneous operations - * - ****************************************************************************/ - - bool XMVerifyCPUSupport() noexcept; - - XMVECTOR XM_CALLCONV XMFresnelTerm(FXMVECTOR CosIncidentAngle, FXMVECTOR RefractionIndex) noexcept; - - bool XMScalarNearEqual(float S1, float S2, float Epsilon) noexcept; - float XMScalarModAngle(float Value) noexcept; - - float XMScalarSin(float Value) noexcept; - float XMScalarSinEst(float Value) noexcept; - - float XMScalarCos(float Value) noexcept; - float XMScalarCosEst(float Value) noexcept; - - void XMScalarSinCos(_Out_ float* pSin, _Out_ float* pCos, float Value) noexcept; - void XMScalarSinCosEst(_Out_ float* pSin, _Out_ float* pCos, float Value) noexcept; - - float XMScalarASin(float Value) noexcept; - float XMScalarASinEst(float Value) noexcept; - - float XMScalarACos(float Value) noexcept; - float XMScalarACosEst(float Value) noexcept; - - /**************************************************************************** - * - * Templates - * - ****************************************************************************/ +XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, FXMVECTOR V2, + uint32_t Elements) noexcept; +XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V, + uint32_t Elements) noexcept; +XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V, + uint32_t Elements) noexcept; +XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, FXMVECTOR VS, + uint32_t VSLeftRotateElements, + uint32_t Select0, uint32_t Select1, + uint32_t Select2, + uint32_t Select3) noexcept; + +XMVECTOR XM_CALLCONV XMVectorEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorEqualR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorEqualIntR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +XMVECTOR XM_CALLCONV XMVectorNotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreaterR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreaterOrEqual(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorGreaterOrEqualR(_Out_ uint32_t* pCR, + _In_ FXMVECTOR V1, + _In_ FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorLess(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorLessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorInBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; +XMVECTOR XM_CALLCONV XMVectorInBoundsR(_Out_ uint32_t* pCR, _In_ FXMVECTOR V, + _In_ FXMVECTOR Bounds) noexcept; + +XMVECTOR XM_CALLCONV XMVectorIsNaN(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorIsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVectorMin(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMax(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorRound(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTruncate(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorFloor(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCeiling(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorClamp(FXMVECTOR V, FXMVECTOR Min, + FXMVECTOR Max) noexcept; +XMVECTOR XM_CALLCONV XMVectorSaturate(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVectorAndInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorAndCInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorOrInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorXorInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; + +XMVECTOR XM_CALLCONV XMVectorNegate(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorAdd(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSum(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorAddAngles(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSubtract(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorSubtractAngles(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMultiply(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorMultiplyAdd(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR V3) noexcept; +XMVECTOR XM_CALLCONV XMVectorDivide(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorNegativeMultiplySubtract(FXMVECTOR V1, + FXMVECTOR V2, + FXMVECTOR V3) noexcept; +XMVECTOR XM_CALLCONV XMVectorScale(FXMVECTOR V, float ScaleFactor) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocalEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSqrtEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSqrt(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocalSqrtEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorReciprocalSqrt(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExp2(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExp10(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExpE(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorExp(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLog2(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLog10(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLogE(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorLog(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorPow(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorAbs(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorMod(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVectorModAngles(FXMVECTOR Angles) noexcept; +XMVECTOR XM_CALLCONV XMVectorSin(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSinEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCos(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCosEst(FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorSinCos(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMVectorSinCosEst(_Out_ XMVECTOR* pSin, _Out_ XMVECTOR* pCos, + _In_ FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTan(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTanEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorSinH(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorCosH(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorTanH(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorASin(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorASinEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorACos(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorACosEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorATan(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorATanEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVectorATan2(FXMVECTOR Y, FXMVECTOR X) noexcept; +XMVECTOR XM_CALLCONV XMVectorATan2Est(FXMVECTOR Y, FXMVECTOR X) noexcept; +XMVECTOR XM_CALLCONV XMVectorLerp(FXMVECTOR V0, FXMVECTOR V1, float t) noexcept; +XMVECTOR XM_CALLCONV XMVectorLerpV(FXMVECTOR V0, FXMVECTOR V1, + FXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMVectorHermite(FXMVECTOR Position0, FXMVECTOR Tangent0, + FXMVECTOR Position1, GXMVECTOR Tangent1, + float t) noexcept; +XMVECTOR XM_CALLCONV XMVectorHermiteV(FXMVECTOR Position0, FXMVECTOR Tangent0, + FXMVECTOR Position1, GXMVECTOR Tangent1, + HXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMVectorCatmullRom(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, + GXMVECTOR Position3, float t) noexcept; +XMVECTOR XM_CALLCONV XMVectorCatmullRomV(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, + GXMVECTOR Position3, + HXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMVectorBaryCentric(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, float f, + float g) noexcept; +XMVECTOR XM_CALLCONV XMVectorBaryCentricV(FXMVECTOR Position0, + FXMVECTOR Position1, + FXMVECTOR Position2, GXMVECTOR F, + HXMVECTOR G) noexcept; + +/**************************************************************************** + * + * 2D vector operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMVector2Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2NearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMVector2NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector2GreaterOrEqualR(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector2InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; + +bool XM_CALLCONV XMVector2IsNaN(FXMVECTOR V) noexcept; +bool XM_CALLCONV XMVector2IsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVector2Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector2Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector2LengthSq(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2ReciprocalLengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2ReciprocalLength(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2LengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2Length(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2NormalizeEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2Normalize(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2ClampLength(FXMVECTOR V, float LengthMin, + float LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector2ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, + FXMVECTOR LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector2Reflect(FXMVECTOR Incident, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector2Refract(FXMVECTOR Incident, FXMVECTOR Normal, + float RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector2RefractV(FXMVECTOR Incident, FXMVECTOR Normal, + FXMVECTOR RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector2Orthogonal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormalsEst(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector2AngleBetweenNormals(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector2AngleBetweenVectors(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector2LinePointDistance(FXMVECTOR LinePoint1, + FXMVECTOR LinePoint2, + FXMVECTOR Point) noexcept; +XMVECTOR XM_CALLCONV XMVector2IntersectLine(FXMVECTOR Line1Point1, + FXMVECTOR Line1Point2, + FXMVECTOR Line2Point1, + GXMVECTOR Line2Point2) noexcept; +XMVECTOR XM_CALLCONV XMVector2Transform(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT4* XM_CALLCONV XMVector2TransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) + const XMFLOAT2* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector2TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT2* XM_CALLCONV XMVector2TransformCoordStream( + _Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) + XMFLOAT2* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) + const XMFLOAT2* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector2TransformNormal(FXMVECTOR V, + FXMMATRIX M) noexcept; +XMFLOAT2* XM_CALLCONV XMVector2TransformNormalStream( + _Out_writes_bytes_(sizeof(XMFLOAT2) + OutputStride * (VectorCount - 1)) + XMFLOAT2* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT2) + InputStride * (VectorCount - 1)) + const XMFLOAT2* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; + +/**************************************************************************** + * + * 3D vector operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMVector3Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3NearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMVector3NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector3GreaterOrEqualR(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector3InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; + +bool XM_CALLCONV XMVector3IsNaN(FXMVECTOR V) noexcept; +bool XM_CALLCONV XMVector3IsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVector3Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector3Cross(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector3LengthSq(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3ReciprocalLengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3ReciprocalLength(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3LengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3Length(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3NormalizeEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3Normalize(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3ClampLength(FXMVECTOR V, float LengthMin, + float LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector3ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, + FXMVECTOR LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector3Reflect(FXMVECTOR Incident, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector3Refract(FXMVECTOR Incident, FXMVECTOR Normal, + float RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector3RefractV(FXMVECTOR Incident, FXMVECTOR Normal, + FXMVECTOR RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector3Orthogonal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormalsEst(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector3AngleBetweenNormals(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector3AngleBetweenVectors(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector3LinePointDistance(FXMVECTOR LinePoint1, + FXMVECTOR LinePoint2, + FXMVECTOR Point) noexcept; +void XM_CALLCONV XMVector3ComponentsFromNormal(_Out_ XMVECTOR* pParallel, + _Out_ XMVECTOR* pPerpendicular, + _In_ FXMVECTOR V, + _In_ FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector3Rotate(FXMVECTOR V, + FXMVECTOR RotationQuaternion) noexcept; +XMVECTOR XM_CALLCONV +XMVector3InverseRotate(FXMVECTOR V, FXMVECTOR RotationQuaternion) noexcept; +XMVECTOR XM_CALLCONV XMVector3Transform(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT4* XM_CALLCONV XMVector3TransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector3TransformCoord(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3TransformCoordStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector3TransformNormal(FXMVECTOR V, + FXMMATRIX M) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3TransformNormalStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; +XMVECTOR XM_CALLCONV XMVector3Project(FXMVECTOR V, float ViewportX, + float ViewportY, float ViewportWidth, + float ViewportHeight, float ViewportMinZ, + float ViewportMaxZ, FXMMATRIX Projection, + CXMMATRIX View, CXMMATRIX World) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3ProjectStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, _In_ float ViewportX, + _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, + _In_ float ViewportMinZ, _In_ float ViewportMaxZ, _In_ FXMMATRIX Projection, + _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; +XMVECTOR XM_CALLCONV XMVector3Unproject(FXMVECTOR V, float ViewportX, + float ViewportY, float ViewportWidth, + float ViewportHeight, + float ViewportMinZ, float ViewportMaxZ, + FXMMATRIX Projection, CXMMATRIX View, + CXMMATRIX World) noexcept; +XMFLOAT3* XM_CALLCONV XMVector3UnprojectStream( + _Out_writes_bytes_(sizeof(XMFLOAT3) + OutputStride * (VectorCount - 1)) + XMFLOAT3* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT3) + InputStride * (VectorCount - 1)) + const XMFLOAT3* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, _In_ float ViewportX, + _In_ float ViewportY, _In_ float ViewportWidth, _In_ float ViewportHeight, + _In_ float ViewportMinZ, _In_ float ViewportMaxZ, _In_ FXMMATRIX Projection, + _In_ CXMMATRIX View, _In_ CXMMATRIX World) noexcept; + +/**************************************************************************** + * + * 4D vector operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMVector4Equal(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4EqualR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4EqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4EqualIntR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4NearEqual(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMVector4NotEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4NotEqualInt(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4Greater(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4GreaterR(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4GreaterOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +uint32_t XM_CALLCONV XMVector4GreaterOrEqualR(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4Less(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4LessOrEqual(FXMVECTOR V1, FXMVECTOR V2) noexcept; +bool XM_CALLCONV XMVector4InBounds(FXMVECTOR V, FXMVECTOR Bounds) noexcept; + +bool XM_CALLCONV XMVector4IsNaN(FXMVECTOR V) noexcept; +bool XM_CALLCONV XMVector4IsInfinite(FXMVECTOR V) noexcept; + +XMVECTOR XM_CALLCONV XMVector4Dot(FXMVECTOR V1, FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector4Cross(FXMVECTOR V1, FXMVECTOR V2, + FXMVECTOR V3) noexcept; +XMVECTOR XM_CALLCONV XMVector4LengthSq(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4ReciprocalLengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4ReciprocalLength(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4LengthEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4Length(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4NormalizeEst(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4Normalize(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4ClampLength(FXMVECTOR V, float LengthMin, + float LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector4ClampLengthV(FXMVECTOR V, FXMVECTOR LengthMin, + FXMVECTOR LengthMax) noexcept; +XMVECTOR XM_CALLCONV XMVector4Reflect(FXMVECTOR Incident, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMVector4Refract(FXMVECTOR Incident, FXMVECTOR Normal, + float RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector4RefractV(FXMVECTOR Incident, FXMVECTOR Normal, + FXMVECTOR RefractionIndex) noexcept; +XMVECTOR XM_CALLCONV XMVector4Orthogonal(FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormalsEst(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector4AngleBetweenNormals(FXMVECTOR N1, + FXMVECTOR N2) noexcept; +XMVECTOR XM_CALLCONV XMVector4AngleBetweenVectors(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMVector4Transform(FXMVECTOR V, FXMMATRIX M) noexcept; +XMFLOAT4* XM_CALLCONV XMVector4TransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (VectorCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (VectorCount - 1)) + const XMFLOAT4* pInputStream, + _In_ size_t InputStride, _In_ size_t VectorCount, + _In_ FXMMATRIX M) noexcept; + +/**************************************************************************** + * + * Matrix operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMMatrixIsNaN(FXMMATRIX M) noexcept; +bool XM_CALLCONV XMMatrixIsInfinite(FXMMATRIX M) noexcept; +bool XM_CALLCONV XMMatrixIsIdentity(FXMMATRIX M) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixMultiply(FXMMATRIX M1, CXMMATRIX M2) noexcept; +XMMATRIX XM_CALLCONV XMMatrixMultiplyTranspose(FXMMATRIX M1, + CXMMATRIX M2) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTranspose(FXMMATRIX M) noexcept; +XMMATRIX XM_CALLCONV XMMatrixInverse(_Out_opt_ XMVECTOR* pDeterminant, + _In_ FXMMATRIX M) noexcept; +XMMATRIX XM_CALLCONV XMMatrixVectorTensorProduct(FXMVECTOR V1, + FXMVECTOR V2) noexcept; +XMVECTOR XM_CALLCONV XMMatrixDeterminant(FXMMATRIX M) noexcept; + +_Success_(return) bool XM_CALLCONV + XMMatrixDecompose(_Out_ XMVECTOR* outScale, _Out_ XMVECTOR* outRotQuat, + _Out_ XMVECTOR* outTrans, _In_ FXMMATRIX M) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixIdentity() noexcept; +XMMATRIX XM_CALLCONV XMMatrixSet(float m00, float m01, float m02, float m03, + float m10, float m11, float m12, float m13, + float m20, float m21, float m22, float m23, + float m30, float m31, float m32, + float m33) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTranslation(float OffsetX, float OffsetY, + float OffsetZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTranslationFromVector(FXMVECTOR Offset) noexcept; +XMMATRIX XM_CALLCONV XMMatrixScaling(float ScaleX, float ScaleY, + float ScaleZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixScalingFromVector(FXMVECTOR Scale) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationX(float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationY(float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationZ(float Angle) noexcept; + +// Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) +XMMATRIX XM_CALLCONV XMMatrixRotationRollPitchYaw(float Pitch, float Yaw, + float Roll) noexcept; + +// Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis +// (Angles.z) +XMMATRIX XM_CALLCONV +XMMatrixRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixRotationNormal(FXMVECTOR NormalAxis, + float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationAxis(FXMVECTOR Axis, float Angle) noexcept; +XMMATRIX XM_CALLCONV XMMatrixRotationQuaternion(FXMVECTOR Quaternion) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTransformation2D( + FXMVECTOR ScalingOrigin, float ScalingOrientation, FXMVECTOR Scaling, + FXMVECTOR RotationOrigin, float Rotation, GXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV XMMatrixTransformation( + FXMVECTOR ScalingOrigin, FXMVECTOR ScalingOrientationQuaternion, + FXMVECTOR Scaling, GXMVECTOR RotationOrigin, HXMVECTOR RotationQuaternion, + HXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV +XMMatrixAffineTransformation2D(FXMVECTOR Scaling, FXMVECTOR RotationOrigin, + float Rotation, FXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV XMMatrixAffineTransformation( + FXMVECTOR Scaling, FXMVECTOR RotationOrigin, FXMVECTOR RotationQuaternion, + GXMVECTOR Translation) noexcept; +XMMATRIX XM_CALLCONV XMMatrixReflect(FXMVECTOR ReflectionPlane) noexcept; +XMMATRIX XM_CALLCONV XMMatrixShadow(FXMVECTOR ShadowPlane, + FXMVECTOR LightPosition) noexcept; + +XMMATRIX XM_CALLCONV XMMatrixLookAtLH(FXMVECTOR EyePosition, + FXMVECTOR FocusPosition, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixLookAtRH(FXMVECTOR EyePosition, + FXMVECTOR FocusPosition, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixLookToLH(FXMVECTOR EyePosition, + FXMVECTOR EyeDirection, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixLookToRH(FXMVECTOR EyePosition, + FXMVECTOR EyeDirection, + FXMVECTOR UpDirection) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveLH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveRH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovLH(float FovAngleY, + float AspectRatio, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveFovRH(float FovAngleY, + float AspectRatio, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterLH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixPerspectiveOffCenterRH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicLH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicRH(float ViewWidth, float ViewHeight, + float NearZ, float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterLH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; +XMMATRIX XM_CALLCONV XMMatrixOrthographicOffCenterRH(float ViewLeft, + float ViewRight, + float ViewBottom, + float ViewTop, float NearZ, + float FarZ) noexcept; + +/**************************************************************************** + * + * Quaternion operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMQuaternionEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; +bool XM_CALLCONV XMQuaternionNotEqual(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; + +bool XM_CALLCONV XMQuaternionIsNaN(FXMVECTOR Q) noexcept; +bool XM_CALLCONV XMQuaternionIsInfinite(FXMVECTOR Q) noexcept; +bool XM_CALLCONV XMQuaternionIsIdentity(FXMVECTOR Q) noexcept; + +XMVECTOR XM_CALLCONV XMQuaternionDot(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionMultiply(FXMVECTOR Q1, FXMVECTOR Q2) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionLengthSq(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionReciprocalLength(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionLength(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionNormalizeEst(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionNormalize(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionConjugate(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionInverse(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionLn(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionExp(FXMVECTOR Q) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSlerp(FXMVECTOR Q0, FXMVECTOR Q1, + float t) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSlerpV(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR T) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSquad(FXMVECTOR Q0, FXMVECTOR Q1, FXMVECTOR Q2, + GXMVECTOR Q3, float t) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionSquadV(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR Q2, GXMVECTOR Q3, + HXMVECTOR T) noexcept; +void XM_CALLCONV XMQuaternionSquadSetup(_Out_ XMVECTOR* pA, _Out_ XMVECTOR* pB, + _Out_ XMVECTOR* pC, _In_ FXMVECTOR Q0, + _In_ FXMVECTOR Q1, _In_ FXMVECTOR Q2, + _In_ GXMVECTOR Q3) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionBaryCentric(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR Q2, float f, + float g) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionBaryCentricV(FXMVECTOR Q0, FXMVECTOR Q1, + FXMVECTOR Q2, GXMVECTOR F, + HXMVECTOR G) noexcept; + +XMVECTOR XM_CALLCONV XMQuaternionIdentity() noexcept; + +// Rotates about y-axis (Yaw), then x-axis (Pitch), then z-axis (Roll) +XMVECTOR XM_CALLCONV XMQuaternionRotationRollPitchYaw(float Pitch, float Yaw, + float Roll) noexcept; + +// Rotates about y-axis (Angles.y), then x-axis (Angles.x), then z-axis +// (Angles.z) +XMVECTOR XM_CALLCONV +XMQuaternionRotationRollPitchYawFromVector(FXMVECTOR Angles) noexcept; + +XMVECTOR XM_CALLCONV XMQuaternionRotationNormal(FXMVECTOR NormalAxis, + float Angle) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionRotationAxis(FXMVECTOR Axis, + float Angle) noexcept; +XMVECTOR XM_CALLCONV XMQuaternionRotationMatrix(FXMMATRIX M) noexcept; + +void XM_CALLCONV XMQuaternionToAxisAngle(_Out_ XMVECTOR* pAxis, + _Out_ float* pAngle, + _In_ FXMVECTOR Q) noexcept; + +/**************************************************************************** + * + * Plane operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMPlaneEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; +bool XM_CALLCONV XMPlaneNearEqual(FXMVECTOR P1, FXMVECTOR P2, + FXMVECTOR Epsilon) noexcept; +bool XM_CALLCONV XMPlaneNotEqual(FXMVECTOR P1, FXMVECTOR P2) noexcept; + +bool XM_CALLCONV XMPlaneIsNaN(FXMVECTOR P) noexcept; +bool XM_CALLCONV XMPlaneIsInfinite(FXMVECTOR P) noexcept; + +XMVECTOR XM_CALLCONV XMPlaneDot(FXMVECTOR P, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMPlaneDotCoord(FXMVECTOR P, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMPlaneDotNormal(FXMVECTOR P, FXMVECTOR V) noexcept; +XMVECTOR XM_CALLCONV XMPlaneNormalizeEst(FXMVECTOR P) noexcept; +XMVECTOR XM_CALLCONV XMPlaneNormalize(FXMVECTOR P) noexcept; +XMVECTOR XM_CALLCONV XMPlaneIntersectLine(FXMVECTOR P, FXMVECTOR LinePoint1, + FXMVECTOR LinePoint2) noexcept; +void XM_CALLCONV XMPlaneIntersectPlane(_Out_ XMVECTOR* pLinePoint1, + _Out_ XMVECTOR* pLinePoint2, + _In_ FXMVECTOR P1, + _In_ FXMVECTOR P2) noexcept; + +// Transforms a plane given an inverse transpose matrix +XMVECTOR XM_CALLCONV XMPlaneTransform(FXMVECTOR P, FXMMATRIX ITM) noexcept; + +// Transforms an array of planes given an inverse transpose matrix +XMFLOAT4* XM_CALLCONV XMPlaneTransformStream( + _Out_writes_bytes_(sizeof(XMFLOAT4) + OutputStride * (PlaneCount - 1)) + XMFLOAT4* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(XMFLOAT4) + InputStride * (PlaneCount - 1)) + const XMFLOAT4* pInputStream, + _In_ size_t InputStride, _In_ size_t PlaneCount, + _In_ FXMMATRIX ITM) noexcept; + +XMVECTOR XM_CALLCONV XMPlaneFromPointNormal(FXMVECTOR Point, + FXMVECTOR Normal) noexcept; +XMVECTOR XM_CALLCONV XMPlaneFromPoints(FXMVECTOR Point1, FXMVECTOR Point2, + FXMVECTOR Point3) noexcept; + +/**************************************************************************** + * + * Color operations + * + ****************************************************************************/ + +bool XM_CALLCONV XMColorEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorNotEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorGreater(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorGreaterOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorLess(FXMVECTOR C1, FXMVECTOR C2) noexcept; +bool XM_CALLCONV XMColorLessOrEqual(FXMVECTOR C1, FXMVECTOR C2) noexcept; + +bool XM_CALLCONV XMColorIsNaN(FXMVECTOR C) noexcept; +bool XM_CALLCONV XMColorIsInfinite(FXMVECTOR C) noexcept; + +XMVECTOR XM_CALLCONV XMColorNegative(FXMVECTOR C) noexcept; +XMVECTOR XM_CALLCONV XMColorModulate(FXMVECTOR C1, FXMVECTOR C2) noexcept; +XMVECTOR XM_CALLCONV XMColorAdjustSaturation(FXMVECTOR C, + float Saturation) noexcept; +XMVECTOR XM_CALLCONV XMColorAdjustContrast(FXMVECTOR C, + float Contrast) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToHSL(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorHSLToRGB(FXMVECTOR hsl) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToHSV(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorHSVToRGB(FXMVECTOR hsv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToYUV(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorYUVToRGB(FXMVECTOR yuv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToYUV_HD(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorYUVToRGB_HD(FXMVECTOR yuv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToYUV_UHD(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorYUVToRGB_UHD(FXMVECTOR yuv) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToXYZ(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorXYZToRGB(FXMVECTOR xyz) noexcept; + +XMVECTOR XM_CALLCONV XMColorXYZToSRGB(FXMVECTOR xyz) noexcept; +XMVECTOR XM_CALLCONV XMColorSRGBToXYZ(FXMVECTOR srgb) noexcept; + +XMVECTOR XM_CALLCONV XMColorRGBToSRGB(FXMVECTOR rgb) noexcept; +XMVECTOR XM_CALLCONV XMColorSRGBToRGB(FXMVECTOR srgb) noexcept; + +/**************************************************************************** + * + * Miscellaneous operations + * + ****************************************************************************/ + +bool XMVerifyCPUSupport() noexcept; + +XMVECTOR XM_CALLCONV XMFresnelTerm(FXMVECTOR CosIncidentAngle, + FXMVECTOR RefractionIndex) noexcept; + +bool XMScalarNearEqual(float S1, float S2, float Epsilon) noexcept; +float XMScalarModAngle(float Value) noexcept; + +float XMScalarSin(float Value) noexcept; +float XMScalarSinEst(float Value) noexcept; + +float XMScalarCos(float Value) noexcept; +float XMScalarCosEst(float Value) noexcept; + +void XMScalarSinCos(_Out_ float* pSin, _Out_ float* pCos, float Value) noexcept; +void XMScalarSinCosEst(_Out_ float* pSin, _Out_ float* pCos, + float Value) noexcept; + +float XMScalarASin(float Value) noexcept; +float XMScalarASinEst(float Value) noexcept; + +float XMScalarACos(float Value) noexcept; +float XMScalarACosEst(float Value) noexcept; + +/**************************************************************************** + * + * Templates + * + ****************************************************************************/ #if defined(__XNAMATH_H__) && defined(XMMin) #undef XMMin #undef XMMax #endif - template inline T XMMin(T a, T b) noexcept { return (a < b) ? a : b; } - template inline T XMMax(T a, T b) noexcept { return (a > b) ? a : b; } +template +inline T XMMin(T a, T b) noexcept { + return (a < b) ? a : b; +} +template +inline T XMMax(T a, T b) noexcept { + return (a > b) ? a : b; +} - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) // PermuteHelper internal template (SSE only) - namespace MathInternal - { - // Slow path fallback for permutes that do not map to a single SSE shuffle opcode. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept - { - static const XMVECTORU32 selectMask = - { { { - WhichX ? 0xFFFFFFFF : 0, - WhichY ? 0xFFFFFFFF : 0, - WhichZ ? 0xFFFFFFFF : 0, - WhichW ? 0xFFFFFFFF : 0, - } } }; +namespace MathInternal { +// Slow path fallback for permutes that do not map to a single SSE shuffle +// opcode. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { + static const XMVECTORU32 selectMask = {{{ + WhichX ? 0xFFFFFFFF : 0, + WhichY ? 0xFFFFFFFF : 0, + WhichZ ? 0xFFFFFFFF : 0, + WhichW ? 0xFFFFFFFF : 0, + }}}; - XMVECTOR shuffled1 = XM_PERMUTE_PS(v1, Shuffle); - XMVECTOR shuffled2 = XM_PERMUTE_PS(v2, Shuffle); + XMVECTOR shuffled1 = XM_PERMUTE_PS(v1, Shuffle); + XMVECTOR shuffled2 = XM_PERMUTE_PS(v2, Shuffle); - XMVECTOR masked1 = _mm_andnot_ps(selectMask, shuffled1); - XMVECTOR masked2 = _mm_and_ps(selectMask, shuffled2); + XMVECTOR masked1 = _mm_andnot_ps(selectMask, shuffled1); + XMVECTOR masked2 = _mm_and_ps(selectMask, shuffled2); - return _mm_or_ps(masked1, masked2); - } - }; - - // Fast path for permutes that only read from the first vector. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR) noexcept { return XM_PERMUTE_PS(v1, Shuffle); } - }; - - // Fast path for permutes that only read from the second vector. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR, FXMVECTOR v2) noexcept { return XM_PERMUTE_PS(v2, Shuffle); } - }; - - // Fast path for permutes that read XY from the first vector, ZW from the second. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { return _mm_shuffle_ps(v1, v2, Shuffle); } - }; - - // Fast path for permutes that read XY from the second vector, ZW from the first. - template struct PermuteHelper - { - static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { return _mm_shuffle_ps(v2, v1, Shuffle); } - }; + return _mm_or_ps(masked1, masked2); } +}; -#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ - - // General permute template - template - inline XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, FXMVECTOR V2) noexcept - { - static_assert(PermuteX <= 7, "PermuteX template parameter out of range"); - static_assert(PermuteY <= 7, "PermuteY template parameter out of range"); - static_assert(PermuteZ <= 7, "PermuteZ template parameter out of range"); - static_assert(PermuteW <= 7, "PermuteW template parameter out of range"); - - #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - constexpr uint32_t Shuffle = _MM_SHUFFLE(PermuteW & 3, PermuteZ & 3, PermuteY & 3, PermuteX & 3); - - constexpr bool WhichX = PermuteX > 3; - constexpr bool WhichY = PermuteY > 3; - constexpr bool WhichZ = PermuteZ > 3; - constexpr bool WhichW = PermuteW > 3; - - return MathInternal::PermuteHelper::Permute(V1, V2); - #else - - return XMVectorPermute(V1, V2, PermuteX, PermuteY, PermuteZ, PermuteW); - - #endif +// Fast path for permutes that only read from the first vector. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR) noexcept { + return XM_PERMUTE_PS(v1, Shuffle); } +}; - // Special-case permute templates - template<> constexpr XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 3>(FXMVECTOR V1, FXMVECTOR) noexcept { return V1; } - template<> constexpr XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 6, 7>(FXMVECTOR, FXMVECTOR V2) noexcept { return V2; } +// Fast path for permutes that only read from the second vector. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR, FXMVECTOR v2) noexcept { + return XM_PERMUTE_PS(v2, Shuffle); + } +}; + +// Fast path for permutes that read XY from the first vector, ZW from the +// second. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { + return _mm_shuffle_ps(v1, v2, Shuffle); + } +}; + +// Fast path for permutes that read XY from the second vector, ZW from the +// first. +template +struct PermuteHelper { + static XMVECTOR XM_CALLCONV Permute(FXMVECTOR v1, FXMVECTOR v2) noexcept { + return _mm_shuffle_ps(v2, v1, Shuffle); + } +}; +} // namespace MathInternal + +#endif // _XM_SSE_INTRINSICS_ && !_XM_NO_INTRINSICS_ + +// General permute template +template +inline XMVECTOR XM_CALLCONV XMVectorPermute(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + static_assert(PermuteX <= 7, "PermuteX template parameter out of range"); + static_assert(PermuteY <= 7, "PermuteY template parameter out of range"); + static_assert(PermuteZ <= 7, "PermuteZ template parameter out of range"); + static_assert(PermuteW <= 7, "PermuteW template parameter out of range"); #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_movelh_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<6, 7, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_movehl_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_unpacklo_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_unpackhi_ps(V1, V2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_castpd_ps(_mm_unpackhi_pd(_mm_castps_pd(V1), _mm_castps_pd(V2))); } + constexpr uint32_t Shuffle = + _MM_SHUFFLE(PermuteW & 3, PermuteZ & 3, PermuteY & 3, PermuteX & 3); + + constexpr bool WhichX = PermuteX > 3; + constexpr bool WhichY = PermuteY > 3; + constexpr bool WhichZ = PermuteZ > 3; + constexpr bool WhichW = PermuteW > 3; + + return MathInternal::PermuteHelper::Permute(V1, V2); +#else + + return XMVectorPermute(V1, V2, PermuteX, PermuteY, PermuteZ, PermuteW); + +#endif +} + +// Special-case permute templates +template <> +constexpr XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 3>(FXMVECTOR V1, + FXMVECTOR) noexcept { + return V1; +} +template <> +constexpr XMVECTOR XM_CALLCONV +XMVectorPermute<4, 5, 6, 7>(FXMVECTOR, FXMVECTOR V2) noexcept { + return V2; +} + +#if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_movelh_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<6, 7, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_movehl_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_unpacklo_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_unpackhi_ps(V1, V2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_castpd_ps(_mm_unpackhi_pd(_mm_castps_pd(V1), _mm_castps_pd(V2))); +} #endif #if defined(_XM_SSE4_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x3); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x4); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x5); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x6); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 6, 3>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x7); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x8); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0x9); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xA); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xB); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xC); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xD); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return _mm_blend_ps(V1, V2, 0xE); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x3); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x4); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x5); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x6); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 6, 3>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x7); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x8); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0x9); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xA); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 5, 2, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xB); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xC); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<4, 1, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xD); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 5, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return _mm_blend_ps(V1, V2, 0xE); +} #endif #if defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - // If the indices are all in the range 0-3 or 4-7, then use XMVectorSwizzle instead - // The mirror cases are not spelled out here as the programmer can always swap the arguments - // (i.e. prefer permutes where the X element comes from the V1 vector instead of the V2 vector) +// If the indices are all in the range 0-3 or 4-7, then use XMVectorSwizzle +// instead The mirror cases are not spelled out here as the programmer can +// always swap the arguments (i.e. prefer permutes where the X element comes +// from the V1 vector instead of the V2 vector) - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vget_low_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_low_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_low_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vrev64_f32(vget_low_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vget_low_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_low_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_low_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), + vrev64_f32(vget_low_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_high_f32(V1), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_high_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vrev64_f32(vget_high_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_high_f32(V1), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_high_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), + vrev64_f32(vget_high_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 6, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_high_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_high_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 7, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vrev64_f32(vget_high_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 6, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), vget_high_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 1, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_low_f32(V1), vrev64_f32(vget_high_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 0, 7, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V1)), + vrev64_f32(vget_high_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_low_f32(V2)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_low_f32(V2))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 5, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vrev64_f32(vget_low_f32(V2))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), vget_low_f32(V2)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vget_high_f32(V1), vrev64_f32(vget_low_f32(V2))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 2, 5, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V1)), + vrev64_f32(vget_low_f32(V2))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 2, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vtrnq_f32(V1, V2).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 5, 3, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vtrnq_f32(V1, V2).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 2, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vtrnq_f32(V1, V2).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 5, 3, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vtrnq_f32(V1, V2).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vzipq_f32(V1, V2).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vzipq_f32(V1, V2).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 4, 1, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vzipq_f32(V1, V2).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 6, 3, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vzipq_f32(V1, V2).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 2, 4, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vuzpq_f32(V1, V2).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 3, 5, 7>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vuzpq_f32(V1, V2).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<0, 2, 4, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vuzpq_f32(V1, V2).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 3, 5, 7>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vuzpq_f32(V1, V2).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 2, 3, 4>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vextq_f32(V1, V2, 1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 4, 5>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vextq_f32(V1, V2, 2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 4, 5, 6>(FXMVECTOR V1, FXMVECTOR V2) noexcept { return vextq_f32(V1, V2, 3); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<1, 2, 3, 4>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vextq_f32(V1, V2, 1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<2, 3, 4, 5>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vextq_f32(V1, V2, 2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorPermute<3, 4, 5, 6>(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + return vextq_f32(V1, V2, 3); +} -#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - // General swizzle template - template - inline XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V) noexcept - { - static_assert(SwizzleX <= 3, "SwizzleX template parameter out of range"); - static_assert(SwizzleY <= 3, "SwizzleY template parameter out of range"); - static_assert(SwizzleZ <= 3, "SwizzleZ template parameter out of range"); - static_assert(SwizzleW <= 3, "SwizzleW template parameter out of range"); - - #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - return XM_PERMUTE_PS(V, _MM_SHUFFLE(SwizzleW, SwizzleZ, SwizzleY, SwizzleX)); - #else - - return XMVectorSwizzle(V, SwizzleX, SwizzleY, SwizzleZ, SwizzleW); - - #endif - } - - // Specialized swizzles - template<> constexpr XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 2, 3>(FXMVECTOR V) noexcept { return V; } +// General swizzle template +template +inline XMVECTOR XM_CALLCONV XMVectorSwizzle(FXMVECTOR V) noexcept { + static_assert(SwizzleX <= 3, "SwizzleX template parameter out of range"); + static_assert(SwizzleY <= 3, "SwizzleY template parameter out of range"); + static_assert(SwizzleZ <= 3, "SwizzleZ template parameter out of range"); + static_assert(SwizzleW <= 3, "SwizzleW template parameter out of range"); #if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { return _mm_movelh_ps(V, V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { return _mm_movehl_ps(V, V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { return _mm_unpacklo_ps(V, V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { return _mm_unpackhi_ps(V, V); } + return XM_PERMUTE_PS(V, + _MM_SHUFFLE(SwizzleW, SwizzleZ, SwizzleY, SwizzleX)); +#else + + return XMVectorSwizzle(V, SwizzleX, SwizzleY, SwizzleZ, SwizzleW); + +#endif +} + +// Specialized swizzles +template <> +constexpr XMVECTOR XM_CALLCONV +XMVectorSwizzle<0, 1, 2, 3>(FXMVECTOR V) noexcept { + return V; +} + +#if defined(_XM_SSE_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { + return _mm_movelh_ps(V, V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { + return _mm_movehl_ps(V, V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { + return _mm_unpacklo_ps(V, V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { + return _mm_unpackhi_ps(V, V); +} #endif #if defined(_XM_SSE3_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { return _mm_moveldup_ps(V); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { return _mm_movehdup_ps(V); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { + return _mm_moveldup_ps(V); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { + return _mm_movehdup_ps(V); +} #endif -#if defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) && defined(_XM_FAVOR_INTEL_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { return _mm_broadcastss_ps(V); } +#if defined(_XM_AVX2_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) && \ + defined(_XM_FAVOR_INTEL_) +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { + return _mm_broadcastss_ps(V); +} #endif #if defined(_XM_ARM_NEON_INTRINSICS_) && !defined(_XM_NO_INTRINSICS_) - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_low_f32(V), 0); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 1, 1>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_low_f32(V), 1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 2, 2>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_high_f32(V), 0); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 3, 3, 3>(FXMVECTOR V) noexcept { return vdupq_lane_f32(vget_high_f32(V), 1); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 0, 0>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_low_f32(V), 0); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 1, 1>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_low_f32(V), 1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 2, 2>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_high_f32(V), 0); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 3, 3, 3>(FXMVECTOR V) noexcept { + return vdupq_lane_f32(vget_high_f32(V), 1); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 3, 2>(FXMVECTOR V) noexcept { return vrev64q_f32(V); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 3, 2>(FXMVECTOR V) noexcept { + return vrev64q_f32(V); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { float32x2_t vt = vget_low_f32(V); return vcombine_f32(vt, vt); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { float32x2_t vt = vget_high_f32(V); return vcombine_f32(vt, vt); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 1, 0>(FXMVECTOR V) noexcept { float32x2_t vt = vrev64_f32(vget_low_f32(V)); return vcombine_f32(vt, vt); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 3, 2>(FXMVECTOR V) noexcept { float32x2_t vt = vrev64_f32(vget_high_f32(V)); return vcombine_f32(vt, vt); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 0, 1>(FXMVECTOR V) noexcept { + float32x2_t vt = vget_low_f32(V); + return vcombine_f32(vt, vt); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 2, 3>(FXMVECTOR V) noexcept { + float32x2_t vt = vget_high_f32(V); + return vcombine_f32(vt, vt); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 1, 0>(FXMVECTOR V) noexcept { + float32x2_t vt = vrev64_f32(vget_low_f32(V)); + return vcombine_f32(vt, vt); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 3, 2>(FXMVECTOR V) noexcept { + float32x2_t vt = vrev64_f32(vget_high_f32(V)); + return vcombine_f32(vt, vt); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 3, 2>(FXMVECTOR V) noexcept { return vcombine_f32(vget_low_f32(V), vrev64_f32(vget_high_f32(V))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 2, 3>(FXMVECTOR V) noexcept { return vcombine_f32(vrev64_f32(vget_low_f32(V)), vget_high_f32(V)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 1, 0>(FXMVECTOR V) noexcept { return vcombine_f32(vget_high_f32(V), vrev64_f32(vget_low_f32(V))); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 0, 1>(FXMVECTOR V) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V)), vget_low_f32(V)); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 1, 0>(FXMVECTOR V) noexcept { return vcombine_f32(vrev64_f32(vget_high_f32(V)), vrev64_f32(vget_low_f32(V))); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 1, 3, 2>(FXMVECTOR V) noexcept { + return vcombine_f32(vget_low_f32(V), vrev64_f32(vget_high_f32(V))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 0, 2, 3>(FXMVECTOR V) noexcept { + return vcombine_f32(vrev64_f32(vget_low_f32(V)), vget_high_f32(V)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 1, 0>(FXMVECTOR V) noexcept { + return vcombine_f32(vget_high_f32(V), vrev64_f32(vget_low_f32(V))); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 0, 1>(FXMVECTOR V) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V)), vget_low_f32(V)); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 2, 1, 0>(FXMVECTOR V) noexcept { + return vcombine_f32(vrev64_f32(vget_high_f32(V)), + vrev64_f32(vget_low_f32(V))); +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { return vtrnq_f32(V, V).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { return vtrnq_f32(V, V).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 2, 2>(FXMVECTOR V) noexcept { + return vtrnq_f32(V, V).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 1, 3, 3>(FXMVECTOR V) noexcept { + return vtrnq_f32(V, V).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { return vzipq_f32(V, V).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { return vzipq_f32(V, V).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 0, 1, 1>(FXMVECTOR V) noexcept { + return vzipq_f32(V, V).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 2, 3, 3>(FXMVECTOR V) noexcept { + return vzipq_f32(V, V).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 2, 0, 2>(FXMVECTOR V) noexcept { return vuzpq_f32(V, V).val[0]; } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 3, 1, 3>(FXMVECTOR V) noexcept { return vuzpq_f32(V, V).val[1]; } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<0, 2, 0, 2>(FXMVECTOR V) noexcept { + return vuzpq_f32(V, V).val[0]; +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 3, 1, 3>(FXMVECTOR V) noexcept { + return vuzpq_f32(V, V).val[1]; +} - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 2, 3, 0>(FXMVECTOR V) noexcept { return vextq_f32(V, V, 1); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 0, 1>(FXMVECTOR V) noexcept { return vextq_f32(V, V, 2); } - template<> inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 0, 1, 2>(FXMVECTOR V) noexcept { return vextq_f32(V, V, 3); } +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<1, 2, 3, 0>(FXMVECTOR V) noexcept { + return vextq_f32(V, V, 1); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<2, 3, 0, 1>(FXMVECTOR V) noexcept { + return vextq_f32(V, V, 2); +} +template <> +inline XMVECTOR XM_CALLCONV XMVectorSwizzle<3, 0, 1, 2>(FXMVECTOR V) noexcept { + return vextq_f32(V, V, 3); +} -#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ +#endif // _XM_ARM_NEON_INTRINSICS_ && !_XM_NO_INTRINSICS_ - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - template - inline XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, FXMVECTOR V2) noexcept - { - static_assert(Elements < 4, "Elements template parameter out of range"); - return XMVectorPermute(V1, V2); - } +template +inline XMVECTOR XM_CALLCONV XMVectorShiftLeft(FXMVECTOR V1, + FXMVECTOR V2) noexcept { + static_assert(Elements < 4, "Elements template parameter out of range"); + return XMVectorPermute(V1, V2); +} - template - inline XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V) noexcept - { - static_assert(Elements < 4, "Elements template parameter out of range"); - return XMVectorSwizzle(V); - } +template +inline XMVECTOR XM_CALLCONV XMVectorRotateLeft(FXMVECTOR V) noexcept { + static_assert(Elements < 4, "Elements template parameter out of range"); + return XMVectorSwizzle(V); +} - template - inline XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V) noexcept - { - static_assert(Elements < 4, "Elements template parameter out of range"); - return XMVectorSwizzle<(4 - Elements) & 3, (5 - Elements) & 3, (6 - Elements) & 3, (7 - Elements) & 3>(V); - } +template +inline XMVECTOR XM_CALLCONV XMVectorRotateRight(FXMVECTOR V) noexcept { + static_assert(Elements < 4, "Elements template parameter out of range"); + return XMVectorSwizzle<(4 - Elements) & 3, (5 - Elements) & 3, + (6 - Elements) & 3, (7 - Elements) & 3>(V); +} - template - inline XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, FXMVECTOR VS) noexcept - { - XMVECTOR Control = XMVectorSelectControl(Select0 & 1, Select1 & 1, Select2 & 1, Select3 & 1); - return XMVectorSelect(VD, XMVectorRotateLeft(VS), Control); - } +template +inline XMVECTOR XM_CALLCONV XMVectorInsert(FXMVECTOR VD, + FXMVECTOR VS) noexcept { + XMVECTOR Control = XMVectorSelectControl(Select0 & 1, Select1 & 1, + Select2 & 1, Select3 & 1); + return XMVectorSelect(VD, XMVectorRotateLeft(VS), + Control); +} - /**************************************************************************** - * - * Globals - * - ****************************************************************************/ +/**************************************************************************** + * + * Globals + * + ****************************************************************************/ - // The purpose of the following global constants is to prevent redundant - // reloading of the constants when they are referenced by more than one - // separate inline math routine called within the same function. Declaring - // a constant locally within a routine is sufficient to prevent redundant - // reloads of that constant when that single routine is called multiple - // times in a function, but if the constant is used (and declared) in a - // separate math routine it would be reloaded. +// The purpose of the following global constants is to prevent redundant +// reloading of the constants when they are referenced by more than one +// separate inline math routine called within the same function. Declaring +// a constant locally within a routine is sufficient to prevent redundant +// reloads of that constant when that single routine is called multiple +// times in a function, but if the constant is used (and declared) in a +// separate math routine it would be reloaded. #ifndef XMGLOBALCONST #if defined(__GNUC__) && !defined(__MINGW32__) @@ -2013,162 +2695,274 @@ namespace DirectX #endif #endif - XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients0 = { { { -0.16666667f, +0.0083333310f, -0.00019840874f, +2.7525562e-06f } } }; - XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients1 = { { { -2.3889859e-08f, -0.16665852f /*Est1*/, +0.0083139502f /*Est2*/, -0.00018524670f /*Est3*/ } } }; - XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients0 = { { { -0.5f, +0.041666638f, -0.0013888378f, +2.4760495e-05f } } }; - XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients1 = { { { -2.6051615e-07f, -0.49992746f /*Est1*/, +0.041493919f /*Est2*/, -0.0012712436f /*Est3*/ } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients0 = { { { 1.0f, 0.333333333f, 0.133333333f, 5.396825397e-2f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients1 = { { { 2.186948854e-2f, 8.863235530e-3f, 3.592128167e-3f, 1.455834485e-3f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients2 = { { { 5.900274264e-4f, 2.391290764e-4f, 9.691537707e-5f, 3.927832950e-5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients0 = { { { +1.5707963050f, -0.2145988016f, +0.0889789874f, -0.0501743046f } } }; - XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients1 = { { { +0.0308918810f, -0.0170881256f, +0.0066700901f, -0.0012624911f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients0 = { { { -0.3333314528f, +0.1999355085f, -0.1420889944f, +0.1065626393f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients1 = { { { -0.0752896400f, +0.0429096138f, -0.0161657367f, +0.0028662257f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients0 = { { { +0.999866f, +0.999866f, +0.999866f, +0.999866f } } }; - XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients1 = { { { -0.3302995f, +0.180141f, -0.085133f, +0.0208351f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTanEstCoefficients = { { { 2.484f, -1.954923183e-1f, 2.467401101f, XM_1DIVPI } } }; - XMGLOBALCONST XMVECTORF32 g_XMArcEstCoefficients = { { { +1.5707288f, -0.2121144f, +0.0742610f, -0.0187293f } } }; - XMGLOBALCONST XMVECTORF32 g_XMPiConstants0 = { { { XM_PI, XM_2PI, XM_1DIVPI, XM_1DIV2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR0 = { { { 1.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR1 = { { { 0.0f, 1.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR2 = { { { 0.0f, 0.0f, 1.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMIdentityR3 = { { { 0.0f, 0.0f, 0.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR0 = { { { -1.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR1 = { { { 0.0f, -1.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR2 = { { { 0.0f, 0.0f, -1.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR3 = { { { 0.0f, 0.0f, 0.0f, -1.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegativeZero = { { { 0x80000000, 0x80000000, 0x80000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegate3 = { { { 0x80000000, 0x80000000, 0x80000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskXY = { { { 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMask3 = { { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskX = { { { 0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskY = { { { 0x00000000, 0xFFFFFFFF, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskZ = { { { 0x00000000, 0x00000000, 0xFFFFFFFF, 0x00000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskW = { { { 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF } } }; - XMGLOBALCONST XMVECTORF32 g_XMOne = { { { 1.0f, 1.0f, 1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMOne3 = { { { 1.0f, 1.0f, 1.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMZero = { { { 0.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMTwo = { { { 2.f, 2.f, 2.f, 2.f } } }; - XMGLOBALCONST XMVECTORF32 g_XMFour = { { { 4.f, 4.f, 4.f, 4.f } } }; - XMGLOBALCONST XMVECTORF32 g_XMSix = { { { 6.f, 6.f, 6.f, 6.f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativeOne = { { { -1.0f, -1.0f, -1.0f, -1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMOneHalf = { { { 0.5f, 0.5f, 0.5f, 0.5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativeOneHalf = { { { -0.5f, -0.5f, -0.5f, -0.5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativeTwoPi = { { { -XM_2PI, -XM_2PI, -XM_2PI, -XM_2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegativePi = { { { -XM_PI, -XM_PI, -XM_PI, -XM_PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMHalfPi = { { { XM_PIDIV2, XM_PIDIV2, XM_PIDIV2, XM_PIDIV2 } } }; - XMGLOBALCONST XMVECTORF32 g_XMPi = { { { XM_PI, XM_PI, XM_PI, XM_PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMReciprocalPi = { { { XM_1DIVPI, XM_1DIVPI, XM_1DIVPI, XM_1DIVPI } } }; - XMGLOBALCONST XMVECTORF32 g_XMTwoPi = { { { XM_2PI, XM_2PI, XM_2PI, XM_2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMReciprocalTwoPi = { { { XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI } } }; - XMGLOBALCONST XMVECTORF32 g_XMEpsilon = { { { 1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f } } }; - XMGLOBALCONST XMVECTORI32 g_XMInfinity = { { { 0x7F800000, 0x7F800000, 0x7F800000, 0x7F800000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMQNaN = { { { 0x7FC00000, 0x7FC00000, 0x7FC00000, 0x7FC00000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMQNaNTest = { { { 0x007FFFFF, 0x007FFFFF, 0x007FFFFF, 0x007FFFFF } } }; - XMGLOBALCONST XMVECTORI32 g_XMAbsMask = { { { 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF } } }; - XMGLOBALCONST XMVECTORI32 g_XMFltMin = { { { 0x00800000, 0x00800000, 0x00800000, 0x00800000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMFltMax = { { { 0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegOneMask = { { { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskA8R8G8B8 = { { { 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipA8R8G8B8 = { { { 0x00000000, 0x00000000, 0x00000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixAA8R8G8B8 = { { { 0.0f, 0.0f, 0.0f, float(0x80000000U) } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeA8R8G8B8 = { { { 1.0f / (255.0f * float(0x10000)), 1.0f / (255.0f * float(0x100)), 1.0f / 255.0f, 1.0f / (255.0f * float(0x1000000)) } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskA2B10G10R10 = { { { 0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipA2B10G10R10 = { { { 0x00000200, 0x00080000, 0x20000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixAA2B10G10R10 = { { { -512.0f, -512.0f * float(0x400), -512.0f * float(0x100000), float(0x80000000U) } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeA2B10G10R10 = { { { 1.0f / 511.0f, 1.0f / (511.0f * float(0x400)), 1.0f / (511.0f * float(0x100000)), 1.0f / (3.0f * float(0x40000000)) } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16 = { { { 0x0000FFFF, 0xFFFF0000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16 = { { { 0x00008000, 0x00000000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16 = { { { -32768.0f, 0.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16 = { { { 1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16Z16W16 = { { { 0x0000FFFF, 0x0000FFFF, 0xFFFF0000, 0xFFFF0000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16Z16W16 = { { { 0x00008000, 0x00008000, 0x00000000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16Z16W16 = { { { -32768.0f, -32768.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16Z16W16 = { { { 1.0f / 32767.0f, 1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), 1.0f / (32767.0f * 65536.0f) } } }; - XMGLOBALCONST XMVECTORF32 g_XMNoFraction = { { { 8388608.0f, 8388608.0f, 8388608.0f, 8388608.0f } } }; - XMGLOBALCONST XMVECTORI32 g_XMMaskByte = { { { 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateX = { { { -1.0f, 1.0f, 1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateY = { { { 1.0f, -1.0f, 1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateZ = { { { 1.0f, 1.0f, -1.0f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMNegateW = { { { 1.0f, 1.0f, 1.0f, -1.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect0101 = { { { XM_SELECT_0, XM_SELECT_1, XM_SELECT_0, XM_SELECT_1 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1010 = { { { XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORI32 g_XMOneHalfMinusEpsilon = { { { 0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1000 = { { { XM_SELECT_1, XM_SELECT_0, XM_SELECT_0, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1100 = { { { XM_SELECT_1, XM_SELECT_1, XM_SELECT_0, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1110 = { { { XM_SELECT_1, XM_SELECT_1, XM_SELECT_1, XM_SELECT_0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMSelect1011 = { { { XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_1 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixupY16 = { { { 1.0f, 1.0f / 65536.0f, 0.0f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixupY16W16 = { { { 1.0f, 1.0f, 1.0f / 65536.0f, 1.0f / 65536.0f } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipY = { { { 0, 0x80000000, 0, 0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipZ = { { { 0, 0, 0x80000000, 0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipW = { { { 0, 0, 0, 0x80000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipYZ = { { { 0, 0x80000000, 0x80000000, 0 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipZW = { { { 0, 0, 0x80000000, 0x80000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMFlipYW = { { { 0, 0x80000000, 0, 0x80000000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMMaskDec4 = { { { 0x3FF, 0x3FF << 10, 0x3FF << 20, static_cast(0xC0000000) } } }; - XMGLOBALCONST XMVECTORI32 g_XMXorDec4 = { { { 0x200, 0x200 << 10, 0x200 << 20, 0 } } }; - XMGLOBALCONST XMVECTORF32 g_XMAddUDec4 = { { { 0, 0, 0, 32768.0f * 65536.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMAddDec4 = { { { -512.0f, -512.0f * 1024.0f, -512.0f * 1024.0f * 1024.0f, 0 } } }; - XMGLOBALCONST XMVECTORF32 g_XMMulDec4 = { { { 1.0f, 1.0f / 1024.0f, 1.0f / (1024.0f * 1024.0f), 1.0f / (1024.0f * 1024.0f * 1024.0f) } } }; - XMGLOBALCONST XMVECTORU32 g_XMMaskByte4 = { { { 0xFF, 0xFF00, 0xFF0000, 0xFF000000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMXorByte4 = { { { 0x80, 0x8000, 0x800000, 0x00000000 } } }; - XMGLOBALCONST XMVECTORF32 g_XMAddByte4 = { { { -128.0f, -128.0f * 256.0f, -128.0f * 65536.0f, 0 } } }; - XMGLOBALCONST XMVECTORF32 g_XMFixUnsigned = { { { 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMMaxInt = { { { 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMMaxUInt = { { { 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMUnsignedFix = { { { 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMsrgbScale = { { { 12.92f, 12.92f, 12.92f, 1.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMsrgbA = { { { 0.055f, 0.055f, 0.055f, 0.0f } } }; - XMGLOBALCONST XMVECTORF32 g_XMsrgbA1 = { { { 1.055f, 1.055f, 1.055f, 1.0f } } }; - XMGLOBALCONST XMVECTORI32 g_XMExponentBias = { { { 127, 127, 127, 127 } } }; - XMGLOBALCONST XMVECTORI32 g_XMSubnormalExponent = { { { -126, -126, -126, -126 } } }; - XMGLOBALCONST XMVECTORI32 g_XMNumTrailing = { { { 23, 23, 23, 23 } } }; - XMGLOBALCONST XMVECTORI32 g_XMMinNormal = { { { 0x00800000, 0x00800000, 0x00800000, 0x00800000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegInfinity = { { { 0xFF800000, 0xFF800000, 0xFF800000, 0xFF800000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMNegQNaN = { { { 0xFFC00000, 0xFFC00000, 0xFFC00000, 0xFFC00000 } } }; - XMGLOBALCONST XMVECTORI32 g_XMBin128 = { { { 0x43000000, 0x43000000, 0x43000000, 0x43000000 } } }; - XMGLOBALCONST XMVECTORU32 g_XMBinNeg150 = { { { 0xC3160000, 0xC3160000, 0xC3160000, 0xC3160000 } } }; - XMGLOBALCONST XMVECTORI32 g_XM253 = { { { 253, 253, 253, 253 } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst1 = { { { -6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst2 = { { { +2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst3 = { { { -5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst4 = { { { +9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst5 = { { { -1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst6 = { { { +1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f } } }; - XMGLOBALCONST XMVECTORF32 g_XMExpEst7 = { { { -1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst0 = { { { +1.442693f, +1.442693f, +1.442693f, +1.442693f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst1 = { { { -0.721242f, -0.721242f, -0.721242f, -0.721242f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst2 = { { { +0.479384f, +0.479384f, +0.479384f, +0.479384f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst3 = { { { -0.350295f, -0.350295f, -0.350295f, -0.350295f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst4 = { { { +0.248590f, +0.248590f, +0.248590f, +0.248590f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst5 = { { { -0.145700f, -0.145700f, -0.145700f, -0.145700f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst6 = { { { +0.057148f, +0.057148f, +0.057148f, +0.057148f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLogEst7 = { { { -0.010578f, -0.010578f, -0.010578f, -0.010578f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLgE = { { { +1.442695f, +1.442695f, +1.442695f, +1.442695f } } }; - XMGLOBALCONST XMVECTORF32 g_XMInvLgE = { { { +6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_XMLg10 = { { { +3.321928f, +3.321928f, +3.321928f, +3.321928f } } }; - XMGLOBALCONST XMVECTORF32 g_XMInvLg10 = { { { +3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f } } }; - XMGLOBALCONST XMVECTORF32 g_UByteMax = { { { 255.0f, 255.0f, 255.0f, 255.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ByteMin = { { { -127.0f, -127.0f, -127.0f, -127.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ByteMax = { { { 127.0f, 127.0f, 127.0f, 127.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ShortMin = { { { -32767.0f, -32767.0f, -32767.0f, -32767.0f } } }; - XMGLOBALCONST XMVECTORF32 g_ShortMax = { { { 32767.0f, 32767.0f, 32767.0f, 32767.0f } } }; - XMGLOBALCONST XMVECTORF32 g_UShortMax = { { { 65535.0f, 65535.0f, 65535.0f, 65535.0f } } }; +XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients0 = { + {{-0.16666667f, +0.0083333310f, -0.00019840874f, +2.7525562e-06f}}}; +XMGLOBALCONST XMVECTORF32 g_XMSinCoefficients1 = { + {{-2.3889859e-08f, -0.16665852f /*Est1*/, +0.0083139502f /*Est2*/, + -0.00018524670f /*Est3*/}}}; +XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients0 = { + {{-0.5f, +0.041666638f, -0.0013888378f, +2.4760495e-05f}}}; +XMGLOBALCONST XMVECTORF32 g_XMCosCoefficients1 = { + {{-2.6051615e-07f, -0.49992746f /*Est1*/, +0.041493919f /*Est2*/, + -0.0012712436f /*Est3*/}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients0 = { + {{1.0f, 0.333333333f, 0.133333333f, 5.396825397e-2f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients1 = { + {{2.186948854e-2f, 8.863235530e-3f, 3.592128167e-3f, 1.455834485e-3f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanCoefficients2 = { + {{5.900274264e-4f, 2.391290764e-4f, 9.691537707e-5f, 3.927832950e-5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients0 = { + {{+1.5707963050f, -0.2145988016f, +0.0889789874f, -0.0501743046f}}}; +XMGLOBALCONST XMVECTORF32 g_XMArcCoefficients1 = { + {{+0.0308918810f, -0.0170881256f, +0.0066700901f, -0.0012624911f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients0 = { + {{-0.3333314528f, +0.1999355085f, -0.1420889944f, +0.1065626393f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanCoefficients1 = { + {{-0.0752896400f, +0.0429096138f, -0.0161657367f, +0.0028662257f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients0 = { + {{+0.999866f, +0.999866f, +0.999866f, +0.999866f}}}; +XMGLOBALCONST XMVECTORF32 g_XMATanEstCoefficients1 = { + {{-0.3302995f, +0.180141f, -0.085133f, +0.0208351f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTanEstCoefficients = { + {{2.484f, -1.954923183e-1f, 2.467401101f, XM_1DIVPI}}}; +XMGLOBALCONST XMVECTORF32 g_XMArcEstCoefficients = { + {{+1.5707288f, -0.2121144f, +0.0742610f, -0.0187293f}}}; +XMGLOBALCONST XMVECTORF32 g_XMPiConstants0 = { + {{XM_PI, XM_2PI, XM_1DIVPI, XM_1DIV2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR0 = {{{1.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR1 = {{{0.0f, 1.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR2 = {{{0.0f, 0.0f, 1.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMIdentityR3 = {{{0.0f, 0.0f, 0.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR0 = {{{-1.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR1 = {{{0.0f, -1.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR2 = {{{0.0f, 0.0f, -1.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegIdentityR3 = {{{0.0f, 0.0f, 0.0f, -1.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegativeZero = { + {{0x80000000, 0x80000000, 0x80000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegate3 = { + {{0x80000000, 0x80000000, 0x80000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskXY = { + {{0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMask3 = { + {{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskX = { + {{0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskY = { + {{0x00000000, 0xFFFFFFFF, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskZ = { + {{0x00000000, 0x00000000, 0xFFFFFFFF, 0x00000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskW = { + {{0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF}}}; +XMGLOBALCONST XMVECTORF32 g_XMOne = {{{1.0f, 1.0f, 1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMOne3 = {{{1.0f, 1.0f, 1.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMZero = {{{0.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMTwo = {{{2.f, 2.f, 2.f, 2.f}}}; +XMGLOBALCONST XMVECTORF32 g_XMFour = {{{4.f, 4.f, 4.f, 4.f}}}; +XMGLOBALCONST XMVECTORF32 g_XMSix = {{{6.f, 6.f, 6.f, 6.f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativeOne = {{{-1.0f, -1.0f, -1.0f, -1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMOneHalf = {{{0.5f, 0.5f, 0.5f, 0.5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativeOneHalf = { + {{-0.5f, -0.5f, -0.5f, -0.5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativeTwoPi = { + {{-XM_2PI, -XM_2PI, -XM_2PI, -XM_2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegativePi = {{{-XM_PI, -XM_PI, -XM_PI, -XM_PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMHalfPi = { + {{XM_PIDIV2, XM_PIDIV2, XM_PIDIV2, XM_PIDIV2}}}; +XMGLOBALCONST XMVECTORF32 g_XMPi = {{{XM_PI, XM_PI, XM_PI, XM_PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMReciprocalPi = { + {{XM_1DIVPI, XM_1DIVPI, XM_1DIVPI, XM_1DIVPI}}}; +XMGLOBALCONST XMVECTORF32 g_XMTwoPi = {{{XM_2PI, XM_2PI, XM_2PI, XM_2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMReciprocalTwoPi = { + {{XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI, XM_1DIV2PI}}}; +XMGLOBALCONST XMVECTORF32 g_XMEpsilon = { + {{1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f, 1.192092896e-7f}}}; +XMGLOBALCONST XMVECTORI32 g_XMInfinity = { + {{0x7F800000, 0x7F800000, 0x7F800000, 0x7F800000}}}; +XMGLOBALCONST XMVECTORI32 g_XMQNaN = { + {{0x7FC00000, 0x7FC00000, 0x7FC00000, 0x7FC00000}}}; +XMGLOBALCONST XMVECTORI32 g_XMQNaNTest = { + {{0x007FFFFF, 0x007FFFFF, 0x007FFFFF, 0x007FFFFF}}}; +XMGLOBALCONST XMVECTORI32 g_XMAbsMask = { + {{0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF}}}; +XMGLOBALCONST XMVECTORI32 g_XMFltMin = { + {{0x00800000, 0x00800000, 0x00800000, 0x00800000}}}; +XMGLOBALCONST XMVECTORI32 g_XMFltMax = { + {{0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF, 0x7F7FFFFF}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegOneMask = { + {{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskA8R8G8B8 = { + {{0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipA8R8G8B8 = { + {{0x00000000, 0x00000000, 0x00000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixAA8R8G8B8 = { + {{0.0f, 0.0f, 0.0f, float(0x80000000U)}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeA8R8G8B8 = { + {{1.0f / (255.0f * float(0x10000)), 1.0f / (255.0f * float(0x100)), + 1.0f / 255.0f, 1.0f / (255.0f * float(0x1000000))}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskA2B10G10R10 = { + {{0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipA2B10G10R10 = { + {{0x00000200, 0x00080000, 0x20000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixAA2B10G10R10 = { + {{-512.0f, -512.0f * float(0x400), -512.0f * float(0x100000), + float(0x80000000U)}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeA2B10G10R10 = { + {{1.0f / 511.0f, 1.0f / (511.0f * float(0x400)), + 1.0f / (511.0f * float(0x100000)), 1.0f / (3.0f * float(0x40000000))}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16 = { + {{0x0000FFFF, 0xFFFF0000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16 = { + {{0x00008000, 0x00000000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16 = {{{-32768.0f, 0.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16 = { + {{1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskX16Y16Z16W16 = { + {{0x0000FFFF, 0x0000FFFF, 0xFFFF0000, 0xFFFF0000}}}; +XMGLOBALCONST XMVECTORI32 g_XMFlipX16Y16Z16W16 = { + {{0x00008000, 0x00008000, 0x00000000, 0x00000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixX16Y16Z16W16 = { + {{-32768.0f, -32768.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNormalizeX16Y16Z16W16 = { + {{1.0f / 32767.0f, 1.0f / 32767.0f, 1.0f / (32767.0f * 65536.0f), + 1.0f / (32767.0f * 65536.0f)}}}; +XMGLOBALCONST XMVECTORF32 g_XMNoFraction = { + {{8388608.0f, 8388608.0f, 8388608.0f, 8388608.0f}}}; +XMGLOBALCONST XMVECTORI32 g_XMMaskByte = { + {{0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateX = {{{-1.0f, 1.0f, 1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateY = {{{1.0f, -1.0f, 1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateZ = {{{1.0f, 1.0f, -1.0f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMNegateW = {{{1.0f, 1.0f, 1.0f, -1.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect0101 = { + {{XM_SELECT_0, XM_SELECT_1, XM_SELECT_0, XM_SELECT_1}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1010 = { + {{XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORI32 g_XMOneHalfMinusEpsilon = { + {{0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD, 0x3EFFFFFD}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1000 = { + {{XM_SELECT_1, XM_SELECT_0, XM_SELECT_0, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1100 = { + {{XM_SELECT_1, XM_SELECT_1, XM_SELECT_0, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1110 = { + {{XM_SELECT_1, XM_SELECT_1, XM_SELECT_1, XM_SELECT_0}}}; +XMGLOBALCONST XMVECTORU32 g_XMSelect1011 = { + {{XM_SELECT_1, XM_SELECT_0, XM_SELECT_1, XM_SELECT_1}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixupY16 = { + {{1.0f, 1.0f / 65536.0f, 0.0f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixupY16W16 = { + {{1.0f, 1.0f, 1.0f / 65536.0f, 1.0f / 65536.0f}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipY = {{{0, 0x80000000, 0, 0}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipZ = {{{0, 0, 0x80000000, 0}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipW = {{{0, 0, 0, 0x80000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipYZ = {{{0, 0x80000000, 0x80000000, 0}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipZW = {{{0, 0, 0x80000000, 0x80000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMFlipYW = {{{0, 0x80000000, 0, 0x80000000}}}; +XMGLOBALCONST XMVECTORI32 g_XMMaskDec4 = { + {{0x3FF, 0x3FF << 10, 0x3FF << 20, static_cast(0xC0000000)}}}; +XMGLOBALCONST XMVECTORI32 g_XMXorDec4 = { + {{0x200, 0x200 << 10, 0x200 << 20, 0}}}; +XMGLOBALCONST XMVECTORF32 g_XMAddUDec4 = {{{0, 0, 0, 32768.0f * 65536.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMAddDec4 = { + {{-512.0f, -512.0f * 1024.0f, -512.0f * 1024.0f * 1024.0f, 0}}}; +XMGLOBALCONST XMVECTORF32 g_XMMulDec4 = { + {{1.0f, 1.0f / 1024.0f, 1.0f / (1024.0f * 1024.0f), + 1.0f / (1024.0f * 1024.0f * 1024.0f)}}}; +XMGLOBALCONST XMVECTORU32 g_XMMaskByte4 = { + {{0xFF, 0xFF00, 0xFF0000, 0xFF000000}}}; +XMGLOBALCONST XMVECTORI32 g_XMXorByte4 = { + {{0x80, 0x8000, 0x800000, 0x00000000}}}; +XMGLOBALCONST XMVECTORF32 g_XMAddByte4 = { + {{-128.0f, -128.0f * 256.0f, -128.0f * 65536.0f, 0}}}; +XMGLOBALCONST XMVECTORF32 g_XMFixUnsigned = { + {{32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, + 32768.0f * 65536.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMMaxInt = { + {{65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f, + 65536.0f * 32768.0f - 128.0f, 65536.0f * 32768.0f - 128.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMMaxUInt = { + {{65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f, + 65536.0f * 65536.0f - 256.0f, 65536.0f * 65536.0f - 256.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMUnsignedFix = { + {{32768.0f * 65536.0f, 32768.0f * 65536.0f, 32768.0f * 65536.0f, + 32768.0f * 65536.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMsrgbScale = {{{12.92f, 12.92f, 12.92f, 1.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMsrgbA = {{{0.055f, 0.055f, 0.055f, 0.0f}}}; +XMGLOBALCONST XMVECTORF32 g_XMsrgbA1 = {{{1.055f, 1.055f, 1.055f, 1.0f}}}; +XMGLOBALCONST XMVECTORI32 g_XMExponentBias = {{{127, 127, 127, 127}}}; +XMGLOBALCONST XMVECTORI32 g_XMSubnormalExponent = {{{-126, -126, -126, -126}}}; +XMGLOBALCONST XMVECTORI32 g_XMNumTrailing = {{{23, 23, 23, 23}}}; +XMGLOBALCONST XMVECTORI32 g_XMMinNormal = { + {{0x00800000, 0x00800000, 0x00800000, 0x00800000}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegInfinity = { + {{0xFF800000, 0xFF800000, 0xFF800000, 0xFF800000}}}; +XMGLOBALCONST XMVECTORU32 g_XMNegQNaN = { + {{0xFFC00000, 0xFFC00000, 0xFFC00000, 0xFFC00000}}}; +XMGLOBALCONST XMVECTORI32 g_XMBin128 = { + {{0x43000000, 0x43000000, 0x43000000, 0x43000000}}}; +XMGLOBALCONST XMVECTORU32 g_XMBinNeg150 = { + {{0xC3160000, 0xC3160000, 0xC3160000, 0xC3160000}}}; +XMGLOBALCONST XMVECTORI32 g_XM253 = {{{253, 253, 253, 253}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst1 = { + {{-6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f, -6.93147182e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst2 = { + {{+2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f, +2.40226462e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst3 = { + {{-5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f, -5.55036440e-2f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst4 = { + {{+9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f, +9.61597636e-3f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst5 = { + {{-1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f, -1.32823968e-3f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst6 = { + {{+1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f, +1.47491097e-4f}}}; +XMGLOBALCONST XMVECTORF32 g_XMExpEst7 = { + {{-1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f, -1.08635004e-5f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst0 = { + {{+1.442693f, +1.442693f, +1.442693f, +1.442693f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst1 = { + {{-0.721242f, -0.721242f, -0.721242f, -0.721242f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst2 = { + {{+0.479384f, +0.479384f, +0.479384f, +0.479384f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst3 = { + {{-0.350295f, -0.350295f, -0.350295f, -0.350295f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst4 = { + {{+0.248590f, +0.248590f, +0.248590f, +0.248590f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst5 = { + {{-0.145700f, -0.145700f, -0.145700f, -0.145700f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst6 = { + {{+0.057148f, +0.057148f, +0.057148f, +0.057148f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLogEst7 = { + {{-0.010578f, -0.010578f, -0.010578f, -0.010578f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLgE = { + {{+1.442695f, +1.442695f, +1.442695f, +1.442695f}}}; +XMGLOBALCONST XMVECTORF32 g_XMInvLgE = { + {{+6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f, +6.93147182e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_XMLg10 = { + {{+3.321928f, +3.321928f, +3.321928f, +3.321928f}}}; +XMGLOBALCONST XMVECTORF32 g_XMInvLg10 = { + {{+3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f, +3.010299956e-1f}}}; +XMGLOBALCONST XMVECTORF32 g_UByteMax = {{{255.0f, 255.0f, 255.0f, 255.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ByteMin = {{{-127.0f, -127.0f, -127.0f, -127.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ByteMax = {{{127.0f, 127.0f, 127.0f, 127.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ShortMin = { + {{-32767.0f, -32767.0f, -32767.0f, -32767.0f}}}; +XMGLOBALCONST XMVECTORF32 g_ShortMax = { + {{32767.0f, 32767.0f, 32767.0f, 32767.0f}}}; +XMGLOBALCONST XMVECTORF32 g_UShortMax = { + {{65535.0f, 65535.0f, 65535.0f, 65535.0f}}}; - /**************************************************************************** - * - * Implementation - * - ****************************************************************************/ +/**************************************************************************** + * + * Implementation + * + ****************************************************************************/ #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4068 4214 4204 4365 4616 4640 6001 6101) - // C4068/4616: ignore unknown pragmas - // C4214/4204: nonstandard extension used - // C4365/4640: Off by default noise - // C6001/6101: False positives +#pragma warning(disable : 4068 4214 4204 4365 4616 4640 6001 6101) +// C4068/4616: ignore unknown pragmas +// C4214/4204: nonstandard extension used +// C4365/4640: Off by default noise +// C6001/6101: False positives #endif #ifdef _PREFAST_ @@ -2187,94 +2981,97 @@ namespace DirectX //------------------------------------------------------------------------------ - inline XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, uint32_t C2, uint32_t C3) noexcept - { - #if defined(_XM_NO_INTRINSICS_) - XMVECTORU32 vResult; - vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; - vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; - vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; - vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; - return vResult.v; - #elif defined(_XM_ARM_NEON_INTRINSICS_) - XMVECTORU32 vResult; - vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; - vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; - vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; - vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; - return vResult.v; - #else // XM_SSE_INTRINSICS_ - static const XMVECTORU32 g_vMask1 = { { { 1, 1, 1, 1 } } }; - // Move the parms to a vector - __m128i vTemp = _mm_set_epi32(static_cast(C3), static_cast(C2), static_cast(C1), static_cast(C0)); - // Mask off the low bits - vTemp = _mm_and_si128(vTemp, g_vMask1); - // 0xFFFFFFFF on true bits - vTemp = _mm_cmpeq_epi32(vTemp, g_vMask1); - // 0xFFFFFFFF -> 1.0f, 0x00000000 -> 0.0f - vTemp = _mm_and_si128(vTemp, g_XMOne); - return _mm_castsi128_ps(vTemp); - #endif - } +inline XMVECTOR XM_CALLCONV XMVectorSetBinaryConstant(uint32_t C0, uint32_t C1, + uint32_t C2, + uint32_t C3) noexcept { +#if defined(_XM_NO_INTRINSICS_) + XMVECTORU32 vResult; + vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; + vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; + vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; + vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; + return vResult.v; +#elif defined(_XM_ARM_NEON_INTRINSICS_) + XMVECTORU32 vResult; + vResult.u[0] = (0 - (C0 & 1)) & 0x3F800000; + vResult.u[1] = (0 - (C1 & 1)) & 0x3F800000; + vResult.u[2] = (0 - (C2 & 1)) & 0x3F800000; + vResult.u[3] = (0 - (C3 & 1)) & 0x3F800000; + return vResult.v; +#else // XM_SSE_INTRINSICS_ + static const XMVECTORU32 g_vMask1 = {{{1, 1, 1, 1}}}; + // Move the parms to a vector + __m128i vTemp = _mm_set_epi32(static_cast(C3), static_cast(C2), + static_cast(C1), static_cast(C0)); + // Mask off the low bits + vTemp = _mm_and_si128(vTemp, g_vMask1); + // 0xFFFFFFFF on true bits + vTemp = _mm_cmpeq_epi32(vTemp, g_vMask1); + // 0xFFFFFFFF -> 1.0f, 0x00000000 -> 0.0f + vTemp = _mm_and_si128(vTemp, g_XMOne); + return _mm_castsi128_ps(vTemp); +#endif +} - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - inline XMVECTOR XM_CALLCONV XMVectorSplatConstant(int32_t IntConstant, uint32_t DivExponent) noexcept - { - assert(IntConstant >= -16 && IntConstant <= 15); - assert(DivExponent < 32); - #if defined(_XM_NO_INTRINSICS_) +inline XMVECTOR XM_CALLCONV +XMVectorSplatConstant(int32_t IntConstant, uint32_t DivExponent) noexcept { + assert(IntConstant >= -16 && IntConstant <= 15); + assert(DivExponent < 32); +#if defined(_XM_NO_INTRINSICS_) - using DirectX::XMConvertVectorIntToFloat; + using DirectX::XMConvertVectorIntToFloat; - XMVECTORI32 V = { { { IntConstant, IntConstant, IntConstant, IntConstant } } }; - return XMConvertVectorIntToFloat(V.v, DivExponent); + XMVECTORI32 V = {{{IntConstant, IntConstant, IntConstant, IntConstant}}}; + return XMConvertVectorIntToFloat(V.v, DivExponent); - #elif defined(_XM_ARM_NEON_INTRINSICS_) - // Splat the int - int32x4_t vScale = vdupq_n_s32(IntConstant); - // Convert to a float - XMVECTOR vResult = vcvtq_f32_s32(vScale); - // Convert DivExponent into 1.0f/(1<(&vScale)[0]); - return vResult; - #else // XM_SSE_INTRINSICS_ - // Splat the int - __m128i vScale = _mm_set1_epi32(IntConstant); - // Convert to a float - XMVECTOR vResult = _mm_cvtepi32_ps(vScale); - // Convert DivExponent into 1.0f/(1<(uScale)); - // Multiply by the reciprocal (Perform a right shift by DivExponent) - vResult = _mm_mul_ps(vResult, _mm_castsi128_ps(vScale)); - return vResult; - #endif - } +#elif defined(_XM_ARM_NEON_INTRINSICS_) + // Splat the int + int32x4_t vScale = vdupq_n_s32(IntConstant); + // Convert to a float + XMVECTOR vResult = vcvtq_f32_s32(vScale); + // Convert DivExponent into 1.0f/(1<(&vScale)[0]); + return vResult; +#else // XM_SSE_INTRINSICS_ + // Splat the int + __m128i vScale = _mm_set1_epi32(IntConstant); + // Convert to a float + XMVECTOR vResult = _mm_cvtepi32_ps(vScale); + // Convert DivExponent into 1.0f/(1<(uScale)); + // Multiply by the reciprocal (Perform a right shift by DivExponent) + vResult = _mm_mul_ps(vResult, _mm_castsi128_ps(vScale)); + return vResult; +#endif +} - //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ - inline XMVECTOR XM_CALLCONV XMVectorSplatConstantInt(int32_t IntConstant) noexcept - { - assert(IntConstant >= -16 && IntConstant <= 15); - #if defined(_XM_NO_INTRINSICS_) +inline XMVECTOR XM_CALLCONV +XMVectorSplatConstantInt(int32_t IntConstant) noexcept { + assert(IntConstant >= -16 && IntConstant <= 15); +#if defined(_XM_NO_INTRINSICS_) - XMVECTORI32 V = { { { IntConstant, IntConstant, IntConstant, IntConstant } } }; - return V.v; + XMVECTORI32 V = {{{IntConstant, IntConstant, IntConstant, IntConstant}}}; + return V.v; - #elif defined(_XM_ARM_NEON_INTRINSICS_) - int32x4_t V = vdupq_n_s32(IntConstant); - return reinterpret_cast(&V)[0]; - #else // XM_SSE_INTRINSICS_ - __m128i V = _mm_set1_epi32(IntConstant); - return _mm_castsi128_ps(V); - #endif - } +#elif defined(_XM_ARM_NEON_INTRINSICS_) + int32x4_t V = vdupq_n_s32(IntConstant); + return reinterpret_cast(&V)[0]; +#else // XM_SSE_INTRINSICS_ + __m128i V = _mm_set1_epi32(IntConstant); + return _mm_castsi128_ps(V); +#endif +} #include "DirectXMathConvert.inl" #include "DirectXMathVector.inl" @@ -2291,5 +3088,4 @@ namespace DirectX #pragma warning(pop) #endif -} // namespace DirectX - +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h index 8eb49113d..2487c67eb 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/DirectXPackedVector.h @@ -11,1249 +11,1319 @@ #include "DirectXMath.h" -namespace DirectX -{ +namespace DirectX { - namespace PackedVector - { - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable:4201 4365 4324 4996) - // C4201: nonstandard extension used - // C4365: Off by default noise - // C4324: alignment padding warnings - // C4996: deprecation warnings - #endif +namespace PackedVector { +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4201 4365 4324 4996) +// C4201: nonstandard extension used +// C4365: Off by default noise +// C4324: alignment padding warnings +// C4996: deprecation warnings +#endif - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wgnu-anonymous-struct" - #pragma clang diagnostic ignored "-Wnested-anon-types" - #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu-anonymous-struct" +#pragma clang diagnostic ignored "-Wnested-anon-types" +#endif - //------------------------------------------------------------------------------ - // ARGB Color; 8-8-8-8 bit unsigned normalized integer components packed into - // a 32 bit integer. The normalized color is packed into 32 bits using 8 bit - // unsigned, normalized integers for the alpha, red, green, and blue components. - // The alpha component is stored in the most significant bits and the blue - // component in the least significant bits (A8R8G8B8): - // [32] aaaaaaaa rrrrrrrr gggggggg bbbbbbbb [0] - struct XMCOLOR - { - union - { - struct - { - uint8_t b; // Blue: 0/255 to 255/255 - uint8_t g; // Green: 0/255 to 255/255 - uint8_t r; // Red: 0/255 to 255/255 - uint8_t a; // Alpha: 0/255 to 255/255 - }; - uint32_t c; - }; - - XMCOLOR() = default; - - XMCOLOR(const XMCOLOR&) = default; - XMCOLOR& operator=(const XMCOLOR&) = default; - - XMCOLOR(XMCOLOR&&) = default; - XMCOLOR& operator=(XMCOLOR&&) = default; - - constexpr XMCOLOR(uint32_t Color) noexcept : c(Color) {} - XMCOLOR(float _r, float _g, float _b, float _a) noexcept; - explicit XMCOLOR(_In_reads_(4) const float* pArray) noexcept; - - operator uint32_t () const noexcept { return c; } - - XMCOLOR& operator= (const uint32_t Color) noexcept { c = Color; return *this; } +//------------------------------------------------------------------------------ +// ARGB Color; 8-8-8-8 bit unsigned normalized integer components packed into +// a 32 bit integer. The normalized color is packed into 32 bits using 8 bit +// unsigned, normalized integers for the alpha, red, green, and blue components. +// The alpha component is stored in the most significant bits and the blue +// component in the least significant bits (A8R8G8B8): +// [32] aaaaaaaa rrrrrrrr gggggggg bbbbbbbb [0] +struct XMCOLOR { + union { + struct { + uint8_t b; // Blue: 0/255 to 255/255 + uint8_t g; // Green: 0/255 to 255/255 + uint8_t r; // Red: 0/255 to 255/255 + uint8_t a; // Alpha: 0/255 to 255/255 }; + uint32_t c; + }; - //------------------------------------------------------------------------------ - // 16 bit floating point number consisting of a sign bit, a 5 bit biased - // exponent, and a 10 bit mantissa - using HALF = uint16_t; + XMCOLOR() = default; - //------------------------------------------------------------------------------ - // 2D Vector; 16 bit floating point components - struct XMHALF2 - { - union - { - struct - { - HALF x; - HALF y; - }; - uint32_t v; - }; + XMCOLOR(const XMCOLOR&) = default; + XMCOLOR& operator=(const XMCOLOR&) = default; - XMHALF2() = default; + XMCOLOR(XMCOLOR&&) = default; + XMCOLOR& operator=(XMCOLOR&&) = default; - XMHALF2(const XMHALF2&) = default; - XMHALF2& operator=(const XMHALF2&) = default; + constexpr XMCOLOR(uint32_t Color) noexcept : c(Color) {} + XMCOLOR(float _r, float _g, float _b, float _a) noexcept; + explicit XMCOLOR(_In_reads_(4) const float* pArray) noexcept; - XMHALF2(XMHALF2&&) = default; - XMHALF2& operator=(XMHALF2&&) = default; + operator uint32_t() const noexcept { return c; } - explicit constexpr XMHALF2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMHALF2(HALF _x, HALF _y) noexcept : x(_x), y(_y) {} - explicit XMHALF2(_In_reads_(2) const HALF* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMHALF2(float _x, float _y) noexcept; - explicit XMHALF2(_In_reads_(2) const float* pArray) noexcept; + XMCOLOR& operator=(const uint32_t Color) noexcept { + c = Color; + return *this; + } +}; - XMHALF2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 16 bit floating point number consisting of a sign bit, a 5 bit biased +// exponent, and a 10 bit mantissa +using HALF = uint16_t; + +//------------------------------------------------------------------------------ +// 2D Vector; 16 bit floating point components +struct XMHALF2 { + union { + struct { + HALF x; + HALF y; }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 2D Vector; 16 bit signed normalized integer components - struct XMSHORTN2 - { - union - { - struct - { - int16_t x; - int16_t y; - }; - uint32_t v; - }; + XMHALF2() = default; - XMSHORTN2() = default; + XMHALF2(const XMHALF2&) = default; + XMHALF2& operator=(const XMHALF2&) = default; - XMSHORTN2(const XMSHORTN2&) = default; - XMSHORTN2& operator=(const XMSHORTN2&) = default; + XMHALF2(XMHALF2&&) = default; + XMHALF2& operator=(XMHALF2&&) = default; - XMSHORTN2(XMSHORTN2&&) = default; - XMSHORTN2& operator=(XMSHORTN2&&) = default; + explicit constexpr XMHALF2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMHALF2(HALF _x, HALF _y) noexcept : x(_x), y(_y) {} + explicit XMHALF2(_In_reads_(2) const HALF* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMHALF2(float _x, float _y) noexcept; + explicit XMHALF2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMSHORTN2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMSHORTN2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} - explicit XMSHORTN2(_In_reads_(2) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMSHORTN2(float _x, float _y) noexcept; - explicit XMSHORTN2(_In_reads_(2) const float* pArray) noexcept; + XMHALF2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORTN2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 2D Vector; 16 bit signed normalized integer components +struct XMSHORTN2 { + union { + struct { + int16_t x; + int16_t y; }; + uint32_t v; + }; - // 2D Vector; 16 bit signed integer components - struct XMSHORT2 - { - union - { - struct - { - int16_t x; - int16_t y; - }; - uint32_t v; - }; + XMSHORTN2() = default; - XMSHORT2() = default; + XMSHORTN2(const XMSHORTN2&) = default; + XMSHORTN2& operator=(const XMSHORTN2&) = default; - XMSHORT2(const XMSHORT2&) = default; - XMSHORT2& operator=(const XMSHORT2&) = default; + XMSHORTN2(XMSHORTN2&&) = default; + XMSHORTN2& operator=(XMSHORTN2&&) = default; - XMSHORT2(XMSHORT2&&) = default; - XMSHORT2& operator=(XMSHORT2&&) = default; + explicit constexpr XMSHORTN2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMSHORTN2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} + explicit XMSHORTN2(_In_reads_(2) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMSHORTN2(float _x, float _y) noexcept; + explicit XMSHORTN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMSHORT2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMSHORT2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} - explicit XMSHORT2(_In_reads_(2) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMSHORT2(float _x, float _y) noexcept; - explicit XMSHORT2(_In_reads_(2) const float* pArray) noexcept; + XMSHORTN2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORT2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 16 bit signed integer components +struct XMSHORT2 { + union { + struct { + int16_t x; + int16_t y; }; + uint32_t v; + }; - // 2D Vector; 16 bit unsigned normalized integer components - struct XMUSHORTN2 - { - union - { - struct - { - uint16_t x; - uint16_t y; - }; - uint32_t v; - }; + XMSHORT2() = default; - XMUSHORTN2() = default; + XMSHORT2(const XMSHORT2&) = default; + XMSHORT2& operator=(const XMSHORT2&) = default; - XMUSHORTN2(const XMUSHORTN2&) = default; - XMUSHORTN2& operator=(const XMUSHORTN2&) = default; + XMSHORT2(XMSHORT2&&) = default; + XMSHORT2& operator=(XMSHORT2&&) = default; - XMUSHORTN2(XMUSHORTN2&&) = default; - XMUSHORTN2& operator=(XMUSHORTN2&&) = default; + explicit constexpr XMSHORT2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMSHORT2(int16_t _x, int16_t _y) noexcept : x(_x), y(_y) {} + explicit XMSHORT2(_In_reads_(2) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMSHORT2(float _x, float _y) noexcept; + explicit XMSHORT2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUSHORTN2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORTN2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} - explicit XMUSHORTN2(_In_reads_(2) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUSHORTN2(float _x, float _y) noexcept; - explicit XMUSHORTN2(_In_reads_(2) const float* pArray) noexcept; + XMSHORT2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORTN2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 16 bit unsigned normalized integer components +struct XMUSHORTN2 { + union { + struct { + uint16_t x; + uint16_t y; }; + uint32_t v; + }; - // 2D Vector; 16 bit unsigned integer components - struct XMUSHORT2 - { - union - { - struct - { - uint16_t x; - uint16_t y; - }; - uint32_t v; - }; + XMUSHORTN2() = default; - XMUSHORT2() = default; + XMUSHORTN2(const XMUSHORTN2&) = default; + XMUSHORTN2& operator=(const XMUSHORTN2&) = default; - XMUSHORT2(const XMUSHORT2&) = default; - XMUSHORT2& operator=(const XMUSHORT2&) = default; + XMUSHORTN2(XMUSHORTN2&&) = default; + XMUSHORTN2& operator=(XMUSHORTN2&&) = default; - XMUSHORT2(XMUSHORT2&&) = default; - XMUSHORT2& operator=(XMUSHORT2&&) = default; + explicit constexpr XMUSHORTN2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORTN2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} + explicit XMUSHORTN2(_In_reads_(2) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUSHORTN2(float _x, float _y) noexcept; + explicit XMUSHORTN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUSHORT2(uint32_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORT2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} - explicit XMUSHORT2(_In_reads_(2) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUSHORT2(float _x, float _y) noexcept; - explicit XMUSHORT2(_In_reads_(2) const float* pArray) noexcept; + XMUSHORTN2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORT2& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 16 bit unsigned integer components +struct XMUSHORT2 { + union { + struct { + uint16_t x; + uint16_t y; }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 2D Vector; 8 bit signed normalized integer components - struct XMBYTEN2 - { - union - { - struct - { - int8_t x; - int8_t y; - }; - uint16_t v; - }; + XMUSHORT2() = default; - XMBYTEN2() = default; + XMUSHORT2(const XMUSHORT2&) = default; + XMUSHORT2& operator=(const XMUSHORT2&) = default; - XMBYTEN2(const XMBYTEN2&) = default; - XMBYTEN2& operator=(const XMBYTEN2&) = default; + XMUSHORT2(XMUSHORT2&&) = default; + XMUSHORT2& operator=(XMUSHORT2&&) = default; - XMBYTEN2(XMBYTEN2&&) = default; - XMBYTEN2& operator=(XMBYTEN2&&) = default; + explicit constexpr XMUSHORT2(uint32_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORT2(uint16_t _x, uint16_t _y) noexcept : x(_x), y(_y) {} + explicit XMUSHORT2(_In_reads_(2) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUSHORT2(float _x, float _y) noexcept; + explicit XMUSHORT2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMBYTEN2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMBYTEN2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} - explicit XMBYTEN2(_In_reads_(2) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMBYTEN2(float _x, float _y) noexcept; - explicit XMBYTEN2(_In_reads_(2) const float* pArray) noexcept; + XMUSHORT2& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMBYTEN2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 2D Vector; 8 bit signed normalized integer components +struct XMBYTEN2 { + union { + struct { + int8_t x; + int8_t y; }; + uint16_t v; + }; - // 2D Vector; 8 bit signed integer components - struct XMBYTE2 - { - union - { - struct - { - int8_t x; - int8_t y; - }; - uint16_t v; - }; + XMBYTEN2() = default; - XMBYTE2() = default; + XMBYTEN2(const XMBYTEN2&) = default; + XMBYTEN2& operator=(const XMBYTEN2&) = default; - XMBYTE2(const XMBYTE2&) = default; - XMBYTE2& operator=(const XMBYTE2&) = default; + XMBYTEN2(XMBYTEN2&&) = default; + XMBYTEN2& operator=(XMBYTEN2&&) = default; - XMBYTE2(XMBYTE2&&) = default; - XMBYTE2& operator=(XMBYTE2&&) = default; + explicit constexpr XMBYTEN2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMBYTEN2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} + explicit XMBYTEN2(_In_reads_(2) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMBYTEN2(float _x, float _y) noexcept; + explicit XMBYTEN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMBYTE2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMBYTE2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} - explicit XMBYTE2(_In_reads_(2) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMBYTE2(float _x, float _y) noexcept; - explicit XMBYTE2(_In_reads_(2) const float* pArray) noexcept; + XMBYTEN2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMBYTE2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 8 bit signed integer components +struct XMBYTE2 { + union { + struct { + int8_t x; + int8_t y; }; + uint16_t v; + }; - // 2D Vector; 8 bit unsigned normalized integer components - struct XMUBYTEN2 - { - union - { - struct - { - uint8_t x; - uint8_t y; - }; - uint16_t v; - }; + XMBYTE2() = default; - XMUBYTEN2() = default; + XMBYTE2(const XMBYTE2&) = default; + XMBYTE2& operator=(const XMBYTE2&) = default; - XMUBYTEN2(const XMUBYTEN2&) = default; - XMUBYTEN2& operator=(const XMUBYTEN2&) = default; + XMBYTE2(XMBYTE2&&) = default; + XMBYTE2& operator=(XMBYTE2&&) = default; - XMUBYTEN2(XMUBYTEN2&&) = default; - XMUBYTEN2& operator=(XMUBYTEN2&&) = default; + explicit constexpr XMBYTE2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMBYTE2(int8_t _x, int8_t _y) noexcept : x(_x), y(_y) {} + explicit XMBYTE2(_In_reads_(2) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMBYTE2(float _x, float _y) noexcept; + explicit XMBYTE2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUBYTEN2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMUBYTEN2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} - explicit XMUBYTEN2(_In_reads_(2) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUBYTEN2(float _x, float _y) noexcept; - explicit XMUBYTEN2(_In_reads_(2) const float* pArray) noexcept; + XMBYTE2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTEN2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 8 bit unsigned normalized integer components +struct XMUBYTEN2 { + union { + struct { + uint8_t x; + uint8_t y; }; + uint16_t v; + }; - // 2D Vector; 8 bit unsigned integer components - struct XMUBYTE2 - { - union - { - struct - { - uint8_t x; - uint8_t y; - }; - uint16_t v; - }; + XMUBYTEN2() = default; - XMUBYTE2() = default; + XMUBYTEN2(const XMUBYTEN2&) = default; + XMUBYTEN2& operator=(const XMUBYTEN2&) = default; - XMUBYTE2(const XMUBYTE2&) = default; - XMUBYTE2& operator=(const XMUBYTE2&) = default; + XMUBYTEN2(XMUBYTEN2&&) = default; + XMUBYTEN2& operator=(XMUBYTEN2&&) = default; - XMUBYTE2(XMUBYTE2&&) = default; - XMUBYTE2& operator=(XMUBYTE2&&) = default; + explicit constexpr XMUBYTEN2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMUBYTEN2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} + explicit XMUBYTEN2(_In_reads_(2) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUBYTEN2(float _x, float _y) noexcept; + explicit XMUBYTEN2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMUBYTE2(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMUBYTE2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} - explicit XMUBYTE2(_In_reads_(2) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]) {} - XMUBYTE2(float _x, float _y) noexcept; - explicit XMUBYTE2(_In_reads_(2) const float* pArray) noexcept; + XMUBYTEN2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTE2& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +// 2D Vector; 8 bit unsigned integer components +struct XMUBYTE2 { + union { + struct { + uint8_t x; + uint8_t y; }; + uint16_t v; + }; - //------------------------------------------------------------------------------ - // 3D vector: 5/6/5 unsigned integer components - struct XMU565 - { - union - { - struct - { - uint16_t x : 5; // 0 to 31 - uint16_t y : 6; // 0 to 63 - uint16_t z : 5; // 0 to 31 - }; - uint16_t v; - }; + XMUBYTE2() = default; - XMU565() = default; + XMUBYTE2(const XMUBYTE2&) = default; + XMUBYTE2& operator=(const XMUBYTE2&) = default; - XMU565(const XMU565&) = default; - XMU565& operator=(const XMU565&) = default; + XMUBYTE2(XMUBYTE2&&) = default; + XMUBYTE2& operator=(XMUBYTE2&&) = default; - XMU565(XMU565&&) = default; - XMU565& operator=(XMU565&&) = default; + explicit constexpr XMUBYTE2(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMUBYTE2(uint8_t _x, uint8_t _y) noexcept : x(_x), y(_y) {} + explicit XMUBYTE2(_In_reads_(2) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]) {} + XMUBYTE2(float _x, float _y) noexcept; + explicit XMUBYTE2(_In_reads_(2) const float* pArray) noexcept; - explicit constexpr XMU565(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMU565(uint8_t _x, uint8_t _y, uint8_t _z) noexcept : x(_x), y(_y), z(_z) {} - explicit XMU565(_In_reads_(3) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} - XMU565(float _x, float _y, float _z) noexcept; - explicit XMU565(_In_reads_(3) const float* pArray) noexcept; + XMUBYTE2& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - operator uint16_t () const noexcept { return v; } - - XMU565& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 3D vector: 5/6/5 unsigned integer components +struct XMU565 { + union { + struct { + uint16_t x : 5; // 0 to 31 + uint16_t y : 6; // 0 to 63 + uint16_t z : 5; // 0 to 31 }; + uint16_t v; + }; - //------------------------------------------------------------------------------ - // 3D vector: 11/11/10 floating-point components - // The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent - // and 6-bit mantissa for x component, a 5-bit biased exponent and - // 6-bit mantissa for y component, a 5-bit biased exponent and a 5-bit - // mantissa for z. The z component is stored in the most significant bits - // and the x component in the least significant bits. No sign bits so - // all partial-precision numbers are positive. - // (Z10Y11X11): [32] ZZZZZzzz zzzYYYYY yyyyyyXX XXXxxxxx [0] - struct XMFLOAT3PK - { - union - { - struct - { - uint32_t xm : 6; // x-mantissa - uint32_t xe : 5; // x-exponent - uint32_t ym : 6; // y-mantissa - uint32_t ye : 5; // y-exponent - uint32_t zm : 5; // z-mantissa - uint32_t ze : 5; // z-exponent - }; - uint32_t v; - }; + XMU565() = default; - XMFLOAT3PK() = default; + XMU565(const XMU565&) = default; + XMU565& operator=(const XMU565&) = default; - XMFLOAT3PK(const XMFLOAT3PK&) = default; - XMFLOAT3PK& operator=(const XMFLOAT3PK&) = default; + XMU565(XMU565&&) = default; + XMU565& operator=(XMU565&&) = default; - XMFLOAT3PK(XMFLOAT3PK&&) = default; - XMFLOAT3PK& operator=(XMFLOAT3PK&&) = default; + explicit constexpr XMU565(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMU565(uint8_t _x, uint8_t _y, uint8_t _z) noexcept + : x(_x), y(_y), z(_z) {} + explicit XMU565(_In_reads_(3) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]) {} + XMU565(float _x, float _y, float _z) noexcept; + explicit XMU565(_In_reads_(3) const float* pArray) noexcept; - explicit constexpr XMFLOAT3PK(uint32_t Packed) noexcept : v(Packed) {} - XMFLOAT3PK(float _x, float _y, float _z) noexcept; - explicit XMFLOAT3PK(_In_reads_(3) const float* pArray) noexcept; + operator uint16_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMU565& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMFLOAT3PK& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 3D vector: 11/11/10 floating-point components +// The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent +// and 6-bit mantissa for x component, a 5-bit biased exponent and +// 6-bit mantissa for y component, a 5-bit biased exponent and a 5-bit +// mantissa for z. The z component is stored in the most significant bits +// and the x component in the least significant bits. No sign bits so +// all partial-precision numbers are positive. +// (Z10Y11X11): [32] ZZZZZzzz zzzYYYYY yyyyyyXX XXXxxxxx [0] +struct XMFLOAT3PK { + union { + struct { + uint32_t xm : 6; // x-mantissa + uint32_t xe : 5; // x-exponent + uint32_t ym : 6; // y-mantissa + uint32_t ye : 5; // y-exponent + uint32_t zm : 5; // z-mantissa + uint32_t ze : 5; // z-exponent }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 3D vector: 9/9/9 floating-point components with shared 5-bit exponent - // The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent - // with 9-bit mantissa for the x, y, and z component. The shared exponent - // is stored in the most significant bits and the x component mantissa is in - // the least significant bits. No sign bits so all partial-precision numbers - // are positive. - // (E5Z9Y9X9): [32] EEEEEzzz zzzzzzyy yyyyyyyx xxxxxxxx [0] - struct XMFLOAT3SE - { - union - { - struct - { - uint32_t xm : 9; // x-mantissa - uint32_t ym : 9; // y-mantissa - uint32_t zm : 9; // z-mantissa - uint32_t e : 5; // shared exponent - }; - uint32_t v; - }; + XMFLOAT3PK() = default; - XMFLOAT3SE() = default; + XMFLOAT3PK(const XMFLOAT3PK&) = default; + XMFLOAT3PK& operator=(const XMFLOAT3PK&) = default; - XMFLOAT3SE(const XMFLOAT3SE&) = default; - XMFLOAT3SE& operator=(const XMFLOAT3SE&) = default; + XMFLOAT3PK(XMFLOAT3PK&&) = default; + XMFLOAT3PK& operator=(XMFLOAT3PK&&) = default; - XMFLOAT3SE(XMFLOAT3SE&&) = default; - XMFLOAT3SE& operator=(XMFLOAT3SE&&) = default; + explicit constexpr XMFLOAT3PK(uint32_t Packed) noexcept : v(Packed) {} + XMFLOAT3PK(float _x, float _y, float _z) noexcept; + explicit XMFLOAT3PK(_In_reads_(3) const float* pArray) noexcept; - explicit constexpr XMFLOAT3SE(uint32_t Packed) noexcept : v(Packed) {} - XMFLOAT3SE(float _x, float _y, float _z) noexcept; - explicit XMFLOAT3SE(_In_reads_(3) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMFLOAT3PK& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMFLOAT3SE& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 3D vector: 9/9/9 floating-point components with shared 5-bit exponent +// The 3D vector is packed into 32 bits as follows: a 5-bit biased exponent +// with 9-bit mantissa for the x, y, and z component. The shared exponent +// is stored in the most significant bits and the x component mantissa is in +// the least significant bits. No sign bits so all partial-precision numbers +// are positive. +// (E5Z9Y9X9): [32] EEEEEzzz zzzzzzyy yyyyyyyx xxxxxxxx [0] +struct XMFLOAT3SE { + union { + struct { + uint32_t xm : 9; // x-mantissa + uint32_t ym : 9; // y-mantissa + uint32_t zm : 9; // z-mantissa + uint32_t e : 5; // shared exponent }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 16 bit floating point components - struct XMHALF4 - { - union - { - struct - { - HALF x; - HALF y; - HALF z; - HALF w; - }; - uint64_t v; - }; + XMFLOAT3SE() = default; - XMHALF4() = default; + XMFLOAT3SE(const XMFLOAT3SE&) = default; + XMFLOAT3SE& operator=(const XMFLOAT3SE&) = default; - XMHALF4(const XMHALF4&) = default; - XMHALF4& operator=(const XMHALF4&) = default; + XMFLOAT3SE(XMFLOAT3SE&&) = default; + XMFLOAT3SE& operator=(XMFLOAT3SE&&) = default; - XMHALF4(XMHALF4&&) = default; - XMHALF4& operator=(XMHALF4&&) = default; + explicit constexpr XMFLOAT3SE(uint32_t Packed) noexcept : v(Packed) {} + XMFLOAT3SE(float _x, float _y, float _z) noexcept; + explicit XMFLOAT3SE(_In_reads_(3) const float* pArray) noexcept; - explicit constexpr XMHALF4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMHALF4(HALF _x, HALF _y, HALF _z, HALF _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMHALF4(_In_reads_(4) const HALF* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMHALF4(float _x, float _y, float _z, float _w) noexcept; - explicit XMHALF4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - XMHALF4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } + XMFLOAT3SE& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; + +//------------------------------------------------------------------------------ +// 4D Vector; 16 bit floating point components +struct XMHALF4 { + union { + struct { + HALF x; + HALF y; + HALF z; + HALF w; }; + uint64_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 16 bit signed normalized integer components - struct XMSHORTN4 - { - union - { - struct - { - int16_t x; - int16_t y; - int16_t z; - int16_t w; - }; - uint64_t v; - }; + XMHALF4() = default; - XMSHORTN4() = default; + XMHALF4(const XMHALF4&) = default; + XMHALF4& operator=(const XMHALF4&) = default; - XMSHORTN4(const XMSHORTN4&) = default; - XMSHORTN4& operator=(const XMSHORTN4&) = default; + XMHALF4(XMHALF4&&) = default; + XMHALF4& operator=(XMHALF4&&) = default; - XMSHORTN4(XMSHORTN4&&) = default; - XMSHORTN4& operator=(XMSHORTN4&&) = default; + explicit constexpr XMHALF4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMHALF4(HALF _x, HALF _y, HALF _z, HALF _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMHALF4(_In_reads_(4) const HALF* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMHALF4(float _x, float _y, float _z, float _w) noexcept; + explicit XMHALF4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMSHORTN4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMSHORTN4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMSHORTN4(_In_reads_(4) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMSHORTN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMSHORTN4(_In_reads_(4) const float* pArray) noexcept; + XMHALF4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORTN4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D Vector; 16 bit signed normalized integer components +struct XMSHORTN4 { + union { + struct { + int16_t x; + int16_t y; + int16_t z; + int16_t w; }; + uint64_t v; + }; - // 4D Vector; 16 bit signed integer components - struct XMSHORT4 - { - union - { - struct - { - int16_t x; - int16_t y; - int16_t z; - int16_t w; - }; - uint64_t v; - }; + XMSHORTN4() = default; - XMSHORT4() = default; + XMSHORTN4(const XMSHORTN4&) = default; + XMSHORTN4& operator=(const XMSHORTN4&) = default; - XMSHORT4(const XMSHORT4&) = default; - XMSHORT4& operator=(const XMSHORT4&) = default; + XMSHORTN4(XMSHORTN4&&) = default; + XMSHORTN4& operator=(XMSHORTN4&&) = default; - XMSHORT4(XMSHORT4&&) = default; - XMSHORT4& operator=(XMSHORT4&&) = default; + explicit constexpr XMSHORTN4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMSHORTN4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMSHORTN4(_In_reads_(4) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMSHORTN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMSHORTN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMSHORT4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMSHORT4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMSHORT4(_In_reads_(4) const int16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMSHORT4(float _x, float _y, float _z, float _w) noexcept; - explicit XMSHORT4(_In_reads_(4) const float* pArray) noexcept; + XMSHORTN4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMSHORT4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 16 bit signed integer components +struct XMSHORT4 { + union { + struct { + int16_t x; + int16_t y; + int16_t z; + int16_t w; }; + uint64_t v; + }; - // 4D Vector; 16 bit unsigned normalized integer components - struct XMUSHORTN4 - { - union - { - struct - { - uint16_t x; - uint16_t y; - uint16_t z; - uint16_t w; - }; - uint64_t v; - }; + XMSHORT4() = default; - XMUSHORTN4() = default; + XMSHORT4(const XMSHORT4&) = default; + XMSHORT4& operator=(const XMSHORT4&) = default; - XMUSHORTN4(const XMUSHORTN4&) = default; - XMUSHORTN4& operator=(const XMUSHORTN4&) = default; + XMSHORT4(XMSHORT4&&) = default; + XMSHORT4& operator=(XMSHORT4&&) = default; - XMUSHORTN4(XMUSHORTN4&&) = default; - XMUSHORTN4& operator=(XMUSHORTN4&&) = default; + explicit constexpr XMSHORT4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMSHORT4(int16_t _x, int16_t _y, int16_t _z, int16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMSHORT4(_In_reads_(4) const int16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMSHORT4(float _x, float _y, float _z, float _w) noexcept; + explicit XMSHORT4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUSHORTN4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORTN4(uint16_t _x, uint16_t _y, uint16_t _z, uint16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUSHORTN4(_In_reads_(4) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUSHORTN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUSHORTN4(_In_reads_(4) const float* pArray) noexcept; + XMSHORT4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORTN4& operator= (uint64_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 16 bit unsigned normalized integer components +struct XMUSHORTN4 { + union { + struct { + uint16_t x; + uint16_t y; + uint16_t z; + uint16_t w; }; + uint64_t v; + }; - // 4D Vector; 16 bit unsigned integer components - struct XMUSHORT4 - { - union - { - struct - { - uint16_t x; - uint16_t y; - uint16_t z; - uint16_t w; - }; - uint64_t v; - }; + XMUSHORTN4() = default; - XMUSHORT4() = default; + XMUSHORTN4(const XMUSHORTN4&) = default; + XMUSHORTN4& operator=(const XMUSHORTN4&) = default; - XMUSHORT4(const XMUSHORT4&) = default; - XMUSHORT4& operator=(const XMUSHORT4&) = default; + XMUSHORTN4(XMUSHORTN4&&) = default; + XMUSHORTN4& operator=(XMUSHORTN4&&) = default; - XMUSHORT4(XMUSHORT4&&) = default; - XMUSHORT4& operator=(XMUSHORT4&&) = default; + explicit constexpr XMUSHORTN4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORTN4(uint16_t _x, uint16_t _y, uint16_t _z, + uint16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUSHORTN4(_In_reads_(4) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUSHORTN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUSHORTN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUSHORT4(uint64_t Packed) noexcept : v(Packed) {} - constexpr XMUSHORT4(uint16_t _x, uint16_t _y, uint16_t _z, uint16_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUSHORT4(_In_reads_(4) const uint16_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUSHORT4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUSHORT4(_In_reads_(4) const float* pArray) noexcept; + XMUSHORTN4& operator=(uint64_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUSHORT4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 16 bit unsigned integer components +struct XMUSHORT4 { + union { + struct { + uint16_t x; + uint16_t y; + uint16_t z; + uint16_t w; }; + uint64_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, - // normalized integer for the w component and 10 bit signed, normalized - // integers for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XMXDECN4 - { - union - { - struct - { - int32_t x : 10; // -511/511 to 511/511 - int32_t y : 10; // -511/511 to 511/511 - int32_t z : 10; // -511/511 to 511/511 - uint32_t w : 2; // 0/3 to 3/3 - }; - uint32_t v; - }; + XMUSHORT4() = default; - XMXDECN4() = default; + XMUSHORT4(const XMUSHORT4&) = default; + XMUSHORT4& operator=(const XMUSHORT4&) = default; - XMXDECN4(const XMXDECN4&) = default; - XMXDECN4& operator=(const XMXDECN4&) = default; + XMUSHORT4(XMUSHORT4&&) = default; + XMUSHORT4& operator=(XMUSHORT4&&) = default; - XMXDECN4(XMXDECN4&&) = default; - XMXDECN4& operator=(XMXDECN4&&) = default; + explicit constexpr XMUSHORT4(uint64_t Packed) noexcept : v(Packed) {} + constexpr XMUSHORT4(uint16_t _x, uint16_t _y, uint16_t _z, + uint16_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUSHORT4(_In_reads_(4) const uint16_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUSHORT4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUSHORT4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMXDECN4(uint32_t Packed) : v(Packed) {} - XMXDECN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMXDECN4(_In_reads_(4) const float* pArray) noexcept; + XMUSHORT4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - operator uint32_t () const noexcept { return v; } - - XMXDECN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, +// normalized integer for the w component and 10 bit signed, normalized +// integers for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XMXDECN4 { + union { + struct { + int32_t x : 10; // -511/511 to 511/511 + int32_t y : 10; // -511/511 to 511/511 + int32_t z : 10; // -511/511 to 511/511 + uint32_t w : 2; // 0/3 to 3/3 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned - // integer for the w component and 10 bit signed integers for the - // z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XM_DEPRECATED XMXDEC4 - { - union - { - struct - { - int32_t x : 10; // -511 to 511 - int32_t y : 10; // -511 to 511 - int32_t z : 10; // -511 to 511 - uint32_t w : 2; // 0 to 3 - }; - uint32_t v; - }; + XMXDECN4() = default; - XMXDEC4() = default; + XMXDECN4(const XMXDECN4&) = default; + XMXDECN4& operator=(const XMXDECN4&) = default; - XMXDEC4(const XMXDEC4&) = default; - XMXDEC4& operator=(const XMXDEC4&) = default; + XMXDECN4(XMXDECN4&&) = default; + XMXDECN4& operator=(XMXDECN4&&) = default; - XMXDEC4(XMXDEC4&&) = default; - XMXDEC4& operator=(XMXDEC4&&) = default; + explicit constexpr XMXDECN4(uint32_t Packed) : v(Packed) {} + XMXDECN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMXDECN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMXDEC4(uint32_t Packed) noexcept : v(Packed) {} - XMXDEC4(float _x, float _y, float _z, float _w) noexcept; - explicit XMXDEC4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMXDECN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMXDEC4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned +// integer for the w component and 10 bit signed integers for the +// z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XM_DEPRECATED XMXDEC4 { + union { + struct { + int32_t x : 10; // -511 to 511 + int32_t y : 10; // -511 to 511 + int32_t z : 10; // -511 to 511 + uint32_t w : 2; // 0 to 3 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit signed, - // normalized integer for the w component and 10 bit signed, normalized - // integers for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XM_DEPRECATED XMDECN4 - { - union - { - struct - { - int32_t x : 10; // -511/511 to 511/511 - int32_t y : 10; // -511/511 to 511/511 - int32_t z : 10; // -511/511 to 511/511 - int32_t w : 2; // -1/1 to 1/1 - }; - uint32_t v; - }; + XMXDEC4() = default; - XMDECN4() = default; + XMXDEC4(const XMXDEC4&) = default; + XMXDEC4& operator=(const XMXDEC4&) = default; - XMDECN4(const XMDECN4&) = default; - XMDECN4& operator=(const XMDECN4&) = default; + XMXDEC4(XMXDEC4&&) = default; + XMXDEC4& operator=(XMXDEC4&&) = default; - XMDECN4(XMDECN4&&) = default; - XMDECN4& operator=(XMDECN4&&) = default; + explicit constexpr XMXDEC4(uint32_t Packed) noexcept : v(Packed) {} + XMXDEC4(float _x, float _y, float _z, float _w) noexcept; + explicit XMXDEC4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMDECN4(uint32_t Packed) noexcept : v(Packed) {} - XMDECN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMDECN4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMXDEC4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMDECN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit signed, +// normalized integer for the w component and 10 bit signed, normalized +// integers for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XM_DEPRECATED XMDECN4 { + union { + struct { + int32_t x : 10; // -511/511 to 511/511 + int32_t y : 10; // -511/511 to 511/511 + int32_t z : 10; // -511/511 to 511/511 + int32_t w : 2; // -1/1 to 1/1 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer - // The 4D Vector is packed into 32 bits as follows: a 2 bit signed, - // integer for the w component and 10 bit signed integers for the - // z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XM_DEPRECATED XMDEC4 - { - union - { - struct - { - int32_t x : 10; // -511 to 511 - int32_t y : 10; // -511 to 511 - int32_t z : 10; // -511 to 511 - int32_t w : 2; // -1 to 1 - }; - uint32_t v; - }; + XMDECN4() = default; - XMDEC4() = default; + XMDECN4(const XMDECN4&) = default; + XMDECN4& operator=(const XMDECN4&) = default; - XMDEC4(const XMDEC4&) = default; - XMDEC4& operator=(const XMDEC4&) = default; + XMDECN4(XMDECN4&&) = default; + XMDECN4& operator=(XMDECN4&&) = default; - XMDEC4(XMDEC4&&) = default; - XMDEC4& operator=(XMDEC4&&) = default; + explicit constexpr XMDECN4(uint32_t Packed) noexcept : v(Packed) {} + XMDECN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMDECN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMDEC4(uint32_t Packed) noexcept : v(Packed) {} - XMDEC4(float _x, float _y, float _z, float _w) noexcept; - explicit XMDEC4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMDECN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMDEC4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer +// The 4D Vector is packed into 32 bits as follows: a 2 bit signed, +// integer for the w component and 10 bit signed integers for the +// z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XM_DEPRECATED XMDEC4 { + union { + struct { + int32_t x : 10; // -511 to 511 + int32_t y : 10; // -511 to 511 + int32_t z : 10; // -511 to 511 + int32_t w : 2; // -1 to 1 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer - // The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, - // normalized integer for the w component and 10 bit unsigned, normalized - // integers for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XMUDECN4 - { - union - { - struct - { - uint32_t x : 10; // 0/1023 to 1023/1023 - uint32_t y : 10; // 0/1023 to 1023/1023 - uint32_t z : 10; // 0/1023 to 1023/1023 - uint32_t w : 2; // 0/3 to 3/3 - }; - uint32_t v; - }; + XMDEC4() = default; - XMUDECN4() = default; + XMDEC4(const XMDEC4&) = default; + XMDEC4& operator=(const XMDEC4&) = default; - XMUDECN4(const XMUDECN4&) = default; - XMUDECN4& operator=(const XMUDECN4&) = default; + XMDEC4(XMDEC4&&) = default; + XMDEC4& operator=(XMDEC4&&) = default; - XMUDECN4(XMUDECN4&&) = default; - XMUDECN4& operator=(XMUDECN4&&) = default; + explicit constexpr XMDEC4(uint32_t Packed) noexcept : v(Packed) {} + XMDEC4(float _x, float _y, float _z, float _w) noexcept; + explicit XMDEC4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUDECN4(uint32_t Packed) noexcept : v(Packed) {} - XMUDECN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUDECN4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMDEC4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUDECN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit normalized components packed into a 32 bit integer +// The normalized 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, +// normalized integer for the w component and 10 bit unsigned, normalized +// integers for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XMUDECN4 { + union { + struct { + uint32_t x : 10; // 0/1023 to 1023/1023 + uint32_t y : 10; // 0/1023 to 1023/1023 + uint32_t z : 10; // 0/1023 to 1023/1023 + uint32_t w : 2; // 0/3 to 3/3 }; + uint32_t v; + }; - // 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer - // The 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, - // integer for the w component and 10 bit unsigned integers - // for the z, y, and x components. The w component is stored in the - // most significant bits and the x component in the least significant bits - // (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] - struct XMUDEC4 - { - union - { - struct - { - uint32_t x : 10; // 0 to 1023 - uint32_t y : 10; // 0 to 1023 - uint32_t z : 10; // 0 to 1023 - uint32_t w : 2; // 0 to 3 - }; - uint32_t v; - }; + XMUDECN4() = default; - XMUDEC4() = default; + XMUDECN4(const XMUDECN4&) = default; + XMUDECN4& operator=(const XMUDECN4&) = default; - XMUDEC4(const XMUDEC4&) = default; - XMUDEC4& operator=(const XMUDEC4&) = default; + XMUDECN4(XMUDECN4&&) = default; + XMUDECN4& operator=(XMUDECN4&&) = default; - XMUDEC4(XMUDEC4&&) = default; - XMUDEC4& operator=(XMUDEC4&&) = default; + explicit constexpr XMUDECN4(uint32_t Packed) noexcept : v(Packed) {} + XMUDECN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUDECN4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUDEC4(uint32_t Packed) noexcept : v(Packed) {} - XMUDEC4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUDEC4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - operator uint32_t () const noexcept { return v; } + XMUDECN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUDEC4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 10-10-10-2 bit components packed into a 32 bit integer +// The 4D Vector is packed into 32 bits as follows: a 2 bit unsigned, +// integer for the w component and 10 bit unsigned integers +// for the z, y, and x components. The w component is stored in the +// most significant bits and the x component in the least significant bits +// (W2Z10Y10X10): [32] wwzzzzzz zzzzyyyy yyyyyyxx xxxxxxxx [0] +struct XMUDEC4 { + union { + struct { + uint32_t x : 10; // 0 to 1023 + uint32_t y : 10; // 0 to 1023 + uint32_t z : 10; // 0 to 1023 + uint32_t w : 2; // 0 to 3 }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 4D Vector; 8 bit signed normalized integer components - struct XMBYTEN4 - { - union - { - struct - { - int8_t x; - int8_t y; - int8_t z; - int8_t w; - }; - uint32_t v; - }; + XMUDEC4() = default; - XMBYTEN4() = default; + XMUDEC4(const XMUDEC4&) = default; + XMUDEC4& operator=(const XMUDEC4&) = default; - XMBYTEN4(const XMBYTEN4&) = default; - XMBYTEN4& operator=(const XMBYTEN4&) = default; + XMUDEC4(XMUDEC4&&) = default; + XMUDEC4& operator=(XMUDEC4&&) = default; - XMBYTEN4(XMBYTEN4&&) = default; - XMBYTEN4& operator=(XMBYTEN4&&) = default; + explicit constexpr XMUDEC4(uint32_t Packed) noexcept : v(Packed) {} + XMUDEC4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUDEC4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMBYTEN4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMBYTEN4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMBYTEN4(_In_reads_(4) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMBYTEN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMBYTEN4(_In_reads_(4) const float* pArray) noexcept; + operator uint32_t() const noexcept { return v; } - XMBYTEN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } + XMUDEC4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; + +//------------------------------------------------------------------------------ +// 4D Vector; 8 bit signed normalized integer components +struct XMBYTEN4 { + union { + struct { + int8_t x; + int8_t y; + int8_t z; + int8_t w; }; + uint32_t v; + }; - // 4D Vector; 8 bit signed integer components - struct XMBYTE4 - { - union - { - struct - { - int8_t x; - int8_t y; - int8_t z; - int8_t w; - }; - uint32_t v; - }; + XMBYTEN4() = default; - XMBYTE4() = default; + XMBYTEN4(const XMBYTEN4&) = default; + XMBYTEN4& operator=(const XMBYTEN4&) = default; - XMBYTE4(const XMBYTE4&) = default; - XMBYTE4& operator=(const XMBYTE4&) = default; + XMBYTEN4(XMBYTEN4&&) = default; + XMBYTEN4& operator=(XMBYTEN4&&) = default; - XMBYTE4(XMBYTE4&&) = default; - XMBYTE4& operator=(XMBYTE4&&) = default; + constexpr XMBYTEN4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMBYTEN4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMBYTEN4(_In_reads_(4) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMBYTEN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMBYTEN4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMBYTE4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMBYTE4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMBYTE4(_In_reads_(4) const int8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMBYTE4(float _x, float _y, float _z, float _w) noexcept; - explicit XMBYTE4(_In_reads_(4) const float* pArray) noexcept; + XMBYTEN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMBYTE4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 8 bit signed integer components +struct XMBYTE4 { + union { + struct { + int8_t x; + int8_t y; + int8_t z; + int8_t w; }; + uint32_t v; + }; - // 4D Vector; 8 bit unsigned normalized integer components - struct XMUBYTEN4 - { - union - { - struct - { - uint8_t x; - uint8_t y; - uint8_t z; - uint8_t w; - }; - uint32_t v; - }; + XMBYTE4() = default; - XMUBYTEN4() = default; + XMBYTE4(const XMBYTE4&) = default; + XMBYTE4& operator=(const XMBYTE4&) = default; - XMUBYTEN4(const XMUBYTEN4&) = default; - XMUBYTEN4& operator=(const XMUBYTEN4&) = default; + XMBYTE4(XMBYTE4&&) = default; + XMBYTE4& operator=(XMBYTE4&&) = default; - XMUBYTEN4(XMUBYTEN4&&) = default; - XMUBYTEN4& operator=(XMUBYTEN4&&) = default; + constexpr XMBYTE4(int8_t _x, int8_t _y, int8_t _z, int8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMBYTE4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMBYTE4(_In_reads_(4) const int8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMBYTE4(float _x, float _y, float _z, float _w) noexcept; + explicit XMBYTE4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMUBYTEN4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMUBYTEN4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMUBYTEN4(_In_reads_(4) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUBYTEN4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUBYTEN4(_In_reads_(4) const float* pArray) noexcept; + XMBYTE4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTEN4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 8 bit unsigned normalized integer components +struct XMUBYTEN4 { + union { + struct { + uint8_t x; + uint8_t y; + uint8_t z; + uint8_t w; }; + uint32_t v; + }; - // 4D Vector; 8 bit unsigned integer components - struct XMUBYTE4 - { - union - { - struct - { - uint8_t x; - uint8_t y; - uint8_t z; - uint8_t w; - }; - uint32_t v; - }; + XMUBYTEN4() = default; - XMUBYTE4() = default; + XMUBYTEN4(const XMUBYTEN4&) = default; + XMUBYTEN4& operator=(const XMUBYTEN4&) = default; - XMUBYTE4(const XMUBYTE4&) = default; - XMUBYTE4& operator=(const XMUBYTE4&) = default; + XMUBYTEN4(XMUBYTEN4&&) = default; + XMUBYTEN4& operator=(XMUBYTEN4&&) = default; - XMUBYTE4(XMUBYTE4&&) = default; - XMUBYTE4& operator=(XMUBYTE4&&) = default; + constexpr XMUBYTEN4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMUBYTEN4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMUBYTEN4(_In_reads_(4) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUBYTEN4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUBYTEN4(_In_reads_(4) const float* pArray) noexcept; - constexpr XMUBYTE4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit constexpr XMUBYTE4(uint32_t Packed) noexcept : v(Packed) {} - explicit XMUBYTE4(_In_reads_(4) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUBYTE4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUBYTE4(_In_reads_(4) const float* pArray) noexcept; + XMUBYTEN4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMUBYTE4& operator= (uint32_t Packed) noexcept { v = Packed; return *this; } +// 4D Vector; 8 bit unsigned integer components +struct XMUBYTE4 { + union { + struct { + uint8_t x; + uint8_t y; + uint8_t z; + uint8_t w; }; + uint32_t v; + }; - //------------------------------------------------------------------------------ - // 4D vector; 4 bit unsigned integer components - struct XMUNIBBLE4 - { - union - { - struct - { - uint16_t x : 4; // 0 to 15 - uint16_t y : 4; // 0 to 15 - uint16_t z : 4; // 0 to 15 - uint16_t w : 4; // 0 to 15 - }; - uint16_t v; - }; + XMUBYTE4() = default; - XMUNIBBLE4() = default; + XMUBYTE4(const XMUBYTE4&) = default; + XMUBYTE4& operator=(const XMUBYTE4&) = default; - XMUNIBBLE4(const XMUNIBBLE4&) = default; - XMUNIBBLE4& operator=(const XMUNIBBLE4&) = default; + XMUBYTE4(XMUBYTE4&&) = default; + XMUBYTE4& operator=(XMUBYTE4&&) = default; - XMUNIBBLE4(XMUNIBBLE4&&) = default; - XMUNIBBLE4& operator=(XMUNIBBLE4&&) = default; + constexpr XMUBYTE4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit constexpr XMUBYTE4(uint32_t Packed) noexcept : v(Packed) {} + explicit XMUBYTE4(_In_reads_(4) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUBYTE4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUBYTE4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMUNIBBLE4(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMUNIBBLE4(uint8_t _x, uint8_t _y, uint8_t _z, uint8_t _w) noexcept : x(_x), y(_y), z(_z), w(_w) {} - explicit XMUNIBBLE4(_In_reads_(4) const uint8_t* pArray) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} - XMUNIBBLE4(float _x, float _y, float _z, float _w) noexcept; - explicit XMUNIBBLE4(_In_reads_(4) const float* pArray) noexcept; + XMUBYTE4& operator=(uint32_t Packed) noexcept { + v = Packed; + return *this; + } +}; - operator uint16_t () const noexcept { return v; } - - XMUNIBBLE4& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D vector; 4 bit unsigned integer components +struct XMUNIBBLE4 { + union { + struct { + uint16_t x : 4; // 0 to 15 + uint16_t y : 4; // 0 to 15 + uint16_t z : 4; // 0 to 15 + uint16_t w : 4; // 0 to 15 }; + uint16_t v; + }; - //------------------------------------------------------------------------------ - // 4D vector: 5/5/5/1 unsigned integer components - struct XMU555 - { - union - { - struct - { - uint16_t x : 5; // 0 to 31 - uint16_t y : 5; // 0 to 31 - uint16_t z : 5; // 0 to 31 - uint16_t w : 1; // 0 or 1 - }; - uint16_t v; - }; + XMUNIBBLE4() = default; - XMU555() = default; + XMUNIBBLE4(const XMUNIBBLE4&) = default; + XMUNIBBLE4& operator=(const XMUNIBBLE4&) = default; - XMU555(const XMU555&) = default; - XMU555& operator=(const XMU555&) = default; + XMUNIBBLE4(XMUNIBBLE4&&) = default; + XMUNIBBLE4& operator=(XMUNIBBLE4&&) = default; - XMU555(XMU555&&) = default; - XMU555& operator=(XMU555&&) = default; + explicit constexpr XMUNIBBLE4(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMUNIBBLE4(uint8_t _x, uint8_t _y, uint8_t _z, + uint8_t _w) noexcept + : x(_x), y(_y), z(_z), w(_w) {} + explicit XMUNIBBLE4(_In_reads_(4) const uint8_t* pArray) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(pArray[3]) {} + XMUNIBBLE4(float _x, float _y, float _z, float _w) noexcept; + explicit XMUNIBBLE4(_In_reads_(4) const float* pArray) noexcept; - explicit constexpr XMU555(uint16_t Packed) noexcept : v(Packed) {} - constexpr XMU555(uint8_t _x, uint8_t _y, uint8_t _z, bool _w) noexcept : x(_x), y(_y), z(_z), w(_w ? 0x1 : 0) {} - XMU555(_In_reads_(3) const uint8_t* pArray, _In_ bool _w) noexcept : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(_w ? 0x1 : 0) {} - XMU555(float _x, float _y, float _z, bool _w) noexcept; - XMU555(_In_reads_(3) const float* pArray, _In_ bool _w) noexcept; + operator uint16_t() const noexcept { return v; } - operator uint16_t () const noexcept { return v; } + XMUNIBBLE4& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMU555& operator= (uint16_t Packed) noexcept { v = Packed; return *this; } +//------------------------------------------------------------------------------ +// 4D vector: 5/5/5/1 unsigned integer components +struct XMU555 { + union { + struct { + uint16_t x : 5; // 0 to 31 + uint16_t y : 5; // 0 to 31 + uint16_t z : 5; // 0 to 31 + uint16_t w : 1; // 0 or 1 }; + uint16_t v; + }; - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif + XMU555() = default; - /**************************************************************************** - * - * Data conversion operations - * - ****************************************************************************/ + XMU555(const XMU555&) = default; + XMU555& operator=(const XMU555&) = default; - float XMConvertHalfToFloat(HALF Value) noexcept; - float* XMConvertHalfToFloatStream(_Out_writes_bytes_(sizeof(float) + OutputStride * (HalfCount - 1)) float* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(HALF) + InputStride * (HalfCount - 1)) const HALF* pInputStream, - _In_ size_t InputStride, _In_ size_t HalfCount) noexcept; - HALF XMConvertFloatToHalf(float Value) noexcept; - HALF* XMConvertFloatToHalfStream(_Out_writes_bytes_(sizeof(HALF) + OutputStride * (FloatCount - 1)) HALF* pOutputStream, - _In_ size_t OutputStride, - _In_reads_bytes_(sizeof(float) + InputStride * (FloatCount - 1)) const float* pInputStream, - _In_ size_t InputStride, _In_ size_t FloatCount) noexcept; + XMU555(XMU555&&) = default; + XMU555& operator=(XMU555&&) = default; - /**************************************************************************** - * - * Load operations - * - ****************************************************************************/ + explicit constexpr XMU555(uint16_t Packed) noexcept : v(Packed) {} + constexpr XMU555(uint8_t _x, uint8_t _y, uint8_t _z, bool _w) noexcept + : x(_x), y(_y), z(_z), w(_w ? 0x1 : 0) {} + XMU555(_In_reads_(3) const uint8_t* pArray, _In_ bool _w) noexcept + : x(pArray[0]), y(pArray[1]), z(pArray[2]), w(_w ? 0x1 : 0) {} + XMU555(float _x, float _y, float _z, bool _w) noexcept; + XMU555(_In_reads_(3) const float* pArray, _In_ bool _w) noexcept; - XMVECTOR XM_CALLCONV XMLoadColor(_In_ const XMCOLOR* pSource) noexcept; + operator uint16_t() const noexcept { return v; } - XMVECTOR XM_CALLCONV XMLoadHalf2(_In_ const XMHALF2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShortN2(_In_ const XMSHORTN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShort2(_In_ const XMSHORT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShortN2(_In_ const XMUSHORTN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShort2(_In_ const XMUSHORT2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByteN2(_In_ const XMBYTEN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByte2(_In_ const XMBYTE2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByteN2(_In_ const XMUBYTEN2* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByte2(_In_ const XMUBYTE2* pSource) noexcept; + XMU555& operator=(uint16_t Packed) noexcept { + v = Packed; + return *this; + } +}; - XMVECTOR XM_CALLCONV XMLoadU565(_In_ const XMU565* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3PK(_In_ const XMFLOAT3PK* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadFloat3SE(_In_ const XMFLOAT3SE* pSource) noexcept; +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif - XMVECTOR XM_CALLCONV XMLoadHalf4(_In_ const XMHALF4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShortN4(_In_ const XMSHORTN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadShort4(_In_ const XMSHORT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShortN4(_In_ const XMUSHORTN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUShort4(_In_ const XMUSHORT4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadXDecN4(_In_ const XMXDECN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUDecN4(_In_ const XMUDECN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUDecN4_XR(_In_ const XMUDECN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUDec4(_In_ const XMUDEC4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByteN4(_In_ const XMBYTEN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadByte4(_In_ const XMBYTE4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByteN4(_In_ const XMUBYTEN4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUByte4(_In_ const XMUBYTE4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadUNibble4(_In_ const XMUNIBBLE4* pSource) noexcept; - XMVECTOR XM_CALLCONV XMLoadU555(_In_ const XMU555* pSource) noexcept; +/**************************************************************************** + * + * Data conversion operations + * + ****************************************************************************/ - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable : 4996) - // C4996: ignore deprecation warning - #endif +float XMConvertHalfToFloat(HALF Value) noexcept; +float* XMConvertHalfToFloatStream( + _Out_writes_bytes_(sizeof(float) + + OutputStride * (HalfCount - 1)) float* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(HALF) + InputStride * (HalfCount - 1)) + const HALF* pInputStream, + _In_ size_t InputStride, _In_ size_t HalfCount) noexcept; +HALF XMConvertFloatToHalf(float Value) noexcept; +HALF* XMConvertFloatToHalfStream( + _Out_writes_bytes_(sizeof(HALF) + OutputStride * (FloatCount - 1)) + HALF* pOutputStream, + _In_ size_t OutputStride, + _In_reads_bytes_(sizeof(float) + InputStride * (FloatCount - 1)) + const float* pInputStream, + _In_ size_t InputStride, _In_ size_t FloatCount) noexcept; - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #endif +/**************************************************************************** + * + * Load operations + * + ****************************************************************************/ - #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +XMVECTOR XM_CALLCONV XMLoadColor(_In_ const XMCOLOR* pSource) noexcept; - XM_DEPRECATED - XMVECTOR XM_CALLCONV XMLoadDecN4(_In_ const XMDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadHalf2(_In_ const XMHALF2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShortN2(_In_ const XMSHORTN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShort2(_In_ const XMSHORT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShortN2(_In_ const XMUSHORTN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShort2(_In_ const XMUSHORT2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByteN2(_In_ const XMBYTEN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByte2(_In_ const XMBYTE2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByteN2(_In_ const XMUBYTEN2* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByte2(_In_ const XMUBYTE2* pSource) noexcept; - XM_DEPRECATED - XMVECTOR XM_CALLCONV XMLoadDec4(_In_ const XMDEC4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadU565(_In_ const XMU565* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3PK(_In_ const XMFLOAT3PK* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadFloat3SE(_In_ const XMFLOAT3SE* pSource) noexcept; - XM_DEPRECATED - XMVECTOR XM_CALLCONV XMLoadXDec4(_In_ const XMXDEC4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadHalf4(_In_ const XMHALF4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShortN4(_In_ const XMSHORTN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadShort4(_In_ const XMSHORT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShortN4(_In_ const XMUSHORTN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUShort4(_In_ const XMUSHORT4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadXDecN4(_In_ const XMXDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUDecN4(_In_ const XMUDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUDecN4_XR(_In_ const XMUDECN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUDec4(_In_ const XMUDEC4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByteN4(_In_ const XMBYTEN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadByte4(_In_ const XMBYTE4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByteN4(_In_ const XMUBYTEN4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUByte4(_In_ const XMUBYTE4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadUNibble4(_In_ const XMUNIBBLE4* pSource) noexcept; +XMVECTOR XM_CALLCONV XMLoadU555(_In_ const XMU555* pSource) noexcept; - #ifdef __GNUC__ - #pragma GCC diagnostic pop - #endif - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4996) +// C4996: ignore deprecation warning +#endif - /**************************************************************************** - * - * Store operations - * - ****************************************************************************/ +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#endif - void XM_CALLCONV XMStoreColor(_Out_ XMCOLOR* pDestination, _In_ FXMVECTOR V) noexcept; +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif - void XM_CALLCONV XMStoreHalf2(_Out_ XMHALF2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShortN2(_Out_ XMSHORTN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShort2(_Out_ XMSHORT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShortN2(_Out_ XMUSHORTN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShort2(_Out_ XMUSHORT2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByteN2(_Out_ XMBYTEN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByte2(_Out_ XMBYTE2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByteN2(_Out_ XMUBYTEN2* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByte2(_Out_ XMUBYTE2* pDestination, _In_ FXMVECTOR V) noexcept; +XM_DEPRECATED +XMVECTOR XM_CALLCONV XMLoadDecN4(_In_ const XMDECN4* pSource) noexcept; - void XM_CALLCONV XMStoreU565(_Out_ XMU565* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3PK(_Out_ XMFLOAT3PK* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreFloat3SE(_Out_ XMFLOAT3SE* pDestination, _In_ FXMVECTOR V) noexcept; +XM_DEPRECATED +XMVECTOR XM_CALLCONV XMLoadDec4(_In_ const XMDEC4* pSource) noexcept; - void XM_CALLCONV XMStoreHalf4(_Out_ XMHALF4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShortN4(_Out_ XMSHORTN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreShort4(_Out_ XMSHORT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShortN4(_Out_ XMUSHORTN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUShort4(_Out_ XMUSHORT4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreXDecN4(_Out_ XMXDECN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUDecN4(_Out_ XMUDECN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUDecN4_XR(_Out_ XMUDECN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUDec4(_Out_ XMUDEC4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByteN4(_Out_ XMBYTEN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreByte4(_Out_ XMBYTE4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByteN4(_Out_ XMUBYTEN4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUByte4(_Out_ XMUBYTE4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreUNibble4(_Out_ XMUNIBBLE4* pDestination, _In_ FXMVECTOR V) noexcept; - void XM_CALLCONV XMStoreU555(_Out_ XMU555* pDestination, _In_ FXMVECTOR V) noexcept; +XM_DEPRECATED +XMVECTOR XM_CALLCONV XMLoadXDec4(_In_ const XMXDEC4* pSource) noexcept; - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable : 4996) - // C4996: ignore deprecation warning - #endif +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - #endif +/**************************************************************************** + * + * Store operations + * + ****************************************************************************/ - #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - #endif +void XM_CALLCONV XMStoreColor(_Out_ XMCOLOR* pDestination, + _In_ FXMVECTOR V) noexcept; - XM_DEPRECATED - void XM_CALLCONV XMStoreDecN4(_Out_ XMDECN4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreHalf2(_Out_ XMHALF2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShortN2(_Out_ XMSHORTN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShort2(_Out_ XMSHORT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShortN2(_Out_ XMUSHORTN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShort2(_Out_ XMUSHORT2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByteN2(_Out_ XMBYTEN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByte2(_Out_ XMBYTE2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByteN2(_Out_ XMUBYTEN2* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByte2(_Out_ XMUBYTE2* pDestination, + _In_ FXMVECTOR V) noexcept; - XM_DEPRECATED - void XM_CALLCONV XMStoreDec4(_Out_ XMDEC4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreU565(_Out_ XMU565* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3PK(_Out_ XMFLOAT3PK* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreFloat3SE(_Out_ XMFLOAT3SE* pDestination, + _In_ FXMVECTOR V) noexcept; - XM_DEPRECATED - void XM_CALLCONV XMStoreXDec4(_Out_ XMXDEC4* pDestination, _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreHalf4(_Out_ XMHALF4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShortN4(_Out_ XMSHORTN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreShort4(_Out_ XMSHORT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShortN4(_Out_ XMUSHORTN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUShort4(_Out_ XMUSHORT4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreXDecN4(_Out_ XMXDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUDecN4(_Out_ XMUDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUDecN4_XR(_Out_ XMUDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUDec4(_Out_ XMUDEC4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByteN4(_Out_ XMBYTEN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreByte4(_Out_ XMBYTE4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByteN4(_Out_ XMUBYTEN4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUByte4(_Out_ XMUBYTE4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreUNibble4(_Out_ XMUNIBBLE4* pDestination, + _In_ FXMVECTOR V) noexcept; +void XM_CALLCONV XMStoreU555(_Out_ XMU555* pDestination, + _In_ FXMVECTOR V) noexcept; - #ifdef __GNUC__ - #pragma GCC diagnostic pop - #endif - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4996) +// C4996: ignore deprecation warning +#endif - /**************************************************************************** - * - * Implementation - * - ****************************************************************************/ - #ifdef _MSC_VER - #pragma warning(push) - #pragma warning(disable:4068 4214 4204 4365 4616 6001 6101) - // C4068/4616: ignore unknown pragmas - // C4214/4204: nonstandard extension used - // C4365: Off by default noise - // C6001/6101: False positives - #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#endif - #ifdef _PREFAST_ - #pragma prefast(push) - #pragma prefast(disable : 25000, "FXMVECTOR is 16 bytes") - #pragma prefast(disable : 26495, "Union initialization confuses /analyze") - #endif +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wunknown-warning-option" - #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" - #endif +XM_DEPRECATED +void XM_CALLCONV XMStoreDecN4(_Out_ XMDECN4* pDestination, + _In_ FXMVECTOR V) noexcept; - #include "DirectXPackedVector.inl" +XM_DEPRECATED +void XM_CALLCONV XMStoreDec4(_Out_ XMDEC4* pDestination, + _In_ FXMVECTOR V) noexcept; - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - #ifdef _PREFAST_ - #pragma prefast(pop) - #endif - #ifdef _MSC_VER - #pragma warning(pop) - #endif - } // namespace PackedVector +XM_DEPRECATED +void XM_CALLCONV XMStoreXDec4(_Out_ XMXDEC4* pDestination, + _In_ FXMVECTOR V) noexcept; -} // namespace DirectX +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif +/**************************************************************************** + * + * Implementation + * + ****************************************************************************/ +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4068 4214 4204 4365 4616 6001 6101) +// C4068/4616: ignore unknown pragmas +// C4214/4204: nonstandard extension used +// C4365: Off by default noise +// C6001/6101: False positives +#endif + +#ifdef _PREFAST_ +#pragma prefast(push) +#pragma prefast(disable : 25000, "FXMVECTOR is 16 bytes") +#pragma prefast(disable : 26495, "Union initialization confuses /analyze") +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunknown-warning-option" +#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" +#endif + +#include "DirectXPackedVector.inl" + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#ifdef _PREFAST_ +#pragma prefast(pop) +#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif +} // namespace PackedVector + +} // namespace DirectX diff --git a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h index f4c53898e..eaf7074c3 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h +++ b/Minecraft.Client/Platform/Linux/Stubs/DirectXMath/sal.h @@ -149,77 +149,86 @@ #define _SAL_VERSION 20 #endif -#ifdef _PREFAST_ // [ +#ifdef _PREFAST_ // [ // choose attribute or __declspec implementation -#ifndef _USE_DECLSPECS_FOR_SAL // [ +#ifndef _USE_DECLSPECS_FOR_SAL // [ #define _USE_DECLSPECS_FOR_SAL 1 -#endif // ] +#endif // ] -#if _USE_DECLSPECS_FOR_SAL // [ +#if _USE_DECLSPECS_FOR_SAL // [ #undef _USE_ATTRIBUTES_FOR_SAL #define _USE_ATTRIBUTES_FOR_SAL 0 -#elif !defined(_USE_ATTRIBUTES_FOR_SAL) // ][ -#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ +#elif !defined(_USE_ATTRIBUTES_FOR_SAL) // ][ +#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ #define _USE_ATTRIBUTES_FOR_SAL 1 -#else // ][ +#else // ][ #define _USE_ATTRIBUTES_FOR_SAL 0 -#endif // ] -#endif // ] +#endif // ] +#endif // ] - -#if !_USE_DECLSPECS_FOR_SAL // [ -#if !_USE_ATTRIBUTES_FOR_SAL // [ -#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ +#if !_USE_DECLSPECS_FOR_SAL // [ +#if !_USE_ATTRIBUTES_FOR_SAL // [ +#if _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // [ #undef _USE_ATTRIBUTES_FOR_SAL #define _USE_ATTRIBUTES_FOR_SAL 1 -#else // ][ +#else // ][ #undef _USE_DECLSPECS_FOR_SAL -#define _USE_DECLSPECS_FOR_SAL 1 -#endif // ] -#endif // ] -#endif // ] +#define _USE_DECLSPECS_FOR_SAL 1 +#endif // ] +#endif // ] +#endif // ] #else // Disable expansion of SAL macros in non-Prefast mode to // improve compiler throughput. -#ifndef _USE_DECLSPECS_FOR_SAL // [ +#ifndef _USE_DECLSPECS_FOR_SAL // [ #define _USE_DECLSPECS_FOR_SAL 0 -#endif // ] -#ifndef _USE_ATTRIBUTES_FOR_SAL // [ +#endif // ] +#ifndef _USE_ATTRIBUTES_FOR_SAL // [ #define _USE_ATTRIBUTES_FOR_SAL 0 -#endif // ] +#endif // ] -#endif // ] +#endif // ] // safeguard for MIDL and RC builds -#if _USE_DECLSPECS_FOR_SAL && ( defined( MIDL_PASS ) || defined(__midl) || defined(RC_INVOKED) || !defined(_PREFAST_) ) /*IFSTRIP=IGN*/ // [ +#if _USE_DECLSPECS_FOR_SAL && (defined(MIDL_PASS) || defined(__midl) || defined(RC_INVOKED) || \ + !defined(_PREFAST_)) /*IFSTRIP=IGN*/ // [ #undef _USE_DECLSPECS_FOR_SAL #define _USE_DECLSPECS_FOR_SAL 0 -#endif // ] -#if _USE_ATTRIBUTES_FOR_SAL && ( !defined(_MSC_EXTENSIONS) || defined( MIDL_PASS ) || defined(__midl) || defined(RC_INVOKED) ) /*IFSTRIP=IGN*/ // [ +#endif // ] +#if _USE_ATTRIBUTES_FOR_SAL && (!defined(_MSC_EXTENSIONS) || defined(MIDL_PASS) || \ + defined(__midl) || defined(RC_INVOKED)) /*IFSTRIP=IGN*/ // [ #undef _USE_ATTRIBUTES_FOR_SAL #define _USE_ATTRIBUTES_FOR_SAL 0 -#endif // ] +#endif // ] #if _USE_DECLSPECS_FOR_SAL || _USE_ATTRIBUTES_FOR_SAL // Special enum type for Y/N/M -enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; +enum __SAL_YesNo { _SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default }; #endif #if defined(BUILD_WINDOWS) && !_USE_ATTRIBUTES_FOR_SAL /*IFSTRIP=IGN*/ -#define _SAL1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1") _GrouP_(annotes _SAL_nop_impl_) -#define _SAL1_1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.1") _GrouP_(annotes _SAL_nop_impl_) -#define _SAL1_2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.2") _GrouP_(annotes _SAL_nop_impl_) -#define _SAL2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "2") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL1_1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.1") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL1_2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.2") _GrouP_(annotes _SAL_nop_impl_) +#define _SAL2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "2") _GrouP_(annotes _SAL_nop_impl_) #else -#define _SAL1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1") _Group_(annotes _SAL_nop_impl_) -#define _SAL1_1_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.1") _Group_(annotes _SAL_nop_impl_) -#define _SAL1_2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "1.2") _Group_(annotes _SAL_nop_impl_) -#define _SAL2_Source_(Name, args, annotes) _SA_annotes3(SAL_name, #Name, "", "2") _Group_(annotes _SAL_nop_impl_) +#define _SAL1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1") _Group_(annotes _SAL_nop_impl_) +#define _SAL1_1_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.1") _Group_(annotes _SAL_nop_impl_) +#define _SAL1_2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "1.2") _Group_(annotes _SAL_nop_impl_) +#define _SAL2_Source_(Name, args, annotes) \ + _SA_annotes3(SAL_name, #Name, "", "2") _Group_(annotes _SAL_nop_impl_) #endif //============================================================================ @@ -232,63 +241,64 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // _At_(target, annos) specifies that the annotations listed in 'annos' is to // be applied to 'target' rather than to the identifier which is the current // lexical target. -#define _At_(target, annos) _At_impl_(target, annos _SAL_nop_impl_) +#define _At_(target, annos) _At_impl_(target, annos _SAL_nop_impl_) // _At_buffer_(target, iter, bound, annos) is similar to _At_, except that // target names a buffer, and each annotation in annos is applied to each // element of target up to bound, with the variable named in iter usable // by the annotations to refer to relevant offsets within target. -#define _At_buffer_(target, iter, bound, annos) _At_buffer_impl_(target, iter, bound, annos _SAL_nop_impl_) +#define _At_buffer_(target, iter, bound, annos) \ + _At_buffer_impl_(target, iter, bound, annos _SAL_nop_impl_) // _When_(expr, annos) specifies that the annotations listed in 'annos' only // apply when 'expr' evaluates to non-zero. -#define _When_(expr, annos) _When_impl_(expr, annos _SAL_nop_impl_) -#define _Group_(annos) _Group_impl_(annos _SAL_nop_impl_) -#define _GrouP_(annos) _GrouP_impl_(annos _SAL_nop_impl_) +#define _When_(expr, annos) _When_impl_(expr, annos _SAL_nop_impl_) +#define _Group_(annos) _Group_impl_(annos _SAL_nop_impl_) +#define _GrouP_(annos) _GrouP_impl_(annos _SAL_nop_impl_) // indicates whether normal post conditions apply to a function -#define _Success_(expr) _SAL2_Source_(_Success_, (expr), _Success_impl_(expr)) +#define _Success_(expr) _SAL2_Source_(_Success_, (expr), _Success_impl_(expr)) // indicates whether post conditions apply to a function returning // the type that this annotation is applied to -#define _Return_type_success_(expr) _SAL2_Source_(_Return_type_success_, (expr), _Success_impl_(expr)) +#define _Return_type_success_(expr) \ + _SAL2_Source_(_Return_type_success_, (expr), _Success_impl_(expr)) // Establish postconditions that apply only if the function does not succeed -#define _On_failure_(annos) _On_failure_impl_(annos _SAL_nop_impl_) +#define _On_failure_(annos) _On_failure_impl_(annos _SAL_nop_impl_) // Establish postconditions that apply in both success and failure cases. // Only applicable with functions that have _Success_ or _Return_type_succss_. -#define _Always_(annos) _Always_impl_(annos _SAL_nop_impl_) +#define _Always_(annos) _Always_impl_(annos _SAL_nop_impl_) // Usable on a function definition. Asserts that a function declaration is // in scope, and its annotations are to be used. There are no other annotations // allowed on the function definition. -#define _Use_decl_annotations_ _Use_decl_anno_impl_ +#define _Use_decl_annotations_ _Use_decl_anno_impl_ // _Notref_ may precede a _Deref_ or "real" annotation, and removes one // level of dereference if the parameter is a C++ reference (&). If the // net deref on a "real" annotation is negative, it is simply discarded. -#define _Notref_ _Notref_impl_ +#define _Notref_ _Notref_impl_ // Annotations for defensive programming styles. -#define _Pre_defensive_ _SA_annotes0(SAL_pre_defensive) -#define _Post_defensive_ _SA_annotes0(SAL_post_defensive) +#define _Pre_defensive_ _SA_annotes0(SAL_pre_defensive) +#define _Post_defensive_ _SA_annotes0(SAL_post_defensive) -#define _In_defensive_(annotes) _Pre_defensive_ _Group_(annotes) -#define _Out_defensive_(annotes) _Post_defensive_ _Group_(annotes) -#define _Inout_defensive_(annotes) _Pre_defensive_ _Post_defensive_ _Group_(annotes) +#define _In_defensive_(annotes) _Pre_defensive_ _Group_(annotes) +#define _Out_defensive_(annotes) _Post_defensive_ _Group_(annotes) +#define _Inout_defensive_(annotes) _Pre_defensive_ _Post_defensive_ _Group_(annotes) //============================================================================ // _In_\_Out_ Layer: //============================================================================ // Reserved pointer parameters, must always be NULL. -#define _Reserved_ _SAL2_Source_(_Reserved_, (), _Pre1_impl_(__null_impl)) +#define _Reserved_ _SAL2_Source_(_Reserved_, (), _Pre1_impl_(__null_impl)) // _Const_ allows specification that any namable memory location is considered // readonly for a given call. -#define _Const_ _SAL2_Source_(_Const_, (), _Pre1_impl_(__readaccess_impl_notref)) - +#define _Const_ _SAL2_Source_(_Const_, (), _Pre1_impl_(__readaccess_impl_notref)) // Input parameters -------------------------- @@ -296,35 +306,51 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // _In_ by itself can be used with non-pointer types (although it is redundant). // e.g. void SetPoint( _In_ const POINT* pPT ); -#define _In_ _SAL2_Source_(_In_, (), _Pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_ _Deref_pre1_impl_(__readaccess_impl_notref)) -#define _In_opt_ _SAL2_Source_(_In_opt_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_ _Deref_pre_readonly_) +#define _In_ \ + _SAL2_Source_(_In_, (), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre_valid_impl_ _Deref_pre1_impl_(__readaccess_impl_notref)) +#define _In_opt_ \ + _SAL2_Source_(_In_opt_, (), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_ _Deref_pre_readonly_) // nullterminated 'in' parameters. // e.g. void CopyStr( _In_z_ const char* szFrom, _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); -#define _In_z_ _SAL2_Source_(_In_z_, (), _In_ _Pre1_impl_(__zterm_impl)) -#define _In_opt_z_ _SAL2_Source_(_In_opt_z_, (), _In_opt_ _Pre1_impl_(__zterm_impl)) - +#define _In_z_ _SAL2_Source_(_In_z_, (), _In_ _Pre1_impl_(__zterm_impl)) +#define _In_opt_z_ _SAL2_Source_(_In_opt_z_, (), _In_opt_ _Pre1_impl_(__zterm_impl)) // 'input' buffers with given size -#define _In_reads_(size) _SAL2_Source_(_In_reads_, (size), _Pre_count_(size) _Deref_pre_readonly_) -#define _In_reads_opt_(size) _SAL2_Source_(_In_reads_opt_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) -#define _In_reads_bytes_(size) _SAL2_Source_(_In_reads_bytes_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) -#define _In_reads_bytes_opt_(size) _SAL2_Source_(_In_reads_bytes_opt_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) -#define _In_reads_z_(size) _SAL2_Source_(_In_reads_z_, (size), _In_reads_(size) _Pre_z_) -#define _In_reads_opt_z_(size) _SAL2_Source_(_In_reads_opt_z_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_ _Pre_opt_z_) -#define _In_reads_or_z_(size) _SAL2_Source_(_In_reads_or_z_, (size), _In_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) -#define _In_reads_or_z_opt_(size) _SAL2_Source_(_In_reads_or_z_opt_, (size), _In_opt_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) - +#define _In_reads_(size) _SAL2_Source_(_In_reads_, (size), _Pre_count_(size) _Deref_pre_readonly_) +#define _In_reads_opt_(size) \ + _SAL2_Source_(_In_reads_opt_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) +#define _In_reads_bytes_(size) \ + _SAL2_Source_(_In_reads_bytes_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) +#define _In_reads_bytes_opt_(size) \ + _SAL2_Source_(_In_reads_bytes_opt_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) +#define _In_reads_z_(size) _SAL2_Source_(_In_reads_z_, (size), _In_reads_(size) _Pre_z_) +#define _In_reads_opt_z_(size) \ + _SAL2_Source_(_In_reads_opt_z_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_ _Pre_opt_z_) +#define _In_reads_or_z_(size) \ + _SAL2_Source_(_In_reads_or_z_, (size), \ + _In_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) \ + _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) +#define _In_reads_or_z_opt_(size) \ + _SAL2_Source_(_In_reads_or_z_opt_, (size), \ + _In_opt_ _When_(_String_length_(_Curr_) < (size), _Pre_z_) \ + _When_(_String_length_(_Curr_) >= (size), _Pre1_impl_(__count_impl(size)))) // 'input' buffers valid to the given end pointer -#define _In_reads_to_ptr_(ptr) _SAL2_Source_(_In_reads_to_ptr_, (ptr), _Pre_ptrdiff_count_(ptr) _Deref_pre_readonly_) -#define _In_reads_to_ptr_opt_(ptr) _SAL2_Source_(_In_reads_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_) -#define _In_reads_to_ptr_z_(ptr) _SAL2_Source_(_In_reads_to_ptr_z_, (ptr), _In_reads_to_ptr_(ptr) _Pre_z_) -#define _In_reads_to_ptr_opt_z_(ptr) _SAL2_Source_(_In_reads_to_ptr_opt_z_, (ptr), _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_ _Pre_opt_z_) - - +#define _In_reads_to_ptr_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_, (ptr), _Pre_ptrdiff_count_(ptr) _Deref_pre_readonly_) +#define _In_reads_to_ptr_opt_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_) +#define _In_reads_to_ptr_z_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_z_, (ptr), _In_reads_to_ptr_(ptr) _Pre_z_) +#define _In_reads_to_ptr_opt_z_(ptr) \ + _SAL2_Source_(_In_reads_to_ptr_opt_z_, (ptr), \ + _Pre_opt_ptrdiff_count_(ptr) _Deref_pre_readonly_ _Pre_opt_z_) // Output parameters -------------------------- @@ -333,31 +359,53 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // _Outptr_/_Outref) (see below) are typically used to return pointers via parameters. // e.g. void GetPoint( _Out_ POINT* pPT ); -#define _Out_ _SAL2_Source_(_Out_, (), _Out_impl_) -#define _Out_opt_ _SAL2_Source_(_Out_opt_, (), _Out_opt_impl_) +#define _Out_ _SAL2_Source_(_Out_, (), _Out_impl_) +#define _Out_opt_ _SAL2_Source_(_Out_opt_, (), _Out_opt_impl_) -#define _Out_writes_(size) _SAL2_Source_(_Out_writes_, (size), _Pre_cap_(size) _Post_valid_impl_) -#define _Out_writes_opt_(size) _SAL2_Source_(_Out_writes_opt_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) -#define _Out_writes_bytes_(size) _SAL2_Source_(_Out_writes_bytes_, (size), _Pre_bytecap_(size) _Post_valid_impl_) -#define _Out_writes_bytes_opt_(size) _SAL2_Source_(_Out_writes_bytes_opt_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) -#define _Out_writes_z_(size) _SAL2_Source_(_Out_writes_z_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_writes_opt_z_(size) _SAL2_Source_(_Out_writes_opt_z_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_writes_(size) _SAL2_Source_(_Out_writes_, (size), _Pre_cap_(size) _Post_valid_impl_) +#define _Out_writes_opt_(size) \ + _SAL2_Source_(_Out_writes_opt_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) +#define _Out_writes_bytes_(size) \ + _SAL2_Source_(_Out_writes_bytes_, (size), _Pre_bytecap_(size) _Post_valid_impl_) +#define _Out_writes_bytes_opt_(size) \ + _SAL2_Source_(_Out_writes_bytes_opt_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) +#define _Out_writes_z_(size) \ + _SAL2_Source_(_Out_writes_z_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_writes_opt_z_(size) \ + _SAL2_Source_(_Out_writes_opt_z_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_writes_to_(size,count) _SAL2_Source_(_Out_writes_to_, (size,count), _Pre_cap_(size) _Post_valid_impl_ _Post_count_(count)) -#define _Out_writes_to_opt_(size,count) _SAL2_Source_(_Out_writes_to_opt_, (size,count), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_count_(count)) -#define _Out_writes_all_(size) _SAL2_Source_(_Out_writes_all_, (size), _Out_writes_to_(_Old_(size), _Old_(size))) -#define _Out_writes_all_opt_(size) _SAL2_Source_(_Out_writes_all_opt_, (size), _Out_writes_to_opt_(_Old_(size), _Old_(size))) +#define _Out_writes_to_(size, count) \ + _SAL2_Source_(_Out_writes_to_, (size, count), \ + _Pre_cap_(size) _Post_valid_impl_ _Post_count_(count)) +#define _Out_writes_to_opt_(size, count) \ + _SAL2_Source_(_Out_writes_to_opt_, (size, count), \ + _Pre_opt_cap_(size) _Post_valid_impl_ _Post_count_(count)) +#define _Out_writes_all_(size) \ + _SAL2_Source_(_Out_writes_all_, (size), _Out_writes_to_(_Old_(size), _Old_(size))) +#define _Out_writes_all_opt_(size) \ + _SAL2_Source_(_Out_writes_all_opt_, (size), _Out_writes_to_opt_(_Old_(size), _Old_(size))) -#define _Out_writes_bytes_to_(size,count) _SAL2_Source_(_Out_writes_bytes_to_, (size,count), _Pre_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) -#define _Out_writes_bytes_to_opt_(size,count) _SAL2_Source_(_Out_writes_bytes_to_opt_, (size,count), _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) -#define _Out_writes_bytes_all_(size) _SAL2_Source_(_Out_writes_bytes_all_, (size), _Out_writes_bytes_to_(_Old_(size), _Old_(size))) -#define _Out_writes_bytes_all_opt_(size) _SAL2_Source_(_Out_writes_bytes_all_opt_, (size), _Out_writes_bytes_to_opt_(_Old_(size), _Old_(size))) - -#define _Out_writes_to_ptr_(ptr) _SAL2_Source_(_Out_writes_to_ptr_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_) -#define _Out_writes_to_ptr_opt_(ptr) _SAL2_Source_(_Out_writes_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_) -#define _Out_writes_to_ptr_z_(ptr) _SAL2_Source_(_Out_writes_to_ptr_z_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) -#define _Out_writes_to_ptr_opt_z_(ptr) _SAL2_Source_(_Out_writes_to_ptr_opt_z_, (ptr), _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) +#define _Out_writes_bytes_to_(size, count) \ + _SAL2_Source_(_Out_writes_bytes_to_, (size, count), \ + _Pre_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) +#define _Out_writes_bytes_to_opt_(size, count) \ + _SAL2_Source_(_Out_writes_bytes_to_opt_, (size, count), \ + _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_bytecount_(count)) +#define _Out_writes_bytes_all_(size) \ + _SAL2_Source_(_Out_writes_bytes_all_, (size), _Out_writes_bytes_to_(_Old_(size), _Old_(size))) +#define _Out_writes_bytes_all_opt_(size) \ + _SAL2_Source_(_Out_writes_bytes_all_opt_, (size), \ + _Out_writes_bytes_to_opt_(_Old_(size), _Old_(size))) +#define _Out_writes_to_ptr_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_) +#define _Out_writes_to_ptr_opt_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_opt_, (ptr), _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_) +#define _Out_writes_to_ptr_z_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_z_, (ptr), _Pre_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) +#define _Out_writes_to_ptr_opt_z_(ptr) \ + _SAL2_Source_(_Out_writes_to_ptr_opt_z_, (ptr), \ + _Pre_opt_ptrdiff_cap_(ptr) _Post_valid_impl_ Post_z_) // Inout parameters ---------------------------- @@ -366,36 +414,65 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // void ModifyPoint( _Inout_ POINT* pPT ); // void ModifyPointByRef( _Inout_ POINT& pPT ); -#define _Inout_ _SAL2_Source_(_Inout_, (), _Prepost_valid_) -#define _Inout_opt_ _SAL2_Source_(_Inout_opt_, (), _Prepost_opt_valid_) +#define _Inout_ _SAL2_Source_(_Inout_, (), _Prepost_valid_) +#define _Inout_opt_ _SAL2_Source_(_Inout_opt_, (), _Prepost_opt_valid_) // For modifying string buffers // void toupper( _Inout_z_ char* sz ); -#define _Inout_z_ _SAL2_Source_(_Inout_z_, (), _Prepost_z_) -#define _Inout_opt_z_ _SAL2_Source_(_Inout_opt_z_, (), _Prepost_opt_z_) +#define _Inout_z_ _SAL2_Source_(_Inout_z_, (), _Prepost_z_) +#define _Inout_opt_z_ _SAL2_Source_(_Inout_opt_z_, (), _Prepost_opt_z_) // For modifying buffers with explicit element size -#define _Inout_updates_(size) _SAL2_Source_(_Inout_updates_, (size), _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_opt_(size) _SAL2_Source_(_Inout_updates_opt_, (size), _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_z_(size) _SAL2_Source_(_Inout_updates_z_, (size), _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) _Post1_impl_(__zterm_impl)) -#define _Inout_updates_opt_z_(size) _SAL2_Source_(_Inout_updates_opt_z_, (size), _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) _Post1_impl_(__zterm_impl)) +#define _Inout_updates_(size) \ + _SAL2_Source_(_Inout_updates_, (size), _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_opt_(size) \ + _SAL2_Source_(_Inout_updates_opt_, (size), \ + _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_z_(size) \ + _SAL2_Source_(_Inout_updates_z_, (size), \ + _Pre_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) \ + _Post1_impl_(__zterm_impl)) +#define _Inout_updates_opt_z_(size) \ + _SAL2_Source_(_Inout_updates_opt_z_, (size), \ + _Pre_opt_cap_(size) _Pre_valid_impl_ _Post_valid_impl_ _Pre1_impl_(__zterm_impl) \ + _Post1_impl_(__zterm_impl)) -#define _Inout_updates_to_(size,count) _SAL2_Source_(_Inout_updates_to_, (size,count), _Out_writes_to_(size,count) _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) -#define _Inout_updates_to_opt_(size,count) _SAL2_Source_(_Inout_updates_to_opt_, (size,count), _Out_writes_to_opt_(size,count) _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) +#define _Inout_updates_to_(size, count) \ + _SAL2_Source_(_Inout_updates_to_, (size, count), \ + _Out_writes_to_(size, count) _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) +#define _Inout_updates_to_opt_(size, count) \ + _SAL2_Source_(_Inout_updates_to_opt_, (size, count), \ + _Out_writes_to_opt_(size, count) \ + _Pre_valid_impl_ _Pre1_impl_(__count_impl(count))) -#define _Inout_updates_all_(size) _SAL2_Source_(_Inout_updates_all_, (size), _Inout_updates_to_(_Old_(size), _Old_(size))) -#define _Inout_updates_all_opt_(size) _SAL2_Source_(_Inout_updates_all_opt_, (size), _Inout_updates_to_opt_(_Old_(size), _Old_(size))) +#define _Inout_updates_all_(size) \ + _SAL2_Source_(_Inout_updates_all_, (size), _Inout_updates_to_(_Old_(size), _Old_(size))) +#define _Inout_updates_all_opt_(size) \ + _SAL2_Source_(_Inout_updates_all_opt_, (size), _Inout_updates_to_opt_(_Old_(size), _Old_(size))) // For modifying buffers with explicit byte size -#define _Inout_updates_bytes_(size) _SAL2_Source_(_Inout_updates_bytes_, (size), _Pre_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_bytes_opt_(size) _SAL2_Source_(_Inout_updates_bytes_opt_, (size), _Pre_opt_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_bytes_(size) \ + _SAL2_Source_(_Inout_updates_bytes_, (size), \ + _Pre_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) +#define _Inout_updates_bytes_opt_(size) \ + _SAL2_Source_(_Inout_updates_bytes_opt_, (size), \ + _Pre_opt_bytecap_(size) _Pre_valid_impl_ _Post_valid_impl_) -#define _Inout_updates_bytes_to_(size,count) _SAL2_Source_(_Inout_updates_bytes_to_, (size,count), _Out_writes_bytes_to_(size,count) _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) -#define _Inout_updates_bytes_to_opt_(size,count) _SAL2_Source_(_Inout_updates_bytes_to_opt_, (size,count), _Out_writes_bytes_to_opt_(size,count) _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) - -#define _Inout_updates_bytes_all_(size) _SAL2_Source_(_Inout_updates_bytes_all_, (size), _Inout_updates_bytes_to_(_Old_(size), _Old_(size))) -#define _Inout_updates_bytes_all_opt_(size) _SAL2_Source_(_Inout_updates_bytes_all_opt_, (size), _Inout_updates_bytes_to_opt_(_Old_(size), _Old_(size))) +#define _Inout_updates_bytes_to_(size, count) \ + _SAL2_Source_(_Inout_updates_bytes_to_, (size, count), \ + _Out_writes_bytes_to_(size, count) \ + _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) +#define _Inout_updates_bytes_to_opt_(size, count) \ + _SAL2_Source_(_Inout_updates_bytes_to_opt_, (size, count), \ + _Out_writes_bytes_to_opt_(size, count) \ + _Pre_valid_impl_ _Pre1_impl_(__bytecount_impl(count))) +#define _Inout_updates_bytes_all_(size) \ + _SAL2_Source_(_Inout_updates_bytes_all_, (size), \ + _Inout_updates_bytes_to_(_Old_(size), _Old_(size))) +#define _Inout_updates_bytes_all_opt_(size) \ + _SAL2_Source_(_Inout_updates_bytes_all_opt_, (size), \ + _Inout_updates_bytes_to_opt_(_Old_(size), _Old_(size))) // Pointer to pointer parameters ------------------------- @@ -406,7 +483,8 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // and initializes memory and returns the pointer to the new LPWSTR in *ppwsz. // // _Outptr_opt_ - describes parameters that are allowed to be NULL. -// _Outptr_*_result_maybenull_ - describes parameters where the called function might return NULL to the caller. +// _Outptr_*_result_maybenull_ - describes parameters where the called function might return NULL +// to the caller. // // Example: // void MyFunc(_Outptr_opt_ int **ppData1, _Outptr_result_maybenull_ int **ppData2); @@ -415,94 +493,203 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // MyFunc(&pData1, &pData2); // ok: both non-NULL // if (*pData1 == *pData2) ... // error: pData2 might be NULL after call -#define _Outptr_ _SAL2_Source_(_Outptr_, (), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) -#define _Outptr_result_maybenull_ _SAL2_Source_(_Outptr_result_maybenull_, (), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) -#define _Outptr_opt_ _SAL2_Source_(_Outptr_opt_, (), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) -#define _Outptr_opt_result_maybenull_ _SAL2_Source_(_Outptr_opt_result_maybenull_, (), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) +#define _Outptr_ \ + _SAL2_Source_(_Outptr_, (), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) +#define _Outptr_result_maybenull_ \ + _SAL2_Source_(_Outptr_result_maybenull_, (), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) +#define _Outptr_opt_ \ + _SAL2_Source_(_Outptr_opt_, (), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(1))) +#define _Outptr_opt_result_maybenull_ \ + _SAL2_Source_(_Outptr_opt_result_maybenull_, (), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(1))) // Annotations for _Outptr_ parameters returning pointers to null terminated strings. -#define _Outptr_result_z_ _SAL2_Source_(_Outptr_result_z_, (), _Out_impl_ _Deref_post_z_) -#define _Outptr_opt_result_z_ _SAL2_Source_(_Outptr_opt_result_z_, (), _Out_opt_impl_ _Deref_post_z_) -#define _Outptr_result_maybenull_z_ _SAL2_Source_(_Outptr_result_maybenull_z_, (), _Out_impl_ _Deref_post_opt_z_) -#define _Outptr_opt_result_maybenull_z_ _SAL2_Source_(_Outptr_opt_result_maybenull_z_, (), _Out_opt_impl_ _Deref_post_opt_z_) +#define _Outptr_result_z_ _SAL2_Source_(_Outptr_result_z_, (), _Out_impl_ _Deref_post_z_) +#define _Outptr_opt_result_z_ \ + _SAL2_Source_(_Outptr_opt_result_z_, (), _Out_opt_impl_ _Deref_post_z_) +#define _Outptr_result_maybenull_z_ \ + _SAL2_Source_(_Outptr_result_maybenull_z_, (), _Out_impl_ _Deref_post_opt_z_) +#define _Outptr_opt_result_maybenull_z_ \ + _SAL2_Source_(_Outptr_opt_result_maybenull_z_, (), _Out_opt_impl_ _Deref_post_opt_z_) -// Annotations for _Outptr_ parameters where the output pointer is set to NULL if the function fails. +// Annotations for _Outptr_ parameters where the output pointer is set to NULL if the function +// fails. -#define _Outptr_result_nullonfailure_ _SAL2_Source_(_Outptr_result_nullonfailure_, (), _Outptr_ _On_failure_(_Deref_post_null_)) -#define _Outptr_opt_result_nullonfailure_ _SAL2_Source_(_Outptr_opt_result_nullonfailure_, (), _Outptr_opt_ _On_failure_(_Deref_post_null_)) +#define _Outptr_result_nullonfailure_ \ + _SAL2_Source_(_Outptr_result_nullonfailure_, (), _Outptr_ _On_failure_(_Deref_post_null_)) +#define _Outptr_opt_result_nullonfailure_ \ + _SAL2_Source_(_Outptr_opt_result_nullonfailure_, (), \ + _Outptr_opt_ _On_failure_(_Deref_post_null_)) // Annotations for _Outptr_ parameters which return a pointer to a ref-counted COM object, // following the COM convention of setting the output to NULL on failure. // The current implementation is identical to _Outptr_result_nullonfailure_. // For pointers to types that are not COM objects, _Outptr_result_nullonfailure_ is preferred. -#define _COM_Outptr_ _SAL2_Source_(_COM_Outptr_, (), _Outptr_ _On_failure_(_Deref_post_null_)) -#define _COM_Outptr_result_maybenull_ _SAL2_Source_(_COM_Outptr_result_maybenull_, (), _Outptr_result_maybenull_ _On_failure_(_Deref_post_null_)) -#define _COM_Outptr_opt_ _SAL2_Source_(_COM_Outptr_opt_, (), _Outptr_opt_ _On_failure_(_Deref_post_null_)) -#define _COM_Outptr_opt_result_maybenull_ _SAL2_Source_(_COM_Outptr_opt_result_maybenull_, (), _Outptr_opt_result_maybenull_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_ _SAL2_Source_(_COM_Outptr_, (), _Outptr_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_result_maybenull_ \ + _SAL2_Source_(_COM_Outptr_result_maybenull_, (), \ + _Outptr_result_maybenull_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_opt_ \ + _SAL2_Source_(_COM_Outptr_opt_, (), _Outptr_opt_ _On_failure_(_Deref_post_null_)) +#define _COM_Outptr_opt_result_maybenull_ \ + _SAL2_Source_(_COM_Outptr_opt_result_maybenull_, (), \ + _Outptr_opt_result_maybenull_ _On_failure_(_Deref_post_null_)) -// Annotations for _Outptr_ parameters returning a pointer to buffer with a specified number of elements/bytes +// Annotations for _Outptr_ parameters returning a pointer to buffer with a specified number of +// elements/bytes -#define _Outptr_result_buffer_(size) _SAL2_Source_(_Outptr_result_buffer_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) -#define _Outptr_opt_result_buffer_(size) _SAL2_Source_(_Outptr_opt_result_buffer_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) -#define _Outptr_result_buffer_to_(size, count) _SAL2_Source_(_Outptr_result_buffer_to_, (size, count), _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), __count_impl(count))) -#define _Outptr_opt_result_buffer_to_(size, count) _SAL2_Source_(_Outptr_opt_result_buffer_to_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), __count_impl(count))) +#define _Outptr_result_buffer_(size) \ + _SAL2_Source_(_Outptr_result_buffer_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) +#define _Outptr_opt_result_buffer_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __cap_impl(size))) +#define _Outptr_result_buffer_to_(size, count) \ + _SAL2_Source_(_Outptr_result_buffer_to_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), \ + __count_impl(count))) +#define _Outptr_opt_result_buffer_to_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_buffer_to_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __cap_impl(size), \ + __count_impl(count))) -#define _Outptr_result_buffer_all_(size) _SAL2_Source_(_Outptr_result_buffer_all_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) -#define _Outptr_opt_result_buffer_all_(size) _SAL2_Source_(_Outptr_opt_result_buffer_all_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) +#define _Outptr_result_buffer_all_(size) \ + _SAL2_Source_(_Outptr_result_buffer_all_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) +#define _Outptr_opt_result_buffer_all_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_all_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __count_impl(size))) -#define _Outptr_result_buffer_maybenull_(size) _SAL2_Source_(_Outptr_result_buffer_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) -#define _Outptr_opt_result_buffer_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_buffer_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) -#define _Outptr_result_buffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_result_buffer_to_maybenull_, (size, count), _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), __count_impl(count))) -#define _Outptr_opt_result_buffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_opt_result_buffer_to_maybenull_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), __count_impl(count))) +#define _Outptr_result_buffer_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_buffer_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) +#define _Outptr_opt_result_buffer_maybenull_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __cap_impl(size))) +#define _Outptr_result_buffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_result_buffer_to_maybenull_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), \ + __count_impl(count))) +#define _Outptr_opt_result_buffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_buffer_to_maybenull_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __cap_impl(size), \ + __count_impl(count))) -#define _Outptr_result_buffer_all_maybenull_(size) _SAL2_Source_(_Outptr_result_buffer_all_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) -#define _Outptr_opt_result_buffer_all_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_buffer_all_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) +#define _Outptr_result_buffer_all_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_buffer_all_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) +#define _Outptr_opt_result_buffer_all_maybenull_(size) \ + _SAL2_Source_(_Outptr_opt_result_buffer_all_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __count_impl(size))) -#define _Outptr_result_bytebuffer_(size) _SAL2_Source_(_Outptr_result_bytebuffer_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) -#define _Outptr_opt_result_bytebuffer_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) -#define _Outptr_result_bytebuffer_to_(size, count) _SAL2_Source_(_Outptr_result_bytebuffer_to_, (size, count), _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) -#define _Outptr_opt_result_bytebuffer_to_(size, count) _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) +#define _Outptr_result_bytebuffer_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) +#define _Outptr_opt_result_bytebuffer_(size) \ + _SAL2_Source_(_Outptr_opt_result_bytebuffer_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecap_impl(size))) +#define _Outptr_result_bytebuffer_to_(size, count) \ + _SAL2_Source_(_Outptr_result_bytebuffer_to_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) +#define _Outptr_opt_result_bytebuffer_to_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__notnull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) -#define _Outptr_result_bytebuffer_all_(size) _SAL2_Source_(_Outptr_result_bytebuffer_all_, (size), _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) -#define _Outptr_opt_result_bytebuffer_all_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_all_, (size), _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) +#define _Outptr_result_bytebuffer_all_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_all_, (size), \ + _Out_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) +#define _Outptr_opt_result_bytebuffer_all_(size) \ + _SAL2_Source_( \ + _Outptr_opt_result_bytebuffer_all_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__notnull_impl_notref, __bytecount_impl(size))) -#define _Outptr_result_bytebuffer_maybenull_(size) _SAL2_Source_(_Outptr_result_bytebuffer_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) -#define _Outptr_opt_result_bytebuffer_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) -#define _Outptr_result_bytebuffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_result_bytebuffer_to_maybenull_, (size, count), _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) -#define _Outptr_opt_result_bytebuffer_to_maybenull_(size, count) _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_maybenull_, (size, count), _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), __bytecount_impl(count))) +#define _Outptr_result_bytebuffer_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) +#define _Outptr_opt_result_bytebuffer_maybenull_(size) \ + _SAL2_Source_( \ + _Outptr_opt_result_bytebuffer_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecap_impl(size))) +#define _Outptr_result_bytebuffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_result_bytebuffer_to_maybenull_, (size, count), \ + _Out_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) +#define _Outptr_opt_result_bytebuffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outptr_opt_result_bytebuffer_to_maybenull_, (size, count), \ + _Out_opt_impl_ _Deref_post3_impl_(__maybenull_impl_notref, __bytecap_impl(size), \ + __bytecount_impl(count))) -#define _Outptr_result_bytebuffer_all_maybenull_(size) _SAL2_Source_(_Outptr_result_bytebuffer_all_maybenull_, (size), _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) -#define _Outptr_opt_result_bytebuffer_all_maybenull_(size) _SAL2_Source_(_Outptr_opt_result_bytebuffer_all_maybenull_, (size), _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) +#define _Outptr_result_bytebuffer_all_maybenull_(size) \ + _SAL2_Source_(_Outptr_result_bytebuffer_all_maybenull_, (size), \ + _Out_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) +#define _Outptr_opt_result_bytebuffer_all_maybenull_(size) \ + _SAL2_Source_( \ + _Outptr_opt_result_bytebuffer_all_maybenull_, (size), \ + _Out_opt_impl_ _Deref_post2_impl_(__maybenull_impl_notref, __bytecount_impl(size))) // Annotations for output reference to pointer parameters. -#define _Outref_ _SAL2_Source_(_Outref_, (), _Out_impl_ _Post_notnull_) -#define _Outref_result_maybenull_ _SAL2_Source_(_Outref_result_maybenull_, (), _Pre2_impl_(__notnull_impl_notref, __cap_c_one_notref_impl) _Post_maybenull_ _Post_valid_impl_) +#define _Outref_ _SAL2_Source_(_Outref_, (), _Out_impl_ _Post_notnull_) +#define _Outref_result_maybenull_ \ + _SAL2_Source_(_Outref_result_maybenull_, (), \ + _Pre2_impl_(__notnull_impl_notref, __cap_c_one_notref_impl) \ + _Post_maybenull_ _Post_valid_impl_) -#define _Outref_result_buffer_(size) _SAL2_Source_(_Outref_result_buffer_, (size), _Outref_ _Post1_impl_(__cap_impl(size))) -#define _Outref_result_bytebuffer_(size) _SAL2_Source_(_Outref_result_bytebuffer_, (size), _Outref_ _Post1_impl_(__bytecap_impl(size))) -#define _Outref_result_buffer_to_(size, count) _SAL2_Source_(_Outref_result_buffer_to_, (size, count), _Outref_result_buffer_(size) _Post1_impl_(__count_impl(count))) -#define _Outref_result_bytebuffer_to_(size, count) _SAL2_Source_(_Outref_result_bytebuffer_to_, (size, count), _Outref_result_bytebuffer_(size) _Post1_impl_(__bytecount_impl(count))) -#define _Outref_result_buffer_all_(size) _SAL2_Source_(_Outref_result_buffer_all_, (size), _Outref_result_buffer_to_(size, _Old_(size))) -#define _Outref_result_bytebuffer_all_(size) _SAL2_Source_(_Outref_result_bytebuffer_all_, (size), _Outref_result_bytebuffer_to_(size, _Old_(size))) +#define _Outref_result_buffer_(size) \ + _SAL2_Source_(_Outref_result_buffer_, (size), _Outref_ _Post1_impl_(__cap_impl(size))) +#define _Outref_result_bytebuffer_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_, (size), _Outref_ _Post1_impl_(__bytecap_impl(size))) +#define _Outref_result_buffer_to_(size, count) \ + _SAL2_Source_(_Outref_result_buffer_to_, (size, count), \ + _Outref_result_buffer_(size) _Post1_impl_(__count_impl(count))) +#define _Outref_result_bytebuffer_to_(size, count) \ + _SAL2_Source_(_Outref_result_bytebuffer_to_, (size, count), \ + _Outref_result_bytebuffer_(size) _Post1_impl_(__bytecount_impl(count))) +#define _Outref_result_buffer_all_(size) \ + _SAL2_Source_(_Outref_result_buffer_all_, (size), _Outref_result_buffer_to_(size, _Old_(size))) +#define _Outref_result_bytebuffer_all_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_all_, (size), \ + _Outref_result_bytebuffer_to_(size, _Old_(size))) -#define _Outref_result_buffer_maybenull_(size) _SAL2_Source_(_Outref_result_buffer_maybenull_, (size), _Outref_result_maybenull_ _Post1_impl_(__cap_impl(size))) -#define _Outref_result_bytebuffer_maybenull_(size) _SAL2_Source_(_Outref_result_bytebuffer_maybenull_, (size), _Outref_result_maybenull_ _Post1_impl_(__bytecap_impl(size))) -#define _Outref_result_buffer_to_maybenull_(size, count) _SAL2_Source_(_Outref_result_buffer_to_maybenull_, (size, count), _Outref_result_buffer_maybenull_(size) _Post1_impl_(__count_impl(count))) -#define _Outref_result_bytebuffer_to_maybenull_(size, count) _SAL2_Source_(_Outref_result_bytebuffer_to_maybenull_, (size, count), _Outref_result_bytebuffer_maybenull_(size) _Post1_impl_(__bytecount_impl(count))) -#define _Outref_result_buffer_all_maybenull_(size) _SAL2_Source_(_Outref_result_buffer_all_maybenull_, (size), _Outref_result_buffer_to_maybenull_(size, _Old_(size))) -#define _Outref_result_bytebuffer_all_maybenull_(size) _SAL2_Source_(_Outref_result_bytebuffer_all_maybenull_, (size), _Outref_result_bytebuffer_to_maybenull_(size, _Old_(size))) +#define _Outref_result_buffer_maybenull_(size) \ + _SAL2_Source_(_Outref_result_buffer_maybenull_, (size), \ + _Outref_result_maybenull_ _Post1_impl_(__cap_impl(size))) +#define _Outref_result_bytebuffer_maybenull_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_maybenull_, (size), \ + _Outref_result_maybenull_ _Post1_impl_(__bytecap_impl(size))) +#define _Outref_result_buffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outref_result_buffer_to_maybenull_, (size, count), \ + _Outref_result_buffer_maybenull_(size) _Post1_impl_(__count_impl(count))) +#define _Outref_result_bytebuffer_to_maybenull_(size, count) \ + _SAL2_Source_(_Outref_result_bytebuffer_to_maybenull_, (size, count), \ + _Outref_result_bytebuffer_maybenull_(size) \ + _Post1_impl_(__bytecount_impl(count))) +#define _Outref_result_buffer_all_maybenull_(size) \ + _SAL2_Source_(_Outref_result_buffer_all_maybenull_, (size), \ + _Outref_result_buffer_to_maybenull_(size, _Old_(size))) +#define _Outref_result_bytebuffer_all_maybenull_(size) \ + _SAL2_Source_(_Outref_result_bytebuffer_all_maybenull_, (size), \ + _Outref_result_bytebuffer_to_maybenull_(size, _Old_(size))) // Annotations for output reference to pointer parameters that guarantee // that the pointer is set to NULL on failure. -#define _Outref_result_nullonfailure_ _SAL2_Source_(_Outref_result_nullonfailure_, (), _Outref_ _On_failure_(_Post_null_)) - -// Generic annotations to set output value of a by-pointer or by-reference parameter to null/zero on failure. -#define _Result_nullonfailure_ _SAL2_Source_(_Result_nullonfailure_, (), _On_failure_(_Notref_impl_ _Deref_impl_ _Post_null_)) -#define _Result_zeroonfailure_ _SAL2_Source_(_Result_zeroonfailure_, (), _On_failure_(_Notref_impl_ _Deref_impl_ _Out_range_(==, 0))) +#define _Outref_result_nullonfailure_ \ + _SAL2_Source_(_Outref_result_nullonfailure_, (), _Outref_ _On_failure_(_Post_null_)) +// Generic annotations to set output value of a by-pointer or by-reference parameter to null/zero on +// failure. +#define _Result_nullonfailure_ \ + _SAL2_Source_(_Result_nullonfailure_, (), _On_failure_(_Notref_impl_ _Deref_impl_ _Post_null_)) +#define _Result_zeroonfailure_ \ + _SAL2_Source_(_Result_zeroonfailure_, (), \ + _On_failure_(_Notref_impl_ _Deref_impl_ _Out_range_(==, 0))) // return values ------------------------------- @@ -512,92 +699,146 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // describing conditions that hold for return values after the call // e.g. _Ret_z_ CString::operator const WCHAR*() const throw(); -#define _Ret_z_ _SAL2_Source_(_Ret_z_, (), _Ret2_impl_(__notnull_impl, __zterm_impl) _Ret_valid_impl_) -#define _Ret_maybenull_z_ _SAL2_Source_(_Ret_maybenull_z_, (), _Ret2_impl_(__maybenull_impl,__zterm_impl) _Ret_valid_impl_) +#define _Ret_z_ \ + _SAL2_Source_(_Ret_z_, (), _Ret2_impl_(__notnull_impl, __zterm_impl) _Ret_valid_impl_) +#define _Ret_maybenull_z_ \ + _SAL2_Source_(_Ret_maybenull_z_, (), \ + _Ret2_impl_(__maybenull_impl, __zterm_impl) _Ret_valid_impl_) // used with allocated but not yet initialized objects -#define _Ret_notnull_ _SAL2_Source_(_Ret_notnull_, (), _Ret1_impl_(__notnull_impl)) -#define _Ret_maybenull_ _SAL2_Source_(_Ret_maybenull_, (), _Ret1_impl_(__maybenull_impl)) -#define _Ret_null_ _SAL2_Source_(_Ret_null_, (), _Ret1_impl_(__null_impl)) +#define _Ret_notnull_ _SAL2_Source_(_Ret_notnull_, (), _Ret1_impl_(__notnull_impl)) +#define _Ret_maybenull_ _SAL2_Source_(_Ret_maybenull_, (), _Ret1_impl_(__maybenull_impl)) +#define _Ret_null_ _SAL2_Source_(_Ret_null_, (), _Ret1_impl_(__null_impl)) // used with allocated and initialized objects // returns single valid object -#define _Ret_valid_ _SAL2_Source_(_Ret_valid_, (), _Ret1_impl_(__notnull_impl_notref) _Ret_valid_impl_) +#define _Ret_valid_ \ + _SAL2_Source_(_Ret_valid_, (), _Ret1_impl_(__notnull_impl_notref) _Ret_valid_impl_) // returns pointer to initialized buffer of specified size -#define _Ret_writes_(size) _SAL2_Source_(_Ret_writes_, (size), _Ret2_impl_(__notnull_impl, __count_impl(size)) _Ret_valid_impl_) -#define _Ret_writes_z_(size) _SAL2_Source_(_Ret_writes_z_, (size), _Ret3_impl_(__notnull_impl, __count_impl(size), __zterm_impl) _Ret_valid_impl_) -#define _Ret_writes_bytes_(size) _SAL2_Source_(_Ret_writes_bytes_, (size), _Ret2_impl_(__notnull_impl, __bytecount_impl(size)) _Ret_valid_impl_) -#define _Ret_writes_maybenull_(size) _SAL2_Source_(_Ret_writes_maybenull_, (size), _Ret2_impl_(__maybenull_impl,__count_impl(size)) _Ret_valid_impl_) -#define _Ret_writes_maybenull_z_(size) _SAL2_Source_(_Ret_writes_maybenull_z_, (size), _Ret3_impl_(__maybenull_impl,__count_impl(size),__zterm_impl) _Ret_valid_impl_) -#define _Ret_writes_bytes_maybenull_(size) _SAL2_Source_(_Ret_writes_bytes_maybenull_, (size), _Ret2_impl_(__maybenull_impl,__bytecount_impl(size)) _Ret_valid_impl_) - -// returns pointer to partially initialized buffer, with total size 'size' and initialized size 'count' -#define _Ret_writes_to_(size,count) _SAL2_Source_(_Ret_writes_to_, (size,count), _Ret3_impl_(__notnull_impl, __cap_impl(size), __count_impl(count)) _Ret_valid_impl_) -#define _Ret_writes_bytes_to_(size,count) _SAL2_Source_(_Ret_writes_bytes_to_, (size,count), _Ret3_impl_(__notnull_impl, __bytecap_impl(size), __bytecount_impl(count)) _Ret_valid_impl_) -#define _Ret_writes_to_maybenull_(size,count) _SAL2_Source_(_Ret_writes_to_maybenull_, (size,count), _Ret3_impl_(__maybenull_impl, __cap_impl(size), __count_impl(count)) _Ret_valid_impl_) -#define _Ret_writes_bytes_to_maybenull_(size,count) _SAL2_Source_(_Ret_writes_bytes_to_maybenull_, (size,count), _Ret3_impl_(__maybenull_impl, __bytecap_impl(size), __bytecount_impl(count)) _Ret_valid_impl_) +#define _Ret_writes_(size) \ + _SAL2_Source_(_Ret_writes_, (size), \ + _Ret2_impl_(__notnull_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_writes_z_(size) \ + _SAL2_Source_(_Ret_writes_z_, (size), \ + _Ret3_impl_(__notnull_impl, __count_impl(size), __zterm_impl) _Ret_valid_impl_) +#define _Ret_writes_bytes_(size) \ + _SAL2_Source_(_Ret_writes_bytes_, (size), \ + _Ret2_impl_(__notnull_impl, __bytecount_impl(size)) _Ret_valid_impl_) +#define _Ret_writes_maybenull_(size) \ + _SAL2_Source_(_Ret_writes_maybenull_, (size), \ + _Ret2_impl_(__maybenull_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_writes_maybenull_z_(size) \ + _SAL2_Source_(_Ret_writes_maybenull_z_, (size), \ + _Ret3_impl_(__maybenull_impl, __count_impl(size), __zterm_impl) \ + _Ret_valid_impl_) +#define _Ret_writes_bytes_maybenull_(size) \ + _SAL2_Source_(_Ret_writes_bytes_maybenull_, (size), \ + _Ret2_impl_(__maybenull_impl, __bytecount_impl(size)) _Ret_valid_impl_) +// returns pointer to partially initialized buffer, with total size 'size' and initialized size +// 'count' +#define _Ret_writes_to_(size, count) \ + _SAL2_Source_(_Ret_writes_to_, (size, count), \ + _Ret3_impl_(__notnull_impl, __cap_impl(size), __count_impl(count)) \ + _Ret_valid_impl_) +#define _Ret_writes_bytes_to_(size, count) \ + _SAL2_Source_(_Ret_writes_bytes_to_, (size, count), \ + _Ret3_impl_(__notnull_impl, __bytecap_impl(size), __bytecount_impl(count)) \ + _Ret_valid_impl_) +#define _Ret_writes_to_maybenull_(size, count) \ + _SAL2_Source_(_Ret_writes_to_maybenull_, (size, count), \ + _Ret3_impl_(__maybenull_impl, __cap_impl(size), __count_impl(count)) \ + _Ret_valid_impl_) +#define _Ret_writes_bytes_to_maybenull_(size, count) \ + _SAL2_Source_(_Ret_writes_bytes_to_maybenull_, (size, count), \ + _Ret3_impl_(__maybenull_impl, __bytecap_impl(size), __bytecount_impl(count)) \ + _Ret_valid_impl_) // Annotations for strict type checking -#define _Points_to_data_ _SAL2_Source_(_Points_to_data_, (), _Pre_ _Points_to_data_impl_) -#define _Literal_ _SAL2_Source_(_Literal_, (), _Pre_ _Literal_impl_) -#define _Notliteral_ _SAL2_Source_(_Notliteral_, (), _Pre_ _Notliteral_impl_) +#define _Points_to_data_ _SAL2_Source_(_Points_to_data_, (), _Pre_ _Points_to_data_impl_) +#define _Literal_ _SAL2_Source_(_Literal_, (), _Pre_ _Literal_impl_) +#define _Notliteral_ _SAL2_Source_(_Notliteral_, (), _Pre_ _Notliteral_impl_) // Check the return value of a function e.g. _Check_return_ ErrorCode Foo(); -#define _Check_return_ _SAL2_Source_(_Check_return_, (), _Check_return_impl_) -#define _Must_inspect_result_ _SAL2_Source_(_Must_inspect_result_, (), _Must_inspect_impl_ _Check_return_impl_) +#define _Check_return_ _SAL2_Source_(_Check_return_, (), _Check_return_impl_) +#define _Must_inspect_result_ \ + _SAL2_Source_(_Must_inspect_result_, (), _Must_inspect_impl_ _Check_return_impl_) // e.g. MyPrintF( _Printf_format_string_ const WCHAR* wzFormat, ... ); -#define _Printf_format_string_ _SAL2_Source_(_Printf_format_string_, (), _Printf_format_string_impl_) -#define _Scanf_format_string_ _SAL2_Source_(_Scanf_format_string_, (), _Scanf_format_string_impl_) -#define _Scanf_s_format_string_ _SAL2_Source_(_Scanf_s_format_string_, (), _Scanf_s_format_string_impl_) +#define _Printf_format_string_ \ + _SAL2_Source_(_Printf_format_string_, (), _Printf_format_string_impl_) +#define _Scanf_format_string_ _SAL2_Source_(_Scanf_format_string_, (), _Scanf_format_string_impl_) +#define _Scanf_s_format_string_ \ + _SAL2_Source_(_Scanf_s_format_string_, (), _Scanf_s_format_string_impl_) -#define _Format_string_impl_(kind,where) _SA_annotes2(SAL_IsFormatString2, kind, where) -#define _Printf_format_string_params_(x) _SAL2_Source_(_Printf_format_string_params_, (x), _Format_string_impl_("printf", x)) -#define _Scanf_format_string_params_(x) _SAL2_Source_(_Scanf_format_string_params_, (x), _Format_string_impl_("scanf", x)) -#define _Scanf_s_format_string_params_(x) _SAL2_Source_(_Scanf_s_format_string_params_, (x), _Format_string_impl_("scanf_s", x)) +#define _Format_string_impl_(kind, where) _SA_annotes2(SAL_IsFormatString2, kind, where) +#define _Printf_format_string_params_(x) \ + _SAL2_Source_(_Printf_format_string_params_, (x), _Format_string_impl_("printf", x)) +#define _Scanf_format_string_params_(x) \ + _SAL2_Source_(_Scanf_format_string_params_, (x), _Format_string_impl_("scanf", x)) +#define _Scanf_s_format_string_params_(x) \ + _SAL2_Source_(_Scanf_s_format_string_params_, (x), _Format_string_impl_("scanf_s", x)) // annotations to express value of integral or pointer parameter -#define _In_range_(lb,ub) _SAL2_Source_(_In_range_, (lb,ub), _In_range_impl_(lb,ub)) -#define _Out_range_(lb,ub) _SAL2_Source_(_Out_range_, (lb,ub), _Out_range_impl_(lb,ub)) -#define _Ret_range_(lb,ub) _SAL2_Source_(_Ret_range_, (lb,ub), _Ret_range_impl_(lb,ub)) -#define _Deref_in_range_(lb,ub) _SAL2_Source_(_Deref_in_range_, (lb,ub), _Deref_in_range_impl_(lb,ub)) -#define _Deref_out_range_(lb,ub) _SAL2_Source_(_Deref_out_range_, (lb,ub), _Deref_out_range_impl_(lb,ub)) -#define _Deref_ret_range_(lb,ub) _SAL2_Source_(_Deref_ret_range_, (lb,ub), _Deref_ret_range_impl_(lb,ub)) -#define _Pre_equal_to_(expr) _SAL2_Source_(_Pre_equal_to_, (expr), _In_range_(==, expr)) -#define _Post_equal_to_(expr) _SAL2_Source_(_Post_equal_to_, (expr), _Out_range_(==, expr)) +#define _In_range_(lb, ub) _SAL2_Source_(_In_range_, (lb, ub), _In_range_impl_(lb, ub)) +#define _Out_range_(lb, ub) _SAL2_Source_(_Out_range_, (lb, ub), _Out_range_impl_(lb, ub)) +#define _Ret_range_(lb, ub) _SAL2_Source_(_Ret_range_, (lb, ub), _Ret_range_impl_(lb, ub)) +#define _Deref_in_range_(lb, ub) \ + _SAL2_Source_(_Deref_in_range_, (lb, ub), _Deref_in_range_impl_(lb, ub)) +#define _Deref_out_range_(lb, ub) \ + _SAL2_Source_(_Deref_out_range_, (lb, ub), _Deref_out_range_impl_(lb, ub)) +#define _Deref_ret_range_(lb, ub) \ + _SAL2_Source_(_Deref_ret_range_, (lb, ub), _Deref_ret_range_impl_(lb, ub)) +#define _Pre_equal_to_(expr) _SAL2_Source_(_Pre_equal_to_, (expr), _In_range_(==, expr)) +#define _Post_equal_to_(expr) _SAL2_Source_(_Post_equal_to_, (expr), _Out_range_(==, expr)) // annotation to express that a value (usually a field of a mutable class) // is not changed by a function call -#define _Unchanged_(e) _SAL2_Source_(_Unchanged_, (e), _At_(e, _Post_equal_to_(_Old_(e)) _Const_)) +#define _Unchanged_(e) _SAL2_Source_(_Unchanged_, (e), _At_(e, _Post_equal_to_(_Old_(e)) _Const_)) // Annotations to allow expressing generalized pre and post conditions. // 'cond' may be any valid SAL expression that is considered to be true as a precondition // or postcondition (respsectively). -#define _Pre_satisfies_(cond) _SAL2_Source_(_Pre_satisfies_, (cond), _Pre_satisfies_impl_(cond)) -#define _Post_satisfies_(cond) _SAL2_Source_(_Post_satisfies_, (cond), _Post_satisfies_impl_(cond)) +#define _Pre_satisfies_(cond) _SAL2_Source_(_Pre_satisfies_, (cond), _Pre_satisfies_impl_(cond)) +#define _Post_satisfies_(cond) _SAL2_Source_(_Post_satisfies_, (cond), _Post_satisfies_impl_(cond)) // Annotations to express struct, class and field invariants -#define _Struct_size_bytes_(size) _SAL2_Source_(_Struct_size_bytes_, (size), _Writable_bytes_(size)) +#define _Struct_size_bytes_(size) _SAL2_Source_(_Struct_size_bytes_, (size), _Writable_bytes_(size)) -#define _Field_size_(size) _SAL2_Source_(_Field_size_, (size), _Notnull_ _Writable_elements_(size)) -#define _Field_size_opt_(size) _SAL2_Source_(_Field_size_opt_, (size), _Maybenull_ _Writable_elements_(size)) -#define _Field_size_part_(size, count) _SAL2_Source_(_Field_size_part_, (size, count), _Notnull_ _Writable_elements_(size) _Readable_elements_(count)) -#define _Field_size_part_opt_(size, count) _SAL2_Source_(_Field_size_part_opt_, (size, count), _Maybenull_ _Writable_elements_(size) _Readable_elements_(count)) -#define _Field_size_full_(size) _SAL2_Source_(_Field_size_full_, (size), _Field_size_part_(size, size)) -#define _Field_size_full_opt_(size) _SAL2_Source_(_Field_size_full_opt_, (size), _Field_size_part_opt_(size, size)) +#define _Field_size_(size) _SAL2_Source_(_Field_size_, (size), _Notnull_ _Writable_elements_(size)) +#define _Field_size_opt_(size) \ + _SAL2_Source_(_Field_size_opt_, (size), _Maybenull_ _Writable_elements_(size)) +#define _Field_size_part_(size, count) \ + _SAL2_Source_(_Field_size_part_, (size, count), \ + _Notnull_ _Writable_elements_(size) _Readable_elements_(count)) +#define _Field_size_part_opt_(size, count) \ + _SAL2_Source_(_Field_size_part_opt_, (size, count), \ + _Maybenull_ _Writable_elements_(size) _Readable_elements_(count)) +#define _Field_size_full_(size) \ + _SAL2_Source_(_Field_size_full_, (size), _Field_size_part_(size, size)) +#define _Field_size_full_opt_(size) \ + _SAL2_Source_(_Field_size_full_opt_, (size), _Field_size_part_opt_(size, size)) -#define _Field_size_bytes_(size) _SAL2_Source_(_Field_size_bytes_, (size), _Notnull_ _Writable_bytes_(size)) -#define _Field_size_bytes_opt_(size) _SAL2_Source_(_Field_size_bytes_opt_, (size), _Maybenull_ _Writable_bytes_(size)) -#define _Field_size_bytes_part_(size, count) _SAL2_Source_(_Field_size_bytes_part_, (size, count), _Notnull_ _Writable_bytes_(size) _Readable_bytes_(count)) -#define _Field_size_bytes_part_opt_(size, count) _SAL2_Source_(_Field_size_bytes_part_opt_, (size, count), _Maybenull_ _Writable_bytes_(size) _Readable_bytes_(count)) -#define _Field_size_bytes_full_(size) _SAL2_Source_(_Field_size_bytes_full_, (size), _Field_size_bytes_part_(size, size)) -#define _Field_size_bytes_full_opt_(size) _SAL2_Source_(_Field_size_bytes_full_opt_, (size), _Field_size_bytes_part_opt_(size, size)) +#define _Field_size_bytes_(size) \ + _SAL2_Source_(_Field_size_bytes_, (size), _Notnull_ _Writable_bytes_(size)) +#define _Field_size_bytes_opt_(size) \ + _SAL2_Source_(_Field_size_bytes_opt_, (size), _Maybenull_ _Writable_bytes_(size)) +#define _Field_size_bytes_part_(size, count) \ + _SAL2_Source_(_Field_size_bytes_part_, (size, count), \ + _Notnull_ _Writable_bytes_(size) _Readable_bytes_(count)) +#define _Field_size_bytes_part_opt_(size, count) \ + _SAL2_Source_(_Field_size_bytes_part_opt_, (size, count), \ + _Maybenull_ _Writable_bytes_(size) _Readable_bytes_(count)) +#define _Field_size_bytes_full_(size) \ + _SAL2_Source_(_Field_size_bytes_full_, (size), _Field_size_bytes_part_(size, size)) +#define _Field_size_bytes_full_opt_(size) \ + _SAL2_Source_(_Field_size_bytes_full_opt_, (size), _Field_size_bytes_part_opt_(size, size)) -#define _Field_z_ _SAL2_Source_(_Field_z_, (), _Null_terminated_) +#define _Field_z_ _SAL2_Source_(_Field_z_, (), _Null_terminated_) -#define _Field_range_(min,max) _SAL2_Source_(_Field_range_, (min,max), _Field_range_impl_(min,max)) +#define _Field_range_(min, max) \ + _SAL2_Source_(_Field_range_, (min, max), _Field_range_impl_(min, max)) //============================================================================ // _Pre_\_Post_ Layer: @@ -607,47 +848,59 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // Raw Pre/Post for declaring custom pre/post conditions // -#define _Pre_ _Pre_impl_ -#define _Post_ _Post_impl_ +#define _Pre_ _Pre_impl_ +#define _Post_ _Post_impl_ // // Validity property // -#define _Valid_ _Valid_impl_ -#define _Notvalid_ _Notvalid_impl_ -#define _Maybevalid_ _Maybevalid_impl_ +#define _Valid_ _Valid_impl_ +#define _Notvalid_ _Notvalid_impl_ +#define _Maybevalid_ _Maybevalid_impl_ // // Buffer size properties // // Expressing buffer sizes without specifying pre or post condition -#define _Readable_bytes_(size) _SAL2_Source_(_Readable_bytes_, (size), _Readable_bytes_impl_(size)) -#define _Readable_elements_(size) _SAL2_Source_(_Readable_elements_, (size), _Readable_elements_impl_(size)) -#define _Writable_bytes_(size) _SAL2_Source_(_Writable_bytes_, (size), _Writable_bytes_impl_(size)) -#define _Writable_elements_(size) _SAL2_Source_(_Writable_elements_, (size), _Writable_elements_impl_(size)) +#define _Readable_bytes_(size) _SAL2_Source_(_Readable_bytes_, (size), _Readable_bytes_impl_(size)) +#define _Readable_elements_(size) \ + _SAL2_Source_(_Readable_elements_, (size), _Readable_elements_impl_(size)) +#define _Writable_bytes_(size) _SAL2_Source_(_Writable_bytes_, (size), _Writable_bytes_impl_(size)) +#define _Writable_elements_(size) \ + _SAL2_Source_(_Writable_elements_, (size), _Writable_elements_impl_(size)) -#define _Null_terminated_ _SAL2_Source_(_Null_terminated_, (), _Null_terminated_impl_) -#define _NullNull_terminated_ _SAL2_Source_(_NullNull_terminated_, (), _NullNull_terminated_impl_) +#define _Null_terminated_ _SAL2_Source_(_Null_terminated_, (), _Null_terminated_impl_) +#define _NullNull_terminated_ _SAL2_Source_(_NullNull_terminated_, (), _NullNull_terminated_impl_) // Expressing buffer size as pre or post condition -#define _Pre_readable_size_(size) _SAL2_Source_(_Pre_readable_size_, (size), _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Pre_writable_size_(size) _SAL2_Source_(_Pre_writable_size_, (size), _Pre1_impl_(__cap_impl(size))) -#define _Pre_readable_byte_size_(size) _SAL2_Source_(_Pre_readable_byte_size_, (size), _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) -#define _Pre_writable_byte_size_(size) _SAL2_Source_(_Pre_writable_byte_size_, (size), _Pre1_impl_(__bytecap_impl(size))) +#define _Pre_readable_size_(size) \ + _SAL2_Source_(_Pre_readable_size_, (size), _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) +#define _Pre_writable_size_(size) \ + _SAL2_Source_(_Pre_writable_size_, (size), _Pre1_impl_(__cap_impl(size))) +#define _Pre_readable_byte_size_(size) \ + _SAL2_Source_(_Pre_readable_byte_size_, (size), \ + _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +#define _Pre_writable_byte_size_(size) \ + _SAL2_Source_(_Pre_writable_byte_size_, (size), _Pre1_impl_(__bytecap_impl(size))) -#define _Post_readable_size_(size) _SAL2_Source_(_Post_readable_size_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Post_writable_size_(size) _SAL2_Source_(_Post_writable_size_, (size), _Post1_impl_(__cap_impl(size))) -#define _Post_readable_byte_size_(size) _SAL2_Source_(_Post_readable_byte_size_, (size), _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) -#define _Post_writable_byte_size_(size) _SAL2_Source_(_Post_writable_byte_size_, (size), _Post1_impl_(__bytecap_impl(size))) +#define _Post_readable_size_(size) \ + _SAL2_Source_(_Post_readable_size_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Post_writable_size_(size) \ + _SAL2_Source_(_Post_writable_size_, (size), _Post1_impl_(__cap_impl(size))) +#define _Post_readable_byte_size_(size) \ + _SAL2_Source_(_Post_readable_byte_size_, (size), \ + _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +#define _Post_writable_byte_size_(size) \ + _SAL2_Source_(_Post_writable_byte_size_, (size), _Post1_impl_(__bytecap_impl(size))) // // Pointer null-ness properties // -#define _Null_ _Null_impl_ -#define _Notnull_ _Notnull_impl_ -#define _Maybenull_ _Maybenull_impl_ +#define _Null_ _Null_impl_ +#define _Notnull_ _Notnull_impl_ +#define _Maybenull_ _Maybenull_impl_ // // _Pre_ annotations --- @@ -656,21 +909,23 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // e.g. int strlen( _Pre_z_ const char* sz ); // buffer is a zero terminated string -#define _Pre_z_ _SAL2_Source_(_Pre_z_, (), _Pre1_impl_(__zterm_impl) _Pre_valid_impl_) +#define _Pre_z_ _SAL2_Source_(_Pre_z_, (), _Pre1_impl_(__zterm_impl) _Pre_valid_impl_) // valid size unknown or indicated by type (e.g.:LPSTR) -#define _Pre_valid_ _SAL2_Source_(_Pre_valid_, (), _Pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) -#define _Pre_opt_valid_ _SAL2_Source_(_Pre_opt_valid_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) +#define _Pre_valid_ \ + _SAL2_Source_(_Pre_valid_, (), _Pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) +#define _Pre_opt_valid_ \ + _SAL2_Source_(_Pre_opt_valid_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) -#define _Pre_invalid_ _SAL2_Source_(_Pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) +#define _Pre_invalid_ _SAL2_Source_(_Pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) // Overrides recursive valid when some field is not yet initialized when using _Inout_ -#define _Pre_unknown_ _SAL2_Source_(_Pre_unknown_, (), _Pre1_impl_(__maybevalid_impl)) +#define _Pre_unknown_ _SAL2_Source_(_Pre_unknown_, (), _Pre1_impl_(__maybevalid_impl)) // used with allocated but not yet initialized objects -#define _Pre_notnull_ _SAL2_Source_(_Pre_notnull_, (), _Pre1_impl_(__notnull_impl_notref)) -#define _Pre_maybenull_ _SAL2_Source_(_Pre_maybenull_, (), _Pre1_impl_(__maybenull_impl_notref)) -#define _Pre_null_ _SAL2_Source_(_Pre_null_, (), _Pre1_impl_(__null_impl_notref)) +#define _Pre_notnull_ _SAL2_Source_(_Pre_notnull_, (), _Pre1_impl_(__notnull_impl_notref)) +#define _Pre_maybenull_ _SAL2_Source_(_Pre_maybenull_, (), _Pre1_impl_(__maybenull_impl_notref)) +#define _Pre_null_ _SAL2_Source_(_Pre_null_, (), _Pre1_impl_(__null_impl_notref)) // // _Post_ annotations --- @@ -679,25 +934,24 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // void CopyStr( _In_z_ const char* szFrom, _Pre_cap_(cch) _Post_z_ char* szFrom, size_t cchFrom ); // buffer will be a zero-terminated string after the call -#define _Post_z_ _SAL2_Source_(_Post_z_, (), _Post1_impl_(__zterm_impl) _Post_valid_impl_) +#define _Post_z_ _SAL2_Source_(_Post_z_, (), _Post1_impl_(__zterm_impl) _Post_valid_impl_) // e.g. HRESULT InitStruct( _Post_valid_ Struct* pobj ); -#define _Post_valid_ _SAL2_Source_(_Post_valid_, (), _Post_valid_impl_) -#define _Post_invalid_ _SAL2_Source_(_Post_invalid_, (), _Deref_post1_impl_(__notvalid_impl)) +#define _Post_valid_ _SAL2_Source_(_Post_valid_, (), _Post_valid_impl_) +#define _Post_invalid_ _SAL2_Source_(_Post_invalid_, (), _Deref_post1_impl_(__notvalid_impl)) // e.g. void free( _Post_ptr_invalid_ void* pv ); -#define _Post_ptr_invalid_ _SAL2_Source_(_Post_ptr_invalid_, (), _Post1_impl_(__notvalid_impl)) +#define _Post_ptr_invalid_ _SAL2_Source_(_Post_ptr_invalid_, (), _Post1_impl_(__notvalid_impl)) // e.g. void ThrowExceptionIfNull( _Post_notnull_ const void* pv ); -#define _Post_notnull_ _SAL2_Source_(_Post_notnull_, (), _Post1_impl_(__notnull_impl)) +#define _Post_notnull_ _SAL2_Source_(_Post_notnull_, (), _Post1_impl_(__notnull_impl)) // e.g. HRESULT GetObject(_Outptr_ _On_failure_(_At_(*p, _Post_null_)) T **p); -#define _Post_null_ _SAL2_Source_(_Post_null_, (), _Post1_impl_(__null_impl)) +#define _Post_null_ _SAL2_Source_(_Post_null_, (), _Post1_impl_(__null_impl)) -#define _Post_maybenull_ _SAL2_Source_(_Post_maybenull_, (), _Post1_impl_(__maybenull_impl)) - -#define _Prepost_z_ _SAL2_Source_(_Prepost_z_, (), _Pre_z_ _Post_z_) +#define _Post_maybenull_ _SAL2_Source_(_Post_maybenull_, (), _Post1_impl_(__maybenull_impl)) +#define _Prepost_z_ _SAL2_Source_(_Prepost_z_, (), _Pre_z_ _Post_z_) // #pragma region Input Buffer SAL 1 compatibility macros @@ -798,679 +1052,1483 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // e.g. void SetCharRange( _In_count_(cch) const char* rgch, size_t cch ) // valid buffer extent described by another parameter -#define _In_count_(size) _SAL1_1_Source_(_In_count_, (size), _Pre_count_(size) _Deref_pre_readonly_) -#define _In_opt_count_(size) _SAL1_1_Source_(_In_opt_count_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) -#define _In_bytecount_(size) _SAL1_1_Source_(_In_bytecount_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) -#define _In_opt_bytecount_(size) _SAL1_1_Source_(_In_opt_bytecount_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) +#define _In_count_(size) _SAL1_1_Source_(_In_count_, (size), _Pre_count_(size) _Deref_pre_readonly_) +#define _In_opt_count_(size) \ + _SAL1_1_Source_(_In_opt_count_, (size), _Pre_opt_count_(size) _Deref_pre_readonly_) +#define _In_bytecount_(size) \ + _SAL1_1_Source_(_In_bytecount_, (size), _Pre_bytecount_(size) _Deref_pre_readonly_) +#define _In_opt_bytecount_(size) \ + _SAL1_1_Source_(_In_opt_bytecount_, (size), _Pre_opt_bytecount_(size) _Deref_pre_readonly_) // valid buffer extent described by a constant extression -#define _In_count_c_(size) _SAL1_1_Source_(_In_count_c_, (size), _Pre_count_c_(size) _Deref_pre_readonly_) -#define _In_opt_count_c_(size) _SAL1_1_Source_(_In_opt_count_c_, (size), _Pre_opt_count_c_(size) _Deref_pre_readonly_) -#define _In_bytecount_c_(size) _SAL1_1_Source_(_In_bytecount_c_, (size), _Pre_bytecount_c_(size) _Deref_pre_readonly_) -#define _In_opt_bytecount_c_(size) _SAL1_1_Source_(_In_opt_bytecount_c_, (size), _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_count_c_(size) \ + _SAL1_1_Source_(_In_count_c_, (size), _Pre_count_c_(size) _Deref_pre_readonly_) +#define _In_opt_count_c_(size) \ + _SAL1_1_Source_(_In_opt_count_c_, (size), _Pre_opt_count_c_(size) _Deref_pre_readonly_) +#define _In_bytecount_c_(size) \ + _SAL1_1_Source_(_In_bytecount_c_, (size), _Pre_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_In_opt_bytecount_c_, (size), _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) // nullterminated 'input' buffers with given size // e.g. void SetCharRange( _In_count_(cch) const char* rgch, size_t cch ) // nullterminated valid buffer extent described by another parameter -#define _In_z_count_(size) _SAL1_1_Source_(_In_z_count_, (size), _Pre_z_ _Pre_count_(size) _Deref_pre_readonly_) -#define _In_opt_z_count_(size) _SAL1_1_Source_(_In_opt_z_count_, (size), _Pre_opt_z_ _Pre_opt_count_(size) _Deref_pre_readonly_) -#define _In_z_bytecount_(size) _SAL1_1_Source_(_In_z_bytecount_, (size), _Pre_z_ _Pre_bytecount_(size) _Deref_pre_readonly_) -#define _In_opt_z_bytecount_(size) _SAL1_1_Source_(_In_opt_z_bytecount_, (size), _Pre_opt_z_ _Pre_opt_bytecount_(size) _Deref_pre_readonly_) +#define _In_z_count_(size) \ + _SAL1_1_Source_(_In_z_count_, (size), _Pre_z_ _Pre_count_(size) _Deref_pre_readonly_) +#define _In_opt_z_count_(size) \ + _SAL1_1_Source_(_In_opt_z_count_, (size), \ + _Pre_opt_z_ _Pre_opt_count_(size) _Deref_pre_readonly_) +#define _In_z_bytecount_(size) \ + _SAL1_1_Source_(_In_z_bytecount_, (size), _Pre_z_ _Pre_bytecount_(size) _Deref_pre_readonly_) +#define _In_opt_z_bytecount_(size) \ + _SAL1_1_Source_(_In_opt_z_bytecount_, (size), \ + _Pre_opt_z_ _Pre_opt_bytecount_(size) _Deref_pre_readonly_) // nullterminated valid buffer extent described by a constant extression -#define _In_z_count_c_(size) _SAL1_1_Source_(_In_z_count_c_, (size), _Pre_z_ _Pre_count_c_(size) _Deref_pre_readonly_) -#define _In_opt_z_count_c_(size) _SAL1_1_Source_(_In_opt_z_count_c_, (size), _Pre_opt_z_ _Pre_opt_count_c_(size) _Deref_pre_readonly_) -#define _In_z_bytecount_c_(size) _SAL1_1_Source_(_In_z_bytecount_c_, (size), _Pre_z_ _Pre_bytecount_c_(size) _Deref_pre_readonly_) -#define _In_opt_z_bytecount_c_(size) _SAL1_1_Source_(_In_opt_z_bytecount_c_, (size), _Pre_opt_z_ _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_z_count_c_(size) \ + _SAL1_1_Source_(_In_z_count_c_, (size), _Pre_z_ _Pre_count_c_(size) _Deref_pre_readonly_) +#define _In_opt_z_count_c_(size) \ + _SAL1_1_Source_(_In_opt_z_count_c_, (size), \ + _Pre_opt_z_ _Pre_opt_count_c_(size) _Deref_pre_readonly_) +#define _In_z_bytecount_c_(size) \ + _SAL1_1_Source_(_In_z_bytecount_c_, (size), \ + _Pre_z_ _Pre_bytecount_c_(size) _Deref_pre_readonly_) +#define _In_opt_z_bytecount_c_(size) \ + _SAL1_1_Source_(_In_opt_z_bytecount_c_, (size), \ + _Pre_opt_z_ _Pre_opt_bytecount_c_(size) _Deref_pre_readonly_) // buffer capacity is described by another pointer -// e.g. void Foo( _In_ptrdiff_count_(pchMax) const char* pch, const char* pchMax ) { while pch < pchMax ) pch++; } -#define _In_ptrdiff_count_(size) _SAL1_1_Source_(_In_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size) _Deref_pre_readonly_) -#define _In_opt_ptrdiff_count_(size) _SAL1_1_Source_(_In_opt_ptrdiff_count_, (size), _Pre_opt_ptrdiff_count_(size) _Deref_pre_readonly_) +// e.g. void Foo( _In_ptrdiff_count_(pchMax) const char* pch, const char* pchMax ) { while pch < +// pchMax ) pch++; } +#define _In_ptrdiff_count_(size) \ + _SAL1_1_Source_(_In_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size) _Deref_pre_readonly_) +#define _In_opt_ptrdiff_count_(size) \ + _SAL1_1_Source_(_In_opt_ptrdiff_count_, (size), \ + _Pre_opt_ptrdiff_count_(size) _Deref_pre_readonly_) // 'x' version for complex expressions that are not supported by the current compiler version // e.g. void Set3ColMatrix( _In_count_x_(3*cRows) const Elem* matrix, int cRows ); -#define _In_count_x_(size) _SAL1_1_Source_(_In_count_x_, (size), _Pre_count_x_(size) _Deref_pre_readonly_) -#define _In_opt_count_x_(size) _SAL1_1_Source_(_In_opt_count_x_, (size), _Pre_opt_count_x_(size) _Deref_pre_readonly_) -#define _In_bytecount_x_(size) _SAL1_1_Source_(_In_bytecount_x_, (size), _Pre_bytecount_x_(size) _Deref_pre_readonly_) -#define _In_opt_bytecount_x_(size) _SAL1_1_Source_(_In_opt_bytecount_x_, (size), _Pre_opt_bytecount_x_(size) _Deref_pre_readonly_) - +#define _In_count_x_(size) \ + _SAL1_1_Source_(_In_count_x_, (size), _Pre_count_x_(size) _Deref_pre_readonly_) +#define _In_opt_count_x_(size) \ + _SAL1_1_Source_(_In_opt_count_x_, (size), _Pre_opt_count_x_(size) _Deref_pre_readonly_) +#define _In_bytecount_x_(size) \ + _SAL1_1_Source_(_In_bytecount_x_, (size), _Pre_bytecount_x_(size) _Deref_pre_readonly_) +#define _In_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_In_opt_bytecount_x_, (size), _Pre_opt_bytecount_x_(size) _Deref_pre_readonly_) // 'out' with buffer size // e.g. void GetIndices( _Out_cap_(cIndices) int* rgIndices, size_t cIndices ); // buffer capacity is described by another parameter -#define _Out_cap_(size) _SAL1_1_Source_(_Out_cap_, (size), _Pre_cap_(size) _Post_valid_impl_) -#define _Out_opt_cap_(size) _SAL1_1_Source_(_Out_opt_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) -#define _Out_bytecap_(size) _SAL1_1_Source_(_Out_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_) -#define _Out_opt_bytecap_(size) _SAL1_1_Source_(_Out_opt_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) +#define _Out_cap_(size) _SAL1_1_Source_(_Out_cap_, (size), _Pre_cap_(size) _Post_valid_impl_) +#define _Out_opt_cap_(size) \ + _SAL1_1_Source_(_Out_opt_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_) +#define _Out_bytecap_(size) \ + _SAL1_1_Source_(_Out_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_) +#define _Out_opt_bytecap_(size) \ + _SAL1_1_Source_(_Out_opt_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_) // buffer capacity is described by a constant expression -#define _Out_cap_c_(size) _SAL1_1_Source_(_Out_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_) -#define _Out_opt_cap_c_(size) _SAL1_1_Source_(_Out_opt_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_) -#define _Out_bytecap_c_(size) _SAL1_1_Source_(_Out_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_) -#define _Out_opt_bytecap_c_(size) _SAL1_1_Source_(_Out_opt_bytecap_c_, (size), _Pre_opt_bytecap_c_(size) _Post_valid_impl_) +#define _Out_cap_c_(size) _SAL1_1_Source_(_Out_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_) +#define _Out_opt_cap_c_(size) \ + _SAL1_1_Source_(_Out_opt_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_) +#define _Out_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_) +#define _Out_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_opt_bytecap_c_, (size), _Pre_opt_bytecap_c_(size) _Post_valid_impl_) // buffer capacity is described by another parameter multiplied by a constant expression -#define _Out_cap_m_(mult,size) _SAL1_1_Source_(_Out_cap_m_, (mult,size), _Pre_cap_m_(mult,size) _Post_valid_impl_) -#define _Out_opt_cap_m_(mult,size) _SAL1_1_Source_(_Out_opt_cap_m_, (mult,size), _Pre_opt_cap_m_(mult,size) _Post_valid_impl_) -#define _Out_z_cap_m_(mult,size) _SAL1_1_Source_(_Out_z_cap_m_, (mult,size), _Pre_cap_m_(mult,size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_m_(mult,size) _SAL1_1_Source_(_Out_opt_z_cap_m_, (mult,size), _Pre_opt_cap_m_(mult,size) _Post_valid_impl_ _Post_z_) +#define _Out_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_cap_m_, (mult, size), _Pre_cap_m_(mult, size) _Post_valid_impl_) +#define _Out_opt_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_opt_cap_m_, (mult, size), _Pre_opt_cap_m_(mult, size) _Post_valid_impl_) +#define _Out_z_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_z_cap_m_, (mult, size), _Pre_cap_m_(mult, size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_m_(mult, size) \ + _SAL1_1_Source_(_Out_opt_z_cap_m_, (mult, size), \ + _Pre_opt_cap_m_(mult, size) _Post_valid_impl_ _Post_z_) // buffer capacity is described by another pointer -// e.g. void Foo( _Out_ptrdiff_cap_(pchMax) char* pch, const char* pchMax ) { while pch < pchMax ) pch++; } -#define _Out_ptrdiff_cap_(size) _SAL1_1_Source_(_Out_ptrdiff_cap_, (size), _Pre_ptrdiff_cap_(size) _Post_valid_impl_) -#define _Out_opt_ptrdiff_cap_(size) _SAL1_1_Source_(_Out_opt_ptrdiff_cap_, (size), _Pre_opt_ptrdiff_cap_(size) _Post_valid_impl_) +// e.g. void Foo( _Out_ptrdiff_cap_(pchMax) char* pch, const char* pchMax ) { while pch < pchMax ) +// pch++; } +#define _Out_ptrdiff_cap_(size) \ + _SAL1_1_Source_(_Out_ptrdiff_cap_, (size), _Pre_ptrdiff_cap_(size) _Post_valid_impl_) +#define _Out_opt_ptrdiff_cap_(size) \ + _SAL1_1_Source_(_Out_opt_ptrdiff_cap_, (size), _Pre_opt_ptrdiff_cap_(size) _Post_valid_impl_) // buffer capacity is described by a complex expression -#define _Out_cap_x_(size) _SAL1_1_Source_(_Out_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_) -#define _Out_opt_cap_x_(size) _SAL1_1_Source_(_Out_opt_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_) -#define _Out_bytecap_x_(size) _SAL1_1_Source_(_Out_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_) -#define _Out_opt_bytecap_x_(size) _SAL1_1_Source_(_Out_opt_bytecap_x_, (size), _Pre_opt_bytecap_x_(size) _Post_valid_impl_) +#define _Out_cap_x_(size) _SAL1_1_Source_(_Out_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_) +#define _Out_opt_cap_x_(size) \ + _SAL1_1_Source_(_Out_opt_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_) +#define _Out_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_) +#define _Out_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_opt_bytecap_x_, (size), _Pre_opt_bytecap_x_(size) _Post_valid_impl_) // a zero terminated string is filled into a buffer of given capacity // e.g. void CopyStr( _In_z_ const char* szFrom, _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); // buffer capacity is described by another parameter -#define _Out_z_cap_(size) _SAL1_1_Source_(_Out_z_cap_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_(size) _SAL1_1_Source_(_Out_opt_z_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_z_bytecap_(size) _SAL1_1_Source_(_Out_z_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_bytecap_(size) _SAL1_1_Source_(_Out_opt_z_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_cap_(size) \ + _SAL1_1_Source_(_Out_z_cap_, (size), _Pre_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_(size) \ + _SAL1_1_Source_(_Out_opt_z_cap_, (size), _Pre_opt_cap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_bytecap_(size) \ + _SAL1_1_Source_(_Out_z_bytecap_, (size), _Pre_bytecap_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_, (size), _Pre_opt_bytecap_(size) _Post_valid_impl_ _Post_z_) // buffer capacity is described by a constant expression -#define _Out_z_cap_c_(size) _SAL1_1_Source_(_Out_z_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_c_(size) _SAL1_1_Source_(_Out_opt_z_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_ _Post_z_) -#define _Out_z_bytecap_c_(size) _SAL1_1_Source_(_Out_z_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Out_opt_z_bytecap_c_, (size), _Pre_opt_bytecap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_cap_c_(size) \ + _SAL1_1_Source_(_Out_z_cap_c_, (size), _Pre_cap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Out_opt_z_cap_c_, (size), _Pre_opt_cap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_z_bytecap_c_, (size), _Pre_bytecap_c_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_c_, (size), \ + _Pre_opt_bytecap_c_(size) _Post_valid_impl_ _Post_z_) // buffer capacity is described by a complex expression -#define _Out_z_cap_x_(size) _SAL1_1_Source_(_Out_z_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_cap_x_(size) _SAL1_1_Source_(_Out_opt_z_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_ _Post_z_) -#define _Out_z_bytecap_x_(size) _SAL1_1_Source_(_Out_z_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_ _Post_z_) -#define _Out_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Out_opt_z_bytecap_x_, (size), _Pre_opt_bytecap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_cap_x_(size) \ + _SAL1_1_Source_(_Out_z_cap_x_, (size), _Pre_cap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Out_opt_z_cap_x_, (size), _Pre_opt_cap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_z_bytecap_x_, (size), _Pre_bytecap_x_(size) _Post_valid_impl_ _Post_z_) +#define _Out_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_x_, (size), \ + _Pre_opt_bytecap_x_(size) _Post_valid_impl_ _Post_z_) // a zero terminated string is filled into a buffer of given capacity -// e.g. size_t CopyCharRange( _In_count_(cchFrom) const char* rgchFrom, size_t cchFrom, _Out_cap_post_count_(cchTo,return)) char* rgchTo, size_t cchTo ); -#define _Out_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_cap_post_count_, (cap,count), _Pre_cap_(cap) _Post_valid_impl_ _Post_count_(count)) -#define _Out_opt_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_opt_cap_post_count_, (cap,count), _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_count_(count)) -#define _Out_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_bytecap_post_bytecount_, (cap,count), _Pre_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) -#define _Out_opt_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_opt_bytecap_post_bytecount_, (cap,count), _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) +// e.g. size_t CopyCharRange( _In_count_(cchFrom) const char* rgchFrom, size_t cchFrom, +// _Out_cap_post_count_(cchTo,return)) char* rgchTo, size_t cchTo ); +#define _Out_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_cap_post_count_, (cap, count), \ + _Pre_cap_(cap) _Post_valid_impl_ _Post_count_(count)) +#define _Out_opt_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_opt_cap_post_count_, (cap, count), \ + _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_count_(count)) +#define _Out_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_bytecap_post_bytecount_, (cap, count), \ + _Pre_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) +#define _Out_opt_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_opt_bytecap_post_bytecount_, (cap, count), \ + _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_bytecount_(count)) // a zero terminated string is filled into a buffer of given capacity -// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Out_z_cap_post_count_(cchTo,return+1) char* szTo, size_t cchTo ); -#define _Out_z_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_z_cap_post_count_, (cap,count), _Pre_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) -#define _Out_opt_z_cap_post_count_(cap,count) _SAL1_1_Source_(_Out_opt_z_cap_post_count_, (cap,count), _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) -#define _Out_z_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_z_bytecap_post_bytecount_, (cap,count), _Pre_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) -#define _Out_opt_z_bytecap_post_bytecount_(cap,count) _SAL1_1_Source_(_Out_opt_z_bytecap_post_bytecount_, (cap,count), _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) +// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Out_z_cap_post_count_(cchTo,return+1) char* +// szTo, size_t cchTo ); +#define _Out_z_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_z_cap_post_count_, (cap, count), \ + _Pre_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) +#define _Out_opt_z_cap_post_count_(cap, count) \ + _SAL1_1_Source_(_Out_opt_z_cap_post_count_, (cap, count), \ + _Pre_opt_cap_(cap) _Post_valid_impl_ _Post_z_count_(count)) +#define _Out_z_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_z_bytecap_post_bytecount_, (cap, count), \ + _Pre_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) +#define _Out_opt_z_bytecap_post_bytecount_(cap, count) \ + _SAL1_1_Source_(_Out_opt_z_bytecap_post_bytecount_, (cap, count), \ + _Pre_opt_bytecap_(cap) _Post_valid_impl_ _Post_z_bytecount_(count)) // only use with dereferenced arguments e.g. '*pcch' -#define _Out_capcount_(capcount) _SAL1_1_Source_(_Out_capcount_, (capcount), _Pre_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) -#define _Out_opt_capcount_(capcount) _SAL1_1_Source_(_Out_opt_capcount_, (capcount), _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) -#define _Out_bytecapcount_(capcount) _SAL1_1_Source_(_Out_bytecapcount_, (capcount), _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) -#define _Out_opt_bytecapcount_(capcount) _SAL1_1_Source_(_Out_opt_bytecapcount_, (capcount), _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) +#define _Out_capcount_(capcount) \ + _SAL1_1_Source_(_Out_capcount_, (capcount), \ + _Pre_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) +#define _Out_opt_capcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_capcount_, (capcount), \ + _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_count_(capcount)) +#define _Out_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_bytecapcount_, (capcount), \ + _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) +#define _Out_opt_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_bytecapcount_, (capcount), \ + _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_bytecount_(capcount)) -#define _Out_capcount_x_(capcount) _SAL1_1_Source_(_Out_capcount_x_, (capcount), _Pre_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) -#define _Out_opt_capcount_x_(capcount) _SAL1_1_Source_(_Out_opt_capcount_x_, (capcount), _Pre_opt_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) -#define _Out_bytecapcount_x_(capcount) _SAL1_1_Source_(_Out_bytecapcount_x_, (capcount), _Pre_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) -#define _Out_opt_bytecapcount_x_(capcount) _SAL1_1_Source_(_Out_opt_bytecapcount_x_, (capcount), _Pre_opt_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) +#define _Out_capcount_x_(capcount) \ + _SAL1_1_Source_(_Out_capcount_x_, (capcount), \ + _Pre_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) +#define _Out_opt_capcount_x_(capcount) \ + _SAL1_1_Source_(_Out_opt_capcount_x_, (capcount), \ + _Pre_opt_cap_x_(capcount) _Post_valid_impl_ _Post_count_x_(capcount)) +#define _Out_bytecapcount_x_(capcount) \ + _SAL1_1_Source_(_Out_bytecapcount_x_, (capcount), \ + _Pre_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) +#define _Out_opt_bytecapcount_x_(capcount) \ + _SAL1_1_Source_(_Out_opt_bytecapcount_x_, (capcount), \ + _Pre_opt_bytecap_x_(capcount) _Post_valid_impl_ _Post_bytecount_x_(capcount)) // e.g. GetString( _Out_z_capcount_(*pLen+1) char* sz, size_t* pLen ); -#define _Out_z_capcount_(capcount) _SAL1_1_Source_(_Out_z_capcount_, (capcount), _Pre_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) -#define _Out_opt_z_capcount_(capcount) _SAL1_1_Source_(_Out_opt_z_capcount_, (capcount), _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) -#define _Out_z_bytecapcount_(capcount) _SAL1_1_Source_(_Out_z_bytecapcount_, (capcount), _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) -#define _Out_opt_z_bytecapcount_(capcount) _SAL1_1_Source_(_Out_opt_z_bytecapcount_, (capcount), _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) - +#define _Out_z_capcount_(capcount) \ + _SAL1_1_Source_(_Out_z_capcount_, (capcount), \ + _Pre_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) +#define _Out_opt_z_capcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_z_capcount_, (capcount), \ + _Pre_opt_cap_(capcount) _Post_valid_impl_ _Post_z_count_(capcount)) +#define _Out_z_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_z_bytecapcount_, (capcount), \ + _Pre_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) +#define _Out_opt_z_bytecapcount_(capcount) \ + _SAL1_1_Source_(_Out_opt_z_bytecapcount_, (capcount), \ + _Pre_opt_bytecap_(capcount) _Post_valid_impl_ _Post_z_bytecount_(capcount)) // 'inout' buffers with initialized elements before and after the call // e.g. void ModifyIndices( _Inout_count_(cIndices) int* rgIndices, size_t cIndices ); -#define _Inout_count_(size) _SAL1_1_Source_(_Inout_count_, (size), _Prepost_count_(size)) -#define _Inout_opt_count_(size) _SAL1_1_Source_(_Inout_opt_count_, (size), _Prepost_opt_count_(size)) -#define _Inout_bytecount_(size) _SAL1_1_Source_(_Inout_bytecount_, (size), _Prepost_bytecount_(size)) -#define _Inout_opt_bytecount_(size) _SAL1_1_Source_(_Inout_opt_bytecount_, (size), _Prepost_opt_bytecount_(size)) +#define _Inout_count_(size) _SAL1_1_Source_(_Inout_count_, (size), _Prepost_count_(size)) +#define _Inout_opt_count_(size) \ + _SAL1_1_Source_(_Inout_opt_count_, (size), _Prepost_opt_count_(size)) +#define _Inout_bytecount_(size) \ + _SAL1_1_Source_(_Inout_bytecount_, (size), _Prepost_bytecount_(size)) +#define _Inout_opt_bytecount_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecount_, (size), _Prepost_opt_bytecount_(size)) -#define _Inout_count_c_(size) _SAL1_1_Source_(_Inout_count_c_, (size), _Prepost_count_c_(size)) -#define _Inout_opt_count_c_(size) _SAL1_1_Source_(_Inout_opt_count_c_, (size), _Prepost_opt_count_c_(size)) -#define _Inout_bytecount_c_(size) _SAL1_1_Source_(_Inout_bytecount_c_, (size), _Prepost_bytecount_c_(size)) -#define _Inout_opt_bytecount_c_(size) _SAL1_1_Source_(_Inout_opt_bytecount_c_, (size), _Prepost_opt_bytecount_c_(size)) +#define _Inout_count_c_(size) _SAL1_1_Source_(_Inout_count_c_, (size), _Prepost_count_c_(size)) +#define _Inout_opt_count_c_(size) \ + _SAL1_1_Source_(_Inout_opt_count_c_, (size), _Prepost_opt_count_c_(size)) +#define _Inout_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_bytecount_c_, (size), _Prepost_bytecount_c_(size)) +#define _Inout_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecount_c_, (size), _Prepost_opt_bytecount_c_(size)) // nullterminated 'inout' buffers with initialized elements before and after the call // e.g. void ModifyIndices( _Inout_count_(cIndices) int* rgIndices, size_t cIndices ); -#define _Inout_z_count_(size) _SAL1_1_Source_(_Inout_z_count_, (size), _Prepost_z_ _Prepost_count_(size)) -#define _Inout_opt_z_count_(size) _SAL1_1_Source_(_Inout_opt_z_count_, (size), _Prepost_z_ _Prepost_opt_count_(size)) -#define _Inout_z_bytecount_(size) _SAL1_1_Source_(_Inout_z_bytecount_, (size), _Prepost_z_ _Prepost_bytecount_(size)) -#define _Inout_opt_z_bytecount_(size) _SAL1_1_Source_(_Inout_opt_z_bytecount_, (size), _Prepost_z_ _Prepost_opt_bytecount_(size)) +#define _Inout_z_count_(size) \ + _SAL1_1_Source_(_Inout_z_count_, (size), _Prepost_z_ _Prepost_count_(size)) +#define _Inout_opt_z_count_(size) \ + _SAL1_1_Source_(_Inout_opt_z_count_, (size), _Prepost_z_ _Prepost_opt_count_(size)) +#define _Inout_z_bytecount_(size) \ + _SAL1_1_Source_(_Inout_z_bytecount_, (size), _Prepost_z_ _Prepost_bytecount_(size)) +#define _Inout_opt_z_bytecount_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecount_, (size), _Prepost_z_ _Prepost_opt_bytecount_(size)) -#define _Inout_z_count_c_(size) _SAL1_1_Source_(_Inout_z_count_c_, (size), _Prepost_z_ _Prepost_count_c_(size)) -#define _Inout_opt_z_count_c_(size) _SAL1_1_Source_(_Inout_opt_z_count_c_, (size), _Prepost_z_ _Prepost_opt_count_c_(size)) -#define _Inout_z_bytecount_c_(size) _SAL1_1_Source_(_Inout_z_bytecount_c_, (size), _Prepost_z_ _Prepost_bytecount_c_(size)) -#define _Inout_opt_z_bytecount_c_(size) _SAL1_1_Source_(_Inout_opt_z_bytecount_c_, (size), _Prepost_z_ _Prepost_opt_bytecount_c_(size)) +#define _Inout_z_count_c_(size) \ + _SAL1_1_Source_(_Inout_z_count_c_, (size), _Prepost_z_ _Prepost_count_c_(size)) +#define _Inout_opt_z_count_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_count_c_, (size), _Prepost_z_ _Prepost_opt_count_c_(size)) +#define _Inout_z_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_z_bytecount_c_, (size), _Prepost_z_ _Prepost_bytecount_c_(size)) +#define _Inout_opt_z_bytecount_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecount_c_, (size), _Prepost_z_ _Prepost_opt_bytecount_c_(size)) -#define _Inout_ptrdiff_count_(size) _SAL1_1_Source_(_Inout_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size)) -#define _Inout_opt_ptrdiff_count_(size) _SAL1_1_Source_(_Inout_opt_ptrdiff_count_, (size), _Pre_opt_ptrdiff_count_(size)) +#define _Inout_ptrdiff_count_(size) \ + _SAL1_1_Source_(_Inout_ptrdiff_count_, (size), _Pre_ptrdiff_count_(size)) +#define _Inout_opt_ptrdiff_count_(size) \ + _SAL1_1_Source_(_Inout_opt_ptrdiff_count_, (size), _Pre_opt_ptrdiff_count_(size)) -#define _Inout_count_x_(size) _SAL1_1_Source_(_Inout_count_x_, (size), _Prepost_count_x_(size)) -#define _Inout_opt_count_x_(size) _SAL1_1_Source_(_Inout_opt_count_x_, (size), _Prepost_opt_count_x_(size)) -#define _Inout_bytecount_x_(size) _SAL1_1_Source_(_Inout_bytecount_x_, (size), _Prepost_bytecount_x_(size)) -#define _Inout_opt_bytecount_x_(size) _SAL1_1_Source_(_Inout_opt_bytecount_x_, (size), _Prepost_opt_bytecount_x_(size)) +#define _Inout_count_x_(size) _SAL1_1_Source_(_Inout_count_x_, (size), _Prepost_count_x_(size)) +#define _Inout_opt_count_x_(size) \ + _SAL1_1_Source_(_Inout_opt_count_x_, (size), _Prepost_opt_count_x_(size)) +#define _Inout_bytecount_x_(size) \ + _SAL1_1_Source_(_Inout_bytecount_x_, (size), _Prepost_bytecount_x_(size)) +#define _Inout_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecount_x_, (size), _Prepost_opt_bytecount_x_(size)) // e.g. void AppendToLPSTR( _In_ LPCSTR szFrom, _Inout_cap_(cchTo) LPSTR* szTo, size_t cchTo ); -#define _Inout_cap_(size) _SAL1_1_Source_(_Inout_cap_, (size), _Pre_valid_cap_(size) _Post_valid_) -#define _Inout_opt_cap_(size) _SAL1_1_Source_(_Inout_opt_cap_, (size), _Pre_opt_valid_cap_(size) _Post_valid_) -#define _Inout_bytecap_(size) _SAL1_1_Source_(_Inout_bytecap_, (size), _Pre_valid_bytecap_(size) _Post_valid_) -#define _Inout_opt_bytecap_(size) _SAL1_1_Source_(_Inout_opt_bytecap_, (size), _Pre_opt_valid_bytecap_(size) _Post_valid_) +#define _Inout_cap_(size) _SAL1_1_Source_(_Inout_cap_, (size), _Pre_valid_cap_(size) _Post_valid_) +#define _Inout_opt_cap_(size) \ + _SAL1_1_Source_(_Inout_opt_cap_, (size), _Pre_opt_valid_cap_(size) _Post_valid_) +#define _Inout_bytecap_(size) \ + _SAL1_1_Source_(_Inout_bytecap_, (size), _Pre_valid_bytecap_(size) _Post_valid_) +#define _Inout_opt_bytecap_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecap_, (size), _Pre_opt_valid_bytecap_(size) _Post_valid_) -#define _Inout_cap_c_(size) _SAL1_1_Source_(_Inout_cap_c_, (size), _Pre_valid_cap_c_(size) _Post_valid_) -#define _Inout_opt_cap_c_(size) _SAL1_1_Source_(_Inout_opt_cap_c_, (size), _Pre_opt_valid_cap_c_(size) _Post_valid_) -#define _Inout_bytecap_c_(size) _SAL1_1_Source_(_Inout_bytecap_c_, (size), _Pre_valid_bytecap_c_(size) _Post_valid_) -#define _Inout_opt_bytecap_c_(size) _SAL1_1_Source_(_Inout_opt_bytecap_c_, (size), _Pre_opt_valid_bytecap_c_(size) _Post_valid_) +#define _Inout_cap_c_(size) \ + _SAL1_1_Source_(_Inout_cap_c_, (size), _Pre_valid_cap_c_(size) _Post_valid_) +#define _Inout_opt_cap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_cap_c_, (size), _Pre_opt_valid_cap_c_(size) _Post_valid_) +#define _Inout_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_bytecap_c_, (size), _Pre_valid_bytecap_c_(size) _Post_valid_) +#define _Inout_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecap_c_, (size), _Pre_opt_valid_bytecap_c_(size) _Post_valid_) -#define _Inout_cap_x_(size) _SAL1_1_Source_(_Inout_cap_x_, (size), _Pre_valid_cap_x_(size) _Post_valid_) -#define _Inout_opt_cap_x_(size) _SAL1_1_Source_(_Inout_opt_cap_x_, (size), _Pre_opt_valid_cap_x_(size) _Post_valid_) -#define _Inout_bytecap_x_(size) _SAL1_1_Source_(_Inout_bytecap_x_, (size), _Pre_valid_bytecap_x_(size) _Post_valid_) -#define _Inout_opt_bytecap_x_(size) _SAL1_1_Source_(_Inout_opt_bytecap_x_, (size), _Pre_opt_valid_bytecap_x_(size) _Post_valid_) +#define _Inout_cap_x_(size) \ + _SAL1_1_Source_(_Inout_cap_x_, (size), _Pre_valid_cap_x_(size) _Post_valid_) +#define _Inout_opt_cap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_cap_x_, (size), _Pre_opt_valid_cap_x_(size) _Post_valid_) +#define _Inout_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_bytecap_x_, (size), _Pre_valid_bytecap_x_(size) _Post_valid_) +#define _Inout_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_bytecap_x_, (size), _Pre_opt_valid_bytecap_x_(size) _Post_valid_) // inout string buffers with writable size // e.g. void AppendStr( _In_z_ const char* szFrom, _Inout_z_cap_(cchTo) char* szTo, size_t cchTo ); -#define _Inout_z_cap_(size) _SAL1_1_Source_(_Inout_z_cap_, (size), _Pre_z_cap_(size) _Post_z_) -#define _Inout_opt_z_cap_(size) _SAL1_1_Source_(_Inout_opt_z_cap_, (size), _Pre_opt_z_cap_(size) _Post_z_) -#define _Inout_z_bytecap_(size) _SAL1_1_Source_(_Inout_z_bytecap_, (size), _Pre_z_bytecap_(size) _Post_z_) -#define _Inout_opt_z_bytecap_(size) _SAL1_1_Source_(_Inout_opt_z_bytecap_, (size), _Pre_opt_z_bytecap_(size) _Post_z_) +#define _Inout_z_cap_(size) _SAL1_1_Source_(_Inout_z_cap_, (size), _Pre_z_cap_(size) _Post_z_) +#define _Inout_opt_z_cap_(size) \ + _SAL1_1_Source_(_Inout_opt_z_cap_, (size), _Pre_opt_z_cap_(size) _Post_z_) +#define _Inout_z_bytecap_(size) \ + _SAL1_1_Source_(_Inout_z_bytecap_, (size), _Pre_z_bytecap_(size) _Post_z_) +#define _Inout_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecap_, (size), _Pre_opt_z_bytecap_(size) _Post_z_) -#define _Inout_z_cap_c_(size) _SAL1_1_Source_(_Inout_z_cap_c_, (size), _Pre_z_cap_c_(size) _Post_z_) -#define _Inout_opt_z_cap_c_(size) _SAL1_1_Source_(_Inout_opt_z_cap_c_, (size), _Pre_opt_z_cap_c_(size) _Post_z_) -#define _Inout_z_bytecap_c_(size) _SAL1_1_Source_(_Inout_z_bytecap_c_, (size), _Pre_z_bytecap_c_(size) _Post_z_) -#define _Inout_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Inout_opt_z_bytecap_c_, (size), _Pre_opt_z_bytecap_c_(size) _Post_z_) - -#define _Inout_z_cap_x_(size) _SAL1_1_Source_(_Inout_z_cap_x_, (size), _Pre_z_cap_x_(size) _Post_z_) -#define _Inout_opt_z_cap_x_(size) _SAL1_1_Source_(_Inout_opt_z_cap_x_, (size), _Pre_opt_z_cap_x_(size) _Post_z_) -#define _Inout_z_bytecap_x_(size) _SAL1_1_Source_(_Inout_z_bytecap_x_, (size), _Pre_z_bytecap_x_(size) _Post_z_) -#define _Inout_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Inout_opt_z_bytecap_x_, (size), _Pre_opt_z_bytecap_x_(size) _Post_z_) +#define _Inout_z_cap_c_(size) _SAL1_1_Source_(_Inout_z_cap_c_, (size), _Pre_z_cap_c_(size) _Post_z_) +#define _Inout_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_cap_c_, (size), _Pre_opt_z_cap_c_(size) _Post_z_) +#define _Inout_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_z_bytecap_c_, (size), _Pre_z_bytecap_c_(size) _Post_z_) +#define _Inout_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecap_c_, (size), _Pre_opt_z_bytecap_c_(size) _Post_z_) +#define _Inout_z_cap_x_(size) _SAL1_1_Source_(_Inout_z_cap_x_, (size), _Pre_z_cap_x_(size) _Post_z_) +#define _Inout_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_z_cap_x_, (size), _Pre_opt_z_cap_x_(size) _Post_z_) +#define _Inout_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_z_bytecap_x_, (size), _Pre_z_bytecap_x_(size) _Post_z_) +#define _Inout_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Inout_opt_z_bytecap_x_, (size), _Pre_opt_z_bytecap_x_(size) _Post_z_) // returning pointers to valid objects -#define _Ret_ _SAL1_1_Source_(_Ret_, (), _Ret_valid_) -#define _Ret_opt_ _SAL1_1_Source_(_Ret_opt_, (), _Ret_opt_valid_) +#define _Ret_ _SAL1_1_Source_(_Ret_, (), _Ret_valid_) +#define _Ret_opt_ _SAL1_1_Source_(_Ret_opt_, (), _Ret_opt_valid_) // annotations to express 'boundedness' of integral value parameter -#define _In_bound_ _SAL1_1_Source_(_In_bound_, (), _In_bound_impl_) -#define _Out_bound_ _SAL1_1_Source_(_Out_bound_, (), _Out_bound_impl_) -#define _Ret_bound_ _SAL1_1_Source_(_Ret_bound_, (), _Ret_bound_impl_) -#define _Deref_in_bound_ _SAL1_1_Source_(_Deref_in_bound_, (), _Deref_in_bound_impl_) -#define _Deref_out_bound_ _SAL1_1_Source_(_Deref_out_bound_, (), _Deref_out_bound_impl_) -#define _Deref_inout_bound_ _SAL1_1_Source_(_Deref_inout_bound_, (), _Deref_in_bound_ _Deref_out_bound_) -#define _Deref_ret_bound_ _SAL1_1_Source_(_Deref_ret_bound_, (), _Deref_ret_bound_impl_) +#define _In_bound_ _SAL1_1_Source_(_In_bound_, (), _In_bound_impl_) +#define _Out_bound_ _SAL1_1_Source_(_Out_bound_, (), _Out_bound_impl_) +#define _Ret_bound_ _SAL1_1_Source_(_Ret_bound_, (), _Ret_bound_impl_) +#define _Deref_in_bound_ _SAL1_1_Source_(_Deref_in_bound_, (), _Deref_in_bound_impl_) +#define _Deref_out_bound_ _SAL1_1_Source_(_Deref_out_bound_, (), _Deref_out_bound_impl_) +#define _Deref_inout_bound_ \ + _SAL1_1_Source_(_Deref_inout_bound_, (), _Deref_in_bound_ _Deref_out_bound_) +#define _Deref_ret_bound_ _SAL1_1_Source_(_Deref_ret_bound_, (), _Deref_ret_bound_impl_) // e.g. HRESULT HrCreatePoint( _Deref_out_opt_ POINT** ppPT ); -#define _Deref_out_ _SAL1_1_Source_(_Deref_out_, (), _Out_ _Deref_post_valid_) -#define _Deref_out_opt_ _SAL1_1_Source_(_Deref_out_opt_, (), _Out_ _Deref_post_opt_valid_) -#define _Deref_opt_out_ _SAL1_1_Source_(_Deref_opt_out_, (), _Out_opt_ _Deref_post_valid_) -#define _Deref_opt_out_opt_ _SAL1_1_Source_(_Deref_opt_out_opt_, (), _Out_opt_ _Deref_post_opt_valid_) +#define _Deref_out_ _SAL1_1_Source_(_Deref_out_, (), _Out_ _Deref_post_valid_) +#define _Deref_out_opt_ _SAL1_1_Source_(_Deref_out_opt_, (), _Out_ _Deref_post_opt_valid_) +#define _Deref_opt_out_ _SAL1_1_Source_(_Deref_opt_out_, (), _Out_opt_ _Deref_post_valid_) +#define _Deref_opt_out_opt_ \ + _SAL1_1_Source_(_Deref_opt_out_opt_, (), _Out_opt_ _Deref_post_opt_valid_) // e.g. void CloneString( _In_z_ const WCHAR* wzFrom, _Deref_out_z_ WCHAR** pWzTo ); -#define _Deref_out_z_ _SAL1_1_Source_(_Deref_out_z_, (), _Out_ _Deref_post_z_) -#define _Deref_out_opt_z_ _SAL1_1_Source_(_Deref_out_opt_z_, (), _Out_ _Deref_post_opt_z_) -#define _Deref_opt_out_z_ _SAL1_1_Source_(_Deref_opt_out_z_, (), _Out_opt_ _Deref_post_z_) -#define _Deref_opt_out_opt_z_ _SAL1_1_Source_(_Deref_opt_out_opt_z_, (), _Out_opt_ _Deref_post_opt_z_) +#define _Deref_out_z_ _SAL1_1_Source_(_Deref_out_z_, (), _Out_ _Deref_post_z_) +#define _Deref_out_opt_z_ _SAL1_1_Source_(_Deref_out_opt_z_, (), _Out_ _Deref_post_opt_z_) +#define _Deref_opt_out_z_ _SAL1_1_Source_(_Deref_opt_out_z_, (), _Out_opt_ _Deref_post_z_) +#define _Deref_opt_out_opt_z_ \ + _SAL1_1_Source_(_Deref_opt_out_opt_z_, (), _Out_opt_ _Deref_post_opt_z_) // // _Deref_pre_ --- // -// describing conditions for array elements of dereferenced pointer parameters that must be met before the call +// describing conditions for array elements of dereferenced pointer parameters that must be met +// before the call // e.g. void SaveStringArray( _In_count_(cStrings) _Deref_pre_z_ const WCHAR* const rgpwch[] ); -#define _Deref_pre_z_ _SAL1_1_Source_(_Deref_pre_z_, (), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__zterm_impl) _Pre_valid_impl_) -#define _Deref_pre_opt_z_ _SAL1_1_Source_(_Deref_pre_opt_z_, (), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__zterm_impl) _Pre_valid_impl_) +#define _Deref_pre_z_ \ + _SAL1_1_Source_(_Deref_pre_z_, (), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__zterm_impl) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_z_ \ + _SAL1_1_Source_(_Deref_pre_opt_z_, (), \ + _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__zterm_impl) \ + _Pre_valid_impl_) -// e.g. void FillInArrayOfStr32( _In_count_(cStrings) _Deref_pre_cap_c_(32) _Deref_post_z_ WCHAR* const rgpwch[] ); -// buffer capacity is described by another parameter -#define _Deref_pre_cap_(size) _SAL1_1_Source_(_Deref_pre_cap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size))) -#define _Deref_pre_opt_cap_(size) _SAL1_1_Source_(_Deref_pre_opt_cap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_impl(size))) -#define _Deref_pre_bytecap_(size) _SAL1_1_Source_(_Deref_pre_bytecap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size))) -#define _Deref_pre_opt_bytecap_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size))) +// e.g. void FillInArrayOfStr32( _In_count_(cStrings) _Deref_pre_cap_c_(32) _Deref_post_z_ WCHAR* +// const rgpwch[] ); buffer capacity is described by another parameter +#define _Deref_pre_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_cap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size))) +#define _Deref_pre_opt_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_cap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_impl(size))) +#define _Deref_pre_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size))) +#define _Deref_pre_opt_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size))) // buffer capacity is described by a constant expression -#define _Deref_pre_cap_c_(size) _SAL1_1_Source_(_Deref_pre_cap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size))) -#define _Deref_pre_opt_cap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_cap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size))) -#define _Deref_pre_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_bytecap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size))) -#define _Deref_pre_opt_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size))) +#define _Deref_pre_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_cap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__cap_c_impl(size))) +#define _Deref_pre_opt_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_cap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_c_impl(size))) +#define _Deref_pre_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size))) +#define _Deref_pre_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size))) // buffer capacity is described by a complex condition -#define _Deref_pre_cap_x_(size) _SAL1_1_Source_(_Deref_pre_cap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size))) -#define _Deref_pre_opt_cap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_cap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size))) -#define _Deref_pre_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_bytecap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size))) -#define _Deref_pre_opt_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size))) +#define _Deref_pre_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_cap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__cap_x_impl(size))) +#define _Deref_pre_opt_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_cap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_x_impl(size))) +#define _Deref_pre_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size))) +#define _Deref_pre_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size))) // convenience macros for nullterminated buffers with given capacity -#define _Deref_pre_z_cap_(size) _SAL1_1_Source_(_Deref_pre_z_cap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_cap_(size) _SAL1_1_Source_(_Deref_pre_opt_z_cap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_bytecap_(size) _SAL1_1_Source_(_Deref_pre_z_bytecap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_bytecap_(size) _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_z_cap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_cap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_z_bytecap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_cap_c_(size) _SAL1_1_Source_(_Deref_pre_z_cap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_cap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_z_cap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_z_bytecap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_z_cap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_cap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_z_bytecap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_cap_x_(size) _SAL1_1_Source_(_Deref_pre_z_cap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_cap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_z_cap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_z_bytecap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_z_cap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_cap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_z_bytecap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_z_bytecap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) // known capacity and valid but unknown readable extent -#define _Deref_pre_valid_cap_(size) _SAL1_1_Source_(_Deref_pre_valid_cap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_cap_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_cap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_bytecap_(size) _SAL1_1_Source_(_Deref_pre_valid_bytecap_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_bytecap_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_cap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_cap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_bytecap_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_cap_c_(size) _SAL1_1_Source_(_Deref_pre_valid_cap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_cap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_cap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_valid_bytecap_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_cap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_cap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_bytecap_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_cap_x_(size) _SAL1_1_Source_(_Deref_pre_valid_cap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_cap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_cap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_valid_bytecap_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_cap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__cap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_cap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_valid_bytecap_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_valid_bytecap_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) // e.g. void SaveMatrix( _In_count_(n) _Deref_pre_count_(n) const Elem** matrix, size_t n ); // valid buffer extent is described by another parameter -#define _Deref_pre_count_(size) _SAL1_1_Source_(_Deref_pre_count_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_count_(size) _SAL1_1_Source_(_Deref_pre_opt_count_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_bytecount_(size) _SAL1_1_Source_(_Deref_pre_bytecount_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_bytecount_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecount_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_count_(size) \ + _SAL1_1_Source_(_Deref_pre_count_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_impl(size)) \ + _Pre_valid_impl_) +#define _Deref_pre_opt_count_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_count_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__count_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_bytecount_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecount_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_bytecount_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecount_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) // valid buffer extent is described by a constant expression -#define _Deref_pre_count_c_(size) _SAL1_1_Source_(_Deref_pre_count_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_count_c_(size) _SAL1_1_Source_(_Deref_pre_opt_count_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_bytecount_c_(size) _SAL1_1_Source_(_Deref_pre_bytecount_c_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_bytecount_c_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecount_c_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_count_c_(size) \ + _SAL1_1_Source_(_Deref_pre_count_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_count_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_count_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecount_c_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecount_c_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) // valid buffer extent is described by a complex expression -#define _Deref_pre_count_x_(size) _SAL1_1_Source_(_Deref_pre_count_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_count_x_(size) _SAL1_1_Source_(_Deref_pre_opt_count_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_bytecount_x_(size) _SAL1_1_Source_(_Deref_pre_bytecount_x_, (size), _Deref_pre1_impl_(__notnull_impl_notref) _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) -#define _Deref_pre_opt_bytecount_x_(size) _SAL1_1_Source_(_Deref_pre_opt_bytecount_x_, (size), _Deref_pre1_impl_(__maybenull_impl_notref) _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_count_x_(size) \ + _SAL1_1_Source_(_Deref_pre_count_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_count_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_count_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_pre_bytecount_x_, (size), \ + _Deref_pre1_impl_(__notnull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) +#define _Deref_pre_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_pre_opt_bytecount_x_, (size), \ + _Deref_pre1_impl_(__maybenull_impl_notref) \ + _Deref_pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) // e.g. void PrintStringArray( _In_count_(cElems) _Deref_pre_valid_ LPCSTR rgStr[], size_t cElems ); -#define _Deref_pre_valid_ _SAL1_1_Source_(_Deref_pre_valid_, (), _Deref_pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) -#define _Deref_pre_opt_valid_ _SAL1_1_Source_(_Deref_pre_opt_valid_, (), _Deref_pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) -#define _Deref_pre_invalid_ _SAL1_1_Source_(_Deref_pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) +#define _Deref_pre_valid_ \ + _SAL1_1_Source_(_Deref_pre_valid_, (), \ + _Deref_pre1_impl_(__notnull_impl_notref) _Pre_valid_impl_) +#define _Deref_pre_opt_valid_ \ + _SAL1_1_Source_(_Deref_pre_opt_valid_, (), \ + _Deref_pre1_impl_(__maybenull_impl_notref) _Pre_valid_impl_) +#define _Deref_pre_invalid_ \ + _SAL1_1_Source_(_Deref_pre_invalid_, (), _Deref_pre1_impl_(__notvalid_impl)) -#define _Deref_pre_notnull_ _SAL1_1_Source_(_Deref_pre_notnull_, (), _Deref_pre1_impl_(__notnull_impl_notref)) -#define _Deref_pre_maybenull_ _SAL1_1_Source_(_Deref_pre_maybenull_, (), _Deref_pre1_impl_(__maybenull_impl_notref)) -#define _Deref_pre_null_ _SAL1_1_Source_(_Deref_pre_null_, (), _Deref_pre1_impl_(__null_impl_notref)) +#define _Deref_pre_notnull_ \ + _SAL1_1_Source_(_Deref_pre_notnull_, (), _Deref_pre1_impl_(__notnull_impl_notref)) +#define _Deref_pre_maybenull_ \ + _SAL1_1_Source_(_Deref_pre_maybenull_, (), _Deref_pre1_impl_(__maybenull_impl_notref)) +#define _Deref_pre_null_ \ + _SAL1_1_Source_(_Deref_pre_null_, (), _Deref_pre1_impl_(__null_impl_notref)) // restrict access rights -#define _Deref_pre_readonly_ _SAL1_1_Source_(_Deref_pre_readonly_, (), _Deref_pre1_impl_(__readaccess_impl_notref)) -#define _Deref_pre_writeonly_ _SAL1_1_Source_(_Deref_pre_writeonly_, (), _Deref_pre1_impl_(__writeaccess_impl_notref)) +#define _Deref_pre_readonly_ \ + _SAL1_1_Source_(_Deref_pre_readonly_, (), _Deref_pre1_impl_(__readaccess_impl_notref)) +#define _Deref_pre_writeonly_ \ + _SAL1_1_Source_(_Deref_pre_writeonly_, (), _Deref_pre1_impl_(__writeaccess_impl_notref)) // // _Deref_post_ --- // -// describing conditions for array elements or dereferenced pointer parameters that hold after the call +// describing conditions for array elements or dereferenced pointer parameters that hold after the +// call // e.g. void CloneString( _In_z_ const Wchar_t* wzIn _Out_ _Deref_post_z_ WCHAR** pWzOut ); -#define _Deref_post_z_ _SAL1_1_Source_(_Deref_post_z_, (), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__zterm_impl) _Post_valid_impl_) -#define _Deref_post_opt_z_ _SAL1_1_Source_(_Deref_post_opt_z_, (), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__zterm_impl) _Post_valid_impl_) +#define _Deref_post_z_ \ + _SAL1_1_Source_(_Deref_post_z_, (), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__zterm_impl) \ + _Post_valid_impl_) +#define _Deref_post_opt_z_ \ + _SAL1_1_Source_(_Deref_post_opt_z_, (), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__zterm_impl) \ + _Post_valid_impl_) // e.g. HRESULT HrAllocateMemory( size_t cb, _Out_ _Deref_post_bytecap_(cb) void** ppv ); // buffer capacity is described by another parameter -#define _Deref_post_cap_(size) _SAL1_1_Source_(_Deref_post_cap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_impl(size))) -#define _Deref_post_opt_cap_(size) _SAL1_1_Source_(_Deref_post_opt_cap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_impl(size))) -#define _Deref_post_bytecap_(size) _SAL1_1_Source_(_Deref_post_bytecap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size))) -#define _Deref_post_opt_bytecap_(size) _SAL1_1_Source_(_Deref_post_opt_bytecap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size))) +#define _Deref_post_cap_(size) \ + _SAL1_1_Source_(_Deref_post_cap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_impl(size))) +#define _Deref_post_opt_cap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_cap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_impl(size))) +#define _Deref_post_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_bytecap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size))) +#define _Deref_post_opt_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size))) // buffer capacity is described by a constant expression -#define _Deref_post_cap_c_(size) _SAL1_1_Source_(_Deref_post_cap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size))) -#define _Deref_post_opt_cap_c_(size) _SAL1_1_Source_(_Deref_post_opt_cap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size))) -#define _Deref_post_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_bytecap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size))) -#define _Deref_post_opt_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_opt_bytecap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size))) +#define _Deref_post_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_cap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size))) +#define _Deref_post_opt_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_cap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size))) +#define _Deref_post_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_bytecap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size))) +#define _Deref_post_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size))) // buffer capacity is described by a complex expression -#define _Deref_post_cap_x_(size) _SAL1_1_Source_(_Deref_post_cap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size))) -#define _Deref_post_opt_cap_x_(size) _SAL1_1_Source_(_Deref_post_opt_cap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size))) -#define _Deref_post_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_bytecap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size))) -#define _Deref_post_opt_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_opt_bytecap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size))) +#define _Deref_post_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_cap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size))) +#define _Deref_post_opt_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_cap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size))) +#define _Deref_post_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_bytecap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size))) +#define _Deref_post_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size))) // convenience macros for nullterminated buffers with given capacity -#define _Deref_post_z_cap_(size) _SAL1_1_Source_(_Deref_post_z_cap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_cap_(size) _SAL1_1_Source_(_Deref_post_opt_z_cap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_bytecap_(size) _SAL1_1_Source_(_Deref_post_z_bytecap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_bytecap_(size) _SAL1_1_Source_(_Deref_post_opt_z_bytecap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_cap_(size) \ + _SAL1_1_Source_(_Deref_post_z_cap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_cap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_cap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_z_bytecap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_bytecap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_cap_c_(size) _SAL1_1_Source_(_Deref_post_z_cap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_cap_c_(size) _SAL1_1_Source_(_Deref_post_opt_z_cap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_z_bytecap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_opt_z_bytecap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_z_cap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_cap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_z_bytecap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_bytecap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_cap_x_(size) _SAL1_1_Source_(_Deref_post_z_cap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_cap_x_(size) _SAL1_1_Source_(_Deref_post_opt_z_cap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_z_bytecap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_opt_z_bytecap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_z_cap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_cap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post2_impl_(__zterm_impl, __cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_z_bytecap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_z_bytecap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post2_impl_( \ + __zterm_impl, __bytecap_x_impl(size)) _Post_valid_impl_) // known capacity and valid but unknown readable extent -#define _Deref_post_valid_cap_(size) _SAL1_1_Source_(_Deref_post_valid_cap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_cap_(size) _SAL1_1_Source_(_Deref_post_opt_valid_cap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_bytecap_(size) _SAL1_1_Source_(_Deref_post_valid_bytecap_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_bytecap_(size) _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_post_valid_cap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_impl(size)) \ + _Post_valid_impl_) +#define _Deref_post_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_cap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_valid_bytecap_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_cap_c_(size) _SAL1_1_Source_(_Deref_post_valid_cap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_cap_c_(size) _SAL1_1_Source_(_Deref_post_opt_valid_cap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_valid_bytecap_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_bytecap_c_(size) _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_valid_cap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_cap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_cap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_valid_bytecap_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_cap_x_(size) _SAL1_1_Source_(_Deref_post_valid_cap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_cap_x_(size) _SAL1_1_Source_(_Deref_post_opt_valid_cap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_valid_bytecap_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_valid_cap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_cap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__cap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_valid_bytecap_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_valid_bytecap_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecap_x_impl(size)) _Post_valid_impl_) -// e.g. HRESULT HrAllocateZeroInitializedMemory( size_t cb, _Out_ _Deref_post_bytecount_(cb) void** ppv ); -// valid buffer extent is described by another parameter -#define _Deref_post_count_(size) _SAL1_1_Source_(_Deref_post_count_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_count_(size) _SAL1_1_Source_(_Deref_post_opt_count_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Deref_post_bytecount_(size) _SAL1_1_Source_(_Deref_post_bytecount_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_bytecount_(size) _SAL1_1_Source_(_Deref_post_opt_bytecount_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +// e.g. HRESULT HrAllocateZeroInitializedMemory( size_t cb, _Out_ _Deref_post_bytecount_(cb) void** +// ppv ); valid buffer extent is described by another parameter +#define _Deref_post_count_(size) \ + _SAL1_1_Source_(_Deref_post_count_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_count_(size) \ + _SAL1_1_Source_(_Deref_post_opt_count_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Deref_post_bytecount_(size) \ + _SAL1_1_Source_(_Deref_post_bytecount_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_bytecount_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecount_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) // buffer capacity is described by a constant expression -#define _Deref_post_count_c_(size) _SAL1_1_Source_(_Deref_post_count_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_count_c_(size) _SAL1_1_Source_(_Deref_post_opt_count_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_bytecount_c_(size) _SAL1_1_Source_(_Deref_post_bytecount_c_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_bytecount_c_(size) _SAL1_1_Source_(_Deref_post_opt_bytecount_c_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_count_c_(size) \ + _SAL1_1_Source_(_Deref_post_count_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_count_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_count_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__count_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_post_bytecount_c_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecount_c_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) // buffer capacity is described by a complex expression -#define _Deref_post_count_x_(size) _SAL1_1_Source_(_Deref_post_count_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_count_x_(size) _SAL1_1_Source_(_Deref_post_opt_count_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_bytecount_x_(size) _SAL1_1_Source_(_Deref_post_bytecount_x_, (size), _Deref_post1_impl_(__notnull_impl_notref) _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) -#define _Deref_post_opt_bytecount_x_(size) _SAL1_1_Source_(_Deref_post_opt_bytecount_x_, (size), _Deref_post1_impl_(__maybenull_impl_notref) _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_count_x_(size) \ + _SAL1_1_Source_(_Deref_post_count_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_count_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_count_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__count_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_post_bytecount_x_, (size), \ + _Deref_post1_impl_(__notnull_impl_notref) \ + _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) +#define _Deref_post_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_post_opt_bytecount_x_, (size), \ + _Deref_post1_impl_(__maybenull_impl_notref) \ + _Deref_post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) -// e.g. void GetStrings( _Out_count_(cElems) _Deref_post_valid_ LPSTR const rgStr[], size_t cElems ); -#define _Deref_post_valid_ _SAL1_1_Source_(_Deref_post_valid_, (), _Deref_post1_impl_(__notnull_impl_notref) _Post_valid_impl_) -#define _Deref_post_opt_valid_ _SAL1_1_Source_(_Deref_post_opt_valid_, (), _Deref_post1_impl_(__maybenull_impl_notref) _Post_valid_impl_) +// e.g. void GetStrings( _Out_count_(cElems) _Deref_post_valid_ LPSTR const rgStr[], size_t cElems +// ); +#define _Deref_post_valid_ \ + _SAL1_1_Source_(_Deref_post_valid_, (), \ + _Deref_post1_impl_(__notnull_impl_notref) _Post_valid_impl_) +#define _Deref_post_opt_valid_ \ + _SAL1_1_Source_(_Deref_post_opt_valid_, (), \ + _Deref_post1_impl_(__maybenull_impl_notref) _Post_valid_impl_) -#define _Deref_post_notnull_ _SAL1_1_Source_(_Deref_post_notnull_, (), _Deref_post1_impl_(__notnull_impl_notref)) -#define _Deref_post_maybenull_ _SAL1_1_Source_(_Deref_post_maybenull_, (), _Deref_post1_impl_(__maybenull_impl_notref)) -#define _Deref_post_null_ _SAL1_1_Source_(_Deref_post_null_, (), _Deref_post1_impl_(__null_impl_notref)) +#define _Deref_post_notnull_ \ + _SAL1_1_Source_(_Deref_post_notnull_, (), _Deref_post1_impl_(__notnull_impl_notref)) +#define _Deref_post_maybenull_ \ + _SAL1_1_Source_(_Deref_post_maybenull_, (), _Deref_post1_impl_(__maybenull_impl_notref)) +#define _Deref_post_null_ \ + _SAL1_1_Source_(_Deref_post_null_, (), _Deref_post1_impl_(__null_impl_notref)) // // _Deref_ret_ --- // -#define _Deref_ret_z_ _SAL1_1_Source_(_Deref_ret_z_, (), _Deref_ret1_impl_(__notnull_impl_notref) _Deref_ret1_impl_(__zterm_impl)) -#define _Deref_ret_opt_z_ _SAL1_1_Source_(_Deref_ret_opt_z_, (), _Deref_ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__zterm_impl)) +#define _Deref_ret_z_ \ + _SAL1_1_Source_(_Deref_ret_z_, (), \ + _Deref_ret1_impl_(__notnull_impl_notref) _Deref_ret1_impl_(__zterm_impl)) +#define _Deref_ret_opt_z_ \ + _SAL1_1_Source_(_Deref_ret_opt_z_, (), \ + _Deref_ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__zterm_impl)) // // special _Deref_ --- // -#define _Deref2_pre_readonly_ _SAL1_1_Source_(_Deref2_pre_readonly_, (), _Deref2_pre1_impl_(__readaccess_impl_notref)) +#define _Deref2_pre_readonly_ \ + _SAL1_1_Source_(_Deref2_pre_readonly_, (), _Deref2_pre1_impl_(__readaccess_impl_notref)) // // _Ret_ --- // // e.g. _Ret_opt_valid_ LPSTR void* CloneSTR( _Pre_valid_ LPSTR src ); -#define _Ret_opt_valid_ _SAL1_1_Source_(_Ret_opt_valid_, (), _Ret1_impl_(__maybenull_impl_notref) _Ret_valid_impl_) -#define _Ret_opt_z_ _SAL1_1_Source_(_Ret_opt_z_, (), _Ret2_impl_(__maybenull_impl,__zterm_impl) _Ret_valid_impl_) +#define _Ret_opt_valid_ \ + _SAL1_1_Source_(_Ret_opt_valid_, (), _Ret1_impl_(__maybenull_impl_notref) _Ret_valid_impl_) +#define _Ret_opt_z_ \ + _SAL1_1_Source_(_Ret_opt_z_, (), _Ret2_impl_(__maybenull_impl, __zterm_impl) _Ret_valid_impl_) // e.g. _Ret_opt_bytecap_(cb) void* AllocateMemory( size_t cb ); // Buffer capacity is described by another parameter -#define _Ret_cap_(size) _SAL1_1_Source_(_Ret_cap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_impl(size))) -#define _Ret_opt_cap_(size) _SAL1_1_Source_(_Ret_opt_cap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_impl(size))) -#define _Ret_bytecap_(size) _SAL1_1_Source_(_Ret_bytecap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) -#define _Ret_opt_bytecap_(size) _SAL1_1_Source_(_Ret_opt_bytecap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) +#define _Ret_cap_(size) \ + _SAL1_1_Source_(_Ret_cap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_impl(size))) +#define _Ret_opt_cap_(size) \ + _SAL1_1_Source_(_Ret_opt_cap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_impl(size))) +#define _Ret_bytecap_(size) \ + _SAL1_1_Source_(_Ret_bytecap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) +#define _Ret_opt_bytecap_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_impl(size))) // Buffer capacity is described by a constant expression -#define _Ret_cap_c_(size) _SAL1_1_Source_(_Ret_cap_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) -#define _Ret_opt_cap_c_(size) _SAL1_1_Source_(_Ret_opt_cap_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) -#define _Ret_bytecap_c_(size) _SAL1_1_Source_(_Ret_bytecap_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) -#define _Ret_opt_bytecap_c_(size) _SAL1_1_Source_(_Ret_opt_bytecap_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) +#define _Ret_cap_c_(size) \ + _SAL1_1_Source_(_Ret_cap_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) +#define _Ret_opt_cap_c_(size) \ + _SAL1_1_Source_(_Ret_opt_cap_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_c_impl(size))) +#define _Ret_bytecap_c_(size) \ + _SAL1_1_Source_(_Ret_bytecap_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) +#define _Ret_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecap_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_c_impl(size))) // Buffer capacity is described by a complex condition -#define _Ret_cap_x_(size) _SAL1_1_Source_(_Ret_cap_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) -#define _Ret_opt_cap_x_(size) _SAL1_1_Source_(_Ret_opt_cap_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) -#define _Ret_bytecap_x_(size) _SAL1_1_Source_(_Ret_bytecap_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) -#define _Ret_opt_bytecap_x_(size) _SAL1_1_Source_(_Ret_opt_bytecap_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) +#define _Ret_cap_x_(size) \ + _SAL1_1_Source_(_Ret_cap_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) +#define _Ret_opt_cap_x_(size) \ + _SAL1_1_Source_(_Ret_opt_cap_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__cap_x_impl(size))) +#define _Ret_bytecap_x_(size) \ + _SAL1_1_Source_(_Ret_bytecap_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) +#define _Ret_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecap_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecap_x_impl(size))) // return value is nullterminated and capacity is given by another parameter -#define _Ret_z_cap_(size) _SAL1_1_Source_(_Ret_z_cap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__cap_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_cap_(size) _SAL1_1_Source_(_Ret_opt_z_cap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__cap_impl(size)) _Ret_valid_impl_) -#define _Ret_z_bytecap_(size) _SAL1_1_Source_(_Ret_z_bytecap_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecap_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_bytecap_(size) _SAL1_1_Source_(_Ret_opt_z_bytecap_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecap_impl(size)) _Ret_valid_impl_) +#define _Ret_z_cap_(size) \ + _SAL1_1_Source_(_Ret_z_cap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl, __cap_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_z_cap_(size) \ + _SAL1_1_Source_(_Ret_opt_z_cap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __cap_impl(size)) _Ret_valid_impl_) +#define _Ret_z_bytecap_(size) \ + _SAL1_1_Source_(_Ret_z_bytecap_, (size), \ + _Ret1_impl_(__notnull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecap_impl(size)) _Ret_valid_impl_) +#define _Ret_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Ret_opt_z_bytecap_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecap_impl(size)) _Ret_valid_impl_) // e.g. _Ret_opt_bytecount_(cb) void* AllocateZeroInitializedMemory( size_t cb ); // Valid Buffer extent is described by another parameter -#define _Ret_count_(size) _SAL1_1_Source_(_Ret_count_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_count_(size) _SAL1_1_Source_(_Ret_opt_count_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_impl(size)) _Ret_valid_impl_) -#define _Ret_bytecount_(size) _SAL1_1_Source_(_Ret_bytecount_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_bytecount_(size) _SAL1_1_Source_(_Ret_opt_bytecount_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) _Ret_valid_impl_) +#define _Ret_count_(size) \ + _SAL1_1_Source_(_Ret_count_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_count_(size) \ + _SAL1_1_Source_(_Ret_opt_count_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_bytecount_(size) \ + _SAL1_1_Source_(_Ret_bytecount_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_bytecount_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecount_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_impl(size)) \ + _Ret_valid_impl_) // Valid Buffer extent is described by a constant expression -#define _Ret_count_c_(size) _SAL1_1_Source_(_Ret_count_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_c_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_count_c_(size) _SAL1_1_Source_(_Ret_opt_count_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_c_impl(size)) _Ret_valid_impl_) -#define _Ret_bytecount_c_(size) _SAL1_1_Source_(_Ret_bytecount_c_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_bytecount_c_(size) _SAL1_1_Source_(_Ret_opt_bytecount_c_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) _Ret_valid_impl_) +#define _Ret_count_c_(size) \ + _SAL1_1_Source_(_Ret_count_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_c_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_count_c_(size) \ + _SAL1_1_Source_(_Ret_opt_count_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_c_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_bytecount_c_(size) \ + _SAL1_1_Source_(_Ret_bytecount_c_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecount_c_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_c_impl(size)) \ + _Ret_valid_impl_) // Valid Buffer extent is described by a complex expression -#define _Ret_count_x_(size) _SAL1_1_Source_(_Ret_count_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_x_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_count_x_(size) _SAL1_1_Source_(_Ret_opt_count_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_x_impl(size)) _Ret_valid_impl_) -#define _Ret_bytecount_x_(size) _SAL1_1_Source_(_Ret_bytecount_x_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_bytecount_x_(size) _SAL1_1_Source_(_Ret_opt_bytecount_x_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) _Ret_valid_impl_) +#define _Ret_count_x_(size) \ + _SAL1_1_Source_(_Ret_count_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__count_x_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_count_x_(size) \ + _SAL1_1_Source_(_Ret_opt_count_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__count_x_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_bytecount_x_(size) \ + _SAL1_1_Source_(_Ret_bytecount_x_, (size), \ + _Ret1_impl_(__notnull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) \ + _Ret_valid_impl_) +#define _Ret_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Ret_opt_bytecount_x_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) _Ret1_impl_(__bytecount_x_impl(size)) \ + _Ret_valid_impl_) // return value is nullterminated and length is given by another parameter -#define _Ret_z_count_(size) _SAL1_1_Source_(_Ret_z_count_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__count_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_count_(size) _SAL1_1_Source_(_Ret_opt_z_count_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__count_impl(size)) _Ret_valid_impl_) -#define _Ret_z_bytecount_(size) _SAL1_1_Source_(_Ret_z_bytecount_, (size), _Ret1_impl_(__notnull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecount_impl(size)) _Ret_valid_impl_) -#define _Ret_opt_z_bytecount_(size) _SAL1_1_Source_(_Ret_opt_z_bytecount_, (size), _Ret1_impl_(__maybenull_impl_notref) _Ret2_impl_(__zterm_impl,__bytecount_impl(size)) _Ret_valid_impl_) - +#define _Ret_z_count_(size) \ + _SAL1_1_Source_(_Ret_z_count_, (size), \ + _Ret1_impl_(__notnull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_opt_z_count_(size) \ + _SAL1_1_Source_(_Ret_opt_z_count_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __count_impl(size)) _Ret_valid_impl_) +#define _Ret_z_bytecount_(size) \ + _SAL1_1_Source_(_Ret_z_bytecount_, (size), \ + _Ret1_impl_(__notnull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecount_impl(size)) _Ret_valid_impl_) +#define _Ret_opt_z_bytecount_(size) \ + _SAL1_1_Source_(_Ret_opt_z_bytecount_, (size), \ + _Ret1_impl_(__maybenull_impl_notref) \ + _Ret2_impl_(__zterm_impl, __bytecount_impl(size)) _Ret_valid_impl_) // _Pre_ annotations --- -#define _Pre_opt_z_ _SAL1_1_Source_(_Pre_opt_z_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__zterm_impl) _Pre_valid_impl_) +#define _Pre_opt_z_ \ + _SAL1_1_Source_(_Pre_opt_z_, (), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__zterm_impl) \ + _Pre_valid_impl_) // restrict access rights -#define _Pre_readonly_ _SAL1_1_Source_(_Pre_readonly_, (), _Pre1_impl_(__readaccess_impl_notref)) -#define _Pre_writeonly_ _SAL1_1_Source_(_Pre_writeonly_, (), _Pre1_impl_(__writeaccess_impl_notref)) +#define _Pre_readonly_ _SAL1_1_Source_(_Pre_readonly_, (), _Pre1_impl_(__readaccess_impl_notref)) +#define _Pre_writeonly_ _SAL1_1_Source_(_Pre_writeonly_, (), _Pre1_impl_(__writeaccess_impl_notref)) // e.g. void FreeMemory( _Pre_bytecap_(cb) _Post_ptr_invalid_ void* pv, size_t cb ); // buffer capacity described by another parameter -#define _Pre_cap_(size) _SAL1_1_Source_(_Pre_cap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size))) -#define _Pre_opt_cap_(size) _SAL1_1_Source_(_Pre_opt_cap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size))) -#define _Pre_bytecap_(size) _SAL1_1_Source_(_Pre_bytecap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) -#define _Pre_opt_bytecap_(size) _SAL1_1_Source_(_Pre_opt_bytecap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) +#define _Pre_cap_(size) \ + _SAL1_1_Source_(_Pre_cap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size))) +#define _Pre_opt_cap_(size) \ + _SAL1_1_Source_(_Pre_opt_cap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size))) +#define _Pre_bytecap_(size) \ + _SAL1_1_Source_(_Pre_bytecap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) +#define _Pre_opt_bytecap_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size))) // buffer capacity described by a constant expression -#define _Pre_cap_c_(size) _SAL1_1_Source_(_Pre_cap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) -#define _Pre_opt_cap_c_(size) _SAL1_1_Source_(_Pre_opt_cap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) -#define _Pre_bytecap_c_(size) _SAL1_1_Source_(_Pre_bytecap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) -#define _Pre_opt_bytecap_c_(size) _SAL1_1_Source_(_Pre_opt_bytecap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) -#define _Pre_cap_c_one_ _SAL1_1_Source_(_Pre_cap_c_one_, (), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) -#define _Pre_opt_cap_c_one_ _SAL1_1_Source_(_Pre_opt_cap_c_one_, (), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) +#define _Pre_cap_c_(size) \ + _SAL1_1_Source_(_Pre_cap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) +#define _Pre_opt_cap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_cap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size))) +#define _Pre_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_bytecap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) +#define _Pre_opt_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size))) +#define _Pre_cap_c_one_ \ + _SAL1_1_Source_(_Pre_cap_c_one_, (), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) +#define _Pre_opt_cap_c_one_ \ + _SAL1_1_Source_(_Pre_opt_cap_c_one_, (), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl)) // buffer capacity is described by another parameter multiplied by a constant expression -#define _Pre_cap_m_(mult,size) _SAL1_1_Source_(_Pre_cap_m_, (mult,size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__mult_impl(mult,size))) -#define _Pre_opt_cap_m_(mult,size) _SAL1_1_Source_(_Pre_opt_cap_m_, (mult,size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__mult_impl(mult,size))) +#define _Pre_cap_m_(mult, size) \ + _SAL1_1_Source_(_Pre_cap_m_, (mult, size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__mult_impl(mult, size))) +#define _Pre_opt_cap_m_(mult, size) \ + _SAL1_1_Source_(_Pre_opt_cap_m_, (mult, size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__mult_impl(mult, size))) // buffer capacity described by size of other buffer, only used by dangerous legacy APIs // e.g. int strcpy(_Pre_cap_for_(src) char* dst, const char* src); -#define _Pre_cap_for_(param) _SAL1_1_Source_(_Pre_cap_for_, (param), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) -#define _Pre_opt_cap_for_(param) _SAL1_1_Source_(_Pre_opt_cap_for_, (param), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) +#define _Pre_cap_for_(param) \ + _SAL1_1_Source_(_Pre_cap_for_, (param), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) +#define _Pre_opt_cap_for_(param) \ + _SAL1_1_Source_(_Pre_opt_cap_for_, (param), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_for_impl(param))) // buffer capacity described by a complex condition -#define _Pre_cap_x_(size) _SAL1_1_Source_(_Pre_cap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) -#define _Pre_opt_cap_x_(size) _SAL1_1_Source_(_Pre_opt_cap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) -#define _Pre_bytecap_x_(size) _SAL1_1_Source_(_Pre_bytecap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) -#define _Pre_opt_bytecap_x_(size) _SAL1_1_Source_(_Pre_opt_bytecap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) +#define _Pre_cap_x_(size) \ + _SAL1_1_Source_(_Pre_cap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) +#define _Pre_opt_cap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_cap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size))) +#define _Pre_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_bytecap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) +#define _Pre_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size))) // buffer capacity described by the difference to another pointer parameter -#define _Pre_ptrdiff_cap_(ptr) _SAL1_1_Source_(_Pre_ptrdiff_cap_, (ptr), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) -#define _Pre_opt_ptrdiff_cap_(ptr) _SAL1_1_Source_(_Pre_opt_ptrdiff_cap_, (ptr), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) +#define _Pre_ptrdiff_cap_(ptr) \ + _SAL1_1_Source_(_Pre_ptrdiff_cap_, (ptr), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) +#define _Pre_opt_ptrdiff_cap_(ptr) \ + _SAL1_1_Source_(_Pre_opt_ptrdiff_cap_, (ptr), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre1_impl_(__cap_x_impl(__ptrdiff(ptr)))) -// e.g. void AppendStr( _Pre_z_ const char* szFrom, _Pre_z_cap_(cchTo) _Post_z_ char* szTo, size_t cchTo ); -#define _Pre_z_cap_(size) _SAL1_1_Source_(_Pre_z_cap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_cap_(size) _SAL1_1_Source_(_Pre_opt_z_cap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_z_bytecap_(size) _SAL1_1_Source_(_Pre_z_bytecap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_bytecap_(size) _SAL1_1_Source_(_Pre_opt_z_bytecap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_impl(size)) _Pre_valid_impl_) +// e.g. void AppendStr( _Pre_z_ const char* szFrom, _Pre_z_cap_(cchTo) _Post_z_ char* szTo, size_t +// cchTo ); +#define _Pre_z_cap_(size) \ + _SAL1_1_Source_(_Pre_z_cap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl, __cap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_z_cap_(size) \ + _SAL1_1_Source_(_Pre_opt_z_cap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_impl(size)) _Pre_valid_impl_) +#define _Pre_z_bytecap_(size) \ + _SAL1_1_Source_(_Pre_z_bytecap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Pre_opt_z_bytecap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_impl(size)) _Pre_valid_impl_) -#define _Pre_z_cap_c_(size) _SAL1_1_Source_(_Pre_z_cap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_cap_c_(size) _SAL1_1_Source_(_Pre_opt_z_cap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_z_bytecap_c_(size) _SAL1_1_Source_(_Pre_z_bytecap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_bytecap_c_(size) _SAL1_1_Source_(_Pre_opt_z_bytecap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_z_cap_c_(size) \ + _SAL1_1_Source_(_Pre_z_cap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_cap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_z_cap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_z_bytecap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_z_bytecap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_z_cap_x_(size) _SAL1_1_Source_(_Pre_z_cap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_cap_x_(size) _SAL1_1_Source_(_Pre_opt_z_cap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_z_bytecap_x_(size) _SAL1_1_Source_(_Pre_z_bytecap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_z_bytecap_x_(size) _SAL1_1_Source_(_Pre_opt_z_bytecap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre2_impl_(__zterm_impl,__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_z_cap_x_(size) \ + _SAL1_1_Source_(_Pre_z_cap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_cap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_z_cap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __cap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_z_bytecap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_opt_z_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_z_bytecap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre2_impl_(__zterm_impl, __bytecap_x_impl(size)) _Pre_valid_impl_) // known capacity and valid but unknown readable extent -#define _Pre_valid_cap_(size) _SAL1_1_Source_(_Pre_valid_cap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_cap_(size) _SAL1_1_Source_(_Pre_opt_valid_cap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size)) _Pre_valid_impl_) -#define _Pre_valid_bytecap_(size) _SAL1_1_Source_(_Pre_valid_bytecap_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_bytecap_(size) _SAL1_1_Source_(_Pre_opt_valid_bytecap_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) _Pre_valid_impl_) +#define _Pre_valid_cap_(size) \ + _SAL1_1_Source_(_Pre_valid_cap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_cap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_valid_bytecap_(size) \ + _SAL1_1_Source_(_Pre_valid_bytecap_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_bytecap_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_impl(size)) \ + _Pre_valid_impl_) -#define _Pre_valid_cap_c_(size) _SAL1_1_Source_(_Pre_valid_cap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_cap_c_(size) _SAL1_1_Source_(_Pre_opt_valid_cap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_valid_bytecap_c_(size) _SAL1_1_Source_(_Pre_valid_bytecap_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_bytecap_c_(size) _SAL1_1_Source_(_Pre_opt_valid_bytecap_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) _Pre_valid_impl_) +#define _Pre_valid_cap_c_(size) \ + _SAL1_1_Source_(_Pre_valid_cap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_cap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_cap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_valid_bytecap_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_bytecap_c_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_bytecap_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_c_impl(size)) \ + _Pre_valid_impl_) -#define _Pre_valid_cap_x_(size) _SAL1_1_Source_(_Pre_valid_cap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_cap_x_(size) _SAL1_1_Source_(_Pre_opt_valid_cap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_valid_bytecap_x_(size) _SAL1_1_Source_(_Pre_valid_bytecap_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Pre_opt_valid_bytecap_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) _Pre_valid_impl_) +#define _Pre_valid_cap_x_(size) \ + _SAL1_1_Source_(_Pre_valid_cap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_cap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_valid_bytecap_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Pre_opt_valid_bytecap_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecap_x_impl(size)) \ + _Pre_valid_impl_) -// e.g. void AppendCharRange( _Pre_count_(cchFrom) const char* rgFrom, size_t cchFrom, _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); -// Valid buffer extent described by another parameter -#define _Pre_count_(size) _SAL1_1_Source_(_Pre_count_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_count_(size) _SAL1_1_Source_(_Pre_opt_count_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_impl(size)) _Pre_valid_impl_) -#define _Pre_bytecount_(size) _SAL1_1_Source_(_Pre_bytecount_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_bytecount_(size) _SAL1_1_Source_(_Pre_opt_bytecount_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) _Pre_valid_impl_) +// e.g. void AppendCharRange( _Pre_count_(cchFrom) const char* rgFrom, size_t cchFrom, +// _Out_z_cap_(cchTo) char* szTo, size_t cchTo ); Valid buffer extent described by another parameter +#define _Pre_count_(size) \ + _SAL1_1_Source_(_Pre_count_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_count_(size) \ + _SAL1_1_Source_(_Pre_opt_count_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_bytecount_(size) \ + _SAL1_1_Source_(_Pre_bytecount_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_bytecount_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecount_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_impl(size)) \ + _Pre_valid_impl_) // Valid buffer extent described by a constant expression -#define _Pre_count_c_(size) _SAL1_1_Source_(_Pre_count_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_count_c_(size) _SAL1_1_Source_(_Pre_opt_count_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_c_impl(size)) _Pre_valid_impl_) -#define _Pre_bytecount_c_(size) _SAL1_1_Source_(_Pre_bytecount_c_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_bytecount_c_(size) _SAL1_1_Source_(_Pre_opt_bytecount_c_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) _Pre_valid_impl_) +#define _Pre_count_c_(size) \ + _SAL1_1_Source_(_Pre_count_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_count_c_(size) \ + _SAL1_1_Source_(_Pre_opt_count_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_bytecount_c_(size) \ + _SAL1_1_Source_(_Pre_bytecount_c_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecount_c_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_c_impl(size)) \ + _Pre_valid_impl_) // Valid buffer extent described by a complex expression -#define _Pre_count_x_(size) _SAL1_1_Source_(_Pre_count_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_count_x_(size) _SAL1_1_Source_(_Pre_opt_count_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_x_impl(size)) _Pre_valid_impl_) -#define _Pre_bytecount_x_(size) _SAL1_1_Source_(_Pre_bytecount_x_, (size), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) -#define _Pre_opt_bytecount_x_(size) _SAL1_1_Source_(_Pre_opt_bytecount_x_, (size), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) _Pre_valid_impl_) +#define _Pre_count_x_(size) \ + _SAL1_1_Source_(_Pre_count_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_count_x_(size) \ + _SAL1_1_Source_(_Pre_opt_count_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_bytecount_x_(size) \ + _SAL1_1_Source_(_Pre_bytecount_x_, (size), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) \ + _Pre_valid_impl_) +#define _Pre_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Pre_opt_bytecount_x_, (size), \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__bytecount_x_impl(size)) \ + _Pre_valid_impl_) // Valid buffer extent described by the difference to another pointer parameter -#define _Pre_ptrdiff_count_(ptr) _SAL1_1_Source_(_Pre_ptrdiff_count_, (ptr), _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) _Pre_valid_impl_) -#define _Pre_opt_ptrdiff_count_(ptr) _SAL1_1_Source_(_Pre_opt_ptrdiff_count_, (ptr), _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) _Pre_valid_impl_) +#define _Pre_ptrdiff_count_(ptr) \ + _SAL1_1_Source_(_Pre_ptrdiff_count_, (ptr), \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) \ + _Pre_valid_impl_) +#define _Pre_opt_ptrdiff_count_(ptr) \ + _SAL1_1_Source_(_Pre_opt_ptrdiff_count_, (ptr), \ + _Pre1_impl_(__maybenull_impl_notref) \ + _Pre1_impl_(__count_x_impl(__ptrdiff(ptr))) _Pre_valid_impl_) +// char * strncpy(_Out_cap_(_Count) _Post_maybez_ char * _Dest, _In_z_ const char * _Source, _In_ +// size_t _Count) buffer maybe zero-terminated after the call +#define _Post_maybez_ _SAL1_1_Source_(_Post_maybez_, (), _Post1_impl_(__maybezterm_impl)) -// char * strncpy(_Out_cap_(_Count) _Post_maybez_ char * _Dest, _In_z_ const char * _Source, _In_ size_t _Count) -// buffer maybe zero-terminated after the call -#define _Post_maybez_ _SAL1_1_Source_(_Post_maybez_, (), _Post1_impl_(__maybezterm_impl)) - -// e.g. SIZE_T HeapSize( _In_ HANDLE hHeap, DWORD dwFlags, _Pre_notnull_ _Post_bytecap_(return) LPCVOID lpMem ); -#define _Post_cap_(size) _SAL1_1_Source_(_Post_cap_, (size), _Post1_impl_(__cap_impl(size))) -#define _Post_bytecap_(size) _SAL1_1_Source_(_Post_bytecap_, (size), _Post1_impl_(__bytecap_impl(size))) +// e.g. SIZE_T HeapSize( _In_ HANDLE hHeap, DWORD dwFlags, _Pre_notnull_ _Post_bytecap_(return) +// LPCVOID lpMem ); +#define _Post_cap_(size) _SAL1_1_Source_(_Post_cap_, (size), _Post1_impl_(__cap_impl(size))) +#define _Post_bytecap_(size) \ + _SAL1_1_Source_(_Post_bytecap_, (size), _Post1_impl_(__bytecap_impl(size))) // e.g. int strlen( _In_z_ _Post_count_(return+1) const char* sz ); -#define _Post_count_(size) _SAL1_1_Source_(_Post_count_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) -#define _Post_bytecount_(size) _SAL1_1_Source_(_Post_bytecount_, (size), _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) -#define _Post_count_c_(size) _SAL1_1_Source_(_Post_count_c_, (size), _Post1_impl_(__count_c_impl(size)) _Post_valid_impl_) -#define _Post_bytecount_c_(size) _SAL1_1_Source_(_Post_bytecount_c_, (size), _Post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) -#define _Post_count_x_(size) _SAL1_1_Source_(_Post_count_x_, (size), _Post1_impl_(__count_x_impl(size)) _Post_valid_impl_) -#define _Post_bytecount_x_(size) _SAL1_1_Source_(_Post_bytecount_x_, (size), _Post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) +#define _Post_count_(size) \ + _SAL1_1_Source_(_Post_count_, (size), _Post1_impl_(__count_impl(size)) _Post_valid_impl_) +#define _Post_bytecount_(size) \ + _SAL1_1_Source_(_Post_bytecount_, (size), \ + _Post1_impl_(__bytecount_impl(size)) _Post_valid_impl_) +#define _Post_count_c_(size) \ + _SAL1_1_Source_(_Post_count_c_, (size), _Post1_impl_(__count_c_impl(size)) _Post_valid_impl_) +#define _Post_bytecount_c_(size) \ + _SAL1_1_Source_(_Post_bytecount_c_, (size), \ + _Post1_impl_(__bytecount_c_impl(size)) _Post_valid_impl_) +#define _Post_count_x_(size) \ + _SAL1_1_Source_(_Post_count_x_, (size), _Post1_impl_(__count_x_impl(size)) _Post_valid_impl_) +#define _Post_bytecount_x_(size) \ + _SAL1_1_Source_(_Post_bytecount_x_, (size), \ + _Post1_impl_(__bytecount_x_impl(size)) _Post_valid_impl_) -// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Pre_cap_(cch) _Post_z_count_(return+1) char* szFrom, size_t cchFrom ); -#define _Post_z_count_(size) _SAL1_1_Source_(_Post_z_count_, (size), _Post2_impl_(__zterm_impl,__count_impl(size)) _Post_valid_impl_) -#define _Post_z_bytecount_(size) _SAL1_1_Source_(_Post_z_bytecount_, (size), _Post2_impl_(__zterm_impl,__bytecount_impl(size)) _Post_valid_impl_) -#define _Post_z_count_c_(size) _SAL1_1_Source_(_Post_z_count_c_, (size), _Post2_impl_(__zterm_impl,__count_c_impl(size)) _Post_valid_impl_) -#define _Post_z_bytecount_c_(size) _SAL1_1_Source_(_Post_z_bytecount_c_, (size), _Post2_impl_(__zterm_impl,__bytecount_c_impl(size)) _Post_valid_impl_) -#define _Post_z_count_x_(size) _SAL1_1_Source_(_Post_z_count_x_, (size), _Post2_impl_(__zterm_impl,__count_x_impl(size)) _Post_valid_impl_) -#define _Post_z_bytecount_x_(size) _SAL1_1_Source_(_Post_z_bytecount_x_, (size), _Post2_impl_(__zterm_impl,__bytecount_x_impl(size)) _Post_valid_impl_) +// e.g. size_t CopyStr( _In_z_ const char* szFrom, _Pre_cap_(cch) _Post_z_count_(return+1) char* +// szFrom, size_t cchFrom ); +#define _Post_z_count_(size) \ + _SAL1_1_Source_(_Post_z_count_, (size), \ + _Post2_impl_(__zterm_impl, __count_impl(size)) _Post_valid_impl_) +#define _Post_z_bytecount_(size) \ + _SAL1_1_Source_(_Post_z_bytecount_, (size), \ + _Post2_impl_(__zterm_impl, __bytecount_impl(size)) _Post_valid_impl_) +#define _Post_z_count_c_(size) \ + _SAL1_1_Source_(_Post_z_count_c_, (size), \ + _Post2_impl_(__zterm_impl, __count_c_impl(size)) _Post_valid_impl_) +#define _Post_z_bytecount_c_(size) \ + _SAL1_1_Source_(_Post_z_bytecount_c_, (size), \ + _Post2_impl_(__zterm_impl, __bytecount_c_impl(size)) _Post_valid_impl_) +#define _Post_z_count_x_(size) \ + _SAL1_1_Source_(_Post_z_count_x_, (size), \ + _Post2_impl_(__zterm_impl, __count_x_impl(size)) _Post_valid_impl_) +#define _Post_z_bytecount_x_(size) \ + _SAL1_1_Source_(_Post_z_bytecount_x_, (size), \ + _Post2_impl_(__zterm_impl, __bytecount_x_impl(size)) _Post_valid_impl_) // // _Prepost_ --- // // describing conditions that hold before and after the function call -#define _Prepost_opt_z_ _SAL1_1_Source_(_Prepost_opt_z_, (), _Pre_opt_z_ _Post_z_) +#define _Prepost_opt_z_ _SAL1_1_Source_(_Prepost_opt_z_, (), _Pre_opt_z_ _Post_z_) -#define _Prepost_count_(size) _SAL1_1_Source_(_Prepost_count_, (size), _Pre_count_(size) _Post_count_(size)) -#define _Prepost_opt_count_(size) _SAL1_1_Source_(_Prepost_opt_count_, (size), _Pre_opt_count_(size) _Post_count_(size)) -#define _Prepost_bytecount_(size) _SAL1_1_Source_(_Prepost_bytecount_, (size), _Pre_bytecount_(size) _Post_bytecount_(size)) -#define _Prepost_opt_bytecount_(size) _SAL1_1_Source_(_Prepost_opt_bytecount_, (size), _Pre_opt_bytecount_(size) _Post_bytecount_(size)) -#define _Prepost_count_c_(size) _SAL1_1_Source_(_Prepost_count_c_, (size), _Pre_count_c_(size) _Post_count_c_(size)) -#define _Prepost_opt_count_c_(size) _SAL1_1_Source_(_Prepost_opt_count_c_, (size), _Pre_opt_count_c_(size) _Post_count_c_(size)) -#define _Prepost_bytecount_c_(size) _SAL1_1_Source_(_Prepost_bytecount_c_, (size), _Pre_bytecount_c_(size) _Post_bytecount_c_(size)) -#define _Prepost_opt_bytecount_c_(size) _SAL1_1_Source_(_Prepost_opt_bytecount_c_, (size), _Pre_opt_bytecount_c_(size) _Post_bytecount_c_(size)) -#define _Prepost_count_x_(size) _SAL1_1_Source_(_Prepost_count_x_, (size), _Pre_count_x_(size) _Post_count_x_(size)) -#define _Prepost_opt_count_x_(size) _SAL1_1_Source_(_Prepost_opt_count_x_, (size), _Pre_opt_count_x_(size) _Post_count_x_(size)) -#define _Prepost_bytecount_x_(size) _SAL1_1_Source_(_Prepost_bytecount_x_, (size), _Pre_bytecount_x_(size) _Post_bytecount_x_(size)) -#define _Prepost_opt_bytecount_x_(size) _SAL1_1_Source_(_Prepost_opt_bytecount_x_, (size), _Pre_opt_bytecount_x_(size) _Post_bytecount_x_(size)) +#define _Prepost_count_(size) \ + _SAL1_1_Source_(_Prepost_count_, (size), _Pre_count_(size) _Post_count_(size)) +#define _Prepost_opt_count_(size) \ + _SAL1_1_Source_(_Prepost_opt_count_, (size), _Pre_opt_count_(size) _Post_count_(size)) +#define _Prepost_bytecount_(size) \ + _SAL1_1_Source_(_Prepost_bytecount_, (size), _Pre_bytecount_(size) _Post_bytecount_(size)) +#define _Prepost_opt_bytecount_(size) \ + _SAL1_1_Source_(_Prepost_opt_bytecount_, (size), \ + _Pre_opt_bytecount_(size) _Post_bytecount_(size)) +#define _Prepost_count_c_(size) \ + _SAL1_1_Source_(_Prepost_count_c_, (size), _Pre_count_c_(size) _Post_count_c_(size)) +#define _Prepost_opt_count_c_(size) \ + _SAL1_1_Source_(_Prepost_opt_count_c_, (size), _Pre_opt_count_c_(size) _Post_count_c_(size)) +#define _Prepost_bytecount_c_(size) \ + _SAL1_1_Source_(_Prepost_bytecount_c_, (size), _Pre_bytecount_c_(size) _Post_bytecount_c_(size)) +#define _Prepost_opt_bytecount_c_(size) \ + _SAL1_1_Source_(_Prepost_opt_bytecount_c_, (size), \ + _Pre_opt_bytecount_c_(size) _Post_bytecount_c_(size)) +#define _Prepost_count_x_(size) \ + _SAL1_1_Source_(_Prepost_count_x_, (size), _Pre_count_x_(size) _Post_count_x_(size)) +#define _Prepost_opt_count_x_(size) \ + _SAL1_1_Source_(_Prepost_opt_count_x_, (size), _Pre_opt_count_x_(size) _Post_count_x_(size)) +#define _Prepost_bytecount_x_(size) \ + _SAL1_1_Source_(_Prepost_bytecount_x_, (size), _Pre_bytecount_x_(size) _Post_bytecount_x_(size)) +#define _Prepost_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Prepost_opt_bytecount_x_, (size), \ + _Pre_opt_bytecount_x_(size) _Post_bytecount_x_(size)) -#define _Prepost_valid_ _SAL1_1_Source_(_Prepost_valid_, (), _Pre_valid_ _Post_valid_) -#define _Prepost_opt_valid_ _SAL1_1_Source_(_Prepost_opt_valid_, (), _Pre_opt_valid_ _Post_valid_) +#define _Prepost_valid_ _SAL1_1_Source_(_Prepost_valid_, (), _Pre_valid_ _Post_valid_) +#define _Prepost_opt_valid_ _SAL1_1_Source_(_Prepost_opt_valid_, (), _Pre_opt_valid_ _Post_valid_) // // _Deref_ --- // // short version for _Deref_pre_ _Deref_post_ -// describing conditions for array elements or dereferenced pointer parameters that hold before and after the call +// describing conditions for array elements or dereferenced pointer parameters that hold before and +// after the call -#define _Deref_prepost_z_ _SAL1_1_Source_(_Deref_prepost_z_, (), _Deref_pre_z_ _Deref_post_z_) -#define _Deref_prepost_opt_z_ _SAL1_1_Source_(_Deref_prepost_opt_z_, (), _Deref_pre_opt_z_ _Deref_post_opt_z_) +#define _Deref_prepost_z_ _SAL1_1_Source_(_Deref_prepost_z_, (), _Deref_pre_z_ _Deref_post_z_) +#define _Deref_prepost_opt_z_ \ + _SAL1_1_Source_(_Deref_prepost_opt_z_, (), _Deref_pre_opt_z_ _Deref_post_opt_z_) -#define _Deref_prepost_cap_(size) _SAL1_1_Source_(_Deref_prepost_cap_, (size), _Deref_pre_cap_(size) _Deref_post_cap_(size)) -#define _Deref_prepost_opt_cap_(size) _SAL1_1_Source_(_Deref_prepost_opt_cap_, (size), _Deref_pre_opt_cap_(size) _Deref_post_opt_cap_(size)) -#define _Deref_prepost_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_bytecap_, (size), _Deref_pre_bytecap_(size) _Deref_post_bytecap_(size)) -#define _Deref_prepost_opt_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecap_, (size), _Deref_pre_opt_bytecap_(size) _Deref_post_opt_bytecap_(size)) +#define _Deref_prepost_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_cap_, (size), _Deref_pre_cap_(size) _Deref_post_cap_(size)) +#define _Deref_prepost_opt_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_cap_, (size), \ + _Deref_pre_opt_cap_(size) _Deref_post_opt_cap_(size)) +#define _Deref_prepost_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecap_, (size), \ + _Deref_pre_bytecap_(size) _Deref_post_bytecap_(size)) +#define _Deref_prepost_opt_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecap_, (size), \ + _Deref_pre_opt_bytecap_(size) _Deref_post_opt_bytecap_(size)) -#define _Deref_prepost_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_cap_x_, (size), _Deref_pre_cap_x_(size) _Deref_post_cap_x_(size)) -#define _Deref_prepost_opt_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_cap_x_, (size), _Deref_pre_opt_cap_x_(size) _Deref_post_opt_cap_x_(size)) -#define _Deref_prepost_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_bytecap_x_, (size), _Deref_pre_bytecap_x_(size) _Deref_post_bytecap_x_(size)) -#define _Deref_prepost_opt_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecap_x_, (size), _Deref_pre_opt_bytecap_x_(size) _Deref_post_opt_bytecap_x_(size)) +#define _Deref_prepost_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_cap_x_, (size), _Deref_pre_cap_x_(size) _Deref_post_cap_x_(size)) +#define _Deref_prepost_opt_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_cap_x_, (size), \ + _Deref_pre_opt_cap_x_(size) _Deref_post_opt_cap_x_(size)) +#define _Deref_prepost_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecap_x_, (size), \ + _Deref_pre_bytecap_x_(size) _Deref_post_bytecap_x_(size)) +#define _Deref_prepost_opt_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecap_x_, (size), \ + _Deref_pre_opt_bytecap_x_(size) _Deref_post_opt_bytecap_x_(size)) -#define _Deref_prepost_z_cap_(size) _SAL1_1_Source_(_Deref_prepost_z_cap_, (size), _Deref_pre_z_cap_(size) _Deref_post_z_cap_(size)) -#define _Deref_prepost_opt_z_cap_(size) _SAL1_1_Source_(_Deref_prepost_opt_z_cap_, (size), _Deref_pre_opt_z_cap_(size) _Deref_post_opt_z_cap_(size)) -#define _Deref_prepost_z_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_z_bytecap_, (size), _Deref_pre_z_bytecap_(size) _Deref_post_z_bytecap_(size)) -#define _Deref_prepost_opt_z_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_opt_z_bytecap_, (size), _Deref_pre_opt_z_bytecap_(size) _Deref_post_opt_z_bytecap_(size)) +#define _Deref_prepost_z_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_z_cap_, (size), _Deref_pre_z_cap_(size) _Deref_post_z_cap_(size)) +#define _Deref_prepost_opt_z_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_z_cap_, (size), \ + _Deref_pre_opt_z_cap_(size) _Deref_post_opt_z_cap_(size)) +#define _Deref_prepost_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_z_bytecap_, (size), \ + _Deref_pre_z_bytecap_(size) _Deref_post_z_bytecap_(size)) +#define _Deref_prepost_opt_z_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_z_bytecap_, (size), \ + _Deref_pre_opt_z_bytecap_(size) _Deref_post_opt_z_bytecap_(size)) -#define _Deref_prepost_valid_cap_(size) _SAL1_1_Source_(_Deref_prepost_valid_cap_, (size), _Deref_pre_valid_cap_(size) _Deref_post_valid_cap_(size)) -#define _Deref_prepost_opt_valid_cap_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_, (size), _Deref_pre_opt_valid_cap_(size) _Deref_post_opt_valid_cap_(size)) -#define _Deref_prepost_valid_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_valid_bytecap_, (size), _Deref_pre_valid_bytecap_(size) _Deref_post_valid_bytecap_(size)) -#define _Deref_prepost_opt_valid_bytecap_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_, (size), _Deref_pre_opt_valid_bytecap_(size) _Deref_post_opt_valid_bytecap_(size)) +#define _Deref_prepost_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_cap_, (size), \ + _Deref_pre_valid_cap_(size) _Deref_post_valid_cap_(size)) +#define _Deref_prepost_opt_valid_cap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_, (size), \ + _Deref_pre_opt_valid_cap_(size) _Deref_post_opt_valid_cap_(size)) +#define _Deref_prepost_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_bytecap_, (size), \ + _Deref_pre_valid_bytecap_(size) _Deref_post_valid_bytecap_(size)) +#define _Deref_prepost_opt_valid_bytecap_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_, (size), \ + _Deref_pre_opt_valid_bytecap_(size) _Deref_post_opt_valid_bytecap_(size)) -#define _Deref_prepost_valid_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_valid_cap_x_, (size), _Deref_pre_valid_cap_x_(size) _Deref_post_valid_cap_x_(size)) -#define _Deref_prepost_opt_valid_cap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_x_, (size), _Deref_pre_opt_valid_cap_x_(size) _Deref_post_opt_valid_cap_x_(size)) -#define _Deref_prepost_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_valid_bytecap_x_, (size), _Deref_pre_valid_bytecap_x_(size) _Deref_post_valid_bytecap_x_(size)) -#define _Deref_prepost_opt_valid_bytecap_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_x_, (size), _Deref_pre_opt_valid_bytecap_x_(size) _Deref_post_opt_valid_bytecap_x_(size)) +#define _Deref_prepost_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_cap_x_, (size), \ + _Deref_pre_valid_cap_x_(size) _Deref_post_valid_cap_x_(size)) +#define _Deref_prepost_opt_valid_cap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_cap_x_, (size), \ + _Deref_pre_opt_valid_cap_x_(size) _Deref_post_opt_valid_cap_x_(size)) +#define _Deref_prepost_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_valid_bytecap_x_, (size), \ + _Deref_pre_valid_bytecap_x_(size) _Deref_post_valid_bytecap_x_(size)) +#define _Deref_prepost_opt_valid_bytecap_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_bytecap_x_, (size), \ + _Deref_pre_opt_valid_bytecap_x_(size) _Deref_post_opt_valid_bytecap_x_(size)) -#define _Deref_prepost_count_(size) _SAL1_1_Source_(_Deref_prepost_count_, (size), _Deref_pre_count_(size) _Deref_post_count_(size)) -#define _Deref_prepost_opt_count_(size) _SAL1_1_Source_(_Deref_prepost_opt_count_, (size), _Deref_pre_opt_count_(size) _Deref_post_opt_count_(size)) -#define _Deref_prepost_bytecount_(size) _SAL1_1_Source_(_Deref_prepost_bytecount_, (size), _Deref_pre_bytecount_(size) _Deref_post_bytecount_(size)) -#define _Deref_prepost_opt_bytecount_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecount_, (size), _Deref_pre_opt_bytecount_(size) _Deref_post_opt_bytecount_(size)) +#define _Deref_prepost_count_(size) \ + _SAL1_1_Source_(_Deref_prepost_count_, (size), _Deref_pre_count_(size) _Deref_post_count_(size)) +#define _Deref_prepost_opt_count_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_count_, (size), \ + _Deref_pre_opt_count_(size) _Deref_post_opt_count_(size)) +#define _Deref_prepost_bytecount_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecount_, (size), \ + _Deref_pre_bytecount_(size) _Deref_post_bytecount_(size)) +#define _Deref_prepost_opt_bytecount_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecount_, (size), \ + _Deref_pre_opt_bytecount_(size) _Deref_post_opt_bytecount_(size)) -#define _Deref_prepost_count_x_(size) _SAL1_1_Source_(_Deref_prepost_count_x_, (size), _Deref_pre_count_x_(size) _Deref_post_count_x_(size)) -#define _Deref_prepost_opt_count_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_count_x_, (size), _Deref_pre_opt_count_x_(size) _Deref_post_opt_count_x_(size)) -#define _Deref_prepost_bytecount_x_(size) _SAL1_1_Source_(_Deref_prepost_bytecount_x_, (size), _Deref_pre_bytecount_x_(size) _Deref_post_bytecount_x_(size)) -#define _Deref_prepost_opt_bytecount_x_(size) _SAL1_1_Source_(_Deref_prepost_opt_bytecount_x_, (size), _Deref_pre_opt_bytecount_x_(size) _Deref_post_opt_bytecount_x_(size)) +#define _Deref_prepost_count_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_count_x_, (size), \ + _Deref_pre_count_x_(size) _Deref_post_count_x_(size)) +#define _Deref_prepost_opt_count_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_count_x_, (size), \ + _Deref_pre_opt_count_x_(size) _Deref_post_opt_count_x_(size)) +#define _Deref_prepost_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_bytecount_x_, (size), \ + _Deref_pre_bytecount_x_(size) _Deref_post_bytecount_x_(size)) +#define _Deref_prepost_opt_bytecount_x_(size) \ + _SAL1_1_Source_(_Deref_prepost_opt_bytecount_x_, (size), \ + _Deref_pre_opt_bytecount_x_(size) _Deref_post_opt_bytecount_x_(size)) -#define _Deref_prepost_valid_ _SAL1_1_Source_(_Deref_prepost_valid_, (), _Deref_pre_valid_ _Deref_post_valid_) -#define _Deref_prepost_opt_valid_ _SAL1_1_Source_(_Deref_prepost_opt_valid_, (), _Deref_pre_opt_valid_ _Deref_post_opt_valid_) +#define _Deref_prepost_valid_ \ + _SAL1_1_Source_(_Deref_prepost_valid_, (), _Deref_pre_valid_ _Deref_post_valid_) +#define _Deref_prepost_opt_valid_ \ + _SAL1_1_Source_(_Deref_prepost_opt_valid_, (), _Deref_pre_opt_valid_ _Deref_post_opt_valid_) // // _Deref_ // // used with references to arrays -#define _Deref_out_z_cap_c_(size) _SAL1_1_Source_(_Deref_out_z_cap_c_, (size), _Deref_pre_cap_c_(size) _Deref_post_z_) -#define _Deref_inout_z_cap_c_(size) _SAL1_1_Source_(_Deref_inout_z_cap_c_, (size), _Deref_pre_z_cap_c_(size) _Deref_post_z_) -#define _Deref_out_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_out_z_bytecap_c_, (size), _Deref_pre_bytecap_c_(size) _Deref_post_z_) -#define _Deref_inout_z_bytecap_c_(size) _SAL1_1_Source_(_Deref_inout_z_bytecap_c_, (size), _Deref_pre_z_bytecap_c_(size) _Deref_post_z_) -#define _Deref_inout_z_ _SAL1_1_Source_(_Deref_inout_z_, (), _Deref_prepost_z_) +#define _Deref_out_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_out_z_cap_c_, (size), _Deref_pre_cap_c_(size) _Deref_post_z_) +#define _Deref_inout_z_cap_c_(size) \ + _SAL1_1_Source_(_Deref_inout_z_cap_c_, (size), _Deref_pre_z_cap_c_(size) _Deref_post_z_) +#define _Deref_out_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_out_z_bytecap_c_, (size), _Deref_pre_bytecap_c_(size) _Deref_post_z_) +#define _Deref_inout_z_bytecap_c_(size) \ + _SAL1_1_Source_(_Deref_inout_z_bytecap_c_, (size), _Deref_pre_z_bytecap_c_(size) _Deref_post_z_) +#define _Deref_inout_z_ _SAL1_1_Source_(_Deref_inout_z_, (), _Deref_prepost_z_) // #pragma endregion Input Buffer SAL 1 compatibility macros - //============================================================================ // Implementation Layer: //============================================================================ - // Naming conventions: // A symbol the begins with _SA_ is for the machinery of creating any // annotations; many of those come from sourceannotations.h in the case @@ -1487,141 +2545,149 @@ enum __SAL_YesNo {_SAL_notpresent, _SAL_no, _SAL_maybe, _SAL_yes, _SAL_default}; // but it does form a complete annotation; usually they are used to build // up even higher level annotations. - -#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ // Sharable "_impl" macros: these can be shared between the various annotation // forms but are part of the implementation of the macros. These are collected // here to assure that only necessary differences in the annotations // exist. -#define _Always_impl_(annos) _Group_(annos _SAL_nop_impl_) _On_failure_impl_(annos _SAL_nop_impl_) -#define _Bound_impl_ _SA_annotes0(SAL_bound) -#define _Field_range_impl_(min,max) _Range_impl_(min,max) -#define _Literal_impl_ _SA_annotes1(SAL_constant, __yes) -#define _Maybenull_impl_ _SA_annotes1(SAL_null, __maybe) -#define _Maybevalid_impl_ _SA_annotes1(SAL_valid, __maybe) +#define _Always_impl_(annos) _Group_(annos _SAL_nop_impl_) _On_failure_impl_(annos _SAL_nop_impl_) +#define _Bound_impl_ _SA_annotes0(SAL_bound) +#define _Field_range_impl_(min, max) _Range_impl_(min, max) +#define _Literal_impl_ _SA_annotes1(SAL_constant, __yes) +#define _Maybenull_impl_ _SA_annotes1(SAL_null, __maybe) +#define _Maybevalid_impl_ _SA_annotes1(SAL_valid, __maybe) #define _Must_inspect_impl_ _Post_impl_ _SA_annotes0(SAL_mustInspect) -#define _Notliteral_impl_ _SA_annotes1(SAL_constant, __no) -#define _Notnull_impl_ _SA_annotes1(SAL_null, __no) -#define _Notvalid_impl_ _SA_annotes1(SAL_valid, __no) -#define _NullNull_terminated_impl_ _Group_(_SA_annotes1(SAL_nullTerminated, __yes) _SA_annotes1(SAL_readableTo,inexpressibleCount("NullNull terminated string"))) -#define _Null_impl_ _SA_annotes1(SAL_null, __yes) -#define _Null_terminated_impl_ _SA_annotes1(SAL_nullTerminated, __yes) -#define _Out_impl_ _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ -#define _Out_opt_impl_ _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ -#define _Points_to_data_impl_ _At_(*_Curr_, _SA_annotes1(SAL_mayBePointer, __no)) -#define _Post_satisfies_impl_(cond) _Post_impl_ _Satisfies_impl_(cond) -#define _Post_valid_impl_ _Post1_impl_(__valid_impl) -#define _Pre_satisfies_impl_(cond) _Pre_impl_ _Satisfies_impl_(cond) -#define _Pre_valid_impl_ _Pre1_impl_(__valid_impl) -#define _Range_impl_(min,max) _SA_annotes2(SAL_range, min, max) -#define _Readable_bytes_impl_(size) _SA_annotes1(SAL_readableTo, byteCount(size)) -#define _Readable_elements_impl_(size) _SA_annotes1(SAL_readableTo, elementCount(size)) -#define _Ret_valid_impl_ _Ret1_impl_(__valid_impl) -#define _Satisfies_impl_(cond) _SA_annotes1(SAL_satisfies, cond) -#define _Valid_impl_ _SA_annotes1(SAL_valid, __yes) -#define _Writable_bytes_impl_(size) _SA_annotes1(SAL_writableTo, byteCount(size)) -#define _Writable_elements_impl_(size) _SA_annotes1(SAL_writableTo, elementCount(size)) +#define _Notliteral_impl_ _SA_annotes1(SAL_constant, __no) +#define _Notnull_impl_ _SA_annotes1(SAL_null, __no) +#define _Notvalid_impl_ _SA_annotes1(SAL_valid, __no) +#define _NullNull_terminated_impl_ \ + _Group_(_SA_annotes1(SAL_nullTerminated, __yes) \ + _SA_annotes1(SAL_readableTo, inexpressibleCount("NullNull terminated string"))) +#define _Null_impl_ _SA_annotes1(SAL_null, __yes) +#define _Null_terminated_impl_ _SA_annotes1(SAL_nullTerminated, __yes) +#define _Out_impl_ \ + _Pre1_impl_(__notnull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ +#define _Out_opt_impl_ \ + _Pre1_impl_(__maybenull_impl_notref) _Pre1_impl_(__cap_c_one_notref_impl) _Post_valid_impl_ +#define _Points_to_data_impl_ _At_(*_Curr_, _SA_annotes1(SAL_mayBePointer, __no)) +#define _Post_satisfies_impl_(cond) _Post_impl_ _Satisfies_impl_(cond) +#define _Post_valid_impl_ _Post1_impl_(__valid_impl) +#define _Pre_satisfies_impl_(cond) _Pre_impl_ _Satisfies_impl_(cond) +#define _Pre_valid_impl_ _Pre1_impl_(__valid_impl) +#define _Range_impl_(min, max) _SA_annotes2(SAL_range, min, max) +#define _Readable_bytes_impl_(size) _SA_annotes1(SAL_readableTo, byteCount(size)) +#define _Readable_elements_impl_(size) _SA_annotes1(SAL_readableTo, elementCount(size)) +#define _Ret_valid_impl_ _Ret1_impl_(__valid_impl) +#define _Satisfies_impl_(cond) _SA_annotes1(SAL_satisfies, cond) +#define _Valid_impl_ _SA_annotes1(SAL_valid, __yes) +#define _Writable_bytes_impl_(size) _SA_annotes1(SAL_writableTo, byteCount(size)) +#define _Writable_elements_impl_(size) _SA_annotes1(SAL_writableTo, elementCount(size)) -#define _In_range_impl_(min,max) _Pre_impl_ _Range_impl_(min,max) -#define _Out_range_impl_(min,max) _Post_impl_ _Range_impl_(min,max) -#define _Ret_range_impl_(min,max) _Post_impl_ _Range_impl_(min,max) -#define _Deref_in_range_impl_(min,max) _Deref_pre_impl_ _Range_impl_(min,max) -#define _Deref_out_range_impl_(min,max) _Deref_post_impl_ _Range_impl_(min,max) -#define _Deref_ret_range_impl_(min,max) _Deref_post_impl_ _Range_impl_(min,max) +#define _In_range_impl_(min, max) _Pre_impl_ _Range_impl_(min, max) +#define _Out_range_impl_(min, max) _Post_impl_ _Range_impl_(min, max) +#define _Ret_range_impl_(min, max) _Post_impl_ _Range_impl_(min, max) +#define _Deref_in_range_impl_(min, max) _Deref_pre_impl_ _Range_impl_(min, max) +#define _Deref_out_range_impl_(min, max) _Deref_post_impl_ _Range_impl_(min, max) +#define _Deref_ret_range_impl_(min, max) _Deref_post_impl_ _Range_impl_(min, max) -#define _Deref_pre_impl_ _Pre_impl_ _Notref_impl_ _Deref_impl_ -#define _Deref_post_impl_ _Post_impl_ _Notref_impl_ _Deref_impl_ +#define _Deref_pre_impl_ _Pre_impl_ _Notref_impl_ _Deref_impl_ +#define _Deref_post_impl_ _Post_impl_ _Notref_impl_ _Deref_impl_ // The following are for the implementation machinery, and are not // suitable for annotating general code. // We're tying to phase this out, someday. The parser quotes the param. -#define __AuToQuOtE _SA_annotes0(SAL_AuToQuOtE) +#define __AuToQuOtE _SA_annotes0(SAL_AuToQuOtE) // Normally the parser does some simple type checking of annotation params, // defer that check to the plugin. -#define __deferTypecheck _SA_annotes0(SAL_deferTypecheck) +#define __deferTypecheck _SA_annotes0(SAL_deferTypecheck) -#define _SA_SPECSTRIZE( x ) #x -#define _SAL_nop_impl_ /* nothing */ -#define __nop_impl(x) x +#define _SA_SPECSTRIZE(x) #x +#define _SAL_nop_impl_ /* nothing */ +#define __nop_impl(x) x #endif - -#if _USE_ATTRIBUTES_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL // [ // Using attributes for sal #include "codeanalysis\sourceannotations.h" +#define _SA_annotes0(n) [SAL_annotes(Name = #n)] +#define _SA_annotes1(n, pp1) [SAL_annotes(Name = #n, p1 = _SA_SPECSTRIZE(pp1))] +#define _SA_annotes2(n, pp1, pp2) \ + [SAL_annotes(Name = #n, p1 = _SA_SPECSTRIZE(pp1), p2 = _SA_SPECSTRIZE(pp2))] +#define _SA_annotes3(n, pp1, pp2, pp3) \ + [SAL_annotes(Name = #n, p1 = _SA_SPECSTRIZE(pp1), p2 = _SA_SPECSTRIZE(pp2), \ + p3 = _SA_SPECSTRIZE(pp3))] -#define _SA_annotes0(n) [SAL_annotes(Name=#n)] -#define _SA_annotes1(n,pp1) [SAL_annotes(Name=#n, p1=_SA_SPECSTRIZE(pp1))] -#define _SA_annotes2(n,pp1,pp2) [SAL_annotes(Name=#n, p1=_SA_SPECSTRIZE(pp1), p2=_SA_SPECSTRIZE(pp2))] -#define _SA_annotes3(n,pp1,pp2,pp3) [SAL_annotes(Name=#n, p1=_SA_SPECSTRIZE(pp1), p2=_SA_SPECSTRIZE(pp2), p3=_SA_SPECSTRIZE(pp3))] - -#define _Pre_impl_ [SAL_pre] -#define _Post_impl_ [SAL_post] -#define _Deref_impl_ [SAL_deref] -#define _Notref_impl_ [SAL_notref] - +#define _Pre_impl_ [SAL_pre] +#define _Post_impl_ [SAL_post] +#define _Deref_impl_ [SAL_deref] +#define _Notref_impl_ [SAL_notref] // Declare a function to be an annotation or primop (respectively). // Done this way so that they don't appear in the regular compiler's // namespace. -#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun; -#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun; -#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; +#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun; +#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun; +#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; // Benign declspec needed here for WindowsPREfast -#define __In_impl_ [SA_Pre(Valid=SA_Yes)] [SA_Pre(Deref=1, Notref=1, Access=SA_Read)] __declspec("SAL_pre SAL_valid") +#define __In_impl_ \ + [SA_Pre(Valid = SA_Yes)][SA_Pre(Deref = 1, Notref = 1, Access = SA_Read)] \ + __declspec("SAL_pre SAL_valid") -#elif _USE_DECLSPECS_FOR_SAL // ][ +#elif _USE_DECLSPECS_FOR_SAL // ][ // Using declspecs for sal -#define _SA_annotes0(n) __declspec(#n) -#define _SA_annotes1(n,pp1) __declspec(#n "(" _SA_SPECSTRIZE(pp1) ")" ) -#define _SA_annotes2(n,pp1,pp2) __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) ")") -#define _SA_annotes3(n,pp1,pp2,pp3) __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) "," _SA_SPECSTRIZE(pp3) ")") +#define _SA_annotes0(n) __declspec(#n) +#define _SA_annotes1(n, pp1) __declspec(#n "(" _SA_SPECSTRIZE(pp1) ")") +#define _SA_annotes2(n, pp1, pp2) __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) ")") +#define _SA_annotes3(n, pp1, pp2, pp3) \ + __declspec(#n "(" _SA_SPECSTRIZE(pp1) "," _SA_SPECSTRIZE(pp2) "," _SA_SPECSTRIZE(pp3) ")") -#define _Pre_impl_ _SA_annotes0(SAL_pre) -#define _Post_impl_ _SA_annotes0(SAL_post) -#define _Deref_impl_ _SA_annotes0(SAL_deref) -#define _Notref_impl_ _SA_annotes0(SAL_notref) +#define _Pre_impl_ _SA_annotes0(SAL_pre) +#define _Post_impl_ _SA_annotes0(SAL_post) +#define _Deref_impl_ _SA_annotes0(SAL_deref) +#define _Notref_impl_ _SA_annotes0(SAL_notref) // Declare a function to be an annotation or primop (respectively). // Done this way so that they don't appear in the regular compiler's // namespace. -#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun +#define __ANNOTATION(fun) _SA_annotes0(SAL_annotation) void __SA_##fun -#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun +#define __PRIMOP(type, fun) _SA_annotes0(SAL_primop) type __SA_##fun -#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; +#define __QUALIFIER(fun) _SA_annotes0(SAL_qualifier) void __SA_##fun; -#define __In_impl_ _Pre_impl_ _SA_annotes0(SAL_valid) _Pre_impl_ _Deref_impl_ _Notref_impl_ _SA_annotes0(SAL_readonly) +#define __In_impl_ \ + _Pre_impl_ _SA_annotes0(SAL_valid) \ + _Pre_impl_ _Deref_impl_ _Notref_impl_ _SA_annotes0(SAL_readonly) -#else // ][ +#else // ][ // Using "nothing" for sal #define _SA_annotes0(n) -#define _SA_annotes1(n,pp1) -#define _SA_annotes2(n,pp1,pp2) -#define _SA_annotes3(n,pp1,pp2,pp3) +#define _SA_annotes1(n, pp1) +#define _SA_annotes2(n, pp1, pp2) +#define _SA_annotes3(n, pp1, pp2, pp3) #define __ANNOTATION(fun) #define __PRIMOP(type, fun) #define __QUALIFIER(type, fun) -#endif // ] +#endif // ] -#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL || _USE_DECLSPECS_FOR_SAL // [ // Declare annotations that need to be declared. __ANNOTATION(SAL_useHeader(void)); __ANNOTATION(SAL_bound(void)); -__ANNOTATION(SAL_allocator(void)); //??? resolve with PFD +__ANNOTATION(SAL_allocator(void)); //??? resolve with PFD __ANNOTATION(SAL_file_parser(__AuToQuOtE __In_impl_ char *, __In_impl_ char *)); __ANNOTATION(SAL_source_code_content(__In_impl_ char *)); __ANNOTATION(SAL_analysisHint(__AuToQuOtE __In_impl_ char *)); @@ -1638,7 +2704,7 @@ __ANNOTATION(SAL_post_type(__AuToQuOtE __In_impl_ char *)); __ANNOTATION(SAL_volatile(void)); __ANNOTATION(SAL_nonvolatile(void)); __ANNOTATION(SAL_entrypoint(__AuToQuOtE __In_impl_ char *, __AuToQuOtE __In_impl_ char *)); -__ANNOTATION(SAL_blocksOn(__In_impl_ void*)); +__ANNOTATION(SAL_blocksOn(__In_impl_ void *)); __ANNOTATION(SAL_mustInspect(void)); // Only appears in model files, but needs to be declared. @@ -1647,410 +2713,400 @@ __ANNOTATION(SAL_TypeName(__AuToQuOtE __In_impl_ char *)); // To be declared well-known soon. __ANNOTATION(SAL_interlocked(void);) -#pragma warning (suppress: 28227 28241) +#pragma warning(suppress : 28227 28241) __ANNOTATION(SAL_name(__In_impl_ char *, __In_impl_ char *, __In_impl_ char *);) __PRIMOP(char *, _Macro_value_(__In_impl_ char *)); __PRIMOP(int, _Macro_defined_(__In_impl_ char *)); __PRIMOP(char *, _Strstr_(__In_impl_ char *, __In_impl_ char *)); -#endif // ] +#endif // ] -#if _USE_ATTRIBUTES_FOR_SAL // [ +#if _USE_ATTRIBUTES_FOR_SAL // [ -#define _Check_return_impl_ [SA_Post(MustCheck=SA_Yes)] +#define _Check_return_impl_ [SA_Post(MustCheck = SA_Yes)] -#define _Success_impl_(expr) [SA_Success(Condition=#expr)] -#define _On_failure_impl_(annos) [SAL_context(p1="SAL_failed")] _Group_(_Post_impl_ _Group_(annos _SAL_nop_impl_)) +#define _Success_impl_(expr) [SA_Success(Condition = #expr)] +#define _On_failure_impl_(annos) \ + [SAL_context(p1 = "SAL_failed")] _Group_(_Post_impl_ _Group_(annos _SAL_nop_impl_)) -#define _Printf_format_string_impl_ [SA_FormatString(Style="printf")] -#define _Scanf_format_string_impl_ [SA_FormatString(Style="scanf")] -#define _Scanf_s_format_string_impl_ [SA_FormatString(Style="scanf_s")] +#define _Printf_format_string_impl_ [SA_FormatString(Style = "printf")] +#define _Scanf_format_string_impl_ [SA_FormatString(Style = "scanf")] +#define _Scanf_s_format_string_impl_ [SA_FormatString(Style = "scanf_s")] -#define _In_bound_impl_ [SA_PreBound(Deref=0)] -#define _Out_bound_impl_ [SA_PostBound(Deref=0)] -#define _Ret_bound_impl_ [SA_PostBound(Deref=0)] -#define _Deref_in_bound_impl_ [SA_PreBound(Deref=1)] -#define _Deref_out_bound_impl_ [SA_PostBound(Deref=1)] -#define _Deref_ret_bound_impl_ [SA_PostBound(Deref=1)] +#define _In_bound_impl_ [SA_PreBound(Deref = 0)] +#define _Out_bound_impl_ [SA_PostBound(Deref = 0)] +#define _Ret_bound_impl_ [SA_PostBound(Deref = 0)] +#define _Deref_in_bound_impl_ [SA_PreBound(Deref = 1)] +#define _Deref_out_bound_impl_ [SA_PostBound(Deref = 1)] +#define _Deref_ret_bound_impl_ [SA_PostBound(Deref = 1)] -#define __valid_impl Valid=SA_Yes -#define __maybevalid_impl Valid=SA_Maybe -#define __notvalid_impl Valid=SA_No +#define __valid_impl Valid = SA_Yes +#define __maybevalid_impl Valid = SA_Maybe +#define __notvalid_impl Valid = SA_No -#define __null_impl Null=SA_Yes -#define __maybenull_impl Null=SA_Maybe -#define __notnull_impl Null=SA_No +#define __null_impl Null = SA_Yes +#define __maybenull_impl Null = SA_Maybe +#define __notnull_impl Null = SA_No -#define __null_impl_notref Null=SA_Yes,Notref=1 -#define __maybenull_impl_notref Null=SA_Maybe,Notref=1 -#define __notnull_impl_notref Null=SA_No,Notref=1 +#define __null_impl_notref Null = SA_Yes, Notref = 1 +#define __maybenull_impl_notref Null = SA_Maybe, Notref = 1 +#define __notnull_impl_notref Null = SA_No, Notref = 1 -#define __zterm_impl NullTerminated=SA_Yes -#define __maybezterm_impl NullTerminated=SA_Maybe -#define __maybzterm_impl NullTerminated=SA_Maybe -#define __notzterm_impl NullTerminated=SA_No +#define __zterm_impl NullTerminated = SA_Yes +#define __maybezterm_impl NullTerminated = SA_Maybe +#define __maybzterm_impl NullTerminated = SA_Maybe +#define __notzterm_impl NullTerminated = SA_No -#define __readaccess_impl Access=SA_Read -#define __writeaccess_impl Access=SA_Write -#define __allaccess_impl Access=SA_ReadWrite +#define __readaccess_impl Access = SA_Read +#define __writeaccess_impl Access = SA_Write +#define __allaccess_impl Access = SA_ReadWrite -#define __readaccess_impl_notref Access=SA_Read,Notref=1 -#define __writeaccess_impl_notref Access=SA_Write,Notref=1 -#define __allaccess_impl_notref Access=SA_ReadWrite,Notref=1 +#define __readaccess_impl_notref Access = SA_Read, Notref = 1 +#define __writeaccess_impl_notref Access = SA_Write, Notref = 1 +#define __allaccess_impl_notref Access = SA_ReadWrite, Notref = 1 -#if _MSC_VER >= 1610 /*IFSTRIP=IGN*/ // [ +#if _MSC_VER >= 1610 /*IFSTRIP=IGN*/ // [ // For SAL2, we need to expect general expressions. -#define __cap_impl(size) WritableElements="\n"#size -#define __bytecap_impl(size) WritableBytes="\n"#size -#define __bytecount_impl(size) ValidBytes="\n"#size -#define __count_impl(size) ValidElements="\n"#size +#define __cap_impl(size) WritableElements = "\n" #size +#define __bytecap_impl(size) WritableBytes = "\n" #size +#define __bytecount_impl(size) ValidBytes = "\n" #size +#define __count_impl(size) ValidElements = "\n" #size -#else // ][ +#else // ][ -#define __cap_impl(size) WritableElements=#size -#define __bytecap_impl(size) WritableBytes=#size -#define __bytecount_impl(size) ValidBytes=#size -#define __count_impl(size) ValidElements=#size +#define __cap_impl(size) WritableElements = #size +#define __bytecap_impl(size) WritableBytes = #size +#define __bytecount_impl(size) ValidBytes = #size +#define __count_impl(size) ValidElements = #size -#endif // ] +#endif // ] -#define __cap_c_impl(size) WritableElementsConst=size -#define __cap_c_one_notref_impl WritableElementsConst=1,Notref=1 -#define __cap_for_impl(param) WritableElementsLength=#param -#define __cap_x_impl(size) WritableElements="\n@"#size +#define __cap_c_impl(size) WritableElementsConst = size +#define __cap_c_one_notref_impl WritableElementsConst = 1, Notref = 1 +#define __cap_for_impl(param) WritableElementsLength = #param +#define __cap_x_impl(size) WritableElements = "\n@" #size -#define __bytecap_c_impl(size) WritableBytesConst=size -#define __bytecap_x_impl(size) WritableBytes="\n@"#size +#define __bytecap_c_impl(size) WritableBytesConst = size +#define __bytecap_x_impl(size) WritableBytes = "\n@" #size -#define __mult_impl(mult,size) __cap_impl((mult)*(size)) +#define __mult_impl(mult, size) __cap_impl((mult) * (size)) -#define __count_c_impl(size) ValidElementsConst=size -#define __count_x_impl(size) ValidElements="\n@"#size +#define __count_c_impl(size) ValidElementsConst = size +#define __count_x_impl(size) ValidElements = "\n@" #size -#define __bytecount_c_impl(size) ValidBytesConst=size -#define __bytecount_x_impl(size) ValidBytes="\n@"#size +#define __bytecount_c_impl(size) ValidBytesConst = size +#define __bytecount_x_impl(size) ValidBytes = "\n@" #size +#define _At_impl_(target, annos) [SAL_at(p1 = #target)] _Group_(annos) +#define _At_buffer_impl_(target, iter, bound, annos) \ + [SAL_at_buffer(p1 = #target, p2 = #iter, p3 = #bound)] _Group_(annos) +#define _When_impl_(expr, annos) [SAL_when(p1 = #expr)] _Group_(annos) -#define _At_impl_(target, annos) [SAL_at(p1=#target)] _Group_(annos) -#define _At_buffer_impl_(target, iter, bound, annos) [SAL_at_buffer(p1=#target, p2=#iter, p3=#bound)] _Group_(annos) -#define _When_impl_(expr, annos) [SAL_when(p1=#expr)] _Group_(annos) +#define _Group_impl_(annos) [SAL_begin] annos[SAL_end] +#define _GrouP_impl_(annos) [SAL_BEGIN] annos[SAL_END] -#define _Group_impl_(annos) [SAL_begin] annos [SAL_end] -#define _GrouP_impl_(annos) [SAL_BEGIN] annos [SAL_END] +#define _Use_decl_anno_impl_ _SA_annotes0(SAL_useHeader) // this is a special case! -#define _Use_decl_anno_impl_ _SA_annotes0(SAL_useHeader) // this is a special case! +#define _Pre1_impl_(p1) [SA_Pre(p1)] +#define _Pre2_impl_(p1, p2) [SA_Pre(p1, p2)] +#define _Pre3_impl_(p1, p2, p3) [SA_Pre(p1, p2, p3)] -#define _Pre1_impl_(p1) [SA_Pre(p1)] -#define _Pre2_impl_(p1,p2) [SA_Pre(p1,p2)] -#define _Pre3_impl_(p1,p2,p3) [SA_Pre(p1,p2,p3)] +#define _Post1_impl_(p1) [SA_Post(p1)] +#define _Post2_impl_(p1, p2) [SA_Post(p1, p2)] +#define _Post3_impl_(p1, p2, p3) [SA_Post(p1, p2, p3)] -#define _Post1_impl_(p1) [SA_Post(p1)] -#define _Post2_impl_(p1,p2) [SA_Post(p1,p2)] -#define _Post3_impl_(p1,p2,p3) [SA_Post(p1,p2,p3)] +#define _Ret1_impl_(p1) [SA_Post(p1)] +#define _Ret2_impl_(p1, p2) [SA_Post(p1, p2)] +#define _Ret3_impl_(p1, p2, p3) [SA_Post(p1, p2, p3)] -#define _Ret1_impl_(p1) [SA_Post(p1)] -#define _Ret2_impl_(p1,p2) [SA_Post(p1,p2)] -#define _Ret3_impl_(p1,p2,p3) [SA_Post(p1,p2,p3)] +#define _Deref_pre1_impl_(p1) [SA_Pre(Deref = 1, p1)] +#define _Deref_pre2_impl_(p1, p2) [SA_Pre(Deref = 1, p1, p2)] +#define _Deref_pre3_impl_(p1, p2, p3) [SA_Pre(Deref = 1, p1, p2, p3)] -#define _Deref_pre1_impl_(p1) [SA_Pre(Deref=1,p1)] -#define _Deref_pre2_impl_(p1,p2) [SA_Pre(Deref=1,p1,p2)] -#define _Deref_pre3_impl_(p1,p2,p3) [SA_Pre(Deref=1,p1,p2,p3)] +#define _Deref_post1_impl_(p1) [SA_Post(Deref = 1, p1)] +#define _Deref_post2_impl_(p1, p2) [SA_Post(Deref = 1, p1, p2)] +#define _Deref_post3_impl_(p1, p2, p3) [SA_Post(Deref = 1, p1, p2, p3)] +#define _Deref_ret1_impl_(p1) [SA_Post(Deref = 1, p1)] +#define _Deref_ret2_impl_(p1, p2) [SA_Post(Deref = 1, p1, p2)] +#define _Deref_ret3_impl_(p1, p2, p3) [SA_Post(Deref = 1, p1, p2, p3)] -#define _Deref_post1_impl_(p1) [SA_Post(Deref=1,p1)] -#define _Deref_post2_impl_(p1,p2) [SA_Post(Deref=1,p1,p2)] -#define _Deref_post3_impl_(p1,p2,p3) [SA_Post(Deref=1,p1,p2,p3)] - -#define _Deref_ret1_impl_(p1) [SA_Post(Deref=1,p1)] -#define _Deref_ret2_impl_(p1,p2) [SA_Post(Deref=1,p1,p2)] -#define _Deref_ret3_impl_(p1,p2,p3) [SA_Post(Deref=1,p1,p2,p3)] - -#define _Deref2_pre1_impl_(p1) [SA_Pre(Deref=2,Notref=1,p1)] -#define _Deref2_post1_impl_(p1) [SA_Post(Deref=2,Notref=1,p1)] -#define _Deref2_ret1_impl_(p1) [SA_Post(Deref=2,Notref=1,p1)] +#define _Deref2_pre1_impl_(p1) [SA_Pre(Deref = 2, Notref = 1, p1)] +#define _Deref2_post1_impl_(p1) [SA_Post(Deref = 2, Notref = 1, p1)] +#define _Deref2_ret1_impl_(p1) [SA_Post(Deref = 2, Notref = 1, p1)] // Obsolete -- may be needed for transition to attributes. -#define __inner_typefix(ctype) [SAL_typefix(p1=_SA_SPECSTRIZE(ctype))] -#define __inner_exceptthat [SAL_except] +#define __inner_typefix(ctype) [SAL_typefix(p1 = _SA_SPECSTRIZE(ctype))] +#define __inner_exceptthat [SAL_except] +#elif _USE_DECLSPECS_FOR_SAL // ][ -#elif _USE_DECLSPECS_FOR_SAL // ][ +#define _Check_return_impl_ __post _SA_annotes0(SAL_checkReturn) -#define _Check_return_impl_ __post _SA_annotes0(SAL_checkReturn) +#define _Success_impl_(expr) _SA_annotes1(SAL_success, expr) +#define _On_failure_impl_(annos) \ + _SA_annotes1(SAL_context, SAL_failed) _Group_(_Post_impl_ _Group_(_SAL_nop_impl_ annos)) -#define _Success_impl_(expr) _SA_annotes1(SAL_success, expr) -#define _On_failure_impl_(annos) _SA_annotes1(SAL_context, SAL_failed) _Group_(_Post_impl_ _Group_(_SAL_nop_impl_ annos)) +#define _Printf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "printf") +#define _Scanf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf") +#define _Scanf_s_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf_s") -#define _Printf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "printf") -#define _Scanf_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf") -#define _Scanf_s_format_string_impl_ _SA_annotes1(SAL_IsFormatString, "scanf_s") +#define _In_bound_impl_ _Pre_impl_ _Bound_impl_ +#define _Out_bound_impl_ _Post_impl_ _Bound_impl_ +#define _Ret_bound_impl_ _Post_impl_ _Bound_impl_ +#define _Deref_in_bound_impl_ _Deref_pre_impl_ _Bound_impl_ +#define _Deref_out_bound_impl_ _Deref_post_impl_ _Bound_impl_ +#define _Deref_ret_bound_impl_ _Deref_post_impl_ _Bound_impl_ -#define _In_bound_impl_ _Pre_impl_ _Bound_impl_ -#define _Out_bound_impl_ _Post_impl_ _Bound_impl_ -#define _Ret_bound_impl_ _Post_impl_ _Bound_impl_ -#define _Deref_in_bound_impl_ _Deref_pre_impl_ _Bound_impl_ -#define _Deref_out_bound_impl_ _Deref_post_impl_ _Bound_impl_ -#define _Deref_ret_bound_impl_ _Deref_post_impl_ _Bound_impl_ +#define __null_impl _SA_annotes0(SAL_null) // _SA_annotes1(SAL_null, __yes) +#define __notnull_impl _SA_annotes0(SAL_notnull) // _SA_annotes1(SAL_null, __no) +#define __maybenull_impl _SA_annotes0(SAL_maybenull) // _SA_annotes1(SAL_null, __maybe) +#define __valid_impl _SA_annotes0(SAL_valid) // _SA_annotes1(SAL_valid, __yes) +#define __notvalid_impl _SA_annotes0(SAL_notvalid) // _SA_annotes1(SAL_valid, __no) +#define __maybevalid_impl _SA_annotes0(SAL_maybevalid) // _SA_annotes1(SAL_valid, __maybe) -#define __null_impl _SA_annotes0(SAL_null) // _SA_annotes1(SAL_null, __yes) -#define __notnull_impl _SA_annotes0(SAL_notnull) // _SA_annotes1(SAL_null, __no) -#define __maybenull_impl _SA_annotes0(SAL_maybenull) // _SA_annotes1(SAL_null, __maybe) +#define __null_impl_notref _Notref_ _Null_impl_ +#define __maybenull_impl_notref _Notref_ _Maybenull_impl_ +#define __notnull_impl_notref _Notref_ _Notnull_impl_ -#define __valid_impl _SA_annotes0(SAL_valid) // _SA_annotes1(SAL_valid, __yes) -#define __notvalid_impl _SA_annotes0(SAL_notvalid) // _SA_annotes1(SAL_valid, __no) -#define __maybevalid_impl _SA_annotes0(SAL_maybevalid) // _SA_annotes1(SAL_valid, __maybe) +#define __zterm_impl _SA_annotes1(SAL_nullTerminated, __yes) +#define __maybezterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) +#define __maybzterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) +#define __notzterm_impl _SA_annotes1(SAL_nullTerminated, __no) -#define __null_impl_notref _Notref_ _Null_impl_ -#define __maybenull_impl_notref _Notref_ _Maybenull_impl_ -#define __notnull_impl_notref _Notref_ _Notnull_impl_ +#define __readaccess_impl _SA_annotes1(SAL_access, 0x1) +#define __writeaccess_impl _SA_annotes1(SAL_access, 0x2) +#define __allaccess_impl _SA_annotes1(SAL_access, 0x3) -#define __zterm_impl _SA_annotes1(SAL_nullTerminated, __yes) -#define __maybezterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) -#define __maybzterm_impl _SA_annotes1(SAL_nullTerminated, __maybe) -#define __notzterm_impl _SA_annotes1(SAL_nullTerminated, __no) - -#define __readaccess_impl _SA_annotes1(SAL_access, 0x1) -#define __writeaccess_impl _SA_annotes1(SAL_access, 0x2) -#define __allaccess_impl _SA_annotes1(SAL_access, 0x3) - -#define __readaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x1) +#define __readaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x1) #define __writeaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x2) -#define __allaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x3) +#define __allaccess_impl_notref _Notref_ _SA_annotes1(SAL_access, 0x3) -#define __cap_impl(size) _SA_annotes1(SAL_writableTo,elementCount(size)) -#define __cap_c_impl(size) _SA_annotes1(SAL_writableTo,elementCount(size)) -#define __cap_c_one_notref_impl _Notref_ _SA_annotes1(SAL_writableTo,elementCount(1)) -#define __cap_for_impl(param) _SA_annotes1(SAL_writableTo,inexpressibleCount(sizeof(param))) -#define __cap_x_impl(size) _SA_annotes1(SAL_writableTo,inexpressibleCount(#size)) +#define __cap_impl(size) _SA_annotes1(SAL_writableTo, elementCount(size)) +#define __cap_c_impl(size) _SA_annotes1(SAL_writableTo, elementCount(size)) +#define __cap_c_one_notref_impl _Notref_ _SA_annotes1(SAL_writableTo, elementCount(1)) +#define __cap_for_impl(param) _SA_annotes1(SAL_writableTo, inexpressibleCount(sizeof(param))) +#define __cap_x_impl(size) _SA_annotes1(SAL_writableTo, inexpressibleCount(#size)) -#define __bytecap_impl(size) _SA_annotes1(SAL_writableTo,byteCount(size)) -#define __bytecap_c_impl(size) _SA_annotes1(SAL_writableTo,byteCount(size)) -#define __bytecap_x_impl(size) _SA_annotes1(SAL_writableTo,inexpressibleCount(#size)) +#define __bytecap_impl(size) _SA_annotes1(SAL_writableTo, byteCount(size)) +#define __bytecap_c_impl(size) _SA_annotes1(SAL_writableTo, byteCount(size)) +#define __bytecap_x_impl(size) _SA_annotes1(SAL_writableTo, inexpressibleCount(#size)) -#define __mult_impl(mult,size) _SA_annotes1(SAL_writableTo,(mult)*(size)) +#define __mult_impl(mult, size) _SA_annotes1(SAL_writableTo, (mult) * (size)) -#define __count_impl(size) _SA_annotes1(SAL_readableTo,elementCount(size)) -#define __count_c_impl(size) _SA_annotes1(SAL_readableTo,elementCount(size)) -#define __count_x_impl(size) _SA_annotes1(SAL_readableTo,inexpressibleCount(#size)) +#define __count_impl(size) _SA_annotes1(SAL_readableTo, elementCount(size)) +#define __count_c_impl(size) _SA_annotes1(SAL_readableTo, elementCount(size)) +#define __count_x_impl(size) _SA_annotes1(SAL_readableTo, inexpressibleCount(#size)) -#define __bytecount_impl(size) _SA_annotes1(SAL_readableTo,byteCount(size)) -#define __bytecount_c_impl(size) _SA_annotes1(SAL_readableTo,byteCount(size)) -#define __bytecount_x_impl(size) _SA_annotes1(SAL_readableTo,inexpressibleCount(#size)) +#define __bytecount_impl(size) _SA_annotes1(SAL_readableTo, byteCount(size)) +#define __bytecount_c_impl(size) _SA_annotes1(SAL_readableTo, byteCount(size)) +#define __bytecount_x_impl(size) _SA_annotes1(SAL_readableTo, inexpressibleCount(#size)) -#define _At_impl_(target, annos) _SA_annotes0(SAL_at(target)) _Group_(annos) -#define _At_buffer_impl_(target, iter, bound, annos) _SA_annotes3(SAL_at_buffer, target, iter, bound) _Group_(annos) -#define _Group_impl_(annos) _SA_annotes0(SAL_begin) annos _SA_annotes0(SAL_end) -#define _GrouP_impl_(annos) _SA_annotes0(SAL_BEGIN) annos _SA_annotes0(SAL_END) -#define _When_impl_(expr, annos) _SA_annotes0(SAL_when(expr)) _Group_(annos) +#define _At_impl_(target, annos) _SA_annotes0(SAL_at(target)) _Group_(annos) +#define _At_buffer_impl_(target, iter, bound, annos) \ + _SA_annotes3(SAL_at_buffer, target, iter, bound) _Group_(annos) +#define _Group_impl_(annos) _SA_annotes0(SAL_begin) annos _SA_annotes0(SAL_end) +#define _GrouP_impl_(annos) _SA_annotes0(SAL_BEGIN) annos _SA_annotes0(SAL_END) +#define _When_impl_(expr, annos) _SA_annotes0(SAL_when(expr)) _Group_(annos) -#define _Use_decl_anno_impl_ __declspec("SAL_useHeader()") // this is a special case! +#define _Use_decl_anno_impl_ __declspec("SAL_useHeader()") // this is a special case! -#define _Pre1_impl_(p1) _Pre_impl_ p1 -#define _Pre2_impl_(p1,p2) _Pre_impl_ p1 _Pre_impl_ p2 -#define _Pre3_impl_(p1,p2,p3) _Pre_impl_ p1 _Pre_impl_ p2 _Pre_impl_ p3 +#define _Pre1_impl_(p1) _Pre_impl_ p1 +#define _Pre2_impl_(p1, p2) _Pre_impl_ p1 _Pre_impl_ p2 +#define _Pre3_impl_(p1, p2, p3) _Pre_impl_ p1 _Pre_impl_ p2 _Pre_impl_ p3 -#define _Post1_impl_(p1) _Post_impl_ p1 -#define _Post2_impl_(p1,p2) _Post_impl_ p1 _Post_impl_ p2 -#define _Post3_impl_(p1,p2,p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 +#define _Post1_impl_(p1) _Post_impl_ p1 +#define _Post2_impl_(p1, p2) _Post_impl_ p1 _Post_impl_ p2 +#define _Post3_impl_(p1, p2, p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 -#define _Ret1_impl_(p1) _Post_impl_ p1 -#define _Ret2_impl_(p1,p2) _Post_impl_ p1 _Post_impl_ p2 -#define _Ret3_impl_(p1,p2,p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 +#define _Ret1_impl_(p1) _Post_impl_ p1 +#define _Ret2_impl_(p1, p2) _Post_impl_ p1 _Post_impl_ p2 +#define _Ret3_impl_(p1, p2, p3) _Post_impl_ p1 _Post_impl_ p2 _Post_impl_ p3 -#define _Deref_pre1_impl_(p1) _Deref_pre_impl_ p1 -#define _Deref_pre2_impl_(p1,p2) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 -#define _Deref_pre3_impl_(p1,p2,p3) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 _Deref_pre_impl_ p3 +#define _Deref_pre1_impl_(p1) _Deref_pre_impl_ p1 +#define _Deref_pre2_impl_(p1, p2) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 +#define _Deref_pre3_impl_(p1, p2, p3) _Deref_pre_impl_ p1 _Deref_pre_impl_ p2 _Deref_pre_impl_ p3 -#define _Deref_post1_impl_(p1) _Deref_post_impl_ p1 -#define _Deref_post2_impl_(p1,p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 -#define _Deref_post3_impl_(p1,p2,p3) _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 +#define _Deref_post1_impl_(p1) _Deref_post_impl_ p1 +#define _Deref_post2_impl_(p1, p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 +#define _Deref_post3_impl_(p1, p2, p3) \ + _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 -#define _Deref_ret1_impl_(p1) _Deref_post_impl_ p1 -#define _Deref_ret2_impl_(p1,p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 -#define _Deref_ret3_impl_(p1,p2,p3) _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 +#define _Deref_ret1_impl_(p1) _Deref_post_impl_ p1 +#define _Deref_ret2_impl_(p1, p2) _Deref_post_impl_ p1 _Deref_post_impl_ p2 +#define _Deref_ret3_impl_(p1, p2, p3) _Deref_post_impl_ p1 _Deref_post_impl_ p2 _Deref_post_impl_ p3 -#define _Deref2_pre1_impl_(p1) _Deref_pre_impl_ _Notref_impl_ _Deref_impl_ p1 -#define _Deref2_post1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 -#define _Deref2_ret1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 +#define _Deref2_pre1_impl_(p1) _Deref_pre_impl_ _Notref_impl_ _Deref_impl_ p1 +#define _Deref2_post1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 +#define _Deref2_ret1_impl_(p1) _Deref_post_impl_ _Notref_impl_ _Deref_impl_ p1 -#define __inner_typefix(ctype) _SA_annotes1(SAL_typefix, ctype) -#define __inner_exceptthat _SA_annotes0(SAL_except) +#define __inner_typefix(ctype) _SA_annotes1(SAL_typefix, ctype) +#define __inner_exceptthat _SA_annotes0(SAL_except) -#elif defined(_MSC_EXTENSIONS) && !defined( MIDL_PASS ) && !defined(__midl) && !defined(RC_INVOKED) && defined(_PFT_VER) && _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // ][ +#elif defined(_MSC_EXTENSIONS) && !defined(MIDL_PASS) && !defined(__midl) && \ + !defined(RC_INVOKED) && defined(_PFT_VER) && _MSC_VER >= 1400 /*IFSTRIP=IGN*/ // ][ // minimum attribute expansion for foreground build -#pragma push_macro( "SA" ) -#pragma push_macro( "REPEATABLE" ) +#pragma push_macro("SA") +#pragma push_macro("REPEATABLE") -#ifdef __cplusplus // [ -#define SA( id ) id +#ifdef __cplusplus // [ +#define SA(id) id #define REPEATABLE [repeatable] #else // !__cplusplus // ][ -#define SA( id ) SA_##id +#define SA(id) SA_##id #define REPEATABLE -#endif // !__cplusplus // ] +#endif // !__cplusplus // ] REPEATABLE -[source_annotation_attribute( SA( Parameter ) )] -struct __P_impl -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(Parameter))] struct __P_impl { +#ifdef __cplusplus // [ __P_impl(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __P_impl __P_impl; REPEATABLE -[source_annotation_attribute( SA( ReturnValue ) )] -struct __R_impl -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(ReturnValue))] struct __R_impl { +#ifdef __cplusplus // [ __R_impl(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __R_impl __R_impl; -[source_annotation_attribute( SA( Method ) )] -struct __M_ -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(Method))] struct __M_ { +#ifdef __cplusplus // [ __M_(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __M_ __M_; -[source_annotation_attribute( SA( All ) )] -struct __A_ -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(All))] struct __A_ { +#ifdef __cplusplus // [ __A_(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __A_ __A_; -[source_annotation_attribute( SA( Field ) )] -struct __F_ -{ -#ifdef __cplusplus // [ +[source_annotation_attribute(SA(Field))] struct __F_ { +#ifdef __cplusplus // [ __F_(); -#endif // ] - int __d_; +#endif // ] + int __d_; }; typedef struct __F_ __F_; -#pragma pop_macro( "REPEATABLE" ) -#pragma pop_macro( "SA" ) - +#pragma pop_macro("REPEATABLE") +#pragma pop_macro("SA") #define _SAL_nop_impl_ -#define _At_impl_(target, annos) [__A_(__d_=0)] -#define _At_buffer_impl_(target, iter, bound, annos) [__A_(__d_=0)] -#define _When_impl_(expr, annos) annos -#define _Group_impl_(annos) annos -#define _GrouP_impl_(annos) annos -#define _Use_decl_anno_impl_ [__M_(__d_=0)] +#define _At_impl_(target, annos) [__A_(__d_ = 0)] +#define _At_buffer_impl_(target, iter, bound, annos) [__A_(__d_ = 0)] +#define _When_impl_(expr, annos) annos +#define _Group_impl_(annos) annos +#define _GrouP_impl_(annos) annos +#define _Use_decl_anno_impl_ [__M_(__d_ = 0)] -#define _Points_to_data_impl_ [__P_impl(__d_=0)] -#define _Literal_impl_ [__P_impl(__d_=0)] -#define _Notliteral_impl_ [__P_impl(__d_=0)] +#define _Points_to_data_impl_ [__P_impl(__d_ = 0)] +#define _Literal_impl_ [__P_impl(__d_ = 0)] +#define _Notliteral_impl_ [__P_impl(__d_ = 0)] -#define _Pre_valid_impl_ [__P_impl(__d_=0)] -#define _Post_valid_impl_ [__P_impl(__d_=0)] -#define _Ret_valid_impl_ [__R_impl(__d_=0)] +#define _Pre_valid_impl_ [__P_impl(__d_ = 0)] +#define _Post_valid_impl_ [__P_impl(__d_ = 0)] +#define _Ret_valid_impl_ [__R_impl(__d_ = 0)] -#define _Check_return_impl_ [__R_impl(__d_=0)] -#define _Must_inspect_impl_ [__R_impl(__d_=0)] +#define _Check_return_impl_ [__R_impl(__d_ = 0)] +#define _Must_inspect_impl_ [__R_impl(__d_ = 0)] -#define _Success_impl_(expr) [__M_(__d_=0)] -#define _On_failure_impl_(expr) [__M_(__d_=0)] -#define _Always_impl_(expr) [__M_(__d_=0)] +#define _Success_impl_(expr) [__M_(__d_ = 0)] +#define _On_failure_impl_(expr) [__M_(__d_ = 0)] +#define _Always_impl_(expr) [__M_(__d_ = 0)] -#define _Printf_format_string_impl_ [__P_impl(__d_=0)] -#define _Scanf_format_string_impl_ [__P_impl(__d_=0)] -#define _Scanf_s_format_string_impl_ [__P_impl(__d_=0)] +#define _Printf_format_string_impl_ [__P_impl(__d_ = 0)] +#define _Scanf_format_string_impl_ [__P_impl(__d_ = 0)] +#define _Scanf_s_format_string_impl_ [__P_impl(__d_ = 0)] -#define _Raises_SEH_exception_impl_ [__M_(__d_=0)] -#define _Maybe_raises_SEH_exception_impl_ [__M_(__d_=0)] +#define _Raises_SEH_exception_impl_ [__M_(__d_ = 0)] +#define _Maybe_raises_SEH_exception_impl_ [__M_(__d_ = 0)] -#define _In_bound_impl_ [__P_impl(__d_=0)] -#define _Out_bound_impl_ [__P_impl(__d_=0)] -#define _Ret_bound_impl_ [__R_impl(__d_=0)] -#define _Deref_in_bound_impl_ [__P_impl(__d_=0)] -#define _Deref_out_bound_impl_ [__P_impl(__d_=0)] -#define _Deref_ret_bound_impl_ [__R_impl(__d_=0)] +#define _In_bound_impl_ [__P_impl(__d_ = 0)] +#define _Out_bound_impl_ [__P_impl(__d_ = 0)] +#define _Ret_bound_impl_ [__R_impl(__d_ = 0)] +#define _Deref_in_bound_impl_ [__P_impl(__d_ = 0)] +#define _Deref_out_bound_impl_ [__P_impl(__d_ = 0)] +#define _Deref_ret_bound_impl_ [__R_impl(__d_ = 0)] -#define _Range_impl_(min,max) [__P_impl(__d_=0)] -#define _In_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Out_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Ret_range_impl_(min,max) [__R_impl(__d_=0)] -#define _Deref_in_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Deref_out_range_impl_(min,max) [__P_impl(__d_=0)] -#define _Deref_ret_range_impl_(min,max) [__R_impl(__d_=0)] +#define _Range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _In_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Out_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Ret_range_impl_(min, max) [__R_impl(__d_ = 0)] +#define _Deref_in_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Deref_out_range_impl_(min, max) [__P_impl(__d_ = 0)] +#define _Deref_ret_range_impl_(min, max) [__R_impl(__d_ = 0)] -#define _Field_range_impl_(min,max) [__F_(__d_=0)] +#define _Field_range_impl_(min, max) [__F_(__d_ = 0)] -#define _Pre_satisfies_impl_(cond) [__A_(__d_=0)] -#define _Post_satisfies_impl_(cond) [__A_(__d_=0)] -#define _Satisfies_impl_(cond) [__A_(__d_=0)] +#define _Pre_satisfies_impl_(cond) [__A_(__d_ = 0)] +#define _Post_satisfies_impl_(cond) [__A_(__d_ = 0)] +#define _Satisfies_impl_(cond) [__A_(__d_ = 0)] -#define _Null_impl_ [__A_(__d_=0)] -#define _Notnull_impl_ [__A_(__d_=0)] -#define _Maybenull_impl_ [__A_(__d_=0)] +#define _Null_impl_ [__A_(__d_ = 0)] +#define _Notnull_impl_ [__A_(__d_ = 0)] +#define _Maybenull_impl_ [__A_(__d_ = 0)] -#define _Valid_impl_ [__A_(__d_=0)] -#define _Notvalid_impl_ [__A_(__d_=0)] -#define _Maybevalid_impl_ [__A_(__d_=0)] +#define _Valid_impl_ [__A_(__d_ = 0)] +#define _Notvalid_impl_ [__A_(__d_ = 0)] +#define _Maybevalid_impl_ [__A_(__d_ = 0)] -#define _Readable_bytes_impl_(size) [__A_(__d_=0)] -#define _Readable_elements_impl_(size) [__A_(__d_=0)] -#define _Writable_bytes_impl_(size) [__A_(__d_=0)] -#define _Writable_elements_impl_(size) [__A_(__d_=0)] +#define _Readable_bytes_impl_(size) [__A_(__d_ = 0)] +#define _Readable_elements_impl_(size) [__A_(__d_ = 0)] +#define _Writable_bytes_impl_(size) [__A_(__d_ = 0)] +#define _Writable_elements_impl_(size) [__A_(__d_ = 0)] -#define _Null_terminated_impl_ [__A_(__d_=0)] -#define _NullNull_terminated_impl_ [__A_(__d_=0)] +#define _Null_terminated_impl_ [__A_(__d_ = 0)] +#define _NullNull_terminated_impl_ [__A_(__d_ = 0)] -#define _Pre_impl_ [__P_impl(__d_=0)] -#define _Pre1_impl_(p1) [__P_impl(__d_=0)] -#define _Pre2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Pre3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Pre_impl_ [__P_impl(__d_ = 0)] +#define _Pre1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Pre2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Pre3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Post_impl_ [__P_impl(__d_=0)] -#define _Post1_impl_(p1) [__P_impl(__d_=0)] -#define _Post2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Post3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Post_impl_ [__P_impl(__d_ = 0)] +#define _Post1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Post2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Post3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Ret1_impl_(p1) [__R_impl(__d_=0)] -#define _Ret2_impl_(p1,p2) [__R_impl(__d_=0)] -#define _Ret3_impl_(p1,p2,p3) [__R_impl(__d_=0)] +#define _Ret1_impl_(p1) [__R_impl(__d_ = 0)] +#define _Ret2_impl_(p1, p2) [__R_impl(__d_ = 0)] +#define _Ret3_impl_(p1, p2, p3) [__R_impl(__d_ = 0)] -#define _Deref_pre1_impl_(p1) [__P_impl(__d_=0)] -#define _Deref_pre2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Deref_pre3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Deref_pre1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Deref_pre2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Deref_pre3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Deref_post1_impl_(p1) [__P_impl(__d_=0)] -#define _Deref_post2_impl_(p1,p2) [__P_impl(__d_=0)] -#define _Deref_post3_impl_(p1,p2,p3) [__P_impl(__d_=0)] +#define _Deref_post1_impl_(p1) [__P_impl(__d_ = 0)] +#define _Deref_post2_impl_(p1, p2) [__P_impl(__d_ = 0)] +#define _Deref_post3_impl_(p1, p2, p3) [__P_impl(__d_ = 0)] -#define _Deref_ret1_impl_(p1) [__R_impl(__d_=0)] -#define _Deref_ret2_impl_(p1,p2) [__R_impl(__d_=0)] -#define _Deref_ret3_impl_(p1,p2,p3) [__R_impl(__d_=0)] +#define _Deref_ret1_impl_(p1) [__R_impl(__d_ = 0)] +#define _Deref_ret2_impl_(p1, p2) [__R_impl(__d_ = 0)] +#define _Deref_ret3_impl_(p1, p2, p3) [__R_impl(__d_ = 0)] -#define _Deref2_pre1_impl_(p1) //[__P_impl(__d_=0)] -#define _Deref2_post1_impl_(p1) //[__P_impl(__d_=0)] -#define _Deref2_ret1_impl_(p1) //[__P_impl(__d_=0)] - -#else // ][ +#define _Deref2_pre1_impl_(p1) //[__P_impl(__d_=0)] +#define _Deref2_post1_impl_(p1) //[__P_impl(__d_=0)] +#define _Deref2_ret1_impl_(p1) //[__P_impl(__d_=0)] +#else // ][ #define _SAL_nop_impl_ X @@ -2087,13 +3143,13 @@ typedef struct __F_ __F_; #define _Deref_out_bound_impl_ #define _Deref_ret_bound_impl_ -#define _Range_impl_(min,max) -#define _In_range_impl_(min,max) -#define _Out_range_impl_(min,max) -#define _Ret_range_impl_(min,max) -#define _Deref_in_range_impl_(min,max) -#define _Deref_out_range_impl_(min,max) -#define _Deref_ret_range_impl_(min,max) +#define _Range_impl_(min, max) +#define _In_range_impl_(min, max) +#define _Out_range_impl_(min, max) +#define _Ret_range_impl_(min, max) +#define _Deref_in_range_impl_(min, max) +#define _Deref_out_range_impl_(min, max) +#define _Deref_ret_range_impl_(min, max) #define _Satisfies_impl_(expr) #define _Pre_satisfies_impl_(expr) @@ -2107,33 +3163,33 @@ typedef struct __F_ __F_; #define _Notvalid_impl_ #define _Maybevalid_impl_ -#define _Field_range_impl_(min,max) +#define _Field_range_impl_(min, max) #define _Pre_impl_ #define _Pre1_impl_(p1) -#define _Pre2_impl_(p1,p2) -#define _Pre3_impl_(p1,p2,p3) +#define _Pre2_impl_(p1, p2) +#define _Pre3_impl_(p1, p2, p3) #define _Post_impl_ #define _Post1_impl_(p1) -#define _Post2_impl_(p1,p2) -#define _Post3_impl_(p1,p2,p3) +#define _Post2_impl_(p1, p2) +#define _Post3_impl_(p1, p2, p3) #define _Ret1_impl_(p1) -#define _Ret2_impl_(p1,p2) -#define _Ret3_impl_(p1,p2,p3) +#define _Ret2_impl_(p1, p2) +#define _Ret3_impl_(p1, p2, p3) #define _Deref_pre1_impl_(p1) -#define _Deref_pre2_impl_(p1,p2) -#define _Deref_pre3_impl_(p1,p2,p3) +#define _Deref_pre2_impl_(p1, p2) +#define _Deref_pre3_impl_(p1, p2, p3) #define _Deref_post1_impl_(p1) -#define _Deref_post2_impl_(p1,p2) -#define _Deref_post3_impl_(p1,p2,p3) +#define _Deref_post2_impl_(p1, p2) +#define _Deref_post3_impl_(p1, p2, p3) #define _Deref_ret1_impl_(p1) -#define _Deref_ret2_impl_(p1,p2) -#define _Deref_ret3_impl_(p1,p2,p3) +#define _Deref_ret2_impl_(p1, p2) +#define _Deref_ret3_impl_(p1, p2, p3) #define _Deref2_pre1_impl_(p1) #define _Deref2_post1_impl_(p1) @@ -2151,7 +3207,7 @@ typedef struct __F_ __F_; #define __inner_typefix(ctype) #define __inner_exceptthat -#endif // ] +#endif // ] // This section contains the deprecated annotations @@ -2360,17 +3416,16 @@ typedef struct __F_ __F_; #define __specstrings -#ifdef __cplusplus // [ -#ifndef __nothrow // [ -# define __nothrow NOTHROW_DECL -#endif // ] +#ifdef __cplusplus // [ +#ifndef __nothrow // [ +#define __nothrow NOTHROW_DECL +#endif // ] extern "C" { -#else // ][ -#ifndef __nothrow // [ -# define __nothrow -#endif // ] -#endif /* #ifdef __cplusplus */ // ] - +#else // ][ +#ifndef __nothrow // [ +#define __nothrow +#endif // ] +#endif /* #ifdef __cplusplus */ // ] /* ------------------------------------------------------------------------------- @@ -2387,248 +3442,246 @@ extern "C" { are defined into nothing, and do not affect the compiled code. */ -#if !defined(__midl) && defined(_PREFAST_) // [ +#if !defined(__midl) && defined(_PREFAST_) // [ - /* - In the primitive "SAL_*" annotations "SAL" stands for Standard - Annotation Language. These "SAL_*" annotations are the - primitives the compiler understands and high-level MACROs - will decompose into these primivates. - */ +/* + In the primitive "SAL_*" annotations "SAL" stands for Standard + Annotation Language. These "SAL_*" annotations are the + primitives the compiler understands and high-level MACROs + will decompose into these primivates. +*/ - #define _SA_SPECSTRIZE( x ) #x +#define _SA_SPECSTRIZE(x) #x - /* - __notnull p - __maybenull p +/* + __notnull p + __maybenull p - Annotates a pointer p. States that pointer p is never null or maybe null. - */ + Annotates a pointer p. States that pointer p is never null or maybe null. +*/ - #define __notnull _Notnull_impl_ - #define __maybenull _Maybenull_impl_ +#define __notnull _Notnull_impl_ +#define __maybenull _Maybenull_impl_ - /* - __readonly l - __notreadonly l - __maybereadonly l +/* + __readonly l + __notreadonly l + __maybereadonly l - Annotates a location l. States that location l is not modified after - this point. If the annotation is placed on the precondition state of - a function, the restriction only applies until the postcondition state - of the function. __maybereadonly states that the annotated location - may be modified, whereas __notreadonly states that a location must be - modified. - */ + Annotates a location l. States that location l is not modified after + this point. If the annotation is placed on the precondition state of + a function, the restriction only applies until the postcondition state + of the function. __maybereadonly states that the annotated location + may be modified, whereas __notreadonly states that a location must be + modified. +*/ - #define __readonly _Pre1_impl_(__readaccess_impl) - #define __notreadonly _Pre1_impl_(__allaccess_impl) - #define __maybereadonly _Pre1_impl_(__readaccess_impl) +#define __readonly _Pre1_impl_(__readaccess_impl) +#define __notreadonly _Pre1_impl_(__allaccess_impl) +#define __maybereadonly _Pre1_impl_(__readaccess_impl) - /* - __valid v - __notvalid v - __maybevalid v +/* + __valid v + __notvalid v + __maybevalid v - Annotates any value v. States that the value satisfies all properties of - valid values of its type. For example, for a string buffer, valid means - that the buffer pointer is either NULL or points to a NULL-terminated string. - */ + Annotates any value v. States that the value satisfies all properties of + valid values of its type. For example, for a string buffer, valid means + that the buffer pointer is either NULL or points to a NULL-terminated string. +*/ - #define __valid _Valid_impl_ - #define __notvalid _Notvalid_impl_ - #define __maybevalid _Maybevalid_impl_ +#define __valid _Valid_impl_ +#define __notvalid _Notvalid_impl_ +#define __maybevalid _Maybevalid_impl_ - /* - __readableTo(extent) p +/* + __readableTo(extent) p - Annotates a buffer pointer p. If the buffer can be read, extent describes - how much of the buffer is readable. For a reader of the buffer, this is - an explicit permission to read up to that amount, rather than a restriction to - read only up to it. - */ + Annotates a buffer pointer p. If the buffer can be read, extent describes + how much of the buffer is readable. For a reader of the buffer, this is + an explicit permission to read up to that amount, rather than a restriction to + read only up to it. +*/ - #define __readableTo(extent) _SA_annotes1(SAL_readableTo, extent) +#define __readableTo(extent) _SA_annotes1(SAL_readableTo, extent) - /* +/* - __elem_readableTo(size) + __elem_readableTo(size) - Annotates a buffer pointer p as being readable to size elements. - */ + Annotates a buffer pointer p as being readable to size elements. +*/ - #define __elem_readableTo(size) _SA_annotes1(SAL_readableTo, elementCount( size )) +#define __elem_readableTo(size) _SA_annotes1(SAL_readableTo, elementCount(size)) - /* - __byte_readableTo(size) +/* + __byte_readableTo(size) - Annotates a buffer pointer p as being readable to size bytes. - */ - #define __byte_readableTo(size) _SA_annotes1(SAL_readableTo, byteCount(size)) + Annotates a buffer pointer p as being readable to size bytes. +*/ +#define __byte_readableTo(size) _SA_annotes1(SAL_readableTo, byteCount(size)) - /* - __writableTo(extent) p +/* + __writableTo(extent) p - Annotates a buffer pointer p. If the buffer can be modified, extent - describes how much of the buffer is writable (usually the allocation - size). For a writer of the buffer, this is an explicit permission to - write up to that amount, rather than a restriction to write only up to it. - */ - #define __writableTo(size) _SA_annotes1(SAL_writableTo, size) + Annotates a buffer pointer p. If the buffer can be modified, extent + describes how much of the buffer is writable (usually the allocation + size). For a writer of the buffer, this is an explicit permission to + write up to that amount, rather than a restriction to write only up to it. +*/ +#define __writableTo(size) _SA_annotes1(SAL_writableTo, size) - /* - __elem_writableTo(size) +/* + __elem_writableTo(size) - Annotates a buffer pointer p as being writable to size elements. - */ - #define __elem_writableTo(size) _SA_annotes1(SAL_writableTo, elementCount( size )) + Annotates a buffer pointer p as being writable to size elements. +*/ +#define __elem_writableTo(size) _SA_annotes1(SAL_writableTo, elementCount(size)) - /* - __byte_writableTo(size) +/* + __byte_writableTo(size) - Annotates a buffer pointer p as being writable to size bytes. - */ - #define __byte_writableTo(size) _SA_annotes1(SAL_writableTo, byteCount( size)) + Annotates a buffer pointer p as being writable to size bytes. +*/ +#define __byte_writableTo(size) _SA_annotes1(SAL_writableTo, byteCount(size)) - /* - __deref p +/* + __deref p - Annotates a pointer p. The next annotation applies one dereference down - in the type. If readableTo(p, size) then the next annotation applies to - all elements *(p+i) for which i satisfies the size. If p is a pointer - to a struct, the next annotation applies to all fields of the struct. - */ - #define __deref _Deref_impl_ + Annotates a pointer p. The next annotation applies one dereference down + in the type. If readableTo(p, size) then the next annotation applies to + all elements *(p+i) for which i satisfies the size. If p is a pointer + to a struct, the next annotation applies to all fields of the struct. +*/ +#define __deref _Deref_impl_ - /* - __pre __next_annotation +/* + __pre __next_annotation - The next annotation applies in the precondition state - */ - #define __pre _Pre_impl_ + The next annotation applies in the precondition state +*/ +#define __pre _Pre_impl_ - /* - __post __next_annotation +/* + __post __next_annotation - The next annotation applies in the postcondition state - */ - #define __post _Post_impl_ + The next annotation applies in the postcondition state +*/ +#define __post _Post_impl_ - /* - __precond() +/* + __precond() - When is true, the next annotation applies in the precondition state - (currently not enabled) - */ - #define __precond(expr) __pre + When is true, the next annotation applies in the precondition state + (currently not enabled) +*/ +#define __precond(expr) __pre - /* - __postcond() +/* + __postcond() - When is true, the next annotation applies in the postcondition state - (currently not enabled) - */ - #define __postcond(expr) __post + When is true, the next annotation applies in the postcondition state + (currently not enabled) +*/ +#define __postcond(expr) __post - /* - __exceptthat +/* + __exceptthat - Given a set of annotations Q containing __exceptthat maybeP, the effect of - the except clause is to erase any P or notP annotations (explicit or - implied) within Q at the same level of dereferencing that the except - clause appears, and to replace it with maybeP. + Given a set of annotations Q containing __exceptthat maybeP, the effect of + the except clause is to erase any P or notP annotations (explicit or + implied) within Q at the same level of dereferencing that the except + clause appears, and to replace it with maybeP. - Example 1: __valid __pre_except_maybenull on a pointer p means that the - pointer may be null, and is otherwise valid, thus overriding - the implicit notnull annotation implied by __valid on - pointers. + Example 1: __valid __pre_except_maybenull on a pointer p means that the + pointer may be null, and is otherwise valid, thus overriding + the implicit notnull annotation implied by __valid on + pointers. - Example 2: __valid __deref __pre_except_maybenull on an int **p means - that p is not null (implied by valid), but the elements - pointed to by p could be null, and are otherwise valid. - */ - #define __exceptthat __inner_exceptthat + Example 2: __valid __deref __pre_except_maybenull on an int **p means + that p is not null (implied by valid), but the elements + pointed to by p could be null, and are otherwise valid. +*/ +#define __exceptthat __inner_exceptthat - /* - _refparam +/* + _refparam - Added to all out parameter macros to indicate that they are all reference - parameters. - */ - #define __refparam _Notref_ __deref __notreadonly + Added to all out parameter macros to indicate that they are all reference + parameters. +*/ +#define __refparam _Notref_ __deref __notreadonly - /* - __inner_* +/* + __inner_* - Helper macros that directly correspond to certain high-level annotations. + Helper macros that directly correspond to certain high-level annotations. - */ +*/ - /* - Macros to classify the entrypoints and indicate their category. +/* + Macros to classify the entrypoints and indicate their category. - Pre-defined control point categories include: RPC, LPC, DeviceDriver, UserToKernel, ISAPI, COM. + Pre-defined control point categories include: RPC, LPC, DeviceDriver, UserToKernel, ISAPI, COM. - */ - #define __inner_control_entrypoint(category) _SA_annotes2(SAL_entrypoint, controlEntry, category) +*/ +#define __inner_control_entrypoint(category) _SA_annotes2(SAL_entrypoint, controlEntry, category) +/* + Pre-defined data entry point categories include: Registry, File, Network. +*/ +#define __inner_data_entrypoint(category) _SA_annotes2(SAL_entrypoint, dataEntry, category) - /* - Pre-defined data entry point categories include: Registry, File, Network. - */ - #define __inner_data_entrypoint(category) _SA_annotes2(SAL_entrypoint, dataEntry, category) +#define __inner_override _SA_annotes0(__override) +#define __inner_callback _SA_annotes0(__callback) +#define __inner_blocksOn(resource) _SA_annotes1(SAL_blocksOn, resource) - #define __inner_override _SA_annotes0(__override) - #define __inner_callback _SA_annotes0(__callback) - #define __inner_blocksOn(resource) _SA_annotes1(SAL_blocksOn, resource) +#define __post_except_maybenull __post __inner_exceptthat _Maybenull_impl_ +#define __pre_except_maybenull __pre __inner_exceptthat _Maybenull_impl_ - #define __post_except_maybenull __post __inner_exceptthat _Maybenull_impl_ - #define __pre_except_maybenull __pre __inner_exceptthat _Maybenull_impl_ +#define __post_deref_except_maybenull __post __deref __inner_exceptthat _Maybenull_impl_ +#define __pre_deref_except_maybenull __pre __deref __inner_exceptthat _Maybenull_impl_ - #define __post_deref_except_maybenull __post __deref __inner_exceptthat _Maybenull_impl_ - #define __pre_deref_except_maybenull __pre __deref __inner_exceptthat _Maybenull_impl_ +#define __inexpressible_readableTo(size) _Readable_elements_impl_(_Inexpressible_(size)) +#define __inexpressible_writableTo(size) _Writable_elements_impl_(_Inexpressible_(size)) - #define __inexpressible_readableTo(size) _Readable_elements_impl_(_Inexpressible_(size)) - #define __inexpressible_writableTo(size) _Writable_elements_impl_(_Inexpressible_(size)) +#else // ][ +#define __notnull +#define __deref +#define __maybenull +#define __readonly +#define __notreadonly +#define __maybereadonly +#define __valid +#define __notvalid +#define __maybevalid +#define __readableTo(extent) +#define __elem_readableTo(size) +#define __byte_readableTo(size) +#define __writableTo(size) +#define __elem_writableTo(size) +#define __byte_writableTo(size) +#define __pre +#define __post +#define __precond(expr) +#define __postcond(expr) +#define __exceptthat +#define __inner_override +#define __inner_callback +#define __inner_blocksOn(resource) +#define __refparam +#define __inner_control_entrypoint(category) +#define __inner_data_entrypoint(category) +#define __post_except_maybenull +#define __pre_except_maybenull +#define __post_deref_except_maybenull +#define __pre_deref_except_maybenull -#else // ][ - #define __notnull - #define __deref - #define __maybenull - #define __readonly - #define __notreadonly - #define __maybereadonly - #define __valid - #define __notvalid - #define __maybevalid - #define __readableTo(extent) - #define __elem_readableTo(size) - #define __byte_readableTo(size) - #define __writableTo(size) - #define __elem_writableTo(size) - #define __byte_writableTo(size) - #define __pre - #define __post - #define __precond(expr) - #define __postcond(expr) - #define __exceptthat - #define __inner_override - #define __inner_callback - #define __inner_blocksOn(resource) - #define __refparam - #define __inner_control_entrypoint(category) - #define __inner_data_entrypoint(category) +#define __inexpressible_readableTo(size) +#define __inexpressible_writableTo(size) - #define __post_except_maybenull - #define __pre_except_maybenull - #define __post_deref_except_maybenull - #define __pre_deref_except_maybenull - - #define __inexpressible_readableTo(size) - #define __inexpressible_writableTo(size) - -#endif /* #if !defined(__midl) && defined(_PREFAST_) */ // ] +#endif /* #if !defined(__midl) && defined(_PREFAST_) */ // ] /* ------------------------------------------------------------------------------- @@ -2640,194 +3693,441 @@ buffer, use the table in the buffer annotations section. ------------------------------------------------------------------------------- */ -#define __ecount(size) _SAL1_Source_(__ecount, (size), __notnull __elem_writableTo(size)) -#define __bcount(size) _SAL1_Source_(__bcount, (size), __notnull __byte_writableTo(size)) -#define __in_ecount(size) _SAL1_Source_(__in_ecount, (size), _In_reads_(size)) -#define __in_bcount(size) _SAL1_Source_(__in_bcount, (size), _In_reads_bytes_(size)) -#define __in_z _SAL1_Source_(__in_z, (), _In_z_) -#define __in_ecount_z(size) _SAL1_Source_(__in_ecount_z, (size), _In_reads_z_(size)) -#define __in_bcount_z(size) _SAL1_Source_(__in_bcount_z, (size), __in_bcount(size) __pre __nullterminated) -#define __in_nz _SAL1_Source_(__in_nz, (), __in) -#define __in_ecount_nz(size) _SAL1_Source_(__in_ecount_nz, (size), __in_ecount(size)) -#define __in_bcount_nz(size) _SAL1_Source_(__in_bcount_nz, (size), __in_bcount(size)) -#define __out_ecount(size) _SAL1_Source_(__out_ecount, (size), _Out_writes_(size)) -#define __out_bcount(size) _SAL1_Source_(__out_bcount, (size), _Out_writes_bytes_(size)) -#define __out_ecount_part(size,length) _SAL1_Source_(__out_ecount_part, (size,length), _Out_writes_to_(size,length)) -#define __out_bcount_part(size,length) _SAL1_Source_(__out_bcount_part, (size,length), _Out_writes_bytes_to_(size,length)) -#define __out_ecount_full(size) _SAL1_Source_(__out_ecount_full, (size), _Out_writes_all_(size)) -#define __out_bcount_full(size) _SAL1_Source_(__out_bcount_full, (size), _Out_writes_bytes_all_(size)) -#define __out_z _SAL1_Source_(__out_z, (), __post __valid __refparam __post __nullterminated) -#define __out_z_opt _SAL1_Source_(__out_z_opt, (), __post __valid __refparam __post __nullterminated __pre_except_maybenull) -#define __out_ecount_z(size) _SAL1_Source_(__out_ecount_z, (size), __ecount(size) __post __valid __refparam __post __nullterminated) -#define __out_bcount_z(size) _SAL1_Source_(__out_bcount_z, (size), __bcount(size) __post __valid __refparam __post __nullterminated) -#define __out_ecount_part_z(size,length) _SAL1_Source_(__out_ecount_part_z, (size,length), __out_ecount_part(size,length) __post __nullterminated) -#define __out_bcount_part_z(size,length) _SAL1_Source_(__out_bcount_part_z, (size,length), __out_bcount_part(size,length) __post __nullterminated) -#define __out_ecount_full_z(size) _SAL1_Source_(__out_ecount_full_z, (size), __out_ecount_full(size) __post __nullterminated) -#define __out_bcount_full_z(size) _SAL1_Source_(__out_bcount_full_z, (size), __out_bcount_full(size) __post __nullterminated) -#define __out_nz _SAL1_Source_(__out_nz, (), __post __valid __refparam) -#define __out_nz_opt _SAL1_Source_(__out_nz_opt, (), __post __valid __refparam __post_except_maybenull_) -#define __out_ecount_nz(size) _SAL1_Source_(__out_ecount_nz, (size), __ecount(size) __post __valid __refparam) -#define __out_bcount_nz(size) _SAL1_Source_(__out_bcount_nz, (size), __bcount(size) __post __valid __refparam) -#define __inout _SAL1_Source_(__inout, (), _Inout_) -#define __inout_ecount(size) _SAL1_Source_(__inout_ecount, (size), _Inout_updates_(size)) -#define __inout_bcount(size) _SAL1_Source_(__inout_bcount, (size), _Inout_updates_bytes_(size)) -#define __inout_ecount_part(size,length) _SAL1_Source_(__inout_ecount_part, (size,length), _Inout_updates_to_(size,length)) -#define __inout_bcount_part(size,length) _SAL1_Source_(__inout_bcount_part, (size,length), _Inout_updates_bytes_to_(size,length)) -#define __inout_ecount_full(size) _SAL1_Source_(__inout_ecount_full, (size), _Inout_updates_all_(size)) -#define __inout_bcount_full(size) _SAL1_Source_(__inout_bcount_full, (size), _Inout_updates_bytes_all_(size)) -#define __inout_z _SAL1_Source_(__inout_z, (), _Inout_z_) -#define __inout_ecount_z(size) _SAL1_Source_(__inout_ecount_z, (size), _Inout_updates_z_(size)) -#define __inout_bcount_z(size) _SAL1_Source_(__inout_bcount_z, (size), __inout_bcount(size) __pre __nullterminated __post __nullterminated) -#define __inout_nz _SAL1_Source_(__inout_nz, (), __inout) -#define __inout_ecount_nz(size) _SAL1_Source_(__inout_ecount_nz, (size), __inout_ecount(size)) -#define __inout_bcount_nz(size) _SAL1_Source_(__inout_bcount_nz, (size), __inout_bcount(size)) -#define __ecount_opt(size) _SAL1_Source_(__ecount_opt, (size), __ecount(size) __pre_except_maybenull) -#define __bcount_opt(size) _SAL1_Source_(__bcount_opt, (size), __bcount(size) __pre_except_maybenull) -#define __in_opt _SAL1_Source_(__in_opt, (), _In_opt_) -#define __in_ecount_opt(size) _SAL1_Source_(__in_ecount_opt, (size), _In_reads_opt_(size)) -#define __in_bcount_opt(size) _SAL1_Source_(__in_bcount_opt, (size), _In_reads_bytes_opt_(size)) -#define __in_z_opt _SAL1_Source_(__in_z_opt, (), _In_opt_z_) -#define __in_ecount_z_opt(size) _SAL1_Source_(__in_ecount_z_opt, (size), __in_ecount_opt(size) __pre __nullterminated) -#define __in_bcount_z_opt(size) _SAL1_Source_(__in_bcount_z_opt, (size), __in_bcount_opt(size) __pre __nullterminated) -#define __in_nz_opt _SAL1_Source_(__in_nz_opt, (), __in_opt) -#define __in_ecount_nz_opt(size) _SAL1_Source_(__in_ecount_nz_opt, (size), __in_ecount_opt(size)) -#define __in_bcount_nz_opt(size) _SAL1_Source_(__in_bcount_nz_opt, (size), __in_bcount_opt(size)) -#define __out_opt _SAL1_Source_(__out_opt, (), _Out_opt_) -#define __out_ecount_opt(size) _SAL1_Source_(__out_ecount_opt, (size), _Out_writes_opt_(size)) -#define __out_bcount_opt(size) _SAL1_Source_(__out_bcount_opt, (size), _Out_writes_bytes_opt_(size)) -#define __out_ecount_part_opt(size,length) _SAL1_Source_(__out_ecount_part_opt, (size,length), __out_ecount_part(size,length) __pre_except_maybenull) -#define __out_bcount_part_opt(size,length) _SAL1_Source_(__out_bcount_part_opt, (size,length), __out_bcount_part(size,length) __pre_except_maybenull) -#define __out_ecount_full_opt(size) _SAL1_Source_(__out_ecount_full_opt, (size), __out_ecount_full(size) __pre_except_maybenull) -#define __out_bcount_full_opt(size) _SAL1_Source_(__out_bcount_full_opt, (size), __out_bcount_full(size) __pre_except_maybenull) -#define __out_ecount_z_opt(size) _SAL1_Source_(__out_ecount_z_opt, (size), __out_ecount_opt(size) __post __nullterminated) -#define __out_bcount_z_opt(size) _SAL1_Source_(__out_bcount_z_opt, (size), __out_bcount_opt(size) __post __nullterminated) -#define __out_ecount_part_z_opt(size,length) _SAL1_Source_(__out_ecount_part_z_opt, (size,length), __out_ecount_part_opt(size,length) __post __nullterminated) -#define __out_bcount_part_z_opt(size,length) _SAL1_Source_(__out_bcount_part_z_opt, (size,length), __out_bcount_part_opt(size,length) __post __nullterminated) -#define __out_ecount_full_z_opt(size) _SAL1_Source_(__out_ecount_full_z_opt, (size), __out_ecount_full_opt(size) __post __nullterminated) -#define __out_bcount_full_z_opt(size) _SAL1_Source_(__out_bcount_full_z_opt, (size), __out_bcount_full_opt(size) __post __nullterminated) -#define __out_ecount_nz_opt(size) _SAL1_Source_(__out_ecount_nz_opt, (size), __out_ecount_opt(size) __post __nullterminated) -#define __out_bcount_nz_opt(size) _SAL1_Source_(__out_bcount_nz_opt, (size), __out_bcount_opt(size) __post __nullterminated) -#define __inout_opt _SAL1_Source_(__inout_opt, (), _Inout_opt_) -#define __inout_ecount_opt(size) _SAL1_Source_(__inout_ecount_opt, (size), __inout_ecount(size) __pre_except_maybenull) -#define __inout_bcount_opt(size) _SAL1_Source_(__inout_bcount_opt, (size), __inout_bcount(size) __pre_except_maybenull) -#define __inout_ecount_part_opt(size,length) _SAL1_Source_(__inout_ecount_part_opt, (size,length), __inout_ecount_part(size,length) __pre_except_maybenull) -#define __inout_bcount_part_opt(size,length) _SAL1_Source_(__inout_bcount_part_opt, (size,length), __inout_bcount_part(size,length) __pre_except_maybenull) -#define __inout_ecount_full_opt(size) _SAL1_Source_(__inout_ecount_full_opt, (size), __inout_ecount_full(size) __pre_except_maybenull) -#define __inout_bcount_full_opt(size) _SAL1_Source_(__inout_bcount_full_opt, (size), __inout_bcount_full(size) __pre_except_maybenull) -#define __inout_z_opt _SAL1_Source_(__inout_z_opt, (), __inout_opt __pre __nullterminated __post __nullterminated) -#define __inout_ecount_z_opt(size) _SAL1_Source_(__inout_ecount_z_opt, (size), __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) -#define __inout_ecount_z_opt(size) _SAL1_Source_(__inout_ecount_z_opt, (size), __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) -#define __inout_bcount_z_opt(size) _SAL1_Source_(__inout_bcount_z_opt, (size), __inout_bcount_opt(size)) -#define __inout_nz_opt _SAL1_Source_(__inout_nz_opt, (), __inout_opt) -#define __inout_ecount_nz_opt(size) _SAL1_Source_(__inout_ecount_nz_opt, (size), __inout_ecount_opt(size)) -#define __inout_bcount_nz_opt(size) _SAL1_Source_(__inout_bcount_nz_opt, (size), __inout_bcount_opt(size)) -#define __deref_ecount(size) _SAL1_Source_(__deref_ecount, (size), _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) __post _Notref_ __deref _Notref_ __notnull __post __deref __elem_writableTo(size)) -#define __deref_bcount(size) _SAL1_Source_(__deref_bcount, (size), _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) __post _Notref_ __deref _Notref_ __notnull __post __deref __byte_writableTo(size)) -#define __deref_out _SAL1_Source_(__deref_out, (), _Outptr_) -#define __deref_out_ecount(size) _SAL1_Source_(__deref_out_ecount, (size), _Outptr_result_buffer_(size)) -#define __deref_out_bcount(size) _SAL1_Source_(__deref_out_bcount, (size), _Outptr_result_bytebuffer_(size)) -#define __deref_out_ecount_part(size,length) _SAL1_Source_(__deref_out_ecount_part, (size,length), _Outptr_result_buffer_to_(size,length)) -#define __deref_out_bcount_part(size,length) _SAL1_Source_(__deref_out_bcount_part, (size,length), _Outptr_result_bytebuffer_to_(size,length)) -#define __deref_out_ecount_full(size) _SAL1_Source_(__deref_out_ecount_full, (size), __deref_out_ecount_part(size,size)) -#define __deref_out_bcount_full(size) _SAL1_Source_(__deref_out_bcount_full, (size), __deref_out_bcount_part(size,size)) -#define __deref_out_z _SAL1_Source_(__deref_out_z, (), _Outptr_result_z_) -#define __deref_out_ecount_z(size) _SAL1_Source_(__deref_out_ecount_z, (size), __deref_out_ecount(size) __post __deref __nullterminated) -#define __deref_out_bcount_z(size) _SAL1_Source_(__deref_out_bcount_z, (size), __deref_out_bcount(size) __post __deref __nullterminated) -#define __deref_out_nz _SAL1_Source_(__deref_out_nz, (), __deref_out) -#define __deref_out_ecount_nz(size) _SAL1_Source_(__deref_out_ecount_nz, (size), __deref_out_ecount(size)) -#define __deref_out_bcount_nz(size) _SAL1_Source_(__deref_out_bcount_nz, (size), __deref_out_ecount(size)) -#define __deref_inout _SAL1_Source_(__deref_inout, (), _Notref_ __notnull _Notref_ __elem_readableTo(1) __pre __deref __valid __post _Notref_ __deref __valid __refparam) -#define __deref_inout_z _SAL1_Source_(__deref_inout_z, (), __deref_inout __pre __deref __nullterminated __post _Notref_ __deref __nullterminated) -#define __deref_inout_ecount(size) _SAL1_Source_(__deref_inout_ecount, (size), __deref_inout __pre __deref __elem_writableTo(size) __post _Notref_ __deref __elem_writableTo(size)) -#define __deref_inout_bcount(size) _SAL1_Source_(__deref_inout_bcount, (size), __deref_inout __pre __deref __byte_writableTo(size) __post _Notref_ __deref __byte_writableTo(size)) -#define __deref_inout_ecount_part(size,length) _SAL1_Source_(__deref_inout_ecount_part, (size,length), __deref_inout_ecount(size) __pre __deref __elem_readableTo(length) __post __deref __elem_readableTo(length)) -#define __deref_inout_bcount_part(size,length) _SAL1_Source_(__deref_inout_bcount_part, (size,length), __deref_inout_bcount(size) __pre __deref __byte_readableTo(length) __post __deref __byte_readableTo(length)) -#define __deref_inout_ecount_full(size) _SAL1_Source_(__deref_inout_ecount_full, (size), __deref_inout_ecount_part(size,size)) -#define __deref_inout_bcount_full(size) _SAL1_Source_(__deref_inout_bcount_full, (size), __deref_inout_bcount_part(size,size)) -#define __deref_inout_ecount_z(size) _SAL1_Source_(__deref_inout_ecount_z, (size), __deref_inout_ecount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_bcount_z(size) _SAL1_Source_(__deref_inout_bcount_z, (size), __deref_inout_bcount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_nz _SAL1_Source_(__deref_inout_nz, (), __deref_inout) -#define __deref_inout_ecount_nz(size) _SAL1_Source_(__deref_inout_ecount_nz, (size), __deref_inout_ecount(size)) -#define __deref_inout_bcount_nz(size) _SAL1_Source_(__deref_inout_bcount_nz, (size), __deref_inout_ecount(size)) -#define __deref_ecount_opt(size) _SAL1_Source_(__deref_ecount_opt, (size), __deref_ecount(size) __post_deref_except_maybenull) -#define __deref_bcount_opt(size) _SAL1_Source_(__deref_bcount_opt, (size), __deref_bcount(size) __post_deref_except_maybenull) -#define __deref_out_opt _SAL1_Source_(__deref_out_opt, (), __deref_out __post_deref_except_maybenull) -#define __deref_out_ecount_opt(size) _SAL1_Source_(__deref_out_ecount_opt, (size), __deref_out_ecount(size) __post_deref_except_maybenull) -#define __deref_out_bcount_opt(size) _SAL1_Source_(__deref_out_bcount_opt, (size), __deref_out_bcount(size) __post_deref_except_maybenull) -#define __deref_out_ecount_part_opt(size,length) _SAL1_Source_(__deref_out_ecount_part_opt, (size,length), __deref_out_ecount_part(size,length) __post_deref_except_maybenull) -#define __deref_out_bcount_part_opt(size,length) _SAL1_Source_(__deref_out_bcount_part_opt, (size,length), __deref_out_bcount_part(size,length) __post_deref_except_maybenull) -#define __deref_out_ecount_full_opt(size) _SAL1_Source_(__deref_out_ecount_full_opt, (size), __deref_out_ecount_full(size) __post_deref_except_maybenull) -#define __deref_out_bcount_full_opt(size) _SAL1_Source_(__deref_out_bcount_full_opt, (size), __deref_out_bcount_full(size) __post_deref_except_maybenull) -#define __deref_out_z_opt _SAL1_Source_(__deref_out_z_opt, (), _Outptr_result_maybenull_z_) -#define __deref_out_ecount_z_opt(size) _SAL1_Source_(__deref_out_ecount_z_opt, (size), __deref_out_ecount_opt(size) __post __deref __nullterminated) -#define __deref_out_bcount_z_opt(size) _SAL1_Source_(__deref_out_bcount_z_opt, (size), __deref_out_bcount_opt(size) __post __deref __nullterminated) -#define __deref_out_nz_opt _SAL1_Source_(__deref_out_nz_opt, (), __deref_out_opt) -#define __deref_out_ecount_nz_opt(size) _SAL1_Source_(__deref_out_ecount_nz_opt, (size), __deref_out_ecount_opt(size)) -#define __deref_out_bcount_nz_opt(size) _SAL1_Source_(__deref_out_bcount_nz_opt, (size), __deref_out_bcount_opt(size)) -#define __deref_inout_opt _SAL1_Source_(__deref_inout_opt, (), __deref_inout __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_ecount_opt(size) _SAL1_Source_(__deref_inout_ecount_opt, (size), __deref_inout_ecount(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_bcount_opt(size) _SAL1_Source_(__deref_inout_bcount_opt, (size), __deref_inout_bcount(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_ecount_part_opt(size,length) _SAL1_Source_(__deref_inout_ecount_part_opt, (size,length), __deref_inout_ecount_part(size,length) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_bcount_part_opt(size,length) _SAL1_Source_(__deref_inout_bcount_part_opt, (size,length), __deref_inout_bcount_part(size,length) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_ecount_full_opt(size) _SAL1_Source_(__deref_inout_ecount_full_opt, (size), __deref_inout_ecount_full(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_bcount_full_opt(size) _SAL1_Source_(__deref_inout_bcount_full_opt, (size), __deref_inout_bcount_full(size) __pre_deref_except_maybenull __post_deref_except_maybenull) -#define __deref_inout_z_opt _SAL1_Source_(__deref_inout_z_opt, (), __deref_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_ecount_z_opt(size) _SAL1_Source_(__deref_inout_ecount_z_opt, (size), __deref_inout_ecount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_bcount_z_opt(size) _SAL1_Source_(__deref_inout_bcount_z_opt, (size), __deref_inout_bcount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_inout_nz_opt _SAL1_Source_(__deref_inout_nz_opt, (), __deref_inout_opt) -#define __deref_inout_ecount_nz_opt(size) _SAL1_Source_(__deref_inout_ecount_nz_opt, (size), __deref_inout_ecount_opt(size)) -#define __deref_inout_bcount_nz_opt(size) _SAL1_Source_(__deref_inout_bcount_nz_opt, (size), __deref_inout_bcount_opt(size)) -#define __deref_opt_ecount(size) _SAL1_Source_(__deref_opt_ecount, (size), __deref_ecount(size) __pre_except_maybenull) -#define __deref_opt_bcount(size) _SAL1_Source_(__deref_opt_bcount, (size), __deref_bcount(size) __pre_except_maybenull) -#define __deref_opt_out _SAL1_Source_(__deref_opt_out, (), _Outptr_opt_) -#define __deref_opt_out_z _SAL1_Source_(__deref_opt_out_z, (), _Outptr_opt_result_z_) -#define __deref_opt_out_ecount(size) _SAL1_Source_(__deref_opt_out_ecount, (size), __deref_out_ecount(size) __pre_except_maybenull) -#define __deref_opt_out_bcount(size) _SAL1_Source_(__deref_opt_out_bcount, (size), __deref_out_bcount(size) __pre_except_maybenull) -#define __deref_opt_out_ecount_part(size,length) _SAL1_Source_(__deref_opt_out_ecount_part, (size,length), __deref_out_ecount_part(size,length) __pre_except_maybenull) -#define __deref_opt_out_bcount_part(size,length) _SAL1_Source_(__deref_opt_out_bcount_part, (size,length), __deref_out_bcount_part(size,length) __pre_except_maybenull) -#define __deref_opt_out_ecount_full(size) _SAL1_Source_(__deref_opt_out_ecount_full, (size), __deref_out_ecount_full(size) __pre_except_maybenull) -#define __deref_opt_out_bcount_full(size) _SAL1_Source_(__deref_opt_out_bcount_full, (size), __deref_out_bcount_full(size) __pre_except_maybenull) -#define __deref_opt_inout _SAL1_Source_(__deref_opt_inout, (), _Inout_opt_) -#define __deref_opt_inout_ecount(size) _SAL1_Source_(__deref_opt_inout_ecount, (size), __deref_inout_ecount(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount(size) _SAL1_Source_(__deref_opt_inout_bcount, (size), __deref_inout_bcount(size) __pre_except_maybenull) -#define __deref_opt_inout_ecount_part(size,length) _SAL1_Source_(__deref_opt_inout_ecount_part, (size,length), __deref_inout_ecount_part(size,length) __pre_except_maybenull) -#define __deref_opt_inout_bcount_part(size,length) _SAL1_Source_(__deref_opt_inout_bcount_part, (size,length), __deref_inout_bcount_part(size,length) __pre_except_maybenull) -#define __deref_opt_inout_ecount_full(size) _SAL1_Source_(__deref_opt_inout_ecount_full, (size), __deref_inout_ecount_full(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount_full(size) _SAL1_Source_(__deref_opt_inout_bcount_full, (size), __deref_inout_bcount_full(size) __pre_except_maybenull) -#define __deref_opt_inout_z _SAL1_Source_(__deref_opt_inout_z, (), __deref_opt_inout __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_ecount_z(size) _SAL1_Source_(__deref_opt_inout_ecount_z, (size), __deref_opt_inout_ecount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_bcount_z(size) _SAL1_Source_(__deref_opt_inout_bcount_z, (size), __deref_opt_inout_bcount(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_nz _SAL1_Source_(__deref_opt_inout_nz, (), __deref_opt_inout) -#define __deref_opt_inout_ecount_nz(size) _SAL1_Source_(__deref_opt_inout_ecount_nz, (size), __deref_opt_inout_ecount(size)) -#define __deref_opt_inout_bcount_nz(size) _SAL1_Source_(__deref_opt_inout_bcount_nz, (size), __deref_opt_inout_bcount(size)) -#define __deref_opt_ecount_opt(size) _SAL1_Source_(__deref_opt_ecount_opt, (size), __deref_ecount_opt(size) __pre_except_maybenull) -#define __deref_opt_bcount_opt(size) _SAL1_Source_(__deref_opt_bcount_opt, (size), __deref_bcount_opt(size) __pre_except_maybenull) -#define __deref_opt_out_opt _SAL1_Source_(__deref_opt_out_opt, (), _Outptr_opt_result_maybenull_) -#define __deref_opt_out_ecount_opt(size) _SAL1_Source_(__deref_opt_out_ecount_opt, (size), __deref_out_ecount_opt(size) __pre_except_maybenull) -#define __deref_opt_out_bcount_opt(size) _SAL1_Source_(__deref_opt_out_bcount_opt, (size), __deref_out_bcount_opt(size) __pre_except_maybenull) -#define __deref_opt_out_ecount_part_opt(size,length) _SAL1_Source_(__deref_opt_out_ecount_part_opt, (size,length), __deref_out_ecount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_out_bcount_part_opt(size,length) _SAL1_Source_(__deref_opt_out_bcount_part_opt, (size,length), __deref_out_bcount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_out_ecount_full_opt(size) _SAL1_Source_(__deref_opt_out_ecount_full_opt, (size), __deref_out_ecount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_out_bcount_full_opt(size) _SAL1_Source_(__deref_opt_out_bcount_full_opt, (size), __deref_out_bcount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_out_z_opt _SAL1_Source_(__deref_opt_out_z_opt, (), __post __deref __valid __refparam __pre_except_maybenull __pre_deref_except_maybenull __post_deref_except_maybenull __post __deref __nullterminated) -#define __deref_opt_out_ecount_z_opt(size) _SAL1_Source_(__deref_opt_out_ecount_z_opt, (size), __deref_opt_out_ecount_opt(size) __post __deref __nullterminated) -#define __deref_opt_out_bcount_z_opt(size) _SAL1_Source_(__deref_opt_out_bcount_z_opt, (size), __deref_opt_out_bcount_opt(size) __post __deref __nullterminated) -#define __deref_opt_out_nz_opt _SAL1_Source_(__deref_opt_out_nz_opt, (), __deref_opt_out_opt) -#define __deref_opt_out_ecount_nz_opt(size) _SAL1_Source_(__deref_opt_out_ecount_nz_opt, (size), __deref_opt_out_ecount_opt(size)) -#define __deref_opt_out_bcount_nz_opt(size) _SAL1_Source_(__deref_opt_out_bcount_nz_opt, (size), __deref_opt_out_bcount_opt(size)) -#define __deref_opt_inout_opt _SAL1_Source_(__deref_opt_inout_opt, (), __deref_inout_opt __pre_except_maybenull) -#define __deref_opt_inout_ecount_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_opt, (size), __deref_inout_ecount_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_opt, (size), __deref_inout_bcount_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_ecount_part_opt(size,length) _SAL1_Source_(__deref_opt_inout_ecount_part_opt, (size,length), __deref_inout_ecount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_inout_bcount_part_opt(size,length) _SAL1_Source_(__deref_opt_inout_bcount_part_opt, (size,length), __deref_inout_bcount_part_opt(size,length) __pre_except_maybenull) -#define __deref_opt_inout_ecount_full_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_full_opt, (size), __deref_inout_ecount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_bcount_full_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_full_opt, (size), __deref_inout_bcount_full_opt(size) __pre_except_maybenull) -#define __deref_opt_inout_z_opt _SAL1_Source_(__deref_opt_inout_z_opt, (), __deref_opt_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_ecount_z_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_z_opt, (size), __deref_opt_inout_ecount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_bcount_z_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_z_opt, (size), __deref_opt_inout_bcount_opt(size) __pre __deref __nullterminated __post __deref __nullterminated) -#define __deref_opt_inout_nz_opt _SAL1_Source_(__deref_opt_inout_nz_opt, (), __deref_opt_inout_opt) -#define __deref_opt_inout_ecount_nz_opt(size) _SAL1_Source_(__deref_opt_inout_ecount_nz_opt, (size), __deref_opt_inout_ecount_opt(size)) -#define __deref_opt_inout_bcount_nz_opt(size) _SAL1_Source_(__deref_opt_inout_bcount_nz_opt, (size), __deref_opt_inout_bcount_opt(size)) +#define __ecount(size) _SAL1_Source_(__ecount, (size), __notnull __elem_writableTo(size)) +#define __bcount(size) _SAL1_Source_(__bcount, (size), __notnull __byte_writableTo(size)) +#define __in_ecount(size) _SAL1_Source_(__in_ecount, (size), _In_reads_(size)) +#define __in_bcount(size) _SAL1_Source_(__in_bcount, (size), _In_reads_bytes_(size)) +#define __in_z _SAL1_Source_(__in_z, (), _In_z_) +#define __in_ecount_z(size) _SAL1_Source_(__in_ecount_z, (size), _In_reads_z_(size)) +#define __in_bcount_z(size) \ + _SAL1_Source_(__in_bcount_z, (size), __in_bcount(size) __pre __nullterminated) +#define __in_nz _SAL1_Source_(__in_nz, (), __in) +#define __in_ecount_nz(size) _SAL1_Source_(__in_ecount_nz, (size), __in_ecount(size)) +#define __in_bcount_nz(size) _SAL1_Source_(__in_bcount_nz, (size), __in_bcount(size)) +#define __out_ecount(size) _SAL1_Source_(__out_ecount, (size), _Out_writes_(size)) +#define __out_bcount(size) _SAL1_Source_(__out_bcount, (size), _Out_writes_bytes_(size)) +#define __out_ecount_part(size, length) \ + _SAL1_Source_(__out_ecount_part, (size, length), _Out_writes_to_(size, length)) +#define __out_bcount_part(size, length) \ + _SAL1_Source_(__out_bcount_part, (size, length), _Out_writes_bytes_to_(size, length)) +#define __out_ecount_full(size) _SAL1_Source_(__out_ecount_full, (size), _Out_writes_all_(size)) +#define __out_bcount_full(size) \ + _SAL1_Source_(__out_bcount_full, (size), _Out_writes_bytes_all_(size)) +#define __out_z _SAL1_Source_(__out_z, (), __post __valid __refparam __post __nullterminated) +#define __out_z_opt \ + _SAL1_Source_(__out_z_opt, (), \ + __post __valid __refparam __post __nullterminated __pre_except_maybenull) +#define __out_ecount_z(size) \ + _SAL1_Source_(__out_ecount_z, (size), \ + __ecount(size) __post __valid __refparam __post __nullterminated) +#define __out_bcount_z(size) \ + _SAL1_Source_(__out_bcount_z, (size), \ + __bcount(size) __post __valid __refparam __post __nullterminated) +#define __out_ecount_part_z(size, length) \ + _SAL1_Source_(__out_ecount_part_z, (size, length), \ + __out_ecount_part(size, length) __post __nullterminated) +#define __out_bcount_part_z(size, length) \ + _SAL1_Source_(__out_bcount_part_z, (size, length), \ + __out_bcount_part(size, length) __post __nullterminated) +#define __out_ecount_full_z(size) \ + _SAL1_Source_(__out_ecount_full_z, (size), __out_ecount_full(size) __post __nullterminated) +#define __out_bcount_full_z(size) \ + _SAL1_Source_(__out_bcount_full_z, (size), __out_bcount_full(size) __post __nullterminated) +#define __out_nz _SAL1_Source_(__out_nz, (), __post __valid __refparam) +#define __out_nz_opt \ + _SAL1_Source_(__out_nz_opt, (), __post __valid __refparam __post_except_maybenull_) +#define __out_ecount_nz(size) \ + _SAL1_Source_(__out_ecount_nz, (size), __ecount(size) __post __valid __refparam) +#define __out_bcount_nz(size) \ + _SAL1_Source_(__out_bcount_nz, (size), __bcount(size) __post __valid __refparam) +#define __inout _SAL1_Source_(__inout, (), _Inout_) +#define __inout_ecount(size) _SAL1_Source_(__inout_ecount, (size), _Inout_updates_(size)) +#define __inout_bcount(size) _SAL1_Source_(__inout_bcount, (size), _Inout_updates_bytes_(size)) +#define __inout_ecount_part(size, length) \ + _SAL1_Source_(__inout_ecount_part, (size, length), _Inout_updates_to_(size, length)) +#define __inout_bcount_part(size, length) \ + _SAL1_Source_(__inout_bcount_part, (size, length), _Inout_updates_bytes_to_(size, length)) +#define __inout_ecount_full(size) \ + _SAL1_Source_(__inout_ecount_full, (size), _Inout_updates_all_(size)) +#define __inout_bcount_full(size) \ + _SAL1_Source_(__inout_bcount_full, (size), _Inout_updates_bytes_all_(size)) +#define __inout_z _SAL1_Source_(__inout_z, (), _Inout_z_) +#define __inout_ecount_z(size) _SAL1_Source_(__inout_ecount_z, (size), _Inout_updates_z_(size)) +#define __inout_bcount_z(size) \ + _SAL1_Source_(__inout_bcount_z, (size), \ + __inout_bcount(size) __pre __nullterminated __post __nullterminated) +#define __inout_nz _SAL1_Source_(__inout_nz, (), __inout) +#define __inout_ecount_nz(size) _SAL1_Source_(__inout_ecount_nz, (size), __inout_ecount(size)) +#define __inout_bcount_nz(size) _SAL1_Source_(__inout_bcount_nz, (size), __inout_bcount(size)) +#define __ecount_opt(size) \ + _SAL1_Source_(__ecount_opt, (size), __ecount(size) __pre_except_maybenull) +#define __bcount_opt(size) \ + _SAL1_Source_(__bcount_opt, (size), __bcount(size) __pre_except_maybenull) +#define __in_opt _SAL1_Source_(__in_opt, (), _In_opt_) +#define __in_ecount_opt(size) _SAL1_Source_(__in_ecount_opt, (size), _In_reads_opt_(size)) +#define __in_bcount_opt(size) _SAL1_Source_(__in_bcount_opt, (size), _In_reads_bytes_opt_(size)) +#define __in_z_opt _SAL1_Source_(__in_z_opt, (), _In_opt_z_) +#define __in_ecount_z_opt(size) \ + _SAL1_Source_(__in_ecount_z_opt, (size), __in_ecount_opt(size) __pre __nullterminated) +#define __in_bcount_z_opt(size) \ + _SAL1_Source_(__in_bcount_z_opt, (size), __in_bcount_opt(size) __pre __nullterminated) +#define __in_nz_opt _SAL1_Source_(__in_nz_opt, (), __in_opt) +#define __in_ecount_nz_opt(size) _SAL1_Source_(__in_ecount_nz_opt, (size), __in_ecount_opt(size)) +#define __in_bcount_nz_opt(size) _SAL1_Source_(__in_bcount_nz_opt, (size), __in_bcount_opt(size)) +#define __out_opt _SAL1_Source_(__out_opt, (), _Out_opt_) +#define __out_ecount_opt(size) _SAL1_Source_(__out_ecount_opt, (size), _Out_writes_opt_(size)) +#define __out_bcount_opt(size) _SAL1_Source_(__out_bcount_opt, (size), _Out_writes_bytes_opt_(size)) +#define __out_ecount_part_opt(size, length) \ + _SAL1_Source_(__out_ecount_part_opt, (size, length), \ + __out_ecount_part(size, length) __pre_except_maybenull) +#define __out_bcount_part_opt(size, length) \ + _SAL1_Source_(__out_bcount_part_opt, (size, length), \ + __out_bcount_part(size, length) __pre_except_maybenull) +#define __out_ecount_full_opt(size) \ + _SAL1_Source_(__out_ecount_full_opt, (size), __out_ecount_full(size) __pre_except_maybenull) +#define __out_bcount_full_opt(size) \ + _SAL1_Source_(__out_bcount_full_opt, (size), __out_bcount_full(size) __pre_except_maybenull) +#define __out_ecount_z_opt(size) \ + _SAL1_Source_(__out_ecount_z_opt, (size), __out_ecount_opt(size) __post __nullterminated) +#define __out_bcount_z_opt(size) \ + _SAL1_Source_(__out_bcount_z_opt, (size), __out_bcount_opt(size) __post __nullterminated) +#define __out_ecount_part_z_opt(size, length) \ + _SAL1_Source_(__out_ecount_part_z_opt, (size, length), \ + __out_ecount_part_opt(size, length) __post __nullterminated) +#define __out_bcount_part_z_opt(size, length) \ + _SAL1_Source_(__out_bcount_part_z_opt, (size, length), \ + __out_bcount_part_opt(size, length) __post __nullterminated) +#define __out_ecount_full_z_opt(size) \ + _SAL1_Source_(__out_ecount_full_z_opt, (size), \ + __out_ecount_full_opt(size) __post __nullterminated) +#define __out_bcount_full_z_opt(size) \ + _SAL1_Source_(__out_bcount_full_z_opt, (size), \ + __out_bcount_full_opt(size) __post __nullterminated) +#define __out_ecount_nz_opt(size) \ + _SAL1_Source_(__out_ecount_nz_opt, (size), __out_ecount_opt(size) __post __nullterminated) +#define __out_bcount_nz_opt(size) \ + _SAL1_Source_(__out_bcount_nz_opt, (size), __out_bcount_opt(size) __post __nullterminated) +#define __inout_opt _SAL1_Source_(__inout_opt, (), _Inout_opt_) +#define __inout_ecount_opt(size) \ + _SAL1_Source_(__inout_ecount_opt, (size), __inout_ecount(size) __pre_except_maybenull) +#define __inout_bcount_opt(size) \ + _SAL1_Source_(__inout_bcount_opt, (size), __inout_bcount(size) __pre_except_maybenull) +#define __inout_ecount_part_opt(size, length) \ + _SAL1_Source_(__inout_ecount_part_opt, (size, length), \ + __inout_ecount_part(size, length) __pre_except_maybenull) +#define __inout_bcount_part_opt(size, length) \ + _SAL1_Source_(__inout_bcount_part_opt, (size, length), \ + __inout_bcount_part(size, length) __pre_except_maybenull) +#define __inout_ecount_full_opt(size) \ + _SAL1_Source_(__inout_ecount_full_opt, (size), __inout_ecount_full(size) __pre_except_maybenull) +#define __inout_bcount_full_opt(size) \ + _SAL1_Source_(__inout_bcount_full_opt, (size), __inout_bcount_full(size) __pre_except_maybenull) +#define __inout_z_opt \ + _SAL1_Source_(__inout_z_opt, (), __inout_opt __pre __nullterminated __post __nullterminated) +#define __inout_ecount_z_opt(size) \ + _SAL1_Source_(__inout_ecount_z_opt, (size), \ + __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) +#define __inout_ecount_z_opt(size) \ + _SAL1_Source_(__inout_ecount_z_opt, (size), \ + __inout_ecount_opt(size) __pre __nullterminated __post __nullterminated) +#define __inout_bcount_z_opt(size) \ + _SAL1_Source_(__inout_bcount_z_opt, (size), __inout_bcount_opt(size)) +#define __inout_nz_opt _SAL1_Source_(__inout_nz_opt, (), __inout_opt) +#define __inout_ecount_nz_opt(size) \ + _SAL1_Source_(__inout_ecount_nz_opt, (size), __inout_ecount_opt(size)) +#define __inout_bcount_nz_opt(size) \ + _SAL1_Source_(__inout_bcount_nz_opt, (size), __inout_bcount_opt(size)) +#define __deref_ecount(size) \ + _SAL1_Source_( \ + __deref_ecount, (size), \ + _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) \ + __post _Notref_ __deref _Notref_ __notnull __post __deref __elem_writableTo(size)) +#define __deref_bcount(size) \ + _SAL1_Source_( \ + __deref_bcount, (size), \ + _Notref_ __ecount(1) __post _Notref_ __elem_readableTo(1) \ + __post _Notref_ __deref _Notref_ __notnull __post __deref __byte_writableTo(size)) +#define __deref_out _SAL1_Source_(__deref_out, (), _Outptr_) +#define __deref_out_ecount(size) \ + _SAL1_Source_(__deref_out_ecount, (size), _Outptr_result_buffer_(size)) +#define __deref_out_bcount(size) \ + _SAL1_Source_(__deref_out_bcount, (size), _Outptr_result_bytebuffer_(size)) +#define __deref_out_ecount_part(size, length) \ + _SAL1_Source_(__deref_out_ecount_part, (size, length), _Outptr_result_buffer_to_(size, length)) +#define __deref_out_bcount_part(size, length) \ + _SAL1_Source_(__deref_out_bcount_part, (size, length), \ + _Outptr_result_bytebuffer_to_(size, length)) +#define __deref_out_ecount_full(size) \ + _SAL1_Source_(__deref_out_ecount_full, (size), __deref_out_ecount_part(size, size)) +#define __deref_out_bcount_full(size) \ + _SAL1_Source_(__deref_out_bcount_full, (size), __deref_out_bcount_part(size, size)) +#define __deref_out_z _SAL1_Source_(__deref_out_z, (), _Outptr_result_z_) +#define __deref_out_ecount_z(size) \ + _SAL1_Source_(__deref_out_ecount_z, (size), \ + __deref_out_ecount(size) __post __deref __nullterminated) +#define __deref_out_bcount_z(size) \ + _SAL1_Source_(__deref_out_bcount_z, (size), \ + __deref_out_bcount(size) __post __deref __nullterminated) +#define __deref_out_nz _SAL1_Source_(__deref_out_nz, (), __deref_out) +#define __deref_out_ecount_nz(size) \ + _SAL1_Source_(__deref_out_ecount_nz, (size), __deref_out_ecount(size)) +#define __deref_out_bcount_nz(size) \ + _SAL1_Source_(__deref_out_bcount_nz, (size), __deref_out_ecount(size)) +#define __deref_inout \ + _SAL1_Source_(__deref_inout, (), \ + _Notref_ __notnull _Notref_ __elem_readableTo(1) \ + __pre __deref __valid __post _Notref_ __deref __valid __refparam) +#define __deref_inout_z \ + _SAL1_Source_( \ + __deref_inout_z, (), \ + __deref_inout __pre __deref __nullterminated __post _Notref_ __deref __nullterminated) +#define __deref_inout_ecount(size) \ + _SAL1_Source_(__deref_inout_ecount, (size), \ + __deref_inout __pre __deref __elem_writableTo(size) \ + __post _Notref_ __deref __elem_writableTo(size)) +#define __deref_inout_bcount(size) \ + _SAL1_Source_(__deref_inout_bcount, (size), \ + __deref_inout __pre __deref __byte_writableTo(size) \ + __post _Notref_ __deref __byte_writableTo(size)) +#define __deref_inout_ecount_part(size, length) \ + _SAL1_Source_(__deref_inout_ecount_part, (size, length), \ + __deref_inout_ecount(size) __pre __deref __elem_readableTo(length) \ + __post __deref __elem_readableTo(length)) +#define __deref_inout_bcount_part(size, length) \ + _SAL1_Source_(__deref_inout_bcount_part, (size, length), \ + __deref_inout_bcount(size) __pre __deref __byte_readableTo(length) \ + __post __deref __byte_readableTo(length)) +#define __deref_inout_ecount_full(size) \ + _SAL1_Source_(__deref_inout_ecount_full, (size), __deref_inout_ecount_part(size, size)) +#define __deref_inout_bcount_full(size) \ + _SAL1_Source_(__deref_inout_bcount_full, (size), __deref_inout_bcount_part(size, size)) +#define __deref_inout_ecount_z(size) \ + _SAL1_Source_(__deref_inout_ecount_z, (size), \ + __deref_inout_ecount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_bcount_z(size) \ + _SAL1_Source_(__deref_inout_bcount_z, (size), \ + __deref_inout_bcount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_nz _SAL1_Source_(__deref_inout_nz, (), __deref_inout) +#define __deref_inout_ecount_nz(size) \ + _SAL1_Source_(__deref_inout_ecount_nz, (size), __deref_inout_ecount(size)) +#define __deref_inout_bcount_nz(size) \ + _SAL1_Source_(__deref_inout_bcount_nz, (size), __deref_inout_ecount(size)) +#define __deref_ecount_opt(size) \ + _SAL1_Source_(__deref_ecount_opt, (size), __deref_ecount(size) __post_deref_except_maybenull) +#define __deref_bcount_opt(size) \ + _SAL1_Source_(__deref_bcount_opt, (size), __deref_bcount(size) __post_deref_except_maybenull) +#define __deref_out_opt \ + _SAL1_Source_(__deref_out_opt, (), __deref_out __post_deref_except_maybenull) +#define __deref_out_ecount_opt(size) \ + _SAL1_Source_(__deref_out_ecount_opt, (size), \ + __deref_out_ecount(size) __post_deref_except_maybenull) +#define __deref_out_bcount_opt(size) \ + _SAL1_Source_(__deref_out_bcount_opt, (size), \ + __deref_out_bcount(size) __post_deref_except_maybenull) +#define __deref_out_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_out_ecount_part_opt, (size, length), \ + __deref_out_ecount_part(size, length) __post_deref_except_maybenull) +#define __deref_out_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_out_bcount_part_opt, (size, length), \ + __deref_out_bcount_part(size, length) __post_deref_except_maybenull) +#define __deref_out_ecount_full_opt(size) \ + _SAL1_Source_(__deref_out_ecount_full_opt, (size), \ + __deref_out_ecount_full(size) __post_deref_except_maybenull) +#define __deref_out_bcount_full_opt(size) \ + _SAL1_Source_(__deref_out_bcount_full_opt, (size), \ + __deref_out_bcount_full(size) __post_deref_except_maybenull) +#define __deref_out_z_opt _SAL1_Source_(__deref_out_z_opt, (), _Outptr_result_maybenull_z_) +#define __deref_out_ecount_z_opt(size) \ + _SAL1_Source_(__deref_out_ecount_z_opt, (size), \ + __deref_out_ecount_opt(size) __post __deref __nullterminated) +#define __deref_out_bcount_z_opt(size) \ + _SAL1_Source_(__deref_out_bcount_z_opt, (size), \ + __deref_out_bcount_opt(size) __post __deref __nullterminated) +#define __deref_out_nz_opt _SAL1_Source_(__deref_out_nz_opt, (), __deref_out_opt) +#define __deref_out_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_out_ecount_nz_opt, (size), __deref_out_ecount_opt(size)) +#define __deref_out_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_out_bcount_nz_opt, (size), __deref_out_bcount_opt(size)) +#define __deref_inout_opt \ + _SAL1_Source_(__deref_inout_opt, (), \ + __deref_inout __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_ecount_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_opt, (size), \ + __deref_inout_ecount(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_bcount_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_opt, (size), \ + __deref_inout_bcount(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_inout_ecount_part_opt, (size, length), \ + __deref_inout_ecount_part(size, length) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_inout_bcount_part_opt, (size, length), \ + __deref_inout_bcount_part(size, length) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_ecount_full_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_full_opt, (size), \ + __deref_inout_ecount_full(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_bcount_full_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_full_opt, (size), \ + __deref_inout_bcount_full(size) \ + __pre_deref_except_maybenull __post_deref_except_maybenull) +#define __deref_inout_z_opt \ + _SAL1_Source_( \ + __deref_inout_z_opt, (), \ + __deref_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_ecount_z_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_z_opt, (size), \ + __deref_inout_ecount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_bcount_z_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_z_opt, (size), \ + __deref_inout_bcount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_inout_nz_opt _SAL1_Source_(__deref_inout_nz_opt, (), __deref_inout_opt) +#define __deref_inout_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_inout_ecount_nz_opt, (size), __deref_inout_ecount_opt(size)) +#define __deref_inout_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_inout_bcount_nz_opt, (size), __deref_inout_bcount_opt(size)) +#define __deref_opt_ecount(size) \ + _SAL1_Source_(__deref_opt_ecount, (size), __deref_ecount(size) __pre_except_maybenull) +#define __deref_opt_bcount(size) \ + _SAL1_Source_(__deref_opt_bcount, (size), __deref_bcount(size) __pre_except_maybenull) +#define __deref_opt_out _SAL1_Source_(__deref_opt_out, (), _Outptr_opt_) +#define __deref_opt_out_z _SAL1_Source_(__deref_opt_out_z, (), _Outptr_opt_result_z_) +#define __deref_opt_out_ecount(size) \ + _SAL1_Source_(__deref_opt_out_ecount, (size), __deref_out_ecount(size) __pre_except_maybenull) +#define __deref_opt_out_bcount(size) \ + _SAL1_Source_(__deref_opt_out_bcount, (size), __deref_out_bcount(size) __pre_except_maybenull) +#define __deref_opt_out_ecount_part(size, length) \ + _SAL1_Source_(__deref_opt_out_ecount_part, (size, length), \ + __deref_out_ecount_part(size, length) __pre_except_maybenull) +#define __deref_opt_out_bcount_part(size, length) \ + _SAL1_Source_(__deref_opt_out_bcount_part, (size, length), \ + __deref_out_bcount_part(size, length) __pre_except_maybenull) +#define __deref_opt_out_ecount_full(size) \ + _SAL1_Source_(__deref_opt_out_ecount_full, (size), \ + __deref_out_ecount_full(size) __pre_except_maybenull) +#define __deref_opt_out_bcount_full(size) \ + _SAL1_Source_(__deref_opt_out_bcount_full, (size), \ + __deref_out_bcount_full(size) __pre_except_maybenull) +#define __deref_opt_inout _SAL1_Source_(__deref_opt_inout, (), _Inout_opt_) +#define __deref_opt_inout_ecount(size) \ + _SAL1_Source_(__deref_opt_inout_ecount, (size), \ + __deref_inout_ecount(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount(size) \ + _SAL1_Source_(__deref_opt_inout_bcount, (size), \ + __deref_inout_bcount(size) __pre_except_maybenull) +#define __deref_opt_inout_ecount_part(size, length) \ + _SAL1_Source_(__deref_opt_inout_ecount_part, (size, length), \ + __deref_inout_ecount_part(size, length) __pre_except_maybenull) +#define __deref_opt_inout_bcount_part(size, length) \ + _SAL1_Source_(__deref_opt_inout_bcount_part, (size, length), \ + __deref_inout_bcount_part(size, length) __pre_except_maybenull) +#define __deref_opt_inout_ecount_full(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_full, (size), \ + __deref_inout_ecount_full(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount_full(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_full, (size), \ + __deref_inout_bcount_full(size) __pre_except_maybenull) +#define __deref_opt_inout_z \ + _SAL1_Source_( \ + __deref_opt_inout_z, (), \ + __deref_opt_inout __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_ecount_z(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_z, (size), \ + __deref_opt_inout_ecount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_bcount_z(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_z, (size), \ + __deref_opt_inout_bcount(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_nz _SAL1_Source_(__deref_opt_inout_nz, (), __deref_opt_inout) +#define __deref_opt_inout_ecount_nz(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_nz, (size), __deref_opt_inout_ecount(size)) +#define __deref_opt_inout_bcount_nz(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_nz, (size), __deref_opt_inout_bcount(size)) +#define __deref_opt_ecount_opt(size) \ + _SAL1_Source_(__deref_opt_ecount_opt, (size), __deref_ecount_opt(size) __pre_except_maybenull) +#define __deref_opt_bcount_opt(size) \ + _SAL1_Source_(__deref_opt_bcount_opt, (size), __deref_bcount_opt(size) __pre_except_maybenull) +#define __deref_opt_out_opt _SAL1_Source_(__deref_opt_out_opt, (), _Outptr_opt_result_maybenull_) +#define __deref_opt_out_ecount_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_opt, (size), \ + __deref_out_ecount_opt(size) __pre_except_maybenull) +#define __deref_opt_out_bcount_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_opt, (size), \ + __deref_out_bcount_opt(size) __pre_except_maybenull) +#define __deref_opt_out_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_out_ecount_part_opt, (size, length), \ + __deref_out_ecount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_out_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_out_bcount_part_opt, (size, length), \ + __deref_out_bcount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_out_ecount_full_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_full_opt, (size), \ + __deref_out_ecount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_out_bcount_full_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_full_opt, (size), \ + __deref_out_bcount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_out_z_opt \ + _SAL1_Source_( \ + __deref_opt_out_z_opt, (), \ + __post __deref __valid __refparam __pre_except_maybenull __pre_deref_except_maybenull \ + __post_deref_except_maybenull __post __deref __nullterminated) +#define __deref_opt_out_ecount_z_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_z_opt, (size), \ + __deref_opt_out_ecount_opt(size) __post __deref __nullterminated) +#define __deref_opt_out_bcount_z_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_z_opt, (size), \ + __deref_opt_out_bcount_opt(size) __post __deref __nullterminated) +#define __deref_opt_out_nz_opt _SAL1_Source_(__deref_opt_out_nz_opt, (), __deref_opt_out_opt) +#define __deref_opt_out_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_out_ecount_nz_opt, (size), __deref_opt_out_ecount_opt(size)) +#define __deref_opt_out_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_out_bcount_nz_opt, (size), __deref_opt_out_bcount_opt(size)) +#define __deref_opt_inout_opt \ + _SAL1_Source_(__deref_opt_inout_opt, (), __deref_inout_opt __pre_except_maybenull) +#define __deref_opt_inout_ecount_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_opt, (size), \ + __deref_inout_ecount_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_opt, (size), \ + __deref_inout_bcount_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_ecount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_inout_ecount_part_opt, (size, length), \ + __deref_inout_ecount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_inout_bcount_part_opt(size, length) \ + _SAL1_Source_(__deref_opt_inout_bcount_part_opt, (size, length), \ + __deref_inout_bcount_part_opt(size, length) __pre_except_maybenull) +#define __deref_opt_inout_ecount_full_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_full_opt, (size), \ + __deref_inout_ecount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_bcount_full_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_full_opt, (size), \ + __deref_inout_bcount_full_opt(size) __pre_except_maybenull) +#define __deref_opt_inout_z_opt \ + _SAL1_Source_( \ + __deref_opt_inout_z_opt, (), \ + __deref_opt_inout_opt __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_ecount_z_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_z_opt, (size), \ + __deref_opt_inout_ecount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_bcount_z_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_z_opt, (size), \ + __deref_opt_inout_bcount_opt(size) \ + __pre __deref __nullterminated __post __deref __nullterminated) +#define __deref_opt_inout_nz_opt _SAL1_Source_(__deref_opt_inout_nz_opt, (), __deref_opt_inout_opt) +#define __deref_opt_inout_ecount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_inout_ecount_nz_opt, (size), __deref_opt_inout_ecount_opt(size)) +#define __deref_opt_inout_bcount_nz_opt(size) \ + _SAL1_Source_(__deref_opt_inout_bcount_nz_opt, (size), __deref_opt_inout_bcount_opt(size)) /* ------------------------------------------------------------------------------- @@ -2839,59 +4139,58 @@ of each annotation, see the advanced annotations section. ------------------------------------------------------------------------------- */ -#define __success(expr) _Success_(expr) -#define __nullterminated _Null_terminated_ +#define __success(expr) _Success_(expr) +#define __nullterminated _Null_terminated_ #define __nullnullterminated -#define __clr_reserved _SAL1_Source_(__reserved, (), _Reserved_) -#define __checkReturn _SAL1_Source_(__checkReturn, (), _Check_return_) -#define __typefix(ctype) _SAL1_Source_(__typefix, (ctype), __inner_typefix(ctype)) -#define __override __inner_override -#define __callback __inner_callback -#define __format_string _Printf_format_string_ -#define __blocksOn(resource) __inner_blocksOn(resource) -#define __control_entrypoint(category) __inner_control_entrypoint(category) -#define __data_entrypoint(category) __inner_data_entrypoint(category) -#define __useHeader _Use_decl_anno_impl_ -#define __on_failure(annotes) _On_failure_impl_(annotes _SAL_nop_impl_) +#define __clr_reserved _SAL1_Source_(__reserved, (), _Reserved_) +#define __checkReturn _SAL1_Source_(__checkReturn, (), _Check_return_) +#define __typefix(ctype) _SAL1_Source_(__typefix, (ctype), __inner_typefix(ctype)) +#define __override __inner_override +#define __callback __inner_callback +#define __format_string _Printf_format_string_ +#define __blocksOn(resource) __inner_blocksOn(resource) +#define __control_entrypoint(category) __inner_control_entrypoint(category) +#define __data_entrypoint(category) __inner_data_entrypoint(category) +#define __useHeader _Use_decl_anno_impl_ +#define __on_failure(annotes) _On_failure_impl_(annotes _SAL_nop_impl_) #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) (0) #endif -#ifndef __fallthrough // [ +#ifndef __fallthrough // [ #if __has_cpp_attribute(fallthrough) #define __fallthrough [[fallthrough]] #else #define __fallthrough #endif -#endif // ] +#endif // ] -#ifndef __analysis_assume // [ -#ifdef _PREFAST_ // [ +#ifndef __analysis_assume // [ +#ifdef _PREFAST_ // [ #define __analysis_assume(expr) __assume(expr) -#else // ][ +#else // ][ #define __analysis_assume(expr) -#endif // ] -#endif // ] +#endif // ] +#endif // ] -#ifndef _Analysis_assume_ // [ -#ifdef _PREFAST_ // [ +#ifndef _Analysis_assume_ // [ +#ifdef _PREFAST_ // [ #define _Analysis_assume_(expr) __assume(expr) -#else // ][ +#else // ][ #define _Analysis_assume_(expr) -#endif // ] -#endif // ] +#endif // ] +#endif // ] -#define _Analysis_noreturn_ _SAL2_Source_(_Analysis_noreturn_, (), _SA_annotes0(SAL_terminates)) +#define _Analysis_noreturn_ _SAL2_Source_(_Analysis_noreturn_, (), _SA_annotes0(SAL_terminates)) -#ifdef _PREFAST_ // [ -__inline __nothrow -void __AnalysisAssumeNullterminated(_Post_ __nullterminated void *p); +#ifdef _PREFAST_ // [ +__inline __nothrow void __AnalysisAssumeNullterminated(_Post_ __nullterminated void *p); #define _Analysis_assume_nullterminated_(x) __AnalysisAssumeNullterminated(x) -#else // ][ +#else // ][ #define _Analysis_assume_nullterminated_(x) -#endif // ] +#endif // ] // // Set the analysis mode (global flags to analysis). @@ -2900,7 +4199,7 @@ void __AnalysisAssumeNullterminated(_Post_ __nullterminated void *p); // // Synthesize a unique symbol. -#define ___MKID(x, y) x ## y +#define ___MKID(x, y) x##y #define __MKID(x, y) ___MKID(x, y) #define __GENSYM(x) __MKID(x, __COUNTER__) @@ -2908,9 +4207,8 @@ __ANNOTATION(SAL_analysisMode(__AuToQuOtE __In_impl_ char *mode);) #define _Analysis_mode_impl_(mode) _SA_annotes1(SAL_analysisMode, #mode) -#define _Analysis_mode_(mode) \ - typedef _Analysis_mode_impl_(mode) int \ - __GENSYM(__prefast_analysis_mode_flag); +#define _Analysis_mode_(mode) \ + typedef _Analysis_mode_impl_(mode) int __GENSYM(__prefast_analysis_mode_flag); // The following are predefined: // _Analysis_operator_new_throw_ (operator new throws) @@ -2919,23 +4217,23 @@ __ANNOTATION(SAL_analysisMode(__AuToQuOtE __In_impl_ char *mode);) // // Function class annotations. -__ANNOTATION(SAL_functionClassNew(__In_impl_ char*);) -__PRIMOP(int, _In_function_class_(__In_impl_ char*);) -#define _In_function_class_(x) _In_function_class_(#x) +__ANNOTATION(SAL_functionClassNew(__In_impl_ char *);) +__PRIMOP(int, _In_function_class_(__In_impl_ char *);) +#define _In_function_class_(x) _In_function_class_(#x) -#define _Function_class_(x) _SA_annotes1(SAL_functionClassNew, #x) +#define _Function_class_(x) _SA_annotes1(SAL_functionClassNew, #x) /* * interlocked operand used in interlocked instructions */ -//#define _Interlocked_operand_ _Pre_ _SA_annotes0(SAL_interlocked) +// #define _Interlocked_operand_ _Pre_ _SA_annotes0(SAL_interlocked) -#define _Enum_is_bitflag_ _SA_annotes0(SAL_enumIsBitflag) -#define _Strict_type_match_ _SA_annotes0(SAL_strictType2) +#define _Enum_is_bitflag_ _SA_annotes0(SAL_enumIsBitflag) +#define _Strict_type_match_ _SA_annotes0(SAL_strictType2) -#define _Maybe_raises_SEH_exception_ _Pre_ _SA_annotes1(SAL_inTry,__yes) -#define _Raises_SEH_exception_ _Group_(_Maybe_raises_SEH_exception_ _Analysis_noreturn_) +#define _Maybe_raises_SEH_exception_ _Pre_ _SA_annotes1(SAL_inTry, __yes) +#define _Raises_SEH_exception_ _Group_(_Maybe_raises_SEH_exception_ _Analysis_noreturn_) -#ifdef __cplusplus // [ +#ifdef __cplusplus // [ } -#endif // ] \ No newline at end of file +#endif // ] \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h b/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h index efa4a9c6b..8e66424cc 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h @@ -32,4 +32,4 @@ #include "xbox_stubs.h" #include "iggy_stubs.h" -#endif // STUBS_H \ No newline at end of file +#endif // STUBS_H \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h index 52edb5625..7d6175c6c 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/d3d11_stubs.h @@ -8,12 +8,11 @@ using namespace DirectX; -typedef struct _RECT -{ - LONG left; - LONG top; - LONG right; - LONG bottom; +typedef struct _RECT { + LONG left; + LONG top; + LONG right; + LONG bottom; } RECT, *PRECT; // stole- i mean borrowed from OrbisStubs.h @@ -27,45 +26,42 @@ typedef void ID3D11Buffer; // typedef DWORD (*PTHREAD_START_ROUTINE)( LPVOID lpThreadParameter); // typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; -// Used only by windows/durango gdraw and UIController. Will be unnecessary once we have our own -// UIController stubs. +// Used only by windows/durango gdraw and UIController. Will be unnecessary once +// we have our own UIController stubs. typedef void ID3D11ShaderResourceView; typedef void ID3D11Resource; typedef void ID3D11Texture2D; typedef void D3D11_TEXTURE2D_DESC; -enum D3D11_BLEND -{ - D3D11_BLEND_ZERO = 1, - D3D11_BLEND_ONE = 2, - D3D11_BLEND_SRC_COLOR = 3, - D3D11_BLEND_INV_SRC_COLOR = 4, - D3D11_BLEND_SRC_ALPHA = 5, - D3D11_BLEND_INV_SRC_ALPHA = 6, - D3D11_BLEND_DEST_ALPHA = 7, - D3D11_BLEND_INV_DEST_ALPHA = 8, - D3D11_BLEND_DEST_COLOR = 9, - D3D11_BLEND_INV_DEST_COLOR = 10, - D3D11_BLEND_SRC_ALPHA_SAT = 11, - D3D11_BLEND_BLEND_FACTOR = 14, - D3D11_BLEND_INV_BLEND_FACTOR = 15, - D3D11_BLEND_SRC1_COLOR = 16, - D3D11_BLEND_INV_SRC1_COLOR = 17, - D3D11_BLEND_SRC1_ALPHA = 18, - D3D11_BLEND_INV_SRC1_ALPHA = 19 +enum D3D11_BLEND { + D3D11_BLEND_ZERO = 1, + D3D11_BLEND_ONE = 2, + D3D11_BLEND_SRC_COLOR = 3, + D3D11_BLEND_INV_SRC_COLOR = 4, + D3D11_BLEND_SRC_ALPHA = 5, + D3D11_BLEND_INV_SRC_ALPHA = 6, + D3D11_BLEND_DEST_ALPHA = 7, + D3D11_BLEND_INV_DEST_ALPHA = 8, + D3D11_BLEND_DEST_COLOR = 9, + D3D11_BLEND_INV_DEST_COLOR = 10, + D3D11_BLEND_SRC_ALPHA_SAT = 11, + D3D11_BLEND_BLEND_FACTOR = 14, + D3D11_BLEND_INV_BLEND_FACTOR = 15, + D3D11_BLEND_SRC1_COLOR = 16, + D3D11_BLEND_INV_SRC1_COLOR = 17, + D3D11_BLEND_SRC1_ALPHA = 18, + D3D11_BLEND_INV_SRC1_ALPHA = 19 }; - -enum D3D11_COMPARISON_FUNC -{ - D3D11_COMPARISON_NEVER = 1, - D3D11_COMPARISON_LESS = 2, - D3D11_COMPARISON_EQUAL = 3, - D3D11_COMPARISON_LESS_EQUAL = 4, - D3D11_COMPARISON_GREATER = 5, - D3D11_COMPARISON_NOT_EQUAL = 6, - D3D11_COMPARISON_GREATER_EQUAL = 7, - D3D11_COMPARISON_ALWAYS = 8 +enum D3D11_COMPARISON_FUNC { + D3D11_COMPARISON_NEVER = 1, + D3D11_COMPARISON_LESS = 2, + D3D11_COMPARISON_EQUAL = 3, + D3D11_COMPARISON_LESS_EQUAL = 4, + D3D11_COMPARISON_GREATER = 5, + D3D11_COMPARISON_NOT_EQUAL = 6, + D3D11_COMPARISON_GREATER_EQUAL = 7, + D3D11_COMPARISON_ALWAYS = 8 }; -#endif // D3D11STUBS_H \ No newline at end of file +#endif // D3D11STUBS_H \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h index 220dbe7fa..97e1cd80a 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/iggy_stubs.h @@ -3,225 +3,258 @@ #pragma once - #include "../../Windows64/Iggy/include/iggy.h" -#define STUBBED {} +#define STUBBED \ + { \ + } -RADEXPFUNC inline IggyValuePath * RADEXPLINK IggyPlayerRootPath(Iggy *f) { - STUBBED; - return nullptr; +RADEXPFUNC inline IggyValuePath* RADEXPLINK IggyPlayerRootPath(Iggy* f) { + STUBBED; + return nullptr; } -RADEXPFUNC inline IggyResult RADEXPLINK IggyPlayerCallMethodRS(Iggy *f, IggyDataValue *result, IggyValuePath *target, IggyName methodname, S32 numargs, IggyDataValue *args) { - STUBBED; - return IGGY_RESULT_SUCCESS; +RADEXPFUNC inline IggyResult RADEXPLINK +IggyPlayerCallMethodRS(Iggy* f, IggyDataValue* result, IggyValuePath* target, + IggyName methodname, S32 numargs, IggyDataValue* args) { + STUBBED; + return IGGY_RESULT_SUCCESS; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDestroy(Iggy *player) { - STUBBED; -} -RADEXPFUNC inline void RADEXPLINK IggyPlayerSetDisplaySize(Iggy *f, S32 w, S32 h) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyPlayerDestroy(Iggy* player) { STUBBED; } +RADEXPFUNC inline void RADEXPLINK IggyPlayerSetDisplaySize(Iggy* f, S32 w, + S32 h) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesStart(Iggy *f) { - STUBBED; -} +RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesStart(Iggy* f) { STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTile(Iggy *f, S32 x0, S32 y0, S32 x1, S32 y1, S32 padding) { - STUBBED; -} -RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesEnd(Iggy *f) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTile(Iggy* f, S32 x0, S32 y0, + S32 x1, S32 y1, + S32 padding) { + STUBBED; } +RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesEnd(Iggy* f) { STUBBED; } // Each fake Iggy player gets its own state block struct FakeIggyPlayer { - int tickCount; - bool needsTick; - IggyProperties props; - void *userdata; + int tickCount; + bool needsTick; + IggyProperties props; + void* userdata; }; -// Simple player pool +// Simple player pool static FakeIggyPlayer s_fakePlayers[64]; static int s_fakePlayerCount = 0; -RADEXPFUNC inline Iggy * RADEXPLINK IggyPlayerCreateFromMemory( - void const * data, - U32 data_size_in_bytes, - IggyPlayerConfig *config) { - if(s_fakePlayerCount >= 64) return nullptr; - FakeIggyPlayer *fp = &s_fakePlayers[s_fakePlayerCount++]; - fp->tickCount = 0; - fp->needsTick = true; - fp->userdata = nullptr; - // Default to 1920x1080 at 30fps - memset(&fp->props, 0, sizeof(fp->props)); - fp->props.movie_width_in_pixels = 1920; - fp->props.movie_height_in_pixels = 1080; - fp->props.movie_frame_rate_from_file_in_fps = 30.0f; - fp->props.movie_frame_rate_current_in_fps = 30.0f; - fprintf(stderr, "[Iggy Stub] Created fake player %d (data=%p, size=%u)\n", s_fakePlayerCount-1, data, data_size_in_bytes); - return (Iggy*)fp; +RADEXPFUNC inline Iggy* RADEXPLINK IggyPlayerCreateFromMemory( + void const* data, U32 data_size_in_bytes, IggyPlayerConfig* config) { + if (s_fakePlayerCount >= 64) return nullptr; + FakeIggyPlayer* fp = &s_fakePlayers[s_fakePlayerCount++]; + fp->tickCount = 0; + fp->needsTick = true; + fp->userdata = nullptr; + // Default to 1920x1080 at 30fps + memset(&fp->props, 0, sizeof(fp->props)); + fp->props.movie_width_in_pixels = 1920; + fp->props.movie_height_in_pixels = 1080; + fp->props.movie_frame_rate_from_file_in_fps = 30.0f; + fp->props.movie_frame_rate_current_in_fps = 30.0f; + fprintf(stderr, "[Iggy Stub] Created fake player %d (data=%p, size=%u)\n", + s_fakePlayerCount - 1, data, data_size_in_bytes); + return (Iggy*)fp; } -static FakeIggyPlayer* getFakePlayer(Iggy *player) { - return (FakeIggyPlayer*)player; +static FakeIggyPlayer* getFakePlayer(Iggy* player) { + return (FakeIggyPlayer*)player; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerInitializeAndTickRS(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) { fp->tickCount = 0; fp->needsTick = true; } +RADEXPFUNC inline void RADEXPLINK IggyPlayerInitializeAndTickRS(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) { + fp->tickCount = 0; + fp->needsTick = true; + } } -RADEXPFUNC inline IggyProperties * RADEXPLINK IggyPlayerProperties(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) return &fp->props; - static IggyProperties defaultProps = {}; - return &defaultProps; +RADEXPFUNC inline IggyProperties* RADEXPLINK +IggyPlayerProperties(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) return &fp->props; + static IggyProperties defaultProps = {}; + return &defaultProps; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerSetUserdata(Iggy *player, void *userdata) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) fp->userdata = userdata; +RADEXPFUNC inline void RADEXPLINK IggyPlayerSetUserdata(Iggy* player, + void* userdata) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) fp->userdata = userdata; } -RADEXPFUNC inline IggyName RADEXPLINK IggyPlayerCreateFastName(Iggy *f, IggyUTF16 const *name, S32 len) { - STUBBED; - return 0; +RADEXPFUNC inline IggyName RADEXPLINK +IggyPlayerCreateFastName(Iggy* f, IggyUTF16 const* name, S32 len) { + STUBBED; + return 0; } -RADEXPFUNC inline rrbool RADEXPLINK IggyDebugGetMemoryUseInfo(Iggy *player, IggyLibrary lib, char const *category_string, S32 category_stringlen, S32 iteration, IggyMemoryUseInfo *data) { - STUBBED; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyDebugGetMemoryUseInfo( + Iggy* player, IggyLibrary lib, char const* category_string, + S32 category_stringlen, S32 iteration, IggyMemoryUseInfo* data) { + STUBBED; + return false; } -RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerReadyToTick(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp && fp->needsTick) return true; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerReadyToTick(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp && fp->needsTick) return true; + return false; } -RADEXPFUNC inline void RADEXPLINK IggyPlayerTickRS(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) { - fp->tickCount++; - // Allow one tick per frame cycle - fp->needsTick = false; - } +RADEXPFUNC inline void RADEXPLINK IggyPlayerTickRS(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) { + fp->tickCount++; + // Allow one tick per frame cycle + fp->needsTick = false; + } } -RADEXPFUNC inline void RADEXPLINK IggyPlayerDraw(Iggy *f) { - // Re-arm tick for next frame - FakeIggyPlayer *fp = getFakePlayer(f); - if(fp) fp->needsTick = true; +RADEXPFUNC inline void RADEXPLINK IggyPlayerDraw(Iggy* f) { + // Re-arm tick for next frame + FakeIggyPlayer* fp = getFakePlayer(f); + if (fp) fp->needsTick = true; } -RADEXPFUNC inline void RADEXPLINK IggyMakeEventKey(IggyEvent *event, IggyKeyevent event_type, IggyKeycode keycode, IggyKeyloc keyloc) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyMakeEventKey(IggyEvent* event, + IggyKeyevent event_type, + IggyKeycode keycode, + IggyKeyloc keyloc) { + STUBBED; } -RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerDispatchEventRS(Iggy *player, IggyEvent *event, IggyEventResult *result) { - STUBBED; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerDispatchEventRS( + Iggy* player, IggyEvent* event, IggyEventResult* result) { + STUBBED; + return false; } -RADEXPFUNC inline void RADEXPLINK IggyFontRemoveUTF8(const char *fontname, S32 namelen_in_bytes, U32 fontflags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontRemoveUTF8(const char* fontname, + S32 namelen_in_bytes, + U32 fontflags) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyFontInstallBitmapUTF8(const IggyBitmapFontProvider *bmf, const char *fontname, S32 namelen_in_bytes, U32 fontflags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontInstallBitmapUTF8( + const IggyBitmapFontProvider* bmf, const char* fontname, + S32 namelen_in_bytes, U32 fontflags) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyFontSetIndirectUTF8(const char *request_name, S32 request_namelen, U32 request_flags, const char *result_name, S32 result_namelen, U32 result_flags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontSetIndirectUTF8( + const char* request_name, S32 request_namelen, U32 request_flags, + const char* result_name, S32 result_namelen, U32 result_flags) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeUTF8(const void *truetype_storage, S32 ttc_index, const char *fontname, S32 namelen_in_bytes, U32 fontflags) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeUTF8( + const void* truetype_storage, S32 ttc_index, const char* fontname, + S32 namelen_in_bytes, U32 fontflags) { + STUBBED; } -RADEXPFUNC inline rrbool RADEXPLINK IggyValuePathMakeNameRef(IggyValuePath *result, IggyValuePath *parent, char const *text_utf8) { - STUBBED; - return false; +RADEXPFUNC inline rrbool RADEXPLINK IggyValuePathMakeNameRef( + IggyValuePath* result, IggyValuePath* parent, char const* text_utf8) { + STUBBED; + return false; } -RADEXPFUNC inline IggyResult RADEXPLINK IggyValueGetBooleanRS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, rrbool *result) { - STUBBED; - return IGGY_RESULT_SUCCESS; +RADEXPFUNC inline IggyResult RADEXPLINK +IggyValueGetBooleanRS(IggyValuePath* var, IggyName sub_name, + char const* sub_name_utf8, rrbool* result) { + STUBBED; + return IGGY_RESULT_SUCCESS; } -RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF8(const char *fontname, S32 len, U32 fontflags, S32 fallback_codepoint) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF8( + const char* fontname, S32 len, U32 fontflags, S32 fallback_codepoint) { + STUBBED; } -RADEXPFUNC inline IggyResult RADEXPLINK IggyValueGetF64RS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, F64 *result) { - STUBBED; - return IGGY_RESULT_SUCCESS; +RADEXPFUNC inline IggyResult RADEXPLINK +IggyValueGetF64RS(IggyValuePath* var, IggyName sub_name, + char const* sub_name_utf8, F64* result) { + STUBBED; + return IGGY_RESULT_SUCCESS; } -RADEXPFUNC inline rrbool RADEXPLINK IggyValueSetBooleanRS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, rrbool value) { - STUBBED; - return true; +RADEXPFUNC inline rrbool RADEXPLINK +IggyValueSetBooleanRS(IggyValuePath* var, IggyName sub_name, + char const* sub_name_utf8, rrbool value) { + STUBBED; + return true; } -RADEXPFUNC inline void RADEXPLINK IggyInit(IggyAllocator *allocator) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyInit(IggyAllocator* allocator) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetWarningCallback(Iggy_WarningFunction *error, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK +IggySetWarningCallback(Iggy_WarningFunction* error, void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetTraceCallbackUTF8(Iggy_TraceFunctionUTF8 *trace_utf8, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetTraceCallbackUTF8( + Iggy_TraceFunctionUTF8* trace_utf8, void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetFontCachingCalculationBuffer( - S32 max_chars, - void *optional_temp_buffer, - S32 optional_temp_buffer_size_in_bytes) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK +IggySetFontCachingCalculationBuffer(S32 max_chars, void* optional_temp_buffer, + S32 optional_temp_buffer_size_in_bytes) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetCustomDrawCallback(Iggy_CustomDrawCallback *custom_draw, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetCustomDrawCallback( + Iggy_CustomDrawCallback* custom_draw, void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetAS3ExternalFunctionCallbackUTF16(Iggy_AS3ExternalFunctionUTF16 *as3_external_function_utf16, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetAS3ExternalFunctionCallbackUTF16( + Iggy_AS3ExternalFunctionUTF16* as3_external_function_utf16, + void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggyMakeEventMouseMove(IggyEvent *event, S32 x, S32 y) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyMakeEventMouseMove(IggyEvent* event, + S32 x, S32 y) { + STUBBED; } -RADEXPFUNC inline void RADEXPLINK IggySetTextureSubstitutionCallbacks(Iggy_TextureSubstitutionCreateCallback *texture_create, Iggy_TextureSubstitutionDestroyCallback *texture_destroy, void *user_callback_data) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggySetTextureSubstitutionCallbacks( + Iggy_TextureSubstitutionCreateCallback* texture_create, + Iggy_TextureSubstitutionDestroyCallback* texture_destroy, + void* user_callback_data) { + STUBBED; } -RADEXPFUNC inline void * RADEXPLINK IggyPlayerGetUserdata(Iggy *player) { - FakeIggyPlayer *fp = getFakePlayer(player); - if(fp) return fp->userdata; - return 0; +RADEXPFUNC inline void* RADEXPLINK IggyPlayerGetUserdata(Iggy* player) { + FakeIggyPlayer* fp = getFakePlayer(player); + if (fp) return fp->userdata; + return 0; } -RADEXPFUNC inline IggyLibrary RADEXPLINK IggyLibraryCreateFromMemoryUTF16( - IggyUTF16 const * url_utf16_null_terminated, - void const * data, - U32 data_size_in_bytes, - IggyPlayerConfig *config) { - STUBBED; - return 0; +RADEXPFUNC inline IggyLibrary RADEXPLINK IggyLibraryCreateFromMemoryUTF16( + IggyUTF16 const* url_utf16_null_terminated, void const* data, + U32 data_size_in_bytes, IggyPlayerConfig* config) { + STUBBED; + return 0; } RADEXPFUNC inline void RADEXPLINK IggyLibraryDestroy(IggyLibrary lib) { - STUBBED; + STUBBED; } // Iggy is fake -static GDrawFunctions *s_iggy_gdraw_funcs = 0; -RADEXPFUNC inline void RADEXPLINK IggySetGDraw(GDrawFunctions *gdraw_funcs) { - s_iggy_gdraw_funcs = gdraw_funcs; +static GDrawFunctions* s_iggy_gdraw_funcs = 0; +RADEXPFUNC inline void RADEXPLINK IggySetGDraw(GDrawFunctions* gdraw_funcs) { + s_iggy_gdraw_funcs = gdraw_funcs; } // Audio stubs -RADEXPFUNC inline void RADEXPLINK IggyAudioUseDefault(void) { - STUBBED; -} +RADEXPFUNC inline void RADEXPLINK IggyAudioUseDefault(void) { STUBBED; } // Explorer/Perfmon, shit implmentation -RADEXPFUNC inline void * RADEXPLINK IggyExpCreate(const char *host, int port, void *storage, int storage_size) { - STUBBED; - return 0; +RADEXPFUNC inline void* RADEXPLINK IggyExpCreate(const char* host, int port, + void* storage, + int storage_size) { + STUBBED; + return 0; } -RADEXPFUNC inline void RADEXPLINK IggyUseExplorer(Iggy *player, void *explorer) { - STUBBED; +RADEXPFUNC inline void RADEXPLINK IggyUseExplorer(Iggy* player, + void* explorer) { + STUBBED; } -RADEXPFUNC inline void * RADEXPLINK IggyPerfmonCreate(void *(*alloc_func)(unsigned long), void (*free_func)(void *), void *user) { - STUBBED; - return 0; -} -RADEXPFUNC inline void RADEXPLINK IggyInstallPerfmon(void *perfmon) { - STUBBED; +RADEXPFUNC inline void* RADEXPLINK IggyPerfmonCreate( + void* (*alloc_func)(unsigned long), void (*free_func)(void*), void* user) { + STUBBED; + return 0; } +RADEXPFUNC inline void RADEXPLINK IggyInstallPerfmon(void* perfmon) { STUBBED; } // GDraw memory/warning functions are defined in gdraw_glfw.c (C linkage) -// Juicey you stupid idiot do NOT define them here +// Juicey you stupid idiot do NOT define them here -#endif // IGGYSTUBS_H \ No newline at end of file +#endif // IGGYSTUBS_H \ No newline at end of file diff --git a/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h index 7fc8f0891..452562fad 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/winapi_stubs.h @@ -9,7 +9,7 @@ #define TRUE true #define FALSE false -#define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length)) +#define RtlZeroMemory(Destination, Length) memset((Destination), 0, (Length)) #define ZeroMemory RtlZeroMemory #define WINAPI @@ -18,10 +18,10 @@ #define S_OK 0 typedef unsigned int DWORD; -typedef const char *LPCSTR; +typedef const char* LPCSTR; typedef bool BOOL; -typedef BOOL *PBOOL; -typedef BOOL *LPBOOL; +typedef BOOL* PBOOL; +typedef BOOL* LPBOOL; typedef void* LPVOID; typedef wchar_t WCHAR; typedef unsigned char BYTE; @@ -60,7 +60,7 @@ typedef struct { typedef long long LONGLONG; typedef size_t SIZE_T; typedef WCHAR *LPWSTR, *PWSTR; -typedef unsigned char boolean; // java brainrot +typedef unsigned char boolean; // java brainrot #define __debugbreak() #define __int32 int #define CONST const @@ -71,13 +71,13 @@ typedef unsigned long ULONG; typedef short SHORT; typedef float FLOAT; -#define ERROR_SUCCESS 0L -#define ERROR_IO_PENDING 997L // dderror -#define ERROR_CANCELLED 1223L -//#define S_OK ((HRESULT)0x00000000L) -#define S_FALSE ((HRESULT)0x00000001L) +#define ERROR_SUCCESS 0L +#define ERROR_IO_PENDING 997L // dderror +#define ERROR_CANCELLED 1223L +// #define S_OK ((HRESULT)0x00000000L) +#define S_FALSE ((HRESULT)0x00000001L) -#define INFINITE 0xFFFFFFFF // Infinite timeout +#define INFINITE 0xFFFFFFFF // Infinite timeout #define PAGE_READWRITE 0x04 #define MEM_LARGE_PAGES 0x20000000 @@ -100,13 +100,13 @@ typedef float FLOAT; #define TRUNCATE_EXISTING 5 #define WAIT_TIMEOUT 258 -#define FILE_FLAG_WRITE_THROUGH 0x80000000 -#define FILE_FLAG_OVERLAPPED 0x40000000 -#define FILE_FLAG_NO_BUFFERING 0x20000000 -#define FILE_FLAG_RANDOM_ACCESS 0x10000000 -#define FILE_FLAG_SEQUENTIAL_SCAN 0x08000000 -#define FILE_FLAG_DELETE_ON_CLOSE 0x04000000 -#define FILE_FLAG_BACKUP_SEMANTICS 0x02000000 +#define FILE_FLAG_WRITE_THROUGH 0x80000000 +#define FILE_FLAG_OVERLAPPED 0x40000000 +#define FILE_FLAG_NO_BUFFERING 0x20000000 +#define FILE_FLAG_RANDOM_ACCESS 0x10000000 +#define FILE_FLAG_SEQUENTIAL_SCAN 0x08000000 +#define FILE_FLAG_DELETE_ON_CLOSE 0x04000000 +#define FILE_FLAG_BACKUP_SEMANTICS 0x02000000 #define FILE_ATTRIBUTE_READONLY 0x00000001 #define FILE_ATTRIBUTE_HIDDEN 0x00000002 @@ -115,64 +115,64 @@ typedef float FLOAT; #define FILE_ATTRIBUTE_ARCHIVE 0x00000020 #define FILE_ATTRIBUTE_NORMAL 0x00000080 #define FILE_ATTRIBUTE_TEMPORARY 0x00000100 -#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) -#define INVALID_FILE_SIZE ((DWORD)-1) -#define INVALID_SET_FILE_POINTER ((DWORD)-1) +#define INVALID_FILE_ATTRIBUTES ((DWORD) - 1) +#define INVALID_FILE_SIZE ((DWORD) - 1) +#define INVALID_SET_FILE_POINTER ((DWORD) - 1) #define FILE_BEGIN SEEK_SET #define FILE_CURRENT SEEK_CUR #define FILE_END SEEK_END -#define PAGE_NOACCESS 0x01 -#define PAGE_READONLY 0x02 -#define PAGE_READWRITE 0x04 -#define PAGE_WRITECOPY 0x08 -#define PAGE_EXECUTE 0x10 -#define PAGE_EXECUTE_READ 0x20 +#define PAGE_NOACCESS 0x01 +#define PAGE_READONLY 0x02 +#define PAGE_READWRITE 0x04 +#define PAGE_WRITECOPY 0x08 +#define PAGE_EXECUTE 0x10 +#define PAGE_EXECUTE_READ 0x20 #define PAGE_EXECUTE_READWRITE 0x40 -#define PAGE_EXECUTE_WRITECOPY 0x80 -#define PAGE_GUARD 0x100 -#define PAGE_NOCACHE 0x200 -#define PAGE_WRITECOMBINE 0x400 -#define PAGE_USER_READONLY 0x1000 -#define PAGE_USER_READWRITE 0x2000 -#define MEM_COMMIT 0x1000 -#define MEM_RESERVE 0x2000 -#define MEM_DECOMMIT 0x4000 -#define MEM_RELEASE 0x8000 -#define MEM_FREE 0x10000 -#define MEM_PRIVATE 0x20000 -#define MEM_RESET 0x80000 -#define MEM_TOP_DOWN 0x100000 -#define MEM_NOZERO 0x800000 -#define MEM_LARGE_PAGES 0x20000000 -#define MEM_HEAP 0x40000000 -#define MEM_16MB_PAGES 0x80000000 +#define PAGE_EXECUTE_WRITECOPY 0x80 +#define PAGE_GUARD 0x100 +#define PAGE_NOCACHE 0x200 +#define PAGE_WRITECOMBINE 0x400 +#define PAGE_USER_READONLY 0x1000 +#define PAGE_USER_READWRITE 0x2000 +#define MEM_COMMIT 0x1000 +#define MEM_RESERVE 0x2000 +#define MEM_DECOMMIT 0x4000 +#define MEM_RELEASE 0x8000 +#define MEM_FREE 0x10000 +#define MEM_PRIVATE 0x20000 +#define MEM_RESET 0x80000 +#define MEM_TOP_DOWN 0x100000 +#define MEM_NOZERO 0x800000 +#define MEM_LARGE_PAGES 0x20000000 +#define MEM_HEAP 0x40000000 +#define MEM_16MB_PAGES 0x80000000 -#define THREAD_BASE_PRIORITY_LOWRT 15 // value that gets a thread to LowRealtime-1 -#define THREAD_BASE_PRIORITY_MAX 2 // maximum thread base priority boost -#define THREAD_BASE_PRIORITY_MIN -2 // minimum thread base priority boost -#define THREAD_BASE_PRIORITY_IDLE -15 // value that gets a thread to idle +#define THREAD_BASE_PRIORITY_LOWRT \ + 15 // value that gets a thread to LowRealtime-1 +#define THREAD_BASE_PRIORITY_MAX 2 // maximum thread base priority boost +#define THREAD_BASE_PRIORITY_MIN -2 // minimum thread base priority boost +#define THREAD_BASE_PRIORITY_IDLE -15 // value that gets a thread to idle -#define THREAD_PRIORITY_LOWEST THREAD_BASE_PRIORITY_MIN -#define THREAD_PRIORITY_BELOW_NORMAL (THREAD_PRIORITY_LOWEST+1) -#define THREAD_PRIORITY_NORMAL 0 -#define THREAD_PRIORITY_HIGHEST THREAD_BASE_PRIORITY_MAX -#define THREAD_PRIORITY_ABOVE_NORMAL (THREAD_PRIORITY_HIGHEST-1) -#define THREAD_PRIORITY_ERROR_RETURN (MAXLONG) +#define THREAD_PRIORITY_LOWEST THREAD_BASE_PRIORITY_MIN +#define THREAD_PRIORITY_BELOW_NORMAL (THREAD_PRIORITY_LOWEST + 1) +#define THREAD_PRIORITY_NORMAL 0 +#define THREAD_PRIORITY_HIGHEST THREAD_BASE_PRIORITY_MAX +#define THREAD_PRIORITY_ABOVE_NORMAL (THREAD_PRIORITY_HIGHEST - 1) +#define THREAD_PRIORITY_ERROR_RETURN (MAXLONG) -#define THREAD_PRIORITY_TIME_CRITICAL THREAD_BASE_PRIORITY_LOWRT -#define THREAD_PRIORITY_IDLE THREAD_BASE_PRIORITY_IDLE +#define THREAD_PRIORITY_TIME_CRITICAL THREAD_BASE_PRIORITY_LOWRT +#define THREAD_PRIORITY_IDLE THREAD_BASE_PRIORITY_IDLE -#define IGNORE 0 // Ignore signal -#define INFINITE 0xFFFFFFFF // Infinite timeout -#define STATUS_WAIT_0 ((DWORD )0x00000000L) -#define WAIT_OBJECT_0 ((STATUS_WAIT_0 ) + 0 ) -#define STATUS_PENDING ((DWORD )0x00000103L) -#define STILL_ACTIVE STATUS_PENDING +#define IGNORE 0 // Ignore signal +#define INFINITE 0xFFFFFFFF // Infinite timeout +#define STATUS_WAIT_0 ((DWORD)0x00000000L) +#define WAIT_OBJECT_0 ((STATUS_WAIT_0) + 0) +#define STATUS_PENDING ((DWORD)0x00000103L) +#define STILL_ACTIVE STATUS_PENDING - -#define INVALID_HANDLE_VALUE ((HANDLE)(ULONG_PTR)-1) +#define INVALID_HANDLE_VALUE ((HANDLE)(ULONG_PTR) - 1) // https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime typedef struct _FILETIME { @@ -181,14 +181,14 @@ typedef struct _FILETIME { } FILETIME, *PFILETIME, *LPFILETIME; typedef struct _MEMORYSTATUS { - DWORD dwLength; - DWORD dwMemoryLoad; - SIZE_T dwTotalPhys; - SIZE_T dwAvailPhys; - SIZE_T dwTotalPageFile; - SIZE_T dwAvailPageFile; - SIZE_T dwTotalVirtual; - SIZE_T dwAvailVirtual; + DWORD dwLength; + DWORD dwMemoryLoad; + SIZE_T dwTotalPhys; + SIZE_T dwAvailPhys; + SIZE_T dwTotalPageFile; + SIZE_T dwAvailPageFile; + SIZE_T dwTotalVirtual; + SIZE_T dwAvailVirtual; } MEMORYSTATUS, *LPMEMORYSTATUS; typedef struct _WIN32_FIND_DATAA { @@ -227,7 +227,7 @@ typedef VOID* XMEMDECOMPRESSION_CONTEXT; // internal search state for FindFirstFile/FindNextFile typedef struct _LINUXSTUBS_FIND_HANDLE { - DIR *dir; + DIR* dir; char dirpath[MAX_PATH]; char pattern[MAX_PATH]; } _LINUXSTUBS_FIND_HANDLE; @@ -255,14 +255,16 @@ typedef HINSTANCE HMODULE; #define _HRESULT_TYPEDEF_(_sc) _sc -#define FAILED(Status) ((HRESULT)(Status)<0) -#define MAKE_HRESULT(sev,fac,code) \ - ((HRESULT) (((unsigned int)(sev)<<31) | ((unsigned int)(fac)<<16) | ((unsigned int)(code))) ) -#define MAKE_SCODE(sev,fac,code) \ - ((SCODE) (((unsigned int)(sev)<<31) | ((unsigned int)(fac)<<16) | ((unsigned int)(code))) ) -#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L) -#define E_ABORT _HRESULT_TYPEDEF_(0x80004004L) -#define E_NOINTERFACE _HRESULT_TYPEDEF_(0x80004002L) +#define FAILED(Status) ((HRESULT)(Status) < 0) +#define MAKE_HRESULT(sev, fac, code) \ + ((HRESULT)(((unsigned int)(sev) << 31) | ((unsigned int)(fac) << 16) | \ + ((unsigned int)(code)))) +#define MAKE_SCODE(sev, fac, code) \ + ((SCODE)(((unsigned int)(sev) << 31) | ((unsigned int)(fac) << 16) | \ + ((unsigned int)(code)))) +#define E_FAIL _HRESULT_TYPEDEF_(0x80004005L) +#define E_ABORT _HRESULT_TYPEDEF_(0x80004004L) +#define E_NOINTERFACE _HRESULT_TYPEDEF_(0x80004002L) typedef pthread_mutex_t RTL_CRITICAL_SECTION; typedef pthread_mutex_t* PRTL_CRITICAL_SECTION; @@ -271,8 +273,8 @@ typedef RTL_CRITICAL_SECTION CRITICAL_SECTION; typedef PRTL_CRITICAL_SECTION PCRITICAL_SECTION; typedef PRTL_CRITICAL_SECTION LPCRITICAL_SECTION; -static inline void InitializeCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void InitializeCriticalSection( + PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); @@ -280,73 +282,61 @@ static inline void InitializeCriticalSection(PRTL_CRITICAL_SECTION CriticalSecti pthread_mutexattr_destroy(&attr); } -static inline void InitializeCriticalSectionAndSpinCount(PRTL_CRITICAL_SECTION CriticalSection, ULONG SpinCount) -{ +static inline void InitializeCriticalSectionAndSpinCount( + PRTL_CRITICAL_SECTION CriticalSection, ULONG SpinCount) { // no spin count required because we use a recursive mutex InitializeCriticalSection(CriticalSection); } -static inline void DeleteCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void DeleteCriticalSection( + PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutex_destroy(CriticalSection); } -static inline void EnterCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void EnterCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutex_lock(CriticalSection); } -static inline void LeaveCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline void LeaveCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) { pthread_mutex_unlock(CriticalSection); } -static inline ULONG TryEnterCriticalSection(PRTL_CRITICAL_SECTION CriticalSection) -{ +static inline ULONG TryEnterCriticalSection( + PRTL_CRITICAL_SECTION CriticalSection) { return pthread_mutex_trylock(CriticalSection) == 0; } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsalloc -static inline DWORD TlsAlloc(VOID) -{ +static inline DWORD TlsAlloc(VOID) { pthread_key_t key; - if (pthread_key_create(&key, NULL) == 0) - return key; + if (pthread_key_create(&key, NULL) == 0) return key; return TLS_OUT_OF_INDEXES; } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsfree -static inline BOOL TlsFree(DWORD dwTlsIndex) -{ +static inline BOOL TlsFree(DWORD dwTlsIndex) { return pthread_key_delete(dwTlsIndex) == 0; } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsgetvalue -static inline LPVOID TlsGetValue(DWORD dwTlsIndex) -{ +static inline LPVOID TlsGetValue(DWORD dwTlsIndex) { return pthread_getspecific(dwTlsIndex); } // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlssetvalue -static inline BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) -{ +static inline BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) { return pthread_setspecific(dwTlsIndex, lpTlsValue) == 0; } // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalmemorystatus -static inline VOID GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer) -{ - // TODO: Parse /proc/meminfo and set lpBuffer based on that. Probably will also need another - // different codepath for macOS too. +static inline VOID GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer) { + // TODO: Parse /proc/meminfo and set lpBuffer based on that. Probably will + // also need another different codepath for macOS too. } -static inline DWORD GetLastError(VOID) -{ - return errno; -} +static inline DWORD GetLastError(VOID) { return errno; } -static inline VOID Sleep(DWORD dwMilliseconds) -{ +static inline VOID Sleep(DWORD dwMilliseconds) { struct timespec ts; ts.tv_nsec = (dwMilliseconds * 1000000) % 1000000000; ts.tv_sec = dwMilliseconds / 1000; @@ -358,18 +348,16 @@ static inline VOID Sleep(DWORD dwMilliseconds) } static inline LONG64 InterlockedCompareExchangeRelease64( - LONG64 volatile *Destination, - LONG64 Exchange, - LONG64 Comperand) -{ + LONG64 volatile* Destination, LONG64 Exchange, LONG64 Comperand) { LONG64 expected = Comperand; - __atomic_compare_exchange_n(Destination, &expected, Exchange, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED); + __atomic_compare_exchange_n(Destination, &expected, Exchange, false, + __ATOMIC_RELEASE, __ATOMIC_RELAXED); return expected; } -// internal helper: convert time_t to FILETIME (100ns intervals since 1601-01-01) -static inline FILETIME _TimeToFileTime(time_t t) -{ +// internal helper: convert time_t to FILETIME (100ns intervals since +// 1601-01-01) +static inline FILETIME _TimeToFileTime(time_t t) { const ULONGLONG EPOCH_DIFF = 11644473600ULL; ULONGLONG val = ((ULONGLONG)t + EPOCH_DIFF) * 10000000ULL; FILETIME ft; @@ -379,11 +367,13 @@ static inline FILETIME _TimeToFileTime(time_t t) } // internal helper: fill WIN32_FIND_DATAA from stat + name -static inline void _FillFindData(const char *name, const struct stat *st, WIN32_FIND_DATAA *out) -{ +static inline void _FillFindData(const char* name, const struct stat* st, + WIN32_FIND_DATAA* out) { memset(out, 0, sizeof(*out)); - out->dwFileAttributes = S_ISDIR(st->st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; - if (!(st->st_mode & S_IWUSR)) out->dwFileAttributes |= FILE_ATTRIBUTE_READONLY; + out->dwFileAttributes = + S_ISDIR(st->st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; + if (!(st->st_mode & S_IWUSR)) + out->dwFileAttributes |= FILE_ATTRIBUTE_READONLY; if (name[0] == '.') out->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN; out->ftCreationTime = _TimeToFileTime(st->st_mtime); out->ftLastAccessTime = _TimeToFileTime(st->st_atime); @@ -393,116 +383,158 @@ static inline void _FillFindData(const char *name, const struct stat *st, WIN32_ strncpy(out->cFileName, name, MAX_PATH - 1); } -static inline HANDLE CreateFileA(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ +static inline HANDLE CreateFileA(const char* lpFileName, DWORD dwDesiredAccess, + DWORD dwShareMode, void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { int flags = 0; - if ((dwDesiredAccess & GENERIC_READ) && (dwDesiredAccess & GENERIC_WRITE)) flags = O_RDWR; - else if (dwDesiredAccess & GENERIC_WRITE) flags = O_WRONLY; - else flags = O_RDONLY; + if ((dwDesiredAccess & GENERIC_READ) && (dwDesiredAccess & GENERIC_WRITE)) + flags = O_RDWR; + else if (dwDesiredAccess & GENERIC_WRITE) + flags = O_WRONLY; + else + flags = O_RDONLY; - switch (dwCreationDisposition) - { - case CREATE_NEW: flags |= O_CREAT | O_EXCL; break; - case CREATE_ALWAYS: flags |= O_CREAT | O_TRUNC; break; - case OPEN_EXISTING: break; - case OPEN_ALWAYS: flags |= O_CREAT; break; - case TRUNCATE_EXISTING: flags |= O_TRUNC; break; + switch (dwCreationDisposition) { + case CREATE_NEW: + flags |= O_CREAT | O_EXCL; + break; + case CREATE_ALWAYS: + flags |= O_CREAT | O_TRUNC; + break; + case OPEN_EXISTING: + break; + case OPEN_ALWAYS: + flags |= O_CREAT; + break; + case TRUNCATE_EXISTING: + flags |= O_TRUNC; + break; } int fd = open(lpFileName, flags, 0644); return fd == -1 ? INVALID_HANDLE_VALUE : (HANDLE)(intptr_t)fd; } -static inline HANDLE CreateFileW(const wchar_t *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ +static inline HANDLE CreateFileW(const wchar_t* lpFileName, + DWORD dwDesiredAccess, DWORD dwShareMode, + void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { char narrowBuf[1024]; wcstombs(narrowBuf, lpFileName, sizeof(narrowBuf)); narrowBuf[sizeof(narrowBuf) - 1] = '\0'; - return CreateFileA(narrowBuf, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + return CreateFileA(narrowBuf, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); } -static inline HANDLE CreateFile(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ - return CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); +static inline HANDLE CreateFile(const char* lpFileName, DWORD dwDesiredAccess, + DWORD dwShareMode, void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { + return CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); } -static inline HANDLE CreateFile(const wchar_t *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, - void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) -{ - return CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); +static inline HANDLE CreateFile(const wchar_t* lpFileName, + DWORD dwDesiredAccess, DWORD dwShareMode, + void* lpSecurityAttributes, + DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, + HANDLE hTemplateFile) { + return CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, + lpSecurityAttributes, dwCreationDisposition, + dwFlagsAndAttributes, hTemplateFile); } -static inline BOOL CloseHandle(HANDLE hObject) -{ +static inline BOOL CloseHandle(HANDLE hObject) { if (hObject == INVALID_HANDLE_VALUE) return FALSE; return close((int)(intptr_t)hObject) == 0; } -static inline DWORD GetFileSize(HANDLE hFile, DWORD *lpFileSizeHigh) -{ +static inline DWORD GetFileSize(HANDLE hFile, DWORD* lpFileSizeHigh) { struct stat st{}; - if (fstat((int)(intptr_t)hFile, &st) != 0) { if (lpFileSizeHigh) *lpFileSizeHigh = 0; return INVALID_FILE_SIZE; } - if (lpFileSizeHigh) *lpFileSizeHigh = (DWORD)((st.st_size >> 32) & 0xFFFFFFFF); + if (fstat((int)(intptr_t)hFile, &st) != 0) { + if (lpFileSizeHigh) *lpFileSizeHigh = 0; + return INVALID_FILE_SIZE; + } + if (lpFileSizeHigh) + *lpFileSizeHigh = (DWORD)((st.st_size >> 32) & 0xFFFFFFFF); return (DWORD)(st.st_size & 0xFFFFFFFF); } -static inline BOOL GetFileSizeEx(HANDLE hFile, LARGE_INTEGER *lpFileSize) -{ +static inline BOOL GetFileSizeEx(HANDLE hFile, LARGE_INTEGER* lpFileSize) { struct stat st{}; if (fstat((int)(intptr_t)hFile, &st) != 0) return FALSE; - if (lpFileSize) { lpFileSize->QuadPart = st.st_size; lpFileSize->LowPart = (DWORD)(st.st_size & 0xFFFFFFFF); lpFileSize->HighPart = (LONG)(st.st_size >> 32); } + if (lpFileSize) { + lpFileSize->QuadPart = st.st_size; + lpFileSize->LowPart = (DWORD)(st.st_size & 0xFFFFFFFF); + lpFileSize->HighPart = (LONG)(st.st_size >> 32); + } return TRUE; } -static inline BOOL ReadFile(HANDLE hFile, void *lpBuffer, DWORD nNumberOfBytesToRead, DWORD *lpNumberOfBytesRead, void *lpOverlapped) -{ +static inline BOOL ReadFile(HANDLE hFile, void* lpBuffer, + DWORD nNumberOfBytesToRead, + DWORD* lpNumberOfBytesRead, void* lpOverlapped) { ssize_t n = read((int)(intptr_t)hFile, lpBuffer, nNumberOfBytesToRead); if (lpNumberOfBytesRead) *lpNumberOfBytesRead = n >= 0 ? (DWORD)n : 0; return n >= 0; } -static inline BOOL WriteFile(HANDLE hFile, const void *lpBuffer, DWORD nNumberOfBytesToWrite, DWORD *lpNumberOfBytesWritten, void *lpOverlapped) -{ +static inline BOOL WriteFile(HANDLE hFile, const void* lpBuffer, + DWORD nNumberOfBytesToWrite, + DWORD* lpNumberOfBytesWritten, + void* lpOverlapped) { ssize_t n = write((int)(intptr_t)hFile, lpBuffer, nNumberOfBytesToWrite); if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = n >= 0 ? (DWORD)n : 0; return n >= 0; } -static inline DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, LONG *lpDistanceToMoveHigh, DWORD dwMoveMethod) -{ +static inline DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, + LONG* lpDistanceToMoveHigh, + DWORD dwMoveMethod) { off_t offset = lDistanceToMove; if (lpDistanceToMoveHigh) offset |= ((off_t)*lpDistanceToMoveHigh << 32); off_t result = lseek((int)(intptr_t)hFile, offset, dwMoveMethod); - if (result == (off_t)-1) { if (lpDistanceToMoveHigh) *lpDistanceToMoveHigh = -1; return INVALID_SET_FILE_POINTER; } + if (result == (off_t)-1) { + if (lpDistanceToMoveHigh) *lpDistanceToMoveHigh = -1; + return INVALID_SET_FILE_POINTER; + } if (lpDistanceToMoveHigh) *lpDistanceToMoveHigh = (LONG)(result >> 32); return (DWORD)(result & 0xFFFFFFFF); } -static inline DWORD GetFileAttributesA(const char *lpFileName) -{ +static inline DWORD GetFileAttributesA(const char* lpFileName) { struct stat st{}; if (stat(lpFileName, &st) != 0) return INVALID_FILE_ATTRIBUTES; - DWORD attrs = S_ISDIR(st.st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; + DWORD attrs = + S_ISDIR(st.st_mode) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL; if (!(st.st_mode & S_IWUSR)) attrs |= FILE_ATTRIBUTE_READONLY; - const char *base = strrchr(lpFileName, '/'); base = base ? base + 1 : lpFileName; + const char* base = strrchr(lpFileName, '/'); + base = base ? base + 1 : lpFileName; if (base[0] == '.') attrs |= FILE_ATTRIBUTE_HIDDEN; return attrs; } -static inline DWORD GetFileAttributes(const char *lpFileName) -{ +static inline DWORD GetFileAttributes(const char* lpFileName) { return GetFileAttributesA(lpFileName); } -static inline BOOL GetFileAttributesExA(const char *lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, void *lpFileInformation) -{ - if (fInfoLevelId != GetFileExInfoStandard || !lpFileInformation) return FALSE; +static inline BOOL GetFileAttributesExA(const char* lpFileName, + GET_FILEEX_INFO_LEVELS fInfoLevelId, + void* lpFileInformation) { + if (fInfoLevelId != GetFileExInfoStandard || !lpFileInformation) + return FALSE; struct stat st{}; if (stat(lpFileName, &st) != 0) return FALSE; - WIN32_FILE_ATTRIBUTE_DATA *out = (WIN32_FILE_ATTRIBUTE_DATA *)lpFileInformation; + WIN32_FILE_ATTRIBUTE_DATA* out = + (WIN32_FILE_ATTRIBUTE_DATA*)lpFileInformation; out->dwFileAttributes = GetFileAttributesA(lpFileName); out->ftCreationTime = _TimeToFileTime(st.st_mtime); out->ftLastAccessTime = _TimeToFileTime(st.st_atime); @@ -512,215 +544,229 @@ static inline BOOL GetFileAttributesExA(const char *lpFileName, GET_FILEEX_INFO_ return TRUE; } -static inline BOOL GetFileAttributesEx(const char *lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, void *lpFileInformation) -{ +static inline BOOL GetFileAttributesEx(const char* lpFileName, + GET_FILEEX_INFO_LEVELS fInfoLevelId, + void* lpFileInformation) { return GetFileAttributesExA(lpFileName, fInfoLevelId, lpFileInformation); } -static inline BOOL CreateDirectoryA(const char *lpPathName, void *lpSecurityAttributes) -{ +static inline BOOL CreateDirectoryA(const char* lpPathName, + void* lpSecurityAttributes) { return mkdir(lpPathName, 0755) == 0; } -static inline BOOL CreateDirectory(const char *lpPathName, void *lpSecurityAttributes) -{ +static inline BOOL CreateDirectory(const char* lpPathName, + void* lpSecurityAttributes) { return CreateDirectoryA(lpPathName, lpSecurityAttributes); } -static inline BOOL DeleteFileA(const char *lpFileName) -{ +static inline BOOL DeleteFileA(const char* lpFileName) { return unlink(lpFileName) == 0; } -static inline BOOL DeleteFile(const char *lpFileName) -{ +static inline BOOL DeleteFile(const char* lpFileName) { return DeleteFileA(lpFileName); } -static inline BOOL MoveFileA(const char *lpExistingFileName, const char *lpNewFileName) -{ +static inline BOOL MoveFileA(const char* lpExistingFileName, + const char* lpNewFileName) { return rename(lpExistingFileName, lpNewFileName) == 0; } -static inline BOOL MoveFile(const char *lpExistingFileName, const char *lpNewFileName) -{ +static inline BOOL MoveFile(const char* lpExistingFileName, + const char* lpNewFileName) { return MoveFileA(lpExistingFileName, lpNewFileName); } // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirstfilea -static inline HANDLE FindFirstFileA(const char *lpFileName, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline HANDLE FindFirstFileA(const char* lpFileName, + WIN32_FIND_DATAA* lpFindFileData) { if (!lpFileName || !lpFindFileData) return INVALID_HANDLE_VALUE; char dirpath[MAX_PATH], pattern[MAX_PATH]; - const char *sep = strrchr(lpFileName, '/'); - if (sep) - { + const char* sep = strrchr(lpFileName, '/'); + if (sep) { size_t len = sep - lpFileName; if (len >= MAX_PATH) return INVALID_HANDLE_VALUE; - strncpy(dirpath, lpFileName, len); dirpath[len] = '\0'; + strncpy(dirpath, lpFileName, len); + dirpath[len] = '\0'; strncpy(pattern, sep + 1, MAX_PATH - 1); - } - else - { + } else { strncpy(dirpath, ".", MAX_PATH - 1); strncpy(pattern, lpFileName, MAX_PATH - 1); } - DIR *dir = opendir(dirpath); + DIR* dir = opendir(dirpath); if (!dir) return INVALID_HANDLE_VALUE; - _LINUXSTUBS_FIND_HANDLE *fh = (_LINUXSTUBS_FIND_HANDLE *)malloc(sizeof(_LINUXSTUBS_FIND_HANDLE)); - if (!fh) { closedir(dir); return INVALID_HANDLE_VALUE; } + _LINUXSTUBS_FIND_HANDLE* fh = + (_LINUXSTUBS_FIND_HANDLE*)malloc(sizeof(_LINUXSTUBS_FIND_HANDLE)); + if (!fh) { + closedir(dir); + return INVALID_HANDLE_VALUE; + } fh->dir = dir; strncpy(fh->dirpath, dirpath, MAX_PATH - 1); strncpy(fh->pattern, pattern, MAX_PATH - 1); - struct dirent *ent; - while ((ent = readdir(fh->dir)) != NULL) - { - if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; - if (fnmatch(fh->pattern, ent->d_name, 0) == 0) - { + struct dirent* ent; + while ((ent = readdir(fh->dir)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) + continue; + if (fnmatch(fh->pattern, ent->d_name, 0) == 0) { char fullpath[MAX_PATH * 2]; - snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, ent->d_name); + snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, + ent->d_name); struct stat st{}; - if (stat(fullpath, &st) == 0) _FillFindData(ent->d_name, &st, lpFindFileData); - else { memset(lpFindFileData, 0, sizeof(*lpFindFileData)); strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); } + if (stat(fullpath, &st) == 0) + _FillFindData(ent->d_name, &st, lpFindFileData); + else { + memset(lpFindFileData, 0, sizeof(*lpFindFileData)); + strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); + } return (HANDLE)fh; } } - closedir(fh->dir); free(fh); + closedir(fh->dir); + free(fh); return INVALID_HANDLE_VALUE; } -static inline HANDLE FindFirstFile(const char *lpFileName, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline HANDLE FindFirstFile(const char* lpFileName, + WIN32_FIND_DATAA* lpFindFileData) { return FindFirstFileA(lpFileName, lpFindFileData); } // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findnextfilea -static inline BOOL FindNextFileA(HANDLE hFindFile, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline BOOL FindNextFileA(HANDLE hFindFile, + WIN32_FIND_DATAA* lpFindFileData) { if (hFindFile == INVALID_HANDLE_VALUE || !lpFindFileData) return FALSE; - _LINUXSTUBS_FIND_HANDLE *fh = (_LINUXSTUBS_FIND_HANDLE *)hFindFile; + _LINUXSTUBS_FIND_HANDLE* fh = (_LINUXSTUBS_FIND_HANDLE*)hFindFile; - struct dirent *ent; - while ((ent = readdir(fh->dir)) != NULL) - { - if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; - if (fnmatch(fh->pattern, ent->d_name, 0) == 0) - { + struct dirent* ent; + while ((ent = readdir(fh->dir)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) + continue; + if (fnmatch(fh->pattern, ent->d_name, 0) == 0) { char fullpath[MAX_PATH * 2]; - snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, ent->d_name); + snprintf(fullpath, sizeof(fullpath), "%s/%s", fh->dirpath, + ent->d_name); struct stat st{}; - if (stat(fullpath, &st) == 0) _FillFindData(ent->d_name, &st, lpFindFileData); - else { memset(lpFindFileData, 0, sizeof(*lpFindFileData)); strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); } + if (stat(fullpath, &st) == 0) + _FillFindData(ent->d_name, &st, lpFindFileData); + else { + memset(lpFindFileData, 0, sizeof(*lpFindFileData)); + strncpy(lpFindFileData->cFileName, ent->d_name, MAX_PATH - 1); + } return TRUE; } } return FALSE; } -static inline BOOL FindNextFile(HANDLE hFindFile, WIN32_FIND_DATAA *lpFindFileData) -{ +static inline BOOL FindNextFile(HANDLE hFindFile, + WIN32_FIND_DATAA* lpFindFileData) { return FindNextFileA(hFindFile, lpFindFileData); } // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findclose -static inline BOOL FindClose(HANDLE hFindFile) -{ +static inline BOOL FindClose(HANDLE hFindFile) { if (hFindFile == INVALID_HANDLE_VALUE) return FALSE; - _LINUXSTUBS_FIND_HANDLE *fh = (_LINUXSTUBS_FIND_HANDLE *)hFindFile; - closedir(fh->dir); free(fh); + _LINUXSTUBS_FIND_HANDLE* fh = (_LINUXSTUBS_FIND_HANDLE*)hFindFile; + closedir(fh->dir); + free(fh); return TRUE; } -// internal helper: convert FILETIME (100ns since 1601) to time_t (seconds since 1970) -static inline time_t _FileTimeToTimeT(const FILETIME& ft) -{ +// internal helper: convert FILETIME (100ns since 1601) to time_t (seconds since +// 1970) +static inline time_t _FileTimeToTimeT(const FILETIME& ft) { ULONGLONG val = ((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime; - const ULONGLONG EPOCH_DIFF = 116444736000000000ULL; // 100ns intervals between 1601-01-01 and 1970-01-01 + const ULONGLONG EPOCH_DIFF = + 116444736000000000ULL; // 100ns intervals between 1601-01-01 and + // 1970-01-01 return (time_t)((val - EPOCH_DIFF) / 10000000ULL); } // internal helper: read the current wall clock into a timespec -static inline void _CurrentTimeSpec(struct timespec *ts) -{ +static inline void _CurrentTimeSpec(struct timespec* ts) { #ifdef CLOCK_REALTIME clock_gettime(CLOCK_REALTIME, ts); #else struct timeval tv; gettimeofday(&tv, NULL); - ts->tv_sec = tv.tv_sec; + ts->tv_sec = tv.tv_sec; ts->tv_nsec = tv.tv_usec * 1000; #endif } // internal helper: fill SYSTEMTIME from a broken-down tm + nanosecond remainder -static inline void _FillSystemTime(const struct tm *tm, long tv_nsec, LPSYSTEMTIME lpSystemTime) -{ - lpSystemTime->wYear = tm->tm_year + 1900; - lpSystemTime->wMonth = tm->tm_mon + 1; - lpSystemTime->wDayOfWeek = tm->tm_wday; // 0 = Sunday - lpSystemTime->wDay = tm->tm_mday; - lpSystemTime->wHour = tm->tm_hour; - lpSystemTime->wMinute = tm->tm_min; - lpSystemTime->wSecond = tm->tm_sec; - lpSystemTime->wMilliseconds = (WORD)(tv_nsec / 1000000); // ns to ms +static inline void _FillSystemTime(const struct tm* tm, long tv_nsec, + LPSYSTEMTIME lpSystemTime) { + lpSystemTime->wYear = tm->tm_year + 1900; + lpSystemTime->wMonth = tm->tm_mon + 1; + lpSystemTime->wDayOfWeek = tm->tm_wday; // 0 = Sunday + lpSystemTime->wDay = tm->tm_mday; + lpSystemTime->wHour = tm->tm_hour; + lpSystemTime->wMinute = tm->tm_min; + lpSystemTime->wSecond = tm->tm_sec; + lpSystemTime->wMilliseconds = (WORD)(tv_nsec / 1000000); // ns to ms } // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtime -static inline VOID GetSystemTime(LPSYSTEMTIME lpSystemTime) -{ - struct timespec ts; _CurrentTimeSpec(&ts); - struct tm tm; gmtime_r(&ts.tv_sec, &tm); // UTC +static inline VOID GetSystemTime(LPSYSTEMTIME lpSystemTime) { + struct timespec ts; + _CurrentTimeSpec(&ts); + struct tm tm; + gmtime_r(&ts.tv_sec, &tm); // UTC _FillSystemTime(&tm, ts.tv_nsec, lpSystemTime); } // https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlocaltime -static inline VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) -{ - struct timespec ts; _CurrentTimeSpec(&ts); - struct tm tm; localtime_r(&ts.tv_sec, &tm); // local time +static inline VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) { + struct timespec ts; + _CurrentTimeSpec(&ts); + struct tm tm; + localtime_r(&ts.tv_sec, &tm); // local time _FillSystemTime(&tm, ts.tv_nsec, lpSystemTime); } // https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-systemtimetofiletime -static inline BOOL SystemTimeToFileTime(const SYSTEMTIME *lpSystemTime, LPFILETIME lpFileTime) -{ +static inline BOOL SystemTimeToFileTime(const SYSTEMTIME* lpSystemTime, + LPFILETIME lpFileTime) { struct tm tm = {}; tm.tm_year = lpSystemTime->wYear - 1900; - tm.tm_mon = lpSystemTime->wMonth - 1; + tm.tm_mon = lpSystemTime->wMonth - 1; tm.tm_mday = lpSystemTime->wDay; tm.tm_hour = lpSystemTime->wHour; - tm.tm_min = lpSystemTime->wMinute; - tm.tm_sec = lpSystemTime->wSecond; + tm.tm_min = lpSystemTime->wMinute; + tm.tm_sec = lpSystemTime->wSecond; time_t t = timegm(&tm); if (t == (time_t)-1) return FALSE; ULONGLONG ft = ((ULONGLONG)t + 11644473600ULL) * 10000000ULL; ft += lpSystemTime->wMilliseconds * 10000ULL; - lpFileTime->dwLowDateTime = (DWORD)(ft & 0xFFFFFFFF); + lpFileTime->dwLowDateTime = (DWORD)(ft & 0xFFFFFFFF); lpFileTime->dwHighDateTime = (DWORD)(ft >> 32); return TRUE; } // https://learn.microsoft.com/en-us/windows/win32/api/timezoneapi/nf-timezoneapi-filetimetosystemtime -static inline BOOL FileTimeToSystemTime(const FILETIME *lpFileTime, LPSYSTEMTIME lpSystemTime) -{ - ULONGLONG ft = ((ULONGLONG)lpFileTime->dwHighDateTime << 32) | lpFileTime->dwLowDateTime; +static inline BOOL FileTimeToSystemTime(const FILETIME* lpFileTime, + LPSYSTEMTIME lpSystemTime) { + ULONGLONG ft = ((ULONGLONG)lpFileTime->dwHighDateTime << 32) | + lpFileTime->dwLowDateTime; time_t t = _FileTimeToTimeT(*lpFileTime); long remainder_ns = (long)((ft % 10000000ULL) * 100); - struct tm tm; gmtime_r(&t, &tm); // UTC + struct tm tm; + gmtime_r(&t, &tm); // UTC _FillSystemTime(&tm, remainder_ns, lpSystemTime); return TRUE; } -static inline DWORD GetTickCount() -{ +static inline DWORD GetTickCount() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -728,41 +774,36 @@ static inline DWORD GetTickCount() return (long long)ts.tv_sec * 1000 + (long long)ts.tv_nsec / 1000000; } -static inline BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency) -{ - // nanoseconds - lpFrequency->QuadPart = 1000000000; - return false; +static inline BOOL QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency) { + // nanoseconds + lpFrequency->QuadPart = 1000000000; + return false; } - -static inline BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount) -{ +static inline BOOL QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); // nanoseconds - lpPerformanceCount->QuadPart = ((long long)ts.tv_sec * 1000000000) + (long long)ts.tv_nsec; + lpPerformanceCount->QuadPart = + ((long long)ts.tv_sec * 1000000000) + (long long)ts.tv_nsec; return true; } // https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringa -static inline VOID OutputDebugStringA(LPCSTR lpOutputString) -{ +static inline VOID OutputDebugStringA(LPCSTR lpOutputString) { if (!lpOutputString) return; fputs(lpOutputString, stderr); } // https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringw -static inline VOID OutputDebugStringW(LPCWSTR lpOutputString) -{ +static inline VOID OutputDebugStringW(LPCWSTR lpOutputString) { if (!lpOutputString) return; fprintf(stderr, "%ls", lpOutputString); } -static inline VOID OutputDebugString(LPCSTR lpOutputString) -{ +static inline VOID OutputDebugString(LPCSTR lpOutputString) { return OutputDebugStringA(lpOutputString); } @@ -782,7 +823,8 @@ static inline HANDLE CreateEvent(int manual_reset, int initial_state) { return (HANDLE)ev; } -static inline HANDLE CreateEvent(void*, BOOL manual_reset, BOOL initial_state, void*) { +static inline HANDLE CreateEvent(void*, BOOL manual_reset, BOOL initial_state, + void*) { return CreateEvent(manual_reset, initial_state); } @@ -791,8 +833,10 @@ static inline BOOL SetEvent(HANDLE hEvent) { if (!ev) return FALSE; pthread_mutex_lock(&ev->mutex); ev->signaled = 1; - if (ev->manual_reset) pthread_cond_broadcast(&ev->cond); - else pthread_cond_signal(&ev->cond); + if (ev->manual_reset) + pthread_cond_broadcast(&ev->cond); + else + pthread_cond_signal(&ev->cond); pthread_mutex_unlock(&ev->mutex); return TRUE; } @@ -819,7 +863,10 @@ static inline DWORD _WaitForEvent(Event* ev, DWORD dwMilliseconds) { clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += dwMilliseconds / 1000; ts.tv_nsec += (dwMilliseconds % 1000) * 1000000; - if (ts.tv_nsec >= 1000000000) { ts.tv_sec++; ts.tv_nsec -= 1000000000; } + if (ts.tv_nsec >= 1000000000) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000; + } while (!ev->signaled) { if (pthread_cond_timedwait(&ev->cond, &ev->mutex, &ts) != 0) { pthread_mutex_unlock(&ev->mutex); @@ -827,7 +874,10 @@ static inline DWORD _WaitForEvent(Event* ev, DWORD dwMilliseconds) { } } } else { - if (!ev->signaled) { pthread_mutex_unlock(&ev->mutex); return WAIT_TIMEOUT; } + if (!ev->signaled) { + pthread_mutex_unlock(&ev->mutex); + return WAIT_TIMEOUT; + } } if (!ev->manual_reset) ev->signaled = 0; pthread_mutex_unlock(&ev->mutex); @@ -835,25 +885,32 @@ static inline DWORD _WaitForEvent(Event* ev, DWORD dwMilliseconds) { } struct LinuxThread; -static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds); +static inline DWORD _WaitForThread(struct LinuxThread* lt, + DWORD dwMilliseconds); static inline DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) { if (!hHandle) return WAIT_FAILED; - // Check if this is a thread handle (LinuxThread has magic number as first field) + // Check if this is a thread handle (LinuxThread has magic number as first + // field) if (*(int*)hHandle == HANDLE_TYPE_THREAD) { return _WaitForThread((struct LinuxThread*)hHandle, dwMilliseconds); } return _WaitForEvent((Event*)hHandle, dwMilliseconds); } -static inline DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE* lpHandles, BOOL bWaitAll, DWORD dwMilliseconds) { +static inline DWORD WaitForMultipleObjects(DWORD nCount, + const HANDLE* lpHandles, + BOOL bWaitAll, + DWORD dwMilliseconds) { if (bWaitAll) { - for (DWORD i = 0; i < nCount; i++) WaitForSingleObject(lpHandles[i], dwMilliseconds); + for (DWORD i = 0; i < nCount; i++) + WaitForSingleObject(lpHandles[i], dwMilliseconds); return WAIT_OBJECT_0; } for (int pass = 0; pass < 1000; pass++) { for (DWORD i = 0; i < nCount; i++) { - if (WaitForSingleObject(lpHandles[i], 0) == WAIT_OBJECT_0) return WAIT_OBJECT_0 + i; + if (WaitForSingleObject(lpHandles[i], 0) == WAIT_OBJECT_0) + return WAIT_OBJECT_0 + i; } usleep(1000); } @@ -890,7 +947,8 @@ struct LinuxThread { static inline void* _linux_thread_entry(void* arg) { LinuxThread* lt = (LinuxThread*)arg; pthread_mutex_lock(<->suspendMutex); - while (lt->suspended) pthread_cond_wait(<->suspendCond, <->suspendMutex); + while (lt->suspended) + pthread_cond_wait(<->suspendCond, <->suspendMutex); pthread_mutex_unlock(<->suspendMutex); lt->exitCode = lt->func(lt->param); // Signal completion @@ -901,7 +959,8 @@ static inline void* _linux_thread_entry(void* arg) { return NULL; } -static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds) { +static inline DWORD _WaitForThread(struct LinuxThread* lt, + DWORD dwMilliseconds) { pthread_mutex_lock(<->completionMutex); if (lt->completed) { pthread_mutex_unlock(<->completionMutex); @@ -912,15 +971,20 @@ static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds) return WAIT_TIMEOUT; } if (dwMilliseconds == INFINITE) { - while (!lt->completed) pthread_cond_wait(<->completionCond, <->completionMutex); + while (!lt->completed) + pthread_cond_wait(<->completionCond, <->completionMutex); } else { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += dwMilliseconds / 1000; ts.tv_nsec += (dwMilliseconds % 1000) * 1000000; - if (ts.tv_nsec >= 1000000000) { ts.tv_sec++; ts.tv_nsec -= 1000000000; } + if (ts.tv_nsec >= 1000000000) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000; + } while (!lt->completed) { - if (pthread_cond_timedwait(<->completionCond, <->completionMutex, &ts) != 0) { + if (pthread_cond_timedwait(<->completionCond, + <->completionMutex, &ts) != 0) { pthread_mutex_unlock(<->completionMutex); return WAIT_TIMEOUT; } @@ -932,7 +996,10 @@ static inline DWORD _WaitForThread(struct LinuxThread* lt, DWORD dwMilliseconds) static DWORD g_nextThreadId = 1000; -static inline HANDLE CreateThread(void*, SIZE_T stackSize, LPTHREAD_START_ROUTINE lpStartAddress, void* lpParameter, DWORD dwCreationFlags, DWORD* lpThreadId) { +static inline HANDLE CreateThread(void*, SIZE_T stackSize, + LPTHREAD_START_ROUTINE lpStartAddress, + void* lpParameter, DWORD dwCreationFlags, + DWORD* lpThreadId) { LinuxThread* lt = (LinuxThread*)calloc(1, sizeof(LinuxThread)); lt->handleType = HANDLE_TYPE_THREAD; lt->func = lpStartAddress; @@ -965,7 +1032,8 @@ static inline DWORD ResumeThread(HANDLE hThread) { } static inline BOOL SetThreadPriority(HANDLE hThread, int nPriority) { - (void)hThread; (void)nPriority; + (void)hThread; + (void)nPriority; return TRUE; } @@ -984,7 +1052,7 @@ static inline HANDLE GetCurrentThread() { return (HANDLE)(unsigned long)pthread_self(); } -template +template static inline int sprintf_s(char (&buf)[N], const char* fmt, ...) { va_list args; va_start(args, fmt); @@ -995,13 +1063,13 @@ static inline int sprintf_s(char (&buf)[N], const char* fmt, ...) { static inline int sprintf_s(char* buf, size_t sz, const char* fmt, ...) { va_list args; - va_start(args, fmt); // fucking horrid + va_start(args, fmt); // fucking horrid int ret = vsnprintf(buf, sz, fmt, args); va_end(args); return ret; } -template +template static inline int swprintf_s(wchar_t (&buf)[N], const wchar_t* fmt, ...) { va_list args; va_start(args, fmt); @@ -1020,29 +1088,36 @@ static inline int swprintf_s(wchar_t* buf, size_t sz, const wchar_t* fmt, ...) { static inline HMODULE GetModuleHandle(LPCSTR lpModuleName) { return 0; } -static inline LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { +static inline LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, + DWORD flAllocationType, DWORD flProtect) { // MEM_COMMIT | MEM_RESERVE → mmap anonymous int prot = 0; - if (flProtect == 0x04 /*PAGE_READWRITE*/) prot = PROT_READ | PROT_WRITE; - else if (flProtect == 0x40 /*PAGE_EXECUTE_READWRITE*/) prot = PROT_READ | PROT_WRITE | PROT_EXEC; - else if (flProtect == 0x02 /*PAGE_READONLY*/) prot = PROT_READ; - else prot = PROT_READ | PROT_WRITE; // default + if (flProtect == 0x04 /*PAGE_READWRITE*/) + prot = PROT_READ | PROT_WRITE; + else if (flProtect == 0x40 /*PAGE_EXECUTE_READWRITE*/) + prot = PROT_READ | PROT_WRITE | PROT_EXEC; + else if (flProtect == 0x02 /*PAGE_READONLY*/) + prot = PROT_READ; + else + prot = PROT_READ | PROT_WRITE; // default int flags = MAP_PRIVATE | MAP_ANONYMOUS; if (lpAddress != NULL) flags |= MAP_FIXED; - void *p = mmap(lpAddress, dwSize, prot, flags, -1, 0); + void* p = mmap(lpAddress, dwSize, prot, flags, -1, 0); if (p == MAP_FAILED) return NULL; return p; } -static inline BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) { +static inline BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, + DWORD dwFreeType) { if (lpAddress == NULL) return FALSE; // MEM_RELEASE (0x8000) frees the whole region if (dwFreeType == 0x8000 /*MEM_RELEASE*/) { - // dwSize should be 0 for MEM_RELEASE per Win32 API, but we don't track allocation sizes - // Use dwSize if provided, otherwise this is a best-effort - if (dwSize == 0) dwSize = 4096; // minimum page + // dwSize should be 0 for MEM_RELEASE per Win32 API, but we don't track + // allocation sizes Use dwSize if provided, otherwise this is a + // best-effort + if (dwSize == 0) dwSize = 4096; // minimum page munmap(lpAddress, dwSize); } else { // MEM_DECOMMIT (0x4000) - just decommit (make inaccessible) @@ -1058,4 +1133,4 @@ static inline BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType #define _strnicmp strncasecmp #define _wcsnicmp wcsncasecmp -#endif // WINAPISTUBS_H +#endif // WINAPISTUBS_H diff --git a/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h b/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h index a5bfca2b9..6b4901e9d 100644 --- a/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h +++ b/Minecraft.Client/Platform/Linux/Stubs/xbox_stubs.h @@ -4,7 +4,7 @@ // //============================================================================= -#if !defined( XBOXSTUBS_H ) && !defined( _X360 ) +#if !defined(XBOXSTUBS_H) && !defined(_X360) #define XBOXSTUBS_H #ifdef _WIN32 @@ -12,7 +12,7 @@ #endif // DecalOverdose: not available in 4J -//#include "tier0/platform.h" +// #include "tier0/platform.h" #define POSIX @@ -23,66 +23,65 @@ typedef long long int int64; #define FORCEINLINE inline // Content creation/open flags -#define XCONTENTFLAG_NONE 0x00 -#define XCONTENTFLAG_CREATENEW 0x00 -#define XCONTENTFLAG_CREATEALWAYS 0x00 -#define XCONTENTFLAG_OPENEXISTING 0x00 -#define XCONTENTFLAG_OPENALWAYS 0x00 -#define XCONTENTFLAG_TRUNCATEEXISTING 0x00 +#define XCONTENTFLAG_NONE 0x00 +#define XCONTENTFLAG_CREATENEW 0x00 +#define XCONTENTFLAG_CREATEALWAYS 0x00 +#define XCONTENTFLAG_OPENEXISTING 0x00 +#define XCONTENTFLAG_OPENALWAYS 0x00 +#define XCONTENTFLAG_TRUNCATEEXISTING 0x00 // Content attributes -#define XCONTENTFLAG_NOPROFILE_TRANSFER 0x00 -#define XCONTENTFLAG_NODEVICE_TRANSFER 0x00 -#define XCONTENTFLAG_STRONG_SIGNED 0x00 -#define XCONTENTFLAG_ALLOWPROFILE_TRANSFER 0x00 -#define XCONTENTFLAG_MOVEONLY_TRANSFER 0x00 +#define XCONTENTFLAG_NOPROFILE_TRANSFER 0x00 +#define XCONTENTFLAG_NODEVICE_TRANSFER 0x00 +#define XCONTENTFLAG_STRONG_SIGNED 0x00 +#define XCONTENTFLAG_ALLOWPROFILE_TRANSFER 0x00 +#define XCONTENTFLAG_MOVEONLY_TRANSFER 0x00 // Console device ports -#define XDEVICE_PORT0 0 -#define XDEVICE_PORT1 1 -#define XDEVICE_PORT2 2 -#define XDEVICE_PORT3 3 +#define XDEVICE_PORT0 0 +#define XDEVICE_PORT1 1 +#define XDEVICE_PORT2 2 +#define XDEVICE_PORT3 3 // #define XUSER_MAX_COUNT 4 -#define XUSER_INDEX_NONE 0x000000FE +#define XUSER_INDEX_NONE 0x000000FE -#define XBX_CLR_DEFAULT 0xFF000000 -#define XBX_CLR_WARNING 0x0000FFFF -#define XBX_CLR_ERROR 0x000000FF +#define XBX_CLR_DEFAULT 0xFF000000 +#define XBX_CLR_WARNING 0x0000FFFF +#define XBX_CLR_ERROR 0x000000FF -#define XBOX_MINBORDERSAFE 0 -#define XBOX_MAXBORDERSAFE 0 +#define XBOX_MINBORDERSAFE 0 +#define XBOX_MAXBORDERSAFE 0 -typedef enum -{ - XK_NULL, - XK_BUTTON_UP, - XK_BUTTON_DOWN, - XK_BUTTON_LEFT, - XK_BUTTON_RIGHT, - XK_BUTTON_START, - XK_BUTTON_BACK, - XK_BUTTON_STICK1, - XK_BUTTON_STICK2, - XK_BUTTON_A, - XK_BUTTON_B, - XK_BUTTON_X, - XK_BUTTON_Y, - XK_BUTTON_LEFT_SHOULDER, - XK_BUTTON_RIGHT_SHOULDER, - XK_BUTTON_LTRIGGER, - XK_BUTTON_RTRIGGER, - XK_STICK1_UP, - XK_STICK1_DOWN, - XK_STICK1_LEFT, - XK_STICK1_RIGHT, - XK_STICK2_UP, - XK_STICK2_DOWN, - XK_STICK2_LEFT, - XK_STICK2_RIGHT, - XK_MAX_KEYS, +typedef enum { + XK_NULL, + XK_BUTTON_UP, + XK_BUTTON_DOWN, + XK_BUTTON_LEFT, + XK_BUTTON_RIGHT, + XK_BUTTON_START, + XK_BUTTON_BACK, + XK_BUTTON_STICK1, + XK_BUTTON_STICK2, + XK_BUTTON_A, + XK_BUTTON_B, + XK_BUTTON_X, + XK_BUTTON_Y, + XK_BUTTON_LEFT_SHOULDER, + XK_BUTTON_RIGHT_SHOULDER, + XK_BUTTON_LTRIGGER, + XK_BUTTON_RTRIGGER, + XK_STICK1_UP, + XK_STICK1_DOWN, + XK_STICK1_LEFT, + XK_STICK1_RIGHT, + XK_STICK2_UP, + XK_STICK2_DOWN, + XK_STICK2_LEFT, + XK_STICK2_RIGHT, + XK_MAX_KEYS, } xKey_t; -//typedef enum +// typedef enum //{ // XVRB_NONE, // off // XVRB_ERROR, // fatal error @@ -90,74 +89,70 @@ typedef enum // XVRB_WARNING, // non-fatal warnings // XVRB_STATUS, // status reports // XVRB_ALL, -//} xverbose_e; +// } xverbose_e; #ifdef POSIX typedef DWORD COLORREF; #endif #ifndef INVALID_HANDLE_VALUE -#define INVALID_HANDLE_VALUE ((HANDLE)-1) +#define INVALID_HANDLE_VALUE ((HANDLE) - 1) #endif // typedef struct { -// IN_ADDR ina; // IP address (zero if not static/DHCP) -// IN_ADDR inaOnline; // Online IP address (zero if not online) -// WORD wPortOnline; // Online port -// BYTE abEnet[6]; // Ethernet MAC address -// BYTE abOnline[20]; // Online identification -// } XNADDR; +// IN_ADDR ina; // IP address (zero if not +// static/DHCP) IN_ADDR inaOnline; // Online IP address +// (zero if not online) WORD wPortOnline; // Online +// port BYTE abEnet[6]; // Ethernet MAC address BYTE +// abOnline[20]; // Online identification } XNADDR; typedef int XNADDR; typedef uint64 XUID; typedef struct { - BYTE ab[8]; // xbox to xbox key identifier + BYTE ab[8]; // xbox to xbox key identifier } XNKID; typedef struct { - BYTE ab[16]; // xbox to xbox key exchange key + BYTE ab[16]; // xbox to xbox key exchange key } XNKEY; -typedef struct _XSESSION_INFO -{ - XNKID sessionID; // 8 bytes - XNADDR hostAddress; // 36 bytes - XNKEY keyExchangeKey; // 16 bytes +typedef struct _XSESSION_INFO { + XNKID sessionID; // 8 bytes + XNADDR hostAddress; // 36 bytes + XNKEY keyExchangeKey; // 16 bytes } XSESSION_INFO, *PXSESSION_INFO; -typedef struct _XSESSION_REGISTRANT -{ - uint64 qwMachineID; - DWORD bTrustworthiness; - DWORD bNumUsers; - XUID *rgUsers; +typedef struct _XSESSION_REGISTRANT { + uint64 qwMachineID; + DWORD bTrustworthiness; + DWORD bNumUsers; + XUID* rgUsers; } XSESSION_REGISTRANT; -typedef struct _XSESSION_REGISTRATION_RESULTS -{ - DWORD wNumRegistrants; - XSESSION_REGISTRANT *rgRegistrants; +typedef struct _XSESSION_REGISTRATION_RESULTS { + DWORD wNumRegistrants; + XSESSION_REGISTRANT* rgRegistrants; } XSESSION_REGISTRATION_RESULTS, *PXSESSION_REGISTRATION_RESULTS; -#define XSESSION_CREATE_HOST 0 -#define XUSER_DATA_TYPE_INT32 0 -#define XSESSION_CREATE_USES_ARBITRATION 0 -#define XNET_QOS_LISTEN_ENABLE 0 -#define XNET_QOS_LISTEN_DISABLE 0 -#define XNET_QOS_LISTEN_SET_DATA 0 +#define XSESSION_CREATE_HOST 0 +#define XUSER_DATA_TYPE_INT32 0 +#define XSESSION_CREATE_USES_ARBITRATION 0 +#define XNET_QOS_LISTEN_ENABLE 0 +#define XNET_QOS_LISTEN_DISABLE 0 +#define XNET_QOS_LISTEN_SET_DATA 0 -FORCEINLINE void XBX_ProcessEvents() {} -FORCEINLINE unsigned int XBX_GetSystemTime() { return 0; } -FORCEINLINE int XBX_GetPrimaryUserId() { return 0; } -FORCEINLINE void XBX_SetPrimaryUserId( DWORD idx ) {} -FORCEINLINE int XBX_GetStorageDeviceId() { return 0; } -FORCEINLINE void XBX_SetStorageDeviceId( DWORD idx ) {} -FORCEINLINE const char *XBX_GetLanguageString() { return ""; } -FORCEINLINE bool XBX_IsLocalized() { return false; } +FORCEINLINE void XBX_ProcessEvents() {} +FORCEINLINE unsigned int XBX_GetSystemTime() { return 0; } +FORCEINLINE int XBX_GetPrimaryUserId() { return 0; } +FORCEINLINE void XBX_SetPrimaryUserId(DWORD idx) {} +FORCEINLINE int XBX_GetStorageDeviceId() { return 0; } +FORCEINLINE void XBX_SetStorageDeviceId(DWORD idx) {} +FORCEINLINE const char* XBX_GetLanguageString() { return ""; } +FORCEINLINE bool XBX_IsLocalized() { return false; } -#define XBX_INVALID_STORAGE_ID ((DWORD) -1) -#define XBX_STORAGE_DECLINED ((DWORD) -2) +#define XBX_INVALID_STORAGE_ID ((DWORD) - 1) +#define XBX_STORAGE_DECLINED ((DWORD) - 2) -#endif // XBOXSTUBS_H +#endif // XBOXSTUBS_H diff --git a/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp b/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp index c2d65ab1b..e8f5bd3a0 100644 --- a/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp +++ b/Minecraft.Client/Platform/Linux/linux_game_stubs.cpp @@ -18,13 +18,18 @@ void PIXSetMarkerDeprecated(int a, const char* b, ...) {} #include "../Xbox/Network/NetworkPlayerXbox.h" -NetworkPlayerXbox::NetworkPlayerXbox(IQNetPlayer* p) : m_qnetPlayer(p), m_pSocket(nullptr) {} +NetworkPlayerXbox::NetworkPlayerXbox(IQNetPlayer* p) + : m_qnetPlayer(p), m_pSocket(nullptr) {} IQNetPlayer* NetworkPlayerXbox::GetQNetPlayer() { return m_qnetPlayer; } unsigned char NetworkPlayerXbox::GetSmallId() { return 0; } void NetworkPlayerXbox::SendData(INetworkPlayer*, const void*, int, bool) {} bool NetworkPlayerXbox::IsSameSystem(INetworkPlayer*) { return false; } -int NetworkPlayerXbox::GetSendQueueSizeBytes(INetworkPlayer*, bool) { return 0; } -int NetworkPlayerXbox::GetSendQueueSizeMessages(INetworkPlayer*, bool) { return 0; } +int NetworkPlayerXbox::GetSendQueueSizeBytes(INetworkPlayer*, bool) { + return 0; +} +int NetworkPlayerXbox::GetSendQueueSizeMessages(INetworkPlayer*, bool) { + return 0; +} int NetworkPlayerXbox::GetCurrentRtt() { return 0; } bool NetworkPlayerXbox::IsHost() { return false; } bool NetworkPlayerXbox::IsGuest() { return false; } diff --git a/Minecraft.Client/Player/EntityTracker.cpp b/Minecraft.Client/Player/EntityTracker.cpp index 2b318b5ea..802f7480d 100644 --- a/Minecraft.Client/Player/EntityTracker.cpp +++ b/Minecraft.Client/Player/EntityTracker.cpp @@ -20,210 +20,212 @@ #include "../../Minecraft.World/Util/BasicTypeContainers.h" #include "../Network/PlayerConnection.h" -EntityTracker::EntityTracker(ServerLevel *level) -{ +EntityTracker::EntityTracker(ServerLevel* level) { this->level = level; maxRange = level->getServer()->getPlayers()->getMaxRange(); } -void EntityTracker::addEntity(std::shared_ptr e) -{ - if (e->GetType() == eTYPE_SERVERPLAYER) - { +void EntityTracker::addEntity(std::shared_ptr e) { + if (e->GetType() == eTYPE_SERVERPLAYER) { addEntity(e, 32 * 16, 2); - std::shared_ptr player = std::dynamic_pointer_cast(e); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - if( (*it)->e != player ) - { - (*it)->updatePlayer(this, player); - } - } - } - else if (e->GetType() == eTYPE_FISHINGHOOK) addEntity(e, 16 * 4, 5, true); - else if (e->GetType() == eTYPE_SMALL_FIREBALL) addEntity(e, 16 * 4, 10, false); - else if (e->GetType() == eTYPE_DRAGON_FIREBALL) addEntity(e, 16 * 4, 10, false); // 4J Added TU9 - else if (e->GetType() == eTYPE_ARROW) addEntity(e, 16 * 4, 20, false); - else if (e->GetType() == eTYPE_FIREBALL) addEntity(e, 16 * 4, 10, false); - else if (e->GetType() == eTYPE_SNOWBALL) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_THROWNENDERPEARL) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_EYEOFENDERSIGNAL ) addEntity(e, 16 * 4, 4, true); - else if (e->GetType() == eTYPE_THROWNEGG) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_THROWNPOTION ) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_THROWNEXPBOTTLE) addEntity(e, 16 * 4, 10, true); - else if (e->GetType() == eTYPE_ITEMENTITY) addEntity(e, 16 * 4, 20, true); - else if (e->GetType() == eTYPE_MINECART) addEntity(e, 16 * 5, 3, true); - else if (e->GetType() == eTYPE_BOAT) addEntity(e, 16 * 5, 3, true); - else if (e->GetType() == eTYPE_SQUID) addEntity(e, 16 * 4, 3, true); - else if (std::dynamic_pointer_cast(e)!=NULL) addEntity(e, 16 * 5, 3, true); - else if (e->GetType() == eTYPE_ENDERDRAGON ) addEntity(e, 16 * 10, 3, true); - else if (e->GetType() == eTYPE_PRIMEDTNT) addEntity(e, 16 * 10, 10, true); - else if (e->GetType() == eTYPE_FALLINGTILE) addEntity(e, 16 * 10, 20, true); - else if (e->GetType() == eTYPE_PAINTING) addEntity(e, 16 * 10, INT_MAX, false); - else if (e->GetType() == eTYPE_EXPERIENCEORB) addEntity(e, 16 * 10, 20, true); - else if (e->GetType() == eTYPE_ENDER_CRYSTAL) addEntity(e, 16 * 16, INT_MAX, false); - else if (e->GetType() == eTYPE_ITEM_FRAME) addEntity(e, 16 * 10, INT_MAX, false); + std::shared_ptr player = + std::dynamic_pointer_cast(e); + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + if ((*it)->e != player) { + (*it)->updatePlayer(this, player); + } + } + } else if (e->GetType() == eTYPE_FISHINGHOOK) + addEntity(e, 16 * 4, 5, true); + else if (e->GetType() == eTYPE_SMALL_FIREBALL) + addEntity(e, 16 * 4, 10, false); + else if (e->GetType() == eTYPE_DRAGON_FIREBALL) + addEntity(e, 16 * 4, 10, false); // 4J Added TU9 + else if (e->GetType() == eTYPE_ARROW) + addEntity(e, 16 * 4, 20, false); + else if (e->GetType() == eTYPE_FIREBALL) + addEntity(e, 16 * 4, 10, false); + else if (e->GetType() == eTYPE_SNOWBALL) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_THROWNENDERPEARL) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_EYEOFENDERSIGNAL) + addEntity(e, 16 * 4, 4, true); + else if (e->GetType() == eTYPE_THROWNEGG) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_THROWNPOTION) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_THROWNEXPBOTTLE) + addEntity(e, 16 * 4, 10, true); + else if (e->GetType() == eTYPE_ITEMENTITY) + addEntity(e, 16 * 4, 20, true); + else if (e->GetType() == eTYPE_MINECART) + addEntity(e, 16 * 5, 3, true); + else if (e->GetType() == eTYPE_BOAT) + addEntity(e, 16 * 5, 3, true); + else if (e->GetType() == eTYPE_SQUID) + addEntity(e, 16 * 4, 3, true); + else if (std::dynamic_pointer_cast(e) != NULL) + addEntity(e, 16 * 5, 3, true); + else if (e->GetType() == eTYPE_ENDERDRAGON) + addEntity(e, 16 * 10, 3, true); + else if (e->GetType() == eTYPE_PRIMEDTNT) + addEntity(e, 16 * 10, 10, true); + else if (e->GetType() == eTYPE_FALLINGTILE) + addEntity(e, 16 * 10, 20, true); + else if (e->GetType() == eTYPE_PAINTING) + addEntity(e, 16 * 10, INT_MAX, false); + else if (e->GetType() == eTYPE_EXPERIENCEORB) + addEntity(e, 16 * 10, 20, true); + else if (e->GetType() == eTYPE_ENDER_CRYSTAL) + addEntity(e, 16 * 16, INT_MAX, false); + else if (e->GetType() == eTYPE_ITEM_FRAME) + addEntity(e, 16 * 10, INT_MAX, false); } -void EntityTracker::addEntity(std::shared_ptr e, int range, int updateInterval) -{ - addEntity(e, range, updateInterval, false); +void EntityTracker::addEntity(std::shared_ptr e, int range, + int updateInterval) { + addEntity(e, range, updateInterval, false); } -void EntityTracker::addEntity(std::shared_ptr e, int range, int updateInterval, bool trackDeltas) -{ +void EntityTracker::addEntity(std::shared_ptr e, int range, + int updateInterval, bool trackDeltas) { if (range > maxRange) range = maxRange; - if (entityMap.find(e->entityId) != entityMap.end()) - { - assert(false); // Entity already tracked - } - if( e->entityId >= 2048 ) - { - __debugbreak(); - } - std::shared_ptr te = std::shared_ptr( new TrackedEntity(e, range, updateInterval, trackDeltas) ); - entities.insert(te); + if (entityMap.find(e->entityId) != entityMap.end()) { + assert(false); // Entity already tracked + } + if (e->entityId >= 2048) { + __debugbreak(); + } + std::shared_ptr te = std::shared_ptr( + new TrackedEntity(e, range, updateInterval, trackDeltas)); + entities.insert(te); entityMap[e->entityId] = te; te->updatePlayers(this, &level->players); } -// 4J - have split removeEntity into two bits - it used to do the equivalent of EntityTracker::removePlayer followed by EntityTracker::removeEntity. -// This is to allow us to now choose to remove the player as a "seenBy" only when the player has actually been removed from the level's own player array -void EntityTracker::removeEntity(std::shared_ptr e) -{ - AUTO_VAR(it, entityMap.find(e->entityId)); - if( it != entityMap.end() ) - { - std::shared_ptr te = it->second; - entityMap.erase(it); - entities.erase(te); - te->broadcastRemoved(); - } -} - -void EntityTracker::removePlayer(std::shared_ptr e) -{ - if (e->GetType() == eTYPE_SERVERPLAYER) - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - (*it)->removePlayer(player); - } +// 4J - have split removeEntity into two bits - it used to do the equivalent of +// EntityTracker::removePlayer followed by EntityTracker::removeEntity. This is +// to allow us to now choose to remove the player as a "seenBy" only when the +// player has actually been removed from the level's own player array +void EntityTracker::removeEntity(std::shared_ptr e) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + std::shared_ptr te = it->second; + entityMap.erase(it); + entities.erase(te); + te->broadcastRemoved(); } } -void EntityTracker::tick() -{ - std::vector > movedPlayers; - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - std::shared_ptr te = *it; - te->tick(this, &level->players); - if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER) - { - movedPlayers.push_back(std::dynamic_pointer_cast(te->e)); +void EntityTracker::removePlayer(std::shared_ptr e) { + if (e->GetType() == eTYPE_SERVERPLAYER) { + std::shared_ptr player = + std::dynamic_pointer_cast(e); + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + (*it)->removePlayer(player); } - } + } +} - // 4J Stu - If one player on a system is updated, then make sure they all are as they all have their - // range extended to include entities visible by any other player on the system - // Fix for #11194 - Gameplay: Host player and their split-screen avatars can become invisible and invulnerable to client. - MinecraftServer *server = MinecraftServer::getInstance(); - for( unsigned int i = 0; i < server->getPlayers()->players.size(); i++ ) - { - std::shared_ptr ep = server->getPlayers()->players[i]; - if( ep->dimension != level->dimension->id ) continue; +void EntityTracker::tick() { + std::vector > movedPlayers; + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + std::shared_ptr te = *it; + te->tick(this, &level->players); + if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER) { + movedPlayers.push_back( + std::dynamic_pointer_cast(te->e)); + } + } - if( ep->connection == NULL ) continue; - INetworkPlayer *thisPlayer = ep->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) continue; + // 4J Stu - If one player on a system is updated, then make sure they all + // are as they all have their range extended to include entities visible by + // any other player on the system Fix for #11194 - Gameplay: Host player and + // their split-screen avatars can become invisible and invulnerable to + // client. + MinecraftServer* server = MinecraftServer::getInstance(); + for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) { + std::shared_ptr ep = server->getPlayers()->players[i]; + if (ep->dimension != level->dimension->id) continue; - bool addPlayer = false; - for (unsigned int j = 0; j < movedPlayers.size(); j++) - { - std::shared_ptr sp = movedPlayers[j]; + if (ep->connection == NULL) continue; + INetworkPlayer* thisPlayer = ep->connection->getNetworkPlayer(); + if (thisPlayer == NULL) continue; - if( sp == ep ) break; + bool addPlayer = false; + for (unsigned int j = 0; j < movedPlayers.size(); j++) { + std::shared_ptr sp = movedPlayers[j]; - if(sp->connection == NULL) continue; - INetworkPlayer *otherPlayer = sp->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - addPlayer = true; - break; - } - } - if( addPlayer ) movedPlayers.push_back( ep ); - } + if (sp == ep) break; - for (unsigned int i = 0; i < movedPlayers.size(); i++) - { + if (sp->connection == NULL) continue; + INetworkPlayer* otherPlayer = sp->connection->getNetworkPlayer(); + if (otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer)) { + addPlayer = true; + break; + } + } + if (addPlayer) movedPlayers.push_back(ep); + } + + for (unsigned int i = 0; i < movedPlayers.size(); i++) { std::shared_ptr player = movedPlayers[i]; - if(player->connection == NULL) continue; - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - std::shared_ptr te = *it; - if (te->e != player) - { + if (player->connection == NULL) continue; + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + std::shared_ptr te = *it; + if (te->e != player) { te->updatePlayer(this, player); } - } + } } - // 4J Stu - We want to do this for dead players as they don't tick normally - for(AUTO_VAR(it, level->players.begin()); it != level->players.end(); ++it) - { - std::shared_ptr player = std::dynamic_pointer_cast(*it); - if(!player->isAlive()) - { - player->flushEntitiesToRemove(); - } - } + // 4J Stu - We want to do this for dead players as they don't tick normally + for (AUTO_VAR(it, level->players.begin()); it != level->players.end(); + ++it) { + std::shared_ptr player = + std::dynamic_pointer_cast(*it); + if (!player->isAlive()) { + player->flushEntitiesToRemove(); + } + } } -void EntityTracker::broadcast(std::shared_ptr e, std::shared_ptr packet) -{ - AUTO_VAR(it, entityMap.find( e->entityId )); - if( it != entityMap.end() ) - { - std::shared_ptr te = it->second; - te->broadcast(packet); - } +void EntityTracker::broadcast(std::shared_ptr e, + std::shared_ptr packet) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + std::shared_ptr te = it->second; + te->broadcast(packet); + } } -void EntityTracker::broadcastAndSend(std::shared_ptr e, std::shared_ptr packet) -{ - AUTO_VAR(it, entityMap.find( e->entityId )); - if( it != entityMap.end() ) - { - std::shared_ptr te = it->second; - te->broadcastAndSend(packet); - } +void EntityTracker::broadcastAndSend(std::shared_ptr e, + std::shared_ptr packet) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + std::shared_ptr te = it->second; + te->broadcastAndSend(packet); + } } -void EntityTracker::clear(std::shared_ptr serverPlayer) -{ - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) - { - std::shared_ptr te = *it; - te->clear(serverPlayer); - } +void EntityTracker::clear(std::shared_ptr serverPlayer) { + for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) { + std::shared_ptr te = *it; + te->clear(serverPlayer); + } } // AP added for Vita so the range can be increased once the level starts -void EntityTracker::updateMaxRange() -{ +void EntityTracker::updateMaxRange() { maxRange = level->getServer()->getPlayers()->getMaxRange(); } - -std::shared_ptr EntityTracker::getTracker(std::shared_ptr e) -{ - AUTO_VAR(it, entityMap.find(e->entityId)); - if( it != entityMap.end() ) - { - return it->second; - } - return nullptr; +std::shared_ptr EntityTracker::getTracker( + std::shared_ptr e) { + AUTO_VAR(it, entityMap.find(e->entityId)); + if (it != entityMap.end()) { + return it->second; + } + return nullptr; } \ No newline at end of file diff --git a/Minecraft.Client/Player/EntityTracker.h b/Minecraft.Client/Player/EntityTracker.h index d3d9a32fe..3a0fb8471 100644 --- a/Minecraft.Client/Player/EntityTracker.h +++ b/Minecraft.Client/Player/EntityTracker.h @@ -7,30 +7,30 @@ class TrackedEntity; class MinecraftServer; class Packet; - - -class EntityTracker -{ +class EntityTracker { private: - ServerLevel *level; - std::unordered_set > entities; - std::unordered_map , IntKeyHash2, IntKeyEq> entityMap; // was IntHashMap + ServerLevel* level; + std::unordered_set > entities; + std::unordered_map, IntKeyHash2, + IntKeyEq> + entityMap; // was IntHashMap int maxRange; public: - EntityTracker(ServerLevel *level); + EntityTracker(ServerLevel* level); void addEntity(std::shared_ptr e); void addEntity(std::shared_ptr e, int range, int updateInterval); - void addEntity(std::shared_ptr e, int range, int updateInterval, bool trackDeltas); + void addEntity(std::shared_ptr e, int range, int updateInterval, + bool trackDeltas); void removeEntity(std::shared_ptr e); - void removePlayer(std::shared_ptr e); // 4J added + void removePlayer(std::shared_ptr e); // 4J added void tick(); void broadcast(std::shared_ptr e, std::shared_ptr packet); - void broadcastAndSend(std::shared_ptr e, std::shared_ptr packet); + void broadcastAndSend(std::shared_ptr e, + std::shared_ptr packet); void clear(std::shared_ptr serverPlayer); - void updateMaxRange(); // AP added for Vita + void updateMaxRange(); // AP added for Vita - - // 4J-JEV: Added, needed access to tracked entity of a riders mount. - std::shared_ptr getTracker(std::shared_ptr entity); + // 4J-JEV: Added, needed access to tracked entity of a riders mount. + std::shared_ptr getTracker(std::shared_ptr entity); }; diff --git a/Minecraft.Client/Player/LocalPlayer.cpp b/Minecraft.Client/Player/LocalPlayer.cpp index 3d8a38895..fca63774d 100644 --- a/Minecraft.Client/Player/LocalPlayer.cpp +++ b/Minecraft.Client/Player/LocalPlayer.cpp @@ -53,241 +53,210 @@ #include "../../Minecraft.World/Stats/CommonStats.h" #endif +LocalPlayer::LocalPlayer(Minecraft* minecraft, Level* level, User* user, + int dimension) + : Player(level) { + flyX = flyY = flyZ = 0.0f; // 4J added + m_awardedThisSession = 0; + sprintTriggerTime = 0; + sprintTriggerRegisteredReturn = false; + twoJumpsRegistered = false; + sprintTime = 0; + m_uiInactiveTicks = 0; -LocalPlayer::LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dimension) : Player(level) -{ - flyX = flyY = flyZ = 0.0f; // 4J added - m_awardedThisSession = 0; - - sprintTriggerTime = 0; - sprintTriggerRegisteredReturn = false; - twoJumpsRegistered = false; - sprintTime = 0; - m_uiInactiveTicks=0; - - yBob = xBob = yBobO = xBobO = 0.0f; + yBob = xBob = yBobO = xBobO = 0.0f; this->minecraft = minecraft; this->dimension = dimension; - if (user != NULL && user->name.length() > 0) - { - customTextureUrl = L"http://s3.amazonaws.com/MinecraftSkins/" + user->name + L".png"; + if (user != NULL && user->name.length() > 0) { + customTextureUrl = + L"http://s3.amazonaws.com/MinecraftSkins/" + user->name + L".png"; } - if( user != NULL ) - { - this->name = user->name; - m_UUID = name; - //wprintf(L"Created LocalPlayer with name %ls\n", name.c_str() ); - // check to see if this player's xuid is in the list of special players - MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) - { - customTextureUrl=pMojangData->wchSkin; - } + if (user != NULL) { + this->name = user->name; + m_UUID = name; + // wprintf(L"Created LocalPlayer with name %ls\n", name.c_str() ); + // check to see if this player's xuid is in the list of special players + MOJANG_DATA* pMojangData = app.GetMojangDataForXuid(getOnlineXuid()); + if (pMojangData) { + customTextureUrl = pMojangData->wchSkin; + } + } + input = NULL; + m_iPad = -1; + m_iScreenSection = + C4JRender::VIEWPORT_TYPE_FULLSCREEN; // assume singleplayer default + m_bPlayerRespawned = false; + ullButtonsPressed = 0LL; + ullDpad_last = ullDpad_this = ullDpad_filtered = 0; - } - input = NULL; - m_iPad = -1; - m_iScreenSection=C4JRender::VIEWPORT_TYPE_FULLSCREEN; // assume singleplayer default - m_bPlayerRespawned=false; - ullButtonsPressed=0LL; - ullDpad_last = ullDpad_this = ullDpad_filtered = 0; + // 4J-PB - moved in from the minecraft structure + // ticks=0; + missTime = 0; + lastClickTick[0] = 0; + lastClickTick[1] = 0; + isRaining = false; - // 4J-PB - moved in from the minecraft structure - //ticks=0; - missTime=0; - lastClickTick[0] = 0; - lastClickTick[1] = 0; - isRaining=false; + m_bIsIdle = false; + m_iThirdPersonView = 0; - m_bIsIdle = false; - m_iThirdPersonView=0; + // 4J Stu - Added for telemetry + SetSessionTimerStart(); - // 4J Stu - Added for telemetry - SetSessionTimerStart(); + // 4J - added for auto repeat in creative mode + lastClickState = lastClick_invalid; + lastClickTolerance = 0.0f; - // 4J - added for auto repeat in creative mode - lastClickState = lastClick_invalid; - lastClickTolerance = 0.0f; - - m_bHasAwardedStayinFrosty = false; + m_bHasAwardedStayinFrosty = false; } -LocalPlayer::~LocalPlayer() -{ - if( this->input != NULL ) - delete input; +LocalPlayer::~LocalPlayer() { + if (this->input != NULL) delete input; } // 4J - added noEntityCubes parameter -void LocalPlayer::move(double xa, double ya, double za, bool noEntityCubes) -{ - if (ClientConstants::DEADMAU5_CAMERA_CHEATS) - { - if (shared_from_this() == minecraft->player && minecraft->options->isFlying) - { +void LocalPlayer::move(double xa, double ya, double za, bool noEntityCubes) { + if (ClientConstants::DEADMAU5_CAMERA_CHEATS) { + if (shared_from_this() == minecraft->player && + minecraft->options->isFlying) { noPhysics = true; - float tmp = walkDist; // update - calculateFlight((float) xa, (float) ya, (float) za); + float tmp = walkDist; // update + calculateFlight((float)xa, (float)ya, (float)za); fallDistance = 0.0f; yd = 0.0f; Player::move(flyX, flyY, flyZ, noEntityCubes); onGround = true; walkDist = tmp; - } - else - { + } else { noPhysics = false; Player::move(xa, ya, za, noEntityCubes); } - } - else - { + } else { Player::move(xa, ya, za, noEntityCubes); } - } -void LocalPlayer::calculateFlight(float xa, float ya, float za) -{ +void LocalPlayer::calculateFlight(float xa, float ya, float za) { xa = xa * minecraft->options->flySpeed; ya = 0; za = za * minecraft->options->flySpeed; - flyX = smoothFlyX.getNewDeltaValue(xa, .35f * minecraft->options->sensitivity); - flyY = smoothFlyY.getNewDeltaValue(ya, .35f * minecraft->options->sensitivity); - flyZ = smoothFlyZ.getNewDeltaValue(za, .35f * minecraft->options->sensitivity); - + flyX = + smoothFlyX.getNewDeltaValue(xa, .35f * minecraft->options->sensitivity); + flyY = + smoothFlyY.getNewDeltaValue(ya, .35f * minecraft->options->sensitivity); + flyZ = + smoothFlyZ.getNewDeltaValue(za, .35f * minecraft->options->sensitivity); } -void LocalPlayer::serverAiStep() -{ +void LocalPlayer::serverAiStep() { Player::serverAiStep(); - - if( abilities.flying && abilities.mayfly ) - { - // snap y rotation for flying to nearest 90 degrees in world space - float fMag = sqrtf(input->xa * input->xa + input->ya * input->ya); - // Don't bother for tiny inputs - if( fMag >= 0.1f ) - { - // Get angle (in player rotated space) of input controls - float yRotInput = atan2f(input->ya, input->xa) * (180.0f / PI); - // Now get in world space - float yRotFinal = yRotInput + yRot; - // Snap this to nearest 90 degrees - float yRotSnapped = floorf((yRotFinal / 45.0f) + 0.5f) * 45.0f; - // Find out how much we had to move to do this snap - float yRotDiff = yRotSnapped - yRotFinal; - // Apply the same difference to the player rotated space angle - float yRotInputAdjust = yRotInput + yRotDiff; - - // Calculate final x/y player-space movement required - this->xxa = cos(yRotInputAdjust * ( PI / 180.0f) ) * fMag; - this->yya = sin(yRotInputAdjust * ( PI / 180.0f) ) * fMag; - } - else - { - this->xxa = input->xa; - this->yya = input->ya; - } - } - else - { - this->xxa = input->xa; - this->yya = input->ya; - } + + if (abilities.flying && abilities.mayfly) { + // snap y rotation for flying to nearest 90 degrees in world space + float fMag = sqrtf(input->xa * input->xa + input->ya * input->ya); + // Don't bother for tiny inputs + if (fMag >= 0.1f) { + // Get angle (in player rotated space) of input controls + float yRotInput = atan2f(input->ya, input->xa) * (180.0f / PI); + // Now get in world space + float yRotFinal = yRotInput + yRot; + // Snap this to nearest 90 degrees + float yRotSnapped = floorf((yRotFinal / 45.0f) + 0.5f) * 45.0f; + // Find out how much we had to move to do this snap + float yRotDiff = yRotSnapped - yRotFinal; + // Apply the same difference to the player rotated space angle + float yRotInputAdjust = yRotInput + yRotDiff; + + // Calculate final x/y player-space movement required + this->xxa = cos(yRotInputAdjust * (PI / 180.0f)) * fMag; + this->yya = sin(yRotInputAdjust * (PI / 180.0f)) * fMag; + } else { + this->xxa = input->xa; + this->yya = input->ya; + } + } else { + this->xxa = input->xa; + this->yya = input->ya; + } this->jumping = input->jumping; - yBobO = yBob; - xBobO = xBob; - xBob += (xRot - xBob) * 0.5; - yBob += (yRot - yBob) * 0.5; + yBobO = yBob; + xBobO = xBob; + xBob += (xRot - xBob) * 0.5; + yBob += (yRot - yBob) * 0.5; - // TODO 4J - Remove - //if (input->jumping) - // mapPlayerChunk(8); + // TODO 4J - Remove + // if (input->jumping) + // mapPlayerChunk(8); } -bool LocalPlayer::isEffectiveAI() -{ - return true; -} +bool LocalPlayer::isEffectiveAI() { return true; } -void LocalPlayer::aiStep() -{ - if (sprintTime > 0) - { - sprintTime--; - if (sprintTime == 0) - { - setSprinting(false); - } - } - if (sprintTriggerTime > 0) sprintTriggerTime--; - if (minecraft->gameMode->isCutScene()) - { - x = z = 0.5; - x = 0; - z = 0; - yRot = tickCount / 12.0f; - xRot = 10; - y = 68.5; - return; - } +void LocalPlayer::aiStep() { + if (sprintTime > 0) { + sprintTime--; + if (sprintTime == 0) { + setSprinting(false); + } + } + if (sprintTriggerTime > 0) sprintTriggerTime--; + if (minecraft->gameMode->isCutScene()) { + x = z = 0.5; + x = 0; + z = 0; + yRot = tickCount / 12.0f; + xRot = 10; + y = 68.5; + return; + } oPortalTime = portalTime; - if (isInsidePortal) - { - if (!level->isClientSide) - { + if (isInsidePortal) { + if (!level->isClientSide) { if (riding != NULL) this->ride(nullptr); } if (minecraft->screen != NULL) minecraft->setScreen(NULL); - if (portalTime == 0) - { - minecraft->soundEngine->playUI(eSoundType_PORTAL_TRIGGER, 1, random->nextFloat() * 0.4f + 0.8f); + if (portalTime == 0) { + minecraft->soundEngine->playUI(eSoundType_PORTAL_TRIGGER, 1, + random->nextFloat() * 0.4f + 0.8f); } portalTime += 1 / 80.0f; - if (portalTime >= 1) - { + if (portalTime >= 1) { portalTime = 1; } isInsidePortal = false; - } - else if (hasEffect(MobEffect::confusion) && getEffect(MobEffect::confusion)->getDuration() > (SharedConstants::TICKS_PER_SECOND * 3)) - { - portalTime += 1 / 150.0f; - if (portalTime > 1) - { - portalTime = 1; - } - } - else - { + } else if (hasEffect(MobEffect::confusion) && + getEffect(MobEffect::confusion)->getDuration() > + (SharedConstants::TICKS_PER_SECOND * 3)) { + portalTime += 1 / 150.0f; + if (portalTime > 1) { + portalTime = 1; + } + } else { if (portalTime > 0) portalTime -= 1 / 20.0f; if (portalTime < 0) portalTime = 0; } if (changingDimensionDelay > 0) changingDimensionDelay--; - bool wasJumping = input->jumping; - float runTreshold = 0.8f; + bool wasJumping = input->jumping; + float runTreshold = 0.8f; - bool wasRunning = input->ya >= runTreshold; - //input->tick( std::dynamic_pointer_cast( shared_from_this() ) ); - // 4J-PB - make it a localplayer - input->tick( this ); - if (isUsingItem()) - { - input->xa *= 0.2f; - input->ya *= 0.2f; - sprintTriggerTime = 0; - } - // this.heightOffset = input.sneaking?1.30f:1.62f; // 4J - this was already commented out - if (input->sneaking) // 4J - removed - TODO replace - { + bool wasRunning = input->ya >= runTreshold; + // input->tick( std::dynamic_pointer_cast( shared_from_this() ) ); + // 4J-PB - make it a localplayer + input->tick(this); + if (isUsingItem()) { + input->xa *= 0.2f; + input->ya *= 0.2f; + sprintTriggerTime = 0; + } + // this.heightOffset = input.sneaking?1.30f:1.62f; // 4J - this was already + // commented out + if (input->sneaking) // 4J - removed - TODO replace + { if (ySlideOffset < 0.2f) ySlideOffset = 0.2f; } @@ -296,777 +265,740 @@ void LocalPlayer::aiStep() checkInTile(x + bbWidth * 0.35, bb->y0 + 0.5, z - bbWidth * 0.35); checkInTile(x + bbWidth * 0.35, bb->y0 + 0.5, z + bbWidth * 0.35); - bool enoughFoodToSprint = getFoodData()->getFoodLevel() > FoodConstants::MAX_FOOD * FoodConstants::FOOD_SATURATION_LOW; + bool enoughFoodToSprint = + getFoodData()->getFoodLevel() > + FoodConstants::MAX_FOOD * FoodConstants::FOOD_SATURATION_LOW; - // 4J Stu - If we can fly, then we should be able to sprint without requiring food. This is particularly a problem for people who save a survival - // world with low food, then reload it in creative. - if(abilities.mayfly || isAllowedToFly() ) enoughFoodToSprint = true; + // 4J Stu - If we can fly, then we should be able to sprint without + // requiring food. This is particularly a problem for people who save a + // survival world with low food, then reload it in creative. + if (abilities.mayfly || isAllowedToFly()) enoughFoodToSprint = true; - // 4J - altered this slightly to make sure that the joypad returns to below returnTreshold in between registering two movements up to runThreshold - if (onGround && !isSprinting() && enoughFoodToSprint && !isUsingItem() && !hasEffect(MobEffect::blindness)) - { - if( !wasRunning && (input->ya >= runTreshold) ) - { - if (sprintTriggerTime == 0) - { - sprintTriggerTime = 7; - sprintTriggerRegisteredReturn = false; - } - else - { - if( sprintTriggerRegisteredReturn ) - { - setSprinting(true); - sprintTriggerTime = 0; - sprintTriggerRegisteredReturn = false; - } - } - } - else if( ( sprintTriggerTime > 0 ) && ( input->ya == 0.0f ) ) // ya of 0.0f here signifies that we have returned to the deadzone - { - sprintTriggerRegisteredReturn = true; - } - else if (input->sprintKey) - { - setSprinting(true); - } - } - if (isSneaking()) sprintTriggerTime = 0; - // 4J-PB - try not stopping sprint on collision - //if (isSprinting() && (input->ya < runTreshold || horizontalCollision || !enoughFoodToSprint)) - if (isSprinting() && ((input->ya < runTreshold && !input->sprintKey) || !enoughFoodToSprint)) - { - setSprinting(false); - } + // 4J - altered this slightly to make sure that the joypad returns to below + // returnTreshold in between registering two movements up to runThreshold + if (onGround && !isSprinting() && enoughFoodToSprint && !isUsingItem() && + !hasEffect(MobEffect::blindness)) { + if (!wasRunning && (input->ya >= runTreshold)) { + if (sprintTriggerTime == 0) { + sprintTriggerTime = 7; + sprintTriggerRegisteredReturn = false; + } else { + if (sprintTriggerRegisteredReturn) { + setSprinting(true); + sprintTriggerTime = 0; + sprintTriggerRegisteredReturn = false; + } + } + } else if ((sprintTriggerTime > 0) && + (input->ya == 0.0f)) // ya of 0.0f here signifies that we + // have returned to the deadzone + { + sprintTriggerRegisteredReturn = true; + } else if (input->sprintKey) { + setSprinting(true); + } + } + if (isSneaking()) sprintTriggerTime = 0; + // 4J-PB - try not stopping sprint on collision + // if (isSprinting() && (input->ya < runTreshold || horizontalCollision || + // !enoughFoodToSprint)) + if (isSprinting() && ((input->ya < runTreshold && !input->sprintKey) || + !enoughFoodToSprint)) { + setSprinting(false); + } - // 4J Stu - Fix for #52705 - Customer Encountered: Player can fly in bed while being in Creative mode. - if (!isSleeping() && (abilities.mayfly || isAllowedToFly() )) - { - // 4J altered to require jump button to released after being tapped twice to trigger move between flying / not flying - if (!wasJumping && input->jumping) - { - if (jumpTriggerTime == 0) - { - jumpTriggerTime = 10; // was 7 - twoJumpsRegistered = false; - } - else - { - twoJumpsRegistered = true; - } - } - else if( ( !input->jumping ) && ( jumpTriggerTime > 0 ) && twoJumpsRegistered ) - { + // 4J Stu - Fix for #52705 - Customer Encountered: Player can fly in bed + // while being in Creative mode. + if (!isSleeping() && (abilities.mayfly || isAllowedToFly())) { + // 4J altered to require jump button to released after being tapped + // twice to trigger move between flying / not flying + if (!wasJumping && input->jumping) { + if (jumpTriggerTime == 0) { + jumpTriggerTime = 10; // was 7 + twoJumpsRegistered = false; + } else { + twoJumpsRegistered = true; + } + } else if ((!input->jumping) && (jumpTriggerTime > 0) && + twoJumpsRegistered) { #ifndef _CONTENT_PACKAGE - printf("flying was %s\n", abilities.flying ? "on" : "off"); + printf("flying was %s\n", abilities.flying ? "on" : "off"); #endif - abilities.flying = !abilities.flying; + abilities.flying = !abilities.flying; #ifndef _CONTENT_PACKAGE - printf("flying is %s\n", abilities.flying ? "on" : "off"); + printf("flying is %s\n", abilities.flying ? "on" : "off"); #endif - jumpTriggerTime = 0; - twoJumpsRegistered = false; - if( abilities.flying ) input->sneaking = false; // 4J added - would we ever intentially want to go into flying mode whilst sneaking? - } - } - else if(abilities.flying) - { + jumpTriggerTime = 0; + twoJumpsRegistered = false; + if (abilities.flying) + input->sneaking = + false; // 4J added - would we ever intentially want to go + // into flying mode whilst sneaking? + } + } else if (abilities.flying) { #ifdef _DEBUG_MENUS_ENABLED - if(!abilities.debugflying) + if (!abilities.debugflying) #endif - { - abilities.flying = false; - } - } - + { + abilities.flying = false; + } + } - if (abilities.flying) - { - // yd = 0; - // 4J - note that the 0.42 added for going down is to make it match with what happens when you jump - jumping itself adds 0.42 to yd in Mob::jumpFromGround - if (ullButtonsPressed & (1LL<jumping) - { - noJumpDelay = 0; - yd += 0.15; - } + if (abilities.flying) { + // yd = 0; + // 4J - note that the 0.42 added for going down is to make it match with + // what happens when you jump - jumping itself adds 0.42 to yd in + // Mob::jumpFromGround + if (ullButtonsPressed & (1LL << MINECRAFT_ACTION_SNEAK_TOGGLE)) + yd -= + (0.15 + 0.42); // 4J - for flying mode, + // MINECRAFT_ACTION_SNEAK_TOGGLE isn't a toggle + // but just indicates that this button is down + if (input->jumping) { + noJumpDelay = 0; + yd += 0.15; + } - // snap y rotation to nearest 90 degree axis aligned value - float yRotSnapped = floorf((yRot / 90.0f) + 0.5f) * 90.0f; + // snap y rotation to nearest 90 degree axis aligned value + float yRotSnapped = floorf((yRot / 90.0f) + 0.5f) * 90.0f; - if(InputManager.GetJoypadMapVal(m_iPad) == 0) - { - if( ullDpad_filtered & (1LL<options->isFlying ) - { - Vec3* viewVector = getViewVector(1.0f); - - // 4J-PB - To let the player build easily while flying, we need to change this - -#ifdef _DEBUG_MENUS_ENABLED - if(abilities.debugflying) - { - flyX = (float)viewVector->x * input->ya; - flyY = (float)viewVector->y * input->ya; - flyZ = (float)viewVector->z * input->ya; - } - else -#endif - { - if( isSprinting() ) - { - // Accelrate up to full speed if we are sprinting, moving in the direction of the view vector - flyX = (float)viewVector->x * input->ya; - flyY = (float)viewVector->y * input->ya; - flyZ = (float)viewVector->z * input->ya; - - float scale = ((float)(SPRINT_DURATION - sprintTime))/10.0f; - scale = scale * scale; - if ( scale > 1.0f ) scale = 1.0f; - flyX *= scale; - flyY *= scale; - flyZ *= scale; - } - else - { - flyX = 0.0f; - flyY = 0.0f; - flyZ = 0.0f; - if( ullDpad_filtered & (1LL< PLAYER_IDLE_TIME ) - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_IDLE,false); - m_bIsIdle = true; - } - else if ( m_bIsIdle && InputManager.GetIdleSeconds( m_iPad ) < PLAYER_IDLE_TIME ) - { - // Are we offline or online, and how many players are there - if(g_NetworkManager.GetPlayerCount()>1) - { - // only do it for this player here - each player will run this code - if(g_NetworkManager.IsLocalGame()) - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYEROFFLINE,false); - } - else - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYER,false); - } - } - else - { - if(g_NetworkManager.IsLocalGame()) - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYER_1POFFLINE,false); - } - else - { - ProfileManager.SetCurrentGameActivity(m_iPad,CONTEXT_PRESENCE_MULTIPLAYER_1P,false); - } - } - updateRichPresence(); - m_bIsIdle = false; - } -} + if (abilities.flying) // minecraft->options->isFlying ) + { + Vec3* viewVector = getViewVector(1.0f); -void LocalPlayer::changeDimension(int i) -{ - if (!level->isClientSide) - { - if (dimension == 1 && i == 1) - { - awardStat(GenericStats::winGame(), GenericStats::param_noArgs()); - //minecraft.setScreen(new WinScreen()); -#ifndef _CONTENT_PACKAGE - app.DebugPrintf("LocalPlayer::changeDimension from 1 to 1 but WinScreen has not been implemented.\n"); - __debugbreak(); + // 4J-PB - To let the player build easily while flying, we need to + // change this + +#ifdef _DEBUG_MENUS_ENABLED + if (abilities.debugflying) { + flyX = (float)viewVector->x * input->ya; + flyY = (float)viewVector->y * input->ya; + flyZ = (float)viewVector->z * input->ya; + } else #endif - } - else - { - awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); + { + if (isSprinting()) { + // Accelrate up to full speed if we are sprinting, moving in the + // direction of the view vector + flyX = (float)viewVector->x * input->ya; + flyY = (float)viewVector->y * input->ya; + flyZ = (float)viewVector->z * input->ya; - minecraft->soundEngine->playUI(eSoundType_PORTAL_TRAVEL, 1, random->nextFloat() * 0.4f + 0.8f); - } - } + float scale = ((float)(SPRINT_DURATION - sprintTime)) / 10.0f; + scale = scale * scale; + if (scale > 1.0f) scale = 1.0f; + flyX *= scale; + flyY *= scale; + flyZ *= scale; + } else { + flyX = 0.0f; + flyY = 0.0f; + flyZ = 0.0f; + if (ullDpad_filtered & (1LL << MINECRAFT_ACTION_DPAD_UP)) { + flyY = 0.1f; + } + if (ullDpad_filtered & (1LL << MINECRAFT_ACTION_DPAD_DOWN)) { + flyY = -0.1f; + } + } + } + + Player::move(flyX, flyY, flyZ); + + fallDistance = 0.0f; + yd = 0.0f; + onGround = true; + } + + // Check if the player is idle and the rich presence needs updated + if (!m_bIsIdle && InputManager.GetIdleSeconds(m_iPad) > PLAYER_IDLE_TIME) { + ProfileManager.SetCurrentGameActivity(m_iPad, CONTEXT_PRESENCE_IDLE, + false); + m_bIsIdle = true; + } else if (m_bIsIdle && + InputManager.GetIdleSeconds(m_iPad) < PLAYER_IDLE_TIME) { + // Are we offline or online, and how many players are there + if (g_NetworkManager.GetPlayerCount() > 1) { + // only do it for this player here - each player will run this code + if (g_NetworkManager.IsLocalGame()) { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYEROFFLINE, false); + } else { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYER, false); + } + } else { + if (g_NetworkManager.IsLocalGame()) { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYER_1POFFLINE, false); + } else { + ProfileManager.SetCurrentGameActivity( + m_iPad, CONTEXT_PRESENCE_MULTIPLAYER_1P, false); + } + } + updateRichPresence(); + m_bIsIdle = false; + } } -float LocalPlayer::getFieldOfViewModifier() -{ - float targetFov = 1.0f; +void LocalPlayer::changeDimension(int i) { + if (!level->isClientSide) { + if (dimension == 1 && i == 1) { + awardStat(GenericStats::winGame(), GenericStats::param_noArgs()); + // minecraft.setScreen(new WinScreen()); +#ifndef _CONTENT_PACKAGE + app.DebugPrintf( + "LocalPlayer::changeDimension from 1 to 1 but WinScreen has " + "not been implemented.\n"); + __debugbreak(); +#endif + } else { + awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); - // modify for movement - if (abilities.flying) targetFov *= 1.1f; - targetFov *= ((walkingSpeed * getWalkingSpeedModifier()) / defaultWalkSpeed + 1) / 2; - - // modify for bow =) - if (isUsingItem() && getUseItem()->id == Item::bow->id) - { - int ticksHeld = getTicksUsingItem(); - float scale = (float) ticksHeld / BowItem::MAX_DRAW_DURATION; - if (scale > 1) - { - scale = 1; - } - else - { - scale *= scale; - } - targetFov *= 1.0f - scale * .15f; - } - - return targetFov; + minecraft->soundEngine->playUI(eSoundType_PORTAL_TRAVEL, 1, + random->nextFloat() * 0.4f + 0.8f); + } + } } -void LocalPlayer::addAdditonalSaveData(CompoundTag *entityTag) -{ +float LocalPlayer::getFieldOfViewModifier() { + float targetFov = 1.0f; + + // modify for movement + if (abilities.flying) targetFov *= 1.1f; + targetFov *= + ((walkingSpeed * getWalkingSpeedModifier()) / defaultWalkSpeed + 1) / 2; + + // modify for bow =) + if (isUsingItem() && getUseItem()->id == Item::bow->id) { + int ticksHeld = getTicksUsingItem(); + float scale = (float)ticksHeld / BowItem::MAX_DRAW_DURATION; + if (scale > 1) { + scale = 1; + } else { + scale *= scale; + } + targetFov *= 1.0f - scale * .15f; + } + + return targetFov; +} + +void LocalPlayer::addAdditonalSaveData(CompoundTag* entityTag) { Player::addAdditonalSaveData(entityTag); entityTag->putInt(L"Score", score); } -void LocalPlayer::readAdditionalSaveData(CompoundTag *entityTag) -{ +void LocalPlayer::readAdditionalSaveData(CompoundTag* entityTag) { Player::readAdditionalSaveData(entityTag); score = entityTag->getInt(L"Score"); } -void LocalPlayer::closeContainer() -{ +void LocalPlayer::closeContainer() { Player::closeContainer(); minecraft->setScreen(NULL); - // 4J - Close any xui here - // Fix for #9164 - CRASH: MP: Title crashes upon opening a chest and having another user destroy it. - ui.PlayUISFX(eSFX_Back); - ui.CloseUIScenes( m_iPad ); + // 4J - Close any xui here + // Fix for #9164 - CRASH: MP: Title crashes upon opening a chest and having + // another user destroy it. + ui.PlayUISFX(eSFX_Back); + ui.CloseUIScenes(m_iPad); } -void LocalPlayer::openTextEdit(std::shared_ptr sign) -{ - bool success = app.LoadSignEntryMenu(GetXboxPad(), sign ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new TextEditScreen(sign)); +void LocalPlayer::openTextEdit(std::shared_ptr sign) { + bool success = app.LoadSignEntryMenu(GetXboxPad(), sign); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new TextEditScreen(sign)); } -bool LocalPlayer::openContainer(std::shared_ptr container) -{ - bool success = app.LoadContainerMenu(GetXboxPad(), inventory, container ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new ContainerScreen(inventory, container)); - return success; +bool LocalPlayer::openContainer(std::shared_ptr container) { + bool success = app.LoadContainerMenu(GetXboxPad(), inventory, container); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new ContainerScreen(inventory, container)); + return success; } -bool LocalPlayer::startCrafting(int x, int y, int z) -{ - bool success = app.LoadCrafting3x3Menu(GetXboxPad(), std::dynamic_pointer_cast( shared_from_this() ), x, y, z ); - if( success ) ui.PlayUISFX(eSFX_Press); - //app.LoadXuiCraftMenu(0,inventory, level, x, y, z); - //minecraft->setScreen(new CraftingScreen(inventory, level, x, y, z)); - return success; +bool LocalPlayer::startCrafting(int x, int y, int z) { + bool success = app.LoadCrafting3x3Menu( + GetXboxPad(), + std::dynamic_pointer_cast(shared_from_this()), x, y, z); + if (success) ui.PlayUISFX(eSFX_Press); + // app.LoadXuiCraftMenu(0,inventory, level, x, y, z); + // minecraft->setScreen(new CraftingScreen(inventory, level, x, y, z)); + return success; } -bool LocalPlayer::startEnchanting(int x, int y, int z) -{ - bool success = app.LoadEnchantingMenu(GetXboxPad(), inventory, x, y, z, level ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new EnchantmentScreen(inventory, level, x, y, z)); - return success; +bool LocalPlayer::startEnchanting(int x, int y, int z) { + bool success = + app.LoadEnchantingMenu(GetXboxPad(), inventory, x, y, z, level); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new EnchantmentScreen(inventory, level, x, y, z)); + return success; } -bool LocalPlayer::startRepairing(int x, int y, int z) -{ - bool success = app.LoadRepairingMenu(GetXboxPad(), inventory, level, x, y, z ); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new RepairScreen(inventory, level, x, y, z)); - return success; +bool LocalPlayer::startRepairing(int x, int y, int z) { + bool success = + app.LoadRepairingMenu(GetXboxPad(), inventory, level, x, y, z); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new RepairScreen(inventory, level, x, y, z)); + return success; } -bool LocalPlayer::openFurnace(std::shared_ptr furnace) -{ - bool success = app.LoadFurnaceMenu(GetXboxPad(),inventory, furnace); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new FurnaceScreen(inventory, furnace)); - return success; +bool LocalPlayer::openFurnace(std::shared_ptr furnace) { + bool success = app.LoadFurnaceMenu(GetXboxPad(), inventory, furnace); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new FurnaceScreen(inventory, furnace)); + return success; } -bool LocalPlayer::openBrewingStand(std::shared_ptr brewingStand) -{ - bool success = app.LoadBrewingStandMenu(GetXboxPad(),inventory, brewingStand); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new BrewingStandScreen(inventory, brewingStand)); - return success; +bool LocalPlayer::openBrewingStand( + std::shared_ptr brewingStand) { + bool success = + app.LoadBrewingStandMenu(GetXboxPad(), inventory, brewingStand); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new BrewingStandScreen(inventory, brewingStand)); + return success; } -bool LocalPlayer::openTrap(std::shared_ptr trap) -{ - bool success = app.LoadTrapMenu(GetXboxPad(),inventory, trap); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft->setScreen(new TrapScreen(inventory, trap)); - return success; +bool LocalPlayer::openTrap(std::shared_ptr trap) { + bool success = app.LoadTrapMenu(GetXboxPad(), inventory, trap); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft->setScreen(new TrapScreen(inventory, trap)); + return success; } -bool LocalPlayer::openTrading(std::shared_ptr traderTarget) -{ - bool success = app.LoadTradingMenu(GetXboxPad(),inventory, traderTarget, level); - if( success ) ui.PlayUISFX(eSFX_Press); - //minecraft.setScreen(new MerchantScreen(inventory, traderTarget, level)); - return success; +bool LocalPlayer::openTrading(std::shared_ptr traderTarget) { + bool success = + app.LoadTradingMenu(GetXboxPad(), inventory, traderTarget, level); + if (success) ui.PlayUISFX(eSFX_Press); + // minecraft.setScreen(new MerchantScreen(inventory, traderTarget, level)); + return success; } -void LocalPlayer::crit(std::shared_ptr e) -{ - std::shared_ptr critParticle = std::shared_ptr( new CritParticle((Level *)minecraft->level, e) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add(critParticle); +void LocalPlayer::crit(std::shared_ptr e) { + std::shared_ptr critParticle = std::shared_ptr( + new CritParticle((Level*)minecraft->level, e)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); } -void LocalPlayer::magicCrit(std::shared_ptr e) -{ - std::shared_ptr critParticle = std::shared_ptr( new CritParticle((Level *)minecraft->level, e, eParticleType_magicCrit) ); - critParticle->CritParticlePostConstructor(); - minecraft->particleEngine->add(critParticle); +void LocalPlayer::magicCrit(std::shared_ptr e) { + std::shared_ptr critParticle = std::shared_ptr( + new CritParticle((Level*)minecraft->level, e, eParticleType_magicCrit)); + critParticle->CritParticlePostConstructor(); + minecraft->particleEngine->add(critParticle); } -void LocalPlayer::take(std::shared_ptr e, int orgCount) -{ - minecraft->particleEngine->add( std::shared_ptr( new TakeAnimationParticle((Level *)minecraft->level, e, shared_from_this(), -0.5f) ) ); +void LocalPlayer::take(std::shared_ptr e, int orgCount) { + minecraft->particleEngine->add( + std::shared_ptr(new TakeAnimationParticle( + (Level*)minecraft->level, e, shared_from_this(), -0.5f))); } -void LocalPlayer::chat(const std::wstring& message) -{ -} +void LocalPlayer::chat(const std::wstring& message) {} -bool LocalPlayer::isSneaking() -{ - return input->sneaking && !m_isSleeping; -} +bool LocalPlayer::isSneaking() { return input->sneaking && !m_isSleeping; } -void LocalPlayer::hurtTo(int newHealth, ETelemetryChallenges damageSource) -{ +void LocalPlayer::hurtTo(int newHealth, ETelemetryChallenges damageSource) { int dmg = getHealth() - newHealth; - if (dmg <= 0) - { + if (dmg <= 0) { setHealth(newHealth); - if (dmg < 0) - { + if (dmg < 0) { invulnerableTime = invulnerableDuration / 2; } - } - else - { + } else { lastHurt = dmg; setHealth(getHealth()); invulnerableTime = invulnerableDuration; - actuallyHurt(DamageSource::genericSource,dmg); + actuallyHurt(DamageSource::genericSource, dmg); hurtTime = hurtDuration = 10; } + if (this->health <= 0) { + int deathTime = (int)(level->getTime() % Level::TICKS_PER_DAY) / 1000; + int carriedId = + inventory->getSelected() == NULL ? 0 : inventory->getSelected()->id; + TelemetryManager->RecordPlayerDiedOrFailed(GetXboxPad(), 0, y, 0, 0, + carriedId, 0, damageSource); - if( this->health <= 0) - { - int deathTime = (int)(level->getTime() % Level::TICKS_PER_DAY)/1000; - int carriedId = inventory->getSelected() == NULL ? 0 : inventory->getSelected()->id; - TelemetryManager->RecordPlayerDiedOrFailed(GetXboxPad(), 0, y, 0, 0, carriedId, 0, damageSource); - - // if there are any xuiscenes up for this player, close them - if(ui.GetMenuDisplayed(GetXboxPad())) - { - ui.CloseUIScenes(GetXboxPad()); - } - } - -} - -void LocalPlayer::respawn() -{ - // Select the right payer to respawn - minecraft->respawnPlayer(GetXboxPad(), 0, 0); -} - -void LocalPlayer::animateRespawn() -{ -// Player.animateRespawn(this, level); -} - -void LocalPlayer::displayClientMessage(int messageId) -{ - minecraft->gui->displayClientMessage(messageId, GetXboxPad()); -} - -void LocalPlayer::awardStat(Stat *stat, byteArray param) -{ -#ifdef _DURANGO - // 4J-JEV: Maybe we want to fine tune this later? #TODO - if ( !ProfileManager.IsGuest(GetXboxPad()) - && app.CanRecordStatsAndAchievements() - && ProfileManager.IsFullVersion() - ) - { - stat->handleParamBlob(std::dynamic_pointer_cast(shared_from_this()), param); - } - delete [] param.data; -#else - int count = CommonStats::readParam(param); - delete [] param.data; - - if (!app.CanRecordStatsAndAchievements()) return; - if (stat == NULL) return; - - if (stat->isAchievement()) - { - Achievement *ach = (Achievement *) stat; - // 4J-PB - changed to attempt to award everytime - the award may need a storage device, so needs a primary player, and the player may not have been a primary player when they first 'got' the award - // so let the award manager figure it out - //if (!minecraft->stats[m_iPad]->hasTaken(ach)) - { - // 4J-PB - Don't display the java popup - //minecraft->achievementPopup->popup(ach); - - // 4J Stu - Added this function in the libraries as some achievements don't get awarded to all players - // e.g. Splitscreen players cannot get theme/avatar/gamerpic and Trial players cannot get any - // This causes some extreme flooding of some awards - if(ProfileManager.CanBeAwarded(m_iPad, ach->getAchievementID() ) ) - { - // 4J Stu - We don't (currently) care about the gamerscore, so setting to a default of 0 points - TelemetryManager->RecordAchievementUnlocked(m_iPad,ach->getAchievementID(),0); - - // 4J Stu - Some awards cause a menu to popup. This can be bad, especially if you are surrounded by mobs! - // We cannot pause the game unless in offline single player, but lets at least do it then - if( g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && ProfileManager.GetAwardType(ach->getAchievementID() ) != eAwardType_Achievement ) - { - ui.CloseUIScenes(m_iPad); - ui.NavigateToScene(m_iPad,eUIScene_PauseMenu); - } - } - - // 4J-JEV: To stop spamming trophies. - unsigned long long achBit = ((unsigned long long)1) << ach->getAchievementID(); - if ( !(achBit & m_awardedThisSession) ) - { - ProfileManager.Award(m_iPad, ach->getAchievementID()); - if (ProfileManager.IsFullVersion()) - m_awardedThisSession |= achBit; - } + // if there are any xuiscenes up for this player, close them + if (ui.GetMenuDisplayed(GetXboxPad())) { + ui.CloseUIScenes(GetXboxPad()); } - minecraft->stats[m_iPad]->award(stat, level->difficulty, count); } - else - { - // 4J : WESTY : Added for new achievements. - StatsCounter* pStats = minecraft->stats[m_iPad]; +} + +void LocalPlayer::respawn() { + // Select the right payer to respawn + minecraft->respawnPlayer(GetXboxPad(), 0, 0); +} + +void LocalPlayer::animateRespawn() { + // Player.animateRespawn(this, level); +} + +void LocalPlayer::displayClientMessage(int messageId) { + minecraft->gui->displayClientMessage(messageId, GetXboxPad()); +} + +void LocalPlayer::awardStat(Stat* stat, byteArray param) { +#ifdef _DURANGO + // 4J-JEV: Maybe we want to fine tune this later? #TODO + if (!ProfileManager.IsGuest(GetXboxPad()) && + app.CanRecordStatsAndAchievements() && ProfileManager.IsFullVersion()) { + stat->handleParamBlob( + std::dynamic_pointer_cast(shared_from_this()), param); + } + delete[] param.data; +#else + int count = CommonStats::readParam(param); + delete[] param.data; + + if (!app.CanRecordStatsAndAchievements()) return; + if (stat == NULL) return; + + if (stat->isAchievement()) { + Achievement* ach = (Achievement*)stat; + // 4J-PB - changed to attempt to award everytime - the award may need a + // storage device, so needs a primary player, and the player may not + // have been a primary player when they first 'got' the award so let the + // award manager figure it out + // if (!minecraft->stats[m_iPad]->hasTaken(ach)) + { + // 4J-PB - Don't display the java popup + // minecraft->achievementPopup->popup(ach); + + // 4J Stu - Added this function in the libraries as some + // achievements don't get awarded to all players e.g. Splitscreen + // players cannot get theme/avatar/gamerpic and Trial players cannot + // get any This causes some extreme flooding of some awards + if (ProfileManager.CanBeAwarded(m_iPad, ach->getAchievementID())) { + // 4J Stu - We don't (currently) care about the gamerscore, so + // setting to a default of 0 points + TelemetryManager->RecordAchievementUnlocked( + m_iPad, ach->getAchievementID(), 0); + + // 4J Stu - Some awards cause a menu to popup. This can be bad, + // especially if you are surrounded by mobs! We cannot pause the + // game unless in offline single player, but lets at least do it + // then + if (g_NetworkManager.IsLocalGame() && + g_NetworkManager.GetPlayerCount() == 1 && + ProfileManager.GetAwardType(ach->getAchievementID()) != + eAwardType_Achievement) { + ui.CloseUIScenes(m_iPad); + ui.NavigateToScene(m_iPad, eUIScene_PauseMenu); + } + } + + // 4J-JEV: To stop spamming trophies. + unsigned long long achBit = ((unsigned long long)1) + << ach->getAchievementID(); + if (!(achBit & m_awardedThisSession)) { + ProfileManager.Award(m_iPad, ach->getAchievementID()); + if (ProfileManager.IsFullVersion()) + m_awardedThisSession |= achBit; + } + } + minecraft->stats[m_iPad]->award(stat, level->difficulty, count); + } else { + // 4J : WESTY : Added for new achievements. + StatsCounter* pStats = minecraft->stats[m_iPad]; pStats->award(stat, level->difficulty, count); - // 4J-JEV: Check achievements for unlocks. + // 4J-JEV: Check achievements for unlocks. - // LEADER OF THE PACK - if ( stat == GenericStats::tamedEntity(eTYPE_WOLF) ) - { - // Check to see if we have befriended 5 wolves! Is this really the best place to do this??!! - if ( pStats->getTotalValue(GenericStats::tamedEntity(eTYPE_WOLF)) >= 5 ) - { - awardStat(GenericStats::leaderOfThePack(), GenericStats::param_noArgs()); - } - } + // LEADER OF THE PACK + if (stat == GenericStats::tamedEntity(eTYPE_WOLF)) { + // Check to see if we have befriended 5 wolves! Is this really the + // best place to do this??!! + if (pStats->getTotalValue(GenericStats::tamedEntity(eTYPE_WOLF)) >= + 5) { + awardStat(GenericStats::leaderOfThePack(), + GenericStats::param_noArgs()); + } + } - // MOAR TOOLS - { - Stat *toolStats[4][5]; - toolStats[0][0] = GenericStats::itemsCrafted(Item::shovel_wood->id); - toolStats[0][1] = GenericStats::itemsCrafted(Item::shovel_stone->id); - toolStats[0][2] = GenericStats::itemsCrafted(Item::shovel_iron->id); - toolStats[0][3] = GenericStats::itemsCrafted(Item::shovel_diamond->id); - toolStats[0][4] = GenericStats::itemsCrafted(Item::shovel_gold->id); - toolStats[1][0] = GenericStats::itemsCrafted(Item::pickAxe_wood->id); - toolStats[1][1] = GenericStats::itemsCrafted(Item::pickAxe_stone->id); - toolStats[1][2] = GenericStats::itemsCrafted(Item::pickAxe_iron->id); - toolStats[1][3] = GenericStats::itemsCrafted(Item::pickAxe_diamond->id); - toolStats[1][4] = GenericStats::itemsCrafted(Item::pickAxe_gold->id); - toolStats[2][0] = GenericStats::itemsCrafted(Item::hatchet_wood->id); - toolStats[2][1] = GenericStats::itemsCrafted(Item::hatchet_stone->id); - toolStats[2][2] = GenericStats::itemsCrafted(Item::hatchet_iron->id); - toolStats[2][3] = GenericStats::itemsCrafted(Item::hatchet_diamond->id); - toolStats[2][4] = GenericStats::itemsCrafted(Item::hatchet_gold->id); - toolStats[3][0] = GenericStats::itemsCrafted(Item::hoe_wood->id); - toolStats[3][1] = GenericStats::itemsCrafted(Item::hoe_stone->id); - toolStats[3][2] = GenericStats::itemsCrafted(Item::hoe_iron->id); - toolStats[3][3] = GenericStats::itemsCrafted(Item::hoe_diamond->id); - toolStats[3][4] = GenericStats::itemsCrafted(Item::hoe_gold->id); - - bool justCraftedTool = false; - for (int i=0; i<4; i++) - { - for (int j=0; j<5; j++) - { - if ( stat == toolStats[i][j] ) - { - justCraftedTool = true; - break; - } - } - } + // MOAR TOOLS + { + Stat* toolStats[4][5]; + toolStats[0][0] = GenericStats::itemsCrafted(Item::shovel_wood->id); + toolStats[0][1] = + GenericStats::itemsCrafted(Item::shovel_stone->id); + toolStats[0][2] = GenericStats::itemsCrafted(Item::shovel_iron->id); + toolStats[0][3] = + GenericStats::itemsCrafted(Item::shovel_diamond->id); + toolStats[0][4] = GenericStats::itemsCrafted(Item::shovel_gold->id); + toolStats[1][0] = + GenericStats::itemsCrafted(Item::pickAxe_wood->id); + toolStats[1][1] = + GenericStats::itemsCrafted(Item::pickAxe_stone->id); + toolStats[1][2] = + GenericStats::itemsCrafted(Item::pickAxe_iron->id); + toolStats[1][3] = + GenericStats::itemsCrafted(Item::pickAxe_diamond->id); + toolStats[1][4] = + GenericStats::itemsCrafted(Item::pickAxe_gold->id); + toolStats[2][0] = + GenericStats::itemsCrafted(Item::hatchet_wood->id); + toolStats[2][1] = + GenericStats::itemsCrafted(Item::hatchet_stone->id); + toolStats[2][2] = + GenericStats::itemsCrafted(Item::hatchet_iron->id); + toolStats[2][3] = + GenericStats::itemsCrafted(Item::hatchet_diamond->id); + toolStats[2][4] = + GenericStats::itemsCrafted(Item::hatchet_gold->id); + toolStats[3][0] = GenericStats::itemsCrafted(Item::hoe_wood->id); + toolStats[3][1] = GenericStats::itemsCrafted(Item::hoe_stone->id); + toolStats[3][2] = GenericStats::itemsCrafted(Item::hoe_iron->id); + toolStats[3][3] = GenericStats::itemsCrafted(Item::hoe_diamond->id); + toolStats[3][4] = GenericStats::itemsCrafted(Item::hoe_gold->id); - if (justCraftedTool) - { - bool awardNow = true; - for (int i=0; i<4; i++) - { - bool craftedThisTool = false; - for (int j=0; j<5; j++) - { - if ( pStats->getTotalValue(toolStats[i][j]) > 0 ) - craftedThisTool = true; - } + bool justCraftedTool = false; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 5; j++) { + if (stat == toolStats[i][j]) { + justCraftedTool = true; + break; + } + } + } - if (!craftedThisTool) - { - awardNow = false; - break; - } - } + if (justCraftedTool) { + bool awardNow = true; + for (int i = 0; i < 4; i++) { + bool craftedThisTool = false; + for (int j = 0; j < 5; j++) { + if (pStats->getTotalValue(toolStats[i][j]) > 0) + craftedThisTool = true; + } - if (awardNow) - { - awardStat(GenericStats::MOARTools(), GenericStats::param_noArgs()); - } - } - - } + if (!craftedThisTool) { + awardNow = false; + break; + } + } + + if (awardNow) { + awardStat(GenericStats::MOARTools(), + GenericStats::param_noArgs()); + } + } + } #ifdef _XBOX - // AWARD: Have we killed 10 creepers? - if ( pStats->getTotalValue( GenericStats::killsCreeper() ) >= 10 ) - { - awardStat( GenericStats::kill10Creepers(), GenericStats::param_noArgs()); - } + // AWARD: Have we killed 10 creepers? + if (pStats->getTotalValue(GenericStats::killsCreeper()) >= 10) { + awardStat(GenericStats::kill10Creepers(), + GenericStats::param_noArgs()); + } - // AWARD : Have we been playing for 100 game days? - if ( pStats->getTotalValue( GenericStats::timePlayed() ) >= ( Level::TICKS_PER_DAY * 100 ) ) - { - awardStat( GenericStats::play100Days(), GenericStats::param_noArgs()); - } - // AWARD : Have we mined 100 blocks? - if ( pStats->getTotalValue( GenericStats::totalBlocksMined() ) >= 100 ) - { - awardStat( GenericStats::mine100Blocks(), GenericStats::param_noArgs()); - } + // AWARD : Have we been playing for 100 game days? + if (pStats->getTotalValue(GenericStats::timePlayed()) >= + (Level::TICKS_PER_DAY * 100)) { + awardStat(GenericStats::play100Days(), + GenericStats::param_noArgs()); + } + // AWARD : Have we mined 100 blocks? + if (pStats->getTotalValue(GenericStats::totalBlocksMined()) >= 100) { + awardStat(GenericStats::mine100Blocks(), + GenericStats::param_noArgs()); + } #endif #ifdef _EXTENDED_ACHIEVEMENTS - // AWARD : Porkchop, cook and eat a porkchop. - { - Stat *cookPorkchop, *eatPorkchop; - cookPorkchop = GenericStats::itemsCrafted(Item::porkChop_cooked_Id); - eatPorkchop = GenericStats::itemsUsed(Item::porkChop_cooked_Id); + // AWARD : Porkchop, cook and eat a porkchop. + { + Stat *cookPorkchop, *eatPorkchop; + cookPorkchop = GenericStats::itemsCrafted(Item::porkChop_cooked_Id); + eatPorkchop = GenericStats::itemsUsed(Item::porkChop_cooked_Id); - if ( stat == cookPorkchop || stat == eatPorkchop ) - { - int numCookPorkchop, numEatPorkchop; - numCookPorkchop = pStats->getTotalValue(cookPorkchop); - numEatPorkchop = pStats->getTotalValue(eatPorkchop); + if (stat == cookPorkchop || stat == eatPorkchop) { + int numCookPorkchop, numEatPorkchop; + numCookPorkchop = pStats->getTotalValue(cookPorkchop); + numEatPorkchop = pStats->getTotalValue(eatPorkchop); - app.DebugPrintf( - "[AwardStat] Check unlock 'Porkchop': " - "pork_cooked=%i, pork_eaten=%i.\n", - numCookPorkchop, numEatPorkchop - ); + app.DebugPrintf( + "[AwardStat] Check unlock 'Porkchop': " + "pork_cooked=%i, pork_eaten=%i.\n", + numCookPorkchop, numEatPorkchop); - if ( (0 < numCookPorkchop) && (0 < numEatPorkchop) ) - { - awardStat( GenericStats::porkChop(), GenericStats::param_porkChop() ); - } - } - } + if ((0 < numCookPorkchop) && (0 < numEatPorkchop)) { + awardStat(GenericStats::porkChop(), + GenericStats::param_porkChop()); + } + } + } - // AWARD : Passing the Time, play for 100 minecraft days. - { - Stat *timePlayed = GenericStats::timePlayed(); + // AWARD : Passing the Time, play for 100 minecraft days. + { + Stat* timePlayed = GenericStats::timePlayed(); - if ( stat == timePlayed ) - { - int iPlayedTicks, iRequiredTicks; - iPlayedTicks = pStats->getTotalValue(timePlayed); - iRequiredTicks = Level::TICKS_PER_DAY * 100; + if (stat == timePlayed) { + int iPlayedTicks, iRequiredTicks; + iPlayedTicks = pStats->getTotalValue(timePlayed); + iRequiredTicks = Level::TICKS_PER_DAY * 100; - /* app.DebugPrintf( - "[AwardStat] Check unlock 'Passing the Time': " - "total_ticks=%i, req=%i.\n", - iPlayedTicks, iRequiredTicks - ); */ + /* app.DebugPrintf( + "[AwardStat] Check unlock 'Passing the Time': " + "total_ticks=%i, req=%i.\n", + iPlayedTicks, iRequiredTicks + ); */ - if (iPlayedTicks >= iRequiredTicks) - { - awardStat( GenericStats::passingTheTime(), GenericStats::param_passingTheTime() ); - } - } - } + if (iPlayedTicks >= iRequiredTicks) { + awardStat(GenericStats::passingTheTime(), + GenericStats::param_passingTheTime()); + } + } + } - // AWARD : The Haggler, Acquire 30 emeralds. - { - Stat *emeraldMined, *emeraldBought; - emeraldMined = GenericStats::blocksMined(Tile::emeraldOre_Id); - emeraldBought = GenericStats::itemsBought(Item::emerald_Id); + // AWARD : The Haggler, Acquire 30 emeralds. + { + Stat *emeraldMined, *emeraldBought; + emeraldMined = GenericStats::blocksMined(Tile::emeraldOre_Id); + emeraldBought = GenericStats::itemsBought(Item::emerald_Id); - if ( stat == emeraldMined || stat == emeraldBought ) - { - int numEmeraldMined, numEmeraldBought, totalSum; - numEmeraldMined = pStats->getTotalValue(emeraldMined); - numEmeraldBought = pStats->getTotalValue(emeraldBought); - totalSum = numEmeraldMined + numEmeraldBought; - - app.DebugPrintf( - "[AwardStat] Check unlock 'The Haggler': " - "emerald_mined=%i, emerald_bought=%i, sum=%i.\n", - numEmeraldMined, numEmeraldBought, totalSum - ); + if (stat == emeraldMined || stat == emeraldBought) { + int numEmeraldMined, numEmeraldBought, totalSum; + numEmeraldMined = pStats->getTotalValue(emeraldMined); + numEmeraldBought = pStats->getTotalValue(emeraldBought); + totalSum = numEmeraldMined + numEmeraldBought; - if (totalSum >= 30) awardStat( GenericStats::theHaggler(), GenericStats::param_theHaggler() ); - } - } + app.DebugPrintf( + "[AwardStat] Check unlock 'The Haggler': " + "emerald_mined=%i, emerald_bought=%i, sum=%i.\n", + numEmeraldMined, numEmeraldBought, totalSum); - // AWARD : Pot Planter, craft and place a flowerpot. - { - Stat *craftFlowerpot, *placeFlowerpot; - craftFlowerpot = GenericStats::itemsCrafted(Item::flowerPot_Id); - placeFlowerpot = GenericStats::blocksPlaced(Tile::flowerPot_Id); + if (totalSum >= 30) + awardStat(GenericStats::theHaggler(), + GenericStats::param_theHaggler()); + } + } - if ( stat == craftFlowerpot || stat == placeFlowerpot ) - { - if ( (pStats->getTotalValue(craftFlowerpot) > 0) && (pStats->getTotalValue(placeFlowerpot) > 0) ) - { - awardStat( GenericStats::potPlanter(), GenericStats::param_potPlanter() ); - } - } - } + // AWARD : Pot Planter, craft and place a flowerpot. + { + Stat *craftFlowerpot, *placeFlowerpot; + craftFlowerpot = GenericStats::itemsCrafted(Item::flowerPot_Id); + placeFlowerpot = GenericStats::blocksPlaced(Tile::flowerPot_Id); - // AWARD : It's a Sign, craft and place a sign. - { - Stat *craftSign, *placeWallsign, *placeSignpost; - craftSign = GenericStats::itemsCrafted(Item::sign_Id); - placeWallsign = GenericStats::blocksPlaced(Tile::wallSign_Id); - placeSignpost = GenericStats::blocksPlaced(Tile::sign_Id); + if (stat == craftFlowerpot || stat == placeFlowerpot) { + if ((pStats->getTotalValue(craftFlowerpot) > 0) && + (pStats->getTotalValue(placeFlowerpot) > 0)) { + awardStat(GenericStats::potPlanter(), + GenericStats::param_potPlanter()); + } + } + } - if ( stat == craftSign || stat == placeWallsign || stat == placeSignpost ) - { - int numCraftedSigns, numPlacedWallSign, numPlacedSignpost; - numCraftedSigns = pStats->getTotalValue(craftSign); - numPlacedWallSign = pStats->getTotalValue(placeWallsign); - numPlacedSignpost = pStats->getTotalValue(placeSignpost); + // AWARD : It's a Sign, craft and place a sign. + { + Stat *craftSign, *placeWallsign, *placeSignpost; + craftSign = GenericStats::itemsCrafted(Item::sign_Id); + placeWallsign = GenericStats::blocksPlaced(Tile::wallSign_Id); + placeSignpost = GenericStats::blocksPlaced(Tile::sign_Id); - app.DebugPrintf( - "[AwardStat] Check unlock 'It's a Sign': " - "crafted=%i, placedWallSigns=%i, placedSignposts=%i.\n", - numCraftedSigns, numPlacedWallSign, numPlacedSignpost - ); + if (stat == craftSign || stat == placeWallsign || + stat == placeSignpost) { + int numCraftedSigns, numPlacedWallSign, numPlacedSignpost; + numCraftedSigns = pStats->getTotalValue(craftSign); + numPlacedWallSign = pStats->getTotalValue(placeWallsign); + numPlacedSignpost = pStats->getTotalValue(placeSignpost); - if ( (numCraftedSigns>0) && ((numPlacedWallSign+numPlacedSignpost)>0) ) - { - awardStat( GenericStats::itsASign(), GenericStats::param_itsASign()); - } - } - } + app.DebugPrintf( + "[AwardStat] Check unlock 'It's a Sign': " + "crafted=%i, placedWallSigns=%i, placedSignposts=%i.\n", + numCraftedSigns, numPlacedWallSign, numPlacedSignpost); - // AWARD : Rainbow Collection, collect all different colours of wool. - { - bool justPickedupWool = false; - - for (int i=0; i<16; i++) - if ( stat == GenericStats::itemsCollected(Tile::cloth_Id, i) ) - justPickedupWool = true; + if ((numCraftedSigns > 0) && + ((numPlacedWallSign + numPlacedSignpost) > 0)) { + awardStat(GenericStats::itsASign(), + GenericStats::param_itsASign()); + } + } + } - if (justPickedupWool) - { - unsigned int woolCount = 0; - - for (unsigned int i = 0; i < 16; i++) - { - if (pStats->getTotalValue(GenericStats::itemsCollected(Tile::cloth_Id, i)) > 0) - woolCount++; - } + // AWARD : Rainbow Collection, collect all different colours of wool. + { + bool justPickedupWool = false; - if (woolCount >= 16) awardStat( GenericStats::rainbowCollection(), GenericStats::param_rainbowCollection() ); - } - } + for (int i = 0; i < 16; i++) + if (stat == GenericStats::itemsCollected(Tile::cloth_Id, i)) + justPickedupWool = true; - // AWARD : Adventuring Time, visit at least 17 biomes - { - bool justEnteredBiome = false; + if (justPickedupWool) { + unsigned int woolCount = 0; - for (int i=0; i<23; i++) - if ( stat == GenericStats::enteredBiome(i) ) - justEnteredBiome = true; + for (unsigned int i = 0; i < 16; i++) { + if (pStats->getTotalValue(GenericStats::itemsCollected( + Tile::cloth_Id, i)) > 0) + woolCount++; + } - if (justEnteredBiome) - { - unsigned int biomeCount = 0; + if (woolCount >= 16) + awardStat(GenericStats::rainbowCollection(), + GenericStats::param_rainbowCollection()); + } + } - for (unsigned int i = 0; i < 23; i++) - { - if (pStats->getTotalValue(GenericStats::enteredBiome(i)) > 0) - biomeCount++; - } + // AWARD : Adventuring Time, visit at least 17 biomes + { + bool justEnteredBiome = false; - if (biomeCount >= 17) awardStat( GenericStats::adventuringTime(), GenericStats::param_adventuringTime() ); - } - } + for (int i = 0; i < 23; i++) + if (stat == GenericStats::enteredBiome(i)) + justEnteredBiome = true; + + if (justEnteredBiome) { + unsigned int biomeCount = 0; + + for (unsigned int i = 0; i < 23; i++) { + if (pStats->getTotalValue(GenericStats::enteredBiome(i)) > + 0) + biomeCount++; + } + + if (biomeCount >= 17) + awardStat(GenericStats::adventuringTime(), + GenericStats::param_adventuringTime()); + } + } #endif - } + } #endif } -bool LocalPlayer::isSolidBlock(int x, int y, int z) -{ - return level->isSolidBlockingTile(x, y, z); +bool LocalPlayer::isSolidBlock(int x, int y, int z) { + return level->isSolidBlockingTile(x, y, z); } -bool LocalPlayer::checkInTile(double x, double y, double z) -{ +bool LocalPlayer::checkInTile(double x, double y, double z) { int xTile = Mth::floor(x); int yTile = Mth::floor(y); int zTile = Mth::floor(z); @@ -1074,32 +1006,32 @@ bool LocalPlayer::checkInTile(double x, double y, double z) double xd = x - xTile; double zd = z - zTile; - if (isSolidBlock(xTile, yTile, zTile) || isSolidBlock(xTile, yTile + 1, zTile)) - { - bool west = !isSolidBlock(xTile - 1, yTile, zTile) && !isSolidBlock(xTile - 1, yTile + 1, zTile); - bool east = !isSolidBlock(xTile + 1, yTile, zTile) && !isSolidBlock(xTile + 1, yTile + 1, zTile); - bool north = !isSolidBlock(xTile, yTile, zTile - 1) && !isSolidBlock(xTile, yTile + 1, zTile - 1); - bool south = !isSolidBlock(xTile, yTile, zTile + 1) && !isSolidBlock(xTile, yTile + 1, zTile + 1); + if (isSolidBlock(xTile, yTile, zTile) || + isSolidBlock(xTile, yTile + 1, zTile)) { + bool west = !isSolidBlock(xTile - 1, yTile, zTile) && + !isSolidBlock(xTile - 1, yTile + 1, zTile); + bool east = !isSolidBlock(xTile + 1, yTile, zTile) && + !isSolidBlock(xTile + 1, yTile + 1, zTile); + bool north = !isSolidBlock(xTile, yTile, zTile - 1) && + !isSolidBlock(xTile, yTile + 1, zTile - 1); + bool south = !isSolidBlock(xTile, yTile, zTile + 1) && + !isSolidBlock(xTile, yTile + 1, zTile + 1); int dir = -1; double closest = 9999; - if (west && xd < closest) - { + if (west && xd < closest) { closest = xd; dir = 0; } - if (east && 1 - xd < closest) - { + if (east && 1 - xd < closest) { closest = 1 - xd; dir = 1; } - if (north && zd < closest) - { + if (north && zd < closest) { closest = zd; dir = 4; } - if (south && 1 - zd < closest) - { + if (south && 1 - zd < closest) { closest = 1 - zd; dir = 5; } @@ -1112,508 +1044,456 @@ bool LocalPlayer::checkInTile(double x, double y, double z) } return false; - } -void LocalPlayer::setSprinting(bool value) -{ - Player::setSprinting(value); - if (value == false) sprintTime = 0; - else sprintTime = SPRINT_DURATION; +void LocalPlayer::setSprinting(bool value) { + Player::setSprinting(value); + if (value == false) + sprintTime = 0; + else + sprintTime = SPRINT_DURATION; } -void LocalPlayer::setExperienceValues(float experienceProgress, int totalExp, int experienceLevel) -{ - this->experienceProgress = experienceProgress; - this->totalExperience = totalExp; - this->experienceLevel = experienceLevel; +void LocalPlayer::setExperienceValues(float experienceProgress, int totalExp, + int experienceLevel) { + this->experienceProgress = experienceProgress; + this->totalExperience = totalExp; + this->experienceLevel = experienceLevel; } -bool LocalPlayer::hasPermission(EGameCommand command) -{ - return level->getLevelData()->getAllowCommands(); +bool LocalPlayer::hasPermission(EGameCommand command) { + return level->getLevelData()->getAllowCommands(); } -void LocalPlayer::onCrafted(std::shared_ptr item) -{ - if( minecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_iPad]; - gameMode->getTutorial()->onCrafted(item); - } +void LocalPlayer::onCrafted(std::shared_ptr item) { + if (minecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)minecraft->localgameModes[m_iPad]; + gameMode->getTutorial()->onCrafted(item); + } } -void LocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) -{ - setCustomSkin(skinId); +void LocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) { + setCustomSkin(skinId); } -void LocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) -{ - setCustomCape(capeId); +void LocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) { + setCustomCape(capeId); } // 4J TODO - Remove #include "../../Minecraft.World/Level/LevelChunk.h" -void LocalPlayer::mapPlayerChunk(const unsigned int flagTileType) -{ - int cx = this->xChunk; - int cz = this->zChunk; +void LocalPlayer::mapPlayerChunk(const unsigned int flagTileType) { + int cx = this->xChunk; + int cz = this->zChunk; - int pZ = ((int) floor(this->z)) %16; - int pX = ((int) floor(this->x)) %16; + int pZ = ((int)floor(this->z)) % 16; + int pX = ((int)floor(this->x)) % 16; - std::cout <<"player in chunk ("<x<<","<y<<","<z<<")\n"; + std::cout << "player in chunk (" << cx << "," << cz << ") at (" << this->x + << "," << this->y << "," << this->z << ")\n"; - for (int v = -1; v < 2; v++) - for (unsigned int z = 0; z < 16; z++) - { - for (int u = -1; u < 2; u++) - for (unsigned int x = 0; x < 16; x++) - { - LevelChunk *cc = level->getChunk(cx+u, cz+v); - if ( x==pX && z==pZ && u==0 && v==0) - std::cout << "O"; - else for (unsigned int y = 127; y > 0; y--) - { - int t = cc->getTile(x,y,z); - if (flagTileType != 0 && t == flagTileType) { std::cout << "@"; break; } - else if (t != 0 && t < 10) { std::cout << t; break; } - else if (t > 0) { std::cout << "#"; break; } - } - } - std::cout << "\n"; - } + for (int v = -1; v < 2; v++) + for (unsigned int z = 0; z < 16; z++) { + for (int u = -1; u < 2; u++) + for (unsigned int x = 0; x < 16; x++) { + LevelChunk* cc = level->getChunk(cx + u, cz + v); + if (x == pX && z == pZ && u == 0 && v == 0) + std::cout << "O"; + else + for (unsigned int y = 127; y > 0; y--) { + int t = cc->getTile(x, y, z); + if (flagTileType != 0 && t == flagTileType) { + std::cout << "@"; + break; + } else if (t != 0 && t < 10) { + std::cout << t; + break; + } else if (t > 0) { + std::cout << "#"; + break; + } + } + } + std::cout << "\n"; + } - std::cout << "\n"; + std::cout << "\n"; } - -void LocalPlayer::handleMouseDown(int button, bool down) -{ - // 4J Stu - We should not accept any input while asleep, except the above to wake up - if(isSleeping() && level != NULL && level->isClientSide) - { - return; - } +void LocalPlayer::handleMouseDown(int button, bool down) { + // 4J Stu - We should not accept any input while asleep, except the above to + // wake up + if (isSleeping() && level != NULL && level->isClientSide) { + return; + } if (!down) missTime = 0; if (button == 0 && missTime > 0) return; - if (down && minecraft->hitResult != NULL && minecraft->hitResult->type == HitResult::TILE && button == 0) - { + if (down && minecraft->hitResult != NULL && + minecraft->hitResult->type == HitResult::TILE && button == 0) { int x = minecraft->hitResult->x; int y = minecraft->hitResult->y; int z = minecraft->hitResult->z; - // 4J - addition to stop layer mining out of the top or bottom of the world - // 4J Stu - Allow this for The End - if( ( ( y == 0 ) || ( ( y == 127 ) && level->dimension->hasCeiling ) ) && level->dimension->id != 1 ) return; + // 4J - addition to stop layer mining out of the top or bottom of the + // world 4J Stu - Allow this for The End + if (((y == 0) || ((y == 127) && level->dimension->hasCeiling)) && + level->dimension->id != 1) + return; - minecraft->gameMode->continueDestroyBlock(x, y, z, minecraft->hitResult->f); - - if(mayBuild(x,y,z)) - { - minecraft->particleEngine->crack(x, y, z, minecraft->hitResult->f); - swing(); - } - } - else - { + minecraft->gameMode->continueDestroyBlock(x, y, z, + minecraft->hitResult->f); + + if (mayBuild(x, y, z)) { + minecraft->particleEngine->crack(x, y, z, minecraft->hitResult->f); + swing(); + } + } else { minecraft->gameMode->stopDestroyBlock(); } } -bool LocalPlayer::creativeModeHandleMouseClick(int button, bool buttonPressed) -{ - if( buttonPressed ) - { - if( lastClickState == lastClick_oldRepeat ) - { - return false; - } +bool LocalPlayer::creativeModeHandleMouseClick(int button, bool buttonPressed) { + if (buttonPressed) { + if (lastClickState == lastClick_oldRepeat) { + return false; + } - // Are we in an auto-repeat situation? - If so only tell the game that we've clicked if we move more than a unit away from our last - // click position in any axis - if( lastClickState != lastClick_invalid ) - { - // If we're in disabled mode already (set when sprinting) then don't do anything - if we're sprinting, we don't auto-repeat at all. - // With auto repeat on, we can quickly place fires causing photosensitivity issues due to rapid flashing - if( lastClickState == lastClick_disabled ) return false; - // If we've started sprinting, go into this mode & also don't do anything - // Ignore repeate when sleeping - if( isSprinting() ) - { - lastClickState = lastClick_disabled; - return false; - } + // Are we in an auto-repeat situation? - If so only tell the game that + // we've clicked if we move more than a unit away from our last click + // position in any axis + if (lastClickState != lastClick_invalid) { + // If we're in disabled mode already (set when sprinting) then don't + // do anything - if we're sprinting, we don't auto-repeat at all. + // With auto repeat on, we can quickly place fires causing + // photosensitivity issues due to rapid flashing + if (lastClickState == lastClick_disabled) return false; + // If we've started sprinting, go into this mode & also don't do + // anything Ignore repeate when sleeping + if (isSprinting()) { + lastClickState = lastClick_disabled; + return false; + } - // Get distance from last click point in each axis - float dX = (float)x - lastClickX; - float dY = (float)y - lastClickY; - float dZ = (float)z - lastClickZ; - bool newClick = false; + // Get distance from last click point in each axis + float dX = (float)x - lastClickX; + float dY = (float)y - lastClickY; + float dZ = (float)z - lastClickZ; + bool newClick = false; - float ddx = dX - lastClickdX; - float ddy = dY - lastClickdY; - float ddz = dZ - lastClickdZ; + float ddx = dX - lastClickdX; + float ddy = dY - lastClickdY; + float ddz = dZ - lastClickdZ; - if( lastClickState == lastClick_moving ) - { - float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz ); - if( deltaChange < 0.01f ) - { - lastClickState = lastClick_stopped; - lastClickTolerance = 0.0f; - } - } - else if( lastClickState == lastClick_stopped ) - { - float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz ); - if( deltaChange >= 0.01f ) - { - lastClickState = lastClick_moving; - lastClickTolerance = 0.0f; - } - else - { - lastClickTolerance += 0.1f; - if( lastClickTolerance > 0.7f ) - { - lastClickTolerance = 0.0f; - lastClickState = lastClick_init; - } - } - } + if (lastClickState == lastClick_moving) { + float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz); + if (deltaChange < 0.01f) { + lastClickState = lastClick_stopped; + lastClickTolerance = 0.0f; + } + } else if (lastClickState == lastClick_stopped) { + float deltaChange = sqrtf(ddx * ddx + ddy * ddy + ddz * ddz); + if (deltaChange >= 0.01f) { + lastClickState = lastClick_moving; + lastClickTolerance = 0.0f; + } else { + lastClickTolerance += 0.1f; + if (lastClickTolerance > 0.7f) { + lastClickTolerance = 0.0f; + lastClickState = lastClick_init; + } + } + } - lastClickdX = dX; - lastClickdY = dY; - lastClickdZ = dZ; + lastClickdX = dX; + lastClickdY = dY; + lastClickdZ = dZ; - // If we have moved more than one unit in any one axis, then register a new click - // The new click position is normalised at one unit in the direction of movement, so that we don't gradually drift away if we detect the movement a fraction over - // the unit distance each time + // If we have moved more than one unit in any one axis, then + // register a new click The new click position is normalised at one + // unit in the direction of movement, so that we don't gradually + // drift away if we detect the movement a fraction over the unit + // distance each time - if( fabsf(dX) >= 1.0f ) - { - dX= ( dX < 0.0f ) ? ceilf(dX) : floorf(dX); - newClick = true; - } - else if( fabsf(dY) >= 1.0f ) - { - dY= ( dY < 0.0f ) ? ceilf(dY) : floorf(dY); - newClick = true; - } - else if( fabsf(dZ) >= 1.0f ) - { - dZ= ( dZ < 0.0f ) ? ceilf(dZ) : floorf(dZ); - newClick = true; - } + if (fabsf(dX) >= 1.0f) { + dX = (dX < 0.0f) ? ceilf(dX) : floorf(dX); + newClick = true; + } else if (fabsf(dY) >= 1.0f) { + dY = (dY < 0.0f) ? ceilf(dY) : floorf(dY); + newClick = true; + } else if (fabsf(dZ) >= 1.0f) { + dZ = (dZ < 0.0f) ? ceilf(dZ) : floorf(dZ); + newClick = true; + } - if( ( !newClick ) && ( lastClickTolerance > 0.0f ) ) - { - float fTarget = 1.0f - lastClickTolerance; + if ((!newClick) && (lastClickTolerance > 0.0f)) { + float fTarget = 1.0f - lastClickTolerance; - if( fabsf(dX) >= fTarget ) newClick = true; - if( fabsf(dY) >= fTarget ) newClick = true; - if( fabsf(dZ) >= fTarget ) newClick = true; - } + if (fabsf(dX) >= fTarget) newClick = true; + if (fabsf(dY) >= fTarget) newClick = true; + if (fabsf(dZ) >= fTarget) newClick = true; + } - if( newClick ) - { - lastClickX += dX; - lastClickY += dY; - lastClickZ += dZ; + if (newClick) { + lastClickX += dX; + lastClickY += dY; + lastClickZ += dZ; - // Get a more accurate pick from the position where the new click should ideally have come from, rather than - // where we happen to be now (ie a rounded number of units from the last Click position) - double oldX = x; - double oldY = y; - double oldZ = z; - x = lastClickX; - y = lastClickY; - z = lastClickZ; + // Get a more accurate pick from the position where the new + // click should ideally have come from, rather than where we + // happen to be now (ie a rounded number of units from the last + // Click position) + double oldX = x; + double oldY = y; + double oldZ = z; + x = lastClickX; + y = lastClickY; + z = lastClickZ; - minecraft->gameRenderer->pick(1); + minecraft->gameRenderer->pick(1); - x = oldX; - y = oldY; - z = oldZ; + x = oldX; + y = oldY; + z = oldZ; - handleMouseClick(button); - - if( lastClickState == lastClick_stopped ) - { - lastClickState = lastClick_init; - lastClickTolerance = 0.0f; - } - else - { - lastClickState = lastClick_moving; - lastClickTolerance = 0.0f; - } - } - } - else - { - // First click - just record position & handle - lastClickX = (float)x; - lastClickY = (float)y; - lastClickZ = (float)z; - // If we actually placed an item, then move into the init state as we are going to be doing the special creative mode auto repeat - bool itemPlaced = handleMouseClick(button); - // If we're sprinting or riding, don't auto-repeat at all. With auto repeat on, we can quickly place fires causing photosensitivity issues due to rapid flashing - // Also ignore repeats when the player is sleeping - if( isSprinting() || isRiding() || isSleeping() ) - { - lastClickState = lastClick_disabled; - } - else - { - if( itemPlaced ) - { - lastClickState = lastClick_init; - lastClickTolerance = 0.0f; - } - else - { - // Didn't place an item - might actually be activating a switch or door or something - just do a standard auto repeat in this case - lastClickState = lastClick_oldRepeat; - } - } - return true; - } - } - else - { - lastClickState = lastClick_invalid; - } - return false; + handleMouseClick(button); + if (lastClickState == lastClick_stopped) { + lastClickState = lastClick_init; + lastClickTolerance = 0.0f; + } else { + lastClickState = lastClick_moving; + lastClickTolerance = 0.0f; + } + } + } else { + // First click - just record position & handle + lastClickX = (float)x; + lastClickY = (float)y; + lastClickZ = (float)z; + // If we actually placed an item, then move into the init state as + // we are going to be doing the special creative mode auto repeat + bool itemPlaced = handleMouseClick(button); + // If we're sprinting or riding, don't auto-repeat at all. With auto + // repeat on, we can quickly place fires causing photosensitivity + // issues due to rapid flashing Also ignore repeats when the player + // is sleeping + if (isSprinting() || isRiding() || isSleeping()) { + lastClickState = lastClick_disabled; + } else { + if (itemPlaced) { + lastClickState = lastClick_init; + lastClickTolerance = 0.0f; + } else { + // Didn't place an item - might actually be activating a + // switch or door or something - just do a standard auto + // repeat in this case + lastClickState = lastClick_oldRepeat; + } + } + return true; + } + } else { + lastClickState = lastClick_invalid; + } + return false; } -bool LocalPlayer::handleMouseClick(int button) -{ - bool returnItemPlaced = false; +bool LocalPlayer::handleMouseClick(int button) { + bool returnItemPlaced = false; - if (button == 0 && missTime > 0) return false; - if (button == 0) - { - //app.DebugPrintf("handleMouseClick - Player %d is swinging\n",GetXboxPad()); - swing(); - } + if (button == 0 && missTime > 0) return false; + if (button == 0) { + // app.DebugPrintf("handleMouseClick - Player %d is + // swinging\n",GetXboxPad()); + swing(); + } - bool mayUse = true; + bool mayUse = true; - // 4J-PB - Adding a special case in here for sleeping in a bed in a multiplayer game - we need to wake up, and we don't have the inbedchatscreen with a button + // 4J-PB - Adding a special case in here for sleeping in a bed in a + // multiplayer game - we need to wake up, and we don't have the + // inbedchatscreen with a button - if(button==1 && (isSleeping() && level != NULL && level->isClientSide)) - { - if(lastClickState == lastClick_oldRepeat) return false; + if (button == 1 && (isSleeping() && level != NULL && level->isClientSide)) { + if (lastClickState == lastClick_oldRepeat) return false; + std::shared_ptr mplp = + std::dynamic_pointer_cast( + shared_from_this()); - std::shared_ptr mplp = std::dynamic_pointer_cast( shared_from_this() ); + if (mplp && mplp->connection) mplp->StopSleeping(); + } + // 4J Stu - We should not accept any input while asleep, except the above to + // wake up + if (isSleeping() && level != NULL && level->isClientSide) { + return false; + } - if(mplp && mplp->connection) mplp->StopSleeping(); - - } - // 4J Stu - We should not accept any input while asleep, except the above to wake up - if(isSleeping() && level != NULL && level->isClientSide) - { - return false; - } + std::shared_ptr oldItem = inventory->getSelected(); - std::shared_ptr oldItem = inventory->getSelected(); + if (minecraft->hitResult == NULL) { + if (button == 0 && + minecraft->localgameModes[GetXboxPad()]->hasMissTime()) + missTime = 10; + } else if (minecraft->hitResult->type == HitResult::ENTITY) { + if (button == 0) { + minecraft->gameMode->attack(minecraft->localplayers[GetXboxPad()], + minecraft->hitResult->entity); + } + if (button == 1) { + // 4J-PB - if we milk a cow here, and end up with a bucket of milk, + // the if (mayUse && button == 1) further down will then empty our + // bucket if we're pointing at a tile It looks like interact really + // should be returning a result so we can check this, but it's + // possibly just the milk bucket that causes a problem - if (minecraft->hitResult == NULL) - { - if (button == 0 && minecraft->localgameModes[GetXboxPad()]->hasMissTime()) missTime = 10; - } - else if (minecraft->hitResult->type == HitResult::ENTITY) - { - if (button == 0) - { - minecraft->gameMode->attack(minecraft->localplayers[GetXboxPad()], minecraft->hitResult->entity); - } - if (button == 1) - { - // 4J-PB - if we milk a cow here, and end up with a bucket of milk, the if (mayUse && button == 1) further down will - // then empty our bucket if we're pointing at a tile - // It looks like interact really should be returning a result so we can check this, but it's possibly just the - // milk bucket that causes a problem + if (minecraft->hitResult->entity->GetType() == eTYPE_COW) { + // If I have an empty bucket in my hand, it's going to be filled + // with milk, so turn off mayUse + std::shared_ptr item = inventory->getSelected(); + if (item && (item->id == Item::bucket_empty_Id)) { + mayUse = false; + } + } + if (minecraft->gameMode->interact( + minecraft->localplayers[GetXboxPad()], + minecraft->hitResult->entity)) { + mayUse = false; + } + } + } else if (minecraft->hitResult->type == HitResult::TILE) { + int x = minecraft->hitResult->x; + int y = minecraft->hitResult->y; + int z = minecraft->hitResult->z; + int face = minecraft->hitResult->f; - if(minecraft->hitResult->entity->GetType()==eTYPE_COW) - { - // If I have an empty bucket in my hand, it's going to be filled with milk, so turn off mayUse - std::shared_ptr item = inventory->getSelected(); - if(item && (item->id==Item::bucket_empty_Id)) - { - mayUse=false; - } - } - if( minecraft->gameMode->interact(minecraft->localplayers[GetXboxPad()], minecraft->hitResult->entity) ) - { - mayUse = false; - } - } - } - else if (minecraft->hitResult->type == HitResult::TILE) - { - int x = minecraft->hitResult->x; - int y = minecraft->hitResult->y; - int z = minecraft->hitResult->z; - int face = minecraft->hitResult->f; + if (button == 0) { + // 4J - addition to stop layer mining out of the top or bottom of + // the world 4J Stu - Allow this for The End + if (!((y == 0) || ((y == 127) && level->dimension->hasCeiling)) || + level->dimension->id == 1) { + minecraft->gameMode->startDestroyBlock(x, y, z, + minecraft->hitResult->f); + } + } else { + std::shared_ptr item = oldItem; + int oldCount = item != NULL ? item->count : 0; + bool usedItem = false; + if (minecraft->gameMode->useItemOn( + minecraft->localplayers[GetXboxPad()], level, item, x, y, z, + face, minecraft->hitResult->pos, false, &usedItem)) { + // Presume that if we actually used the held item, then we've + // placed it + if (usedItem) { + returnItemPlaced = true; + } + mayUse = false; + // app.DebugPrintf("Player %d is swinging\n",GetXboxPad()); + swing(); + } + if (item == NULL) { + return false; + } - if (button == 0) - { - // 4J - addition to stop layer mining out of the top or bottom of the world - // 4J Stu - Allow this for The End - if( !( ( y == 0 ) || ( ( y == 127 ) && level->dimension->hasCeiling ) ) || level->dimension->id == 1 ) - { - minecraft->gameMode->startDestroyBlock(x, y, z, minecraft->hitResult->f); - } - } - else - { - std::shared_ptr item = oldItem; - int oldCount = item != NULL ? item->count : 0; - bool usedItem = false; - if (minecraft->gameMode->useItemOn(minecraft->localplayers[GetXboxPad()], level, item, x, y, z, face, minecraft->hitResult->pos, false, &usedItem)) - { - // Presume that if we actually used the held item, then we've placed it - if( usedItem ) - { - returnItemPlaced = true; - } - mayUse = false; - //app.DebugPrintf("Player %d is swinging\n",GetXboxPad()); - swing(); - } - if (item == NULL) - { - return false; - } + if (item->count == 0) { + inventory->items[inventory->selected] = nullptr; + } else if (item->count != oldCount || + minecraft->localgameModes[GetXboxPad()] + ->hasInfiniteItems()) { + minecraft->gameRenderer->itemInHandRenderer->itemPlaced(); + } + } + } - if (item->count == 0) - { - inventory->items[inventory->selected] = nullptr; - } - else if (item->count != oldCount || minecraft->localgameModes[GetXboxPad()]->hasInfiniteItems()) - { - minecraft->gameRenderer->itemInHandRenderer->itemPlaced(); - } - } - } - - if (mayUse && button == 1) - { - std::shared_ptr item = inventory->getSelected(); - if (item != NULL) - { - if (minecraft->gameMode->useItem(minecraft->localplayers[GetXboxPad()], level, item)) - { - minecraft->gameRenderer->itemInHandRenderer->itemUsed(); - } - } - } - return returnItemPlaced; + if (mayUse && button == 1) { + std::shared_ptr item = inventory->getSelected(); + if (item != NULL) { + if (minecraft->gameMode->useItem( + minecraft->localplayers[GetXboxPad()], level, item)) { + minecraft->gameRenderer->itemInHandRenderer->itemUsed(); + } + } + } + return returnItemPlaced; } -void LocalPlayer::updateRichPresence() -{ - if((m_iPad!=-1)/* && !ui.GetMenuDisplayed(m_iPad)*/ ) - { - std::shared_ptr selectedItem = inventory->getSelected(); - if(selectedItem != NULL && selectedItem->id == Item::fishingRod_Id) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_FISHING); - } - else if(selectedItem != NULL && selectedItem->id == Item::map_Id) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_MAP); - } - else if(riding != NULL && std::dynamic_pointer_cast(riding) != NULL) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_RIDING_MINECART); - } - else if(riding != NULL && std::dynamic_pointer_cast(riding) != NULL) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_BOATING); - } - else if(riding != NULL && std::dynamic_pointer_cast(riding) != NULL) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_RIDING_PIG); - } - else if( this->dimension == -1 ) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_NETHER); - } - else if( minecraft->soundEngine->GetIsPlayingStreamingCDMusic() ) - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_CD); - } - else - { - app.SetRichPresenceContext(m_iPad,CONTEXT_GAME_STATE_BLANK); - } - } +void LocalPlayer::updateRichPresence() { + if ((m_iPad != -1) /* && !ui.GetMenuDisplayed(m_iPad)*/) { + std::shared_ptr selectedItem = inventory->getSelected(); + if (selectedItem != NULL && selectedItem->id == Item::fishingRod_Id) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_FISHING); + } else if (selectedItem != NULL && selectedItem->id == Item::map_Id) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_MAP); + } else if (riding != NULL && + std::dynamic_pointer_cast(riding) != NULL) { + app.SetRichPresenceContext(m_iPad, + CONTEXT_GAME_STATE_RIDING_MINECART); + } else if (riding != NULL && + std::dynamic_pointer_cast(riding) != NULL) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_BOATING); + } else if (riding != NULL && + std::dynamic_pointer_cast(riding) != NULL) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_RIDING_PIG); + } else if (this->dimension == -1) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_NETHER); + } else if (minecraft->soundEngine->GetIsPlayingStreamingCDMusic()) { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_CD); + } else { + app.SetRichPresenceContext(m_iPad, CONTEXT_GAME_STATE_BLANK); + } + } } // 4J Stu - Added for telemetry -void LocalPlayer::SetSessionTimerStart(void) -{ - m_sessionTimeStart=app.getAppTime(); - m_dimensionTimeStart=m_sessionTimeStart; +void LocalPlayer::SetSessionTimerStart(void) { + m_sessionTimeStart = app.getAppTime(); + m_dimensionTimeStart = m_sessionTimeStart; } -float LocalPlayer::getSessionTimer(void) -{ - return app.getAppTime()-m_sessionTimeStart; +float LocalPlayer::getSessionTimer(void) { + return app.getAppTime() - m_sessionTimeStart; } -float LocalPlayer::getAndResetChangeDimensionTimer() -{ - float appTime = app.getAppTime(); - float returnVal = appTime - m_dimensionTimeStart; - m_dimensionTimeStart = appTime; - return returnVal; +float LocalPlayer::getAndResetChangeDimensionTimer() { + float appTime = app.getAppTime(); + float returnVal = appTime - m_dimensionTimeStart; + m_dimensionTimeStart = appTime; + return returnVal; } -void LocalPlayer::handleCollectItem(std::shared_ptr item) -{ - if(item != NULL) - { - unsigned int itemCountAnyAux = 0; - unsigned int itemCountThisAux = 0; - for (unsigned int k = 0; k < inventory->items.length; ++k) - { - if (inventory->items[k] != NULL) - { - // do they have the item - if(inventory->items[k]->id == item->id) - { - unsigned int quantity = inventory->items[k]->GetCount(); +void LocalPlayer::handleCollectItem(std::shared_ptr item) { + if (item != NULL) { + unsigned int itemCountAnyAux = 0; + unsigned int itemCountThisAux = 0; + for (unsigned int k = 0; k < inventory->items.length; ++k) { + if (inventory->items[k] != NULL) { + // do they have the item + if (inventory->items[k]->id == item->id) { + unsigned int quantity = inventory->items[k]->GetCount(); - itemCountAnyAux += quantity; + itemCountAnyAux += quantity; - if( inventory->items[k]->getAuxValue() == item->getAuxValue() ) - { - itemCountThisAux += quantity; - } - } - } - } - TutorialMode *gameMode = (TutorialMode *)minecraft->localgameModes[m_iPad]; - gameMode->getTutorial()->onTake(item, itemCountAnyAux, itemCountThisAux); - } + if (inventory->items[k]->getAuxValue() == + item->getAuxValue()) { + itemCountThisAux += quantity; + } + } + } + } + TutorialMode* gameMode = + (TutorialMode*)minecraft->localgameModes[m_iPad]; + gameMode->getTutorial()->onTake(item, itemCountAnyAux, + itemCountThisAux); + } - if(ui.IsContainerMenuDisplayed(m_iPad)) - { - ui.HandleInventoryUpdated(m_iPad); - } + if (ui.IsContainerMenuDisplayed(m_iPad)) { + ui.HandleInventoryUpdated(m_iPad); + } } -void LocalPlayer::SetPlayerAdditionalModelParts(std::vectorpAdditionalModelParts) -{ - m_pAdditionalModelParts=pAdditionalModelParts; +void LocalPlayer::SetPlayerAdditionalModelParts( + std::vector pAdditionalModelParts) { + m_pAdditionalModelParts = pAdditionalModelParts; } diff --git a/Minecraft.Client/Player/LocalPlayer.h b/Minecraft.Client/Player/LocalPlayer.h index cb8b5dfa1..28edd6270 100644 --- a/Minecraft.Client/Player/LocalPlayer.h +++ b/Minecraft.Client/Player/LocalPlayer.h @@ -14,187 +14,199 @@ class Input; class Stat; class Minecraft; - - // Time in seconds before the players presence is update to Idle #define PLAYER_IDLE_TIME 300 -class LocalPlayer : public Player -{ +class LocalPlayer : public Player { public: - static const int SPRINT_DURATION = 20 * 30; + static const int SPRINT_DURATION = 20 * 30; + + Input* input; - Input *input; protected: - Minecraft *minecraft; - int sprintTriggerTime; - bool sprintTriggerRegisteredReturn; // 4J added - bool twoJumpsRegistered; // 4J added + Minecraft* minecraft; + int sprintTriggerTime; + bool sprintTriggerRegisteredReturn; // 4J added + bool twoJumpsRegistered; // 4J added - unsigned int m_uiInactiveTicks; // To measure time for idle anims + unsigned int m_uiInactiveTicks; // To measure time for idle anims - unsigned long long m_awardedThisSession; + unsigned long long m_awardedThisSession; - // 4J - Last time we checked for achievement uunlocks. - //long long m_lastAchievementUpdate; + // 4J - Last time we checked for achievement uunlocks. + // long long m_lastAchievementUpdate; public: - int sprintTime; + int sprintTime; - float yBob, xBob; - float yBobO, xBobO; + float yBob, xBob; + float yBobO, xBobO; - LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dimension); - virtual ~LocalPlayer(); + LocalPlayer(Minecraft* minecraft, Level* level, User* user, int dimension); + virtual ~LocalPlayer(); - void move(double xa, double ya, double za, bool noEntityCubes=false); // 4J - added noEntityCubes parameter + void move( + double xa, double ya, double za, + bool noEntityCubes = false); // 4J - added noEntityCubes parameter - - int m_iScreenSection; // assuming 4player splitscreen for now, or -1 for single player - __uint64 ullButtonsPressed; // Stores the button presses, since the inputmanager can be ticked faster than the minecraft - // player tick, and a button press and release combo can be missed in the minecraft::tick + int m_iScreenSection; // assuming 4player splitscreen for now, or -1 for + // single player + __uint64 + ullButtonsPressed; // Stores the button presses, since the inputmanager + // can be ticked faster than the minecraft player + // tick, and a button press and release combo can be + // missed in the minecraft::tick - __uint64 ullDpad_last; - __uint64 ullDpad_this; - __uint64 ullDpad_filtered; + __uint64 ullDpad_last; + __uint64 ullDpad_this; + __uint64 ullDpad_filtered; - // 4J-PB - moved these in from the minecraft structure, since they are per player things for splitscreen - //int ticks; - int missTime; - int lastClickTick[2]; - bool isRaining ; - int m_iThirdPersonView; + // 4J-PB - moved these in from the minecraft structure, since they are per + // player things for splitscreen + // int ticks; + int missTime; + int lastClickTick[2]; + bool isRaining; + int m_iThirdPersonView; - bool m_bHasAwardedStayinFrosty; + bool m_bHasAwardedStayinFrosty; private: - float flyX, flyY, flyZ; - -protected: - // 4J-PB - player's xbox pad - int m_iPad; + float flyX, flyY, flyZ; - bool m_bIsIdle; +protected: + // 4J-PB - player's xbox pad + int m_iPad; + + bool m_bIsIdle; private: // local player fly // -------------------------------------------------------------------------- // smooth camera settings - SmoothFloat smoothFlyX; + SmoothFloat smoothFlyX; SmoothFloat smoothFlyY; SmoothFloat smoothFlyZ; void calculateFlight(float xa, float ya, float za); public: - virtual void serverAiStep(); + virtual void serverAiStep(); protected: - bool isEffectiveAI(); + bool isEffectiveAI(); public: virtual void aiStep(); - virtual void changeDimension(int i); - virtual float getFieldOfViewModifier(); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void readAdditionalSaveData(CompoundTag *entityTag); + virtual void changeDimension(int i); + virtual float getFieldOfViewModifier(); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void readAdditionalSaveData(CompoundTag* entityTag); virtual void closeContainer(); virtual void openTextEdit(std::shared_ptr sign); - virtual bool openContainer(std::shared_ptr container); // 4J added bool return - virtual bool startCrafting(int x, int y, int z); // 4J added bool return - virtual bool startEnchanting(int x, int y, int z); // 4J added bool return - virtual bool startRepairing(int x, int y, int z); - virtual bool openFurnace(std::shared_ptr furnace); // 4J added bool return - virtual bool openBrewingStand(std::shared_ptr brewingStand); // 4J added bool return - virtual bool openTrap(std::shared_ptr trap); // 4J added bool return - virtual bool openTrading(std::shared_ptr traderTarget); - virtual void crit(std::shared_ptr e); - virtual void magicCrit(std::shared_ptr e); + virtual bool openContainer( + std::shared_ptr container); // 4J added bool return + virtual bool startCrafting(int x, int y, int z); // 4J added bool return + virtual bool startEnchanting(int x, int y, int z); // 4J added bool return + virtual bool startRepairing(int x, int y, int z); + virtual bool openFurnace( + std::shared_ptr furnace); // 4J added bool return + virtual bool openBrewingStand(std::shared_ptr + brewingStand); // 4J added bool return + virtual bool openTrap( + std::shared_ptr trap); // 4J added bool return + virtual bool openTrading(std::shared_ptr traderTarget); + virtual void crit(std::shared_ptr e); + virtual void magicCrit(std::shared_ptr e); virtual void take(std::shared_ptr e, int orgCount); virtual void chat(const std::wstring& message); - virtual bool isSneaking(); - //virtual bool isIdle(); + virtual bool isSneaking(); + // virtual bool isIdle(); virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource); virtual void respawn(); virtual void animateRespawn(); virtual void displayClientMessage(int messageId); - virtual void awardStat(Stat *stat, byteArray param); - virtual int ThirdPersonView() { return m_iThirdPersonView;} - // 4J - have changed 3rd person view to be 0 if not enabled, 1 for mode like original, 2 reversed mode - virtual void SetThirdPersonView(int val) {m_iThirdPersonView=val;} + virtual void awardStat(Stat* stat, byteArray param); + virtual int ThirdPersonView() { return m_iThirdPersonView; } + // 4J - have changed 3rd person view to be 0 if not enabled, 1 for mode like + // original, 2 reversed mode + virtual void SetThirdPersonView(int val) { m_iThirdPersonView = val; } - void ResetInactiveTicks() { m_uiInactiveTicks=0;} - unsigned int GetInactiveTicks() { return m_uiInactiveTicks;} - void IncrementInactiveTicks() { if(m_uiInactiveTicks<255) m_uiInactiveTicks++;} + void ResetInactiveTicks() { m_uiInactiveTicks = 0; } + unsigned int GetInactiveTicks() { return m_uiInactiveTicks; } + void IncrementInactiveTicks() { + if (m_uiInactiveTicks < 255) m_uiInactiveTicks++; + } - void mapPlayerChunk(unsigned int); - // 4J-PB - xbox pad for this player - void SetXboxPad(int iPad) {m_iPad=iPad;} - int GetXboxPad() {return m_iPad;} - void SetPlayerRespawned(bool bVal) {m_bPlayerRespawned=bVal;} - bool GetPlayerRespawned() {return m_bPlayerRespawned;} + void mapPlayerChunk(unsigned int); + // 4J-PB - xbox pad for this player + void SetXboxPad(int iPad) { m_iPad = iPad; } + int GetXboxPad() { return m_iPad; } + void SetPlayerRespawned(bool bVal) { m_bPlayerRespawned = bVal; } + bool GetPlayerRespawned() { return m_bPlayerRespawned; } - // 4J-PB - Moved these in here from the minecraft structure since they are local player related - void handleMouseDown(int button, bool down); - bool handleMouseClick(int button); + // 4J-PB - Moved these in here from the minecraft structure since they are + // local player related + void handleMouseDown(int button, bool down); + bool handleMouseClick(int button); - // 4J - added for improved autorepeat - bool creativeModeHandleMouseClick(int button, bool buttonPressed); - float lastClickX; - float lastClickY; - float lastClickZ; - float lastClickdX; - float lastClickdY; - float lastClickdZ; - enum eLastClickState - { - lastClick_invalid, - lastClick_init, - lastClick_moving, - lastClick_stopped, - lastClick_oldRepeat, - lastClick_disabled - }; - float lastClickTolerance; - int lastClickState; + // 4J - added for improved autorepeat + bool creativeModeHandleMouseClick(int button, bool buttonPressed); + float lastClickX; + float lastClickY; + float lastClickZ; + float lastClickdX; + float lastClickdY; + float lastClickdZ; + enum eLastClickState { + lastClick_invalid, + lastClick_init, + lastClick_moving, + lastClick_stopped, + lastClick_oldRepeat, + lastClick_disabled + }; + float lastClickTolerance; + int lastClickState; - // 4J Stu - Added to allow callback to tutorial to stay within Minecraft.Client - virtual void onCrafted(std::shared_ptr item); + // 4J Stu - Added to allow callback to tutorial to stay within + // Minecraft.Client + virtual void onCrafted(std::shared_ptr item); - virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); - virtual void setAndBroadcastCustomCape(std::uint32_t capeId); + virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); + virtual void setAndBroadcastCustomCape(std::uint32_t capeId); private: - bool isSolidBlock(int x, int y, int z); - bool m_bPlayerRespawned; + bool isSolidBlock(int x, int y, int z); + bool m_bPlayerRespawned; protected: - bool checkInTile(double x, double y, double z); + bool checkInTile(double x, double y, double z); public: - void setSprinting(bool value); - void setExperienceValues(float experienceProgress, int totalExp, int experienceLevel); + void setSprinting(bool value); + void setExperienceValues(float experienceProgress, int totalExp, + int experienceLevel); - bool hasPermission(EGameCommand command); + bool hasPermission(EGameCommand command); - void updateRichPresence(); + void updateRichPresence(); - // 4J Stu - Added for telemetry - float m_sessionTimeStart; - float m_dimensionTimeStart; + // 4J Stu - Added for telemetry + float m_sessionTimeStart; + float m_dimensionTimeStart; public: - void SetSessionTimerStart(void); - float getSessionTimer(void); + void SetSessionTimerStart(void); + float getSessionTimer(void); - float getAndResetChangeDimensionTimer(); + float getAndResetChangeDimensionTimer(); - virtual void handleCollectItem(std::shared_ptr item); - void SetPlayerAdditionalModelParts(std::vectorpAdditionalModelParts); + virtual void handleCollectItem(std::shared_ptr item); + void SetPlayerAdditionalModelParts( + std::vector pAdditionalModelParts); private: - std::vector m_pAdditionalModelParts; + std::vector m_pAdditionalModelParts; }; - - diff --git a/Minecraft.Client/Player/MultiPlayerGameMode.cpp b/Minecraft.Client/Player/MultiPlayerGameMode.cpp index 4e5e0426d..8d9957c3e 100644 --- a/Minecraft.Client/Player/MultiPlayerGameMode.cpp +++ b/Minecraft.Client/Player/MultiPlayerGameMode.cpp @@ -13,9 +13,9 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.inventory.h" #include "../../Minecraft.World/Headers/net.minecraft.h" -MultiPlayerGameMode::MultiPlayerGameMode(Minecraft *minecraft, ClientConnection *connection) -{ - // 4J - added initialisers +MultiPlayerGameMode::MultiPlayerGameMode(Minecraft* minecraft, + ClientConnection* connection) { + // 4J - added initialisers xDestroyBlock = -1; yDestroyBlock = -1; zDestroyBlock = -1; @@ -24,112 +24,102 @@ MultiPlayerGameMode::MultiPlayerGameMode(Minecraft *minecraft, ClientConnection destroyTicks = 0; destroyDelay = 0; isDestroying = false; - carriedItem = 0; - localPlayerMode = GameType::SURVIVAL; - this->minecraft = minecraft; - this->connection = connection; + carriedItem = 0; + localPlayerMode = GameType::SURVIVAL; + this->minecraft = minecraft; + this->connection = connection; } -void MultiPlayerGameMode::creativeDestroyBlock(Minecraft *minecraft, MultiPlayerGameMode *gameMode, int x, int y, int z, int face) -{ - if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) - { - gameMode->destroyBlock(x, y, z, face); - } +void MultiPlayerGameMode::creativeDestroyBlock(Minecraft* minecraft, + MultiPlayerGameMode* gameMode, + int x, int y, int z, int face) { + if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) { + gameMode->destroyBlock(x, y, z, face); + } } -void MultiPlayerGameMode::adjustPlayer(std::shared_ptr player) -{ - localPlayerMode->updatePlayerAbilities(&player->abilities); +void MultiPlayerGameMode::adjustPlayer(std::shared_ptr player) { + localPlayerMode->updatePlayerAbilities(&player->abilities); } -bool MultiPlayerGameMode::isCutScene() -{ - return false; +bool MultiPlayerGameMode::isCutScene() { return false; } + +void MultiPlayerGameMode::setLocalMode(GameType* mode) { + localPlayerMode = mode; + localPlayerMode->updatePlayerAbilities(&minecraft->player->abilities); } -void MultiPlayerGameMode::setLocalMode(GameType *mode) -{ - localPlayerMode = mode; - localPlayerMode->updatePlayerAbilities(&minecraft->player->abilities); +void MultiPlayerGameMode::initPlayer(std::shared_ptr player) { + player->yRot = -180; } -void MultiPlayerGameMode::initPlayer(std::shared_ptr player) -{ - player->yRot = -180; +bool MultiPlayerGameMode::canHurtPlayer() { + return localPlayerMode->isSurvival(); } -bool MultiPlayerGameMode::canHurtPlayer() -{ - return localPlayerMode->isSurvival(); -} +bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) { + if (localPlayerMode->isReadOnly()) { + return false; + } -bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) -{ - if (localPlayerMode->isReadOnly()) - { - return false; - } + Level* level = minecraft->level; + Tile* oldTile = Tile::tiles[level->getTile(x, y, z)]; - Level *level = minecraft->level; - Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; + if (oldTile == NULL) return false; - if (oldTile == NULL) return false; + level->levelEvent( + LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, + oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); - level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); + int data = level->getData(x, y, z); + bool changed = level->setTile(x, y, z, 0); + if (changed) { + oldTile->destroy(level, x, y, z, data); + } - int data = level->getData(x, y, z); - bool changed = level->setTile(x, y, z, 0); - if (changed) - { - oldTile->destroy(level, x, y, z, data); - } - - if (!localPlayerMode->isCreative()) - { - std::shared_ptr item = minecraft->player->getSelectedItem(); - if (item != NULL) - { - item->mineBlock(level, oldTile->id, x, y, z, minecraft->player); - if (item->count == 0) - { - minecraft->player->removeSelectedItem(); - } - } - } + if (!localPlayerMode->isCreative()) { + std::shared_ptr item = + minecraft->player->getSelectedItem(); + if (item != NULL) { + item->mineBlock(level, oldTile->id, x, y, z, minecraft->player); + if (item->count == 0) { + minecraft->player->removeSelectedItem(); + } + } + } return changed; } -void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) -{ - if(!minecraft->player->isAllowedToMine()) return; - if (localPlayerMode->isReadOnly()) - { - return; - } +void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) { + if (!minecraft->player->isAllowedToMine()) return; + if (localPlayerMode->isReadOnly()) { + return; + } - if (localPlayerMode->isCreative()) - { - connection->send(std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) )); - creativeDestroyBlock(minecraft, this, x, y, z, face); - destroyDelay = 5; - } - else if (!isDestroying || x != xDestroyBlock || y != yDestroyBlock || z != zDestroyBlock) - { - connection->send( std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); + if (localPlayerMode->isCreative()) { + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face))); + creativeDestroyBlock(minecraft, this, x, y, z, face); + destroyDelay = 5; + } else if (!isDestroying || x != xDestroyBlock || y != yDestroyBlock || + z != zDestroyBlock) { + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face))); int t = minecraft->level->getTile(x, y, z); - if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); + if (t > 0 && destroyProgress == 0) + Tile::tiles[t]->attack(minecraft->level, x, y, z, + minecraft->player); if (t > 0 && - (Tile::tiles[t]->getDestroyProgress(minecraft->player, minecraft->player->level, x, y, z) >= 1 || - (app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<getDestroyProgress( + minecraft->player, minecraft->player->level, x, y, z) >= 1 || + (app.DebugSettingsOn() && + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_InstantDestroy)))) { destroyBlock(x, y, z, face); - } - else - { + } else { isDestroying = true; xDestroyBlock = x; yDestroyBlock = y; @@ -137,342 +127,351 @@ void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); + minecraft->level->destroyTileProgress( + minecraft->player->entityId, xDestroyBlock, yDestroyBlock, + zDestroyBlock, (int)(destroyProgress * 10) - 1); } } - } -void MultiPlayerGameMode::stopDestroyBlock() -{ - if (isDestroying) - { - connection->send(std::shared_ptr(new PlayerActionPacket(PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1))); - } +void MultiPlayerGameMode::stopDestroyBlock() { + if (isDestroying) { + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, + yDestroyBlock, zDestroyBlock, -1))); + } - isDestroying = false; - destroyProgress = 0; - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); + isDestroying = false; + destroyProgress = 0; + minecraft->level->destroyTileProgress(minecraft->player->entityId, + xDestroyBlock, yDestroyBlock, + zDestroyBlock, -1); } -void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) -{ - if(!minecraft->player->isAllowedToMine()) return; +void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) { + if (!minecraft->player->isAllowedToMine()) return; ensureHasSentCarriedItem(); -// connection.send(new PlayerActionPacket(PlayerActionPacket.CONTINUE_DESTROY_BLOCK, x, y, z, face)); + // connection.send(new + // PlayerActionPacket(PlayerActionPacket.CONTINUE_DESTROY_BLOCK, x, + // y, z, face)); - if (destroyDelay > 0) - { + if (destroyDelay > 0) { destroyDelay--; return; } - if (localPlayerMode->isCreative()) - { - destroyDelay = 5; - connection->send(std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); - creativeDestroyBlock(minecraft, this, x, y, z, face); - return; - } + if (localPlayerMode->isCreative()) { + destroyDelay = 5; + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face))); + creativeDestroyBlock(minecraft, this, x, y, z, face); + return; + } - if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) - { + if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) { int t = minecraft->level->getTile(x, y, z); - if (t == 0) - { + if (t == 0) { isDestroying = false; return; } - Tile *tile = Tile::tiles[t]; + Tile* tile = Tile::tiles[t]; - destroyProgress += tile->getDestroyProgress(minecraft->player, minecraft->player->level, x, y, z); + destroyProgress += tile->getDestroyProgress( + minecraft->player, minecraft->player->level, x, y, z); - if (destroyTicks % 4 == 0) - { - if (tile != NULL) - { - int iStepSound=tile->soundType->getStepSound(); + if (destroyTicks % 4 == 0) { + if (tile != NULL) { + int iStepSound = tile->soundType->getStepSound(); - minecraft->soundEngine->play(iStepSound, x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f); + minecraft->soundEngine->play( + iStepSound, x + 0.5f, y + 0.5f, z + 0.5f, + (tile->soundType->getVolume() + 1) / 8, + tile->soundType->getPitch() * 0.5f); } } destroyTicks++; - if (destroyProgress >= 1) - { + if (destroyProgress >= 1) { isDestroying = false; - connection->send( std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face) ) ); - destroyBlock(x, y, z, face); + connection->send( + std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face))); + destroyBlock(x, y, z, face); destroyProgress = 0; oDestroyProgress = 0; destroyTicks = 0; destroyDelay = 5; } - minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); - } - else - { + minecraft->level->destroyTileProgress( + minecraft->player->entityId, xDestroyBlock, yDestroyBlock, + zDestroyBlock, (int)(destroyProgress * 10) - 1); + } else { startDestroyBlock(x, y, z, face); } - } -float MultiPlayerGameMode::getPickRange() -{ - if (localPlayerMode->isCreative()) - { - return 5.0f; - } - return 4.5f; +float MultiPlayerGameMode::getPickRange() { + if (localPlayerMode->isCreative()) { + return 5.0f; + } + return 4.5f; } -void MultiPlayerGameMode::tick() -{ +void MultiPlayerGameMode::tick() { ensureHasSentCarriedItem(); oDestroyProgress = destroyProgress; - //minecraft->soundEngine->playMusicTick(); + // minecraft->soundEngine->playMusicTick(); } -void MultiPlayerGameMode::ensureHasSentCarriedItem() -{ +void MultiPlayerGameMode::ensureHasSentCarriedItem() { int newItem = minecraft->player->inventory->selected; - if (newItem != carriedItem) - { + if (newItem != carriedItem) { carriedItem = newItem; - connection->send( std::shared_ptr( new SetCarriedItemPacket(carriedItem) ) ); + connection->send(std::shared_ptr( + new SetCarriedItemPacket(carriedItem))); } } -bool MultiPlayerGameMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly, bool *pbUsedItem) -{ - if( pbUsedItem ) *pbUsedItem = false; // Did we actually use the held item? +bool MultiPlayerGameMode::useItemOn(std::shared_ptr player, + Level* level, + std::shared_ptr item, int x, + int y, int z, int face, Vec3* hit, + bool bTestUseOnly, bool* pbUsedItem) { + if (pbUsedItem) *pbUsedItem = false; // Did we actually use the held item? - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if(!bTestUseOnly) - { - ensureHasSentCarriedItem(); - } - float clickX = (float) hit->x - x; - float clickY = (float) hit->y - y; - float clickZ = (float) hit->z - z; - bool didSomething = false; - int t = level->getTile(x, y, z); - - if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) - { - if(bTestUseOnly) - { - switch(t) - { - case Tile::recordPlayer_Id: - case Tile::bed_Id: // special case for a bed - if (Tile::tiles[t]->TestUse(level, x, y, z, player )) - { - return true; - } - else if (t==Tile::bed_Id) // 4J-JEV: You can still use items on record players (ie. set fire to them). - { - // bed is too far away, or something - return false; - } - break; - default: - if (Tile::tiles[t]->TestUse()) return true; - break; - } - } - else - { - if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ)) didSomething = true; - } - } + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (!bTestUseOnly) { + ensureHasSentCarriedItem(); + } + float clickX = (float)hit->x - x; + float clickY = (float)hit->y - y; + float clickZ = (float)hit->z - z; + bool didSomething = false; + int t = level->getTile(x, y, z); - if (!didSomething && item != NULL && dynamic_cast(item->getItem())) - { - TileItem *tile = dynamic_cast(item->getItem()); - if (!tile->mayPlace(level, x, y, z, face, player, item)) return false; - } + if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) { + if (bTestUseOnly) { + switch (t) { + case Tile::recordPlayer_Id: + case Tile::bed_Id: // special case for a bed + if (Tile::tiles[t]->TestUse(level, x, y, z, player)) { + return true; + } else if (t == Tile::bed_Id) // 4J-JEV: You can still use + // items on record players + // (ie. set fire to them). + { + // bed is too far away, or something + return false; + } + break; + default: + if (Tile::tiles[t]->TestUse()) return true; + break; + } + } else { + if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, + clickY, clickZ)) + didSomething = true; + } + } - // 4J Stu - In Java we send the use packet before the above check for item being NULL - // so the following never gets executed but the packet still gets sent (for opening chests etc) - if(item != NULL) - { - if(!didSomething && player->isAllowedToUse(item)) - { - if (localPlayerMode->isCreative()) - { - int aux = item->getAuxValue(); - int count = item->count; - didSomething = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnly); - item->setAuxValue(aux); - item->count = count; - } - else - { - didSomething = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnly); - } - if( didSomething ) - { - if( pbUsedItem ) *pbUsedItem = true; - } - } - } - else - { - // 4J - Bit of a hack, however seems preferable to any larger changes which would have more chance of causing unwanted side effects. - // If we aren't going to be actually performing the use method locally, then call this method with its "soundOnly" parameter set to true. - // This is an addition from the java version, and as its name suggests, doesn't actually perform the use locally but just makes any sounds that - // are meant to be directly caused by this. If we don't do this, then the sounds never happen as the tile's use method is only called on the - // server, and that won't allow any sounds that are directly made, or broadcast back level events to us that would make the sound, since we are - // the source of the event. - if( ( t > 0 ) && ( !bTestUseOnly ) && player->isAllowedToUse(Tile::tiles[t]) ) - { - Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ, true); - } - } + if (!didSomething && item != NULL && + dynamic_cast(item->getItem())) { + TileItem* tile = dynamic_cast(item->getItem()); + if (!tile->mayPlace(level, x, y, z, face, player, item)) return false; + } - // 4J Stu - Do the action before we send the packet, so that our predicted count is sent in the packet and the server - // doesn't think it has to update us - // Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. - if(!bTestUseOnly) - { - connection->send( std::shared_ptr( new UseItemPacket(x, y, z, face, player->inventory->getSelected(), clickX, clickY, clickZ) ) ); - } + // 4J Stu - In Java we send the use packet before the above check for item + // being NULL so the following never gets executed but the packet still gets + // sent (for opening chests etc) + if (item != NULL) { + if (!didSomething && player->isAllowedToUse(item)) { + if (localPlayerMode->isCreative()) { + int aux = item->getAuxValue(); + int count = item->count; + didSomething = item->useOn(player, level, x, y, z, face, clickX, + clickY, clickZ, bTestUseOnly); + item->setAuxValue(aux); + item->count = count; + } else { + didSomething = item->useOn(player, level, x, y, z, face, clickX, + clickY, clickZ, bTestUseOnly); + } + if (didSomething) { + if (pbUsedItem) *pbUsedItem = true; + } + } + } else { + // 4J - Bit of a hack, however seems preferable to any larger changes + // which would have more chance of causing unwanted side effects. If we + // aren't going to be actually performing the use method locally, then + // call this method with its "soundOnly" parameter set to true. This is + // an addition from the java version, and as its name suggests, doesn't + // actually perform the use locally but just makes any sounds that are + // meant to be directly caused by this. If we don't do this, then the + // sounds never happen as the tile's use method is only called on the + // server, and that won't allow any sounds that are directly made, or + // broadcast back level events to us that would make the sound, since we + // are the source of the event. + if ((t > 0) && (!bTestUseOnly) && + player->isAllowedToUse(Tile::tiles[t])) { + Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, + clickZ, true); + } + } + + // 4J Stu - Do the action before we send the packet, so that our predicted + // count is sent in the packet and the server doesn't think it has to update + // us Fix for #7904 - Gameplay: Players can dupe torches by throwing them + // repeatedly into water. + if (!bTestUseOnly) { + connection->send(std::shared_ptr( + new UseItemPacket(x, y, z, face, player->inventory->getSelected(), + clickX, clickY, clickZ))); + } return didSomething; } -bool MultiPlayerGameMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly) -{ - if(!player->isAllowedToUse(item)) return false; +bool MultiPlayerGameMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly) { + if (!player->isAllowedToUse(item)) return false; - // 4J-PB - Adding a test only version to allow tooltips to be displayed - if(!bTestUseOnly) - { - ensureHasSentCarriedItem(); - } + // 4J-PB - Adding a test only version to allow tooltips to be displayed + if (!bTestUseOnly) { + ensureHasSentCarriedItem(); + } - // 4J Stu - Do the action before we send the packet, so that our predicted count is sent in the packet and the server - // doesn't think it has to update us, or can update us if we are wrong - // Fix for #13120 - Using a bucket of water or lava in the spawn area (centre of the map) causes the inventory to get out of sync + // 4J Stu - Do the action before we send the packet, so that our predicted + // count is sent in the packet and the server doesn't think it has to update + // us, or can update us if we are wrong Fix for #13120 - Using a bucket of + // water or lava in the spawn area (centre of the map) causes the inventory + // to get out of sync bool result = false; - - // 4J-PB added for tooltips to test use only - if(bTestUseOnly) - { - result = item->TestUse(level, player); - } - else - { - int oldCount = item->count; - std::shared_ptr itemInstance = item->use(level, player); - if ((itemInstance != NULL && itemInstance != item) || (itemInstance != NULL && itemInstance->count != oldCount)) - { - player->inventory->items[player->inventory->selected] = itemInstance; - if (itemInstance->count == 0) - { - player->inventory->items[player->inventory->selected] = nullptr; - } - result = true; - } - } - - if(!bTestUseOnly) - { - connection->send( std::shared_ptr( new UseItemPacket(-1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0) ) ); - } + + // 4J-PB added for tooltips to test use only + if (bTestUseOnly) { + result = item->TestUse(level, player); + } else { + int oldCount = item->count; + std::shared_ptr itemInstance = item->use(level, player); + if ((itemInstance != NULL && itemInstance != item) || + (itemInstance != NULL && itemInstance->count != oldCount)) { + player->inventory->items[player->inventory->selected] = + itemInstance; + if (itemInstance->count == 0) { + player->inventory->items[player->inventory->selected] = nullptr; + } + result = true; + } + } + + if (!bTestUseOnly) { + connection->send(std::shared_ptr(new UseItemPacket( + -1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0))); + } return result; } -std::shared_ptr MultiPlayerGameMode::createPlayer(Level *level) -{ - return std::shared_ptr( new MultiplayerLocalPlayer(minecraft, level, minecraft->user, connection) ); +std::shared_ptr MultiPlayerGameMode::createPlayer( + Level* level) { + return std::shared_ptr(new MultiplayerLocalPlayer( + minecraft, level, minecraft->user, connection)); } -void MultiPlayerGameMode::attack(std::shared_ptr player, std::shared_ptr entity) -{ +void MultiPlayerGameMode::attack(std::shared_ptr player, + std::shared_ptr entity) { ensureHasSentCarriedItem(); - connection->send( std::shared_ptr( new InteractPacket(player->entityId, entity->entityId, InteractPacket::ATTACK) ) ); + connection->send(std::shared_ptr(new InteractPacket( + player->entityId, entity->entityId, InteractPacket::ATTACK))); player->attack(entity); } -bool MultiPlayerGameMode::interact(std::shared_ptr player, std::shared_ptr entity) -{ +bool MultiPlayerGameMode::interact(std::shared_ptr player, + std::shared_ptr entity) { ensureHasSentCarriedItem(); - connection->send(std::shared_ptr( new InteractPacket(player->entityId, entity->entityId, InteractPacket::INTERACT) ) ); + connection->send(std::shared_ptr(new InteractPacket( + player->entityId, entity->entityId, InteractPacket::INTERACT))); return player->interact(entity); } -std::shared_ptr MultiPlayerGameMode::handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player) -{ +std::shared_ptr MultiPlayerGameMode::handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player) { short changeUid = player->containerMenu->backup(player->inventory); - std::shared_ptr clicked = player->containerMenu->clicked(slotNum, buttonNum, quickKeyHeld?AbstractContainerMenu::CLICK_QUICK_MOVE:AbstractContainerMenu::CLICK_PICKUP, player); - connection->send( std::shared_ptr( new ContainerClickPacket(containerId, slotNum, buttonNum, quickKeyHeld, clicked, changeUid) ) ); + std::shared_ptr clicked = player->containerMenu->clicked( + slotNum, buttonNum, + quickKeyHeld ? AbstractContainerMenu::CLICK_QUICK_MOVE + : AbstractContainerMenu::CLICK_PICKUP, + player); + connection->send(std::shared_ptr( + new ContainerClickPacket(containerId, slotNum, buttonNum, quickKeyHeld, + clicked, changeUid))); return clicked; } -void MultiPlayerGameMode::handleInventoryButtonClick(int containerId, int buttonId) -{ - connection->send(std::shared_ptr( new ContainerButtonClickPacket(containerId, buttonId) )); +void MultiPlayerGameMode::handleInventoryButtonClick(int containerId, + int buttonId) { + connection->send(std::shared_ptr( + new ContainerButtonClickPacket(containerId, buttonId))); } -void MultiPlayerGameMode::handleCreativeModeItemAdd(std::shared_ptr clicked, int slot) -{ - if (localPlayerMode->isCreative()) - { - connection->send(std::shared_ptr( new SetCreativeModeSlotPacket(slot, clicked) ) ); - } +void MultiPlayerGameMode::handleCreativeModeItemAdd( + std::shared_ptr clicked, int slot) { + if (localPlayerMode->isCreative()) { + connection->send(std::shared_ptr( + new SetCreativeModeSlotPacket(slot, clicked))); + } } -void MultiPlayerGameMode::handleCreativeModeItemDrop(std::shared_ptr clicked) -{ - if (localPlayerMode->isCreative() && clicked != NULL) - { - connection->send(std::shared_ptr( new SetCreativeModeSlotPacket(-1, clicked) ) ); - } +void MultiPlayerGameMode::handleCreativeModeItemDrop( + std::shared_ptr clicked) { + if (localPlayerMode->isCreative() && clicked != NULL) { + connection->send(std::shared_ptr( + new SetCreativeModeSlotPacket(-1, clicked))); + } } -void MultiPlayerGameMode::releaseUsingItem(std::shared_ptr player) -{ - ensureHasSentCarriedItem(); - connection->send(std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255) ) ); - player->releaseUsingItem(); +void MultiPlayerGameMode::releaseUsingItem(std::shared_ptr player) { + ensureHasSentCarriedItem(); + connection->send(std::shared_ptr(new PlayerActionPacket( + PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255))); + player->releaseUsingItem(); } -bool MultiPlayerGameMode::hasExperience() -{ - return true; +bool MultiPlayerGameMode::hasExperience() { return true; } + +bool MultiPlayerGameMode::hasMissTime() { + return !localPlayerMode->isCreative(); } -bool MultiPlayerGameMode::hasMissTime() -{ - return !localPlayerMode->isCreative(); +bool MultiPlayerGameMode::hasInfiniteItems() { + return localPlayerMode->isCreative(); } -bool MultiPlayerGameMode::hasInfiniteItems() -{ - return localPlayerMode->isCreative(); +bool MultiPlayerGameMode::hasFarPickRange() { + return localPlayerMode->isCreative(); } -bool MultiPlayerGameMode::hasFarPickRange() -{ - return localPlayerMode->isCreative(); -} - -bool MultiPlayerGameMode::handleCraftItem(int recipe, std::shared_ptr player) -{ +bool MultiPlayerGameMode::handleCraftItem(int recipe, + std::shared_ptr player) { short changeUid = player->containerMenu->backup(player->inventory); - connection->send( std::shared_ptr( new CraftItemPacket(recipe, changeUid) ) ); + connection->send(std::shared_ptr( + new CraftItemPacket(recipe, changeUid))); return true; } -void MultiPlayerGameMode::handleDebugOptions(unsigned int uiVal, std::shared_ptr player) -{ - player->SetDebugOptions(uiVal); - connection->send( std::shared_ptr( new DebugOptionsPacket(uiVal) ) ); +void MultiPlayerGameMode::handleDebugOptions(unsigned int uiVal, + std::shared_ptr player) { + player->SetDebugOptions(uiVal); + connection->send( + std::shared_ptr(new DebugOptionsPacket(uiVal))); } diff --git a/Minecraft.Client/Player/MultiPlayerGameMode.h b/Minecraft.Client/Player/MultiPlayerGameMode.h index 34396aebd..d136461c6 100644 --- a/Minecraft.Client/Player/MultiPlayerGameMode.h +++ b/Minecraft.Client/Player/MultiPlayerGameMode.h @@ -4,65 +4,80 @@ class ClientConnection; class GameType; class Vec3; -class MultiPlayerGameMode -{ +class MultiPlayerGameMode { private: - int xDestroyBlock; + int xDestroyBlock; int yDestroyBlock; int zDestroyBlock; float destroyProgress; float oDestroyProgress; - int destroyTicks; // 4J was float but doesn't seem to need to be + int destroyTicks; // 4J was float but doesn't seem to need to be int destroyDelay; bool isDestroying; - GameType *localPlayerMode; - ClientConnection *connection; + GameType* localPlayerMode; + ClientConnection* connection; protected: - Minecraft *minecraft; + Minecraft* minecraft; public: - MultiPlayerGameMode(Minecraft *minecraft, ClientConnection *connection); - virtual ~MultiPlayerGameMode(){} - static void creativeDestroyBlock(Minecraft *minecraft, MultiPlayerGameMode *gameMode, int x, int y, int z, int face); - void adjustPlayer(std::shared_ptr player); - bool isCutScene(); - void setLocalMode(GameType *mode); + MultiPlayerGameMode(Minecraft* minecraft, ClientConnection* connection); + virtual ~MultiPlayerGameMode() {} + static void creativeDestroyBlock(Minecraft* minecraft, + MultiPlayerGameMode* gameMode, int x, + int y, int z, int face); + void adjustPlayer(std::shared_ptr player); + bool isCutScene(); + void setLocalMode(GameType* mode); virtual void initPlayer(std::shared_ptr player); - virtual bool canHurtPlayer(); + virtual bool canHurtPlayer(); virtual bool destroyBlock(int x, int y, int z, int face); virtual void startDestroyBlock(int x, int y, int z, int face); virtual void stopDestroyBlock(); virtual void continueDestroyBlock(int x, int y, int z, int face); virtual float getPickRange(); virtual void tick(); -private: - int carriedItem; private: - void ensureHasSentCarriedItem(); + int carriedItem; + +private: + void ensureHasSentCarriedItem(); + public: - virtual bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly=false, bool *pbUsedItem=NULL); - virtual bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly=false); - virtual std::shared_ptr createPlayer(Level *level); - virtual void attack(std::shared_ptr player, std::shared_ptr entity); - virtual bool interact(std::shared_ptr player, std::shared_ptr entity); - virtual std::shared_ptr handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr player); - virtual void handleInventoryButtonClick(int containerId, int buttonId); - virtual void handleCreativeModeItemAdd(std::shared_ptr clicked, int slot); - virtual void handleCreativeModeItemDrop(std::shared_ptr clicked); - virtual void releaseUsingItem(std::shared_ptr player); - virtual bool hasExperience(); - virtual bool hasMissTime(); - virtual bool hasInfiniteItems(); - virtual bool hasFarPickRange(); - - // 4J Stu - Added so we can send packets for this in the network game - virtual bool handleCraftItem(int recipe, std::shared_ptr player); - virtual void handleDebugOptions(unsigned int uiVal, std::shared_ptr player); + virtual bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, + int z, int face, Vec3* hit, + bool bTestUseOnly = false, bool* pbUsedItem = NULL); + virtual bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly = false); + virtual std::shared_ptr createPlayer(Level* level); + virtual void attack(std::shared_ptr player, + std::shared_ptr entity); + virtual bool interact(std::shared_ptr player, + std::shared_ptr entity); + virtual std::shared_ptr handleInventoryMouseClick( + int containerId, int slotNum, int buttonNum, bool quickKeyHeld, + std::shared_ptr player); + virtual void handleInventoryButtonClick(int containerId, int buttonId); + virtual void handleCreativeModeItemAdd( + std::shared_ptr clicked, int slot); + virtual void handleCreativeModeItemDrop( + std::shared_ptr clicked); + virtual void releaseUsingItem(std::shared_ptr player); + virtual bool hasExperience(); + virtual bool hasMissTime(); + virtual bool hasInfiniteItems(); + virtual bool hasFarPickRange(); - // 4J Stu - Added for tutorial checks - virtual bool isInputAllowed(int mapping) { return true; } - virtual bool isTutorial() { return false; } - virtual Tutorial *getTutorial() { return NULL; } + // 4J Stu - Added so we can send packets for this in the network game + virtual bool handleCraftItem(int recipe, std::shared_ptr player); + virtual void handleDebugOptions(unsigned int uiVal, + std::shared_ptr player); + + // 4J Stu - Added for tutorial checks + virtual bool isInputAllowed(int mapping) { return true; } + virtual bool isTutorial() { return false; } + virtual Tutorial* getTutorial() { return NULL; } }; diff --git a/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp b/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp index 3b9a9e676..8b79bcadc 100644 --- a/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp +++ b/Minecraft.Client/Player/MultiPlayerLocalPlayer.cpp @@ -1,5 +1,5 @@ #include "../Platform/stdafx.h" -//#include "../../Minecraft.World/Util/JavaMath.h" +// #include "../../Minecraft.World/Util/JavaMath.h" #include "MultiPlayerLocalPlayer.h" #include "../Network/ClientConnection.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" @@ -13,91 +13,107 @@ #include "../../Minecraft.World/Level/LevelData.h" #include "../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" - - - -MultiplayerLocalPlayer::MultiplayerLocalPlayer(Minecraft *minecraft, Level *level, User *user, ClientConnection *connection) : LocalPlayer(minecraft, level, user, level->dimension->id) -{ - // 4J - added initialisers +MultiplayerLocalPlayer::MultiplayerLocalPlayer(Minecraft* minecraft, + Level* level, User* user, + ClientConnection* connection) + : LocalPlayer(minecraft, level, user, level->dimension->id) { + // 4J - added initialisers flashOnSetHealth = false; - xLast = yLast1 = yLast2 = zLast = 0; + xLast = yLast1 = yLast2 = zLast = 0; yRotLast = xRotLast = 0; - lastOnGround = false; + lastOnGround = false; lastSneaked = false; - lastIdle = false; - lastSprinting = false; + lastIdle = false; + lastSprinting = false; positionReminder = 0; this->connection = connection; } -bool MultiplayerLocalPlayer::hurt(DamageSource *source, int dmg) -{ - return false; +bool MultiplayerLocalPlayer::hurt(DamageSource* source, int dmg) { + return false; } -void MultiplayerLocalPlayer::heal(int heal) -{ -} +void MultiplayerLocalPlayer::heal(int heal) {} -void MultiplayerLocalPlayer::tick() -{ - // 4J Added - // 4J-PB - changing this to a game host option ot hide gamertags - //bool bIsisPrimaryHost=g_NetworkManager.IsHost() && (ProfileManager.GetPrimaryPad()==m_iPad); +void MultiplayerLocalPlayer::tick() { + // 4J Added + // 4J-PB - changing this to a game host option ot hide gamertags + // bool bIsisPrimaryHost=g_NetworkManager.IsHost() && + // (ProfileManager.GetPrimaryPad()==m_iPad); - /*if((app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0) != m_bShownOnMaps) - { - m_bShownOnMaps = (app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0); - if (m_bShownOnMaps) connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::SHOW_ON_MAPS) ) ); - else connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::HIDE_ON_MAPS) ) ); - }*/ + /*if((app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0) != + m_bShownOnMaps) + { + m_bShownOnMaps = + (app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0); if + (m_bShownOnMaps) connection->send( std::shared_ptr( new + PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::SHOW_ON_MAPS) ) + ); else connection->send( std::shared_ptr( new + PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::HIDE_ON_MAPS) ) + ); + }*/ - if (!level->hasChunkAt(Mth::floor(x), 0, Mth::floor(z))) return; + if (!level->hasChunkAt(Mth::floor(x), 0, Mth::floor(z))) return; - double tempX = x, tempY = y, tempZ = z; + double tempX = x, tempY = y, tempZ = z; LocalPlayer::tick(); - - //if( !minecraft->localgameModes[m_iPad]->isTutorial() || minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, tempY, tempZ, x, y, z) ) - if(minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, tempY, tempZ, x, y, z)) - { - sendPosition(); - } - else - { - //app.Debugprintf("Cannot move to position (%f, %f, %f), falling back to (%f, %f, %f)\n", x, y, z, tempX, y, tempZ); - this->setPos(tempX, y, tempZ); - } + + // if( !minecraft->localgameModes[m_iPad]->isTutorial() || + // minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, + // tempY, tempZ, x, y, z) ) + if (minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition( + tempX, tempY, tempZ, x, y, z)) { + sendPosition(); + } else { + // app.Debugprintf("Cannot move to position (%f, %f, %f), falling back + // to (%f, %f, %f)\n", x, y, z, tempX, y, tempZ); + this->setPos(tempX, y, tempZ); + } } -void MultiplayerLocalPlayer::sendPosition() -{ - bool sprinting = isSprinting(); - if (sprinting != lastSprinting) - { - if (sprinting) connection->send(std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SPRINTING))); - else connection->send(std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SPRINTING))); +void MultiplayerLocalPlayer::sendPosition() { + bool sprinting = isSprinting(); + if (sprinting != lastSprinting) { + if (sprinting) + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::START_SPRINTING))); + else + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_SPRINTING))); - lastSprinting = sprinting; - } + lastSprinting = sprinting; + } bool sneaking = isSneaking(); - if (sneaking != lastSneaked) - { - if (sneaking) connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SNEAKING) ) ); - else connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SNEAKING) ) ); + if (sneaking != lastSneaked) { + if (sneaking) + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::START_SNEAKING))); + else + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_SNEAKING))); lastSneaked = sneaking; } - bool idle = isIdle(); - if (idle != lastIdle) - { - if (idle) connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_IDLEANIM) ) ); - else connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM) ) ); + bool idle = isIdle(); + if (idle != lastIdle) { + if (idle) + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::START_IDLEANIM))); + else + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM))); - lastIdle = idle; - } + lastIdle = idle; + } double xdd = x - xLast; double ydd1 = bb->y0 - yLast1; @@ -106,266 +122,244 @@ void MultiplayerLocalPlayer::sendPosition() double rydd = yRot - yRotLast; double rxdd = xRot - xRotLast; - bool move = (xdd * xdd + ydd1 * ydd1 + zdd * zdd) > 0.03 * 0.03 || positionReminder >= POSITION_REMINDER_INTERVAL; + bool move = (xdd * xdd + ydd1 * ydd1 + zdd * zdd) > 0.03 * 0.03 || + positionReminder >= POSITION_REMINDER_INTERVAL; bool rot = rydd != 0 || rxdd != 0; - if (riding != NULL) - { - connection->send( std::shared_ptr( new MovePlayerPacket::PosRot(xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying) ) ); + if (riding != NULL) { + connection->send( + std::shared_ptr(new MovePlayerPacket::PosRot( + xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying))); move = false; - } - else - { - if (move && rot) - { - connection->send( std::shared_ptr( new MovePlayerPacket::PosRot(x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying) ) ); - } - else if (move) - { - connection->send( std::shared_ptr( new MovePlayerPacket::Pos(x, bb->y0, y, z, onGround, abilities.flying) ) ); - } - else if (rot) - { - connection->send( std::shared_ptr( new MovePlayerPacket::Rot(yRot, xRot, onGround, abilities.flying) ) ); - } - else - { - connection->send( std::shared_ptr( new MovePlayerPacket(onGround, abilities.flying) ) ); + } else { + if (move && rot) { + connection->send( + std::shared_ptr(new MovePlayerPacket::PosRot( + x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying))); + } else if (move) { + connection->send( + std::shared_ptr(new MovePlayerPacket::Pos( + x, bb->y0, y, z, onGround, abilities.flying))); + } else if (rot) { + connection->send( + std::shared_ptr(new MovePlayerPacket::Rot( + yRot, xRot, onGround, abilities.flying))); + } else { + connection->send(std::shared_ptr( + new MovePlayerPacket(onGround, abilities.flying))); } } - positionReminder++; + positionReminder++; lastOnGround = onGround; - if (move) - { + if (move) { xLast = x; yLast1 = bb->y0; yLast2 = y; zLast = z; - positionReminder = 0; + positionReminder = 0; } - if (rot) - { + if (rot) { yRotLast = yRot; xRotLast = xRot; } - } -std::shared_ptr MultiplayerLocalPlayer::drop() -{ - connection->send( std::shared_ptr( new PlayerActionPacket(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0) ) ); - return nullptr; +std::shared_ptr MultiplayerLocalPlayer::drop() { + connection->send(std::shared_ptr( + new PlayerActionPacket(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0))); + return nullptr; } -void MultiplayerLocalPlayer::reallyDrop(std::shared_ptr itemEntity) -{ +void MultiplayerLocalPlayer::reallyDrop( + std::shared_ptr itemEntity) {} + +void MultiplayerLocalPlayer::chat(const std::wstring& message) { + connection->send(std::shared_ptr(new ChatPacket(message))); } -void MultiplayerLocalPlayer::chat(const std::wstring& message) -{ - connection->send( std::shared_ptr( new ChatPacket(message) ) ); +void MultiplayerLocalPlayer::swing() { + LocalPlayer::swing(); + connection->send(std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::SWING))); } -void MultiplayerLocalPlayer::swing() -{ - LocalPlayer::swing(); - connection->send( std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::SWING) ) ); - +void MultiplayerLocalPlayer::respawn() { + connection->send(std::shared_ptr( + new ClientCommandPacket(ClientCommandPacket::PERFORM_RESPAWN))); } -void MultiplayerLocalPlayer::respawn() -{ - connection->send( std::shared_ptr( new ClientCommandPacket(ClientCommandPacket::PERFORM_RESPAWN))); -} - - -void MultiplayerLocalPlayer::actuallyHurt(DamageSource *source, int dmg) -{ - setHealth(getHealth() - dmg); +void MultiplayerLocalPlayer::actuallyHurt(DamageSource* source, int dmg) { + setHealth(getHealth() - dmg); } // 4J Added override to capture event for tutorial messages -void MultiplayerLocalPlayer::completeUsingItem() -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(useItem != NULL && pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->completeUsingItem(useItem); - } - Player::completeUsingItem(); +void MultiplayerLocalPlayer::completeUsingItem() { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (useItem != NULL && pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->completeUsingItem(useItem); + } + Player::completeUsingItem(); } -void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance *effect) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); - } - Player::onEffectAdded(effect); +void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance* effect) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); + } + Player::onEffectAdded(effect); } - -void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance *effect) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); - } - Player::onEffectUpdated(effect); +void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance* effect) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); + } + Player::onEffectUpdated(effect); } - -void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance *effect) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - if(pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - Tutorial *tutorial = gameMode->getTutorial(); - tutorial->onEffectChanged(MobEffect::effects[effect->getId()],true); - } - Player::onEffectRemoved(effect); +void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance* effect) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + Tutorial* tutorial = gameMode->getTutorial(); + tutorial->onEffectChanged(MobEffect::effects[effect->getId()], true); + } + Player::onEffectRemoved(effect); } -void MultiplayerLocalPlayer::closeContainer() -{ - connection->send( std::shared_ptr( new ContainerClosePacket(containerMenu->containerId) ) ); +void MultiplayerLocalPlayer::closeContainer() { + connection->send(std::shared_ptr( + new ContainerClosePacket(containerMenu->containerId))); inventory->setCarried(nullptr); LocalPlayer::closeContainer(); } -void MultiplayerLocalPlayer::hurtTo(int newHealth, ETelemetryChallenges damageSource) -{ - if (flashOnSetHealth) - { - LocalPlayer::hurtTo(newHealth, damageSource); - } - else - { - setHealth(newHealth); - flashOnSetHealth = true; - } +void MultiplayerLocalPlayer::hurtTo(int newHealth, + ETelemetryChallenges damageSource) { + if (flashOnSetHealth) { + LocalPlayer::hurtTo(newHealth, damageSource); + } else { + setHealth(newHealth); + flashOnSetHealth = true; + } } -void MultiplayerLocalPlayer::awardStat(Stat *stat, byteArray param) -{ - if (stat == NULL) - { - delete [] param.data; +void MultiplayerLocalPlayer::awardStat(Stat* stat, byteArray param) { + if (stat == NULL) { + delete[] param.data; return; } - if (stat->awardLocallyOnly) - { - LocalPlayer::awardStat(stat, param); - } - else - { - delete [] param.data; + if (stat->awardLocallyOnly) { + LocalPlayer::awardStat(stat, param); + } else { + delete[] param.data; return; } } -void MultiplayerLocalPlayer::awardStatFromServer(Stat *stat, byteArray param) -{ - if ( stat != NULL && !stat->awardLocallyOnly ) - { - LocalPlayer::awardStat(stat, param); - } - else delete [] param.data; +void MultiplayerLocalPlayer::awardStatFromServer(Stat* stat, byteArray param) { + if (stat != NULL && !stat->awardLocallyOnly) { + LocalPlayer::awardStat(stat, param); + } else + delete[] param.data; } -void MultiplayerLocalPlayer::onUpdateAbilities() -{ - connection->send(std::shared_ptr(new PlayerAbilitiesPacket(&abilities))); +void MultiplayerLocalPlayer::onUpdateAbilities() { + connection->send(std::shared_ptr( + new PlayerAbilitiesPacket(&abilities))); } -bool MultiplayerLocalPlayer::isLocalPlayer() -{ - return true; +bool MultiplayerLocalPlayer::isLocalPlayer() { return true; } + +void MultiplayerLocalPlayer::ride(std::shared_ptr e) { + bool wasRiding = riding != NULL; + LocalPlayer::ride(e); + bool isRiding = riding != NULL; + + if (isRiding) { + ETelemetryChallenges eventType = eTelemetryChallenges_Unknown; + if (this->riding != NULL) { + switch (riding->GetType()) { + case eTYPE_BOAT: + eventType = eTelemetryInGame_Ride_Boat; + break; + case eTYPE_MINECART: + eventType = eTelemetryInGame_Ride_Minecart; + break; + case eTYPE_PIG: + eventType = eTelemetryInGame_Ride_Pig; + break; + default: + break; + }; + } + TelemetryManager->RecordEnemyKilledOrOvercome(GetXboxPad(), 0, y, 0, 0, + 0, 0, eventType); + } + + updateRichPresence(); + + Minecraft* pMinecraft = Minecraft::GetInstance(); + + if (pMinecraft->localgameModes[m_iPad] != NULL) { + TutorialMode* gameMode = + (TutorialMode*)pMinecraft->localgameModes[m_iPad]; + if (wasRiding && !isRiding) { + gameMode->getTutorial()->changeTutorialState( + e_Tutorial_State_Gameplay); + } else if (!wasRiding && isRiding) { + if (std::dynamic_pointer_cast(e) != NULL) + gameMode->getTutorial()->changeTutorialState( + e_Tutorial_State_Riding_Minecart); + else if (std::dynamic_pointer_cast(e) != NULL) + gameMode->getTutorial()->changeTutorialState( + e_Tutorial_State_Riding_Boat); + } + } } -void MultiplayerLocalPlayer::ride(std::shared_ptr e) -{ - bool wasRiding = riding != NULL; - LocalPlayer::ride(e); - bool isRiding = riding != NULL; - - if( isRiding ) - { - ETelemetryChallenges eventType = eTelemetryChallenges_Unknown; - if( this->riding != NULL ) - { - switch(riding->GetType()) - { - case eTYPE_BOAT: - eventType = eTelemetryInGame_Ride_Boat; - break; - case eTYPE_MINECART: - eventType = eTelemetryInGame_Ride_Minecart; - break; - case eTYPE_PIG: - eventType = eTelemetryInGame_Ride_Pig; - break; - default: - break; - }; - } - TelemetryManager->RecordEnemyKilledOrOvercome(GetXboxPad(), 0, y, 0, 0, 0, 0, eventType); - } - - updateRichPresence(); - - Minecraft *pMinecraft = Minecraft::GetInstance(); - - if( pMinecraft->localgameModes[m_iPad] != NULL ) - { - TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; - if(wasRiding && !isRiding) - { - gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Gameplay); - } - else if (!wasRiding && isRiding) - { - if(std::dynamic_pointer_cast(e) != NULL) - gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Riding_Minecart); - else if(std::dynamic_pointer_cast(e) != NULL) - gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Riding_Boat); - } - } -} - -void MultiplayerLocalPlayer::StopSleeping() -{ - connection->send( std::shared_ptr( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SLEEPING) ) ); +void MultiplayerLocalPlayer::StopSleeping() { + connection->send( + std::shared_ptr(new PlayerCommandPacket( + shared_from_this(), PlayerCommandPacket::STOP_SLEEPING))); } // 4J Added -void MultiplayerLocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) -{ - std::uint32_t oldSkinIndex = getCustomSkin(); - LocalPlayer::setCustomSkin(skinId); +void MultiplayerLocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) { + std::uint32_t oldSkinIndex = getCustomSkin(); + LocalPlayer::setCustomSkin(skinId); #ifndef _CONTENT_PACKAGE - wprintf(L"Skin for local player %ls has changed to %ls (%d)\n", name.c_str(), customTextureUrl.c_str(), getPlayerDefaultSkin() ); + wprintf(L"Skin for local player %ls has changed to %ls (%d)\n", + name.c_str(), customTextureUrl.c_str(), getPlayerDefaultSkin()); #endif - if(getCustomSkin() != oldSkinIndex) connection->send( std::shared_ptr( new TextureAndGeometryChangePacket( shared_from_this(), app.GetPlayerSkinName(GetXboxPad()) ) ) ); + if (getCustomSkin() != oldSkinIndex) + connection->send(std::shared_ptr( + new TextureAndGeometryChangePacket( + shared_from_this(), app.GetPlayerSkinName(GetXboxPad())))); } -void MultiplayerLocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) -{ - std::uint32_t oldCapeIndex = getCustomCape(); - LocalPlayer::setCustomCape(capeId); +void MultiplayerLocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) { + std::uint32_t oldCapeIndex = getCustomCape(); + LocalPlayer::setCustomCape(capeId); #ifndef _CONTENT_PACKAGE - wprintf(L"Cape for local player %ls has changed to %ls\n", name.c_str(), customTextureUrl2.c_str()); + wprintf(L"Cape for local player %ls has changed to %ls\n", name.c_str(), + customTextureUrl2.c_str()); #endif - if(getCustomCape() != oldCapeIndex) connection->send( std::shared_ptr( new TextureChangePacket( shared_from_this(), TextureChangePacket::e_TextureChange_Cape, app.GetPlayerCapeName(GetXboxPad()) ) ) ); + if (getCustomCape() != oldCapeIndex) + connection->send( + std::shared_ptr(new TextureChangePacket( + shared_from_this(), TextureChangePacket::e_TextureChange_Cape, + app.GetPlayerCapeName(GetXboxPad())))); } diff --git a/Minecraft.Client/Player/MultiPlayerLocalPlayer.h b/Minecraft.Client/Player/MultiPlayerLocalPlayer.h index ea66686c0..b865dd566 100644 --- a/Minecraft.Client/Player/MultiPlayerLocalPlayer.h +++ b/Minecraft.Client/Player/MultiPlayerLocalPlayer.h @@ -7,68 +7,80 @@ class ClientConnection; class Minecraft; class Level; -class MultiplayerLocalPlayer : public LocalPlayer -{ +class MultiplayerLocalPlayer : public LocalPlayer { private: - static const int POSITION_REMINDER_INTERVAL = SharedConstants::TICKS_PER_SECOND; + static const int POSITION_REMINDER_INTERVAL = + SharedConstants::TICKS_PER_SECOND; + public: - ClientConnection *connection; + ClientConnection* connection; + private: bool flashOnSetHealth; + public: - MultiplayerLocalPlayer(Minecraft *minecraft, Level *level, User *user, ClientConnection *connection); + MultiplayerLocalPlayer(Minecraft* minecraft, Level* level, User* user, + ClientConnection* connection); + private: - double xLast, yLast1, yLast2, zLast; + double xLast, yLast1, yLast2, zLast; float yRotLast, xRotLast; + public: - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); virtual void heal(int heal); virtual void tick(); -private: - bool lastOnGround; - bool lastSneaked; - bool lastIdle; - bool lastSprinting; - int positionReminder; -public: - void sendPosition(); - using Player::drop; - virtual std::shared_ptr drop(); -protected: - virtual void reallyDrop(std::shared_ptr itemEntity); +private: + bool lastOnGround; + bool lastSneaked; + bool lastIdle; + bool lastSprinting; + int positionReminder; + public: - virtual void chat(const std::wstring& message); + void sendPosition(); + + using Player::drop; + virtual std::shared_ptr drop(); + +protected: + virtual void reallyDrop(std::shared_ptr itemEntity); + +public: + virtual void chat(const std::wstring& message); virtual void swing(); virtual void respawn(); + protected: - virtual void actuallyHurt(DamageSource *source, int dmg); + virtual void actuallyHurt(DamageSource* source, int dmg); - // 4J Added override to capture event for tutorial messages - virtual void completeUsingItem(); + // 4J Added override to capture event for tutorial messages + virtual void completeUsingItem(); + + // 4J Added overrides to capture events for tutorial + virtual void onEffectAdded(MobEffectInstance* effect); + virtual void onEffectUpdated(MobEffectInstance* effect); + virtual void onEffectRemoved(MobEffectInstance* effect); - // 4J Added overrides to capture events for tutorial - virtual void onEffectAdded(MobEffectInstance *effect); - virtual void onEffectUpdated(MobEffectInstance *effect); - virtual void onEffectRemoved(MobEffectInstance *effect); public: - virtual void closeContainer(); + virtual void closeContainer(); virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource); - virtual void awardStat(Stat *stat, byteArray param); - void awardStatFromServer(Stat *stat, byteArray param); - void onUpdateAbilities(); - bool isLocalPlayer(); + virtual void awardStat(Stat* stat, byteArray param); + void awardStatFromServer(Stat* stat, byteArray param); + void onUpdateAbilities(); + bool isLocalPlayer(); - // 4J - send the custom skin texture data if there is one - //void CustomSkin(PBYTE pbData, DWORD dwBytes); + // 4J - send the custom skin texture data if there is one + // void CustomSkin(PBYTE pbData, DWORD dwBytes); - // 4J Overriding this so we can flag an event for the tutorial - virtual void ride(std::shared_ptr e); + // 4J Overriding this so we can flag an event for the tutorial + virtual void ride(std::shared_ptr e); - // 4J - added for the Stop Sleeping - virtual void StopSleeping(); + // 4J - added for the Stop Sleeping + virtual void StopSleeping(); - // 4J Added - virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); - virtual void setAndBroadcastCustomCape(std::uint32_t capeId); + // 4J Added + virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); + virtual void setAndBroadcastCustomCape(std::uint32_t capeId); }; diff --git a/Minecraft.Client/Player/RemotePlayer.cpp b/Minecraft.Client/Player/RemotePlayer.cpp index 5e554cbab..cd81b5743 100644 --- a/Minecraft.Client/Player/RemotePlayer.cpp +++ b/Minecraft.Client/Player/RemotePlayer.cpp @@ -3,45 +3,39 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../Minecraft.World/Util/Mth.h" -RemotePlayer::RemotePlayer(Level *level, const std::wstring& name) : Player(level) -{ - // 4J - added initialisers - hasStartedUsingItem = false; - lSteps = 0; - lx = ly = lz = lyr = lxr = 0.0; - fallTime = 0.0f; +RemotePlayer::RemotePlayer(Level* level, const std::wstring& name) + : Player(level) { + // 4J - added initialisers + hasStartedUsingItem = false; + lSteps = 0; + lx = ly = lz = lyr = lxr = 0.0; + fallTime = 0.0f; this->name = name; - m_UUID = name; - app.DebugPrintf("Created RemotePlayer with name %ls\n", name.c_str() ); + m_UUID = name; + app.DebugPrintf("Created RemotePlayer with name %ls\n", name.c_str()); heightOffset = 0; this->footSize = 0; - if (name.length() > 0) - { - customTextureUrl = L"";//L"http://s3.amazonaws.com/MinecraftSkins/" + name + L".png"; + if (name.length() > 0) { + customTextureUrl = L""; // L"http://s3.amazonaws.com/MinecraftSkins/" + + // name + L".png"; } - this->noPhysics = true; + this->noPhysics = true; bedOffsetY = 4 / 16.0f; this->viewScale = 10; } -void RemotePlayer::setDefaultHeadHeight() -{ - heightOffset = 0; -} +void RemotePlayer::setDefaultHeadHeight() { heightOffset = 0; } -bool RemotePlayer::hurt(DamageSource *source, int dmg) -{ - return true; -} +bool RemotePlayer::hurt(DamageSource* source, int dmg) { return true; } -void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) -{ -// heightOffset = 0; +void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot, + int steps) { + // heightOffset = 0; lx = x; ly = y; lz = z; @@ -51,8 +45,7 @@ void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot, lSteps = steps; } -void RemotePlayer::tick() -{ +void RemotePlayer::tick() { bedOffsetY = 0 / 16.0f; Player::tick(); @@ -64,50 +57,43 @@ void RemotePlayer::tick() walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; walkAnimPos += walkAnimSpeed; - if (!hasStartedUsingItem && isUsingItemFlag() && inventory->items[inventory->selected] != NULL) - { - std::shared_ptr item = inventory->items[inventory->selected]; - startUsingItem(inventory->items[inventory->selected], Item::items[item->id]->getUseDuration(item)); - hasStartedUsingItem = true; - } - else if (hasStartedUsingItem && !isUsingItemFlag()) - { - stopUsingItem(); - hasStartedUsingItem = false; - } + if (!hasStartedUsingItem && isUsingItemFlag() && + inventory->items[inventory->selected] != NULL) { + std::shared_ptr item = + inventory->items[inventory->selected]; + startUsingItem(inventory->items[inventory->selected], + Item::items[item->id]->getUseDuration(item)); + hasStartedUsingItem = true; + } else if (hasStartedUsingItem && !isUsingItemFlag()) { + stopUsingItem(); + hasStartedUsingItem = false; + } - // if (eatItem != null) { - // if (eatItemTickCount <= 25 && eatItemTickCount % 4 == 0) { - // spawnEatParticles(eatItem, 5); - // } - // eatItemTickCount--; - // if (eatItemTickCount <= 0) { - // spawnEatParticles(eatItem, 16); - // swing(); - // eatItem = null; - // } - // } + // if (eatItem != null) { + // if (eatItemTickCount <= 25 && eatItemTickCount % 4 == 0) { + // spawnEatParticles(eatItem, 5); + // } + // eatItemTickCount--; + // if (eatItemTickCount <= 0) { + // spawnEatParticles(eatItem, 16); + // swing(); + // eatItem = null; + // } + // } } -float RemotePlayer::getShadowHeightOffs() -{ - return 0; -} +float RemotePlayer::getShadowHeightOffs() { return 0; } -void RemotePlayer::aiStep() -{ +void RemotePlayer::aiStep() { Player::serverAiStep(); - if (lSteps > 0) - { + if (lSteps > 0) { double xt = x + (lx - x) / lSteps; double yt = y + (ly - y) / lSteps; double zt = z + (lz - z) / lSteps; double yrd = lyr - yRot; - while (yrd < -180) - yrd += 360; - while (yrd >= 180) - yrd -= 360; + while (yrd < -180) yrd += 360; + while (yrd >= 180) yrd -= 360; yRot += (float)((yrd) / lSteps); xRot += (float)((lxr - xRot) / lSteps); @@ -118,35 +104,29 @@ void RemotePlayer::aiStep() } oBob = bob; - float tBob = (float) Mth::sqrt(xd * xd + zd * zd); - float tTilt = (float) atan(-yd * 0.2f) * 15.0f; + float tBob = (float)Mth::sqrt(xd * xd + zd * zd); + float tTilt = (float)atan(-yd * 0.2f) * 15.0f; if (tBob > 0.1f) tBob = 0.1f; if (!onGround || getHealth() <= 0) tBob = 0; if (onGround || getHealth() <= 0) tTilt = 0; bob += (tBob - bob) * 0.4f; tilt += (tTilt - tilt) * 0.8f; - } -// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game -void RemotePlayer::setEquippedSlot(int slot, std::shared_ptr item) -{ - if (slot == 0) - { +// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer +// Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for +// other players in online game +void RemotePlayer::setEquippedSlot(int slot, + std::shared_ptr item) { + if (slot == 0) { inventory->items[inventory->selected] = item; - } - else - { + } else { inventory->armor[slot - 1] = item; } } -void RemotePlayer::animateRespawn() -{ -// Player.animateRespawn(this, level); +void RemotePlayer::animateRespawn() { + // Player.animateRespawn(this, level); } -float RemotePlayer::getHeadHeight() -{ - return 1.82f; -} \ No newline at end of file +float RemotePlayer::getHeadHeight() { return 1.82f; } \ No newline at end of file diff --git a/Minecraft.Client/Player/RemotePlayer.h b/Minecraft.Client/Player/RemotePlayer.h index 7082a10c0..47ac32c21 100644 --- a/Minecraft.Client/Player/RemotePlayer.h +++ b/Minecraft.Client/Player/RemotePlayer.h @@ -4,30 +4,39 @@ class Input; -class RemotePlayer : public Player -{ +class RemotePlayer : public Player { private: - bool hasStartedUsingItem; + bool hasStartedUsingItem; + public: - Input *input; - RemotePlayer(Level *level, const std::wstring& name); + Input* input; + RemotePlayer(Level* level, const std::wstring& name); + protected: - virtual void setDefaultHeadHeight(); + virtual void setDefaultHeadHeight(); + public: - virtual bool hurt(DamageSource *source, int dmg); + virtual bool hurt(DamageSource* source, int dmg); + private: - int lSteps; + int lSteps; double lx, ly, lz, lyr, lxr; public: - virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); + virtual void lerpTo(double x, double y, double z, float yRot, float xRot, + int steps); float fallTime; virtual void tick(); virtual float getShadowHeightOffs(); virtual void aiStep(); - virtual void setEquippedSlot(int slot, std::shared_ptr item);// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game + virtual void setEquippedSlot( + int slot, std::shared_ptr + item); // 4J Stu - Brought forward change from 1.3 to fix + // #64688 - Customer Encountered: TU7: Content: + // Art: Aura of enchanted item is not displayed + // for other players in online game virtual void animateRespawn(); - virtual float getHeadHeight(); - bool hasPermission(EGameCommand command) { return false; } + virtual float getHeadHeight(); + bool hasPermission(EGameCommand command) { return false; } }; \ No newline at end of file diff --git a/Minecraft.Client/Player/ServerPlayer.cpp b/Minecraft.Client/Player/ServerPlayer.cpp index 5de88dafe..9de4edcfc 100644 --- a/Minecraft.Client/Player/ServerPlayer.cpp +++ b/Minecraft.Client/Player/ServerPlayer.cpp @@ -27,278 +27,266 @@ #include "../../Minecraft.World/Level/LevelChunk.h" #include "../Rendering/LevelRenderer.h" -ServerPlayer::ServerPlayer(MinecraftServer *server, Level *level, const std::wstring& name, ServerPlayerGameMode *gameMode) : Player(level) -{ - // 4J - added initialisers - connection = nullptr; +ServerPlayer::ServerPlayer(MinecraftServer* server, Level* level, + const std::wstring& name, + ServerPlayerGameMode* gameMode) + : Player(level) { + // 4J - added initialisers + connection = nullptr; lastMoveX = lastMoveZ = 0; spewTimer = 0; - lastSentHealth = -99999999; - lastSentFood = -99999999; - lastFoodSaturationZero = true; - lastSentExp = -99999999; + lastSentHealth = -99999999; + lastSentFood = -99999999; + lastFoodSaturationZero = true; + lastSentExp = -99999999; invulnerableTime = 20 * 3; - containerCounter = 0; - ignoreSlotUpdateHack = false; - latency = 0; - wonGame = false; - m_enteredEndExitPortal = false; - lastCarried = ItemInstanceArray(5); - viewDistance = 10; - - // 4jcraft added (0 initialized) - m_lastDamageSource = eTelemetryChallenges_Unknown; + containerCounter = 0; + ignoreSlotUpdateHack = false; + latency = 0; + wonGame = false; + m_enteredEndExitPortal = false; + lastCarried = ItemInstanceArray(5); + viewDistance = 10; -// gameMode->player = this; // 4J - removed to avoid use of shared_from_this in ctor, now set up externally + // 4jcraft added (0 initialized) + m_lastDamageSource = eTelemetryChallenges_Unknown; + + // gameMode->player = this; // 4J - removed to avoid use of + // shared_from_this in ctor, now set up externally this->gameMode = gameMode; - Pos *spawnPos = level->getSharedSpawnPos(); + Pos* spawnPos = level->getSharedSpawnPos(); int xx = spawnPos->x; int zz = spawnPos->z; int yy = spawnPos->y; - delete spawnPos; + delete spawnPos; - if (!level->dimension->hasCeiling && level->getLevelData()->getGameType() != GameType::ADVENTURE) - { - level->isFindingSpawn = true; + if (!level->dimension->hasCeiling && + level->getLevelData()->getGameType() != GameType::ADVENTURE) { + level->isFindingSpawn = true; - // 4J added - do additional checking that we aren't putting the player in deep water. Give up after 20 or goes just - // in case the spawnPos is somehow in a really bad spot and we would just lock here. - int waterDepth = 0; - int attemptCount = 0; - int xx2, yy2, zz2; + // 4J added - do additional checking that we aren't putting the player + // in deep water. Give up after 20 or goes just in case the spawnPos is + // somehow in a really bad spot and we would just lock here. + int waterDepth = 0; + int attemptCount = 0; + int xx2, yy2, zz2; - int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; - int maxXZ = (level->dimension->getXZSize() * 16 ) / 2 - 1; + int minXZ = -(level->dimension->getXZSize() * 16) / 2; + int maxXZ = (level->dimension->getXZSize() * 16) / 2 - 1; - bool playerNear = false; - do - { - // Also check that we aren't straying outside of the map - do - { - xx2 = xx + random->nextInt(20) - 10; - zz2 = zz + random->nextInt(20) - 10; - } while ( ( xx2 > maxXZ ) || ( xx2 < minXZ ) || ( zz2 > maxXZ ) || ( zz2 < minXZ ) ); - yy2 = level->getTopSolidBlock(xx2, zz2); + bool playerNear = false; + do { + // Also check that we aren't straying outside of the map + do { + xx2 = xx + random->nextInt(20) - 10; + zz2 = zz + random->nextInt(20) - 10; + } while ((xx2 > maxXZ) || (xx2 < minXZ) || (zz2 > maxXZ) || + (zz2 < minXZ)); + yy2 = level->getTopSolidBlock(xx2, zz2); - waterDepth = 0; - int yw = yy2; - while( ( yw < 128 ) && - (( level->getTile(xx2,yw,zz2) == Tile::water_Id ) || - ( level->getTile(xx2,yw,zz2) == Tile::calmWater_Id )) ) - { - yw++; - waterDepth++; - } - attemptCount++; - playerNear = ( level->getNearestPlayer(xx + 0.5, yy, zz + 0.5,3) != NULL ); - } while ( ( waterDepth > 1 ) && (!playerNear) && ( attemptCount < 20 ) ); - xx = xx2; - yy = yy2; - zz = zz2; + waterDepth = 0; + int yw = yy2; + while ((yw < 128) && + ((level->getTile(xx2, yw, zz2) == Tile::water_Id) || + (level->getTile(xx2, yw, zz2) == Tile::calmWater_Id))) { + yw++; + waterDepth++; + } + attemptCount++; + playerNear = + (level->getNearestPlayer(xx + 0.5, yy, zz + 0.5, 3) != NULL); + } while ((waterDepth > 1) && (!playerNear) && (attemptCount < 20)); + xx = xx2; + yy = yy2; + zz = zz2; - level->isFindingSpawn = false; + level->isFindingSpawn = false; } - heightOffset = 0; // 4J - this height used to be set up after moveTo, but that ends up with the y value being incorrect as it depends on this offset + heightOffset = + 0; // 4J - this height used to be set up after moveTo, but that ends up + // with the y value being incorrect as it depends on this offset this->moveTo(xx + 0.5, yy, zz + 0.5, 0, 0); this->server = server; footSize = 0; this->name = name; - m_UUID = name; + m_UUID = name; - // 4J Added - lastBrupSendTickCount = 0; + // 4J Added + lastBrupSendTickCount = 0; } -ServerPlayer::~ServerPlayer() -{ - delete [] lastCarried.data; +ServerPlayer::~ServerPlayer() { delete[] lastCarried.data; } + +// 4J added - add bits to a flag array that is passed in, to represent those +// entities which have small Ids, and are in our vector of entitiesToRemove. If +// there aren't any entities to be flagged, this function does nothing. If there +// *are* entities to be added, uses the removedFound as an input to determine if +// the flag array has already been initialised at all - if it has been, then +// just adds flags to it; if it hasn't, then memsets the output flag array and +// adds to it for this ServerPlayer. +void ServerPlayer::flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound) { + if (entitiesToRemove.empty()) { + return; + } + if ((*removedFound) == false) { + *removedFound = true; + memset(flags, 0, 2048 / 32); + } + + AUTO_VAR(it, entitiesToRemove.begin()); + for (AUTO_VAR(it, entitiesToRemove.begin()); it != entitiesToRemove.end(); + it++) { + int index = *it; + if (index < 2048) { + unsigned int i = index / 32; + unsigned int j = index % 32; + unsigned int uiMask = 0x80000000 >> j; + + flags[i] |= uiMask; + } + } } -// 4J added - add bits to a flag array that is passed in, to represent those entities which have small Ids, and are in our vector of entitiesToRemove. -// If there aren't any entities to be flagged, this function does nothing. If there *are* entities to be added, uses the removedFound as an input to -// determine if the flag array has already been initialised at all - if it has been, then just adds flags to it; if it hasn't, then memsets the output -// flag array and adds to it for this ServerPlayer. -void ServerPlayer::flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound) -{ - if( entitiesToRemove.empty() ) - { - return; - } - if( ( *removedFound ) == false ) - { - *removedFound = true; - memset(flags, 0, 2048/32); - } +void ServerPlayer::readAdditionalSaveData(CompoundTag* entityTag) { + Player::readAdditionalSaveData(entityTag); - AUTO_VAR(it, entitiesToRemove.begin() ); - for( AUTO_VAR(it, entitiesToRemove.begin()); it != entitiesToRemove.end(); it++ ) - { - int index = *it; - if( index < 2048 ) - { - unsigned int i = index / 32; - unsigned int j = index % 32; - unsigned int uiMask = 0x80000000 >> j; + if (entityTag->contains(L"playerGameType")) { + // 4J Stu - We do not want to change the game mode for the player, + // instead we let the server override it globally + // gameMode->setGameModeForPlayer(GameType::byId(entityTag->getInt(L"playerGameType"))); + } - flags[i] |= uiMask; - } - } + GameRulesInstance* grs = gameMode->getGameRules(); + if (entityTag->contains(L"GameRules") && grs != NULL) { + byteArray ba = entityTag->getByteArray(L"GameRules"); + ByteArrayInputStream bais(ba); + DataInputStream dis(&bais); + grs->read(&dis); + dis.close(); + bais.close(); + // delete [] ba.data; + } } -void ServerPlayer::readAdditionalSaveData(CompoundTag *entityTag) -{ - Player::readAdditionalSaveData(entityTag); +void ServerPlayer::addAdditonalSaveData(CompoundTag* entityTag) { + Player::addAdditonalSaveData(entityTag); - if (entityTag->contains(L"playerGameType")) - { - // 4J Stu - We do not want to change the game mode for the player, instead we let the server override it globally - //gameMode->setGameModeForPlayer(GameType::byId(entityTag->getInt(L"playerGameType"))); - } + GameRulesInstance* grs = gameMode->getGameRules(); + if (grs != NULL) { + ByteArrayOutputStream baos; + DataOutputStream dos(&baos); + grs->write(&dos); + entityTag->putByteArray(L"GameRules", baos.buf); + baos.buf.data = NULL; + dos.close(); + baos.close(); + } - GameRulesInstance *grs = gameMode->getGameRules(); - if (entityTag->contains(L"GameRules") && grs != NULL) - { - byteArray ba = entityTag->getByteArray(L"GameRules"); - ByteArrayInputStream bais(ba); - DataInputStream dis(&bais); - grs->read(&dis); - dis.close(); - bais.close(); - //delete [] ba.data; - } + // 4J Stu - We do not want to change the game mode for the player, instead + // we let the server override it globally + // entityTag->putInt(L"playerGameType", + // gameMode->getGameModeForPlayer()->getId()); } -void ServerPlayer::addAdditonalSaveData(CompoundTag *entityTag) -{ - Player::addAdditonalSaveData(entityTag); - - GameRulesInstance *grs = gameMode->getGameRules(); - if (grs != NULL) - { - ByteArrayOutputStream baos; - DataOutputStream dos(&baos); - grs->write(&dos); - entityTag->putByteArray(L"GameRules", baos.buf); - baos.buf.data = NULL; - dos.close(); - baos.close(); - } - - // 4J Stu - We do not want to change the game mode for the player, instead we let the server override it globally - //entityTag->putInt(L"playerGameType", gameMode->getGameModeForPlayer()->getId()); +void ServerPlayer::withdrawExperienceLevels(int amount) { + Player::withdrawExperienceLevels(amount); + lastSentExp = -1; } -void ServerPlayer::withdrawExperienceLevels(int amount) -{ - Player::withdrawExperienceLevels(amount); - lastSentExp = -1; -} +void ServerPlayer::initMenu() { containerMenu->addSlotListener(this); } -void ServerPlayer::initMenu() -{ - containerMenu->addSlotListener(this); -} +ItemInstanceArray ServerPlayer::getEquipmentSlots() { return lastCarried; } -ItemInstanceArray ServerPlayer::getEquipmentSlots() -{ - return lastCarried; -} +void ServerPlayer::setDefaultHeadHeight() { heightOffset = 0; } -void ServerPlayer::setDefaultHeadHeight() -{ - heightOffset = 0; -} +float ServerPlayer::getHeadHeight() { return 1.62f; } -float ServerPlayer::getHeadHeight() -{ - return 1.62f; -} - -void ServerPlayer::tick() -{ +void ServerPlayer::tick() { gameMode->tick(); if (invulnerableTime > 0) invulnerableTime--; containerMenu->broadcastChanges(); - // 4J-JEV, hook for Durango event 'EnteredNewBiome'. - Biome *newBiome = level->getBiome(x,z); - if (newBiome != currentBiome) - { - awardStat( - GenericStats::enteredBiome(newBiome->id), - GenericStats::param_enteredBiome(newBiome->id) - ); - currentBiome = newBiome; - } + // 4J-JEV, hook for Durango event 'EnteredNewBiome'. + Biome* newBiome = level->getBiome(x, z); + if (newBiome != currentBiome) { + awardStat(GenericStats::enteredBiome(newBiome->id), + GenericStats::param_enteredBiome(newBiome->id)); + currentBiome = newBiome; + } - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { std::shared_ptr currentCarried = getCarried(i); - if (currentCarried != lastCarried[i]) - { - getLevel()->getTracker()->broadcast(shared_from_this(), std::shared_ptr( new SetEquippedItemPacket(this->entityId, i, currentCarried) ) ); + if (currentCarried != lastCarried[i]) { + getLevel()->getTracker()->broadcast( + shared_from_this(), + std::shared_ptr( + new SetEquippedItemPacket(this->entityId, i, + currentCarried))); lastCarried[i] = currentCarried; } } - flushEntitiesToRemove(); + flushEntitiesToRemove(); } // 4J Stu - Split out here so that we can call this from other places -void ServerPlayer::flushEntitiesToRemove() -{ - if (!entitiesToRemove.empty()) - { - int sz = entitiesToRemove.size(); - int amount = std::min(sz, RemoveEntitiesPacket::MAX_PER_PACKET); - intArray ids(amount); - int pos = 0; +void ServerPlayer::flushEntitiesToRemove() { + if (!entitiesToRemove.empty()) { + int sz = entitiesToRemove.size(); + int amount = std::min(sz, RemoveEntitiesPacket::MAX_PER_PACKET); + intArray ids(amount); + int pos = 0; - AUTO_VAR(it, entitiesToRemove.begin() ); - while (it != entitiesToRemove.end() && pos < amount) - { - ids[pos++] = *it; - it = entitiesToRemove.erase(it); - } + AUTO_VAR(it, entitiesToRemove.begin()); + while (it != entitiesToRemove.end() && pos < amount) { + ids[pos++] = *it; + it = entitiesToRemove.erase(it); + } - connection->send(std::shared_ptr(new RemoveEntitiesPacket(ids))); - } + connection->send(std::shared_ptr( + new RemoveEntitiesPacket(ids))); + } } - -// 4J - have split doTick into 3 bits, so that we can call the doChunkSendingTick separately, but still do the equivalent of what calling a full doTick used to do, by calling this method -void ServerPlayer::doTick(bool sendChunks, bool dontDelayChunks/*=false*/, bool ignorePortal/*=false*/) -{ - doTickA(); - if( sendChunks ) - { - doChunkSendingTick(dontDelayChunks); - } - doTickB(ignorePortal); +// 4J - have split doTick into 3 bits, so that we can call the +// doChunkSendingTick separately, but still do the equivalent of what calling a +// full doTick used to do, by calling this method +void ServerPlayer::doTick(bool sendChunks, bool dontDelayChunks /*=false*/, + bool ignorePortal /*=false*/) { + doTickA(); + if (sendChunks) { + doChunkSendingTick(dontDelayChunks); + } + doTickB(ignorePortal); } -void ServerPlayer::doTickA() -{ +void ServerPlayer::doTickA() { Player::tick(); - for (unsigned int i = 0; i < inventory->getContainerSize(); i++) - { + for (unsigned int i = 0; i < inventory->getContainerSize(); i++) { std::shared_ptr ie = inventory->getItem(i); - if (ie != NULL) - { - // 4J - removed condition. These were getting lower priority than tile update packets etc. on the slow outbound queue, and so were extremely slow to send sometimes, - // particularly at the start of a game. They don't typically seem to be massive and shouldn't be send when there isn't actually any updating to do. - if (Item::items[ie->id]->isComplex() ) // && connection->countDelayedPackets() <= 2) - { - std::shared_ptr packet = (dynamic_cast(Item::items[ie->id])->getUpdatePacket(ie, level, std::dynamic_pointer_cast( shared_from_this() ) ) ); - if (packet != NULL) - { + if (ie != NULL) { + // 4J - removed condition. These were getting lower priority than + // tile update packets etc. on the slow outbound queue, and so were + // extremely slow to send sometimes, particularly at the start of a + // game. They don't typically seem to be massive and shouldn't be + // send when there isn't actually any updating to do. + if (Item::items[ie->id] + ->isComplex()) // && connection->countDelayedPackets() <= + // 2) + { + std::shared_ptr packet = + (dynamic_cast(Item::items[ie->id]) + ->getUpdatePacket(ie, level, + std::dynamic_pointer_cast( + shared_from_this()))); + if (packet != NULL) { connection->send(packet); } } @@ -306,488 +294,552 @@ void ServerPlayer::doTickA() } } -// 4J - split off the chunk sending bit of the tick here from ::doTick so we can do this exactly once per player per server tick -void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) -{ -// printf("[%d] %s: sendChunks: %d, empty: %d\n",tickCount, connection->getNetworkPlayer()->GetUID().getOnlineID(),sendChunks,chunksToSend.empty()); - if (!chunksToSend.empty()) - { +// 4J - split off the chunk sending bit of the tick here from ::doTick so we can +// do this exactly once per player per server tick +void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) { + // printf("[%d] %s: sendChunks: %d, empty: %d\n",tickCount, + //connection->getNetworkPlayer()->GetUID().getOnlineID(),sendChunks,chunksToSend.empty()); + if (!chunksToSend.empty()) { ChunkPos nearest = chunksToSend.front(); - bool nearestValid = false; + bool nearestValid = false; - // 4J - reinstated and optimised some code that was commented out in the original, to make sure that we always - // send the nearest chunk to the player. The original uses the bukkit sorting thing to try and avoid doing this, but - // the player can quickly wander away from the centre of the spiral of chunks that that method creates, long before transmission - // of them is complete. + // 4J - reinstated and optimised some code that was commented out in the + // original, to make sure that we always send the nearest chunk to the + // player. The original uses the bukkit sorting thing to try and avoid + // doing this, but the player can quickly wander away from the centre of + // the spiral of chunks that that method creates, long before + // transmission of them is complete. double dist = DBL_MAX; - for( AUTO_VAR(it, chunksToSend.begin()); it != chunksToSend.end(); it++ ) - { + for (AUTO_VAR(it, chunksToSend.begin()); it != chunksToSend.end(); + it++) { ChunkPos chunk = *it; - if( level->isChunkFinalised(chunk.x, chunk.z) ) - { - double newDist = chunk.distanceToSqr(x, z); - if ( (!nearestValid) || (newDist < dist) ) - { - nearest = chunk; - dist = chunk.distanceToSqr(x, z); - nearestValid = true; - } - } + if (level->isChunkFinalised(chunk.x, chunk.z)) { + double newDist = chunk.distanceToSqr(x, z); + if ((!nearestValid) || (newDist < dist)) { + nearest = chunk; + dist = chunk.distanceToSqr(x, z); + nearestValid = true; + } + } } -// if (nearest != NULL) // 4J - removed as we don't have references here - if( nearestValid ) - { + // if (nearest != NULL) // 4J - removed as we don't have + // references here + if (nearestValid) { bool okToSend = false; -// if (dist < 32 * 32) okToSend = true; - if( connection->isLocal() ) - { - if( !connection->done ) okToSend = true; - } - else - { - bool canSendOnSlowQueue = MinecraftServer::canSendOnSlowQueue(connection->getNetworkPlayer()); - -// app.DebugPrintf("%ls: canSendOnSlowQueue %d, countDelayedPackets %d GetSendQueueSizeBytes %d done: %d", -// connection->getNetworkPlayer()->GetUID().toString().c_str(), -// canSendOnSlowQueue, connection->countDelayedPackets(), -// g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( NULL, true ), -// connection->done); - - if( dontDelayChunks || - (canSendOnSlowQueue && - (connection->countDelayedPackets() < 4 )&& + // if (dist < 32 * 32) okToSend = true; + if (connection->isLocal()) { + if (!connection->done) okToSend = true; + } else { + bool canSendOnSlowQueue = MinecraftServer::canSendOnSlowQueue( + connection->getNetworkPlayer()); + + // app.DebugPrintf("%ls: + //canSendOnSlowQueue %d, countDelayedPackets %d + //GetSendQueueSizeBytes %d done: %d", + // connection->getNetworkPlayer()->GetUID().toString().c_str(), + // canSendOnSlowQueue, + //connection->countDelayedPackets(), + // g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( + //NULL, true ), connection->done); + + if (dontDelayChunks || + (canSendOnSlowQueue && + (connection->countDelayedPackets() < 4) && #ifdef _XBOX_ONE - // The network manager on xbox one doesn't currently split data into slow & fast queues - since we can only measure - // both together then bytes provides a better metric than count of data items to determine if we should avoid queueing too much up - (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( NULL, true ) < 8192 )&& + // The network manager on xbox one doesn't currently split + // data into slow & fast queues - since we can only measure + // both together then bytes provides a better metric than + // count of data items to determine if we should avoid + // queueing too much up + (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeBytes( + NULL, true) < 8192) && #else - (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( NULL, true ) < 4 )&& -#endif - //(tickCount - lastBrupSendTickCount) > (connection->getNetworkPlayer()->GetCurrentRtt()>>4) && - !connection->done) ) - { - lastBrupSendTickCount = tickCount; - okToSend = true; - MinecraftServer::s_slowQueuePacketSent = true; + (g_NetworkManager.GetHostPlayer() + ->GetSendQueueSizeMessages(NULL, true) < 4) && +#endif + //(tickCount - lastBrupSendTickCount) > + //(connection->getNetworkPlayer()->GetCurrentRtt()>>4) && + !connection->done)) { + lastBrupSendTickCount = tickCount; + okToSend = true; + MinecraftServer::s_slowQueuePacketSent = true; -// static std::unordered_map mapLastTime; -// __int64 thisTime = System::currentTimeMillis(); -// __int64 lastTime = mapLastTime[connection->getNetworkPlayer()->GetUID().toString()]; -// app.DebugPrintf(" - OK to send (%d ms since last)\n", thisTime - lastTime); -// mapLastTime[connection->getNetworkPlayer()->GetUID().toString()] = thisTime; - } - else - { -// app.DebugPrintf(" - \n"); - } - } + // static + //std::unordered_map mapLastTime; + // __int64 thisTime = + //System::currentTimeMillis(); + // __int64 lastTime = + //mapLastTime[connection->getNetworkPlayer()->GetUID().toString()]; + // app.DebugPrintf(" - OK + //to send (%d ms since last)\n", thisTime - lastTime); + // mapLastTime[connection->getNetworkPlayer()->GetUID().toString()] + //= thisTime; + } else { + // app.DebugPrintf(" - \n"); + } + } - if (okToSend) - { - ServerLevel *level = server->getLevel(dimension); - int flagIndex = getFlagIndexForChunk(nearest,this->level->dimension->id); + if (okToSend) { + ServerLevel* level = server->getLevel(dimension); + int flagIndex = + getFlagIndexForChunk(nearest, this->level->dimension->id); chunksToSend.remove(nearest); - bool chunkDataSent = false; + bool chunkDataSent = false; - // Don't send the chunk to the local machine - the chunks there are mapped directly to the server chunks. We could potentially stop this process earlier on by not adding - // to the chunksToSend list, but that would stop the tile entities being broadcast too - if( !connection->isLocal() ) // force here to disable sharing of data - { - // Don't send the chunk if we've set a flag to say that we've already sent it to this machine. This stops two things - // (1) Sending a chunk to multiple players doing split screen on one machine - // (2) Sending a chunk that we've already sent as the player moves around. The original version of the game resends these, since it maintains - // a region of active chunks round each player in the "infinite" world, but in our finite world, we don't ever request that chunks be - // unloaded on the client and so just gradually build up more and more of the finite set of chunks as the player moves - if( !g_NetworkManager.SystemFlagGet(connection->getNetworkPlayer(),flagIndex) ) - { -// app.DebugPrintf("Creating BRUP for %d %d\n",nearest.x, nearest.z); - PIXBeginNamedEvent(0,"Creation BRUP for sending\n"); - std::shared_ptr packet = std::shared_ptr( new BlockRegionUpdatePacket(nearest.x * 16, 0, nearest.z * 16, 16, Level::maxBuildHeight, 16, level) ); - PIXEndNamedEvent(); - if( dontDelayChunks ) packet->shouldDelay = false; + // Don't send the chunk to the local machine - the chunks there + // are mapped directly to the server chunks. We could + // potentially stop this process earlier on by not adding to the + // chunksToSend list, but that would stop the tile entities + // being broadcast too + if (!connection + ->isLocal()) // force here to disable sharing of data + { + // Don't send the chunk if we've set a flag to say that + // we've already sent it to this machine. This stops two + // things (1) Sending a chunk to multiple players doing + // split screen on one machine (2) Sending a chunk that + // we've already sent as the player moves around. The + // original version of the game resends these, since it + // maintains + // a region of active chunks round each player in the + // "infinite" world, but in our finite world, we don't + // ever request that chunks be unloaded on the client + // and so just gradually build up more and more of the + // finite set of chunks as the player moves + if (!g_NetworkManager.SystemFlagGet( + connection->getNetworkPlayer(), flagIndex)) { + // app.DebugPrintf("Creating + //BRUP for %d %d\n",nearest.x, nearest.z); + PIXBeginNamedEvent(0, "Creation BRUP for sending\n"); + std::shared_ptr packet = + std::shared_ptr( + new BlockRegionUpdatePacket( + nearest.x * 16, 0, nearest.z * 16, 16, + Level::maxBuildHeight, 16, level)); + PIXEndNamedEvent(); + if (dontDelayChunks) packet->shouldDelay = false; - if( packet->shouldDelay == true ) - { - // Other than the first packet we always want these initial chunks to be sent over - // QNet at a lower priority - connection->queueSend( packet ); - } - else - { - connection->send( packet ); - } - // Set flag to say we have send this block already to this system - g_NetworkManager.SystemFlagSet(connection->getNetworkPlayer(),flagIndex); + if (packet->shouldDelay == true) { + // Other than the first packet we always want these + // initial chunks to be sent over QNet at a lower + // priority + connection->queueSend(packet); + } else { + connection->send(packet); + } + // Set flag to say we have send this block already to + // this system + g_NetworkManager.SystemFlagSet( + connection->getNetworkPlayer(), flagIndex); - chunkDataSent = true; - } - } - else - { - // For local connections, we'll need to copy the lighting data over from server to client at this point. This is to try and keep lighting as similar as possible to the java version, - // where client & server are individually responsible for maintaining their lighting (since 1.2.3). This is really an alternative to sending the lighting data over the fake local - // network connection at this point. + chunkDataSent = true; + } + } else { + // For local connections, we'll need to copy the lighting + // data over from server to client at this point. This is to + // try and keep lighting as similar as possible to the java + // version, where client & server are individually + // responsible for maintaining their lighting (since 1.2.3). + // This is really an alternative to sending the lighting + // data over the fake local network connection at this + // point. - MultiPlayerLevel *clientLevel = Minecraft::GetInstance()->getLevel(level->dimension->id); - if( clientLevel ) - { - LevelChunk *lc = clientLevel->getChunk( nearest.x, nearest.z ); - lc->reSyncLighting(); - lc->recalcHeightmapOnly(); - clientLevel->setTilesDirty(nearest.x * 16 + 1, 1, nearest.z * 16 + 1, - nearest.x * 16 + 14, Level::maxBuildHeight - 2, nearest.z * 16 + 14 ); - } - } - // Don't send TileEntity data until we have sent the block data - if( connection->isLocal() || chunkDataSent) - { - std::vector > *tes = level->getTileEntitiesInRegion(nearest.x * 16, 0, nearest.z * 16, nearest.x * 16 + 16, Level::maxBuildHeight, nearest.z * 16 + 16); - for (unsigned int i = 0; i < tes->size(); i++) - { - // 4J Stu - Added delay param to ensure that these arrive after the BRUPs from above - // Fix for #9169 - ART : Sign text is replaced with the words “Awaiting approval”. - broadcast(tes->at(i), !connection->isLocal() && !dontDelayChunks); - } - delete tes; - } + MultiPlayerLevel* clientLevel = + Minecraft::GetInstance()->getLevel( + level->dimension->id); + if (clientLevel) { + LevelChunk* lc = + clientLevel->getChunk(nearest.x, nearest.z); + lc->reSyncLighting(); + lc->recalcHeightmapOnly(); + clientLevel->setTilesDirty( + nearest.x * 16 + 1, 1, nearest.z * 16 + 1, + nearest.x * 16 + 14, Level::maxBuildHeight - 2, + nearest.z * 16 + 14); + } + } + // Don't send TileEntity data until we have sent the block data + if (connection->isLocal() || chunkDataSent) { + std::vector >* tes = + level->getTileEntitiesInRegion( + nearest.x * 16, 0, nearest.z * 16, + nearest.x * 16 + 16, Level::maxBuildHeight, + nearest.z * 16 + 16); + for (unsigned int i = 0; i < tes->size(); i++) { + // 4J Stu - Added delay param to ensure that these + // arrive after the BRUPs from above Fix for #9169 - ART + // : Sign text is replaced with the words “Awaiting + // approval”. + broadcast(tes->at(i), + !connection->isLocal() && !dontDelayChunks); + } + delete tes; + } } } } } -void ServerPlayer::doTickB(bool ignorePortal) -{ +void ServerPlayer::doTickB(bool ignorePortal) { #ifndef _CONTENT_PACKAGE - // check if there's a debug dimension change requested - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<dimension->id == 0 ) - { - ignorePortal=false; - isInsidePortal=true; - portalTime=1; - } - unsigned int uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id == 0 ) -// { -// server->players->toggleDimension( std::dynamic_pointer_cast( shared_from_this() ), 1 ); -// } -// unsigned int uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); -// app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id != 0 ) - { - ignorePortal=false; - isInsidePortal=true; - portalTime=1; - } - unsigned int uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); - app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id == 0) { + ignorePortal = false; + isInsidePortal = true; + portalTime = 1; + } + unsigned int uiVal = + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); + app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(), + uiVal & ~(1L << eDebugSetting_GoToNether)); + } + // else if + // (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<dimension->id == 0 ) + // { + // server->players->toggleDimension( + // std::dynamic_pointer_cast( shared_from_this() ), 1 ); + // } + // unsigned int + // uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); + // app.SetGameSettingsDebugMask(ProfileManager.GetPrimaryPad(),uiVal&~(1L<dimension->id != 0) { + ignorePortal = false; + isInsidePortal = true; + portalTime = 1; + } + unsigned int uiVal = + app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); + app.SetGameSettingsDebugMask( + ProfileManager.GetPrimaryPad(), + uiVal & ~(1L << eDebugSetting_GoToOverworld)); + } #endif - if(!ignorePortal) - { - if (isInsidePortal) - { - if (server->isNetherEnabled()) - { - if (containerMenu != inventoryMenu) - { - closeContainer(); - } - if (riding != NULL) - { - this->ride(riding); - } - else - { + if (!ignorePortal) { + if (isInsidePortal) { + if (server->isNetherEnabled()) { + if (containerMenu != inventoryMenu) { + closeContainer(); + } + if (riding != NULL) { + this->ride(riding); + } else { + portalTime += 1 / 80.0f; + if (portalTime >= 1) { + portalTime = 1; + changingDimensionDelay = 10; - portalTime += 1 / 80.0f; - if (portalTime >= 1) - { - portalTime = 1; - changingDimensionDelay = 10; + int targetDimension = 0; + if (dimension == -1) + targetDimension = 0; + else + targetDimension = -1; - int targetDimension = 0; - if (dimension == -1) targetDimension = 0; - else targetDimension = -1; + server->getPlayers()->toggleDimension( + std::dynamic_pointer_cast( + shared_from_this()), + targetDimension); + lastSentExp = -1; + lastSentHealth = -1; + lastSentFood = -1; - server->getPlayers()->toggleDimension( std::dynamic_pointer_cast( shared_from_this() ), targetDimension ); - lastSentExp = -1; - lastSentHealth = -1; - lastSentFood = -1; - - //awardStat(Achievements::portal); - } - } - isInsidePortal = false; - } - } - else - { - if (portalTime > 0) portalTime -= 1 / 20.0f; - if (portalTime < 0) portalTime = 0; - } - if (changingDimensionDelay > 0) changingDimensionDelay--; - } - - if (getHealth() != lastSentHealth || lastSentFood != foodData.getFoodLevel() || ((foodData.getSaturationLevel() == 0) != lastFoodSaturationZero)) - { - // 4J Stu - Added m_lastDamageSource for telemetry //4jcraft, nice but you never initialized it - connection->send( std::shared_ptr( new SetHealthPacket(getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel(), m_lastDamageSource) ) ); - lastSentHealth = getHealth(); - lastSentFood = foodData.getFoodLevel(); - lastFoodSaturationZero = foodData.getSaturationLevel() == 0; + // awardStat(Achievements::portal); + } + } + isInsidePortal = false; + } + } else { + if (portalTime > 0) portalTime -= 1 / 20.0f; + if (portalTime < 0) portalTime = 0; + } + if (changingDimensionDelay > 0) changingDimensionDelay--; } - if (totalExperience != lastSentExp) - { - lastSentExp = totalExperience; - connection->send( std::shared_ptr( new SetExperiencePacket(experienceProgress, totalExperience, experienceLevel) ) ); - } + if (getHealth() != lastSentHealth || + lastSentFood != foodData.getFoodLevel() || + ((foodData.getSaturationLevel() == 0) != lastFoodSaturationZero)) { + // 4J Stu - Added m_lastDamageSource for telemetry //4jcraft, nice but + // you never initialized it + connection->send(std::shared_ptr(new SetHealthPacket( + getHealth(), foodData.getFoodLevel(), foodData.getSaturationLevel(), + m_lastDamageSource))); + lastSentHealth = getHealth(); + lastSentFood = foodData.getFoodLevel(); + lastFoodSaturationZero = foodData.getSaturationLevel() == 0; + } + if (totalExperience != lastSentExp) { + lastSentExp = totalExperience; + connection->send( + std::shared_ptr(new SetExperiencePacket( + experienceProgress, totalExperience, experienceLevel))); + } } -std::shared_ptr ServerPlayer::getCarried(int slot) -{ +std::shared_ptr ServerPlayer::getCarried(int slot) { if (slot == 0) return inventory->getSelected(); return inventory->armor[slot - 1]; } -void ServerPlayer::die(DamageSource *source) -{ - server->getPlayers()->broadcastAll(source->getDeathMessagePacket(std::dynamic_pointer_cast(shared_from_this()))); - inventory->dropAll(); +void ServerPlayer::die(DamageSource* source) { + server->getPlayers()->broadcastAll(source->getDeathMessagePacket( + std::dynamic_pointer_cast(shared_from_this()))); + inventory->dropAll(); } -bool ServerPlayer::hurt(DamageSource *dmgSource, int dmg) -{ +bool ServerPlayer::hurt(DamageSource* dmgSource, int dmg) { if (invulnerableTime > 0) return false; - if (dynamic_cast(dmgSource) != NULL) - { - // 4J Stu - Fix for #46422 - TU5: Crash: Gameplay: Crash when being hit by a trap using a dispenser - // getEntity returns the owner of projectiles, and this would never be the arrow. The owner is sometimes NULL. - std::shared_ptr source = dmgSource->getDirectEntity(); + if (dynamic_cast(dmgSource) != NULL) { + // 4J Stu - Fix for #46422 - TU5: Crash: Gameplay: Crash when being hit + // by a trap using a dispenser getEntity returns the owner of + // projectiles, and this would never be the arrow. The owner is + // sometimes NULL. + std::shared_ptr source = dmgSource->getDirectEntity(); - - if (std::dynamic_pointer_cast(source) != NULL && (!server->pvp || !std::dynamic_pointer_cast(source)->isAllowedToAttackPlayers()) ) - { - return false; - } + if (std::dynamic_pointer_cast(source) != NULL && + (!server->pvp || !std::dynamic_pointer_cast(source) + ->isAllowedToAttackPlayers())) { + return false; + } - if (source != NULL && source->GetType() == eTYPE_ARROW) - { - std::shared_ptr arrow = std::dynamic_pointer_cast(source); - if (std::dynamic_pointer_cast(arrow->owner) != NULL && (!server->pvp || !std::dynamic_pointer_cast(arrow->owner)->isAllowedToAttackPlayers()) ) - { - return false; - } - } + if (source != NULL && source->GetType() == eTYPE_ARROW) { + std::shared_ptr arrow = + std::dynamic_pointer_cast(source); + if (std::dynamic_pointer_cast(arrow->owner) != NULL && + (!server->pvp || + !std::dynamic_pointer_cast(arrow->owner) + ->isAllowedToAttackPlayers())) { + return false; + } + } } bool returnVal = Player::hurt(dmgSource, dmg); - if( returnVal ) - { - // 4J Stu - Work out the source of this damage for telemetry - m_lastDamageSource = eTelemetryChallenges_Unknown; + if (returnVal) { + // 4J Stu - Work out the source of this damage for telemetry + m_lastDamageSource = eTelemetryChallenges_Unknown; - if(dmgSource == DamageSource::fall) m_lastDamageSource = eTelemetryPlayerDeathSource_Fall; - else if(dmgSource == DamageSource::onFire || dmgSource == DamageSource::inFire) m_lastDamageSource = eTelemetryPlayerDeathSource_Fire; - else if(dmgSource == DamageSource::lava) m_lastDamageSource = eTelemetryPlayerDeathSource_Lava; - else if(dmgSource == DamageSource::drown) m_lastDamageSource = eTelemetryPlayerDeathSource_Water; - else if(dmgSource == DamageSource::inWall) m_lastDamageSource = eTelemetryPlayerDeathSource_Suffocate; - else if(dmgSource == DamageSource::outOfWorld) m_lastDamageSource = eTelemetryPlayerDeathSource_OutOfWorld; - else if(dmgSource == DamageSource::cactus) m_lastDamageSource = eTelemetryPlayerDeathSource_Cactus; - else - { - std::shared_ptr source = dmgSource->getEntity(); - if( source != NULL ) - { - switch(source->GetType()) - { - case eTYPE_PLAYER: - case eTYPE_SERVERPLAYER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Player_Weapon; - break; - case eTYPE_WOLF: - m_lastDamageSource = eTelemetryPlayerDeathSource_Wolf; - break; - case eTYPE_CREEPER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Explosion_Creeper; - break; - case eTYPE_SKELETON: - m_lastDamageSource = eTelemetryPlayerDeathSource_Skeleton; - break; - case eTYPE_SPIDER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Spider; - break; - case eTYPE_ZOMBIE: - m_lastDamageSource = eTelemetryPlayerDeathSource_Zombie; - break; - case eTYPE_PIGZOMBIE: - m_lastDamageSource = eTelemetryPlayerDeathSource_ZombiePigman; - break; - case eTYPE_GHAST: - m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; - break; - case eTYPE_SLIME: - m_lastDamageSource = eTelemetryPlayerDeathSource_Slime; - break; - case eTYPE_PRIMEDTNT: - m_lastDamageSource = eTelemetryPlayerDeathSource_Explosion_Tnt; - break; - case eTYPE_ARROW: - if ((std::dynamic_pointer_cast(source))->owner != NULL) - { - std::shared_ptr attacker = (std::dynamic_pointer_cast(source))->owner; - if (attacker != NULL) - { - switch(attacker->GetType()) - { - case eTYPE_SKELETON: - m_lastDamageSource = eTelemetryPlayerDeathSource_Skeleton; - break; - case eTYPE_PLAYER: - case eTYPE_SERVERPLAYER: - m_lastDamageSource = eTelemetryPlayerDeathSource_Player_Arrow; - break; - } - } - } - break; - case eTYPE_FIREBALL: - m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; - break; - }; - } - }; - } + if (dmgSource == DamageSource::fall) + m_lastDamageSource = eTelemetryPlayerDeathSource_Fall; + else if (dmgSource == DamageSource::onFire || + dmgSource == DamageSource::inFire) + m_lastDamageSource = eTelemetryPlayerDeathSource_Fire; + else if (dmgSource == DamageSource::lava) + m_lastDamageSource = eTelemetryPlayerDeathSource_Lava; + else if (dmgSource == DamageSource::drown) + m_lastDamageSource = eTelemetryPlayerDeathSource_Water; + else if (dmgSource == DamageSource::inWall) + m_lastDamageSource = eTelemetryPlayerDeathSource_Suffocate; + else if (dmgSource == DamageSource::outOfWorld) + m_lastDamageSource = eTelemetryPlayerDeathSource_OutOfWorld; + else if (dmgSource == DamageSource::cactus) + m_lastDamageSource = eTelemetryPlayerDeathSource_Cactus; + else { + std::shared_ptr source = dmgSource->getEntity(); + if (source != NULL) { + switch (source->GetType()) { + case eTYPE_PLAYER: + case eTYPE_SERVERPLAYER: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Player_Weapon; + break; + case eTYPE_WOLF: + m_lastDamageSource = eTelemetryPlayerDeathSource_Wolf; + break; + case eTYPE_CREEPER: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Explosion_Creeper; + break; + case eTYPE_SKELETON: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Skeleton; + break; + case eTYPE_SPIDER: + m_lastDamageSource = eTelemetryPlayerDeathSource_Spider; + break; + case eTYPE_ZOMBIE: + m_lastDamageSource = eTelemetryPlayerDeathSource_Zombie; + break; + case eTYPE_PIGZOMBIE: + m_lastDamageSource = + eTelemetryPlayerDeathSource_ZombiePigman; + break; + case eTYPE_GHAST: + m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; + break; + case eTYPE_SLIME: + m_lastDamageSource = eTelemetryPlayerDeathSource_Slime; + break; + case eTYPE_PRIMEDTNT: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Explosion_Tnt; + break; + case eTYPE_ARROW: + if ((std::dynamic_pointer_cast(source))->owner != + NULL) { + std::shared_ptr attacker = + (std::dynamic_pointer_cast(source)) + ->owner; + if (attacker != NULL) { + switch (attacker->GetType()) { + case eTYPE_SKELETON: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Skeleton; + break; + case eTYPE_PLAYER: + case eTYPE_SERVERPLAYER: + m_lastDamageSource = + eTelemetryPlayerDeathSource_Player_Arrow; + break; + } + } + } + break; + case eTYPE_FIREBALL: + m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; + break; + }; + } + }; + } - return returnVal; + return returnVal; } -bool ServerPlayer::isPlayerVersusPlayer() -{ - return server->pvp; -} +bool ServerPlayer::isPlayerVersusPlayer() { return server->pvp; } -void ServerPlayer::changeDimension(int i) -{ - if(!connection->hasClientTickedOnce()) return; +void ServerPlayer::changeDimension(int i) { + if (!connection->hasClientTickedOnce()) return; - if (dimension == 1 && i == 1) - { - app.DebugPrintf("Start win game\n"); - awardStat(GenericStats::winGame(), GenericStats::param_winGame()); + if (dimension == 1 && i == 1) { + app.DebugPrintf("Start win game\n"); + awardStat(GenericStats::winGame(), GenericStats::param_winGame()); - // All players on the same system as this player should also be removed from the game while the Win screen is shown - INetworkPlayer *thisPlayer = connection->getNetworkPlayer(); + // All players on the same system as this player should also be removed + // from the game while the Win screen is shown + INetworkPlayer* thisPlayer = connection->getNetworkPlayer(); - if(!wonGame) - { - level->removeEntity(shared_from_this()); - wonGame = true; - m_enteredEndExitPortal = true; // We only flag this for the player in the portal - connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex()) ) ); - app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); - } - if(thisPlayer != NULL) - { - for(AUTO_VAR(it, MinecraftServer::getInstance()->getPlayers()->players.begin()); it != MinecraftServer::getInstance()->getPlayers()->players.end(); ++it) - { - std::shared_ptr servPlayer = *it; - INetworkPlayer *checkPlayer = servPlayer->connection->getNetworkPlayer(); - if(thisPlayer != checkPlayer && checkPlayer != NULL && thisPlayer->IsSameSystem( checkPlayer ) && !servPlayer->wonGame ) - { - servPlayer->wonGame = true; - servPlayer->connection->send( std::shared_ptr( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex() ) ) ); - app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); - } - } - } - app.DebugPrintf("End win game\n"); - } - else - { - awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); + if (!wonGame) { + level->removeEntity(shared_from_this()); + wonGame = true; + m_enteredEndExitPortal = + true; // We only flag this for the player in the portal + connection->send( + std::shared_ptr(new GameEventPacket( + GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex()))); + app.DebugPrintf("Sending packet to %d\n", + thisPlayer->GetUserIndex()); + } + if (thisPlayer != NULL) { + for (AUTO_VAR(it, MinecraftServer::getInstance() + ->getPlayers() + ->players.begin()); + it != + MinecraftServer::getInstance()->getPlayers()->players.end(); + ++it) { + std::shared_ptr servPlayer = *it; + INetworkPlayer* checkPlayer = + servPlayer->connection->getNetworkPlayer(); + if (thisPlayer != checkPlayer && checkPlayer != NULL && + thisPlayer->IsSameSystem(checkPlayer) && + !servPlayer->wonGame) { + servPlayer->wonGame = true; + servPlayer->connection->send( + std::shared_ptr( + new GameEventPacket(GameEventPacket::WIN_GAME, + thisPlayer->GetUserIndex()))); + app.DebugPrintf("Sending packet to %d\n", + thisPlayer->GetUserIndex()); + } + } + } + app.DebugPrintf("End win game\n"); + } else { + awardStat(GenericStats::theEnd(), GenericStats::param_theEnd()); - Pos *pos = server->getLevel(i)->getDimensionSpecificSpawn(); - if (pos != NULL) - { - connection->teleport(pos->x, pos->y, pos->z, 0, 0); - delete pos; - } - server->getPlayers()->toggleDimension( std::dynamic_pointer_cast(shared_from_this()), 1); - lastSentExp = -1; - lastSentHealth = -1; - lastSentFood = -1; - } + Pos* pos = server->getLevel(i)->getDimensionSpecificSpawn(); + if (pos != NULL) { + connection->teleport(pos->x, pos->y, pos->z, 0, 0); + delete pos; + } + server->getPlayers()->toggleDimension( + std::dynamic_pointer_cast(shared_from_this()), 1); + lastSentExp = -1; + lastSentHealth = -1; + lastSentFood = -1; + } } // 4J Added delay param -void ServerPlayer::broadcast(std::shared_ptr te, bool delay /*= false*/) -{ - if (te != NULL) - { +void ServerPlayer::broadcast(std::shared_ptr te, + bool delay /*= false*/) { + if (te != NULL) { std::shared_ptr p = te->getUpdatePacket(); - if (p != NULL) - { - p->shouldDelay = delay; - if(delay) connection->queueSend(p); - else connection->send(p); + if (p != NULL) { + p->shouldDelay = delay; + if (delay) + connection->queueSend(p); + else + connection->send(p); } } } -void ServerPlayer::take(std::shared_ptr e, int orgCount) -{ - if (!e->removed) - { - EntityTracker *entityTracker = getLevel()->getTracker(); - if (e->GetType() == eTYPE_ITEMENTITY) - { - entityTracker->broadcast(e, std::shared_ptr( new TakeItemEntityPacket(e->entityId, entityId) ) ); +void ServerPlayer::take(std::shared_ptr e, int orgCount) { + if (!e->removed) { + EntityTracker* entityTracker = getLevel()->getTracker(); + if (e->GetType() == eTYPE_ITEMENTITY) { + entityTracker->broadcast( + e, std::shared_ptr( + new TakeItemEntityPacket(e->entityId, entityId))); } - if (e->GetType() == eTYPE_ARROW) - { - entityTracker->broadcast(e, std::shared_ptr( new TakeItemEntityPacket(e->entityId, entityId) ) ); - } - if (e->GetType() == eTYPE_EXPERIENCEORB) - { - entityTracker->broadcast(e, std::shared_ptr( new TakeItemEntityPacket(e->entityId, entityId) ) ); + if (e->GetType() == eTYPE_ARROW) { + entityTracker->broadcast( + e, std::shared_ptr( + new TakeItemEntityPacket(e->entityId, entityId))); + } + if (e->GetType() == eTYPE_EXPERIENCEORB) { + entityTracker->broadcast( + e, std::shared_ptr( + new TakeItemEntityPacket(e->entityId, entityId))); } } Player::take(e, orgCount); containerMenu->broadcastChanges(); } -void ServerPlayer::swing() -{ - if (!swinging) - { +void ServerPlayer::swing() { + if (!swinging) { swingTime = -1; swinging = true; - getLevel()->getTracker()->broadcast(shared_from_this(), std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::SWING) ) ); + getLevel()->getTracker()->broadcast( + shared_from_this(), + std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::SWING))); } } -Player::BedSleepingResult ServerPlayer::startSleepInBed(int x, int y, int z, bool bTestUse) -{ +Player::BedSleepingResult ServerPlayer::startSleepInBed(int x, int y, int z, + bool bTestUse) { BedSleepingResult result = Player::startSleepInBed(x, y, z, bTestUse); - if (result == OK) - { - std::shared_ptr p = std::shared_ptr( new EntityActionAtPositionPacket(shared_from_this(), EntityActionAtPositionPacket::START_SLEEP, x, y, z) ); + if (result == OK) { + std::shared_ptr p = + std::shared_ptr( + new EntityActionAtPositionPacket( + shared_from_this(), + EntityActionAtPositionPacket::START_SLEEP, x, y, z)); getLevel()->getTracker()->broadcast(shared_from_this(), p); connection->teleport(this->x, this->y, this->z, yRot, xRot); connection->send(p); @@ -795,210 +847,215 @@ Player::BedSleepingResult ServerPlayer::startSleepInBed(int x, int y, int z, boo return result; } -void ServerPlayer::stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint) -{ - if (isSleeping()) - { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::WAKE_UP) ) ); +void ServerPlayer::stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, + bool saveRespawnPoint) { + if (isSleeping()) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), + std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::WAKE_UP))); } Player::stopSleepInBed(forcefulWakeUp, updateLevelList, saveRespawnPoint); if (connection != NULL) connection->teleport(x, y, z, yRot, xRot); } -void ServerPlayer::ride(std::shared_ptr e) -{ +void ServerPlayer::ride(std::shared_ptr e) { Player::ride(e); - connection->send( std::shared_ptr( new SetRidingPacket(shared_from_this(), riding) ) ); + connection->send(std::shared_ptr( + new SetRidingPacket(shared_from_this(), riding))); - // 4J Removed this - The act of riding will be handled on the client and will change the position - // of the player. If we also teleport it then we can end up with a repeating movements, e.g. bouncing - // up and down after exiting a boat due to slight differences in position on the client and server - //connection->teleport(x, y, z, yRot, xRot); + // 4J Removed this - The act of riding will be handled on the client and + // will change the position of the player. If we also teleport it then we + // can end up with a repeating movements, e.g. bouncing up and down after + // exiting a boat due to slight differences in position on the client and + // server + // connection->teleport(x, y, z, yRot, xRot); } -void ServerPlayer::checkFallDamage(double ya, bool onGround) -{ +void ServerPlayer::checkFallDamage(double ya, bool onGround) {} + +void ServerPlayer::doCheckFallDamage(double ya, bool onGround) { + Player::checkFallDamage(ya, onGround); } -void ServerPlayer::doCheckFallDamage(double ya, bool onGround) -{ - Player::checkFallDamage(ya, onGround); +void ServerPlayer::nextContainerCounter() { + containerCounter = (containerCounter % 100) + 1; } -void ServerPlayer::nextContainerCounter() -{ - containerCounter = (containerCounter % 100) + 1; +bool ServerPlayer::startCrafting(int x, int y, int z) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::WORKBENCH, 0, 9))); + containerMenu = new CraftingMenu(inventory, level, x, y, z); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open crafting container when one was " + "already open\n"); + } + + return true; } -bool ServerPlayer::startCrafting(int x, int y, int z) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::WORKBENCH, 0, 9) ) ); - containerMenu = new CraftingMenu(inventory, level, x, y, z); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open crafting container when one was already open\n"); - } - - return true; +bool ServerPlayer::startEnchanting(int x, int y, int z) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::ENCHANTMENT, 0, 9))); + containerMenu = new EnchantmentMenu(inventory, level, x, y, z); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open enchanting container when one was " + "already open\n"); + } + + return true; } -bool ServerPlayer::startEnchanting(int x, int y, int z) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send(std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::ENCHANTMENT, 0, 9) )); - containerMenu = new EnchantmentMenu(inventory, level, x, y, z); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open enchanting container when one was already open\n"); - } +bool ServerPlayer::startRepairing(int x, int y, int z) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::REPAIR_TABLE, 0, 9))); + containerMenu = new RepairMenu( + inventory, level, x, y, z, + std::dynamic_pointer_cast(shared_from_this())); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open enchanting container when one was " + "already open\n"); + } - return true; + return true; } -bool ServerPlayer::startRepairing(int x, int y, int z) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send(std::shared_ptr ( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::REPAIR_TABLE, 0, 9)) ); - containerMenu = new RepairMenu(inventory, level, x, y, z, std::dynamic_pointer_cast(shared_from_this())); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open enchanting container when one was already open\n"); - } +bool ServerPlayer::openContainer(std::shared_ptr container) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::CONTAINER, + container->getName(), container->getContainerSize()))); - return true; + containerMenu = new ContainerMenu(inventory, container); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open container when one was already open\n"); + } + + return true; } -bool ServerPlayer::openContainer(std::shared_ptr container) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::CONTAINER, container->getName(), container->getContainerSize()) ) ); +bool ServerPlayer::openFurnace(std::shared_ptr furnace) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::FURNACE, 0, + furnace->getContainerSize()))); + containerMenu = new FurnaceMenu(inventory, furnace); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open furnace when one was already open\n"); + } - containerMenu = new ContainerMenu(inventory, container); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open container when one was already open\n"); - } - - return true; + return true; } -bool ServerPlayer::openFurnace(std::shared_ptr furnace) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::FURNACE, 0, furnace->getContainerSize()) ) ); - containerMenu = new FurnaceMenu(inventory, furnace); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open furnace when one was already open\n"); - } +bool ServerPlayer::openTrap(std::shared_ptr trap) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send(std::shared_ptr( + new ContainerOpenPacket(containerCounter, ContainerOpenPacket::TRAP, + 0, trap->getContainerSize()))); + containerMenu = new TrapMenu(inventory, trap); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open dispenser when one was already open\n"); + } - return true; + return true; } -bool ServerPlayer::openTrap(std::shared_ptr trap) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send( std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::TRAP, 0, trap->getContainerSize()) ) ); - containerMenu = new TrapMenu(inventory, trap); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open dispenser when one was already open\n"); - } - - return true; +bool ServerPlayer::openBrewingStand( + std::shared_ptr brewingStand) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::BREWING_STAND, 0, + brewingStand->getContainerSize()))); + containerMenu = new BrewingStandMenu(inventory, brewingStand); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + } else { + app.DebugPrintf( + "ServerPlayer tried to open brewing stand when one was already " + "open\n"); + } + + return true; } -bool ServerPlayer::openBrewingStand(std::shared_ptr brewingStand) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - connection->send(std::shared_ptr( new ContainerOpenPacket(containerCounter, ContainerOpenPacket::BREWING_STAND, 0, brewingStand->getContainerSize()))); - containerMenu = new BrewingStandMenu(inventory, brewingStand); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - } - else - { - app.DebugPrintf("ServerPlayer tried to open brewing stand when one was already open\n"); - } +bool ServerPlayer::openTrading(std::shared_ptr traderTarget) { + if (containerMenu == inventoryMenu) { + nextContainerCounter(); + containerMenu = new MerchantMenu(inventory, traderTarget, level); + containerMenu->containerId = containerCounter; + containerMenu->addSlotListener(this); + std::shared_ptr container = + ((MerchantMenu*)containerMenu)->getTradeContainer(); - return true; + connection->send( + std::shared_ptr(new ContainerOpenPacket( + containerCounter, ContainerOpenPacket::TRADER_NPC, + container->getName(), container->getContainerSize()))); + + MerchantRecipeList* offers = traderTarget->getOffers( + std::dynamic_pointer_cast(shared_from_this())); + if (offers != NULL) { + ByteArrayOutputStream rawOutput; + DataOutputStream output(&rawOutput); + + // just to make sure the offers are matched to the container + output.writeInt(containerCounter); + offers->writeToStream(&output); + + connection->send(std::shared_ptr( + new CustomPayloadPacket(CustomPayloadPacket::TRADER_LIST_PACKET, + rawOutput.toByteArray()))); + } + } else { + app.DebugPrintf( + "ServerPlayer tried to open trading menu when one was already " + "open\n"); + } + + return true; } -bool ServerPlayer::openTrading(std::shared_ptr traderTarget) -{ - if(containerMenu == inventoryMenu) - { - nextContainerCounter(); - containerMenu = new MerchantMenu(inventory, traderTarget, level); - containerMenu->containerId = containerCounter; - containerMenu->addSlotListener(this); - std::shared_ptr container = ((MerchantMenu *) containerMenu)->getTradeContainer(); - - connection->send(std::shared_ptr(new ContainerOpenPacket(containerCounter, ContainerOpenPacket::TRADER_NPC, container->getName(), container->getContainerSize()))); - - MerchantRecipeList *offers = traderTarget->getOffers(std::dynamic_pointer_cast(shared_from_this())); - if (offers != NULL) - { - ByteArrayOutputStream rawOutput; - DataOutputStream output(&rawOutput); - - // just to make sure the offers are matched to the container - output.writeInt(containerCounter); - offers->writeToStream(&output); - - connection->send(std::shared_ptr( new CustomPayloadPacket(CustomPayloadPacket::TRADER_LIST_PACKET, rawOutput.toByteArray()))); - } - } - else - { - app.DebugPrintf("ServerPlayer tried to open trading menu when one was already open\n"); - } - - return true; -} - -void ServerPlayer::slotChanged(AbstractContainerMenu *container, int slotIndex, std::shared_ptr item) -{ - if (dynamic_cast(container->getSlot(slotIndex))) - { +void ServerPlayer::slotChanged(AbstractContainerMenu* container, int slotIndex, + std::shared_ptr item) { + if (dynamic_cast(container->getSlot(slotIndex))) { return; } - if (ignoreSlotUpdateHack) - { + if (ignoreSlotUpdateHack) { // Do not send this packet! // // This is a horrible hack that makes sure that inventory clicks @@ -1007,28 +1064,29 @@ void ServerPlayer::slotChanged(AbstractContainerMenu *container, int slotIndex, return; } - connection->send( std::shared_ptr( new ContainerSetSlotPacket(container->containerId, slotIndex, item) ) ); - + connection->send(std::shared_ptr( + new ContainerSetSlotPacket(container->containerId, slotIndex, item))); } -void ServerPlayer::refreshContainer(AbstractContainerMenu *menu) -{ - std::vector > *items = menu->getItems(); - refreshContainer(menu, items); - delete items; +void ServerPlayer::refreshContainer(AbstractContainerMenu* menu) { + std::vector >* items = menu->getItems(); + refreshContainer(menu, items); + delete items; } -void ServerPlayer::refreshContainer(AbstractContainerMenu *container, std::vector > *items) -{ - connection->send( std::shared_ptr( new ContainerSetContentPacket(container->containerId, items) ) ); - connection->send( std::shared_ptr( new ContainerSetSlotPacket(-1, -1, inventory->getCarried()) ) ); +void ServerPlayer::refreshContainer( + AbstractContainerMenu* container, + std::vector >* items) { + connection->send(std::shared_ptr( + new ContainerSetContentPacket(container->containerId, items))); + connection->send(std::shared_ptr( + new ContainerSetSlotPacket(-1, -1, inventory->getCarried()))); } -void ServerPlayer::setContainerData(AbstractContainerMenu *container, int id, int value) -{ - // 4J - added, so that furnace updates also have this hack - if (ignoreSlotUpdateHack) - { +void ServerPlayer::setContainerData(AbstractContainerMenu* container, int id, + int value) { + // 4J - added, so that furnace updates also have this hack + if (ignoreSlotUpdateHack) { // Do not send this packet! // // This is a horrible hack that makes sure that inventory clicks @@ -1036,408 +1094,449 @@ void ServerPlayer::setContainerData(AbstractContainerMenu *container, int id, in // client again. return; } - connection->send( std::shared_ptr( new ContainerSetDataPacket(container->containerId, id, value) ) ); + connection->send(std::shared_ptr( + new ContainerSetDataPacket(container->containerId, id, value))); } -void ServerPlayer::closeContainer() -{ - connection->send( std::shared_ptr( new ContainerClosePacket(containerMenu->containerId) ) ); +void ServerPlayer::closeContainer() { + connection->send(std::shared_ptr( + new ContainerClosePacket(containerMenu->containerId))); doCloseContainer(); } -void ServerPlayer::broadcastCarriedItem() -{ - if (ignoreSlotUpdateHack) - { +void ServerPlayer::broadcastCarriedItem() { + if (ignoreSlotUpdateHack) { // Do not send this packet! // This is a horrible hack that makes sure that inventory clicks // that the client correctly predicted don't get sent out to the // client again. return; } - connection->send( std::shared_ptr( new ContainerSetSlotPacket(-1, -1, inventory->getCarried()) ) ); + connection->send(std::shared_ptr( + new ContainerSetSlotPacket(-1, -1, inventory->getCarried()))); } -void ServerPlayer::doCloseContainer() -{ - containerMenu->removed( std::dynamic_pointer_cast( shared_from_this() ) ); +void ServerPlayer::doCloseContainer() { + containerMenu->removed( + std::dynamic_pointer_cast(shared_from_this())); containerMenu = inventoryMenu; } -void ServerPlayer::setPlayerInput(float xa, float ya, bool jumping, bool sneaking, float xRot, float yRot) -{ +void ServerPlayer::setPlayerInput(float xa, float ya, bool jumping, + bool sneaking, float xRot, float yRot) { xxa = xa; yya = ya; this->jumping = jumping; - this->setSneaking(sneaking); - this->xRot = xRot; + this->setSneaking(sneaking); + this->xRot = xRot; this->yRot = yRot; } -void ServerPlayer::awardStat(Stat *stat, byteArray param) -{ - if (stat == NULL) - { - delete [] param.data; - return; - } +void ServerPlayer::awardStat(Stat* stat, byteArray param) { + if (stat == NULL) { + delete[] param.data; + return; + } - if (!stat->awardLocallyOnly) - { + if (!stat->awardLocallyOnly) { #ifndef _DURANGO - int count = *((int*)param.data); - delete [] param.data; + int count = *((int*)param.data); + delete[] param.data; - while (count > 100) - { - connection->send( std::shared_ptr( new AwardStatPacket(stat->id, 100) ) ); + while (count > 100) { + connection->send(std::shared_ptr( + new AwardStatPacket(stat->id, 100))); count -= 100; } - connection->send( std::shared_ptr( new AwardStatPacket(stat->id, count) ) ); + connection->send(std::shared_ptr( + new AwardStatPacket(stat->id, count))); #else - connection->send( std::shared_ptr( new AwardStatPacket(stat->id, param) ) ); - // byteArray deleted in AwardStatPacket destructor. + connection->send(std::shared_ptr( + new AwardStatPacket(stat->id, param))); + // byteArray deleted in AwardStatPacket destructor. #endif - } - else delete [] param.data; + } else + delete[] param.data; } -void ServerPlayer::disconnect() -{ +void ServerPlayer::disconnect() { if (riding != NULL) ride(riding); - if (rider.lock() != NULL) rider.lock()->ride(shared_from_this() ); - if (this->m_isSleeping) - { + if (rider.lock() != NULL) rider.lock()->ride(shared_from_this()); + if (this->m_isSleeping) { stopSleepInBed(true, false, false); } } -void ServerPlayer::resetSentInfo() -{ - lastSentHealth = -99999999; +void ServerPlayer::resetSentInfo() { lastSentHealth = -99999999; } + +void ServerPlayer::displayClientMessage(int messageId) { + ChatPacket::EChatPacketMessage messageType = ChatPacket::e_ChatCustom; + // Convert the message id to an enum that will not change between game + // versions + switch (messageId) { + case IDS_TILE_BED_OCCUPIED: + messageType = ChatPacket::e_ChatBedOccupied; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_NO_SLEEP: + messageType = ChatPacket::e_ChatBedNoSleep; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_NOT_VALID: + messageType = ChatPacket::e_ChatBedNotValid; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_NOTSAFE: + messageType = ChatPacket::e_ChatBedNotSafe; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + case IDS_TILE_BED_PLAYERSLEEP: + messageType = ChatPacket::e_ChatBedPlayerSleep; + // broadcast to all the other players in the game + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() != player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatBedPlayerSleep))); + } else { + player->connection->send(std::shared_ptr( + new ChatPacket(name, ChatPacket::e_ChatBedMeSleep))); + } + } + return; + break; + case IDS_PLAYER_ENTERED_END: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() != player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerEnteredEnd))); + } + } + break; + case IDS_PLAYER_LEFT_END: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() != player) { + player->connection->send(std::shared_ptr( + new ChatPacket(name, ChatPacket::e_ChatPlayerLeftEnd))); + } + } + break; + case IDS_TILE_BED_MESLEEP: + messageType = ChatPacket::e_ChatBedMeSleep; + connection->send( + std::shared_ptr(new ChatPacket(L"", messageType))); + break; + + case IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxPigsSheepCows))); + } + } + break; + case IDS_MAX_CHICKENS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxChickens))); + } + } + break; + case IDS_MAX_SQUID_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxSquid))); + } + } + break; + case IDS_MAX_WOLVES_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxWolves))); + } + } + break; + case IDS_MAX_MOOSHROOMS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxMooshrooms))); + } + } + break; + case IDS_MAX_ENEMIES_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxEnemies))); + } + } + break; + + case IDS_MAX_VILLAGERS_SPAWNED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxVillagers))); + } + } + break; + case IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, + ChatPacket::e_ChatPlayerMaxBredPigsSheepCows))); + } + } + break; + case IDS_MAX_CHICKENS_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBredChickens))); + } + } + break; + case IDS_MAX_MUSHROOMCOWS_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBredMooshrooms))); + } + } + break; + + case IDS_MAX_WOLVES_BRED: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBredWolves))); + } + } + break; + + case IDS_CANT_SHEAR_MOOSHROOM: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerCantShearMooshroom))); + } + } + break; + + case IDS_MAX_HANGINGENTITIES: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxHangingEntities))); + } + } + break; + case IDS_CANT_SPAWN_IN_PEACEFUL: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, + ChatPacket::e_ChatPlayerCantSpawnInPeaceful))); + } + } + break; + + case IDS_MAX_BOATS: + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + std::shared_ptr player = + server->getPlayers()->players[i]; + if (shared_from_this() == player) { + player->connection->send( + std::shared_ptr(new ChatPacket( + name, ChatPacket::e_ChatPlayerMaxBoats))); + } + } + break; + + default: + app.DebugPrintf( + "Tried to send a chat packet to the player with an unhandled " + "messageId\n"); + assert(false); + break; + } + + // Language *language = Language::getInstance(); + // std::wstring languageString = + // app.GetString(messageId);//language->getElement(messageId); + // connection->send( std::shared_ptr( new ChatPacket(L"", + // messageType) ) ); } -void ServerPlayer::displayClientMessage(int messageId) -{ - ChatPacket::EChatPacketMessage messageType = ChatPacket::e_ChatCustom; - // Convert the message id to an enum that will not change between game versions - switch(messageId) - { - case IDS_TILE_BED_OCCUPIED: - messageType = ChatPacket::e_ChatBedOccupied; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_NO_SLEEP: - messageType = ChatPacket::e_ChatBedNoSleep; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_NOT_VALID: - messageType = ChatPacket::e_ChatBedNotValid; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_NOTSAFE: - messageType = ChatPacket::e_ChatBedNotSafe; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - case IDS_TILE_BED_PLAYERSLEEP: - messageType = ChatPacket::e_ChatBedPlayerSleep; - // broadcast to all the other players in the game - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()!=player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatBedPlayerSleep))); - } - else - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatBedMeSleep))); - } - } - return; - break; - case IDS_PLAYER_ENTERED_END: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()!=player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerEnteredEnd))); - } - } - break; - case IDS_PLAYER_LEFT_END: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()!=player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerLeftEnd))); - } - } - break; - case IDS_TILE_BED_MESLEEP: - messageType = ChatPacket::e_ChatBedMeSleep; - connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); - break; - - case IDS_MAX_PIGS_SHEEP_COWS_CATS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxPigsSheepCows))); - } - } - break; - case IDS_MAX_CHICKENS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxChickens))); - } - } - break; - case IDS_MAX_SQUID_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxSquid))); - } - } - break; - case IDS_MAX_WOLVES_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxWolves))); - } - } - break; - case IDS_MAX_MOOSHROOMS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxMooshrooms))); - } - } - break; - case IDS_MAX_ENEMIES_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxEnemies))); - } - } - break; - - case IDS_MAX_VILLAGERS_SPAWNED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxVillagers))); - } - } - break; - case IDS_MAX_PIGS_SHEEP_COWS_CATS_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredPigsSheepCows))); - } - } - break; - case IDS_MAX_CHICKENS_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredChickens))); - } - } - break; - case IDS_MAX_MUSHROOMCOWS_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredMooshrooms))); - } - } - break; - - case IDS_MAX_WOLVES_BRED: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredWolves))); - } - } - break; - - case IDS_CANT_SHEAR_MOOSHROOM: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerCantShearMooshroom))); - } - } - break; - - - case IDS_MAX_HANGINGENTITIES: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxHangingEntities))); - } - } - break; - case IDS_CANT_SPAWN_IN_PEACEFUL: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerCantSpawnInPeaceful))); - } - } - break; - - case IDS_MAX_BOATS: - for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) - { - std::shared_ptr player = server->getPlayers()->players[i]; - if(shared_from_this()==player) - { - player->connection->send(std::shared_ptr( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBoats))); - } - } - break; - - default: - app.DebugPrintf("Tried to send a chat packet to the player with an unhandled messageId\n"); - assert( false ); - break; - } - - //Language *language = Language::getInstance(); - //std::wstring languageString = app.GetString(messageId);//language->getElement(messageId); - //connection->send( std::shared_ptr( new ChatPacket(L"", messageType) ) ); +void ServerPlayer::completeUsingItem() { + connection->send(std::shared_ptr( + new EntityEventPacket(entityId, EntityEvent::USE_ITEM_COMPLETE))); + Player::completeUsingItem(); } -void ServerPlayer::completeUsingItem() -{ - connection->send(std::shared_ptr( new EntityEventPacket(entityId, EntityEvent::USE_ITEM_COMPLETE) ) ); - Player::completeUsingItem(); +void ServerPlayer::startUsingItem(std::shared_ptr instance, + int duration) { + Player::startUsingItem(instance, duration); + + if (instance != NULL && instance->getItem() != NULL && + instance->getItem()->getUseAnimation(instance) == UseAnim_eat) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), + std::shared_ptr( + new AnimatePacket(shared_from_this(), AnimatePacket::EAT))); + } } -void ServerPlayer::startUsingItem(std::shared_ptr instance, int duration) -{ - Player::startUsingItem(instance, duration); - - if (instance != NULL && instance->getItem() != NULL && instance->getItem()->getUseAnimation(instance) == UseAnim_eat) - { - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(shared_from_this(), AnimatePacket::EAT) ) ); - } +void ServerPlayer::restoreFrom(std::shared_ptr oldPlayer, + bool restoreAll) { + Player::restoreFrom(oldPlayer, restoreAll); + lastSentExp = -1; + lastSentHealth = -1; + lastSentFood = -1; + entitiesToRemove = + std::dynamic_pointer_cast(oldPlayer)->entitiesToRemove; } -void ServerPlayer::restoreFrom(std::shared_ptr oldPlayer, bool restoreAll) -{ - Player::restoreFrom(oldPlayer, restoreAll); - lastSentExp = -1; - lastSentHealth = -1; - lastSentFood = -1; - entitiesToRemove = std::dynamic_pointer_cast(oldPlayer)->entitiesToRemove; +void ServerPlayer::onEffectAdded(MobEffectInstance* effect) { + Player::onEffectAdded(effect); + connection->send(std::shared_ptr( + new UpdateMobEffectPacket(entityId, effect))); } -void ServerPlayer::onEffectAdded(MobEffectInstance *effect) -{ - Player::onEffectAdded(effect); - connection->send(std::shared_ptr( new UpdateMobEffectPacket(entityId, effect) ) ); +void ServerPlayer::onEffectUpdated(MobEffectInstance* effect) { + Player::onEffectUpdated(effect); + connection->send(std::shared_ptr( + new UpdateMobEffectPacket(entityId, effect))); } - -void ServerPlayer::onEffectUpdated(MobEffectInstance *effect) -{ - Player::onEffectUpdated(effect); - connection->send(std::shared_ptr( new UpdateMobEffectPacket(entityId, effect) ) ); +void ServerPlayer::onEffectRemoved(MobEffectInstance* effect) { + Player::onEffectRemoved(effect); + connection->send(std::shared_ptr( + new RemoveMobEffectPacket(entityId, effect))); } - -void ServerPlayer::onEffectRemoved(MobEffectInstance *effect) -{ - Player::onEffectRemoved(effect); - connection->send(std::shared_ptr( new RemoveMobEffectPacket(entityId, effect) ) ); +void ServerPlayer::teleportTo(double x, double y, double z) { + connection->teleport(x, y, z, yRot, xRot); } -void ServerPlayer::teleportTo(double x, double y, double z) -{ - connection->teleport(x, y, z, yRot, xRot); +void ServerPlayer::crit(std::shared_ptr entity) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), std::shared_ptr(new AnimatePacket( + entity, AnimatePacket::CRITICAL_HIT))); } -void ServerPlayer::crit(std::shared_ptr entity) -{ - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(entity, AnimatePacket::CRITICAL_HIT) )); +void ServerPlayer::magicCrit(std::shared_ptr entity) { + getLevel()->getTracker()->broadcastAndSend( + shared_from_this(), std::shared_ptr(new AnimatePacket( + entity, AnimatePacket::MAGIC_CRITICAL_HIT))); } -void ServerPlayer::magicCrit(std::shared_ptr entity) -{ - getLevel()->getTracker()->broadcastAndSend(shared_from_this(), std::shared_ptr( new AnimatePacket(entity, AnimatePacket::MAGIC_CRITICAL_HIT) )); +void ServerPlayer::onUpdateAbilities() { + if (connection == NULL) return; + connection->send(std::shared_ptr( + new PlayerAbilitiesPacket(&abilities))); } -void ServerPlayer::onUpdateAbilities() -{ - if (connection == NULL) return; - connection->send(std::shared_ptr(new PlayerAbilitiesPacket(&abilities))); +ServerLevel* ServerPlayer::getLevel() { return (ServerLevel*)level; } + +void ServerPlayer::setGameMode(GameType* mode) { + gameMode->setGameModeForPlayer(mode); + connection->send(std::shared_ptr( + new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, mode->getId()))); } -ServerLevel *ServerPlayer::getLevel() -{ - return (ServerLevel *) level; +void ServerPlayer::sendMessage( + const std::wstring& message, + ChatPacket::EChatPacketMessage type /*= e_ChatCustom*/, + int customData /*= -1*/, const std::wstring& additionalMessage /*= L""*/) { + connection->send(std::shared_ptr( + new ChatPacket(message, type, customData, additionalMessage))); } -void ServerPlayer::setGameMode(GameType *mode) -{ - gameMode->setGameModeForPlayer(mode); - connection->send(std::shared_ptr(new GameEventPacket(GameEventPacket::CHANGE_GAME_MODE, mode->getId()))); -} - -void ServerPlayer::sendMessage(const std::wstring& message, ChatPacket::EChatPacketMessage type /*= e_ChatCustom*/, int customData /*= -1*/, const std::wstring& additionalMessage /*= L""*/) -{ - connection->send(std::shared_ptr(new ChatPacket(message,type,customData,additionalMessage))); -} - -bool ServerPlayer::hasPermission(EGameCommand command) -{ - return server->getPlayers()->isOp(std::dynamic_pointer_cast(shared_from_this())); +bool ServerPlayer::hasPermission(EGameCommand command) { + return server->getPlayers()->isOp( + std::dynamic_pointer_cast(shared_from_this())); } // 4J - Don't use -//void ServerPlayer::updateOptions(std::shared_ptr packet) +// void ServerPlayer::updateOptions(std::shared_ptr +// packet) //{ // // 4J - Don't need // //if (language.getLanguageList().containsKey(packet.getLanguage())) @@ -1446,7 +1545,8 @@ bool ServerPlayer::hasPermission(EGameCommand command) // //} // // int dist = 16 * 16 >> packet->getViewDistance(); -// if (dist > PlayerChunkMap::MIN_VIEW_DISTANCE && dist < PlayerChunkMap::MAX_VIEW_DISTANCE) +// if (dist > PlayerChunkMap::MIN_VIEW_DISTANCE && dist < +//PlayerChunkMap::MAX_VIEW_DISTANCE) // { // this->viewDistance = dist; // } @@ -1455,64 +1555,63 @@ bool ServerPlayer::hasPermission(EGameCommand command) // canChatColor = packet->getChatColors(); // // // 4J - Don't need -// //if (server.isSingleplayer() && server.getSingleplayerName().equals(name)) +// //if (server.isSingleplayer() && +//server.getSingleplayerName().equals(name)) // //{ // // server.setDifficulty(packet.getDifficulty()); // //} //} -int ServerPlayer::getViewDistance() -{ - return viewDistance; -} +int ServerPlayer::getViewDistance() { return viewDistance; } -//bool ServerPlayer::canChatInColor() +// bool ServerPlayer::canChatInColor() //{ // return canChatColor; -//} +// } // -//int ServerPlayer::getChatVisibility() +// int ServerPlayer::getChatVisibility() //{ // return chatVisibility; -//} +// } -// Get an index that can be used to uniquely reference this chunk from either dimension -int ServerPlayer::getFlagIndexForChunk(const ChunkPos& pos, int dimension) -{ - // Scale pos x & z up by 16 as getGlobalIndexForChunk is expecting tile rather than chunk coords - return LevelRenderer::getGlobalIndexForChunk(pos.x * 16 , 0, pos.z * 16, dimension ) / (Level::maxBuildHeight / 16); // dividing here by number of renderer chunks in one column; +// Get an index that can be used to uniquely reference this chunk from either +// dimension +int ServerPlayer::getFlagIndexForChunk(const ChunkPos& pos, int dimension) { + // Scale pos x & z up by 16 as getGlobalIndexForChunk is expecting tile + // rather than chunk coords + return LevelRenderer::getGlobalIndexForChunk(pos.x * 16, 0, pos.z * 16, + dimension) / + (Level::maxBuildHeight / + 16); // dividing here by number of renderer chunks in one column; } // 4J Added, returns a number which is subtracted from the default view distance -int ServerPlayer::getPlayerViewDistanceModifier() -{ - int value = 0; +int ServerPlayer::getPlayerViewDistanceModifier() { + int value = 0; - if( !connection->isLocal() ) - { - INetworkPlayer *player = connection->getNetworkPlayer(); + if (!connection->isLocal()) { + INetworkPlayer* player = connection->getNetworkPlayer(); - if( player != NULL ) - { - int rtt = player->GetCurrentRtt(); + if (player != NULL) { + int rtt = player->GetCurrentRtt(); - value = rtt >> 6; + value = rtt >> 6; - if(value > 4) value = 4; - } - } + if (value > 4) value = 4; + } + } - return value; + return value; } -void ServerPlayer::handleCollectItem(std::shared_ptr item) -{ - if(gameMode->getGameRules() != NULL) gameMode->getGameRules()->onCollectItem(item); +void ServerPlayer::handleCollectItem(std::shared_ptr item) { + if (gameMode->getGameRules() != NULL) + gameMode->getGameRules()->onCollectItem(item); } #ifndef _CONTENT_PACKAGE -void ServerPlayer::debug_setPosition(double x, double y, double z, double nYRot, double nXRot) -{ - connection->teleport(x, y, z, nYRot, nXRot); +void ServerPlayer::debug_setPosition(double x, double y, double z, double nYRot, + double nXRot) { + connection->teleport(x, y, z, nYRot, nXRot); } #endif diff --git a/Minecraft.Client/Player/ServerPlayer.h b/Minecraft.Client/Player/ServerPlayer.h index 378186ebb..f3f4c5c45 100644 --- a/Minecraft.Client/Player/ServerPlayer.h +++ b/Minecraft.Client/Player/ServerPlayer.h @@ -12,153 +12,183 @@ class Entity; class BrewingStandTileEntity; class Merchant; - -class ServerPlayer : public Player, public net_minecraft_world_inventory::ContainerListener -{ +class ServerPlayer : public Player, + public net_minecraft_world_inventory::ContainerListener { public: - eINSTANCEOF GetType() { return eTYPE_SERVERPLAYER; } - std::shared_ptr connection; - MinecraftServer *server; - ServerPlayerGameMode *gameMode; + eINSTANCEOF GetType() { return eTYPE_SERVERPLAYER; } + std::shared_ptr connection; + MinecraftServer* server; + ServerPlayerGameMode* gameMode; double lastMoveX, lastMoveZ; std::list chunksToSend; - std::vector entitiesToRemove; + std::vector entitiesToRemove; std::unordered_set seenChunks; int spewTimer; - // 4J-Added, for 'Adventure Time' achievement. - Biome *currentBiome; + // 4J-Added, for 'Adventure Time' achievement. + Biome* currentBiome; private: - int lastSentHealth; - int lastSentFood; - bool lastFoodSaturationZero; - int lastSentExp; + int lastSentHealth; + int lastSentFood; + bool lastFoodSaturationZero; + int lastSentExp; int invulnerableTime; - int viewDistance; - int lastBrupSendTickCount; // 4J Added + int viewDistance; + int lastBrupSendTickCount; // 4J Added public: - ServerPlayer(MinecraftServer *server, Level *level, const std::wstring& name, ServerPlayerGameMode *gameMode); - ~ServerPlayer(); - void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added + ServerPlayer(MinecraftServer* server, Level* level, + const std::wstring& name, ServerPlayerGameMode* gameMode); + ~ServerPlayer(); + void flagEntitiesToBeRemoved(unsigned int* flags, + bool* removedFound); // 4J added - virtual void readAdditionalSaveData(CompoundTag *entityTag); - virtual void addAdditonalSaveData(CompoundTag *entityTag); - virtual void withdrawExperienceLevels(int amount); + virtual void readAdditionalSaveData(CompoundTag* entityTag); + virtual void addAdditonalSaveData(CompoundTag* entityTag); + virtual void withdrawExperienceLevels(int amount); void initMenu(); private: - ItemInstanceArray lastCarried; + ItemInstanceArray lastCarried; public: - virtual ItemInstanceArray getEquipmentSlots(); + virtual ItemInstanceArray getEquipmentSlots(); + protected: - virtual void setDefaultHeadHeight(); + virtual void setDefaultHeadHeight(); + public: - virtual float getHeadHeight(); + virtual float getHeadHeight(); virtual void tick(); - void flushEntitiesToRemove(); + void flushEntitiesToRemove(); virtual std::shared_ptr getCarried(int slot); - virtual void die(DamageSource *source); - virtual bool hurt(DamageSource *dmgSource, int dmg); - virtual bool isPlayerVersusPlayer(); - void doTick(bool sendChunks, bool dontDelayChunks = false, bool ignorePortal = false); - void doTickA(); - void doChunkSendingTick(bool dontDelayChunks); - void doTickB(bool ignorePortal); - virtual void changeDimension(int i); + virtual void die(DamageSource* source); + virtual bool hurt(DamageSource* dmgSource, int dmg); + virtual bool isPlayerVersusPlayer(); + void doTick(bool sendChunks, bool dontDelayChunks = false, + bool ignorePortal = false); + void doTickA(); + void doChunkSendingTick(bool dontDelayChunks); + void doTickB(bool ignorePortal); + virtual void changeDimension(int i); + private: - void broadcast(std::shared_ptr te, bool delay = false); + void broadcast(std::shared_ptr te, bool delay = false); + public: virtual void take(std::shared_ptr e, int orgCount); virtual void swing(); - virtual BedSleepingResult startSleepInBed(int x, int y, int z, bool bTestUse = false); + virtual BedSleepingResult startSleepInBed(int x, int y, int z, + bool bTestUse = false); public: - virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); + virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, + bool saveRespawnPoint); virtual void ride(std::shared_ptr e); + protected: - virtual void checkFallDamage(double ya, bool onGround); -public: - void doCheckFallDamage(double ya, bool onGround); -private: - int containerCounter; -public: - bool ignoreSlotUpdateHack; - int latency; - bool wonGame; - bool m_enteredEndExitPortal; // 4J Added - -private: - void nextContainerCounter(); + virtual void checkFallDamage(double ya, bool onGround); public: - virtual bool startCrafting(int x, int y, int z); // 4J added bool return - virtual bool startEnchanting(int x, int y, int z); // 4J added bool return - virtual bool startRepairing(int x, int y, int z); // 4J added bool return - virtual bool openContainer(std::shared_ptr container); // 4J added bool return - virtual bool openFurnace(std::shared_ptr furnace); // 4J added bool return - virtual bool openTrap(std::shared_ptr trap); // 4J added bool return - virtual bool openBrewingStand(std::shared_ptr brewingStand); // 4J added bool return - virtual bool openTrading(std::shared_ptr traderTarget); // 4J added bool return - virtual void slotChanged(AbstractContainerMenu *container, int slotIndex, std::shared_ptr item); - void refreshContainer(AbstractContainerMenu *menu); - virtual void refreshContainer(AbstractContainerMenu *container, std::vector > *items); - virtual void setContainerData(AbstractContainerMenu *container, int id, int value); + void doCheckFallDamage(double ya, bool onGround); + +private: + int containerCounter; + +public: + bool ignoreSlotUpdateHack; + int latency; + bool wonGame; + bool m_enteredEndExitPortal; // 4J Added + +private: + void nextContainerCounter(); + +public: + virtual bool startCrafting(int x, int y, int z); // 4J added bool return + virtual bool startEnchanting(int x, int y, int z); // 4J added bool return + virtual bool startRepairing(int x, int y, int z); // 4J added bool return + virtual bool openContainer( + std::shared_ptr container); // 4J added bool return + virtual bool openFurnace( + std::shared_ptr furnace); // 4J added bool return + virtual bool openTrap( + std::shared_ptr trap); // 4J added bool return + virtual bool openBrewingStand(std::shared_ptr + brewingStand); // 4J added bool return + virtual bool openTrading( + std::shared_ptr traderTarget); // 4J added bool return + virtual void slotChanged(AbstractContainerMenu* container, int slotIndex, + std::shared_ptr item); + void refreshContainer(AbstractContainerMenu* menu); + virtual void refreshContainer( + AbstractContainerMenu* container, + std::vector >* items); + virtual void setContainerData(AbstractContainerMenu* container, int id, + int value); virtual void closeContainer(); void broadcastCarriedItem(); void doCloseContainer(); - void setPlayerInput(float xa, float ya, bool jumping, bool sneaking, float xRot, float yRot); + void setPlayerInput(float xa, float ya, bool jumping, bool sneaking, + float xRot, float yRot); - virtual void awardStat(Stat *stat, byteArray param); + virtual void awardStat(Stat* stat, byteArray param); - void disconnect(); + void disconnect(); void resetSentInfo(); virtual void displayClientMessage(int messageId); protected: - virtual void completeUsingItem(); + virtual void completeUsingItem(); public: - virtual void startUsingItem(std::shared_ptr instance, int duration); - virtual void restoreFrom(std::shared_ptr oldPlayer, bool restoreAll); + virtual void startUsingItem(std::shared_ptr instance, + int duration); + virtual void restoreFrom(std::shared_ptr oldPlayer, + bool restoreAll); protected: - virtual void onEffectAdded(MobEffectInstance *effect); - virtual void onEffectUpdated(MobEffectInstance *effect); - virtual void onEffectRemoved(MobEffectInstance *effect); + virtual void onEffectAdded(MobEffectInstance* effect); + virtual void onEffectUpdated(MobEffectInstance* effect); + virtual void onEffectRemoved(MobEffectInstance* effect); public: - virtual void teleportTo(double x, double y, double z); + virtual void teleportTo(double x, double y, double z); virtual void crit(std::shared_ptr entity); virtual void magicCrit(std::shared_ptr entity); - void onUpdateAbilities(); - ServerLevel *getLevel(); - void setGameMode(GameType *mode); - void sendMessage(const std::wstring& message, ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, int customData = -1, const std::wstring& additionalMessage = L""); - bool hasPermission(EGameCommand command); - // 4J - Don't use - //void updateOptions(std::shared_ptr packet); - int getViewDistance(); - //bool canChatInColor(); - //int getChatVisibility(); + void onUpdateAbilities(); + ServerLevel* getLevel(); + void setGameMode(GameType* mode); + void sendMessage( + const std::wstring& message, + ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, + int customData = -1, const std::wstring& additionalMessage = L""); + bool hasPermission(EGameCommand command); + // 4J - Don't use + // void updateOptions(std::shared_ptr packet); + int getViewDistance(); + // bool canChatInColor(); + // int getChatVisibility(); public: - - static int getFlagIndexForChunk(const ChunkPos& pos, int dimension); // 4J - added - int getPlayerViewDistanceModifier(); // 4J Added, returns a number which is subtracted from the default view distance + static int getFlagIndexForChunk(const ChunkPos& pos, + int dimension); // 4J - added + int getPlayerViewDistanceModifier(); // 4J Added, returns a number which is + // subtracted from the default view + // distance public: - // 4J Stu - Added hooks for the game rules - virtual void handleCollectItem(std::shared_ptr item); + // 4J Stu - Added hooks for the game rules + virtual void handleCollectItem(std::shared_ptr item); #ifndef _CONTENT_PACKAGE - void debug_setPosition(double,double,double,double,double); + void debug_setPosition(double, double, double, double, double); #endif protected: - // 4J Added to record telemetry of player deaths, this should store the last source of damage - ETelemetryChallenges m_lastDamageSource; + // 4J Added to record telemetry of player deaths, this should store the last + // source of damage + ETelemetryChallenges m_lastDamageSource; }; diff --git a/Minecraft.Client/Player/ServerPlayerGameMode.cpp b/Minecraft.Client/Player/ServerPlayerGameMode.cpp index 50a1a5d55..cabbf4189 100644 --- a/Minecraft.Client/Player/ServerPlayerGameMode.cpp +++ b/Minecraft.Client/Player/ServerPlayerGameMode.cpp @@ -13,363 +13,341 @@ #include "../Level/MultiPlayerLevel.h" #include "../Rendering/LevelRenderer.h" -ServerPlayerGameMode::ServerPlayerGameMode(Level *level) -{ - // 4J - added initialisers - isDestroyingBlock = false; +ServerPlayerGameMode::ServerPlayerGameMode(Level* level) { + // 4J - added initialisers + isDestroyingBlock = false; destroyProgressStart = 0; xDestroyBlock = yDestroyBlock = zDestroyBlock = 0; gameTicks = 0; hasDelayedDestroy = false; delayedDestroyX = delayedDestroyY = delayedDestroyZ = 0; delayedTickStart = 0; - lastSentState = -1; - gameModeForPlayer = GameType::NOT_SET; + lastSentState = -1; + gameModeForPlayer = GameType::NOT_SET; - this->level = level; + this->level = level; - // 4J Added - m_gameRules = NULL; + // 4J Added + m_gameRules = NULL; } -ServerPlayerGameMode::~ServerPlayerGameMode() -{ - if(m_gameRules!=NULL) delete m_gameRules; +ServerPlayerGameMode::~ServerPlayerGameMode() { + if (m_gameRules != NULL) delete m_gameRules; } -void ServerPlayerGameMode::setGameModeForPlayer(GameType *gameModeForPlayer) -{ - this->gameModeForPlayer = gameModeForPlayer; - - gameModeForPlayer->updatePlayerAbilities(&(player->abilities)); - player->onUpdateAbilities(); +void ServerPlayerGameMode::setGameModeForPlayer(GameType* gameModeForPlayer) { + this->gameModeForPlayer = gameModeForPlayer; + gameModeForPlayer->updatePlayerAbilities(&(player->abilities)); + player->onUpdateAbilities(); } -GameType *ServerPlayerGameMode::getGameModeForPlayer() -{ - return gameModeForPlayer; +GameType* ServerPlayerGameMode::getGameModeForPlayer() { + return gameModeForPlayer; } -bool ServerPlayerGameMode::isSurvival() -{ - return gameModeForPlayer->isSurvival(); +bool ServerPlayerGameMode::isSurvival() { + return gameModeForPlayer->isSurvival(); } -bool ServerPlayerGameMode::isCreative() -{ - return gameModeForPlayer->isCreative(); +bool ServerPlayerGameMode::isCreative() { + return gameModeForPlayer->isCreative(); } -void ServerPlayerGameMode::updateGameMode(GameType *gameType) -{ - if (gameModeForPlayer == GameType::NOT_SET) - { - gameModeForPlayer = gameType; - } - setGameModeForPlayer(gameModeForPlayer); +void ServerPlayerGameMode::updateGameMode(GameType* gameType) { + if (gameModeForPlayer == GameType::NOT_SET) { + gameModeForPlayer = gameType; + } + setGameModeForPlayer(gameModeForPlayer); } -void ServerPlayerGameMode::tick() -{ +void ServerPlayerGameMode::tick() { gameTicks++; - if (hasDelayedDestroy) - { + if (hasDelayedDestroy) { int ticksSpentDestroying = gameTicks - delayedTickStart; - int t = level->getTile(delayedDestroyX, delayedDestroyY, delayedDestroyZ); - if (t == 0) - { - hasDelayedDestroy = false; - } - else - { - Tile *tile = Tile::tiles[t]; - float destroyProgress = tile->getDestroyProgress(player, player->level, delayedDestroyX, delayedDestroyY, delayedDestroyZ) * (ticksSpentDestroying + 1); - int state = (int) (destroyProgress * 10); + int t = + level->getTile(delayedDestroyX, delayedDestroyY, delayedDestroyZ); + if (t == 0) { + hasDelayedDestroy = false; + } else { + Tile* tile = Tile::tiles[t]; + float destroyProgress = + tile->getDestroyProgress(player, player->level, delayedDestroyX, + delayedDestroyY, delayedDestroyZ) * + (ticksSpentDestroying + 1); + int state = (int)(destroyProgress * 10); - if (state != lastSentState) - { - level->destroyTileProgress(player->entityId, delayedDestroyX, delayedDestroyY, delayedDestroyZ, state); - lastSentState = state; - } - if (destroyProgress >= 1) - { - hasDelayedDestroy = false; - destroyBlock(delayedDestroyX, delayedDestroyY, delayedDestroyZ); - } - } - } - else if (isDestroyingBlock) - { - int t = level->getTile(xDestroyBlock, yDestroyBlock, zDestroyBlock); - Tile *tile = Tile::tiles[t]; - - if (tile == NULL) - { - level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); - lastSentState = -1; - isDestroyingBlock = false; - } - else - { - int ticksSpentDestroying = gameTicks - destroyProgressStart; - float destroyProgress = tile->getDestroyProgress(player, player->level, xDestroyBlock, yDestroyBlock, zDestroyBlock) * (ticksSpentDestroying + 1); - int state = (int) (destroyProgress * 10); - - if (state != lastSentState) - { - level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, state); - lastSentState = state; - } - } - } -} - -void ServerPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) -{ - if(!player->isAllowedToMine()) return; - - if (gameModeForPlayer->isReadOnly()) - { - return; - } - - if (isCreative()) - { - if(!level->extinguishFire(nullptr, x, y, z, face)) - { - destroyBlock(x, y, z); - } - return; - } - level->extinguishFire(player, x, y, z, face); - destroyProgressStart = gameTicks; - float progress = 1.0f; - int t = level->getTile(x, y, z); - if (t > 0) - { - Tile::tiles[t]->attack(level, x, y, z, player); - progress = Tile::tiles[t]->getDestroyProgress(player, player->level, x, y, z); - } - - if (t > 0 && (progress >= 1 || (app.DebugSettingsOn() && (player->GetDebugOptions()&(1L<destroyTileProgress(player->entityId, x, y, z, state); - lastSentState = state; - } -} - -void ServerPlayerGameMode::stopDestroyBlock(int x, int y, int z) -{ - if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) - { -// int ticksSpentDestroying = gameTicks - destroyProgressStart; - - int t = level->getTile(x, y, z); - if (t != 0) - { - Tile *tile = Tile::tiles[t]; - - // MGH - removed checking for the destroy progress here, it has already been checked on the client before it sent the packet. - // fixes issues with this failing to destroy because of packets bunching up -// float destroyProgress = tile->getDestroyProgress(player, player->level, x, y, z) * (ticksSpentDestroying + 1); -// if (destroyProgress >= .7f || bIgnoreDestroyProgress) - { - isDestroyingBlock = false; - level->destroyTileProgress(player->entityId, x, y, z, -1); - destroyBlock(x, y, z); + if (state != lastSentState) { + level->destroyTileProgress(player->entityId, delayedDestroyX, + delayedDestroyY, delayedDestroyZ, + state); + lastSentState = state; + } + if (destroyProgress >= 1) { + hasDelayedDestroy = false; + destroyBlock(delayedDestroyX, delayedDestroyY, delayedDestroyZ); + } + } + } else if (isDestroyingBlock) { + int t = level->getTile(xDestroyBlock, yDestroyBlock, zDestroyBlock); + Tile* tile = Tile::tiles[t]; + + if (tile == NULL) { + level->destroyTileProgress(player->entityId, xDestroyBlock, + yDestroyBlock, zDestroyBlock, -1); + lastSentState = -1; + isDestroyingBlock = false; + } else { + int ticksSpentDestroying = gameTicks - destroyProgressStart; + float destroyProgress = + tile->getDestroyProgress(player, player->level, xDestroyBlock, + yDestroyBlock, zDestroyBlock) * + (ticksSpentDestroying + 1); + int state = (int)(destroyProgress * 10); + + if (state != lastSentState) { + level->destroyTileProgress(player->entityId, xDestroyBlock, + yDestroyBlock, zDestroyBlock, state); + lastSentState = state; } -// else if (!hasDelayedDestroy) -// { -// isDestroyingBlock = false; -// hasDelayedDestroy = true; -// delayedDestroyX = x; -// delayedDestroyY = y; -// delayedDestroyZ = z; -// delayedTickStart = destroyProgressStart; -// } } } } -void ServerPlayerGameMode::abortDestroyBlock(int x, int y, int z) -{ - isDestroyingBlock = false; - level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); +void ServerPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) { + if (!player->isAllowedToMine()) return; + + if (gameModeForPlayer->isReadOnly()) { + return; + } + + if (isCreative()) { + if (!level->extinguishFire(nullptr, x, y, z, face)) { + destroyBlock(x, y, z); + } + return; + } + level->extinguishFire(player, x, y, z, face); + destroyProgressStart = gameTicks; + float progress = 1.0f; + int t = level->getTile(x, y, z); + if (t > 0) { + Tile::tiles[t]->attack(level, x, y, z, player); + progress = + Tile::tiles[t]->getDestroyProgress(player, player->level, x, y, z); + } + + if (t > 0 && (progress >= 1 || (app.DebugSettingsOn() && + (player->GetDebugOptions() & + (1L << eDebugSetting_InstantDestroy))))) { + destroyBlock(x, y, z); + } else { + isDestroyingBlock = true; + xDestroyBlock = x; + yDestroyBlock = y; + zDestroyBlock = z; + int state = (int)(progress * 10); + level->destroyTileProgress(player->entityId, x, y, z, state); + lastSentState = state; + } } -bool ServerPlayerGameMode::superDestroyBlock(int x, int y, int z) -{ - Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; +void ServerPlayerGameMode::stopDestroyBlock(int x, int y, int z) { + if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) { + // int ticksSpentDestroying = gameTicks - destroyProgressStart; + + int t = level->getTile(x, y, z); + if (t != 0) { + Tile* tile = Tile::tiles[t]; + + // MGH - removed checking for the destroy progress here, it has + // already been checked on the client before it sent the packet. + // fixes issues with this failing to destroy + //because of packets bunching up + // float destroyProgress = + // tile->getDestroyProgress(player, player->level, x, y, + // z) * (ticksSpentDestroying + 1); if (destroyProgress + // >= .7f || bIgnoreDestroyProgress) + { + isDestroyingBlock = false; + level->destroyTileProgress(player->entityId, x, y, z, -1); + destroyBlock(x, y, z); + } + // else if (!hasDelayedDestroy) + // { + // isDestroyingBlock = false; + // hasDelayedDestroy = true; + // delayedDestroyX = x; + // delayedDestroyY = y; + // delayedDestroyZ = z; + // delayedTickStart = destroyProgressStart; + // } + } + } +} + +void ServerPlayerGameMode::abortDestroyBlock(int x, int y, int z) { + isDestroyingBlock = false; + level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, + zDestroyBlock, -1); +} + +bool ServerPlayerGameMode::superDestroyBlock(int x, int y, int z) { + Tile* oldTile = Tile::tiles[level->getTile(x, y, z)]; int data = level->getData(x, y, z); - if (oldTile != NULL) - { - oldTile->playerWillDestroy(level, x, y, z, data, player); - } + if (oldTile != NULL) { + oldTile->playerWillDestroy(level, x, y, z, data, player); + } bool changed = level->setTile(x, y, z, 0); - if (oldTile != NULL && changed) - { + if (oldTile != NULL && changed) { oldTile->destroy(level, x, y, z, data); } return changed; } -bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) -{ - if (gameModeForPlayer->isReadOnly()) - { - return false; - } +bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) { + if (gameModeForPlayer->isReadOnly()) { + return false; + } int t = level->getTile(x, y, z); int data = level->getData(x, y, z); - - level->levelEvent(player, LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, t + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); - - // 4J - In creative mode, the point where we need to tell the renderer that we are about to destroy a tile via destroyingTileAt is quite complicated. - // If the player being told is remote, then we always want the client to do it as it does the final update. If the player being told is local, - // then we need to update the renderer Here if we are sharing data between host & client as this is the final point where the original data is still intact. - // If the player being told is local, and we aren't sharing data between host & client, then we can just treat it as if it is a remote player and - // it can update the renderer. - bool clientToUpdateRenderer = false; - if( isCreative() ) - { - clientToUpdateRenderer = true; - if( std::dynamic_pointer_cast(player)->connection->isLocal() ) - { - // Establish whether we are sharing this chunk between client & server - MultiPlayerLevel *clientLevel = Minecraft::GetInstance()->getLevel(level->dimension->id); - if( clientLevel ) - { - LevelChunk *lc = clientLevel->getChunkAt( x, z ); -#ifdef SHARING_ENABLED - if( lc->sharingTilesAndData ) - { - // We are sharing - this is the last point we can tell the renderer - Minecraft::GetInstance()->levelRenderer->destroyedTileManager->destroyingTileAt( clientLevel, x, y, z ); - // Don't need to ask the client to do this too - clientToUpdateRenderer = false; - } + level->levelEvent(player, LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, + t + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); + + // 4J - In creative mode, the point where we need to tell the renderer that + // we are about to destroy a tile via destroyingTileAt is quite complicated. + // If the player being told is remote, then we always want the client to do + // it as it does the final update. If the player being told is local, then + // we need to update the renderer Here if we are sharing data between host & + // client as this is the final point where the original data is still + // intact. If the player being told is local, and we aren't sharing data + // between host & client, then we can just treat it as if it is a remote + // player and it can update the renderer. + bool clientToUpdateRenderer = false; + if (isCreative()) { + clientToUpdateRenderer = true; + if (std::dynamic_pointer_cast(player) + ->connection->isLocal()) { + // Establish whether we are sharing this chunk between client & + // server + MultiPlayerLevel* clientLevel = + Minecraft::GetInstance()->getLevel(level->dimension->id); + if (clientLevel) { + LevelChunk* lc = clientLevel->getChunkAt(x, z); +#ifdef SHARING_ENABLED + if (lc->sharingTilesAndData) { + // We are sharing - this is the last point we can tell the + // renderer + Minecraft::GetInstance() + ->levelRenderer->destroyedTileManager->destroyingTileAt( + clientLevel, x, y, z); + + // Don't need to ask the client to do this too + clientToUpdateRenderer = false; + } #endif - } - } - } + } + } + } bool changed = superDestroyBlock(x, y, z); - if (isCreative()) - { - std::shared_ptr tup = std::shared_ptr( new TileUpdatePacket(x, y, z, level) ); - // 4J - a bit of a hack here, but if we want to tell the client that it needs to inform the renderer of a block being destroyed, then send a block 255 instead of a 0. This is handled in ClientConnection::handleTileUpdate - if( tup->block == 0 ) - { - if( clientToUpdateRenderer ) tup->block = 255; - } - player->connection->send( tup ); - } - else - { - std::shared_ptr item = player->getSelectedItem(); - bool canDestroy = player->canDestroy(Tile::tiles[t]); - if (item != NULL) - { - item->mineBlock(level, t, x, y, z, player); - if (item->count == 0) - { - player->removeSelectedItem(); - } - } - if (changed && canDestroy) - { - Tile::tiles[t]->playerDestroy(level, player, x, y, z, data); - } - } + if (isCreative()) { + std::shared_ptr tup = + std::shared_ptr( + new TileUpdatePacket(x, y, z, level)); + // 4J - a bit of a hack here, but if we want to tell the client that it + // needs to inform the renderer of a block being destroyed, then send a + // block 255 instead of a 0. This is handled in + // ClientConnection::handleTileUpdate + if (tup->block == 0) { + if (clientToUpdateRenderer) tup->block = 255; + } + player->connection->send(tup); + } else { + std::shared_ptr item = player->getSelectedItem(); + bool canDestroy = player->canDestroy(Tile::tiles[t]); + if (item != NULL) { + item->mineBlock(level, t, x, y, z, player); + if (item->count == 0) { + player->removeSelectedItem(); + } + } + if (changed && canDestroy) { + Tile::tiles[t]->playerDestroy(level, player, x, y, z, data); + } + } return changed; - } -bool ServerPlayerGameMode::useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly) -{ - if(!player->isAllowedToUse(item)) return false; +bool ServerPlayerGameMode::useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, + bool bTestUseOnly) { + if (!player->isAllowedToUse(item)) return false; int oldCount = item->count; - int oldAux = item->getAuxValue(); + int oldAux = item->getAuxValue(); std::shared_ptr itemInstance = item->use(level, player); - if ((itemInstance != NULL && itemInstance != item) || (itemInstance != NULL && itemInstance->count != oldCount) || (itemInstance != NULL && itemInstance->getUseDuration() > 0)) - { + if ((itemInstance != NULL && itemInstance != item) || + (itemInstance != NULL && itemInstance->count != oldCount) || + (itemInstance != NULL && itemInstance->getUseDuration() > 0)) { player->inventory->items[player->inventory->selected] = itemInstance; - if (isCreative()) - { - itemInstance->count = oldCount; - itemInstance->setAuxValue(oldAux); - } - if (itemInstance->count == 0) - { + if (isCreative()) { + itemInstance->count = oldCount; + itemInstance->setAuxValue(oldAux); + } + if (itemInstance->count == 0) { player->inventory->items[player->inventory->selected] = nullptr; } return true; } return false; - } -bool ServerPlayerGameMode::useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly, bool *pbUsedItem) -{ - // 4J-PB - Adding a test only version to allow tooltips to be displayed - int t = level->getTile(x, y, z); - if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) - { - if(bTestUseOnOnly) - { - if (Tile::tiles[t]->TestUse()) return true; - } - else - { - if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ)) - { - if(m_gameRules != NULL) m_gameRules->onUseTile(t,x,y,z); - return true; - } - } - } - +bool ServerPlayerGameMode::useItemOn(std::shared_ptr player, + Level* level, + std::shared_ptr item, int x, + int y, int z, int face, float clickX, + float clickY, float clickZ, + bool bTestUseOnOnly, bool* pbUsedItem) { + // 4J-PB - Adding a test only version to allow tooltips to be displayed + int t = level->getTile(x, y, z); + if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) { + if (bTestUseOnOnly) { + if (Tile::tiles[t]->TestUse()) return true; + } else { + if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, + clickY, clickZ)) { + if (m_gameRules != NULL) m_gameRules->onUseTile(t, x, y, z); + return true; + } + } + } + if (item == NULL || !player->isAllowedToUse(item)) return false; - if (isCreative()) - { - int aux = item->getAuxValue(); - int count = item->count; - bool success = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ); - item->setAuxValue(aux); - item->count = count; - return success; - } - else - { - return item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnOnly); - } + if (isCreative()) { + int aux = item->getAuxValue(); + int count = item->count; + bool success = + item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ); + item->setAuxValue(aux); + item->count = count; + return success; + } else { + return item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, + bTestUseOnOnly); + } } -void ServerPlayerGameMode::setLevel(ServerLevel *newLevel) -{ - level = newLevel; -} +void ServerPlayerGameMode::setLevel(ServerLevel* newLevel) { level = newLevel; } // 4J Added -void ServerPlayerGameMode::setGameRules(GameRulesInstance *rules) -{ - if(m_gameRules != NULL) delete m_gameRules; - m_gameRules = rules; +void ServerPlayerGameMode::setGameRules(GameRulesInstance* rules) { + if (m_gameRules != NULL) delete m_gameRules; + m_gameRules = rules; } \ No newline at end of file diff --git a/Minecraft.Client/Player/ServerPlayerGameMode.h b/Minecraft.Client/Player/ServerPlayerGameMode.h index c590f11e8..74440c69a 100644 --- a/Minecraft.Client/Player/ServerPlayerGameMode.h +++ b/Minecraft.Client/Player/ServerPlayerGameMode.h @@ -6,17 +6,16 @@ class ServerLevel; class GameRulesInstance; class GameType; -class ServerPlayerGameMode -{ +class ServerPlayerGameMode { public: - Level *level; - std::shared_ptr player; + Level* level; + std::shared_ptr player; private: - GameType *gameModeForPlayer; + GameType* gameModeForPlayer; private: - bool isDestroyingBlock; + bool isDestroyingBlock; int destroyProgressStart; int xDestroyBlock, yDestroyBlock, zDestroyBlock; int gameTicks; @@ -24,24 +23,25 @@ private: bool hasDelayedDestroy; int delayedDestroyX, delayedDestroyY, delayedDestroyZ; int delayedTickStart; - int lastSentState; + int lastSentState; private: - // 4J Added - GameRulesInstance *m_gameRules; -public: - void setGameRules(GameRulesInstance *rules); - GameRulesInstance *getGameRules() { return m_gameRules; } + // 4J Added + GameRulesInstance* m_gameRules; public: - ServerPlayerGameMode(Level *level); - ~ServerPlayerGameMode(); + void setGameRules(GameRulesInstance* rules); + GameRulesInstance* getGameRules() { return m_gameRules; } - void setGameModeForPlayer(GameType *gameModeForPlayer); - GameType *getGameModeForPlayer(); - bool isSurvival(); - bool isCreative(); - void updateGameMode(GameType *gameType); +public: + ServerPlayerGameMode(Level* level); + ~ServerPlayerGameMode(); + + void setGameModeForPlayer(GameType* gameModeForPlayer); + GameType* getGameModeForPlayer(); + bool isSurvival(); + bool isCreative(); + void updateGameMode(GameType* gameType); void tick(); void startDestroyBlock(int x, int y, int z, int face); @@ -53,8 +53,12 @@ private: public: bool destroyBlock(int x, int y, int z); - bool useItem(std::shared_ptr player, Level *level, std::shared_ptr item, bool bTestUseOnly=false); - bool useItemOn(std::shared_ptr player, Level *level, std::shared_ptr item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false, bool *pbUsedItem=NULL); + bool useItem(std::shared_ptr player, Level* level, + std::shared_ptr item, bool bTestUseOnly = false); + bool useItemOn(std::shared_ptr player, Level* level, + std::shared_ptr item, int x, int y, int z, + int face, float clickX, float clickY, float clickZ, + bool bTestUseOnOnly = false, bool* pbUsedItem = NULL); - void setLevel(ServerLevel *newLevel); + void setLevel(ServerLevel* newLevel); }; \ No newline at end of file diff --git a/Minecraft.Client/Player/TrackedEntity.cpp b/Minecraft.Client/Player/TrackedEntity.cpp index fb10ea8d1..c6f58808b 100644 --- a/Minecraft.Client/Player/TrackedEntity.cpp +++ b/Minecraft.Client/Player/TrackedEntity.cpp @@ -20,19 +20,19 @@ #include "../Network/PlayerChunkMap.h" #ifndef __linux__ #include -#endif // __linux__ +#endif // __linux__ -TrackedEntity::TrackedEntity(std::shared_ptr e, int range, int updateInterval, bool trackDelta) -{ - // 4J added initialisers +TrackedEntity::TrackedEntity(std::shared_ptr e, int range, + int updateInterval, bool trackDelta) { + // 4J added initialisers xap = yap = zap = 0; tickCount = 0; - xpu = ypu = zpu = 0; + xpu = ypu = zpu = 0; updatedPlayerVisibility = false; teleportDelay = 0; - moved = false; - - this->e = e; + moved = false; + + this->e = e; this->range = range; this->updateInterval = updateInterval; this->trackDelta = trackDelta; @@ -43,16 +43,15 @@ TrackedEntity::TrackedEntity(std::shared_ptr e, int range, int updateInt yRotp = Mth::floor(e->yRot * 256 / 360); xRotp = Mth::floor(e->xRot * 256 / 360); - yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); + yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); } int c0a = 0, c0b = 0, c1a = 0, c1b = 0, c1c = 0, c2a = 0, c2b = 0; -void TrackedEntity::tick(EntityTracker *tracker, std::vector > *players) -{ +void TrackedEntity::tick(EntityTracker* tracker, + std::vector >* players) { moved = false; - if (!updatedPlayerVisibility || e->distanceToSqr(xpu, ypu, zpu) > 4 * 4) - { + if (!updatedPlayerVisibility || e->distanceToSqr(xpu, ypu, zpu) > 4 * 4) { xpu = e->x; ypu = e->y; zpu = e->z; @@ -61,870 +60,949 @@ void TrackedEntity::tick(EntityTracker *tracker, std::vectorriding) - { - wasRiding = e->riding; - broadcast(std::shared_ptr(new SetRidingPacket(e, e->riding))); - } - - // Moving forward special case for item frames - if (e->GetType()== eTYPE_ITEM_FRAME && tickCount % 10 == 0) - { - std::shared_ptr frame = std::dynamic_pointer_cast (e); - std::shared_ptr item = frame->getItem(); - - if (item != NULL && item->getItem()->id == Item::map_Id && !e->removed) - { - std::shared_ptr data = Item::map->getSavedData(item, e->level); - for (AUTO_VAR(it,players->begin() ); it != players->end(); ++it) - { - std::shared_ptr player = std::dynamic_pointer_cast(*it); - data->tickCarriedBy(player, item); - - if (!player->removed && player->connection && player->connection->countDelayedPackets() <= 5) - { - std::shared_ptr packet = Item::map->getUpdatePacket(item, e->level, player); - if (packet != NULL) player->connection->send(packet); - } - } - } - - std::shared_ptr entityData = e->getEntityData(); - if (entityData->isDirty()) - { - broadcastAndSend( std::shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false) ) ); - } - } - else - { - if(e->riding == NULL) - { - teleportDelay++; - if (tickCount++ % updateInterval == 0 || e->hasImpulse) - { - int xn = Mth::floor(this->e->x * 32.0); - int yn = Mth::floor(this->e->y * 32.0); - int zn = Mth::floor(this->e->z * 32.0); - int yRotn = Mth::floor(e->yRot * 256 / 360); - int xRotn = Mth::floor(e->xRot * 256 / 360); - - - int xa = xn - xp; - int ya = yn - yp; - int za = zn - zp; - - std::shared_ptr packet = nullptr; - - // 4J - this pos flag used to be set based on abs(xn) etc. but that just seems wrong - bool pos = abs(xa) >= TOLERANCE_LEVEL || abs(ya) >= TOLERANCE_LEVEL || abs(za) >= TOLERANCE_LEVEL; - // 4J - changed rotation to be generally sent as a delta as well as position - int yRota = yRotn - yRotp; - int xRota = xRotn - xRotp; - // Keep rotation deltas in +/- 180 degree range - while( yRota > 127 ) yRota -= 256; - while( yRota < -128 ) yRota += 256; - while( xRota > 127 ) xRota -= 256; - while( xRota < -128 ) xRota += 256; - - bool rot = abs(yRota) >= TOLERANCE_LEVEL || abs(xRota) >= TOLERANCE_LEVEL; - - if (xa < -128 || xa >= 128 || ya < -128 || ya >= 128 || za < -128 || za >= 128 - // 4J Stu - I fixed the initialisation of teleportDelay in the ctor, but we managed this far without out - // and would prefer not to have all the extra traffix so ignore it - // 4J Stu - Fix for #9579 - GAMEPLAY: Boats with a player in them slowly sink under the water over time, and with no player in them they float into the sky. - || (e->GetType() == eTYPE_BOAT && teleportDelay > 20 * 20) - ) - { - teleportDelay = 0; - packet = std::shared_ptr( new TeleportEntityPacket(e->entityId, xn, yn, zn, (uint8_t) yRotn, (uint8_t) xRotn) ); - // printf("%d: New teleport rot %d\n",e->entityId,yRotn); - yRotp = yRotn; - xRotp = xRotn; - } - else - { - if (pos && rot) - { - // 4J If the movement is small enough, and there's no xrot, then use the new smaller packets - if( ( xa >= -16 ) && ( xa <= 15 ) && - ( za >= -16 ) && ( za <= 15 ) && - ( ya >= -32 ) && ( ya <= 31 ) && - ( xRota == 0 )) - { - // Clamp rotations that are too big - if( yRota < -16 ) - { - yRota = -16; - yRotn = yRotp + yRota; - } - else if( yRota > 15 ) - { - yRota = 15; - yRotn = yRotp + yRota; - } - // 5 bits each for x & z, and 6 for y - packet = std::shared_ptr( new MoveEntityPacketSmall::PosRot(e->entityId, (char) xa, (char) ya, (char) za, (char) yRota, 0 ) ); - c0a++; - } - else - { - packet = std::shared_ptr( new MoveEntityPacket::PosRot(e->entityId, (char) xa, (char) ya, (char) za, (char) yRota, (char) xRota) ); - // printf("%d: New posrot %d + %d = %d\n",e->entityId,yRotp,yRota,yRotn); - c0b++; - } - } - else if (pos) - { - // 4J If the movement is small enough, then use the new smaller packets - if( ( xa >= -8 ) && ( xa <= 7 ) && - ( za >= -8 ) && ( za <= 7 ) && - ( ya >= -16 ) && ( ya <= 15 ) ) - { - // 4 bits each for x & z, and 5 for y - packet = std::shared_ptr( new MoveEntityPacketSmall::Pos(e->entityId, (char) xa, (char) ya, (char) za) ); - c1a++; - } - - else if( ( xa >= -16 ) && ( xa <= 15 ) && - ( za >= -16 ) && ( za <= 15 ) && - ( ya >= -32 ) && ( ya <= 31 ) ) - { - // use the packet with small packet with rotation if we can - 5 bits each for x & z, and 6 for y - still a byte less than the alternative - packet = std::shared_ptr( new MoveEntityPacketSmall::PosRot(e->entityId, (char) xa, (char) ya, (char) za, 0, 0 )); - c1b++; - } - else - { - packet = std::shared_ptr( new MoveEntityPacket::Pos(e->entityId, (char) xa, (char) ya, (char) za) ); - c1c++; - } - } - else if (rot) - { - // 4J If there's no x rotation, then use the new smaller packet type - if( xRota == 0 ) - { - // Clamp rotations that are too big - if( yRota < -16 ) - { - yRota = -16; - yRotn = yRotp + yRota; - } - else if( yRota > 15 ) - { - yRota = 15; - yRotn = yRotp + yRota; - } - packet = std::shared_ptr( new MoveEntityPacketSmall::Rot(e->entityId, (char) yRota, 0) ); - c2a++; - } - else - { - // printf("%d: New rot %d + %d = %d\n",e->entityId,yRotp,yRota,yRotn); - packet = std::shared_ptr( new MoveEntityPacket::Rot(e->entityId, (char) yRota, (char) xRota) ); - c2b++; - } - } - } - - if (trackDelta) - { - double xad = e->xd - xap; - double yad = e->yd - yap; - double zad = e->zd - zap; - - double max = 0.02; - - double diff = xad * xad + yad * yad + zad * zad; - - if (diff > max * max || (diff > 0 && e->xd == 0 && e->yd == 0 && e->zd == 0)) - { - xap = e->xd; - yap = e->yd; - zap = e->zd; - broadcast( std::shared_ptr( new SetEntityMotionPacket(e->entityId, xap, yap, zap) ) ); - } - - } - - if (packet != NULL) - { - broadcast(packet); - } - - std::shared_ptr entityData = e->getEntityData(); - - if (entityData->isDirty()) - { - broadcastAndSend( std::shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false) ) ); - } - - int yHeadRot = Mth::floor(e->getYHeadRot() * 256 / 360); - if (abs(yHeadRot - yHeadRotp) >= TOLERANCE_LEVEL) - { - broadcast(std::shared_ptr(new RotateHeadPacket(e->entityId, (uint8_t) yHeadRot))); - yHeadRotp = yHeadRot; - } - - if (pos) - { - xp = xn; - yp = yn; - zp = zn; - } - if (rot) - { - yRotp = yRotn; - xRotp = xRotn; - } - - // if( std::dynamic_pointer_cast(e) != NULL ) - // { - // printf("%d: %d + %d = %d (%f)\n",e->entityId,xRotp,xRota,xRotn,e->xRot); - // } - } - - } - else // 4J-JEV: Added: Mobs in minecarts weren't synching their invisibility. - { - std::shared_ptr entityData = e->getEntityData(); - if (entityData->isDirty()) - broadcastAndSend( std::shared_ptr( new SetEntityDataPacket(e->entityId, entityData, false) ) ); - } - e->hasImpulse = false; - } - - if (e->hurtMarked) - { - // broadcast(new AnimatePacket(e, AnimatePacket.HURT)); - broadcastAndSend( std::shared_ptr( new SetEntityMotionPacket(e) ) ); - e->hurtMarked = false; + if (wasRiding != e->riding) { + wasRiding = e->riding; + broadcast(std::shared_ptr( + new SetRidingPacket(e, e->riding))); } + // Moving forward special case for item frames + if (e->GetType() == eTYPE_ITEM_FRAME && tickCount % 10 == 0) { + std::shared_ptr frame = + std::dynamic_pointer_cast(e); + std::shared_ptr item = frame->getItem(); + + if (item != NULL && item->getItem()->id == Item::map_Id && + !e->removed) { + std::shared_ptr data = + Item::map->getSavedData(item, e->level); + for (AUTO_VAR(it, players->begin()); it != players->end(); ++it) { + std::shared_ptr player = + std::dynamic_pointer_cast(*it); + data->tickCarriedBy(player, item); + + if (!player->removed && player->connection && + player->connection->countDelayedPackets() <= 5) { + std::shared_ptr packet = + Item::map->getUpdatePacket(item, e->level, player); + if (packet != NULL) player->connection->send(packet); + } + } + } + + std::shared_ptr entityData = e->getEntityData(); + if (entityData->isDirty()) { + broadcastAndSend(std::shared_ptr( + new SetEntityDataPacket(e->entityId, entityData, false))); + } + } else { + if (e->riding == NULL) { + teleportDelay++; + if (tickCount++ % updateInterval == 0 || e->hasImpulse) { + int xn = Mth::floor(this->e->x * 32.0); + int yn = Mth::floor(this->e->y * 32.0); + int zn = Mth::floor(this->e->z * 32.0); + int yRotn = Mth::floor(e->yRot * 256 / 360); + int xRotn = Mth::floor(e->xRot * 256 / 360); + + int xa = xn - xp; + int ya = yn - yp; + int za = zn - zp; + + std::shared_ptr packet = nullptr; + + // 4J - this pos flag used to be set based on abs(xn) etc. but + // that just seems wrong + bool pos = abs(xa) >= TOLERANCE_LEVEL || + abs(ya) >= TOLERANCE_LEVEL || + abs(za) >= TOLERANCE_LEVEL; + // 4J - changed rotation to be generally sent as a delta as well + // as position + int yRota = yRotn - yRotp; + int xRota = xRotn - xRotp; + // Keep rotation deltas in +/- 180 degree range + while (yRota > 127) yRota -= 256; + while (yRota < -128) yRota += 256; + while (xRota > 127) xRota -= 256; + while (xRota < -128) xRota += 256; + + bool rot = abs(yRota) >= TOLERANCE_LEVEL || + abs(xRota) >= TOLERANCE_LEVEL; + + if (xa < -128 || xa >= 128 || ya < -128 || ya >= 128 || + za < -128 || + za >= 128 + // 4J Stu - I fixed the initialisation of teleportDelay in + // the ctor, but we managed this far without out and would + // prefer not to have all the extra traffix so ignore it 4J + // Stu - Fix for #9579 - GAMEPLAY: Boats with a player in + // them slowly sink under the water over time, and with no + // player in them they float into the sky. + || + (e->GetType() == eTYPE_BOAT && teleportDelay > 20 * 20)) { + teleportDelay = 0; + packet = std::shared_ptr( + new TeleportEntityPacket(e->entityId, xn, yn, zn, + (uint8_t)yRotn, + (uint8_t)xRotn)); + // printf("%d: New teleport rot + //%d\n",e->entityId,yRotn); + yRotp = yRotn; + xRotp = xRotn; + } else { + if (pos && rot) { + // 4J If the movement is small enough, and there's no + // xrot, then use the new smaller packets + if ((xa >= -16) && (xa <= 15) && (za >= -16) && + (za <= 15) && (ya >= -32) && (ya <= 31) && + (xRota == 0)) { + // Clamp rotations that are too big + if (yRota < -16) { + yRota = -16; + yRotn = yRotp + yRota; + } else if (yRota > 15) { + yRota = 15; + yRotn = yRotp + yRota; + } + // 5 bits each for x & z, and 6 for y + packet = std::shared_ptr( + new MoveEntityPacketSmall::PosRot( + e->entityId, (char)xa, (char)ya, (char)za, + (char)yRota, 0)); + c0a++; + } else { + packet = std::shared_ptr( + new MoveEntityPacket::PosRot( + e->entityId, (char)xa, (char)ya, (char)za, + (char)yRota, (char)xRota)); + // printf("%d: New + //posrot %d + %d = + //%d\n",e->entityId,yRotp,yRota,yRotn); + c0b++; + } + } else if (pos) { + // 4J If the movement is small enough, then use the new + // smaller packets + if ((xa >= -8) && (xa <= 7) && (za >= -8) && + (za <= 7) && (ya >= -16) && (ya <= 15)) { + // 4 bits each for x & z, and 5 for y + packet = std::shared_ptr( + new MoveEntityPacketSmall::Pos( + e->entityId, (char)xa, (char)ya, (char)za)); + c1a++; + } + + else if ((xa >= -16) && (xa <= 15) && (za >= -16) && + (za <= 15) && (ya >= -32) && (ya <= 31)) { + // use the packet with small packet with rotation if + // we can - 5 bits each for x & z, and 6 for y - + // still a byte less than the alternative + packet = std::shared_ptr( + new MoveEntityPacketSmall::PosRot( + e->entityId, (char)xa, (char)ya, (char)za, + 0, 0)); + c1b++; + } else { + packet = std::shared_ptr( + new MoveEntityPacket::Pos(e->entityId, (char)xa, + (char)ya, (char)za)); + c1c++; + } + } else if (rot) { + // 4J If there's no x rotation, then use the new smaller + // packet type + if (xRota == 0) { + // Clamp rotations that are too big + if (yRota < -16) { + yRota = -16; + yRotn = yRotp + yRota; + } else if (yRota > 15) { + yRota = 15; + yRotn = yRotp + yRota; + } + packet = std::shared_ptr( + new MoveEntityPacketSmall::Rot(e->entityId, + (char)yRota, 0)); + c2a++; + } else { + // printf("%d: New + //rot %d + %d = + //%d\n",e->entityId,yRotp,yRota,yRotn); + packet = std::shared_ptr( + new MoveEntityPacket::Rot( + e->entityId, (char)yRota, (char)xRota)); + c2b++; + } + } + } + + if (trackDelta) { + double xad = e->xd - xap; + double yad = e->yd - yap; + double zad = e->zd - zap; + + double max = 0.02; + + double diff = xad * xad + yad * yad + zad * zad; + + if (diff > max * max || + (diff > 0 && e->xd == 0 && e->yd == 0 && e->zd == 0)) { + xap = e->xd; + yap = e->yd; + zap = e->zd; + broadcast(std::shared_ptr( + new SetEntityMotionPacket(e->entityId, xap, yap, + zap))); + } + } + + if (packet != NULL) { + broadcast(packet); + } + + std::shared_ptr entityData = + e->getEntityData(); + + if (entityData->isDirty()) { + broadcastAndSend(std::shared_ptr( + new SetEntityDataPacket(e->entityId, entityData, + false))); + } + + int yHeadRot = Mth::floor(e->getYHeadRot() * 256 / 360); + if (abs(yHeadRot - yHeadRotp) >= TOLERANCE_LEVEL) { + broadcast(std::shared_ptr( + new RotateHeadPacket(e->entityId, (uint8_t)yHeadRot))); + yHeadRotp = yHeadRot; + } + + if (pos) { + xp = xn; + yp = yn; + zp = zn; + } + if (rot) { + yRotp = yRotn; + xRotp = xRotn; + } + + // if( std::dynamic_pointer_cast(e) + //!= NULL ) + // { + // printf("%d: %d + %d = %d + //(%f)\n",e->entityId,xRotp,xRota,xRotn,e->xRot); + // } + } + + } else // 4J-JEV: Added: Mobs in minecarts weren't synching their + // invisibility. + { + std::shared_ptr entityData = e->getEntityData(); + if (entityData->isDirty()) + broadcastAndSend(std::shared_ptr( + new SetEntityDataPacket(e->entityId, entityData, false))); + } + e->hasImpulse = false; + } + + if (e->hurtMarked) { + // broadcast(new AnimatePacket(e, AnimatePacket.HURT)); + broadcastAndSend(std::shared_ptr( + new SetEntityMotionPacket(e))); + e->hurtMarked = false; + } } -void TrackedEntity::broadcast(std::shared_ptr packet) -{ - if( Packet::canSendToAnyClient( packet ) ) - { - // 4J-PB - due to the knockback on a player being hit, we need to send to all players, but limit the network traffic here to players that have not already had it sent to their system - std::vector< std::shared_ptr > sentTo; +void TrackedEntity::broadcast(std::shared_ptr packet) { + if (Packet::canSendToAnyClient(packet)) { + // 4J-PB - due to the knockback on a player being hit, we need to send + // to all players, but limit the network traffic here to players that + // have not already had it sent to their system + std::vector > sentTo; - // 4J - don't send to a player we've already sent this data to that shares the same machine. - // EntityMotionPacket used to limit themselves to sending once to each machine - // by only sending to the primary player on each machine. This was causing trouble for split screen - // as only the primary player would get a knockback velocity. Now these packets can be sent to any - // player, but we try to restrict the network impact this has by not resending to the one machine + // 4J - don't send to a player we've already sent this data to that + // shares the same machine. EntityMotionPacket used to limit themselves + // to sending once to each machine by only sending to the primary player + // on each machine. This was causing trouble for split screen as only + // the primary player would get a knockback velocity. Now these packets + // can be sent to any player, but we try to restrict the network impact + // this has by not resending to the one machine - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) - { - std::shared_ptr player = *it; - bool dontSend = false; - if( sentTo.size() ) - { - INetworkPlayer *thisPlayer =player->connection->getNetworkPlayer(); - if( thisPlayer == NULL ) - { - dontSend = true; - } - else - { - for(unsigned int j = 0; j < sentTo.size(); j++ ) - { - std::shared_ptr player2 = sentTo[j]; - INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - dontSend = true; - // #ifdef _DEBUG - // std::shared_ptr emp= std::dynamic_pointer_cast (packet); - // if(emp!=NULL) - // { - // app.DebugPrintf("Not sending this SetEntityMotionPacket to player - it's already been sent to a player on their console\n"); - // } - // #endif - } - } - } - } - if( dontSend ) - { - continue; - } + for (AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++) { + std::shared_ptr player = *it; + bool dontSend = false; + if (sentTo.size()) { + INetworkPlayer* thisPlayer = + player->connection->getNetworkPlayer(); + if (thisPlayer == NULL) { + dontSend = true; + } else { + for (unsigned int j = 0; j < sentTo.size(); j++) { + std::shared_ptr player2 = sentTo[j]; + INetworkPlayer* otherPlayer = + player2->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + dontSend = true; + // #ifdef _DEBUG + // std::shared_ptr + // emp= + // std::dynamic_pointer_cast + // (packet); if(emp!=NULL) + // { + // app.DebugPrintf("Not + // sending this SetEntityMotionPacket to player - + // it's already been sent to a player on their + // console\n"); + // } + // #endif + } + } + } + } + if (dontSend) { + continue; + } + (*it)->connection->send(packet); + sentTo.push_back(player); + } + } else { + // This packet hasn't got canSendToAnyClient set, so just send to + // everyone here, and it - (*it)->connection->send(packet); - sentTo.push_back(player); - } - } - else - { - // This packet hasn't got canSendToAnyClient set, so just send to everyone here, and it - - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) - { - (*it)->connection->send(packet); - } - } + for (AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++) { + (*it)->connection->send(packet); + } + } } -void TrackedEntity::broadcastAndSend(std::shared_ptr packet) -{ - std::vector< std::shared_ptr > sentTo; +void TrackedEntity::broadcastAndSend(std::shared_ptr packet) { + std::vector > sentTo; broadcast(packet); - std::shared_ptr sp = std::dynamic_pointer_cast(e); - if (sp != NULL && sp->connection) - { + std::shared_ptr sp = + std::dynamic_pointer_cast(e); + if (sp != NULL && sp->connection) { sp->connection->send(packet); } } -void TrackedEntity::broadcastRemoved() -{ - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) - { - (*it)->entitiesToRemove.push_back(e->entityId); - } +void TrackedEntity::broadcastRemoved() { + for (AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++) { + (*it)->entitiesToRemove.push_back(e->entityId); + } } -void TrackedEntity::removePlayer(std::shared_ptr sp) -{ - AUTO_VAR(it, seenBy.find( sp )); - if( it != seenBy.end() ) - { - seenBy.erase( it ); - } +void TrackedEntity::removePlayer(std::shared_ptr sp) { + AUTO_VAR(it, seenBy.find(sp)); + if (it != seenBy.end()) { + seenBy.erase(it); + } } // 4J-JEV: Added for code reuse. -TrackedEntity::eVisibility TrackedEntity::isVisible(EntityTracker *tracker, std::shared_ptr sp, bool forRider) -{ - // 4J Stu - We call update players when the entity has moved more than a certain amount at the start of it's tick - // Before this call we set xpu, ypu and zpu to the entities new position, but xp,yp and zp are the old position until later in the tick. - // Therefore we should use the new position for visibility checks - double xd = sp->x - xpu; //xp / 32; - double zd = sp->z - zpu; //zp / 32; +TrackedEntity::eVisibility TrackedEntity::isVisible( + EntityTracker* tracker, std::shared_ptr sp, bool forRider) { + // 4J Stu - We call update players when the entity has moved more than a + // certain amount at the start of it's tick Before this call we set xpu, ypu + // and zpu to the entities new position, but xp,yp and zp are the old + // position until later in the tick. Therefore we should use the new + // position for visibility checks + double xd = sp->x - xpu; // xp / 32; + double zd = sp->z - zpu; // zp / 32; - int playersRange = range; - if( playersRange > TRACKED_ENTITY_MINIMUM_VIEW_DISTANCE ) - { - playersRange -= sp->getPlayerViewDistanceModifier(); - } + int playersRange = range; + if (playersRange > TRACKED_ENTITY_MINIMUM_VIEW_DISTANCE) { + playersRange -= sp->getPlayerViewDistanceModifier(); + } - bool bVisible = xd >= -playersRange && xd <= playersRange && zd >= -playersRange && zd <= playersRange; - bool canBeSeenBy = canBySeenBy(sp); + bool bVisible = xd >= -playersRange && xd <= playersRange && + zd >= -playersRange && zd <= playersRange; + bool canBeSeenBy = canBySeenBy(sp); - // 4J - added. Try and find other players who are in the same dimension as this one and on the same machine, and extend our visibility - // so things are consider visible to this player if they are near the other one. This is because we only send entity tracking info to - // players who canReceiveAllPackets(). - if(!bVisible) - { - MinecraftServer *server = MinecraftServer::getInstance(); - INetworkPlayer *thisPlayer = sp->connection->getNetworkPlayer(); - if( thisPlayer ) - { - for( unsigned int i = 0; i < server->getPlayers()->players.size(); i++ ) - { - // Consider extra players, but not if they are the entity we are tracking, or the player we've been passed as input, or in another dimension - std::shared_ptr ep = server->getPlayers()->players[i]; - if( ep == sp ) continue; - if( ep == e ) continue; - if( ep->dimension != sp->dimension ) continue; + // 4J - added. Try and find other players who are in the same dimension as + // this one and on the same machine, and extend our visibility so things are + // consider visible to this player if they are near the other one. This is + // because we only send entity tracking info to players who + // canReceiveAllPackets(). + if (!bVisible) { + MinecraftServer* server = MinecraftServer::getInstance(); + INetworkPlayer* thisPlayer = sp->connection->getNetworkPlayer(); + if (thisPlayer) { + for (unsigned int i = 0; i < server->getPlayers()->players.size(); + i++) { + // Consider extra players, but not if they are the entity we are + // tracking, or the player we've been passed as input, or in + // another dimension + std::shared_ptr ep = + server->getPlayers()->players[i]; + if (ep == sp) continue; + if (ep == e) continue; + if (ep->dimension != sp->dimension) continue; - INetworkPlayer * otherPlayer = ep->connection->getNetworkPlayer(); - if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) - { - // 4J Stu - We call update players when the entity has moved more than a certain amount at the start of it's tick - // Before this call we set xpu, ypu and zpu to the entities new position, but xp,yp and zp are the old position until later in the tick. - // Therefore we should use the new position for visibility checks - double xd = ep->x - xpu; //xp / 32; - double zd = ep->z - zpu; //zp / 32; - bVisible |= ( xd >= -playersRange && xd <= playersRange && zd >= -playersRange && zd <= playersRange ); - canBeSeenBy |= canBySeenBy(ep); - } - } - } - } + INetworkPlayer* otherPlayer = + ep->connection->getNetworkPlayer(); + if (otherPlayer != NULL && + thisPlayer->IsSameSystem(otherPlayer)) { + // 4J Stu - We call update players when the entity has moved + // more than a certain amount at the start of it's tick + // Before this call we set xpu, ypu and zpu to the entities + // new position, but xp,yp and zp are the old position until + // later in the tick. Therefore we should use the new + // position for visibility checks + double xd = ep->x - xpu; // xp / 32; + double zd = ep->z - zpu; // zp / 32; + bVisible |= (xd >= -playersRange && xd <= playersRange && + zd >= -playersRange && zd <= playersRange); + canBeSeenBy |= canBySeenBy(ep); + } + } + } + } - // 4J Stu - We need to ensure that we send the mount before the rider, so check that the player has been added to the seenBy list - if(forRider) - { - canBeSeenBy = canBeSeenBy && (seenBy.find(sp) != seenBy.end()); - } + // 4J Stu - We need to ensure that we send the mount before the rider, so + // check that the player has been added to the seenBy list + if (forRider) { + canBeSeenBy = canBeSeenBy && (seenBy.find(sp) != seenBy.end()); + } - // 4J-JEV: ADDED! An entities mount has to be visible before the entity visible, - // this is to ensure that the mount is already in the client's game when the rider is added. - if (canBeSeenBy && bVisible && e->riding != NULL) - { - return tracker->getTracker(e->riding)->isVisible(tracker, sp, true); - } - else if (canBeSeenBy && bVisible) return eVisibility_SeenAndVisible; - else if (bVisible) return eVisibility_IsVisible; - else return eVisibility_NotVisible; + // 4J-JEV: ADDED! An entities mount has to be visible before the entity + // visible, this is to ensure that the mount is already in the client's game + // when the rider is added. + if (canBeSeenBy && bVisible && e->riding != NULL) { + return tracker->getTracker(e->riding)->isVisible(tracker, sp, true); + } else if (canBeSeenBy && bVisible) + return eVisibility_SeenAndVisible; + else if (bVisible) + return eVisibility_IsVisible; + else + return eVisibility_NotVisible; } -void TrackedEntity::updatePlayer(EntityTracker *tracker, std::shared_ptr sp) -{ +void TrackedEntity::updatePlayer(EntityTracker* tracker, + std::shared_ptr sp) { if (sp == e) return; - eVisibility visibility = this->isVisible(tracker, sp); - - if ( visibility == eVisibility_SeenAndVisible - && seenBy.find(sp) == seenBy.end() ) - { + eVisibility visibility = this->isVisible(tracker, sp); + + if (visibility == eVisibility_SeenAndVisible && + seenBy.find(sp) == seenBy.end()) { seenBy.insert(sp); - std::shared_ptr packet = getAddEntityPacket(); + std::shared_ptr packet = getAddEntityPacket(); sp->connection->send(packet); - xap = e->xd; - yap = e->yd; - zap = e->zd; + xap = e->xd; + yap = e->yd; + zap = e->zd; - std::shared_ptr plr = std::dynamic_pointer_cast(e); - if (plr != NULL) - { - app.DebugPrintf( "TrackedEntity:: Player '%ls' is now visible to player '%ls', %s.\n", - plr->name.c_str(), sp->name.c_str(), - (e->riding==NULL?"not riding minecart":"in minecart") - ); - } - - // 4J Stu brought forward to fix when Item Frames - if (!e->getEntityData()->isEmpty() && !(std::dynamic_pointer_cast(packet))) - { - sp->connection->send(std::shared_ptr( new SetEntityDataPacket(e->entityId, e->getEntityData(), true))); - } - - if (this->trackDelta) - { - sp->connection->send( std::shared_ptr( new SetEntityMotionPacket(e->entityId, e->xd, e->yd, e->zd) ) ); + std::shared_ptr plr = std::dynamic_pointer_cast(e); + if (plr != NULL) { + app.DebugPrintf( + "TrackedEntity:: Player '%ls' is now visible to player '%ls', " + "%s.\n", + plr->name.c_str(), sp->name.c_str(), + (e->riding == NULL ? "not riding minecart" : "in minecart")); } - if (e->riding != NULL) - { - sp->connection->send(std::shared_ptr(new SetRidingPacket(e, e->riding))); - } + // 4J Stu brought forward to fix when Item Frames + if (!e->getEntityData()->isEmpty() && + !(std::dynamic_pointer_cast(packet))) { + sp->connection->send( + std::shared_ptr(new SetEntityDataPacket( + e->entityId, e->getEntityData(), true))); + } + + if (this->trackDelta) { + sp->connection->send(std::shared_ptr( + new SetEntityMotionPacket(e->entityId, e->xd, e->yd, e->zd))); + } + + if (e->riding != NULL) { + sp->connection->send(std::shared_ptr( + new SetRidingPacket(e, e->riding))); + } ItemInstanceArray equipped = e->getEquipmentSlots(); - if (equipped.data != NULL) - { - for (unsigned int i = 0; i < equipped.length; i++) - { - sp->connection->send( std::shared_ptr( new SetEquippedItemPacket(e->entityId, i, equipped[i]) ) ); + if (equipped.data != NULL) { + for (unsigned int i = 0; i < equipped.length; i++) { + sp->connection->send(std::shared_ptr( + new SetEquippedItemPacket(e->entityId, i, equipped[i]))); } } - if (std::dynamic_pointer_cast(e) != NULL) - { + if (std::dynamic_pointer_cast(e) != NULL) { std::shared_ptr spe = std::dynamic_pointer_cast(e); - if (spe->isSleeping()) - { - sp->connection->send( std::shared_ptr( new EntityActionAtPositionPacket(e, EntityActionAtPositionPacket::START_SLEEP, Mth::floor(e->x), Mth::floor(e->y), Mth::floor(e->z)) ) ); + if (spe->isSleeping()) { + sp->connection->send( + std::shared_ptr( + new EntityActionAtPositionPacket( + e, EntityActionAtPositionPacket::START_SLEEP, + Mth::floor(e->x), Mth::floor(e->y), + Mth::floor(e->z)))); } } - if (std::dynamic_pointer_cast(e) != NULL) - { - std::shared_ptr mob = std::dynamic_pointer_cast(e); - std::vector *activeEffects = mob->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; + if (std::dynamic_pointer_cast(e) != NULL) { + std::shared_ptr mob = std::dynamic_pointer_cast(e); + std::vector* activeEffects = + mob->getActiveEffects(); + for (AUTO_VAR(it, activeEffects->begin()); + it != activeEffects->end(); ++it) { + MobEffectInstance* effect = *it; - sp->connection->send(std::shared_ptr( new UpdateMobEffectPacket(e->entityId, effect) ) ); - } - delete activeEffects; - } - } - else if (visibility == eVisibility_NotVisible) - { - AUTO_VAR(it, seenBy.find(sp)); - if (it != seenBy.end()) - { + sp->connection->send(std::shared_ptr( + new UpdateMobEffectPacket(e->entityId, effect))); + } + delete activeEffects; + } + } else if (visibility == eVisibility_NotVisible) { + AUTO_VAR(it, seenBy.find(sp)); + if (it != seenBy.end()) { seenBy.erase(it); sp->entitiesToRemove.push_back(e->entityId); } } - } -bool TrackedEntity::canBySeenBy(std::shared_ptr player) -{ - // 4J - for some reason this isn't currently working, and is causing players to not appear until we are really close to them. Not sure - // what the conflict is between the java & our version, but removing for now as it is causing issues and we shouldn't *really* need it - // TODO - investigate further +bool TrackedEntity::canBySeenBy(std::shared_ptr player) { + // 4J - for some reason this isn't currently working, and is causing players + // to not appear until we are really close to them. Not sure what the + // conflict is between the java & our version, but removing for now as it is + // causing issues and we shouldn't *really* need it + // TODO - investigate further - return true; -// return player->getLevel()->getChunkMap()->isPlayerIn(player, e->xChunk, e->zChunk); + return true; + // return player->getLevel()->getChunkMap()->isPlayerIn(player, e->xChunk, + //e->zChunk); } -void TrackedEntity::updatePlayers(EntityTracker *tracker, std::vector > *players) -{ - for (unsigned int i = 0; i < players->size(); i++) - { - updatePlayer(tracker, std::dynamic_pointer_cast( players->at(i) ) ); +void TrackedEntity::updatePlayers( + EntityTracker* tracker, std::vector >* players) { + for (unsigned int i = 0; i < players->size(); i++) { + updatePlayer(tracker, + std::dynamic_pointer_cast(players->at(i))); } } -std::shared_ptr TrackedEntity::getAddEntityPacket() -{ - if (e->removed) - { - app.DebugPrintf("Fetching addPacket for removed entity - %ls\n", e->getAName().c_str()); - } - - // 4J-PB - replacing with a switch, rather than tons of ifs - if (std::dynamic_pointer_cast(e) != NULL) - { - yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp) ); - } - - switch(e->GetType()) - { - case eTYPE_ITEMENTITY: - { - std::shared_ptr packet = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ITEM, 1, yRotp, xRotp, xp, yp, zp) ); - return packet; - } - break; - case eTYPE_SERVERPLAYER: - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - PlayerUID xuid = INVALID_XUID; - PlayerUID OnlineXuid = INVALID_XUID; - if( player != NULL ) - { - xuid = player->getXuid(); - OnlineXuid = player->getOnlineXuid(); - } - // 4J Added yHeadRotp param to fix #102563 - TU12: Content: Gameplay: When one of the Players is idle for a few minutes his head turns 180 degrees. - return std::shared_ptr( new AddPlayerPacket(std::dynamic_pointer_cast(e), xuid, OnlineXuid, xp, yp, zp, yRotp, xRotp, yHeadRotp ) ); - } - break; - case eTYPE_MINECART: - { - std::shared_ptr minecart = std::dynamic_pointer_cast(e); - if (minecart->type == Minecart::RIDEABLE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::CHEST) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_CHEST, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::FURNACE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_FURNACE, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_BOAT: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_ENDERDRAGON: - { - yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp, yHeadRotp ) ); - } - break; - case eTYPE_FISHINGHOOK: - { - std::shared_ptr owner = std::dynamic_pointer_cast(e)->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FISH_HOOK, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_ARROW: - { - std::shared_ptr owner = (std::dynamic_pointer_cast(e))->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ARROW, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_SNOWBALL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_THROWNPOTION: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_POTION, ((std::dynamic_pointer_cast(e))->getPotionValue()), yRotp, xRotp, xp, yp, zp)); - } - break; - case eTYPE_THROWNEXPBOTTLE: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_THROWNENDERPEARL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_EYEOFENDERSIGNAL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_SMALL_FIREBALL: - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = nullptr; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - break; - case eTYPE_DRAGON_FIREBALL: - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = nullptr; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::DRAGON_FIRE_BALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::DRAGON_FIRE_BALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - break; - case eTYPE_FIREBALL: - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = nullptr; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - break; - case eTYPE_THROWNEGG: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_PRIMEDTNT: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_ENDER_CRYSTAL: - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_FALLINGTILE: - { - std::shared_ptr ft = std::dynamic_pointer_cast(e); - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING, ft->tile | (ft->data << 16), yRotp, xRotp, xp, yp, zp) ); - } - break; - case eTYPE_PAINTING: - { - return std::shared_ptr( new AddPaintingPacket(std::dynamic_pointer_cast(e)) ); - } - break; - case eTYPE_ITEM_FRAME: - { - std::shared_ptr frame = std::dynamic_pointer_cast(e); - { - - int ix= (int)frame->xTile; - int iy= (int)frame->yTile; - int iz= (int)frame->zTile; - app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); - } - - std::shared_ptr packet = std::shared_ptr(new AddEntityPacket(e, AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp)); - packet->x = Mth::floor(frame->xTile * 32.0f); - packet->y = Mth::floor(frame->yTile * 32.0f); - packet->z = Mth::floor(frame->zTile * 32.0f); - return packet; - } - break; - case eTYPE_EXPERIENCEORB: - { - return std::shared_ptr( new AddExperienceOrbPacket(std::dynamic_pointer_cast(e)) ); - } - break; - default: - assert(false); - break; - } -/* - if (e->GetType() == eTYPE_ITEMENTITY) - { - std::shared_ptr itemEntity = std::dynamic_pointer_cast(e); - std::shared_ptr packet = std::shared_ptr( new AddItemEntityPacket(itemEntity, xp, yp, zp) ); - itemEntity->x = packet->x / 32.0; - itemEntity->y = packet->y / 32.0; - itemEntity->z = packet->z / 32.0; - return packet; +std::shared_ptr TrackedEntity::getAddEntityPacket() { + if (e->removed) { + app.DebugPrintf("Fetching addPacket for removed entity - %ls\n", + e->getAName().c_str()); } - if (e->GetType() == eTYPE_SERVERPLAYER ) - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - XUID xuid = INVALID_XUID; - XUID OnlineXuid = INVALID_XUID; - if( player != NULL ) - { - xuid = player->getXuid(); - OnlineXuid = player->getOnlineXuid(); - } - return std::shared_ptr( new AddPlayerPacket(std::dynamic_pointer_cast(e), xuid, OnlineXuid, xp, yp, zp, yRotp, xRotp ) ); + // 4J-PB - replacing with a switch, rather than tons of ifs + if (std::dynamic_pointer_cast(e) != NULL) { + yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); + return std::shared_ptr( + new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, + xp, yp, zp, yHeadRotp)); } - if (e->GetType() == eTYPE_MINECART) - { - std::shared_ptr minecart = std::dynamic_pointer_cast(e); - if (minecart->type == Minecart::RIDEABLE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::CHEST) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_CHEST, yRotp, xRotp, xp, yp, zp) ); - if (minecart->type == Minecart::FURNACE) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::MINECART_FURNACE, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_BOAT) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp) ); - } - if (std::dynamic_pointer_cast(e) != NULL) - { - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_ENDERDRAGON) - { - return std::shared_ptr( new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp ) ); - } - if (e->GetType() == eTYPE_FISHINGHOOK) - { - std::shared_ptr owner = std::dynamic_pointer_cast(e)->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FISH_HOOK, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_ARROW) - { - std::shared_ptr owner = (std::dynamic_pointer_cast(e))->owner; - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ARROW, owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_SNOWBALL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_THROWNPOTION) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_POTION, ((std::dynamic_pointer_cast(e))->getPotionValue()), yRotp, xRotp, xp, yp, zp)); - } - if (e->GetType() == eTYPE_THROWNEXPBOTTLE) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_THROWNENDERPEARL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_EYEOFENDERSIGNAL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_SMALL_FIREBALL) - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = NULL; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - if (e->GetType() == eTYPE_FIREBALL) - { - std::shared_ptr fb = std::dynamic_pointer_cast(e); - std::shared_ptr aep = NULL; - if (fb->owner != NULL) - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, xRotp, xp, yp, zp) ); - } - else - { - aep = std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, zp) ); - } - aep->xa = (int) (fb->xPower * 8000); - aep->ya = (int) (fb->yPower * 8000); - aep->za = (int) (fb->zPower * 8000); - return aep; - } - if (e->GetType() == eTYPE_THROWNEGG) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_PRIMEDTNT) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_ENDER_CRYSTAL) - { - return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_FALLINGTILE) - { - std::shared_ptr ft = std::dynamic_pointer_cast(e); - if (ft->tile == Tile::sand_Id) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING_SAND, yRotp, xRotp, xp, yp, zp) ); - if (ft->tile == Tile::gravel_Id) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING_GRAVEL, yRotp, xRotp, xp, yp, zp) ); - if (ft->tile == Tile::dragonEgg_Id) return std::shared_ptr( new AddEntityPacket(e, AddEntityPacket::FALLING_EGG, yRotp, xRotp, xp, yp, zp) ); - } - if (e->GetType() == eTYPE_PAINTING) - { - return std::shared_ptr( new AddPaintingPacket(std::dynamic_pointer_cast(e)) ); - } - if (e->GetType() == eTYPE_ITEM_FRAME) - { - std::shared_ptr frame = std::dynamic_pointer_cast(e); - { - int ix= (int)frame->xTile; - int iy= (int)frame->yTile; - int iz= (int)frame->zTile; - app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); - } + switch (e->GetType()) { + case eTYPE_ITEMENTITY: { + std::shared_ptr packet = + std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::ITEM, 1, yRotp, xRotp, xp, yp, zp)); + return packet; + } break; + case eTYPE_SERVERPLAYER: { + std::shared_ptr player = + std::dynamic_pointer_cast(e); + PlayerUID xuid = INVALID_XUID; + PlayerUID OnlineXuid = INVALID_XUID; + if (player != NULL) { + xuid = player->getXuid(); + OnlineXuid = player->getOnlineXuid(); + } + // 4J Added yHeadRotp param to fix #102563 - TU12: Content: + // Gameplay: When one of the Players is idle for a few minutes his + // head turns 180 degrees. + return std::shared_ptr(new AddPlayerPacket( + std::dynamic_pointer_cast(e), xuid, OnlineXuid, xp, yp, + zp, yRotp, xRotp, yHeadRotp)); + } break; + case eTYPE_MINECART: { + std::shared_ptr minecart = + std::dynamic_pointer_cast(e); + if (minecart->type == Minecart::RIDEABLE) + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, + yRotp, xRotp, xp, yp, zp)); + if (minecart->type == Minecart::CHEST) + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::MINECART_CHEST, + yRotp, xRotp, xp, yp, zp)); + if (minecart->type == Minecart::FURNACE) + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::MINECART_FURNACE, + yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_BOAT: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_ENDERDRAGON: { + yHeadRotp = Mth::floor(e->getYHeadRot() * 256 / 360); + return std::shared_ptr( + new AddMobPacket(std::dynamic_pointer_cast(e), yRotp, + xRotp, xp, yp, zp, yHeadRotp)); + } break; + case eTYPE_FISHINGHOOK: { + std::shared_ptr owner = + std::dynamic_pointer_cast(e)->owner; + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FISH_HOOK, + owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, + yp, zp)); + } break; + case eTYPE_ARROW: { + std::shared_ptr owner = + (std::dynamic_pointer_cast(e))->owner; + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::ARROW, + owner != NULL ? owner->entityId : e->entityId, yRotp, xRotp, xp, + yp, zp)); + } break; + case eTYPE_SNOWBALL: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_THROWNPOTION: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::THROWN_POTION, + ((std::dynamic_pointer_cast(e)) + ->getPotionValue()), + yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_THROWNEXPBOTTLE: { + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, + xRotp, xp, yp, zp)); + } break; + case eTYPE_THROWNENDERPEARL: { + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, + yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_EYEOFENDERSIGNAL: { + return std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, + xRotp, xp, yp, zp)); + } break; + case eTYPE_SMALL_FIREBALL: { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = nullptr; + if (fb->owner != NULL) { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, + yRotp, xRotp, xp, yp, zp)); + } else { + aep = std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, + yRotp, xRotp, xp, yp, zp)); + } + aep->xa = (int)(fb->xPower * 8000); + aep->ya = (int)(fb->yPower * 8000); + aep->za = (int)(fb->zPower * 8000); + return aep; + } break; + case eTYPE_DRAGON_FIREBALL: { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = nullptr; + if (fb->owner != NULL) { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::DRAGON_FIRE_BALL, fb->owner->entityId, + yRotp, xRotp, xp, yp, zp)); + } else { + aep = std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::DRAGON_FIRE_BALL, 0, + yRotp, xRotp, xp, yp, zp)); + } + aep->xa = (int)(fb->xPower * 8000); + aep->ya = (int)(fb->yPower * 8000); + aep->za = (int)(fb->zPower * 8000); + return aep; + } break; + case eTYPE_FIREBALL: { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = nullptr; + if (fb->owner != NULL) { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, + xRotp, xp, yp, zp)); + } else { + aep = std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, zp)); + } + aep->xa = (int)(fb->xPower * 8000); + aep->ya = (int)(fb->yPower * 8000); + aep->za = (int)(fb->zPower * 8000); + return aep; + } break; + case eTYPE_THROWNEGG: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_PRIMEDTNT: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_ENDER_CRYSTAL: { + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, zp)); + } break; + case eTYPE_FALLINGTILE: { + std::shared_ptr ft = + std::dynamic_pointer_cast(e); + return std::shared_ptr(new AddEntityPacket( + e, AddEntityPacket::FALLING, ft->tile | (ft->data << 16), yRotp, + xRotp, xp, yp, zp)); + } break; + case eTYPE_PAINTING: { + return std::shared_ptr( + new AddPaintingPacket(std::dynamic_pointer_cast(e))); + } break; + case eTYPE_ITEM_FRAME: { + std::shared_ptr frame = + std::dynamic_pointer_cast(e); + { + int ix = (int)frame->xTile; + int iy = (int)frame->yTile; + int iz = (int)frame->zTile; + app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n", ix, iy, iz); + } - std::shared_ptr packet = std::shared_ptr(new AddEntityPacket(e, AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp)); - packet->x = Mth::floor(frame->xTile * 32.0f); - packet->y = Mth::floor(frame->yTile * 32.0f); - packet->z = Mth::floor(frame->zTile * 32.0f); - return packet; - } - if (e->GetType() == eTYPE_EXPERIENCEORB) - { - return std::shared_ptr( new AddExperienceOrbPacket(std::dynamic_pointer_cast(e)) ); + std::shared_ptr packet = + std::shared_ptr( + new AddEntityPacket(e, AddEntityPacket::ITEM_FRAME, + frame->dir, yRotp, xRotp, xp, yp, zp)); + packet->x = Mth::floor(frame->xTile * 32.0f); + packet->y = Mth::floor(frame->yTile * 32.0f); + packet->z = Mth::floor(frame->zTile * 32.0f); + return packet; + } break; + case eTYPE_EXPERIENCEORB: { + return std::shared_ptr( + new AddExperienceOrbPacket( + std::dynamic_pointer_cast(e))); + } break; + default: + assert(false); + break; } - assert(false); - */ - return nullptr; + /* + if (e->GetType() == eTYPE_ITEMENTITY) + { + std::shared_ptr itemEntity = + std::dynamic_pointer_cast(e); + std::shared_ptr packet = + std::shared_ptr( new AddItemEntityPacket(itemEntity, + xp, yp, zp) ); itemEntity->x = packet->x / 32.0; itemEntity->y = + packet->y / 32.0; itemEntity->z = packet->z / 32.0; return packet; + } + + if (e->GetType() == eTYPE_SERVERPLAYER ) + { + std::shared_ptr player = + std::dynamic_pointer_cast(e); XUID xuid = INVALID_XUID; + XUID OnlineXuid = INVALID_XUID; + if( player != NULL ) + { + xuid = player->getXuid(); + OnlineXuid = player->getOnlineXuid(); + } + return std::shared_ptr( new + AddPlayerPacket(std::dynamic_pointer_cast(e), xuid, OnlineXuid, + xp, yp, zp, yRotp, xRotp ) ); + } + if (e->GetType() == eTYPE_MINECART) + { + std::shared_ptr minecart = + std::dynamic_pointer_cast(e); if (minecart->type == + Minecart::RIDEABLE) return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::MINECART_RIDEABLE, yRotp, xRotp, xp, + yp, zp) ); if (minecart->type == Minecart::CHEST) return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::MINECART_CHEST, yRotp, xRotp, xp, yp, zp) ); if + (minecart->type == Minecart::FURNACE) return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::MINECART_FURNACE, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_BOAT) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::BOAT, yRotp, xRotp, xp, yp, zp) ); + } + if (std::dynamic_pointer_cast(e) != NULL) + { + return std::shared_ptr( new + AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp) + ); + } + if (e->GetType() == eTYPE_ENDERDRAGON) + { + return std::shared_ptr( new + AddMobPacket(std::dynamic_pointer_cast(e), yRotp, xRotp, xp, yp, zp + ) ); + } + if (e->GetType() == eTYPE_FISHINGHOOK) + { + std::shared_ptr owner = + std::dynamic_pointer_cast(e)->owner; return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::FISH_HOOK, owner != NULL ? owner->entityId : + e->entityId, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_ARROW) + { + std::shared_ptr owner = + (std::dynamic_pointer_cast(e))->owner; return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::ARROW, owner != NULL ? owner->entityId : e->entityId, + yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_SNOWBALL) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::SNOWBALL, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_THROWNPOTION) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::THROWN_POTION, + ((std::dynamic_pointer_cast(e))->getPotionValue()), yRotp, + xRotp, xp, yp, zp)); + } + if (e->GetType() == eTYPE_THROWNEXPBOTTLE) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::THROWN_EXPBOTTLE, yRotp, xRotp, xp, + yp, zp) ); + } + if (e->GetType() == eTYPE_THROWNENDERPEARL) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::THROWN_ENDERPEARL, yRotp, xRotp, xp, + yp, zp) ); + } + if (e->GetType() == eTYPE_EYEOFENDERSIGNAL) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::EYEOFENDERSIGNAL, yRotp, xRotp, xp, + yp, zp) ); + } + if (e->GetType() == eTYPE_SMALL_FIREBALL) + { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); + std::shared_ptr aep = NULL; + if (fb->owner != NULL) + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, fb->owner->entityId, + yRotp, xRotp, xp, yp, zp) ); + } + else + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::SMALL_FIREBALL, 0, yRotp, xRotp, xp, + yp, zp) ); + } + aep->xa = (int) (fb->xPower * 8000); + aep->ya = (int) (fb->yPower * 8000); + aep->za = (int) (fb->zPower * 8000); + return aep; + } + if (e->GetType() == eTYPE_FIREBALL) + { + std::shared_ptr fb = + std::dynamic_pointer_cast(e); std::shared_ptr + aep = NULL; if (fb->owner != NULL) + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::FIREBALL, fb->owner->entityId, yRotp, + xRotp, xp, yp, zp) ); + } + else + { + aep = std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::FIREBALL, 0, yRotp, xRotp, xp, yp, + zp) ); + } + aep->xa = (int) (fb->xPower * 8000); + aep->ya = (int) (fb->yPower * 8000); + aep->za = (int) (fb->zPower * 8000); + return aep; + } + if (e->GetType() == eTYPE_THROWNEGG) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::EGG, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_PRIMEDTNT) + { + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::PRIMED_TNT, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_ENDER_CRYSTAL) + { + return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::ENDER_CRYSTAL, yRotp, xRotp, xp, yp, + zp) ); + } + if (e->GetType() == eTYPE_FALLINGTILE) + { + std::shared_ptr ft = + std::dynamic_pointer_cast(e); if (ft->tile == Tile::sand_Id) + return std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::FALLING_SAND, yRotp, xRotp, xp, yp, zp) ); if (ft->tile + == Tile::gravel_Id) return std::shared_ptr( new + AddEntityPacket(e, AddEntityPacket::FALLING_GRAVEL, yRotp, xRotp, xp, yp, + zp) ); if (ft->tile == Tile::dragonEgg_Id) return + std::shared_ptr( new AddEntityPacket(e, + AddEntityPacket::FALLING_EGG, yRotp, xRotp, xp, yp, zp) ); + } + if (e->GetType() == eTYPE_PAINTING) + { + return std::shared_ptr( new + AddPaintingPacket(std::dynamic_pointer_cast(e)) ); + } + if (e->GetType() == eTYPE_ITEM_FRAME) + { + std::shared_ptr frame = + std::dynamic_pointer_cast(e); + { + + int ix= (int)frame->xTile; + int iy= (int)frame->yTile; + int iz= (int)frame->zTile; + app.DebugPrintf("eTYPE_ITEM_FRAME xyz %d,%d,%d\n",ix,iy,iz); + } + + std::shared_ptr packet = + std::shared_ptr(new AddEntityPacket(e, + AddEntityPacket::ITEM_FRAME, frame->dir, yRotp, xRotp, xp, yp, zp)); + packet->x = Mth::floor(frame->xTile * 32.0f); + packet->y = Mth::floor(frame->yTile * 32.0f); + packet->z = Mth::floor(frame->zTile * 32.0f); + return packet; + } + if (e->GetType() == eTYPE_EXPERIENCEORB) + { + return std::shared_ptr( new + AddExperienceOrbPacket(std::dynamic_pointer_cast(e)) ); + } + assert(false); + */ + return nullptr; } -void TrackedEntity::clear(std::shared_ptr sp) -{ - AUTO_VAR(it, seenBy.find(sp)); - if (it != seenBy.end()) - { +void TrackedEntity::clear(std::shared_ptr sp) { + AUTO_VAR(it, seenBy.find(sp)); + if (it != seenBy.end()) { seenBy.erase(it); sp->entitiesToRemove.push_back(e->entityId); } diff --git a/Minecraft.Client/Player/TrackedEntity.h b/Minecraft.Client/Player/TrackedEntity.h index 70df9da3e..4a879eb03 100644 --- a/Minecraft.Client/Player/TrackedEntity.h +++ b/Minecraft.Client/Player/TrackedEntity.h @@ -1,21 +1,19 @@ #pragma once class Entity; -//class ServerPlayer; +// class ServerPlayer; #include "ServerPlayer.h" class Packet; - class EntityTracker; #define TRACKED_ENTITY_MINIMUM_VIEW_DISTANCE 4 -class TrackedEntity -{ +class TrackedEntity { private: - static const int TOLERANCE_LEVEL = 4; + static const int TOLERANCE_LEVEL = 4; public: - std::shared_ptr e; + std::shared_ptr e; int range, updateInterval; int xp, yp, zp, yRotp, xRotp, yHeadRotp; @@ -23,43 +21,51 @@ public: int tickCount; private: - double xpu, ypu, zpu; + double xpu, ypu, zpu; bool updatedPlayerVisibility; bool trackDelta; int teleportDelay; - std::shared_ptr wasRiding; + std::shared_ptr wasRiding; public: - bool moved; + bool moved; - std::unordered_set , PlayerKeyHash, PlayerKeyEq > seenBy; + std::unordered_set, PlayerKeyHash, + PlayerKeyEq> + seenBy; - TrackedEntity(std::shared_ptr e, int range, int updateInterval, bool trackDelta); + TrackedEntity(std::shared_ptr e, int range, int updateInterval, + bool trackDelta); - void tick(EntityTracker *tracker, std::vector > *players); + void tick(EntityTracker* tracker, + std::vector >* players); void broadcast(std::shared_ptr packet); void broadcastAndSend(std::shared_ptr packet); void broadcastRemoved(); void removePlayer(std::shared_ptr sp); private: - bool canBySeenBy(std::shared_ptr player); + bool canBySeenBy(std::shared_ptr player); - enum eVisibility - { - eVisibility_NotVisible = 0, - eVisibility_IsVisible = 1, - eVisibility_SeenAndVisible = 2, - }; + enum eVisibility { + eVisibility_NotVisible = 0, + eVisibility_IsVisible = 1, + eVisibility_SeenAndVisible = 2, + }; + + eVisibility isVisible(EntityTracker* tracker, + std::shared_ptr sp, + bool forRider = false); // 4J Added forRider - eVisibility isVisible(EntityTracker *tracker, std::shared_ptr sp, bool forRider = false); // 4J Added forRider - public: - void updatePlayer(EntityTracker *tracker, std::shared_ptr sp); - void updatePlayers(EntityTracker *tracker, std::vector > *players); + void updatePlayer(EntityTracker* tracker, std::shared_ptr sp); + void updatePlayers(EntityTracker* tracker, + std::vector >* players); + private: - void sendEntityData(std::shared_ptr conn); - std::shared_ptr getAddEntityPacket(); + void sendEntityData(std::shared_ptr conn); + std::shared_ptr getAddEntityPacket(); + public: void clear(std::shared_ptr sp); }; diff --git a/Minecraft.Client/Player/User.cpp b/Minecraft.Client/Player/User.cpp index 514070b54..3c5ac9fe0 100644 --- a/Minecraft.Client/Player/User.cpp +++ b/Minecraft.Client/Player/User.cpp @@ -2,10 +2,9 @@ #include "User.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -std::vector User::allowedTiles; +std::vector User::allowedTiles; -void User::staticCtor() -{ +void User::staticCtor() { allowedTiles.push_back(Tile::rock); allowedTiles.push_back(Tile::stoneBrick); allowedTiles.push_back(Tile::redBrick); @@ -38,8 +37,7 @@ void User::staticCtor() allowedTiles.push_back(Tile::obsidian); } -User::User(const std::wstring& name, const std::wstring& sessionId) -{ +User::User(const std::wstring& name, const std::wstring& sessionId) { this->name = name; this->sessionId = sessionId; } diff --git a/Minecraft.Client/Player/User.h b/Minecraft.Client/Player/User.h index 7650b7cc2..8ab308bd6 100644 --- a/Minecraft.Client/Player/User.h +++ b/Minecraft.Client/Player/User.h @@ -1,14 +1,12 @@ #pragma once - -class User -{ +class User { public: - static std::vector allowedTiles; - static void staticCtor(); - std::wstring name; - std::wstring sessionId; - std::wstring mpPassword; + static std::vector allowedTiles; + static void staticCtor(); + std::wstring name; + std::wstring sessionId; + std::wstring mpPassword; - User(const std::wstring& name, const std::wstring& sessionId); + User(const std::wstring& name, const std::wstring& sessionId); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Camera.cpp b/Minecraft.Client/Rendering/Camera.cpp index 8a2338f1d..e085cf06c 100644 --- a/Minecraft.Client/Rendering/Camera.cpp +++ b/Minecraft.Client/Rendering/Camera.cpp @@ -10,10 +10,10 @@ float Camera::xPlayerOffs = 0.0f; float Camera::yPlayerOffs = 0.0f; float Camera::zPlayerOffs = 0.0f; -//IntBuffer *Camera::viewport = MemoryTracker::createIntBuffer(16); -FloatBuffer *Camera::modelview = MemoryTracker::createFloatBuffer(16); -FloatBuffer *Camera::projection = MemoryTracker::createFloatBuffer(16); -//FloatBuffer *Camera::position = MemoryTracker::createFloatBuffer(3); +// IntBuffer *Camera::viewport = MemoryTracker::createIntBuffer(16); +FloatBuffer* Camera::modelview = MemoryTracker::createFloatBuffer(16); +FloatBuffer* Camera::projection = MemoryTracker::createFloatBuffer(16); +// FloatBuffer *Camera::position = MemoryTracker::createFloatBuffer(3); float Camera::xa = 0.0f; float Camera::ya = 0.0f; @@ -21,58 +21,59 @@ float Camera::za = 0.0f; float Camera::xa2 = 0.0f; float Camera::za2 = 0.0f; -void Camera::prepare(std::shared_ptr player, bool mirror) -{ +void Camera::prepare(std::shared_ptr player, bool mirror) { glGetFloat(GL_MODELVIEW_MATRIX, modelview); glGetFloat(GL_PROJECTION_MATRIX, projection); - /* Original java code for reference - glGetInteger(GL_VIEWPORT, viewport); + /* Original java code for reference +glGetInteger(GL_VIEWPORT, viewport); - float x = (viewport.get(0) + viewport.get(2)) / 2; - float y = (viewport.get(1) + viewport.get(3)) / 2; - gluUnProject(x, y, 0, modelview, projection, viewport, position); +float x = (viewport.get(0) + viewport.get(2)) / 2; +float y = (viewport.get(1) + viewport.get(3)) / 2; +gluUnProject(x, y, 0, modelview, projection, viewport, position); - xPlayerOffs = position->get(0); - yPlayerOffs = position->get(1); - zPlayerOffs = position->get(2); - */ +xPlayerOffs = position->get(0); +yPlayerOffs = position->get(1); +zPlayerOffs = position->get(2); + */ - // Xbox conversion here... note that we don't bother getting the viewport as this is just working out how to get a (0,0,0) point in clip space to pass into the inverted - // combined model/view/projection matrix, so we just need to get this matrix and get its translation as an equivalent. - XMMATRIX _modelview, _proj, _final, _invert; - XMVECTOR _det; - XMFLOAT4 trans; + // Xbox conversion here... note that we don't bother getting the viewport as + // this is just working out how to get a (0,0,0) point in clip space to pass + // into the inverted combined model/view/projection matrix, so we just need + // to get this matrix and get its translation as an equivalent. + XMMATRIX _modelview, _proj, _final, _invert; + XMVECTOR _det; + XMFLOAT4 trans; - memcpy( &_modelview, modelview->_getDataPointer(), 64 ); - memcpy( &_proj, projection->_getDataPointer(), 64 ); + memcpy(&_modelview, modelview->_getDataPointer(), 64); + memcpy(&_proj, projection->_getDataPointer(), 64); -#if ( defined __ORBIS__ ) || ( defined __PSVITA__ ) - _modelview = transpose(_modelview); - _proj = transpose(_proj); - _final = _modelview * _proj; - _invert = sce::Vectormath::Simd::Aos::inverse(_final); - xPlayerOffs = _invert.getElem(0,3) / _invert.getElem(3,3); - yPlayerOffs = _invert.getElem(1,3) / _invert.getElem(3,3); - zPlayerOffs = _invert.getElem(2,3) / _invert.getElem(3,3); -#elif defined __PS3__ - _modelview = transpose(_modelview); - _proj = transpose(_proj); - _final = _modelview * _proj; - _invert = Vectormath::Aos::inverse(_final); - xPlayerOffs = _invert.getElem(0,3) / _invert.getElem(3,3); - yPlayerOffs = _invert.getElem(1,3) / _invert.getElem(3,3); - zPlayerOffs = _invert.getElem(2,3) / _invert.getElem(3,3); +#if (defined __ORBIS__) || (defined __PSVITA__) + _modelview = transpose(_modelview); + _proj = transpose(_proj); + _final = _modelview * _proj; + _invert = sce::Vectormath::Simd::Aos::inverse(_final); + xPlayerOffs = _invert.getElem(0, 3) / _invert.getElem(3, 3); + yPlayerOffs = _invert.getElem(1, 3) / _invert.getElem(3, 3); + zPlayerOffs = _invert.getElem(2, 3) / _invert.getElem(3, 3); +#elif defined __PS3__ + _modelview = transpose(_modelview); + _proj = transpose(_proj); + _final = _modelview * _proj; + _invert = Vectormath::Aos::inverse(_final); + xPlayerOffs = _invert.getElem(0, 3) / _invert.getElem(3, 3); + yPlayerOffs = _invert.getElem(1, 3) / _invert.getElem(3, 3); + zPlayerOffs = _invert.getElem(2, 3) / _invert.getElem(3, 3); #else - _final = XMMatrixMultiply( _modelview, _proj ); - _det = XMMatrixDeterminant(_final); - _invert = XMMatrixInverse(&_det, _final); + _final = XMMatrixMultiply(_modelview, _proj); + _det = XMMatrixDeterminant(_final); + _invert = XMMatrixInverse(&_det, _final); - XMStoreFloat4(&trans,_invert.r[3]); + XMStoreFloat4(&trans, _invert.r[3]); - xPlayerOffs = trans.x / trans.w; - yPlayerOffs = trans.y / trans.w; - zPlayerOffs = trans.z / trans.w; + xPlayerOffs = trans.x / trans.w; + yPlayerOffs = trans.y / trans.w; + zPlayerOffs = trans.z / trans.w; #endif int flipCamera = mirror ? 1 : 0; @@ -88,15 +89,14 @@ void Camera::prepare(std::shared_ptr player, bool mirror) ya = cosf(xRot * PI / 180.0f); } -TilePos *Camera::getCameraTilePos(std::shared_ptr player, double alpha) -{ - return new TilePos(getCameraPos(player, alpha)); +TilePos* Camera::getCameraTilePos(std::shared_ptr player, double alpha) { + return new TilePos(getCameraPos(player, alpha)); } -Vec3 *Camera::getCameraPos(std::shared_ptr player, double alpha) -{ +Vec3* Camera::getCameraPos(std::shared_ptr player, double alpha) { double xx = player->xo + (player->x - player->xo) * alpha; - double yy = player->yo + (player->y - player->yo) * alpha + player->getHeadHeight(); + double yy = + player->yo + (player->y - player->yo) * alpha + player->getHeadHeight(); double zz = player->zo + (player->z - player->zo) * alpha; double xt = xx + Camera::xPlayerOffs * 1; @@ -106,17 +106,15 @@ Vec3 *Camera::getCameraPos(std::shared_ptr player, double alpha) return Vec3::newTemp(xt, yt, zt); } -int Camera::getBlockAt(Level *level, std::shared_ptr player, float alpha) -{ - Vec3 *p = Camera::getCameraPos(player, alpha); +int Camera::getBlockAt(Level* level, std::shared_ptr player, float alpha) { + Vec3* p = Camera::getCameraPos(player, alpha); TilePos tp = TilePos(p); int t = level->getTile(tp.x, tp.y, tp.z); - if (t != 0 && Tile::tiles[t]->material->isLiquid()) - { - float hh = LiquidTile::getHeight(level->getData(tp.x, tp.y, tp.z)) - 1 / 9.0f; + if (t != 0 && Tile::tiles[t]->material->isLiquid()) { + float hh = + LiquidTile::getHeight(level->getData(tp.x, tp.y, tp.z)) - 1 / 9.0f; float h = tp.y + 1 - hh; - if (p->y >= h) - { + if (p->y >= h) { t = level->getTile(tp.x, tp.y + 1, tp.z); } } diff --git a/Minecraft.Client/Rendering/Camera.h b/Minecraft.Client/Rendering/Camera.h index 1d42f58fa..019a6efa7 100644 --- a/Minecraft.Client/Rendering/Camera.h +++ b/Minecraft.Client/Rendering/Camera.h @@ -2,31 +2,30 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "../../Minecraft.World/IO/Streams/IntBuffer.h" - class TilePos; class Vec3; class Player; class Mob; -class Camera -{ +class Camera { public: - static float xPlayerOffs; + static float xPlayerOffs; static float yPlayerOffs; static float zPlayerOffs; private: -// static IntBuffer *viewport; - static FloatBuffer *modelview; - static FloatBuffer *projection; -// static FloatBuffer *position; + // static IntBuffer *viewport; + static FloatBuffer* modelview; + static FloatBuffer* projection; + // static FloatBuffer *position; public: - static float xa, ya, za, xa2, za2; + static float xa, ya, za, xa2, za2; - static void prepare(std::shared_ptr player, bool mirror); + static void prepare(std::shared_ptr player, bool mirror); - static TilePos *getCameraTilePos(std::shared_ptr player, double alpha); - static Vec3 *getCameraPos(std::shared_ptr player, double alpha); - static int getBlockAt(Level *level, std::shared_ptr player, float alpha); + static TilePos* getCameraTilePos(std::shared_ptr player, double alpha); + static Vec3* getCameraPos(std::shared_ptr player, double alpha); + static int getBlockAt(Level* level, std::shared_ptr player, + float alpha); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Chunk.cpp b/Minecraft.Client/Rendering/Chunk.cpp index cbf5bb4a3..746d29d79 100644 --- a/Minecraft.Client/Rendering/Chunk.cpp +++ b/Minecraft.Client/Rendering/Chunk.cpp @@ -22,1024 +22,1068 @@ int Chunk::updates = 0; #ifdef _LARGE_WORLDS unsigned int Chunk::tlsIdx = TlsAlloc(); -void Chunk::CreateNewThreadStorage() -{ - unsigned char *tileIds = new unsigned char[16 * 16 * Level::maxBuildHeight]; - TlsSetValue(tlsIdx, tileIds); +void Chunk::CreateNewThreadStorage() { + unsigned char* tileIds = new unsigned char[16 * 16 * Level::maxBuildHeight]; + TlsSetValue(tlsIdx, tileIds); } -void Chunk::ReleaseThreadStorage() -{ - unsigned char *tileIds = (unsigned char *)TlsGetValue(tlsIdx); - delete tileIds; +void Chunk::ReleaseThreadStorage() { + unsigned char* tileIds = (unsigned char*)TlsGetValue(tlsIdx); + delete tileIds; } -unsigned char *Chunk::GetTileIdsStorage() -{ - unsigned char *tileIds = (unsigned char *)TlsGetValue(tlsIdx); - return tileIds; +unsigned char* Chunk::GetTileIdsStorage() { + unsigned char* tileIds = (unsigned char*)TlsGetValue(tlsIdx); + return tileIds; } #else // 4J Stu - Don't want this when multi-threaded -Tesselator *Chunk::t = Tesselator::getInstance(); +Tesselator* Chunk::t = Tesselator::getInstance(); #endif -LevelRenderer *Chunk::levelRenderer; +LevelRenderer* Chunk::levelRenderer; -// TODO - 4J see how input entity vector is set up and decide what way is best to pass this to the function -Chunk::Chunk(Level *level, LevelRenderer::rteMap &globalRenderableTileEntities, CRITICAL_SECTION& globalRenderableTileEntities_cs, int x, int y, int z, ClipChunk *clipChunk) - : globalRenderableTileEntities( &globalRenderableTileEntities ), globalRenderableTileEntities_cs(&globalRenderableTileEntities_cs) -{ - clipChunk->visible = false; - bb = NULL; - id = 0; +// TODO - 4J see how input entity vector is set up and decide what way is best +// to pass this to the function +Chunk::Chunk(Level* level, LevelRenderer::rteMap& globalRenderableTileEntities, + CRITICAL_SECTION& globalRenderableTileEntities_cs, int x, int y, + int z, ClipChunk* clipChunk) + : globalRenderableTileEntities(&globalRenderableTileEntities), + globalRenderableTileEntities_cs(&globalRenderableTileEntities_cs) { + clipChunk->visible = false; + bb = NULL; + id = 0; - this->level = level; - //this->globalRenderableTileEntities = globalRenderableTileEntities; + this->level = level; + // this->globalRenderableTileEntities = globalRenderableTileEntities; - assigned = false; - this->clipChunk = clipChunk; - setPos(x, y, z); + assigned = false; + this->clipChunk = clipChunk; + setPos(x, y, z); } -void Chunk::setPos(int x, int y, int z) -{ - if(assigned && (x == this->x && y == this->y && z == this->z)) return; +void Chunk::setPos(int x, int y, int z) { + if (assigned && (x == this->x && y == this->y && z == this->z)) return; - reset(); + reset(); - this->x = x; - this->y = y; - this->z = z; - xm = x + XZSIZE / 2; - ym = y + SIZE / 2; - zm = z + XZSIZE / 2; - clipChunk->xm = xm; - clipChunk->ym = ym; - clipChunk->zm = zm; + this->x = x; + this->y = y; + this->z = z; + xm = x + XZSIZE / 2; + ym = y + SIZE / 2; + zm = z + XZSIZE / 2; + clipChunk->xm = xm; + clipChunk->ym = ym; + clipChunk->zm = zm; - clipChunk->globalIdx = LevelRenderer::getGlobalIndexForChunk(x, y, z, level); + clipChunk->globalIdx = + LevelRenderer::getGlobalIndexForChunk(x, y, z, level); #if 1 - // 4J - we're not using offsetted renderlists anymore, so just set the full position of this chunk into x/y/zRenderOffs where - // it will be used directly in the renderlist of this chunk - xRenderOffs = x; - yRenderOffs = y; - zRenderOffs = z; - xRender = 0; - yRender = 0; - zRender = 0; + // 4J - we're not using offsetted renderlists anymore, so just set the full + // position of this chunk into x/y/zRenderOffs where it will be used + // directly in the renderlist of this chunk + xRenderOffs = x; + yRenderOffs = y; + zRenderOffs = z; + xRender = 0; + yRender = 0; + zRender = 0; #else - xRenderOffs = x & 1023; - yRenderOffs = y; - zRenderOffs = z & 1023; - xRender = x - xRenderOffs; - yRender = y - yRenderOffs; - zRender = z - zRenderOffs; + xRenderOffs = x & 1023; + yRenderOffs = y; + zRenderOffs = z & 1023; + xRender = x - xRenderOffs; + yRender = y - yRenderOffs; + zRender = z - zRenderOffs; #endif - float g = 6.0f; - // 4J - changed to just set the value rather than make a new one, if we've already created storage - if( bb == NULL ) - { - bb = AABB::newPermanent(-g, -g, -g, XZSIZE+g, SIZE+g, XZSIZE+g); - } - else - { - // 4J MGH - bounds are relative to the position now, so the AABB will be setup already, either above, or from the tesselator bounds. -// bb->set(-g, -g, -g, SIZE+g, SIZE+g, SIZE+g); - } - clipChunk->aabb[0] = bb->x0 + x; - clipChunk->aabb[1] = bb->y0 + y; - clipChunk->aabb[2] = bb->z0 + z; - clipChunk->aabb[3] = bb->x1 + x; - clipChunk->aabb[4] = bb->y1 + y; - clipChunk->aabb[5] = bb->z1 + z; + float g = 6.0f; + // 4J - changed to just set the value rather than make a new one, if we've + // already created storage + if (bb == NULL) { + bb = AABB::newPermanent(-g, -g, -g, XZSIZE + g, SIZE + g, XZSIZE + g); + } else { + // 4J MGH - bounds are relative to the position now, so the AABB will be + // setup already, either above, or from the tesselator bounds. + // bb->set(-g, -g, -g, SIZE+g, SIZE+g, SIZE+g); + } + clipChunk->aabb[0] = bb->x0 + x; + clipChunk->aabb[1] = bb->y0 + y; + clipChunk->aabb[2] = bb->z0 + z; + clipChunk->aabb[3] = bb->x1 + x; + clipChunk->aabb[4] = bb->y1 + y; + clipChunk->aabb[5] = bb->z1 + z; - assigned = true; + assigned = true; - EnterCriticalSection(&levelRenderer->m_csDirtyChunks); - unsigned char refCount = levelRenderer->incGlobalChunkRefCount(x, y, z, level); -// printf("\t\t [inc] refcount %d at %d, %d, %d\n",refCount,x,y,z); + EnterCriticalSection(&levelRenderer->m_csDirtyChunks); + unsigned char refCount = + levelRenderer->incGlobalChunkRefCount(x, y, z, level); + // printf("\t\t [inc] refcount %d at %d, %d, %d\n",refCount,x,y,z); -// int idx = levelRenderer->getGlobalIndexForChunk(x, y, z, level); + // int idx = levelRenderer->getGlobalIndexForChunk(x, y, z, level); - // If we're the first thing to be referencing this, mark it up as dirty to get rebuilt - if( refCount == 1 ) - { -// printf("Setting %d %d %d dirty [%d]\n",x,y,z, idx); - // Chunks being made dirty in this way can be very numerous (eg the full visible area of the world at start up, or a whole edge of the world when moving). - // On account of this, don't want to stick them into our lock free queue that we would normally use for letting the render update thread know about this chunk. - // Instead, just set the flag to say this is dirty, and then pass a special value of 1 through to the lock free stack which lets that thread know that at least - // one chunk other than the ones in the stack itself have been made dirty. - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_DIRTY ); + // If we're the first thing to be referencing this, mark it up as dirty to + // get rebuilt + if (refCount == 1) { + // printf("Setting %d %d %d dirty [%d]\n",x,y,z, idx); + // Chunks being made dirty in this way can be very numerous (eg the full + // visible area of the world at start up, or a whole edge of the world + // when moving). On account of this, don't want to stick them into our + // lock free queue that we would normally use for letting the render + // update thread know about this chunk. Instead, just set the flag to + // say this is dirty, and then pass a special value of 1 through to the + // lock free stack which lets that thread know that at least one chunk + // other than the ones in the stack itself have been made dirty. + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_DIRTY); #ifdef _XBOX - PIXSetMarker(0,"Non-stack event pushed"); + PIXSetMarker(0, "Non-stack event pushed"); #else - PIXSetMarkerDeprecated(0,"Non-stack event pushed"); + PIXSetMarkerDeprecated(0, "Non-stack event pushed"); #endif - } + } - LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); - - + LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); } -void Chunk::translateToPos() -{ - glTranslatef((float)xRenderOffs, (float)yRenderOffs, (float)zRenderOffs); +void Chunk::translateToPos() { + glTranslatef((float)xRenderOffs, (float)yRenderOffs, (float)zRenderOffs); } +Chunk::Chunk() {} -Chunk::Chunk() -{ +void Chunk::makeCopyForRebuild(Chunk* source) { + this->level = source->level; + this->x = source->x; + this->y = source->y; + this->z = source->z; + this->xRender = source->xRender; + this->yRender = source->yRender; + this->zRender = source->zRender; + this->xRenderOffs = source->xRenderOffs; + this->yRenderOffs = source->yRenderOffs; + this->zRenderOffs = source->zRenderOffs; + this->xm = source->xm; + this->ym = source->ym; + this->zm = source->zm; + this->bb = source->bb; + this->clipChunk = NULL; + this->id = source->id; + this->globalRenderableTileEntities = source->globalRenderableTileEntities; + this->globalRenderableTileEntities_cs = + source->globalRenderableTileEntities_cs; } -void Chunk::makeCopyForRebuild(Chunk *source) -{ - this->level = source->level; - this->x = source->x; - this->y = source->y; - this->z = source->z; - this->xRender = source->xRender; - this->yRender = source->yRender; - this->zRender = source->zRender; - this->xRenderOffs = source->xRenderOffs; - this->yRenderOffs = source->yRenderOffs; - this->zRenderOffs = source->zRenderOffs; - this->xm = source->xm; - this->ym = source->ym; - this->zm = source->zm; - this->bb = source->bb; - this->clipChunk = NULL; - this->id = source->id; - this->globalRenderableTileEntities = source->globalRenderableTileEntities; - this->globalRenderableTileEntities_cs = source->globalRenderableTileEntities_cs; -} - -void Chunk::rebuild() -{ - PIXBeginNamedEvent(0,"Rebuilding chunk %d, %d, %d", x, y, z); +void Chunk::rebuild() { + PIXBeginNamedEvent(0, "Rebuilding chunk %d, %d, %d", x, y, z); #if defined __PS3__ && !defined DISABLE_SPU_CODE - rebuild_SPU(); - return; -#endif // __PS3__ + rebuild_SPU(); + return; +#endif // __PS3__ -// if (!dirty) return; - PIXBeginNamedEvent(0,"Rebuild section A"); - -#ifdef _LARGE_WORLDS - Tesselator *t = Tesselator::getInstance(); -#else - Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser being set at the wrong time -#endif - - updates++; - - int x0 = x; - int y0 = y; - int z0 = z; - int x1 = x + XZSIZE; - int y1 = y + SIZE; - int z1 = z + XZSIZE; - - LevelChunk::touchedSky = false; - -// std::unordered_set > oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); // 4J removed this & next line -// renderableTileEntities.clear(); - - std::vector > renderableTileEntities; // 4J - added - - int r = 1; - - int lists = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level) * 2; - lists += levelRenderer->chunkLists; - - PIXEndNamedEvent(); - - PIXBeginNamedEvent(0,"Rebuild section B"); - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // 4J - optimisation begins. - - // Get the data for the level chunk that this render chunk is it (level chunk is 16 x 16 x 128, - // render chunk is 16 x 16 x 16. We wouldn't have to actually get all of it if the data was ordered differently, but currently - // it is ordered by x then z then y so just getting a small range of y out of it would involve getting the whole thing into - // the cache anyway. + // if (!dirty) return; + PIXBeginNamedEvent(0, "Rebuild section A"); #ifdef _LARGE_WORLDS - unsigned char *tileIds = GetTileIdsStorage(); + Tesselator* t = Tesselator::getInstance(); #else - static unsigned char tileIds[16 * 16 * Level::maxBuildHeight]; + Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser + // being set at the wrong time #endif - byteArray tileArray = byteArray(tileIds, 16 * 16 * Level::maxBuildHeight); - level->getChunkAt(x,z)->getBlockData(tileArray); // 4J - TODO - now our data has been re-arranged, we could just extra the vertical slice of this chunk rather than the whole thing - LevelSource *region = new Region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); - TileRenderer *tileRenderer = new TileRenderer(region, this->x, this->y, this->z, tileIds); + updates++; - // AP - added a caching system for Chunk::rebuild to take advantage of - // Basically we're storing of copy of the tileIDs array inside the region so that calls to Region::getTile can grab data - // more quickly from this array rather than calling CompressedTileStorage. On the Vita the total thread time spent in - // Region::getTile went from 20% to 4%. + int x0 = x; + int y0 = y; + int z0 = z; + int x1 = x + XZSIZE; + int y1 = y + SIZE; + int z1 = z + XZSIZE; + + LevelChunk::touchedSky = false; + + // std::unordered_set > + //oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); + //// 4J removed this & next line renderableTileEntities.clear(); + + std::vector > + renderableTileEntities; // 4J - added + + int r = 1; + + int lists = levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, + level) * + 2; + lists += levelRenderer->chunkLists; + + PIXEndNamedEvent(); + + PIXBeginNamedEvent(0, "Rebuild section B"); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 4J - optimisation begins. + + // Get the data for the level chunk that this render chunk is it (level + // chunk is 16 x 16 x 128, render chunk is 16 x 16 x 16. We wouldn't have to + // actually get all of it if the data was ordered differently, but currently + // it is ordered by x then z then y so just getting a small range of y out + // of it would involve getting the whole thing into the cache anyway. + +#ifdef _LARGE_WORLDS + unsigned char* tileIds = GetTileIdsStorage(); +#else + static unsigned char tileIds[16 * 16 * Level::maxBuildHeight]; +#endif + byteArray tileArray = byteArray(tileIds, 16 * 16 * Level::maxBuildHeight); + level->getChunkAt(x, z)->getBlockData( + tileArray); // 4J - TODO - now our data has been re-arranged, we could + // just extra the vertical slice of this chunk rather than + // the whole thing + + LevelSource* region = + new Region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); + TileRenderer* tileRenderer = + new TileRenderer(region, this->x, this->y, this->z, tileIds); + + // AP - added a caching system for Chunk::rebuild to take advantage of + // Basically we're storing of copy of the tileIDs array inside the region so + // that calls to Region::getTile can grab data more quickly from this array + // rather than calling CompressedTileStorage. On the Vita the total thread + // time spent in Region::getTile went from 20% to 4%. #ifdef __PSVITA__ - int xc = x >> 4; - int zc = z >> 4; - ((Region*)region)->setCachedTiles(tileIds, xc, zc); + int xc = x >> 4; + int zc = z >> 4; + ((Region*)region)->setCachedTiles(tileIds, xc, zc); #endif - // We now go through the vertical section of this level chunk that we are interested in and try and establish - // (1) if it is completely empty - // (2) if any of the tiles can be quickly determined to not need rendering because they are in the middle of other tiles and - // so can't be seen. A large amount (> 60% in tests) of tiles that call tesselateInWorld in the unoptimised version - // of this function fall into this category. By far the largest category of these are tiles in solid regions of rock. - bool empty = true; - for( int yy = y0; yy < y1; yy++ ) - { - for( int zz = 0; zz < 16; zz++ ) - { - for( int xx = 0; xx < 16; xx++ ) - { - // 4J Stu - tile data is ordered in 128 blocks of full width, lower 128 then upper 128 - int indexY = yy; - int offset = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } + // We now go through the vertical section of this level chunk that we are + // interested in and try and establish (1) if it is completely empty (2) if + // any of the tiles can be quickly determined to not need rendering because + // they are in the middle of other tiles and + // so can't be seen. A large amount (> 60% in tests) of tiles that call + // tesselateInWorld in the unoptimised version of this function fall + // into this category. By far the largest category of these are tiles in + // solid regions of rock. + bool empty = true; + for (int yy = y0; yy < y1; yy++) { + for (int zz = 0; zz < 16; zz++) { + for (int xx = 0; xx < 16; xx++) { + // 4J Stu - tile data is ordered in 128 blocks of full width, + // lower 128 then upper 128 + int indexY = yy; + int offset = 0; + if (indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } - unsigned char tileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 ) ) ]; - if( tileId > 0 ) empty = false; + unsigned char tileId = + tileIds[offset + (((xx + 0) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + if (tileId > 0) empty = false; - // Don't bother trying to work out neighbours for this tile if we are at the edge of the chunk - apart from the very - // bottom of the world where we shouldn't ever be able to see - if( yy == (Level::maxBuildHeight - 1) ) continue; - if(( xx == 0 ) || ( xx == 15 )) continue; - if(( zz == 0 ) || ( zz == 15 )) continue; - - // Establish whether this tile and its neighbours are all made of rock, dirt, unbreakable tiles, or have already - // been determined to meet this criteria themselves and have a tile of 255 set. - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx - 1 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx + 1 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz - 1 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - tileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 1 ) << 7 ) | ( indexY + 0 )) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - // Treat the bottom of the world differently - we shouldn't ever be able to look up at this, so consider tiles as invisible - // if they are surrounded on sides other than the bottom - if( yy > 0 ) - { - int indexYMinusOne = yy - 1; - int yMinusOneOffset = 0; - if(indexYMinusOne >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexYMinusOne -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - yMinusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } - tileId = tileIds[ yMinusOneOffset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | indexYMinusOne ) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; - } - int indexYPlusOne = yy + 1; - int yPlusOneOffset = 0; - if(indexYPlusOne >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexYPlusOne -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - yPlusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } - tileId = tileIds[ yPlusOneOffset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | indexYPlusOne ) ]; - if( !( ( tileId == Tile::rock_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; + // Don't bother trying to work out neighbours for this tile if + // we are at the edge of the chunk - apart from the very bottom + // of the world where we shouldn't ever be able to see + if (yy == (Level::maxBuildHeight - 1)) continue; + if ((xx == 0) || (xx == 15)) continue; + if ((zz == 0) || (zz == 15)) continue; - // This tile is surrounded. Flag it as not requiring to be rendered by setting its id to 255. - tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 ) ) ] = 0xff; - } - } - } - PIXEndNamedEvent(); - // Nothing at all to do for this chunk? - if( empty ) - { - // 4J - added - clear any renderer data associated with this - for (int currentLayer = 0; currentLayer < 2; currentLayer++) - { - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - RenderManager.CBuffClear(lists + currentLayer); - } + // Establish whether this tile and its neighbours are all made + // of rock, dirt, unbreakable tiles, or have already been + // determined to meet this criteria themselves and have a tile + // of 255 set. + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx - 1) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx + 1) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx + 0) << 11) | ((zz - 1) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + tileId = tileIds[offset + (((xx + 0) << 11) | ((zz + 1) << 7) | + (indexY + 0))]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + // Treat the bottom of the world differently - we shouldn't ever + // be able to look up at this, so consider tiles as invisible if + // they are surrounded on sides other than the bottom + if (yy > 0) { + int indexYMinusOne = yy - 1; + int yMinusOneOffset = 0; + if (indexYMinusOne >= + Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexYMinusOne -= + Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + yMinusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } + tileId = tileIds[yMinusOneOffset + (((xx + 0) << 11) | + ((zz + 0) << 7) | + indexYMinusOne)]; + if (!((tileId == Tile::rock_Id) || + (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; + } + int indexYPlusOne = yy + 1; + int yPlusOneOffset = 0; + if (indexYPlusOne >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexYPlusOne -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + yPlusOneOffset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } + tileId = + tileIds[yPlusOneOffset + (((xx + 0) << 11) | + ((zz + 0) << 7) | indexYPlusOne)]; + if (!((tileId == Tile::rock_Id) || (tileId == Tile::dirt_Id) || + (tileId == Tile::unbreakable_Id) || (tileId == 255))) + continue; - delete region; - delete tileRenderer; - return; - } - // 4J - optimisation ends - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // This tile is surrounded. Flag it as not requiring to be + // rendered by setting its id to 255. + tileIds[offset + (((xx + 0) << 11) | ((zz + 0) << 7) | + (indexY + 0))] = 0xff; + } + } + } + PIXEndNamedEvent(); + // Nothing at all to do for this chunk? + if (empty) { + // 4J - added - clear any renderer data associated with this + for (int currentLayer = 0; currentLayer < 2; currentLayer++) { + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, + currentLayer); + RenderManager.CBuffClear(lists + currentLayer); + } - PIXBeginNamedEvent(0,"Rebuild section C"); - Tesselator::Bounds bounds; // 4J MGH - added - { - // this was the old default clip bounds for the chunk, set in Chunk::setPos. - float g = 6.0f; - bounds.boundingBox[0] = -g; - bounds.boundingBox[1] = -g; - bounds.boundingBox[2] = -g; - bounds.boundingBox[3] = XZSIZE+g; - bounds.boundingBox[4] = SIZE+g; - bounds.boundingBox[5] = XZSIZE+g; - } - for (int currentLayer = 0; currentLayer < 2; currentLayer++) - { - bool renderNextLayer = false; - bool rendered = false; + delete region; + delete tileRenderer; + return; + } + // 4J - optimisation ends + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - bool started = false; + PIXBeginNamedEvent(0, "Rebuild section C"); + Tesselator::Bounds bounds; // 4J MGH - added + { + // this was the old default clip bounds for the chunk, set in + // Chunk::setPos. + float g = 6.0f; + bounds.boundingBox[0] = -g; + bounds.boundingBox[1] = -g; + bounds.boundingBox[2] = -g; + bounds.boundingBox[3] = XZSIZE + g; + bounds.boundingBox[4] = SIZE + g; + bounds.boundingBox[5] = XZSIZE + g; + } + for (int currentLayer = 0; currentLayer < 2; currentLayer++) { + bool renderNextLayer = false; + bool rendered = false; - // 4J - changed loop order here to leave y as the innermost loop for better cache performance - for (int z = z0; z < z1; z++) - { - for (int x = x0; x < x1; x++) - { - for (int y = y0; y < y1; y++) - { - // 4J Stu - tile data is ordered in 128 blocks of full width, lower 128 then upper 128 - int indexY = y; - int offset = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } + bool started = false; - // 4J - get tile from those copied into our local array in earlier optimisation - unsigned char tileId = tileIds[ offset + ( ( ( x - x0 ) << 11 ) | ( ( z - z0 ) << 7 ) | indexY) ]; - // If flagged as not visible, drop out straight away - if( tileId == 0xff ) continue; -// int tileId = region->getTile(x,y,z); - if (tileId > 0) - { - if (!started) - { - started = true; + // 4J - changed loop order here to leave y as the innermost loop for + // better cache performance + for (int z = z0; z < z1; z++) { + for (int x = x0; x < x1; x++) { + for (int y = y0; y < y1; y++) { + // 4J Stu - tile data is ordered in 128 blocks of full + // width, lower 128 then upper 128 + int indexY = y; + int offset = 0; + if (indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } - MemSect(31); - glNewList(lists + currentLayer, GL_COMPILE); - MemSect(0); - glPushMatrix(); - glDepthMask(true); // 4J added - t->useCompactVertices(false); // 4J added - translateToPos(); - float ss = 1.000001f; - // 4J - have removed this scale as I don't think we should need it, and have now optimised the vertex - // shader so it doesn't do anything other than translate with this matrix anyway + // 4J - get tile from those copied into our local array in + // earlier optimisation + unsigned char tileId = + tileIds[offset + + (((x - x0) << 11) | ((z - z0) << 7) | indexY)]; + // If flagged as not visible, drop out straight away + if (tileId == 0xff) continue; + // int tileId = + //region->getTile(x,y,z); + if (tileId > 0) { + if (!started) { + started = true; + + MemSect(31); + glNewList(lists + currentLayer, GL_COMPILE); + MemSect(0); + glPushMatrix(); + glDepthMask(true); // 4J added + t->useCompactVertices(false); // 4J added + translateToPos(); + float ss = 1.000001f; + // 4J - have removed this scale as I don't think we + // should need it, and have now optimised the vertex + // shader so it doesn't do anything other than + // translate with this matrix anyway #if 0 glTranslatef(-zs / 2.0f, -ys / 2.0f, -zs / 2.0f); glScalef(ss, ss, ss); glTranslatef(zs / 2.0f, ys / 2.0f, zs / 2.0f); #endif - t->begin(); - t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); - } - - Tile *tile = Tile::tiles[tileId]; - if (currentLayer == 0 && tile->isEntityTile()) - { - std::shared_ptr et = region->getTileEntity(x, y, z); - if (TileEntityRenderDispatcher::instance->hasRenderer(et)) - { - renderableTileEntities.push_back(et); - } - } - int renderLayer = tile->getRenderLayer(); + t->begin(); + t->offset((float)(-this->x), (float)(-this->y), + (float)(-this->z)); + } - if (renderLayer != currentLayer) - { - renderNextLayer = true; - } - else if (renderLayer == currentLayer) - { - rendered |= tileRenderer->tesselateInWorld(tile, x, y, z); - } - } - } - } - } + Tile* tile = Tile::tiles[tileId]; + if (currentLayer == 0 && tile->isEntityTile()) { + std::shared_ptr et = + region->getTileEntity(x, y, z); + if (TileEntityRenderDispatcher::instance + ->hasRenderer(et)) { + renderableTileEntities.push_back(et); + } + } + int renderLayer = tile->getRenderLayer(); + + if (renderLayer != currentLayer) { + renderNextLayer = true; + } else if (renderLayer == currentLayer) { + rendered |= + tileRenderer->tesselateInWorld(tile, x, y, z); + } + } + } + } + } #ifdef __PSVITA__ - if( currentLayer==0 ) - { - levelRenderer->clearGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_CUT_OUT); - } + if (currentLayer == 0) { + levelRenderer->clearGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_CUT_OUT); + } #endif - if (started) - { + if (started) { #ifdef __PSVITA__ - // AP - make sure we don't attempt to render chunks without cutout geometry - if( t->getCutOutFound() ) - { - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_CUT_OUT); - } + // AP - make sure we don't attempt to render chunks without cutout + // geometry + if (t->getCutOutFound()) { + levelRenderer->setGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_CUT_OUT); + } #endif - t->end(); - bounds.addBounds(t->bounds); // 4J MGH - added - glPopMatrix(); - glEndList(); - t->useCompactVertices(false); // 4J added - t->offset(0, 0, 0); - } - else - { - rendered = false; - } + t->end(); + bounds.addBounds(t->bounds); // 4J MGH - added + glPopMatrix(); + glEndList(); + t->useCompactVertices(false); // 4J added + t->offset(0, 0, 0); + } else { + rendered = false; + } - if (rendered) - { - levelRenderer->clearGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - } - else - { - // 4J - added - clear any renderer data associated with this unused list - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - RenderManager.CBuffClear(lists + currentLayer); - } - if((currentLayer==0)&&(!renderNextLayer)) - { - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY1); - RenderManager.CBuffClear(lists + 1); - break; - } - } + if (rendered) { + levelRenderer->clearGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); + } else { + // 4J - added - clear any renderer data associated with this unused + // list + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, + currentLayer); + RenderManager.CBuffClear(lists + currentLayer); + } + if ((currentLayer == 0) && (!renderNextLayer)) { + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY1); + RenderManager.CBuffClear(lists + 1); + break; + } + } - // 4J MGH - added this to take the bound from the value calc'd in the tesselator - if( bb ) - { - bb->set(bounds.boundingBox[0], bounds.boundingBox[1], bounds.boundingBox[2], - bounds.boundingBox[3], bounds.boundingBox[4], bounds.boundingBox[5]); - } + // 4J MGH - added this to take the bound from the value calc'd in the + // tesselator + if (bb) { + bb->set(bounds.boundingBox[0], bounds.boundingBox[1], + bounds.boundingBox[2], bounds.boundingBox[3], + bounds.boundingBox[4], bounds.boundingBox[5]); + } - delete tileRenderer; - delete region; + delete tileRenderer; + delete region; - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Rebuild section D"); + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Rebuild section D"); - // 4J - have rewritten the way that tile entities are stored globally to make it work more easily with split screen. Chunks are now - // stored globally in the levelrenderer, in a hashmap with a special key made up from the dimension and chunk position (using same index - // as is used for global flags) + // 4J - have rewritten the way that tile entities are stored globally to + // make it work more easily with split screen. Chunks are now stored + // globally in the levelrenderer, in a hashmap with a special key made up + // from the dimension and chunk position (using same index as is used for + // global flags) #if 1 - int key = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level); - EnterCriticalSection(globalRenderableTileEntities_cs); - if( renderableTileEntities.size() ) - { - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - // We've got some renderable tile entities that we want associated with this chunk, and an existing list of things that used to be. - // We need to flag any that we don't need any more to be removed, keep those that we do, and add any new ones + int key = + levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, level); + EnterCriticalSection(globalRenderableTileEntities_cs); + if (renderableTileEntities.size()) { + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + // We've got some renderable tile entities that we want associated + // with this chunk, and an existing list of things that used to be. + // We need to flag any that we don't need any more to be removed, + // keep those that we do, and add any new ones - // First pass - flag everything already existing to be removed - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } + // First pass - flag everything already existing to be removed + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } - // Now go through the current list. If these are already in the list, then unflag the remove flag. If they aren't, then add - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - AUTO_VAR(it2, find( it->second.begin(), it->second.end(), renderableTileEntities[i] )); - if( it2 == it->second.end() ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - else - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageKeep); - } - } - } - else - { - // Easy case - nothing already existing for this chunk. Add them all in. - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - } - } - else - { - // Another easy case - we don't want any renderable tile entities associated with this chunk. Flag all to be removed. - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } - } - } - LeaveCriticalSection(globalRenderableTileEntities_cs); - PIXEndNamedEvent(); + // Now go through the current list. If these are already in the + // list, then unflag the remove flag. If they aren't, then add + for (int i = 0; i < renderableTileEntities.size(); i++) { + AUTO_VAR(it2, find(it->second.begin(), it->second.end(), + renderableTileEntities[i])); + if (it2 == it->second.end()) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } else { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageKeep); + } + } + } else { + // Easy case - nothing already existing for this chunk. Add them all + // in. + for (int i = 0; i < renderableTileEntities.size(); i++) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } + } + } else { + // Another easy case - we don't want any renderable tile entities + // associated with this chunk. Flag all to be removed. + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } + } + } + LeaveCriticalSection(globalRenderableTileEntities_cs); + PIXEndNamedEvent(); #else - // Find the removed ones: + // Find the removed ones: - // 4J - original code for this section: - /* - Set newTileEntities = new HashSet(); - newTileEntities.addAll(renderableTileEntities); - newTileEntities.removeAll(oldTileEntities); - globalRenderableTileEntities.addAll(newTileEntities); + // 4J - original code for this section: + /* + Set newTileEntities = new HashSet(); + newTileEntities.addAll(renderableTileEntities); + newTileEntities.removeAll(oldTileEntities); + globalRenderableTileEntities.addAll(newTileEntities); - oldTileEntities.removeAll(renderableTileEntities); - globalRenderableTileEntities.removeAll(oldTileEntities); - */ - + oldTileEntities.removeAll(renderableTileEntities); + globalRenderableTileEntities.removeAll(oldTileEntities); + */ - std::unordered_set > newTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); - - AUTO_VAR(endIt, oldTileEntities.end()); - for( std::unordered_set >::iterator it = oldTileEntities.begin(); it != endIt; it++ ) - { - newTileEntities.erase(*it); - } + std::unordered_set > newTileEntities( + renderableTileEntities.begin(), renderableTileEntities.end()); - // 4J - newTileEntities is now renderableTileEntities with any old ones from oldTileEntitesRemoved (so just new things added) + AUTO_VAR(endIt, oldTileEntities.end()); + for (std::unordered_set >::iterator it = + oldTileEntities.begin(); + it != endIt; it++) { + newTileEntities.erase(*it); + } - EnterCriticalSection(globalRenderableTileEntities_cs); - endIt = newTileEntities.end(); - for( std::unordered_set >::iterator it = newTileEntities.begin(); it != endIt; it++ ) - { - globalRenderableTileEntities->push_back(*it); - } + // 4J - newTileEntities is now renderableTileEntities with any old ones from + // oldTileEntitesRemoved (so just new things added) - // 4J - All these new things added to globalRenderableTileEntities + EnterCriticalSection(globalRenderableTileEntities_cs); + endIt = newTileEntities.end(); + for (std::unordered_set >::iterator it = + newTileEntities.begin(); + it != endIt; it++) { + globalRenderableTileEntities->push_back(*it); + } - AUTO_VAR(endItRTE, renderableTileEntities.end()); - for( std::vector >::iterator it = renderableTileEntities.begin(); it != endItRTE; it++ ) - { - oldTileEntities.erase(*it); - } - // 4J - oldTileEntities is now the removed items - std::vector >::iterator it = globalRenderableTileEntities->begin(); - while( it != globalRenderableTileEntities->end() ) - { - if( oldTileEntities.find(*it) != oldTileEntities.end() ) - { - it = globalRenderableTileEntities->erase(it); - } - else - { - ++it; - } - } + // 4J - All these new things added to globalRenderableTileEntities - LeaveCriticalSection(globalRenderableTileEntities_cs); + AUTO_VAR(endItRTE, renderableTileEntities.end()); + for (std::vector >::iterator it = + renderableTileEntities.begin(); + it != endItRTE; it++) { + oldTileEntities.erase(*it); + } + // 4J - oldTileEntities is now the removed items + std::vector >::iterator it = + globalRenderableTileEntities->begin(); + while (it != globalRenderableTileEntities->end()) { + if (oldTileEntities.find(*it) != oldTileEntities.end()) { + it = globalRenderableTileEntities->erase(it); + } else { + ++it; + } + } + + LeaveCriticalSection(globalRenderableTileEntities_cs); #endif - // 4J - These removed items are now also removed from globalRenderableTileEntities - - if( LevelChunk::touchedSky ) - { - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - else - { - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_COMPILED); - PIXEndNamedEvent(); - return; + // 4J - These removed items are now also removed from + // globalRenderableTileEntities + if (LevelChunk::touchedSky) { + levelRenderer->clearGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } else { + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_COMPILED); + PIXEndNamedEvent(); + return; } - #ifdef __PS3__ ChunkRebuildData g_rebuildDataIn __attribute__((__aligned__(16))); ChunkRebuildData g_rebuildDataOut __attribute__((__aligned__(16))); TileCompressData_SPU g_tileCompressDataIn __attribute__((__aligned__(16))); -unsigned char* g_tileCompressDataOut = (unsigned char*)&g_rebuildDataIn.m_tileIds; +unsigned char* g_tileCompressDataOut = + (unsigned char*)&g_rebuildDataIn.m_tileIds; #define TILE_RENDER_SPU +void RunSPURebuild() { + static C4JSpursJobQueue::Port p("C4JSpursJob_ChunkUpdate"); + C4JSpursJob_CompressedTile tileJob(&g_tileCompressDataIn, + g_tileCompressDataOut); + C4JSpursJob_ChunkUpdate chunkJob(&g_rebuildDataIn, &g_rebuildDataOut); -void RunSPURebuild() -{ + if (g_rebuildDataIn.m_currentLayer == + 0) // only need to create the tiles on the first layer + { + p.submitJob(&tileJob); + p.submitSync(); + } - static C4JSpursJobQueue::Port p("C4JSpursJob_ChunkUpdate"); - C4JSpursJob_CompressedTile tileJob(&g_tileCompressDataIn,g_tileCompressDataOut); - C4JSpursJob_ChunkUpdate chunkJob(&g_rebuildDataIn, &g_rebuildDataOut); + p.submitJob(&chunkJob); + p.waitForCompletion(); - if(g_rebuildDataIn.m_currentLayer == 0) // only need to create the tiles on the first layer - { - p.submitJob(&tileJob); - p.submitSync(); - } - - p.submitJob(&chunkJob); - p.waitForCompletion(); - - assert(g_rebuildDataIn.m_x0 == g_rebuildDataOut.m_x0); + assert(g_rebuildDataIn.m_x0 == g_rebuildDataOut.m_x0); } -void Chunk::rebuild_SPU() -{ +void Chunk::rebuild_SPU() { + // if (!dirty) return; + Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser + // being set at the wrong time + updates++; -// if (!dirty) return; - Chunk::t = Tesselator::getInstance(); // 4J - added - static initialiser being set at the wrong time - updates++; + int x0 = x; + int y0 = y; + int z0 = z; + int x1 = x + SIZE; + int y1 = y + SIZE; + int z1 = z + SIZE; - int x0 = x; - int y0 = y; - int z0 = z; - int x1 = x + SIZE; - int y1 = y + SIZE; - int z1 = z + SIZE; + LevelChunk::touchedSky = false; - LevelChunk::touchedSky = false; + // std::unordered_set > + //oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); + //// 4J removed this & next line renderableTileEntities.clear(); -// std::unordered_set > oldTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); // 4J removed this & next line -// renderableTileEntities.clear(); + std::vector > + renderableTileEntities; // 4J - added - std::vector > renderableTileEntities; // 4J - added + // List newTileEntities = new ArrayList(); + // newTileEntities.clear(); + // renderableTileEntities.clear(); -// List newTileEntities = new ArrayList(); -// newTileEntities.clear(); -// renderableTileEntities.clear(); + int r = 1; - int r = 1; + Region region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); + TileRenderer tileRenderer(®ion); - Region region(level, x0 - r, y0 - r, z0 - r, x1 + r, y1 + r, z1 + r); - TileRenderer tileRenderer(®ion); + int lists = levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, + level) * + 2; + lists += levelRenderer->chunkLists; - int lists = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level) * 2; - lists += levelRenderer->chunkLists; + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // 4J - optimisation begins. - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // 4J - optimisation begins. + // Get the data for the level chunk that this render chunk is it (level + // chunk is 16 x 16 x 128, render chunk is 16 x 16 x 16. We wouldn't have to + // actually get all of it if the data was ordered differently, but currently + // it is ordered by x then z then y so just getting a small range of y out + // of it would involve getting the whole thing into the cache anyway. + ChunkRebuildData* pOutData = NULL; + g_rebuildDataIn.buildForChunk(®ion, level, x0, y0, z0); - // Get the data for the level chunk that this render chunk is it (level chunk is 16 x 16 x 128, - // render chunk is 16 x 16 x 16. We wouldn't have to actually get all of it if the data was ordered differently, but currently - // it is ordered by x then z then y so just getting a small range of y out of it would involve getting the whole thing into - // the cache anyway. - ChunkRebuildData* pOutData = NULL; - g_rebuildDataIn.buildForChunk(®ion, level, x0, y0, z0); + Tesselator::Bounds bounds; + { + // this was the old default clip bounds for the chunk, set in + // Chunk::setPos. + float g = 6.0f; + bounds.boundingBox[0] = -g; + bounds.boundingBox[1] = -g; + bounds.boundingBox[2] = -g; + bounds.boundingBox[3] = SIZE + g; + bounds.boundingBox[4] = SIZE + g; + bounds.boundingBox[5] = SIZE + g; + } - Tesselator::Bounds bounds; - { - // this was the old default clip bounds for the chunk, set in Chunk::setPos. - float g = 6.0f; - bounds.boundingBox[0] = -g; - bounds.boundingBox[1] = -g; - bounds.boundingBox[2] = -g; - bounds.boundingBox[3] = SIZE+g; - bounds.boundingBox[4] = SIZE+g; - bounds.boundingBox[5] = SIZE+g; - } + for (int currentLayer = 0; currentLayer < 2; currentLayer++) { + bool rendered = false; - for (int currentLayer = 0; currentLayer < 2; currentLayer++) - { - bool rendered = false; - - { - glNewList(lists + currentLayer, GL_COMPILE); - MemSect(0); - glPushMatrix(); - glDepthMask(true); // 4J added - t->useCompactVertices(false); // 4J added - translateToPos(); - float ss = 1.000001f; - // 4J - have removed this scale as I don't think we should need it, and have now optimised the vertex - // shader so it doesn't do anything other than translate with this matrix anyway - #if 0 + { + glNewList(lists + currentLayer, GL_COMPILE); + MemSect(0); + glPushMatrix(); + glDepthMask(true); // 4J added + t->useCompactVertices(false); // 4J added + translateToPos(); + float ss = 1.000001f; + // 4J - have removed this scale as I don't think we should need it, + // and have now optimised the vertex shader so it doesn't do + // anything other than translate with this matrix anyway +#if 0 glTranslatef(-zs / 2.0f, -ys / 2.0f, -zs / 2.0f); glScalef(ss, ss, ss); glTranslatef(zs / 2.0f, ys / 2.0f, zs / 2.0f); - #endif - t->begin(); - t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); - } +#endif + t->begin(); + t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); + } - g_rebuildDataIn.copyFromTesselator(); - intArray_SPU tesselatorArray((unsigned int*)g_rebuildDataIn.m_tesselator.m_PPUArray); - g_rebuildDataIn.m_tesselator._array = &tesselatorArray; - g_rebuildDataIn.m_currentLayer = currentLayer; - #ifdef TILE_RENDER_SPU - g_tileCompressDataIn.setForChunk(®ion, x0, y0, z0); - RunSPURebuild(); - g_rebuildDataOut.storeInTesselator(); - pOutData = &g_rebuildDataOut; - #else - g_rebuildDataIn.disableUnseenTiles(); - TileRenderer_SPU *pTileRenderer = new TileRenderer_SPU(&g_rebuildDataIn); - g_rebuildDataIn.tesselateAllTiles(pTileRenderer); - g_rebuildDataIn.storeInTesselator(); - pOutData = &g_rebuildDataIn; - #endif - if(pOutData->m_flags & ChunkRebuildData::e_flag_Rendered) - rendered = true; - - // 4J - changed loop order here to leave y as the innermost loop for better cache performance - for (int z = z0; z < z1; z++) - { - for (int x = x0; x < x1; x++) - { - for (int y = y0; y < y1; y++) - { - // 4J - get tile from those copied into our local array in earlier optimisation - unsigned char tileId = pOutData->getTile(x,y,z); - if (tileId > 0) - { - if (currentLayer == 0 && Tile::tiles[tileId]->isEntityTile()) - { - std::shared_ptr et = region.getTileEntity(x, y, z); - if (TileEntityRenderDispatcher::instance->hasRenderer(et)) - { - renderableTileEntities.push_back(et); - } - } - int flags = pOutData->getFlags(x,y,z); - if(flags & ChunkRebuildData::e_flag_SPURenderCodeMissing) - { - - Tile *tile = Tile::tiles[tileId]; - int renderLayer = tile->getRenderLayer(); - - if (renderLayer != currentLayer) - { - // renderNextLayer = true; - } - else if (renderLayer == currentLayer) - { - //if(currentLayer == 0) - // numRenderedLayer0++; - rendered |= tileRenderer.tesselateInWorld(tile, x, y, z); - } - } - } - } - } - } - - - { - t->end(); - bounds.addBounds(t->bounds); - glPopMatrix(); - glEndList(); - t->useCompactVertices(false); // 4J added - t->offset(0, 0, 0); - } - if (rendered) - { - levelRenderer->clearGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - } - else - { - // 4J - added - clear any renderer data associated with this unused list - levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); - RenderManager.CBuffClear(lists + currentLayer); - } - - } - - if( bb ) - { - bb->set(bounds.boundingBox[0], bounds.boundingBox[1], bounds.boundingBox[2], - bounds.boundingBox[3], bounds.boundingBox[4], bounds.boundingBox[5]); - } - - - if(pOutData->m_flags & ChunkRebuildData::e_flag_TouchedSky) - LevelChunk::touchedSky = true; - - - // 4J - have rewritten the way that tile entities are stored globally to make it work more easily with split screen. Chunks are now - // stored globally in the levelrenderer, in a hashmap with a special key made up from the dimension and chunk position (using same index - // as is used for global flags) -#if 1 - int key = levelRenderer->getGlobalIndexForChunk(this->x,this->y,this->z,level); - EnterCriticalSection(globalRenderableTileEntities_cs); - if( renderableTileEntities.size() ) - { - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - // We've got some renderable tile entities that we want associated with this chunk, and an existing list of things that used to be. - // We need to flag any that we don't need any more to be removed, keep those that we do, and add any new ones - - // First pass - flag everything already existing to be removed - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } - - // Now go through the current list. If these are already in the list, then unflag the remove flag. If they aren't, then add - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - AUTO_VAR(it2, find( it->second.begin(), it->second.end(), renderableTileEntities[i] )); - if( it2 == it->second.end() ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - else - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageKeep); - } - } - } - else - { - // Easy case - nothing already existing for this chunk. Add them all in. - for( int i = 0; i < renderableTileEntities.size(); i++ ) - { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); - } - } - } - else - { - // Another easy case - we don't want any renderable tile entities associated with this chunk. Flag all to be removed. - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) - { - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) - { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); - } - } - } - LeaveCriticalSection(globalRenderableTileEntities_cs); + g_rebuildDataIn.copyFromTesselator(); + intArray_SPU tesselatorArray( + (unsigned int*)g_rebuildDataIn.m_tesselator.m_PPUArray); + g_rebuildDataIn.m_tesselator._array = &tesselatorArray; + g_rebuildDataIn.m_currentLayer = currentLayer; +#ifdef TILE_RENDER_SPU + g_tileCompressDataIn.setForChunk(®ion, x0, y0, z0); + RunSPURebuild(); + g_rebuildDataOut.storeInTesselator(); + pOutData = &g_rebuildDataOut; #else - // Find the removed ones: + g_rebuildDataIn.disableUnseenTiles(); + TileRenderer_SPU* pTileRenderer = + new TileRenderer_SPU(&g_rebuildDataIn); + g_rebuildDataIn.tesselateAllTiles(pTileRenderer); + g_rebuildDataIn.storeInTesselator(); + pOutData = &g_rebuildDataIn; +#endif + if (pOutData->m_flags & ChunkRebuildData::e_flag_Rendered) + rendered = true; - // 4J - original code for this section: - /* - Set newTileEntities = new HashSet(); - newTileEntities.addAll(renderableTileEntities); - newTileEntities.removeAll(oldTileEntities); - globalRenderableTileEntities.addAll(newTileEntities); + // 4J - changed loop order here to leave y as the innermost loop for + // better cache performance + for (int z = z0; z < z1; z++) { + for (int x = x0; x < x1; x++) { + for (int y = y0; y < y1; y++) { + // 4J - get tile from those copied into our local array in + // earlier optimisation + unsigned char tileId = pOutData->getTile(x, y, z); + if (tileId > 0) { + if (currentLayer == 0 && + Tile::tiles[tileId]->isEntityTile()) { + std::shared_ptr et = + region.getTileEntity(x, y, z); + if (TileEntityRenderDispatcher::instance + ->hasRenderer(et)) { + renderableTileEntities.push_back(et); + } + } + int flags = pOutData->getFlags(x, y, z); + if (flags & + ChunkRebuildData::e_flag_SPURenderCodeMissing) { + Tile* tile = Tile::tiles[tileId]; + int renderLayer = tile->getRenderLayer(); - oldTileEntities.removeAll(renderableTileEntities); - globalRenderableTileEntities.removeAll(oldTileEntities); - */ - + if (renderLayer != currentLayer) { + // renderNextLayer + //= true; + } else if (renderLayer == currentLayer) { + // if(currentLayer == 0) + // numRenderedLayer0++; + rendered |= tileRenderer.tesselateInWorld( + tile, x, y, z); + } + } + } + } + } + } - std::unordered_set > newTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); - - AUTO_VAR(endIt, oldTileEntities.end()); - for( std::unordered_set >::iterator it = oldTileEntities.begin(); it != endIt; it++ ) - { - newTileEntities.erase(*it); - } + { + t->end(); + bounds.addBounds(t->bounds); + glPopMatrix(); + glEndList(); + t->useCompactVertices(false); // 4J added + t->offset(0, 0, 0); + } + if (rendered) { + levelRenderer->clearGlobalChunkFlag( + this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, currentLayer); + } else { + // 4J - added - clear any renderer data associated with this unused + // list + levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, + LevelRenderer::CHUNK_FLAG_EMPTY0, + currentLayer); + RenderManager.CBuffClear(lists + currentLayer); + } + } - // 4J - newTileEntities is now renderableTileEntities with any old ones from oldTileEntitesRemoved (so just new things added) + if (bb) { + bb->set(bounds.boundingBox[0], bounds.boundingBox[1], + bounds.boundingBox[2], bounds.boundingBox[3], + bounds.boundingBox[4], bounds.boundingBox[5]); + } - EnterCriticalSection(globalRenderableTileEntities_cs); - endIt = newTileEntities.end(); - for( std::unordered_set >::iterator it = newTileEntities.begin(); it != endIt; it++ ) - { - globalRenderableTileEntities.push_back(*it); - } + if (pOutData->m_flags & ChunkRebuildData::e_flag_TouchedSky) + LevelChunk::touchedSky = true; - // 4J - All these new things added to globalRenderableTileEntities + // 4J - have rewritten the way that tile entities are stored globally to + // make it work more easily with split screen. Chunks are now stored + // globally in the levelrenderer, in a hashmap with a special key made up + // from the dimension and chunk position (using same index as is used for + // global flags) +#if 1 + int key = + levelRenderer->getGlobalIndexForChunk(this->x, this->y, this->z, level); + EnterCriticalSection(globalRenderableTileEntities_cs); + if (renderableTileEntities.size()) { + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + // We've got some renderable tile entities that we want associated + // with this chunk, and an existing list of things that used to be. + // We need to flag any that we don't need any more to be removed, + // keep those that we do, and add any new ones - AUTO_VAR(endItRTE, renderableTileEntities.end()); - for( std::vector >::iterator it = renderableTileEntities.begin(); it != endItRTE; it++ ) - { - oldTileEntities.erase(*it); - } - // 4J - oldTileEntities is now the removed items - std::vector >::iterator it = globalRenderableTileEntities->begin(); - while( it != globalRenderableTileEntities->end() ) - { - if( oldTileEntities.find(*it) != oldTileEntities.end() ) - { - it = globalRenderableTileEntities->erase(it); - } - else - { - ++it; - } - } + // First pass - flag everything already existing to be removed + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } - LeaveCriticalSection(globalRenderableTileEntities_cs); + // Now go through the current list. If these are already in the + // list, then unflag the remove flag. If they aren't, then add + for (int i = 0; i < renderableTileEntities.size(); i++) { + AUTO_VAR(it2, find(it->second.begin(), it->second.end(), + renderableTileEntities[i])); + if (it2 == it->second.end()) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } else { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageKeep); + } + } + } else { + // Easy case - nothing already existing for this chunk. Add them all + // in. + for (int i = 0; i < renderableTileEntities.size(); i++) { + (*globalRenderableTileEntities)[key].push_back( + renderableTileEntities[i]); + } + } + } else { + // Another easy case - we don't want any renderable tile entities + // associated with this chunk. Flag all to be removed. + AUTO_VAR(it, globalRenderableTileEntities->find(key)); + if (it != globalRenderableTileEntities->end()) { + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + (*it2)->setRenderRemoveStage( + TileEntity::e_RenderRemoveStageFlaggedAtChunk); + } + } + } + LeaveCriticalSection(globalRenderableTileEntities_cs); +#else + // Find the removed ones: + + // 4J - original code for this section: + /* + Set newTileEntities = new HashSet(); + newTileEntities.addAll(renderableTileEntities); + newTileEntities.removeAll(oldTileEntities); + globalRenderableTileEntities.addAll(newTileEntities); + + oldTileEntities.removeAll(renderableTileEntities); + globalRenderableTileEntities.removeAll(oldTileEntities); + */ + + std::unordered_set > newTileEntities( + renderableTileEntities.begin(), renderableTileEntities.end()); + + AUTO_VAR(endIt, oldTileEntities.end()); + for (std::unordered_set >::iterator it = + oldTileEntities.begin(); + it != endIt; it++) { + newTileEntities.erase(*it); + } + + // 4J - newTileEntities is now renderableTileEntities with any old ones from + // oldTileEntitesRemoved (so just new things added) + + EnterCriticalSection(globalRenderableTileEntities_cs); + endIt = newTileEntities.end(); + for (std::unordered_set >::iterator it = + newTileEntities.begin(); + it != endIt; it++) { + globalRenderableTileEntities.push_back(*it); + } + + // 4J - All these new things added to globalRenderableTileEntities + + AUTO_VAR(endItRTE, renderableTileEntities.end()); + for (std::vector >::iterator it = + renderableTileEntities.begin(); + it != endItRTE; it++) { + oldTileEntities.erase(*it); + } + // 4J - oldTileEntities is now the removed items + std::vector >::iterator it = + globalRenderableTileEntities->begin(); + while (it != globalRenderableTileEntities->end()) { + if (oldTileEntities.find(*it) != oldTileEntities.end()) { + it = globalRenderableTileEntities->erase(it); + } else { + ++it; + } + } + + LeaveCriticalSection(globalRenderableTileEntities_cs); #endif - // 4J - These removed items are now also removed from globalRenderableTileEntities - - if( LevelChunk::touchedSky ) - { - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - else - { - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); - } - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_COMPILED); - return; + // 4J - These removed items are now also removed from + // globalRenderableTileEntities + if (LevelChunk::touchedSky) { + levelRenderer->clearGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } else { + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_NOTSKYLIT); + } + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_COMPILED); + return; } -#endif // _PS3_ +#endif // _PS3_ - -float Chunk::distanceToSqr(std::shared_ptr player) const -{ - float xd = (float) (player->x - xm); - float yd = (float) (player->y - ym); - float zd = (float) (player->z - zm); - return xd * xd + yd * yd + zd * zd; +float Chunk::distanceToSqr(std::shared_ptr player) const { + float xd = (float)(player->x - xm); + float yd = (float)(player->y - ym); + float zd = (float)(player->z - zm); + return xd * xd + yd * yd + zd * zd; } -float Chunk::squishedDistanceToSqr(std::shared_ptr player) -{ - float xd = (float) (player->x - xm); - float yd = (float) (player->y - ym) * 2; - float zd = (float) (player->z - zm); - return xd * xd + yd * yd + zd * zd; +float Chunk::squishedDistanceToSqr(std::shared_ptr player) { + float xd = (float)(player->x - xm); + float yd = (float)(player->y - ym) * 2; + float zd = (float)(player->z - zm); + return xd * xd + yd * yd + zd * zd; } -void Chunk::reset() -{ - if( assigned ) - { - EnterCriticalSection(&levelRenderer->m_csDirtyChunks); - unsigned char refCount = levelRenderer->decGlobalChunkRefCount(x, y, z, level); - assigned = false; -// printf("\t\t [dec] refcount %d at %d, %d, %d\n",refCount,x,y,z); - if( refCount == 0 ) - { - int lists = levelRenderer->getGlobalIndexForChunk(x, y, z, level) * 2; - if(lists >= 0) - { - lists += levelRenderer->chunkLists; - for (int i = 0; i < 2; i++) - { - // 4J - added - clear any renderer data associated with this unused list - RenderManager.CBuffClear(lists + i); - } - levelRenderer->setGlobalChunkFlags(x, y, z, level, 0); - } - } - LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); - } +void Chunk::reset() { + if (assigned) { + EnterCriticalSection(&levelRenderer->m_csDirtyChunks); + unsigned char refCount = + levelRenderer->decGlobalChunkRefCount(x, y, z, level); + assigned = false; + // printf("\t\t [dec] refcount %d at %d, %d, + //%d\n",refCount,x,y,z); + if (refCount == 0) { + int lists = + levelRenderer->getGlobalIndexForChunk(x, y, z, level) * 2; + if (lists >= 0) { + lists += levelRenderer->chunkLists; + for (int i = 0; i < 2; i++) { + // 4J - added - clear any renderer data associated with this + // unused list + RenderManager.CBuffClear(lists + i); + } + levelRenderer->setGlobalChunkFlags(x, y, z, level, 0); + } + } + LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); + } - clipChunk->visible = false; + clipChunk->visible = false; } -void Chunk::_delete() -{ - reset(); - level = NULL; +void Chunk::_delete() { + reset(); + level = NULL; } -int Chunk::getList(int layer) -{ - if (!clipChunk->visible) return -1; +int Chunk::getList(int layer) { + if (!clipChunk->visible) return -1; - int lists = levelRenderer->getGlobalIndexForChunk(x, y, z,level) * 2; - lists += levelRenderer->chunkLists; + int lists = levelRenderer->getGlobalIndexForChunk(x, y, z, level) * 2; + lists += levelRenderer->chunkLists; - bool empty = levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); - if (!empty) return lists + layer; - return -1; + bool empty = levelRenderer->getGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); + if (!empty) return lists + layer; + return -1; } -void Chunk::cull(Culler *culler) -{ - clipChunk->visible = culler->isVisible(bb); +void Chunk::cull(Culler* culler) { clipChunk->visible = culler->isVisible(bb); } + +void Chunk::renderBB() { + // glCallList(lists + 2); // 4J - removed - TODO put back in } -void Chunk::renderBB() -{ -// glCallList(lists + 2); // 4J - removed - TODO put back in +bool Chunk::isEmpty() { + if (!levelRenderer->getGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_COMPILED)) + return false; + return levelRenderer->getGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTYBOTH); } -bool Chunk::isEmpty() -{ - if (!levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_COMPILED)) return false; - return levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTYBOTH); +void Chunk::setDirty() { + // 4J - not used, but if this starts being used again then we'll need to + // investigate how best to handle it. + __debugbreak(); + levelRenderer->setGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_DIRTY); } -void Chunk::setDirty() -{ - // 4J - not used, but if this starts being used again then we'll need to investigate how best to handle it. - __debugbreak(); - levelRenderer->setGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_DIRTY); -} - -void Chunk::clearDirty() -{ - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_DIRTY); +void Chunk::clearDirty() { + levelRenderer->clearGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_DIRTY); #ifdef _CRITICAL_CHUNKS - levelRenderer->clearGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_CRITICAL); + levelRenderer->clearGlobalChunkFlag(x, y, z, level, + LevelRenderer::CHUNK_FLAG_CRITICAL); #endif } -Chunk::~Chunk() -{ - delete bb; -} +Chunk::~Chunk() { delete bb; } -bool Chunk::emptyFlagSet(int layer) -{ - return levelRenderer->getGlobalChunkFlag(x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); +bool Chunk::emptyFlagSet(int layer) { + return levelRenderer->getGlobalChunkFlag( + x, y, z, level, LevelRenderer::CHUNK_FLAG_EMPTY0, layer); } diff --git a/Minecraft.Client/Rendering/Chunk.h b/Minecraft.Client/Rendering/Chunk.h index efcdfc914..23d5ef532 100644 --- a/Minecraft.Client/Rendering/Chunk.h +++ b/Minecraft.Client/Rendering/Chunk.h @@ -8,80 +8,85 @@ class Level; class TileEntity; class Entity; - -class ClipChunk -{ +class ClipChunk { public: - Chunk *chunk; - int globalIdx; - bool visible; - float aabb[6]; - int xm, ym, zm; + Chunk* chunk; + int globalIdx; + bool visible; + float aabb[6]; + int xm, ym, zm; }; -class Chunk -{ +class Chunk { private: - static const int XZSIZE = LevelRenderer::CHUNK_XZSIZE; - static const int SIZE = LevelRenderer::CHUNK_SIZE; + static const int XZSIZE = LevelRenderer::CHUNK_XZSIZE; + static const int SIZE = LevelRenderer::CHUNK_SIZE; public: - Level *level; - static LevelRenderer *levelRenderer; + Level* level; + static LevelRenderer* levelRenderer; + private: #ifndef _LARGE_WORLDS - static Tesselator *t; + static Tesselator* t; #else - static unsigned int tlsIdx; + static unsigned int tlsIdx; + public: - static void CreateNewThreadStorage(); - static void ReleaseThreadStorage(); - static unsigned char *GetTileIdsStorage(); + static void CreateNewThreadStorage(); + static void ReleaseThreadStorage(); + static unsigned char* GetTileIdsStorage(); #endif - + public: - static int updates; + static int updates; int x, y, z; int xRender, yRender, zRender; int xRenderOffs, yRenderOffs, zRenderOffs; - + int xm, ym, zm; - AABB *bb; - ClipChunk *clipChunk; + AABB* bb; + ClipChunk* clipChunk; int id; -//public: -// std::vector > renderableTileEntities; // 4J - removed - + // public: + // std::vector > renderableTileEntities; + //// 4J - removed + private: - LevelRenderer::rteMap *globalRenderableTileEntities; - CRITICAL_SECTION *globalRenderableTileEntities_cs; - bool assigned; + LevelRenderer::rteMap* globalRenderableTileEntities; + CRITICAL_SECTION* globalRenderableTileEntities_cs; + bool assigned; + public: - Chunk(Level *level, LevelRenderer::rteMap &globalRenderableTileEntities, CRITICAL_SECTION &globalRenderableTileEntities_cs, int x, int y, int z, ClipChunk *clipChunk); - Chunk(); + Chunk(Level* level, LevelRenderer::rteMap& globalRenderableTileEntities, + CRITICAL_SECTION& globalRenderableTileEntities_cs, int x, int y, + int z, ClipChunk* clipChunk); + Chunk(); void setPos(int x, int y, int z); + private: - void translateToPos(); + void translateToPos(); + public: - void makeCopyForRebuild(Chunk *source); - void rebuild(); + void makeCopyForRebuild(Chunk* source); + void rebuild(); #ifdef __PS3__ - void rebuild_SPU(); -#endif // __PS3__ - float distanceToSqr(std::shared_ptr player) const; + void rebuild_SPU(); +#endif // __PS3__ + float distanceToSqr(std::shared_ptr player) const; float squishedDistanceToSqr(std::shared_ptr player); void reset(); void _delete(); int getList(int layer); - void cull(Culler *culler); - void renderBB() ; + void cull(Culler* culler); + void renderBB(); bool isEmpty(); void setDirty(); - void clearDirty(); // 4J added - bool emptyFlagSet(int layer); - ~Chunk(); + void clearDirty(); // 4J added + bool emptyFlagSet(int layer); + ~Chunk(); }; diff --git a/Minecraft.Client/Rendering/Cube.cpp b/Minecraft.Client/Rendering/Cube.cpp index e3124c41f..259eb9cac 100644 --- a/Minecraft.Client/Rendering/Cube.cpp +++ b/Minecraft.Client/Rendering/Cube.cpp @@ -3,35 +3,35 @@ #include "Models/ModelPart.h" #include "Cube.h" - - // 4J - added - helper function to set up vertex arrays -VertexArray Cube::VertexArray4(Vertex *v0, Vertex *v1, Vertex *v2, Vertex *v3) -{ - VertexArray ret = VertexArray(4); - ret[0] = v0; - ret[1] = v1; - ret[2] = v2; - ret[3] = v3; +VertexArray Cube::VertexArray4(Vertex* v0, Vertex* v1, Vertex* v2, Vertex* v3) { + VertexArray ret = VertexArray(4); + ret[0] = v0; + ret[1] = v1; + ret[2] = v2; + ret[3] = v3; - return ret; + return ret; } -//void Cube::addBox(float x0, float y0, float z0, int w, int h, int d, float g) -Cube::Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, float z0, int w, int h, int d, float g, int faceMask /* = 63 */, bool bFlipPoly3UVs) : // 4J - added faceMask, added bFlipPoly3UVs to reverse the uvs back so player skins display right - x0(x0), - y0(y0), - z0(z0), - x1(x0 + w), - y1(y0 + h), - z1(z0 + d) -{ -// this->x0 = x0; -// this->y0 = y0; -// this->z0 = z0; -// this->x1 = x0 + w; -// this->y1 = y0 + h; -// this->z1 = z0 + d; +// void Cube::addBox(float x0, float y0, float z0, int w, int h, int d, float g) +Cube::Cube(ModelPart* modelPart, int xTexOffs, int yTexOffs, float x0, float y0, + float z0, int w, int h, int d, float g, int faceMask /* = 63 */, + bool bFlipPoly3UVs) + : // 4J - added faceMask, added bFlipPoly3UVs to reverse the uvs back so + // player skins display right + x0(x0), + y0(y0), + z0(z0), + x1(x0 + w), + y1(y0 + h), + z1(z0 + d) { + // this->x0 = x0; + // this->y0 = y0; + // this->z0 = z0; + // this->x1 = x0 + w; + // this->y1 = y0 + h; + // this->z1 = z0 + d; vertices = VertexArray(8); polygons = PolygonArray(6); @@ -47,22 +47,21 @@ Cube::Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, y1 += g; z1 += g; - if (modelPart->bMirror) - { + if (modelPart->bMirror) { float tmp = x1; x1 = x0; x0 = tmp; } - Vertex *u0 = new Vertex(x0, y0, z0, 0, 0); - Vertex *u1 = new Vertex(x1, y0, z0, 0, 8); - Vertex *u2 = new Vertex(x1, y1, z0, 8, 8); - Vertex *u3 = new Vertex(x0, y1, z0, 8, 0); - - Vertex *l0 = new Vertex(x0, y0, z1, 0, 0); - Vertex *l1 = new Vertex(x1, y0, z1, 0, 8); - Vertex *l2 = new Vertex(x1, y1, z1, 8, 8); - Vertex *l3 = new Vertex(x0, y1, z1, 8, 0); + Vertex* u0 = new Vertex(x0, y0, z0, 0, 0); + Vertex* u1 = new Vertex(x1, y0, z0, 0, 8); + Vertex* u2 = new Vertex(x1, y1, z0, 8, 8); + Vertex* u3 = new Vertex(x0, y1, z0, 8, 0); + + Vertex* l0 = new Vertex(x0, y0, z1, 0, 0); + Vertex* l1 = new Vertex(x1, y0, z1, 0, 8); + Vertex* l2 = new Vertex(x1, y1, z1, 8, 8); + Vertex* l3 = new Vertex(x0, y1, z1, 8, 0); vertices[0] = u0; vertices[1] = u1; @@ -73,41 +72,61 @@ Cube::Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, vertices[6] = l2; vertices[7] = l3; - // 4J - added ability to mask individual faces - int faceCount = 0; - if( faceMask & 1 ) polygons[faceCount++] = new _Polygon(VertexArray4(l1, u1, u2, l2), xTexOffs + d + w, yTexOffs + d, xTexOffs + d + w + d, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Right - if( faceMask & 2 ) polygons[faceCount++] = new _Polygon(VertexArray4(u0, l0, l3, u3), xTexOffs + 0, yTexOffs + d, xTexOffs + d, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Left - if( faceMask & 4 ) polygons[faceCount++] = new _Polygon(VertexArray4(l1, l0, u0, u1), xTexOffs + d, yTexOffs + 0, xTexOffs + d + w, yTexOffs + d, modelPart->xTexSize, modelPart->yTexSize); // Up - if(bFlipPoly3UVs) - { - if( faceMask & 8 ) polygons[faceCount++] = new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, yTexOffs + 0, xTexOffs + d + w + w, yTexOffs + d, modelPart->xTexSize, modelPart->yTexSize); // Down - } - else - { - if( faceMask & 8 ) polygons[faceCount++] = new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, yTexOffs + d, xTexOffs + d + w + w, yTexOffs + 0, modelPart->xTexSize, modelPart->yTexSize); // Down - } - if( faceMask & 16 ) polygons[faceCount++] = new _Polygon(VertexArray4(u1, u0, u3, u2), xTexOffs + d, yTexOffs + d, xTexOffs + d + w, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Front - if( faceMask & 32 ) polygons[faceCount++] = new _Polygon(VertexArray4(l0, l1, l2, l3), xTexOffs + d + w + d, yTexOffs + d, xTexOffs + d + w + d + w, yTexOffs + d + h, modelPart->xTexSize, modelPart->yTexSize); // Back - polygons.length = faceCount; + // 4J - added ability to mask individual faces + int faceCount = 0; + if (faceMask & 1) + polygons[faceCount++] = + new _Polygon(VertexArray4(l1, u1, u2, l2), xTexOffs + d + w, + yTexOffs + d, xTexOffs + d + w + d, yTexOffs + d + h, + modelPart->xTexSize, modelPart->yTexSize); // Right + if (faceMask & 2) + polygons[faceCount++] = + new _Polygon(VertexArray4(u0, l0, l3, u3), xTexOffs + 0, + yTexOffs + d, xTexOffs + d, yTexOffs + d + h, + modelPart->xTexSize, modelPart->yTexSize); // Left + if (faceMask & 4) + polygons[faceCount++] = + new _Polygon(VertexArray4(l1, l0, u0, u1), xTexOffs + d, + yTexOffs + 0, xTexOffs + d + w, yTexOffs + d, + modelPart->xTexSize, modelPart->yTexSize); // Up + if (bFlipPoly3UVs) { + if (faceMask & 8) + polygons[faceCount++] = + new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, + yTexOffs + 0, xTexOffs + d + w + w, yTexOffs + d, + modelPart->xTexSize, modelPart->yTexSize); // Down + } else { + if (faceMask & 8) + polygons[faceCount++] = + new _Polygon(VertexArray4(u2, u3, l3, l2), xTexOffs + d + w, + yTexOffs + d, xTexOffs + d + w + w, yTexOffs + 0, + modelPart->xTexSize, modelPart->yTexSize); // Down + } + if (faceMask & 16) + polygons[faceCount++] = + new _Polygon(VertexArray4(u1, u0, u3, u2), xTexOffs + d, + yTexOffs + d, xTexOffs + d + w, yTexOffs + d + h, + modelPart->xTexSize, modelPart->yTexSize); // Front + if (faceMask & 32) + polygons[faceCount++] = new _Polygon( + VertexArray4(l0, l1, l2, l3), xTexOffs + d + w + d, yTexOffs + d, + xTexOffs + d + w + d + w, yTexOffs + d + h, modelPart->xTexSize, + modelPart->yTexSize); // Back + polygons.length = faceCount; - if (modelPart->bMirror) - { + if (modelPart->bMirror) { for (unsigned int i = 0; i < polygons.length; i++) polygons[i]->mirror(); } } - -void Cube::render(Tesselator *t,float scale) -{ - for (int i = 0; i < polygons.length; i++) - { - polygons[i]->render(t, scale); - } +void Cube::render(Tesselator* t, float scale) { + for (int i = 0; i < polygons.length; i++) { + polygons[i]->render(t, scale); + } } -Cube *Cube::setId(const std::wstring &id) -{ - this->id = id; - return this; +Cube* Cube::setId(const std::wstring& id) { + this->id = id; + return this; } diff --git a/Minecraft.Client/Rendering/Cube.h b/Minecraft.Client/Rendering/Cube.h index eafa57ba5..549672e45 100644 --- a/Minecraft.Client/Rendering/Cube.h +++ b/Minecraft.Client/Rendering/Cube.h @@ -5,25 +5,25 @@ class Model; -class Cube -{ - +class Cube { private: - VertexArray vertices; + VertexArray vertices; PolygonArray polygons; - -public: - - const float x0, y0, z0, x1, y1, z1; - std::wstring id; public: - Cube(ModelPart *modelPart, int xTexOffs, int yTexOffs, float x0, float y0, float z0, int w, int h, int d, float g, int faceMask = 63, bool bFlipPoly3UVs = false); // 4J - added faceMask + const float x0, y0, z0, x1, y1, z1; + std::wstring id; + +public: + Cube(ModelPart* modelPart, int xTexOffs, int yTexOffs, float x0, float y0, + float z0, int w, int h, int d, float g, int faceMask = 63, + bool bFlipPoly3UVs = false); // 4J - added faceMask private: - VertexArray VertexArray4(Vertex *v0, Vertex *v1, Vertex *v2, Vertex *v3); // 4J added + VertexArray VertexArray4(Vertex* v0, Vertex* v1, Vertex* v2, + Vertex* v3); // 4J added public: - void render(Tesselator *t,float scale); - Cube *setId(const std::wstring &id); + void render(Tesselator* t, float scale); + Cube* setId(const std::wstring& id); }; diff --git a/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp b/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp index f72d825e2..87ef63f07 100644 --- a/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp +++ b/Minecraft.Client/Rendering/Culling/AllowAllCuller.cpp @@ -1,21 +1,16 @@ #include "../../Platform/stdafx.h" -#include "AllowAllCuller.h" +#include "AllowAllCuller.h" -bool AllowAllCuller::isVisible(AABB *bb) -{ - return true; +bool AllowAllCuller::isVisible(AABB* bb) { return true; } + +bool AllowAllCuller::cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) { + return true; } -bool AllowAllCuller::cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return true; +bool AllowAllCuller::cubeFullyInFrustum(double x0, double y0, double z0, + double x1, double y1, double z1) { + return true; } -bool AllowAllCuller::cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return true; -} - -void AllowAllCuller::prepare(double xOff, double yOff, double zOff) -{ -} \ No newline at end of file +void AllowAllCuller::prepare(double xOff, double yOff, double zOff) {} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/AllowAllCuller.h b/Minecraft.Client/Rendering/Culling/AllowAllCuller.h index 5b866049e..3851d6114 100644 --- a/Minecraft.Client/Rendering/Culling/AllowAllCuller.h +++ b/Minecraft.Client/Rendering/Culling/AllowAllCuller.h @@ -1,11 +1,12 @@ #pragma once #include "Culler.h" -class AllowAllCuller -{ +class AllowAllCuller { public: - virtual bool isVisible(AABB *bb); - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual void prepare(double xOff, double yOff, double zOff); + virtual bool isVisible(AABB* bb); + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual void prepare(double xOff, double yOff, double zOff); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/Culler.h b/Minecraft.Client/Rendering/Culling/Culler.h index 83ab87ef0..a84da40c9 100644 --- a/Minecraft.Client/Rendering/Culling/Culler.h +++ b/Minecraft.Client/Rendering/Culling/Culler.h @@ -1,11 +1,12 @@ #pragma once #include "../../../Minecraft.World/Util/AABB.h" -class Culler -{ +class Culler { public: - virtual bool isVisible(AABB *bb) = 0; - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) = 0; - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) = 0; - virtual void prepare(double xOff, double yOff, double zOff) = 0; + virtual bool isVisible(AABB* bb) = 0; + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) = 0; + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) = 0; + virtual void prepare(double xOff, double yOff, double zOff) = 0; }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp index a93002c59..cfb90360b 100644 --- a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp +++ b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.cpp @@ -3,14 +3,14 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../Chunk.h" -DirtyChunkSorter::DirtyChunkSorter(std::shared_ptr cameraEntity, int playerIndex) // 4J - added player index +DirtyChunkSorter::DirtyChunkSorter(std::shared_ptr cameraEntity, + int playerIndex) // 4J - added player index { - this->cameraEntity = cameraEntity; - this->playerIndex = playerIndex; + this->cameraEntity = cameraEntity; + this->playerIndex = playerIndex; } -bool DirtyChunkSorter::operator()(const Chunk *c0, const Chunk *c1) const -{ +bool DirtyChunkSorter::operator()(const Chunk* c0, const Chunk* c1) const { bool i0 = c0->clipChunk->visible; bool i1 = c1->clipChunk->visible; if (i0 && !i1) return false; @@ -22,5 +22,5 @@ bool DirtyChunkSorter::operator()(const Chunk *c0, const Chunk *c1) const if (d0 < d1) return false; if (d0 > d1) return true; - return c0->id >= c1->id; // 4J - was c0.id < c1.id ? 1 : -1 + return c0->id >= c1->id; // 4J - was c0.id < c1.id ? 1 : -1 } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h index 0de6efda3..523a8754e 100644 --- a/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h +++ b/Minecraft.Client/Rendering/Culling/DirtyChunkSorter.h @@ -2,13 +2,13 @@ class Chunk; class Mob; -class DirtyChunkSorter -{ +class DirtyChunkSorter { private: - std::shared_ptr cameraEntity; - int playerIndex; // 4J added + std::shared_ptr cameraEntity; + int playerIndex; // 4J added public: - DirtyChunkSorter(std::shared_ptr cameraEntity, int playerIndex); // 4J - added player index - bool operator()(const Chunk *a, const Chunk *b) const; + DirtyChunkSorter(std::shared_ptr cameraEntity, + int playerIndex); // 4J - added player index + bool operator()(const Chunk* a, const Chunk* b) const; }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp index f67380a0a..09ff30e06 100644 --- a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp +++ b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.cpp @@ -3,22 +3,22 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../Chunk.h" -DistanceChunkSorter::DistanceChunkSorter(std::shared_ptr player) -{ +DistanceChunkSorter::DistanceChunkSorter(std::shared_ptr player) { ix = -player->x; iy = -player->y; iz = -player->z; } -bool DistanceChunkSorter::operator()(const Chunk *c0, const Chunk *c1) const -{ +bool DistanceChunkSorter::operator()(const Chunk* c0, const Chunk* c1) const { double xd0 = c0->xm + ix; double yd0 = c0->ym + iy; double zd0 = c0->zm + iz; - + double xd1 = c1->xm + ix; double yd1 = c1->ym + iy; double zd1 = c1->zm + iz; - return (((xd0 * xd0 + yd0 * yd0 + zd0 * zd0) - (xd1 * xd1 + yd1 * yd1 + zd1 * zd1)) * 1024) < 0.0; + return (((xd0 * xd0 + yd0 * yd0 + zd0 * zd0) - + (xd1 * xd1 + yd1 * yd1 + zd1 * zd1)) * + 1024) < 0.0; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h index 461ec79a1..2557d9ece 100644 --- a/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h +++ b/Minecraft.Client/Rendering/Culling/DistanceChunkSorter.h @@ -2,12 +2,11 @@ class Entity; class Chunk; -class DistanceChunkSorter -{ +class DistanceChunkSorter { private: - double ix, iy, iz; + double ix, iy, iz; public: DistanceChunkSorter(std::shared_ptr player); - bool operator()(const Chunk *a, const Chunk *b) const; + bool operator()(const Chunk* a, const Chunk* b) const; }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp b/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp index 8c6d5beb5..7b07efaaf 100644 --- a/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp +++ b/Minecraft.Client/Rendering/Culling/ViewportCuller.cpp @@ -2,98 +2,96 @@ #include "ViewportCuller.h" #include "../../../Minecraft.World/Util/Mth.h" -ViewportCuller::Face::Face(double x, double y, double z, float yRot, float xRot) -{ +ViewportCuller::Face::Face(double x, double y, double z, float yRot, + float xRot) { this->xc = x; this->yc = y; this->zc = z; - + xd = Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); zd = -Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); yd = -Mth::sin(xRot / 180 * PI); - - cullOffs = xc*xd+yc*yd+zc*zd; -} - -bool ViewportCuller::Face::inFront(double x, double y, double z, double r) -{ - return x*xd+y*yd+z*zd>cullOffs-r; + + cullOffs = xc * xd + yc * yd + zc * zd; } -bool ViewportCuller::Face::inFront(double x0, double y0, double z0, double x1, double y1, double z1) -{ - if ( - x0*xd+y0*yd+z0*zd>cullOffs || - x1*xd+y0*yd+z0*zd>cullOffs || - x0*xd+y1*yd+z0*zd>cullOffs || - x1*xd+y1*yd+z0*zd>cullOffs || - x0*xd+y0*yd+z1*zd>cullOffs || - x1*xd+y0*yd+z1*zd>cullOffs || - x0*xd+y1*yd+z1*zd>cullOffs || - x1*xd+y1*yd+z1*zd>cullOffs - ) return true; +bool ViewportCuller::Face::inFront(double x, double y, double z, double r) { + return x * xd + y * yd + z * zd > cullOffs - r; +} + +bool ViewportCuller::Face::inFront(double x0, double y0, double z0, double x1, + double y1, double z1) { + if (x0 * xd + y0 * yd + z0 * zd > cullOffs || + x1 * xd + y0 * yd + z0 * zd > cullOffs || + x0 * xd + y1 * yd + z0 * zd > cullOffs || + x1 * xd + y1 * yd + z0 * zd > cullOffs || + x0 * xd + y0 * yd + z1 * zd > cullOffs || + x1 * xd + y0 * yd + z1 * zd > cullOffs || + x0 * xd + y1 * yd + z1 * zd > cullOffs || + x1 * xd + y1 * yd + z1 * zd > cullOffs) + return true; return false; } -bool ViewportCuller::Face::fullyInFront(double x0, double y0, double z0, double x1, double y1, double z1) -{ - if ( x0*xd+y0*yd+z0*zd mob, double fogDistance, float a) -{ - float yRot = mob->yRotO+(mob->yRot-mob->yRotO)*a; - float xRot = mob->xRotO+(mob->xRot-mob->xRotO)*a; - - double x = mob->xOld+(mob->x-mob->xOld)*a; - double y = mob->yOld+(mob->y-mob->yOld)*a; - double z = mob->zOld+(mob->z-mob->zOld)*a; +ViewportCuller::ViewportCuller(std::shared_ptr mob, double fogDistance, + float a) { + float yRot = mob->yRotO + (mob->yRot - mob->yRotO) * a; + float xRot = mob->xRotO + (mob->xRot - mob->xRotO) * a; - double xd = Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); - double zd = -Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); - double yd = -Mth::sin(xRot / 180 * PI); + double x = mob->xOld + (mob->x - mob->xOld) * a; + double y = mob->yOld + (mob->y - mob->yOld) * a; + double z = mob->zOld + (mob->z - mob->zOld) * a; - float xFov = 30; - float yFov = 45; - faces[0] = Face(x, y, z, yRot, xRot); - faces[1] = Face(x, y, z, yRot+xFov, xRot); - faces[2] = Face(x, y, z, yRot-xFov, xRot); - faces[3] = Face(x, y, z, yRot, xRot+yFov); - faces[4] = Face(x, y, z, yRot, xRot-yFov); - faces[5] = Face(x+xd*fogDistance, y+yd*fogDistance, z+zd*fogDistance, yRot+180, -xRot); + double xd = Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); + double zd = -Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI); + double yd = -Mth::sin(xRot / 180 * PI); + + float xFov = 30; + float yFov = 45; + faces[0] = Face(x, y, z, yRot, xRot); + faces[1] = Face(x, y, z, yRot + xFov, xRot); + faces[2] = Face(x, y, z, yRot - xFov, xRot); + faces[3] = Face(x, y, z, yRot, xRot + yFov); + faces[4] = Face(x, y, z, yRot, xRot - yFov); + faces[5] = Face(x + xd * fogDistance, y + yd * fogDistance, + z + zd * fogDistance, yRot + 180, -xRot); } -bool ViewportCuller::isVisible(AABB bb) -{ - return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); +bool ViewportCuller::isVisible(AABB bb) { + return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); } -bool ViewportCuller::cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - x0-=xOff; - y0-=yOff; - z0-=zOff; - x1-=xOff; - y1-=yOff; - z1-=zOff; - double xd = (x1-x0)/2.0f; - double yd = (y1-y0)/2.0f; - double zd = (z1-z0)/2.0f; - - double xc = x0+xd; - double yc = y0+yd; - double zc = z0+zd; - double r = _max(xd, yd, zd)*1.5f; - +bool ViewportCuller::cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) { + x0 -= xOff; + y0 -= yOff; + z0 -= zOff; + x1 -= xOff; + y1 -= yOff; + z1 -= zOff; + double xd = (x1 - x0) / 2.0f; + double yd = (y1 - y0) / 2.0f; + double zd = (z1 - z0) / 2.0f; + + double xc = x0 + xd; + double yc = y0 + yd; + double zc = z0 + zd; + double r = _max(xd, yd, zd) * 1.5f; + if (!faces[0].inFront(xc, yc, zc, r)) return false; if (!faces[1].inFront(xc, yc, zc, r)) return false; if (!faces[2].inFront(xc, yc, zc, r)) return false; @@ -108,26 +106,25 @@ bool ViewportCuller::cubeInFrustum(double x0, double y0, double z0, double x1, d if (!faces[4].inFront(x0, y0, z0, x1, y1, z1)) return false; if (!faces[5].inFront(x0, y0, z0, x1, y1, z1)) return false; return true; - } -bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - x0-=xOff; - y0-=yOff; - z0-=zOff; - x1-=xOff; - y1-=yOff; - z1-=zOff; +bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, + double x1, double y1, double z1) { + x0 -= xOff; + y0 -= yOff; + z0 -= zOff; + x1 -= xOff; + y1 -= yOff; + z1 -= zOff; - double xd = (x1-x0)/2.0f; - double yd = (y1-y0)/2.0f; - double zd = (z1-z0)/2.0f; - - double xc = x0+xd; - double yc = y0+yd; - double zc = z0+zd; - double r = _max(xd, yd, zd)*1.5f; + double xd = (x1 - x0) / 2.0f; + double yd = (y1 - y0) / 2.0f; + double zd = (z1 - z0) / 2.0f; + + double xc = x0 + xd; + double yc = y0 + yd; + double zc = z0 + zd; + double r = _max(xd, yd, zd) * 1.5f; if (!faces[0].inFront(xc, yc, zc, r)) return false; if (!faces[1].inFront(xc, yc, zc, r)) return false; @@ -135,8 +132,7 @@ bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, double if (!faces[3].inFront(xc, yc, zc, r)) return false; if (!faces[4].inFront(xc, yc, zc, r)) return false; if (!faces[5].inFront(xc, yc, zc, r)) return false; - - + if (!faces[0].fullyInFront(x0, y0, z0, x1, y1, z1)) return false; if (!faces[1].fullyInFront(x0, y0, z0, x1, y1, z1)) return false; if (!faces[2].fullyInFront(x0, y0, z0, x1, y1, z1)) return false; @@ -146,13 +142,11 @@ bool ViewportCuller::cubeFullyInFrustum(double x0, double y0, double z0, double return true; } -double ViewportCuller::_max(double a, double b, double c) -{ - return (a>b?a>c?c:a:b>c?b:c); +double ViewportCuller::_max(double a, double b, double c) { + return (a > b ? a > c ? c : a : b > c ? b : c); } -void ViewportCuller::prepare(double xOff, double yOff, double zOff) -{ +void ViewportCuller::prepare(double xOff, double yOff, double zOff) { this->xOff = xOff; this->yOff = yOff; this->zOff = zOff; diff --git a/Minecraft.Client/Rendering/Culling/ViewportCuller.h b/Minecraft.Client/Rendering/Culling/ViewportCuller.h index 251f17130..0d634f9b1 100644 --- a/Minecraft.Client/Rendering/Culling/ViewportCuller.h +++ b/Minecraft.Client/Rendering/Culling/ViewportCuller.h @@ -3,33 +3,41 @@ #include "../../../Minecraft.World/Entities/Mob.h" class Mob; -class ViewportCuller : public Culler -{ +class ViewportCuller : public Culler { private: - class Face - { - private: + class Face { + private: double xc, yc, zc; double xd, yd, zd; double cullOffs; - public: - Face() {} // 4J - added so we can declare an array of these (unitialised) in the class - Face(double x, double y, double z, float yRot, float xRot); + + public: + Face() {} // 4J - added so we can declare an array of these + // (unitialised) in the class + Face(double x, double y, double z, float yRot, float xRot); bool inFront(double x, double y, double z, double r); - bool inFront(double x0, double y0, double z0, double x1, double y1, double z1); - bool fullyInFront(double x0, double y0, double z0, double x1, double y1, double z1); + bool inFront(double x0, double y0, double z0, double x1, double y1, + double z1); + bool fullyInFront(double x0, double y0, double z0, double x1, double y1, + double z1); }; private: - Face faces[6]; + Face faces[6]; double xOff, yOff, zOff; + public: - ViewportCuller(std::shared_ptr mob, double fogDistance, float a); + ViewportCuller(std::shared_ptr mob, double fogDistance, float a); virtual bool isVisible(AABB bb); - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + private: - double _max(double a, double b, double c); // 4J - renamed from _max due to #define conflict in stdlib + double _max( + double a, double b, + double c); // 4J - renamed from _max due to #define conflict in stdlib public: virtual void prepare(double xOff, double yOff, double zOff); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp index 85d475925..83d7764e5 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.cpp @@ -3,29 +3,34 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.projectile.h" #include "../../../Minecraft.World/Util/Mth.h" -void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Arrow rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr arrow = std::dynamic_pointer_cast(_arrow); - bindTexture(TN_ITEM_ARROWS); // 4J - was L"/item/arrows.png" +void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Arrow rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr arrow = std::dynamic_pointer_cast(_arrow); + bindTexture(TN_ITEM_ARROWS); // 4J - was L"/item/arrows.png" glPushMatrix(); - float yRot = arrow->yRot; - float xRot = arrow->xRot; - float yRotO = arrow->yRotO; - float xRotO = arrow->xRotO; - if( ( yRot - yRotO ) > 180.0f ) yRot -= 360.0f; - else if( ( yRot - yRotO ) < -180.0f ) yRot += 360.0f; - if( ( xRot - xRotO ) > 180.0f ) xRot -= 360.0f; - else if( ( xRot - xRotO ) < -180.0f ) xRot += 360.0f; + float yRot = arrow->yRot; + float xRot = arrow->xRot; + float yRotO = arrow->yRotO; + float xRotO = arrow->xRotO; + if ((yRot - yRotO) > 180.0f) + yRot -= 360.0f; + else if ((yRot - yRotO) < -180.0f) + yRot += 360.0f; + if ((xRot - xRotO) > 180.0f) + xRot -= 360.0f; + else if ((xRot - xRotO) < -180.0f) + xRot += 360.0f; glTranslatef((float)x, (float)y, (float)z); glRotatef(yRotO + (yRot - yRotO) * a - 90, 0, 1, 0); glRotatef(xRotO + (xRot - xRotO) * a, 0, 0, 1); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); int type = 0; float u0 = 0 / 32.0f; @@ -39,10 +44,9 @@ void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, d float v12 = (10 + type * 10) / 32.0f; float ss = 0.9f / 16.0f; glEnable(GL_RESCALE_NORMAL); - float shake = arrow->shakeTime-a; - if (shake>0) - { - float pow = -Mth::sin(shake*3)*shake; + float shake = arrow->shakeTime - a; + if (shake > 0) { + float pow = -Mth::sin(shake * 3) * shake; glRotatef(pow, 0, 0, 1); } glRotatef(45, 1, 0, 0); @@ -50,35 +54,46 @@ void ArrowRenderer::render(std::shared_ptr _arrow, double x, double y, d glTranslatef(-4, 0, 0); -// glNormal3f(ss, 0, 0); // 4J - changed to use tesselator + // glNormal3f(ss, 0, 0); // 4J - changed to use tesselator t->begin(); - t->normal(1,0,0); - t->vertexUV((float)(-7), (float)( -2), (float)( -2), (float)( u02), (float)( v02)); - t->vertexUV((float)(-7), (float)( -2), (float)( +2), (float)( u12), (float)( v02)); - t->vertexUV((float)(-7), (float)( +2), (float)( +2), (float)( u12), (float)( v12)); - t->vertexUV((float)(-7), (float)( +2), (float)( -2), (float)( u02), (float)( v12)); + t->normal(1, 0, 0); + t->vertexUV((float)(-7), (float)(-2), (float)(-2), (float)(u02), + (float)(v02)); + t->vertexUV((float)(-7), (float)(-2), (float)(+2), (float)(u12), + (float)(v02)); + t->vertexUV((float)(-7), (float)(+2), (float)(+2), (float)(u12), + (float)(v12)); + t->vertexUV((float)(-7), (float)(+2), (float)(-2), (float)(u02), + (float)(v12)); t->end(); -// glNormal3f(-ss, 0, 0); // 4J - changed to use tesselator + // glNormal3f(-ss, 0, 0); // 4J - changed to use tesselator t->begin(); - t->normal(-1,0,0); - t->vertexUV((float)(-7), (float)( +2), (float)( -2), (float)( u02), (float)( v02)); - t->vertexUV((float)(-7), (float)( +2), (float)( +2), (float)( u12), (float)( v02)); - t->vertexUV((float)(-7), (float)( -2), (float)( +2), (float)( u12), (float)( v12)); - t->vertexUV((float)(-7), (float)( -2), (float)( -2), (float)( u02), (float)( v12)); + t->normal(-1, 0, 0); + t->vertexUV((float)(-7), (float)(+2), (float)(-2), (float)(u02), + (float)(v02)); + t->vertexUV((float)(-7), (float)(+2), (float)(+2), (float)(u12), + (float)(v02)); + t->vertexUV((float)(-7), (float)(-2), (float)(+2), (float)(u12), + (float)(v12)); + t->vertexUV((float)(-7), (float)(-2), (float)(-2), (float)(u02), + (float)(v12)); t->end(); - for (int i = 0; i < 4; i++) - { - + for (int i = 0; i < 4; i++) { glRotatef(90, 1, 0, 0); -// glNormal3f(0, 0, ss); // 4J - changed to use tesselator + // glNormal3f(0, 0, ss); // 4J - changed to use + // tesselator t->begin(); - t->normal(0,0,1); - t->vertexUV((float)(-8), (float)( -2), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+8), (float)( -2), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+8), (float)( +2), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-8), (float)( +2), (float)( 0), (float)( u0), (float)( v1)); + t->normal(0, 0, 1); + t->vertexUV((float)(-8), (float)(-2), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(+8), (float)(-2), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(+8), (float)(+2), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-8), (float)(+2), (float)(0), (float)(u0), + (float)(v1)); t->end(); } glDisable(GL_RESCALE_NORMAL); diff --git a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h index 3348fc332..0491c6990 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ArrowRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class ArrowRenderer : public EntityRenderer -{ +class ArrowRenderer : public EntityRenderer { public: - virtual void render(std::shared_ptr _arrow, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _arrow, double x, double y, + double z, float rot, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp index 9e2f4bcee..8670234d2 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.cpp @@ -3,22 +3,21 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "BlazeRenderer.h" -BlazeRenderer::BlazeRenderer() : MobRenderer(new BlazeModel(), 0.5f) -{ - this->modelVersion = ((BlazeModel *) model)->modelVersion(); +BlazeRenderer::BlazeRenderer() : MobRenderer(new BlazeModel(), 0.5f) { + this->modelVersion = ((BlazeModel*)model)->modelVersion(); } -void BlazeRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void BlazeRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - int modelVersion = ((BlazeModel *) model)->modelVersion(); - if (modelVersion != this->modelVersion) - { - this->modelVersion = modelVersion; - model = new BlazeModel(); - } - MobRenderer::render(mob, x, y, z, rot, a); + int modelVersion = ((BlazeModel*)model)->modelVersion(); + if (modelVersion != this->modelVersion) { + this->modelVersion = modelVersion; + model = new BlazeModel(); + } + MobRenderer::render(mob, x, y, z, rot, a); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h index 0ee973cab..12284da6b 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/BlazeRenderer.h @@ -2,13 +2,13 @@ #include "MobRenderer.h" -class BlazeRenderer : public MobRenderer -{ +class BlazeRenderer : public MobRenderer { private: - int modelVersion; + int modelVersion; public: - BlazeRenderer(); + BlazeRenderer(); - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp index 270ee1eff..3018a7c8e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.cpp @@ -4,37 +4,37 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" #include "../../../Minecraft.World/Util/Mth.h" -BoatRenderer::BoatRenderer() : EntityRenderer() -{ +BoatRenderer::BoatRenderer() : EntityRenderer() { this->shadowRadius = 0.5f; model = new BoatModel(); } -void BoatRenderer::render(std::shared_ptr _boat, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr boat = std::dynamic_pointer_cast(_boat); +void BoatRenderer::render(std::shared_ptr _boat, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr boat = std::dynamic_pointer_cast(_boat); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); - glRotatef(180-rot, 0, 1, 0); + glRotatef(180 - rot, 0, 1, 0); float hurt = boat->getHurtTime() - a; float dmg = boat->getDamage() - a; - if (dmg<0) dmg = 0; - if (hurt>0) - { - glRotatef(Mth::sin(hurt)*hurt*dmg/10*boat->getHurtDir(), 1, 0, 0); + if (dmg < 0) dmg = 0; + if (hurt > 0) { + glRotatef(Mth::sin(hurt) * hurt * dmg / 10 * boat->getHurtDir(), 1, 0, + 0); } - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - float ss = 12/16.0f; + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + float ss = 12 / 16.0f; glScalef(ss, ss, ss); - glScalef(1/ss, 1/ss, 1/ss); + glScalef(1 / ss, 1 / ss, 1 / ss); - bindTexture(TN_ITEM_BOAT); // 4J was L"/item/boat.png" + bindTexture(TN_ITEM_BOAT); // 4J was L"/item/boat.png" glScalef(-1, -1, 1); model->render(boat, 0, 0, -0.1f, 0, 0, 1 / 16.0f, true); glPopMatrix(); diff --git a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h index c4bb03128..06e490794 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/BoatRenderer.h @@ -1,13 +1,13 @@ #pragma once #include "EntityRenderer.h" -class BoatRenderer : public EntityRenderer -{ +class BoatRenderer : public EntityRenderer { protected: - Model *model; + Model* model; public: - BoatRenderer(); + BoatRenderer(); - virtual void render(std::shared_ptr boat, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr boat, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp index 20c9e3031..f2050f311 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.cpp @@ -6,100 +6,94 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.entity.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -ChestRenderer::ChestRenderer() -{ - chestModel = new ChestModel(); - largeChestModel = new LargeChestModel(); +ChestRenderer::ChestRenderer() { + chestModel = new ChestModel(); + largeChestModel = new LargeChestModel(); } -ChestRenderer::~ChestRenderer() -{ - delete chestModel; - delete largeChestModel; +ChestRenderer::~ChestRenderer() { + delete chestModel; + delete largeChestModel; } -void ChestRenderer::render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr chest = std::dynamic_pointer_cast(_chest); +void ChestRenderer::render(std::shared_ptr _chest, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr chest = + std::dynamic_pointer_cast(_chest); - int data; + int data; - if (!chest->hasLevel()) - { - data = 0; - } - else - { - Tile *tile = chest->getTile(); - data = chest->getData(); + if (!chest->hasLevel()) { + data = 0; + } else { + Tile* tile = chest->getTile(); + data = chest->getData(); - if (tile != NULL && data == 0) - { - ((ChestTile *) tile)->recalcLockDir(chest->getLevel(), chest->x, chest->y, chest->z); - data = chest->getData(); - } + if (tile != NULL && data == 0) { + ((ChestTile*)tile) + ->recalcLockDir(chest->getLevel(), chest->x, chest->y, + chest->z); + data = chest->getData(); + } - chest->checkNeighbors(); - } - if (chest->n.lock() != NULL || chest->w.lock() != NULL) return; + chest->checkNeighbors(); + } + if (chest->n.lock() != NULL || chest->w.lock() != NULL) return; + ChestModel* model; + if (chest->e.lock() != NULL || chest->s.lock() != NULL) { + model = largeChestModel; + bindTexture(TN_TILE_LARGE_CHEST); // 4J Was "/item/largechest.png" + } else { + model = chestModel; + bindTexture(TN_TILE_CHEST); // 4J Was "/item/chest.png" + } - ChestModel *model; - if (chest->e.lock() != NULL || chest->s.lock() != NULL) - { - model = largeChestModel; - bindTexture(TN_TILE_LARGE_CHEST); // 4J Was "/item/largechest.png" - } - else - { - model = chestModel; - bindTexture(TN_TILE_CHEST); // 4J Was "/item/chest.png" - } + glPushMatrix(); + glEnable(GL_RESCALE_NORMAL); + // if( setColor ) glColor4f(1, 1, 1, 1); + if (setColor) glColor4f(1, 1, 1, alpha); + glTranslatef((float)x, (float)y + 1, (float)z + 1); + glScalef(1, -1, -1); - glPushMatrix(); - glEnable(GL_RESCALE_NORMAL); - //if( setColor ) glColor4f(1, 1, 1, 1); - if( setColor ) glColor4f(1, 1, 1, alpha); - glTranslatef((float) x, (float) y + 1, (float) z + 1); - glScalef(1, -1, -1); + glTranslatef(0.5f, 0.5f, 0.5f); + int rot = 0; + if (data == 2) rot = 180; + if (data == 3) rot = 0; + if (data == 4) rot = 90; + if (data == 5) rot = -90; - glTranslatef(0.5f, 0.5f, 0.5f); - int rot = 0; - if (data == 2) rot = 180; - if (data == 3) rot = 0; - if (data == 4) rot = 90; - if (data == 5) rot = -90; + if (data == 2 && chest->e.lock() != NULL) { + glTranslatef(1, 0, 0); + } + if (data == 5 && chest->s.lock() != NULL) { + glTranslatef(0, 0, -1); + } + glRotatef(rot, 0, 1, 0); + glTranslatef(-0.5f, -0.5f, -0.5f); - if (data == 2 && chest->e.lock() != NULL) - { - glTranslatef(1, 0, 0); - } - if (data == 5 && chest->s.lock() != NULL) - { - glTranslatef(0, 0, -1); - } - glRotatef(rot, 0, 1, 0); - glTranslatef(-0.5f, -0.5f, -0.5f); + float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; + if (chest->n.lock() != NULL) { + float open2 = + chest->n.lock()->oOpenness + + (chest->n.lock()->openness - chest->n.lock()->oOpenness) * a; + if (open2 > open) open = open2; + } + if (chest->w.lock() != NULL) { + float open2 = + chest->w.lock()->oOpenness + + (chest->w.lock()->openness - chest->w.lock()->oOpenness) * a; + if (open2 > open) open = open2; + } - float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; - if (chest->n.lock() != NULL) - { - float open2 = chest->n.lock()->oOpenness + (chest->n.lock()->openness - chest->n.lock()->oOpenness) * a; - if (open2 > open) open = open2; - } - if (chest->w.lock() != NULL) - { - float open2 = chest->w.lock()->oOpenness + (chest->w.lock()->openness - chest->w.lock()->oOpenness) * a; - if (open2 > open) open = open2; - } + open = 1 - open; + open = 1 - open * open * open; - open = 1 - open; - open = 1 - open * open * open; - - model->lid->xRot = -(open * PI / 2); - model->render(useCompiled); - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); - if( setColor ) glColor4f(1, 1, 1, 1); + model->lid->xRot = -(open * PI / 2); + model->render(useCompiled); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); + if (setColor) glColor4f(1, 1, 1, 1); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h index ffd4da033..9fe5ba593 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ChestRenderer.h @@ -4,15 +4,16 @@ class ChestModel; -class ChestRenderer : public TileEntityRenderer -{ +class ChestRenderer : public TileEntityRenderer { private: - ChestModel *chestModel; - ChestModel *largeChestModel; + ChestModel* chestModel; + ChestModel* largeChestModel; public: - ChestRenderer(); - ~ChestRenderer(); + ChestRenderer(); + ~ChestRenderer(); - void render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + void render(std::shared_ptr _chest, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp index a718c8bff..dbc846b12 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.cpp @@ -3,22 +3,21 @@ #include "ChickenRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -ChickenRenderer::ChickenRenderer(Model *model, float shadow) : MobRenderer(model,shadow) -{ +ChickenRenderer::ChickenRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void ChickenRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } -void ChickenRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); -} +float ChickenRenderer::getBob(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); -float ChickenRenderer::getBob(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + float flap = mob->oFlap + (mob->flap - mob->oFlap) * a; + float flapSpeed = mob->oFlapSpeed + (mob->flapSpeed - mob->oFlapSpeed) * a; - float flap = mob->oFlap+(mob->flap-mob->oFlap)*a; - float flapSpeed = mob->oFlapSpeed+(mob->flapSpeed-mob->oFlapSpeed)*a; - - return (Mth::sin(flap)+1)*flapSpeed; + return (Mth::sin(flap) + 1) * flapSpeed; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h index 2c33176d5..642c0ed00 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ChickenRenderer.h @@ -1,11 +1,12 @@ #pragma once #include "MobRenderer.h" -class ChickenRenderer : public MobRenderer -{ +class ChickenRenderer : public MobRenderer { public: - ChickenRenderer(Model *model, float shadow); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + ChickenRenderer(Model* model, float shadow); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); + protected: - virtual float getBob(std::shared_ptr _mob, float a); + virtual float getBob(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp index 34385c584..34206f879 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.cpp @@ -1,11 +1,10 @@ #include "../../Platform/stdafx.h" #include "CowRenderer.h" -CowRenderer::CowRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ -} +CowRenderer::CowRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} -void CowRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); +void CowRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h index 0dabaf290..14b5b9230 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/CowRenderer.h @@ -1,9 +1,9 @@ #pragma once #include "MobRenderer.h" -class CowRenderer : public MobRenderer -{ +class CowRenderer : public MobRenderer { public: - CowRenderer(Model *model, float shadow); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + CowRenderer(Model* model, float shadow); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp index d9079bf8d..c3ada0872 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.cpp @@ -4,13 +4,11 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../../../Minecraft.World/Util/Mth.h" -CreeperRenderer::CreeperRenderer() : MobRenderer( new CreeperModel(), 0.5f ) -{ - armorModel = new CreeperModel(2); +CreeperRenderer::CreeperRenderer() : MobRenderer(new CreeperModel(), 0.5f) { + armorModel = new CreeperModel(2); } -void CreeperRenderer::scale(std::shared_ptr mob, float a) -{ +void CreeperRenderer::scale(std::shared_ptr mob, float a) { std::shared_ptr creeper = std::dynamic_pointer_cast(mob); float g = creeper->getSwelling(a); @@ -25,15 +23,17 @@ void CreeperRenderer::scale(std::shared_ptr mob, float a) glScalef(s, hs, s); } -int CreeperRenderer::getOverlayColor(std::shared_ptr mob, float br, float a) -{ - std::shared_ptr creeper = std::dynamic_pointer_cast(mob); +int CreeperRenderer::getOverlayColor(std::shared_ptr mob, float br, + float a) { + std::shared_ptr creeper = std::dynamic_pointer_cast(mob); float step = creeper->getSwelling(a); - if ((int) (step * 10) % 2 == 0) return 0; + if ((int)(step * 10) % 2 == 0) return 0; - int _a = (int) (step * 0.2f * 255) + 25; // 4J - added 25 here as our entities are rendered with alpha test still enabled, and so anything less is invisible + int _a = (int)(step * 0.2f * 255) + + 25; // 4J - added 25 here as our entities are rendered with alpha + // test still enabled, and so anything less is invisible if (_a < 0) _a = 0; if (_a > 255) _a = 255; @@ -44,19 +44,20 @@ int CreeperRenderer::getOverlayColor(std::shared_ptr mob, float br, float a return (_a << 24) | (r << 16) | (g << 8) | b; } -int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isPowered()) - { - if (mob->isInvisible()) glDepthMask(false); - else glDepthMask(true); +int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + if (mob->isPowered()) { + if (mob->isInvisible()) + glDepthMask(false); + else + glDepthMask(true); - if (layer == 1) - { + if (layer == 1) { float time = mob->tickCount + a; - bindTexture(TN_POWERED_CREEPER);// was L"/armor/power.png"); + bindTexture(TN_POWERED_CREEPER); // was L"/armor/power.png"); glMatrixMode(GL_TEXTURE); glLoadIdentity(); float uo = time * 0.01f; @@ -71,8 +72,7 @@ int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) glBlendFunc(GL_ONE, GL_ONE); return 1; } - if (layer == 2) - { + if (layer == 2) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); @@ -81,10 +81,9 @@ int CreeperRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) } } return -1; - } -int CreeperRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, float a) -{ - return -1; +int CreeperRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, + float a) { + return -1; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h index 3afd511bc..75b34d344 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/CreeperRenderer.h @@ -1,16 +1,17 @@ #pragma once #include "MobRenderer.h" -class CreeperRenderer: public MobRenderer -{ +class CreeperRenderer : public MobRenderer { private: - Model *armorModel; + Model* armorModel; public: - CreeperRenderer(); + CreeperRenderer(); + protected: - virtual void scale(std::shared_ptr _mob, float a); + virtual void scale(std::shared_ptr _mob, float a); virtual int getOverlayColor(std::shared_ptr mob, float br, float a); virtual int prepareArmor(std::shared_ptr mob, int layer, float a); - virtual int prepareArmorOverlay(std::shared_ptr _mob, int layer, float a); + virtual int prepareArmorOverlay(std::shared_ptr _mob, int layer, + float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp index a79b23e6e..ad631c6df 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.cpp @@ -2,10 +2,11 @@ #include "DefaultRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.h" -void DefaultRenderer::render(std::shared_ptr entity, double x, double y, double z, float rot, float a) -{ +void DefaultRenderer::render(std::shared_ptr entity, double x, double y, + double z, float rot, float a) { glPushMatrix(); -// 4J - removed following line as doesn't really make any sense -// render(entity->bb, (x-entity->xOld), (y-entity->yOld), (z-entity->zOld)); + // 4J - removed following line as doesn't really make any sense + // render(entity->bb, (x-entity->xOld), (y-entity->yOld), + // (z-entity->zOld)); glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h index 651a99c15..6811a800d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/DefaultRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class DefaultRenderer : public EntityRenderer -{ +class DefaultRenderer : public EntityRenderer { public: - virtual void render(std::shared_ptr entity, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr entity, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp index 99db92af5..b7a66b504 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.cpp @@ -4,56 +4,53 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "EnchantTableRenderer.h" -EnchantTableRenderer::EnchantTableRenderer() -{ - bookModel = new BookModel(); -} +EnchantTableRenderer::EnchantTableRenderer() { bookModel = new BookModel(); } -EnchantTableRenderer::~EnchantTableRenderer() -{ - delete bookModel; -} +EnchantTableRenderer::~EnchantTableRenderer() { delete bookModel; } -void EnchantTableRenderer::render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr table = std::dynamic_pointer_cast(_table); +void EnchantTableRenderer::render(std::shared_ptr _table, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr table = + std::dynamic_pointer_cast(_table); #ifdef __PSVITA__ - // AP - the book pages are made with 0 depth so the front and back polys are at the same location. This can cause z-fighting if culling is disabled which can sometimes happen - // depending on what object was last seen so make sure culling is always enabled. Should this be a problem for other platforms? - glEnable(GL_CULL_FACE); + // AP - the book pages are made with 0 depth so the front and back polys are + // at the same location. This can cause z-fighting if culling is disabled + // which can sometimes happen depending on what object was last seen so make + // sure culling is always enabled. Should this be a problem for other + // platforms? + glEnable(GL_CULL_FACE); #endif - glPushMatrix(); - glTranslatef((float) x + 0.5f, (float) y + 12 / 16.0f, (float) z + 0.5f); + glPushMatrix(); + glTranslatef((float)x + 0.5f, (float)y + 12 / 16.0f, (float)z + 0.5f); - float tt = table->time + a; + float tt = table->time + a; - glTranslatef(0, 0.1f + sin(tt * 0.1f) * 0.01f, 0); - float orot = (table->rot - table->oRot); - while (orot >= PI) - orot -= PI * 2; - while (orot < -PI) - orot += PI * 2; + glTranslatef(0, 0.1f + sin(tt * 0.1f) * 0.01f, 0); + float orot = (table->rot - table->oRot); + while (orot >= PI) orot -= PI * 2; + while (orot < -PI) orot += PI * 2; - float yRot = table->oRot + orot * a; + float yRot = table->oRot + orot * a; - glRotatef(-yRot * 180 / PI, 0, 1, 0); - glRotatef(80, 0, 0, 1); - bindTexture(TN_ITEM_BOOK); // 4J was "/item/book.png" + glRotatef(-yRot * 180 / PI, 0, 1, 0); + glRotatef(80, 0, 0, 1); + bindTexture(TN_ITEM_BOOK); // 4J was "/item/book.png" - float ff1 = table->oFlip + (table->flip - table->oFlip) * a + 0.25f; - float ff2 = table->oFlip + (table->flip - table->oFlip) * a + 0.75f; - ff1 = (ff1 - Mth::fastFloor(ff1)) * 1.6f - 0.3f; - ff2 = (ff2 - Mth::fastFloor(ff2)) * 1.6f - 0.3f; + float ff1 = table->oFlip + (table->flip - table->oFlip) * a + 0.25f; + float ff2 = table->oFlip + (table->flip - table->oFlip) * a + 0.75f; + ff1 = (ff1 - Mth::fastFloor(ff1)) * 1.6f - 0.3f; + ff2 = (ff2 - Mth::fastFloor(ff2)) * 1.6f - 0.3f; - if (ff1 < 0) ff1 = 0; - if (ff2 < 0) ff2 = 0; - if (ff1 > 1) ff1 = 1; - if (ff2 > 1) ff2 = 1; + if (ff1 < 0) ff1 = 0; + if (ff2 < 0) ff2 = 0; + if (ff1 > 1) ff1 = 1; + if (ff2 > 1) ff2 = 1; - float o = table->oOpen + (table->open - table->oOpen) * a; - bookModel->render(nullptr, tt, ff1, ff2, o, 0, 1 / 16.0f,true); - glPopMatrix(); + float o = table->oOpen + (table->open - table->oOpen) * a; + bookModel->render(nullptr, tt, ff1, ff2, o, 0, 1 / 16.0f, true); + glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h index 774857191..fa7de9dcf 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnchantTableRenderer.h @@ -4,16 +4,18 @@ class BookModel; -class EnchantTableRenderer : public TileEntityRenderer -{ - friend class CXuiCtrlEnchantmentBook; - friend class UIControl_EnchantmentBook; +class EnchantTableRenderer : public TileEntityRenderer { + friend class CXuiCtrlEnchantmentBook; + friend class UIControl_EnchantmentBook; + private: - BookModel *bookModel; + BookModel* bookModel; public: - EnchantTableRenderer(); - ~EnchantTableRenderer(); + EnchantTableRenderer(); + ~EnchantTableRenderer(); - virtual void render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); + virtual void render(std::shared_ptr _table, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp index 5ba499998..876c48d2e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.cpp @@ -3,50 +3,51 @@ #include "../Models/ModelPart.h" #include "EnderChestRenderer.h" -void EnderChestRenderer::render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr chest = std::dynamic_pointer_cast(_chest); +void EnderChestRenderer::render(std::shared_ptr _chest, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr chest = + std::dynamic_pointer_cast(_chest); - int data = 0; + int data = 0; - if (chest->hasLevel()) - { - data = chest->getData(); - } + if (chest->hasLevel()) { + data = chest->getData(); + } - bindTexture(TN_TILE_ENDER_CHEST); //"/item/enderchest.png"); + bindTexture(TN_TILE_ENDER_CHEST); //"/item/enderchest.png"); - glPushMatrix(); - glEnable(GL_RESCALE_NORMAL); - //glColor4f(1, 1, 1, 1); - if( setColor ) glColor4f(1, 1, 1, alpha); - glTranslatef((float) x, (float) y + 1, (float) z + 1); - glScalef(1, -1, -1); + glPushMatrix(); + glEnable(GL_RESCALE_NORMAL); + // glColor4f(1, 1, 1, 1); + if (setColor) glColor4f(1, 1, 1, alpha); + glTranslatef((float)x, (float)y + 1, (float)z + 1); + glScalef(1, -1, -1); - glTranslatef(0.5f, 0.5f, 0.5f); - int rot = 0; - if (data == 2) rot = 180; - if (data == 3) rot = 0; - if (data == 4) rot = 90; - if (data == 5) rot = -90; + glTranslatef(0.5f, 0.5f, 0.5f); + int rot = 0; + if (data == 2) rot = 180; + if (data == 3) rot = 0; + if (data == 4) rot = 90; + if (data == 5) rot = -90; - // if (data == 2) { - // glTranslatef(1, 0, 0); - // } - // if (data == 5) { - // glTranslatef(0, 0, -1); - // } - glRotatef(rot, 0, 1, 0); - glTranslatef(-0.5f, -0.5f, -0.5f); + // if (data == 2) { + // glTranslatef(1, 0, 0); + // } + // if (data == 5) { + // glTranslatef(0, 0, -1); + // } + glRotatef(rot, 0, 1, 0); + glTranslatef(-0.5f, -0.5f, -0.5f); - float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; - open = 1 - open; - open = 1 - open * open * open; + float open = chest->oOpenness + (chest->openness - chest->oOpenness) * a; + open = 1 - open; + open = 1 - open * open * open; - chestModel.lid->xRot = -(open * PI / 2); - chestModel.render(useCompiled); - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); - if( setColor ) glColor4f(1, 1, 1, 1); + chestModel.lid->xRot = -(open * PI / 2); + chestModel.render(useCompiled); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); + if (setColor) glColor4f(1, 1, 1, 1); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h index ab7b65547..b6df8e638 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderChestRenderer.h @@ -3,11 +3,12 @@ #include "TileEntityRenderer.h" #include "../Models/ChestModel.h" -class EnderChestRenderer : public TileEntityRenderer -{ +class EnderChestRenderer : public TileEntityRenderer { private: - ChestModel chestModel; + ChestModel chestModel; public: - void render(std::shared_ptr _chest, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + void render(std::shared_ptr _chest, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp index 3b5e232a0..fb9dad13c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.cpp @@ -3,31 +3,32 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.boss.enderdragon.h" #include "EnderCrystalRenderer.h" -EnderCrystalRenderer::EnderCrystalRenderer() -{ - currentModel = -1; - this->shadowRadius = 0.5f; +EnderCrystalRenderer::EnderCrystalRenderer() { + currentModel = -1; + this->shadowRadius = 0.5f; } -void EnderCrystalRenderer::render(std::shared_ptr _crystal, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type EnderCrystal rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr crystal = std::dynamic_pointer_cast(_crystal); - if (currentModel != EnderCrystalModel::MODEL_ID) - { - model = new EnderCrystalModel(0); - currentModel = EnderCrystalModel::MODEL_ID; - } +void EnderCrystalRenderer::render(std::shared_ptr _crystal, double x, + double y, double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type EnderCrystal rather than std::shared_ptr we have here - do + // some casting around instead + std::shared_ptr crystal = + std::dynamic_pointer_cast(_crystal); + if (currentModel != EnderCrystalModel::MODEL_ID) { + model = new EnderCrystalModel(0); + currentModel = EnderCrystalModel::MODEL_ID; + } + float tt = crystal->time + a; + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); + bindTexture( + TN_MOB_ENDERDRAGON_ENDERCRYSTAL); // 4J was + // "/mob/enderdragon/crystal.png" + float hh = sin(tt * 0.2f) / 2 + 0.5f; + hh = hh * hh + hh; + model->render(crystal, 0, tt * 3, hh * 0.2f, 0, 0, 1 / 16.0f, true); - float tt = crystal->time + a; - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); - bindTexture(TN_MOB_ENDERDRAGON_ENDERCRYSTAL); // 4J was "/mob/enderdragon/crystal.png" - float hh = sin(tt * 0.2f) / 2 + 0.5f; - hh = hh * hh + hh; - model->render(crystal, 0, tt * 3, hh * 0.2f, 0, 0, 1 / 16.0f, true); - - glPopMatrix(); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h index 5ac644d15..caa764121 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderCrystalRenderer.h @@ -4,14 +4,14 @@ class Model; -class EnderCrystalRenderer : public EntityRenderer -{ +class EnderCrystalRenderer : public EntityRenderer { private: - int currentModel; - Model *model; + int currentModel; + Model* model; public: - EnderCrystalRenderer(); + EnderCrystalRenderer(); - virtual void render(std::shared_ptr _crystal, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _crystal, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp index 9b2cbee0a..09a6e1d0e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.cpp @@ -8,260 +8,278 @@ std::shared_ptr EnderDragonRenderer::bossInstance; int EnderDragonRenderer::currentModel; -EnderDragonRenderer::EnderDragonRenderer() : MobRenderer(new DragonModel(0), 0.5f) -{ - currentModel = 0; - dragonModel = (DragonModel *) model; - this->setArmor(model); +EnderDragonRenderer::EnderDragonRenderer() + : MobRenderer(new DragonModel(0), 0.5f) { + currentModel = 0; + dragonModel = (DragonModel*)model; + this->setArmor(model); } -void EnderDragonRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EnderDragonRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); - // 4J - reorganised a bit so we can free allocations - double lpComponents[3]; - doubleArray lp = doubleArray(lpComponents, 3); - mob->getLatencyPos(lp, 7, a); - float yr = lp[0]; - //mob->getLatencyPos(lp, 5, a); - //float rot2 = lp[1]; - //mob->getLatencyPos(lp, 10,a); - //rot2 -= lp[1]; - float rot2 = mob->getTilt(a); + // 4J - reorganised a bit so we can free allocations + double lpComponents[3]; + doubleArray lp = doubleArray(lpComponents, 3); + mob->getLatencyPos(lp, 7, a); + float yr = lp[0]; + // mob->getLatencyPos(lp, 5, a); + // float rot2 = lp[1]; + // mob->getLatencyPos(lp, 10,a); + // rot2 -= lp[1]; + float rot2 = mob->getTilt(a); - glRotatef(-yr, 0, 1, 0); - - glRotatef(rot2, 1, 0, 0); - //glRotatef(rot2 * 10, 1, 0, 0); + glRotatef(-yr, 0, 1, 0); - glTranslatef(0, 0, 1); - if (mob->deathTime > 0) - { - float fall = (mob->deathTime + a - 1) / 20.0f * 1.6f; - fall = sqrt(fall); - if (fall > 1) fall = 1; - glRotatef(fall * getFlipDegrees(mob), 0, 0, 1); - } + glRotatef(rot2, 1, 0, 0); + // glRotatef(rot2 * 10, 1, 0, 0); + + glTranslatef(0, 0, 1); + if (mob->deathTime > 0) { + float fall = (mob->deathTime + a - 1) / 20.0f * 1.6f; + fall = sqrt(fall); + if (fall > 1) fall = 1; + glRotatef(fall * getFlipDegrees(mob), 0, 0, 1); + } } -void EnderDragonRenderer::renderModel(std::shared_ptr _mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EnderDragonRenderer::renderModel(std::shared_ptr _mob, float wp, + float ws, float bob, + float headRotMinusBodyRot, float headRotx, + float scale) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); - if (mob->dragonDeathTime > 0) - { - float tt = (mob->dragonDeathTime / 200.0f); - glDepthFunc(GL_LEQUAL); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, tt); - bindTexture(mob->customTextureUrl, TN_MOB_ENDERDRAGON_SHUFFLE); // 4J was "/mob/enderdragon/shuffle.png" - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - glAlphaFunc(GL_GREATER, 0.1f); + if (mob->dragonDeathTime > 0) { + float tt = (mob->dragonDeathTime / 200.0f); + glDepthFunc(GL_LEQUAL); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, tt); + bindTexture( + mob->customTextureUrl, + TN_MOB_ENDERDRAGON_SHUFFLE); // 4J was + // "/mob/enderdragon/shuffle.png" + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); + glAlphaFunc(GL_GREATER, 0.1f); - glDepthFunc(GL_EQUAL); - } + glDepthFunc(GL_EQUAL); + } + bindTexture(mob->customTextureUrl, mob->getTexture()); + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - bindTexture(mob->customTextureUrl, mob->getTexture()); - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - - if (mob->hurtTime > 0) - { - glDepthFunc(GL_EQUAL); - glDisable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(1, 0, 0, 0.5f); + if (mob->hurtTime > 0) { + glDepthFunc(GL_EQUAL); + glDisable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(1, 0, 0, 0.5f); #ifdef __PSVITA__ - // AP - not sure that the usecompiled flag is supposed to be false. This makes it really slow on vita. Making it true still seems to look the same - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); + // AP - not sure that the usecompiled flag is supposed to be false. This + // makes it really slow on vita. Making it true still seems to look the + // same + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); #else - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, false); + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + false); #endif - glEnable(GL_TEXTURE_2D); - glDisable(GL_BLEND); - glDepthFunc(GL_LEQUAL); - } + glEnable(GL_TEXTURE_2D); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + } } -void EnderDragonRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - EnderDragonRenderer::bossInstance = mob; - if (currentModel != DragonModel::MODEL_ID) - { - model = new DragonModel(0); - currentModel = DragonModel::MODEL_ID; - } - MobRenderer::render(mob, x, y, z, rot, a); - if (mob->nearestCrystal != NULL) - { - float tt = mob->nearestCrystal->time + a; - float hh = sin(tt * 0.2f) / 2 + 0.5f; - hh = (hh * hh + hh) * 0.2f; +void EnderDragonRenderer::render(std::shared_ptr _mob, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + EnderDragonRenderer::bossInstance = mob; + if (currentModel != DragonModel::MODEL_ID) { + model = new DragonModel(0); + currentModel = DragonModel::MODEL_ID; + } + MobRenderer::render(mob, x, y, z, rot, a); + if (mob->nearestCrystal != NULL) { + float tt = mob->nearestCrystal->time + a; + float hh = sin(tt * 0.2f) / 2 + 0.5f; + hh = (hh * hh + hh) * 0.2f; - float xd = (float) (mob->nearestCrystal->x - mob->x - (mob->xo - mob->x) * (1 - a)); - float yd = (float) (hh + mob->nearestCrystal->y - 1 - mob->y - (mob->yo - mob->y) * (1 - a)); - float zd = (float) (mob->nearestCrystal->z - mob->z - (mob->zo - mob->z) * (1 - a)); + float xd = (float)(mob->nearestCrystal->x - mob->x - + (mob->xo - mob->x) * (1 - a)); + float yd = (float)(hh + mob->nearestCrystal->y - 1 - mob->y - + (mob->yo - mob->y) * (1 - a)); + float zd = (float)(mob->nearestCrystal->z - mob->z - + (mob->zo - mob->z) * (1 - a)); - float sdd = sqrt(xd * xd + zd * zd); - float dd = sqrt(xd * xd + yd * yd + zd * zd); + float sdd = sqrt(xd * xd + zd * zd); + float dd = sqrt(xd * xd + yd * yd + zd * zd); - // this fixes a problem when the dragon is hit and the beam goes black because the diffuse colour isn't being reset in MobRenderer::render - glColor4f(1, 1, 1, 1); + // this fixes a problem when the dragon is hit and the beam goes black + // because the diffuse colour isn't being reset in MobRenderer::render + glColor4f(1, 1, 1, 1); - glPushMatrix(); - glTranslatef((float) x, (float) y + 2, (float) z); - glRotatef((float) (-atan2(zd, xd)) * 180.0f / PI - 90.0f, 0, 1, 0); - glRotatef((float) (-atan2(sdd, yd)) * 180.0f / PI - 90.0f, 1, 0, 0); + glPushMatrix(); + glTranslatef((float)x, (float)y + 2, (float)z); + glRotatef((float)(-atan2(zd, xd)) * 180.0f / PI - 90.0f, 0, 1, 0); + glRotatef((float)(-atan2(sdd, yd)) * 180.0f / PI - 90.0f, 1, 0, 0); - // 4J-PB - Rotating the healing beam too - static float fRot=0.0f; - glRotatef(fRot, 0, 0, 1); - fRot+=0.5f; // 4J - rate of rotation changed from 5.0 to 0.5 for photosensitivity reasons - if(fRot>=360.0f) - { - fRot=0.0f; - } + // 4J-PB - Rotating the healing beam too + static float fRot = 0.0f; + glRotatef(fRot, 0, 0, 1); + fRot += 0.5f; // 4J - rate of rotation changed from 5.0 to 0.5 for + // photosensitivity reasons + if (fRot >= 360.0f) { + fRot = 0.0f; + } - Tesselator *t = Tesselator::getInstance(); - Lighting::turnOff(); - glDisable(GL_CULL_FACE); + Tesselator* t = Tesselator::getInstance(); + Lighting::turnOff(); + glDisable(GL_CULL_FACE); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); - bindTexture(TN_MOB_ENDERDRAGON_BEAM); // 4J was "/mob/enderdragon/beam.png" + bindTexture( + TN_MOB_ENDERDRAGON_BEAM); // 4J was "/mob/enderdragon/beam.png" - glShadeModel(GL_SMOOTH); + glShadeModel(GL_SMOOTH); - float v0 = 0 - (mob->tickCount + a) * 0.005f; // 4J - rate of movement changed from 0.01 to 0.005 for photosensitivity reasons - float v1 = sqrt(xd * xd + yd * yd + zd * zd) / 32.0f - (mob->tickCount + a) * 0.005f; + float v0 = 0 - (mob->tickCount + a) * + 0.005f; // 4J - rate of movement changed from 0.01 + // to 0.005 for photosensitivity reasons + float v1 = sqrt(xd * xd + yd * yd + zd * zd) / 32.0f - + (mob->tickCount + a) * 0.005f; - t->begin(GL_TRIANGLE_STRIP); + t->begin(GL_TRIANGLE_STRIP); - int steps = 8; - for (int i = 0; i <= steps; i++) - { - double d=i % steps * PI * 2 / steps; - float s = sin(i % steps * PI * 2 / steps) * 0.75f; - float c = cos(i % steps * PI * 2 / steps) * 0.75f; - float u = i % steps * 1.0f / steps; - //t->color(0x000000); - t->vertexUV(s * 0.2f, c * 0.2f, 0, u, v1); - //t->color(0xffffff); - t->vertexUV(s, c, dd, u, v0); - } + int steps = 8; + for (int i = 0; i <= steps; i++) { + double d = i % steps * PI * 2 / steps; + float s = sin(i % steps * PI * 2 / steps) * 0.75f; + float c = cos(i % steps * PI * 2 / steps) * 0.75f; + float u = i % steps * 1.0f / steps; + // t->color(0x000000); + t->vertexUV(s * 0.2f, c * 0.2f, 0, u, v1); + // t->color(0xffffff); + t->vertexUV(s, c, dd, u, v0); + } - t->end(); - glEnable(GL_CULL_FACE); - glShadeModel(GL_FLAT); - glDisable(GL_BLEND); + t->end(); + glEnable(GL_CULL_FACE); + glShadeModel(GL_FLAT); + glDisable(GL_BLEND); - glPopMatrix(); - Lighting::turnOn(); - } + glPopMatrix(); + Lighting::turnOn(); + } } -void EnderDragonRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - Tesselator *t = Tesselator::getInstance(); +void EnderDragonRenderer::additionalRendering(std::shared_ptr _mob, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::additionalRendering(mob, a); + Tesselator* t = Tesselator::getInstance(); - if (mob->dragonDeathTime > 0) - { - Lighting::turnOff(); - float tt = ((mob->dragonDeathTime + a) / 200.0f); - float overDrive = 0; - if (tt > 0.8f) - { - overDrive = (tt - 0.8f) / 0.2f; - } - - Random random(432); - glDisable(GL_TEXTURE_2D); - glShadeModel(GL_SMOOTH); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glDisable(GL_ALPHA_TEST); - glEnable(GL_CULL_FACE); - glDepthMask(false); - glPushMatrix(); - glTranslatef(0, -1, -2); - for (int i = 0; i < (tt + tt * tt) / 2 * 60; i++) - { - glRotatef(random.nextFloat() * 360, 1, 0, 0); - glRotatef(random.nextFloat() * 360, 0, 1, 0); - glRotatef(random.nextFloat() * 360, 0, 0, 1); - glRotatef(random.nextFloat() * 360, 1, 0, 0); - glRotatef(random.nextFloat() * 360, 0, 1, 0); - glRotatef(random.nextFloat() * 360 + tt * 90, 0, 0, 1); - t->begin(GL_TRIANGLE_FAN); - float dist = random.nextFloat() * 20 + 5 + overDrive * 10; - float w = random.nextFloat() * 2 + 1 + overDrive * 2; - t->color(0xffffff, (int) (255 * (1 - overDrive))); - t->vertex(0, 0, 0); - t->color(0xff00ff, 0); - t->vertex(-0.866 * w, dist, -0.5f * w); - t->vertex(+0.866 * w, dist, -0.5f * w); - t->vertex(0, dist, 1 * w); - t->vertex(-0.866 * w, dist, -0.5f * w); - t->end(); - } - glPopMatrix(); - glDepthMask(true); - glDisable(GL_CULL_FACE); - glDisable(GL_BLEND); - glShadeModel(GL_FLAT); - glColor4f(1, 1, 1, 1); - glEnable(GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); - Lighting::turnOn(); - } + if (mob->dragonDeathTime > 0) { + Lighting::turnOff(); + float tt = ((mob->dragonDeathTime + a) / 200.0f); + float overDrive = 0; + if (tt > 0.8f) { + overDrive = (tt - 0.8f) / 0.2f; + } + Random random(432); + glDisable(GL_TEXTURE_2D); + glShadeModel(GL_SMOOTH); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glDisable(GL_ALPHA_TEST); + glEnable(GL_CULL_FACE); + glDepthMask(false); + glPushMatrix(); + glTranslatef(0, -1, -2); + for (int i = 0; i < (tt + tt * tt) / 2 * 60; i++) { + glRotatef(random.nextFloat() * 360, 1, 0, 0); + glRotatef(random.nextFloat() * 360, 0, 1, 0); + glRotatef(random.nextFloat() * 360, 0, 0, 1); + glRotatef(random.nextFloat() * 360, 1, 0, 0); + glRotatef(random.nextFloat() * 360, 0, 1, 0); + glRotatef(random.nextFloat() * 360 + tt * 90, 0, 0, 1); + t->begin(GL_TRIANGLE_FAN); + float dist = random.nextFloat() * 20 + 5 + overDrive * 10; + float w = random.nextFloat() * 2 + 1 + overDrive * 2; + t->color(0xffffff, (int)(255 * (1 - overDrive))); + t->vertex(0, 0, 0); + t->color(0xff00ff, 0); + t->vertex(-0.866 * w, dist, -0.5f * w); + t->vertex(+0.866 * w, dist, -0.5f * w); + t->vertex(0, dist, 1 * w); + t->vertex(-0.866 * w, dist, -0.5f * w); + t->end(); + } + glPopMatrix(); + glDepthMask(true); + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glShadeModel(GL_FLAT); + glColor4f(1, 1, 1, 1); + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); + Lighting::turnOn(); + } } -int EnderDragonRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +int EnderDragonRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); - if (layer == 1) - { - glDepthFunc(GL_LEQUAL); - } - if (layer != 0) return -1; + if (layer == 1) { + glDepthFunc(GL_LEQUAL); + } + if (layer != 0) return -1; - bindTexture(TN_MOB_ENDERDRAGON_ENDEREYES); // 4J was "/mob/enderdragon/ender_eyes.png" - float br = 1; - glEnable(GL_BLEND); - // 4J Stu - We probably don't need to do this on 360 either (as we force it back on the renderer) - // However we do want it off for other platforms that don't force it on in the render lib CBuff handling - // Several texture packs have fully transparent bits that break if this is off + bindTexture( + TN_MOB_ENDERDRAGON_ENDEREYES); // 4J was + // "/mob/enderdragon/ender_eyes.png" + float br = 1; + glEnable(GL_BLEND); + // 4J Stu - We probably don't need to do this on 360 either (as we force it + // back on the renderer) However we do want it off for other platforms that + // don't force it on in the render lib CBuff handling Several texture packs + // have fully transparent bits that break if this is off #ifdef _XBOX glDisable(GL_ALPHA_TEST); #endif - glBlendFunc(GL_ONE, GL_ONE); - glDisable(GL_LIGHTING); - glDepthFunc(GL_EQUAL); + glBlendFunc(GL_ONE, GL_ONE); + glDisable(GL_LIGHTING); + glDepthFunc(GL_EQUAL); - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = 0xf0f0; - int u = col % 65536; - int v = col / 65536; + if (SharedConstants::TEXTURE_LIGHTING) { + int col = 0xf0f0; + int u = col % 65536; + int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glEnable(GL_LIGHTING); - glColor4f(1, 1, 1, br); - return 1; + glEnable(GL_LIGHTING); + glColor4f(1, 1, 1, br); + return 1; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h index 095e2cf28..25659a509 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderDragonRenderer.h @@ -7,30 +7,33 @@ class EnderDragon; #endif class DragonModel; -class EnderDragonRenderer : public MobRenderer -{ +class EnderDragonRenderer : public MobRenderer { public: - static std::shared_ptr bossInstance; + static std::shared_ptr bossInstance; private: - static int currentModel; + static int currentModel; protected: - DragonModel *dragonModel; + DragonModel* dragonModel; public: - EnderDragonRenderer(); + EnderDragonRenderer(); protected: - virtual void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); + virtual void setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a); protected: - void renderModel(std::shared_ptr _mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale); + void renderModel(std::shared_ptr _mob, float wp, float ws, + float bob, float headRotMinusBodyRot, float headRotx, + float scale); public: - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); protected: - virtual void additionalRendering(std::shared_ptr _mob, float a); - virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp index cfb91c452..14f7420e2 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.cpp @@ -4,104 +4,104 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -EndermanRenderer::EndermanRenderer() : MobRenderer(new EndermanModel(), 0.5f) -{ - model = (EndermanModel *) MobRenderer::model; - this->setArmor(model); +EndermanRenderer::EndermanRenderer() : MobRenderer(new EndermanModel(), 0.5f) { + model = (EndermanModel*)MobRenderer::model; + this->setArmor(model); } -void EndermanRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EndermanRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - model->carrying = mob->getCarryingTile() > 0; - model->creepy = mob->isCreepy(); + model->carrying = mob->getCarryingTile() > 0; + model->creepy = mob->isCreepy(); - if (mob->isCreepy()) - { - double d = 0.02; - x += random.nextGaussian() * d; - z += random.nextGaussian() * d; - } + if (mob->isCreepy()) { + double d = 0.02; + x += random.nextGaussian() * d; + z += random.nextGaussian() * d; + } - MobRenderer::render(mob, x, y, z, rot, a); + MobRenderer::render(mob, x, y, z, rot, a); } -void EndermanRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void EndermanRenderer::additionalRendering(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(_mob, a); + MobRenderer::additionalRendering(_mob, a); - if (mob->getCarryingTile() > 0) - { - glEnable(GL_RESCALE_NORMAL); - glPushMatrix(); + if (mob->getCarryingTile() > 0) { + glEnable(GL_RESCALE_NORMAL); + glPushMatrix(); - float s = 8 / 16.0f; - glTranslatef(-0 / 16.0f, 11 / 16.0f, -12 / 16.0f); - s *= 1.00f; - glRotatef(20, 1, 0, 0); - glRotatef(45, 0, 1, 0); - glScalef(s, -s, s); + float s = 8 / 16.0f; + glTranslatef(-0 / 16.0f, 11 / 16.0f, -12 / 16.0f); + s *= 1.00f; + glRotatef(20, 1, 0, 0); + glRotatef(45, 0, 1, 0); + glScalef(s, -s, s); + if (SharedConstants::TEXTURE_LIGHTING) { + int col = mob->getLightColor(a); + int u = col % 65536; + int v = col / 65536; - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = mob->getLightColor(a); - int u = col % 65536; - int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } - - glColor4f(1, 1, 1, 1); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - tileRenderer->renderTile(Tile::tiles[mob->getCarryingTile()], mob->getCarryingData(), 1); - glPopMatrix(); - glDisable(GL_RESCALE_NORMAL); - } + glColor4f(1, 1, 1, 1); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + tileRenderer->renderTile(Tile::tiles[mob->getCarryingTile()], + mob->getCarryingData(), 1); + glPopMatrix(); + glDisable(GL_RESCALE_NORMAL); + } } -int EndermanRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Boat rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +int EndermanRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + // 4J - original version used generics and thus had an input parameter of + // type Boat rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (layer != 0) return -1; + if (layer != 0) return -1; - bindTexture(TN_MOB_ENDERMAN_EYES); // 4J was L"/mob/enderman_eyes.png" - float br = 1; - glEnable(GL_BLEND); - // 4J Stu - We probably don't need to do this on 360 either (as we force it back on the renderer) - // However we do want it off for other platforms that don't force it on in the render lib CBuff handling - // Several texture packs have fully transparent bits that break if this is off + bindTexture(TN_MOB_ENDERMAN_EYES); // 4J was L"/mob/enderman_eyes.png" + float br = 1; + glEnable(GL_BLEND); + // 4J Stu - We probably don't need to do this on 360 either (as we force it + // back on the renderer) However we do want it off for other platforms that + // don't force it on in the render lib CBuff handling Several texture packs + // have fully transparent bits that break if this is off #ifdef _XBOX glDisable(GL_ALPHA_TEST); #endif - glBlendFunc(GL_ONE, GL_ONE); - glDisable(GL_LIGHTING); + glBlendFunc(GL_ONE, GL_ONE); + glDisable(GL_LIGHTING); - if (mob->isInvisible()) glDepthMask(false); - else glDepthMask(true); + if (mob->isInvisible()) + glDepthMask(false); + else + glDepthMask(true); - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = 0xf0f0; - int u = col % 65536; - int v = col / 65536; + if (SharedConstants::TEXTURE_LIGHTING) { + int col = 0xf0f0; + int u = col % 65536; + int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glEnable(GL_LIGHTING); - glColor4f(1, 1, 1, br); - return 1; + glEnable(GL_LIGHTING); + glColor4f(1, 1, 1, br); + return 1; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h index eaf6393e7..1c1693cc1 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EnderManRenderer.h @@ -5,18 +5,18 @@ class EnderMan; class EndermanModel; -class EndermanRenderer : public MobRenderer -{ +class EndermanRenderer : public MobRenderer { private: - EndermanModel *model; - Random random; + EndermanModel* model; + Random random; public: - EndermanRenderer(); + EndermanRenderer(); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); - virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); protected: - virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); + virtual int prepareArmor(std::shared_ptr _mob, int layer, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp index b6b681e28..4e59b19d3 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.cpp @@ -76,117 +76,127 @@ double EntityRenderDispatcher::xOff = 0.0; double EntityRenderDispatcher::yOff = 0.0; double EntityRenderDispatcher::zOff = 0.0; -EntityRenderDispatcher *EntityRenderDispatcher::instance = NULL; +EntityRenderDispatcher* EntityRenderDispatcher::instance = NULL; -void EntityRenderDispatcher::staticCtor() -{ - instance = new EntityRenderDispatcher(); +void EntityRenderDispatcher::staticCtor() { + instance = new EntityRenderDispatcher(); } -EntityRenderDispatcher::EntityRenderDispatcher() -{ - glEnable(GL_LIGHTING); - renderers[eTYPE_SPIDER] = new SpiderRenderer(); - renderers[eTYPE_CAVESPIDER] = new SpiderRenderer(); - renderers[eTYPE_PIG] = new PigRenderer(new PigModel(), new PigModel(0.5f), 0.7f); - renderers[eTYPE_SHEEP] = new SheepRenderer(new SheepModel(), new SheepFurModel(), 0.7f); - renderers[eTYPE_COW] = new CowRenderer(new CowModel(), 0.7f); - renderers[eTYPE_MUSHROOMCOW] = new MushroomCowRenderer(new CowModel(), 0.7f); - renderers[eTYPE_WOLF] = new WolfRenderer(new WolfModel(), new WolfModel(), 0.5f); - renderers[eTYPE_CHICKEN] = new ChickenRenderer(new ChickenModel(), 0.3f); - renderers[eTYPE_OZELOT] = new OzelotRenderer(new OzelotModel(), 0.4f); - renderers[eTYPE_SILVERFISH] = new SilverfishRenderer(); - renderers[eTYPE_CREEPER] = new CreeperRenderer(); - renderers[eTYPE_ENDERMAN] = new EndermanRenderer(); - renderers[eTYPE_SNOWMAN] = new SnowManRenderer(); - renderers[eTYPE_SKELETON] = new HumanoidMobRenderer(new SkeletonModel(), 0.5f); - renderers[eTYPE_BLAZE] = new BlazeRenderer(); - renderers[eTYPE_ZOMBIE] = new ZombieRenderer(); - renderers[eTYPE_PIGZOMBIE] = new HumanoidMobRenderer(new ZombieModel(), 0.5f); - renderers[eTYPE_SLIME] = new SlimeRenderer(new SlimeModel(16), new SlimeModel(0), 0.25f); - renderers[eTYPE_LAVASLIME] = new LavaSlimeRenderer(); - renderers[eTYPE_PLAYER] = new PlayerRenderer(); - renderers[eTYPE_GIANT] = new GiantMobRenderer(new ZombieModel(), 0.5f, 6); - renderers[eTYPE_GHAST] = new GhastRenderer(); - renderers[eTYPE_SQUID] = new SquidRenderer(new SquidModel(), 0.7f); - renderers[eTYPE_VILLAGER] = new VillagerRenderer(); - renderers[eTYPE_VILLAGERGOLEM] = new VillagerGolemRenderer(); - renderers[eTYPE_MOB] = new MobRenderer(new HumanoidModel(), 0.5f); - renderers[eTYPE_ENDERDRAGON] = new EnderDragonRenderer(); - renderers[eTYPE_ENDER_CRYSTAL] = new EnderCrystalRenderer(); - renderers[eTYPE_ENTITY] = new DefaultRenderer(); - renderers[eTYPE_PAINTING] = new PaintingRenderer(); - renderers[eTYPE_ITEM_FRAME] = new ItemFrameRenderer(); - renderers[eTYPE_ARROW] = new ArrowRenderer(); - renderers[eTYPE_SNOWBALL] = new ItemSpriteRenderer(Item::snowBall); - renderers[eTYPE_THROWNENDERPEARL] = new ItemSpriteRenderer(Item::enderPearl); - renderers[eTYPE_EYEOFENDERSIGNAL] = new ItemSpriteRenderer(Item::eyeOfEnder); - renderers[eTYPE_THROWNEGG] = new ItemSpriteRenderer(Item::egg); - renderers[eTYPE_THROWNPOTION] = new ItemSpriteRenderer(Item::potion, PotionBrewing::THROWABLE_MASK); - renderers[eTYPE_THROWNEXPBOTTLE] = new ItemSpriteRenderer(Item::expBottle); - renderers[eTYPE_FIREBALL] = new FireballRenderer(2.0f); - renderers[eTYPE_SMALL_FIREBALL] = new FireballRenderer(0.5f); - renderers[eTYPE_DRAGON_FIREBALL] = new FireballRenderer(2.0f); // 4J Added TU9 - renderers[eTYPE_ITEMENTITY] = new ItemRenderer(); - renderers[eTYPE_EXPERIENCEORB] = new ExperienceOrbRenderer(); - renderers[eTYPE_PRIMEDTNT] = new TntRenderer(); - renderers[eTYPE_FALLINGTILE] = new FallingTileRenderer(); - renderers[eTYPE_MINECART] = new MinecartRenderer(); - renderers[eTYPE_BOAT] = new BoatRenderer(); - renderers[eTYPE_FISHINGHOOK] = new FishingHookRenderer(); - renderers[eTYPE_LIGHTNINGBOLT] = new LightningBoltRenderer(); - renderers[eTYPE_ARROW] = new ArrowRenderer(); - glDisable(GL_LIGHTING); +EntityRenderDispatcher::EntityRenderDispatcher() { + glEnable(GL_LIGHTING); + renderers[eTYPE_SPIDER] = new SpiderRenderer(); + renderers[eTYPE_CAVESPIDER] = new SpiderRenderer(); + renderers[eTYPE_PIG] = + new PigRenderer(new PigModel(), new PigModel(0.5f), 0.7f); + renderers[eTYPE_SHEEP] = + new SheepRenderer(new SheepModel(), new SheepFurModel(), 0.7f); + renderers[eTYPE_COW] = new CowRenderer(new CowModel(), 0.7f); + renderers[eTYPE_MUSHROOMCOW] = + new MushroomCowRenderer(new CowModel(), 0.7f); + renderers[eTYPE_WOLF] = + new WolfRenderer(new WolfModel(), new WolfModel(), 0.5f); + renderers[eTYPE_CHICKEN] = new ChickenRenderer(new ChickenModel(), 0.3f); + renderers[eTYPE_OZELOT] = new OzelotRenderer(new OzelotModel(), 0.4f); + renderers[eTYPE_SILVERFISH] = new SilverfishRenderer(); + renderers[eTYPE_CREEPER] = new CreeperRenderer(); + renderers[eTYPE_ENDERMAN] = new EndermanRenderer(); + renderers[eTYPE_SNOWMAN] = new SnowManRenderer(); + renderers[eTYPE_SKELETON] = + new HumanoidMobRenderer(new SkeletonModel(), 0.5f); + renderers[eTYPE_BLAZE] = new BlazeRenderer(); + renderers[eTYPE_ZOMBIE] = new ZombieRenderer(); + renderers[eTYPE_PIGZOMBIE] = + new HumanoidMobRenderer(new ZombieModel(), 0.5f); + renderers[eTYPE_SLIME] = + new SlimeRenderer(new SlimeModel(16), new SlimeModel(0), 0.25f); + renderers[eTYPE_LAVASLIME] = new LavaSlimeRenderer(); + renderers[eTYPE_PLAYER] = new PlayerRenderer(); + renderers[eTYPE_GIANT] = new GiantMobRenderer(new ZombieModel(), 0.5f, 6); + renderers[eTYPE_GHAST] = new GhastRenderer(); + renderers[eTYPE_SQUID] = new SquidRenderer(new SquidModel(), 0.7f); + renderers[eTYPE_VILLAGER] = new VillagerRenderer(); + renderers[eTYPE_VILLAGERGOLEM] = new VillagerGolemRenderer(); + renderers[eTYPE_MOB] = new MobRenderer(new HumanoidModel(), 0.5f); + renderers[eTYPE_ENDERDRAGON] = new EnderDragonRenderer(); + renderers[eTYPE_ENDER_CRYSTAL] = new EnderCrystalRenderer(); + renderers[eTYPE_ENTITY] = new DefaultRenderer(); + renderers[eTYPE_PAINTING] = new PaintingRenderer(); + renderers[eTYPE_ITEM_FRAME] = new ItemFrameRenderer(); + renderers[eTYPE_ARROW] = new ArrowRenderer(); + renderers[eTYPE_SNOWBALL] = new ItemSpriteRenderer(Item::snowBall); + renderers[eTYPE_THROWNENDERPEARL] = + new ItemSpriteRenderer(Item::enderPearl); + renderers[eTYPE_EYEOFENDERSIGNAL] = + new ItemSpriteRenderer(Item::eyeOfEnder); + renderers[eTYPE_THROWNEGG] = new ItemSpriteRenderer(Item::egg); + renderers[eTYPE_THROWNPOTION] = + new ItemSpriteRenderer(Item::potion, PotionBrewing::THROWABLE_MASK); + renderers[eTYPE_THROWNEXPBOTTLE] = new ItemSpriteRenderer(Item::expBottle); + renderers[eTYPE_FIREBALL] = new FireballRenderer(2.0f); + renderers[eTYPE_SMALL_FIREBALL] = new FireballRenderer(0.5f); + renderers[eTYPE_DRAGON_FIREBALL] = + new FireballRenderer(2.0f); // 4J Added TU9 + renderers[eTYPE_ITEMENTITY] = new ItemRenderer(); + renderers[eTYPE_EXPERIENCEORB] = new ExperienceOrbRenderer(); + renderers[eTYPE_PRIMEDTNT] = new TntRenderer(); + renderers[eTYPE_FALLINGTILE] = new FallingTileRenderer(); + renderers[eTYPE_MINECART] = new MinecartRenderer(); + renderers[eTYPE_BOAT] = new BoatRenderer(); + renderers[eTYPE_FISHINGHOOK] = new FishingHookRenderer(); + renderers[eTYPE_LIGHTNINGBOLT] = new LightningBoltRenderer(); + renderers[eTYPE_ARROW] = new ArrowRenderer(); + glDisable(GL_LIGHTING); - AUTO_VAR(itEnd, renderers.end()); - for( classToRendererMap::iterator it = renderers.begin(); it != itEnd; it++ ) - { - it->second->init(this); - } + AUTO_VAR(itEnd, renderers.end()); + for (classToRendererMap::iterator it = renderers.begin(); it != itEnd; + it++) { + it->second->init(this); + } - isGuiRender = false; // 4J added + isGuiRender = false; // 4J added } -EntityRenderer *EntityRenderDispatcher::getRenderer(eINSTANCEOF e) -{ - //EntityRenderer * r = renderers[e]; - AUTO_VAR(it, renderers.find( e )); // 4J Stu - The .at and [] accessors insert elements if they don't exist +EntityRenderer* EntityRenderDispatcher::getRenderer(eINSTANCEOF e) { + // EntityRenderer * r = renderers[e]; + AUTO_VAR(it, renderers.find(e)); // 4J Stu - The .at and [] accessors + // insert elements if they don't exist - if( it == renderers.end() ) - { - // New renderer mapping required in above table - __debugbreak(); - } - /* 4J - not doing this hierarchical search anymore. We need to explicitly add renderers for any eINSTANCEOF type that we want to be able to render - if (it == renderers.end() && e != Entity::_class) - { - EntityRenderer *r = getRenderer(dynamic_cast( e->getSuperclass() )); - renderers.insert( classToRendererMap::value_type( e, r ) ); - return r; - //assert(false); - }*/ - return it->second; + if (it == renderers.end()) { + // New renderer mapping required in above table + __debugbreak(); + } + /* 4J - not doing this hierarchical search anymore. We need to explicitly +add renderers for any eINSTANCEOF type that we want to be able to render if (it +== renderers.end() && e != Entity::_class) + { + EntityRenderer *r = getRenderer(dynamic_cast( +e->getSuperclass() )); renderers.insert( classToRendererMap::value_type( e, r ) +); return r; + //assert(false); +}*/ + return it->second; } -EntityRenderer *EntityRenderDispatcher::getRenderer(std::shared_ptr e) -{ - return getRenderer(e->GetType()); +EntityRenderer* EntityRenderDispatcher::getRenderer(std::shared_ptr e) { + return getRenderer(e->GetType()); } -void EntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, Options *options, float a) -{ +void EntityRenderDispatcher::prepare(Level* level, Textures* textures, + Font* font, std::shared_ptr player, + Options* options, float a) { this->level = level; this->textures = textures; this->options = options; this->cameraEntity = player; this->font = font; - if (player->isSleeping()) - { - int t = level->getTile(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - if (t == Tile::bed_Id) - { - int data = level->getData(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + if (player->isSleeping()) { + int t = level->getTile(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + if (t == Tile::bed_Id) { + int data = + level->getData(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); int direction = data & 3; playerRotY = (float)(direction * 90 + 180); @@ -197,45 +207,38 @@ void EntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *fon playerRotX = player->xRotO + (player->xRot - player->xRotO) * a; } - std::shared_ptr pl = std::dynamic_pointer_cast(player); - if (pl->ThirdPersonView() == 2) - { - playerRotY += 180; - } + std::shared_ptr pl = std::dynamic_pointer_cast(player); + if (pl->ThirdPersonView() == 2) { + playerRotY += 180; + } xPlayer = player->xOld + (player->x - player->xOld) * a; yPlayer = player->yOld + (player->y - player->yOld) * a; zPlayer = player->zOld + (player->z - player->zOld) * a; - } -void EntityRenderDispatcher::render(std::shared_ptr entity, float a) -{ +void EntityRenderDispatcher::render(std::shared_ptr entity, float a) { double x = entity->xOld + (entity->x - entity->xOld) * a; double y = entity->yOld + (entity->y - entity->yOld) * a; double z = entity->zOld + (entity->z - entity->zOld) * a; - // Fix for #61057 - TU7: Gameplay: Boat is glitching when player float forward and turning. - // Fix to handle the case that yRot and yRotO wrap over the 0/360 line - float rotDiff = entity->yRot - entity->yRotO; - if( rotDiff > 180 || rotDiff < -180) - { - if(entity->yRot > entity->yRotO) - { - rotDiff = (entity->yRot - 360) - entity->yRotO; - } - else - { - rotDiff = entity->yRot - (entity->yRotO - 360); - } - } - float r = entity->yRotO + (rotDiff) * a; - + // Fix for #61057 - TU7: Gameplay: Boat is glitching when player float + // forward and turning. Fix to handle the case that yRot and yRotO wrap over + // the 0/360 line + float rotDiff = entity->yRot - entity->yRotO; + if (rotDiff > 180 || rotDiff < -180) { + if (entity->yRot > entity->yRotO) { + rotDiff = (entity->yRot - 360) - entity->yRotO; + } else { + rotDiff = entity->yRot - (entity->yRotO - 360); + } + } + float r = entity->yRotO + (rotDiff)*a; + int col = entity->getLightColor(a); - if (entity->isOnFire()) - { - col = SharedConstants::FULLBRIGHT_LIGHTVALUE; - } + if (entity->isOnFire()) { + col = SharedConstants::FULLBRIGHT_LIGHTVALUE; + } int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); @@ -244,37 +247,32 @@ void EntityRenderDispatcher::render(std::shared_ptr entity, float a) render(entity, x - xOff, y - yOff, z - zOff, r, a); } -void EntityRenderDispatcher::render(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bItemFrame, bool bRenderPlayerShadow) -{ - EntityRenderer *renderer = getRenderer(entity); - if (renderer != NULL) - { - renderer->SetItemFrame(bItemFrame); - - renderer->render(entity, x, y, z, rot, a); +void EntityRenderDispatcher::render(std::shared_ptr entity, double x, + double y, double z, float rot, float a, + bool bItemFrame, bool bRenderPlayerShadow) { + EntityRenderer* renderer = getRenderer(entity); + if (renderer != NULL) { + renderer->SetItemFrame(bItemFrame); + + renderer->render(entity, x, y, z, rot, a); renderer->postRender(entity, x, y, z, rot, a, bRenderPlayerShadow); } } -double EntityRenderDispatcher::distanceToSqr(double x, double y, double z) -{ +double EntityRenderDispatcher::distanceToSqr(double x, double y, double z) { double xd = x - xPlayer; double yd = y - yPlayer; double zd = z - zPlayer; return xd * xd + yd * yd + zd * zd; } -Font *EntityRenderDispatcher::getFont() -{ - return font; -} +Font* EntityRenderDispatcher::getFont() { return font; } -void EntityRenderDispatcher::registerTerrainTextures(IconRegister *iconRegister) -{ - //for (EntityRenderer renderer : renderers.values()) - for(AUTO_VAR(it, renderers.begin()); it != renderers.end(); ++it) - { - EntityRenderer *renderer = it->second; - renderer->registerTerrainTextures(iconRegister); - } +void EntityRenderDispatcher::registerTerrainTextures( + IconRegister* iconRegister) { + // for (EntityRenderer renderer : renderers.values()) + for (AUTO_VAR(it, renderers.begin()); it != renderers.end(); ++it) { + EntityRenderer* renderer = it->second; + renderer->registerTerrainTextures(iconRegister); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h index 92ac51da6..4e6b50a31 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderDispatcher.h @@ -4,46 +4,53 @@ #include "../../../Minecraft.World/Util/JavaIntHash.h" class font; - -class EntityRenderDispatcher -{ +class EntityRenderDispatcher { public: - static void staticCtor(); // 4J added + static void staticCtor(); // 4J added private: - typedef std::unordered_map classToRendererMap; - classToRendererMap renderers; - // 4J - was: -// Map, EntityRenderer> renderers = new HashMap, EntityRenderer>(); + typedef std::unordered_map + classToRendererMap; + classToRendererMap renderers; + // 4J - was: + // Map, EntityRenderer> renderers + //= new HashMap, EntityRenderer>(); public: - static EntityRenderDispatcher *instance; + static EntityRenderDispatcher* instance; + private: - Font *font; + Font* font; public: - static double xOff, yOff, zOff; + static double xOff, yOff, zOff; - Textures *textures; - ItemInHandRenderer *itemInHandRenderer; - Level *level; + Textures* textures; + ItemInHandRenderer* itemInHandRenderer; + Level* level; std::shared_ptr cameraEntity; float playerRotY; float playerRotX; - Options *options; - bool isGuiRender; // 4J added + Options* options; + bool isGuiRender; // 4J added double xPlayer, yPlayer, zPlayer; private: - EntityRenderDispatcher(); + EntityRenderDispatcher(); + public: - EntityRenderer *getRenderer(eINSTANCEOF e); - EntityRenderer *getRenderer(std::shared_ptr e); - void prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, Options *options, float a); + EntityRenderer* getRenderer(eINSTANCEOF e); + EntityRenderer* getRenderer(std::shared_ptr e); + void prepare(Level* level, Textures* textures, Font* font, + std::shared_ptr player, Options* options, float a); void render(std::shared_ptr entity, float a); - void render(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bItemFrame = false, bool bRenderPlayerShadow = true); - void setLevel(Level *level); + void render(std::shared_ptr entity, double x, double y, double z, + float rot, float a, bool bItemFrame = false, + bool bRenderPlayerShadow = true); + void setLevel(Level* level); double distanceToSqr(double x, double y, double z); - Font *getFont(); - void registerTerrainTextures(IconRegister *iconRegister); + Font* getFont(); + void registerTerrainTextures(IconRegister* iconRegister); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp index 7d3614bd0..485254d0a 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.cpp @@ -13,128 +13,115 @@ #include "../../Player/LocalPlayer.h" // 4J - added -EntityRenderer::EntityRenderer() -{ - model = NULL; - tileRenderer = new TileRenderer(); +EntityRenderer::EntityRenderer() { + model = NULL; + tileRenderer = new TileRenderer(); shadowRadius = 0; shadowStrength = 1.0f; } -EntityRenderer::~EntityRenderer() -{ - delete tileRenderer; -} +EntityRenderer::~EntityRenderer() { delete tileRenderer; } -void EntityRenderer::bindTexture(int resourceName) -{ +void EntityRenderer::bindTexture(int resourceName) { entityRenderDispatcher->textures->bindTexture(resourceName); } -void EntityRenderer::bindTexture(const std::wstring& resourceName) -{ +void EntityRenderer::bindTexture(const std::wstring& resourceName) { entityRenderDispatcher->textures->bindTexture(resourceName); } -bool EntityRenderer::bindTexture(const std::wstring& urlTexture, int backupTexture) -{ - Textures *t = entityRenderDispatcher->textures; +bool EntityRenderer::bindTexture(const std::wstring& urlTexture, + int backupTexture) { + Textures* t = entityRenderDispatcher->textures; - // 4J-PB - no http textures on the xbox, mem textures instead - - //int id = t->loadHttpTexture(urlTexture, backupTexture); - int id = t->loadMemTexture(urlTexture, backupTexture); + // 4J-PB - no http textures on the xbox, mem textures instead - if (id >= 0) - { - glBindTexture(GL_TEXTURE_2D, id); - t->clearLastBoundId(); + // int id = t->loadHttpTexture(urlTexture, backupTexture); + int id = t->loadMemTexture(urlTexture, backupTexture); + + if (id >= 0) { + glBindTexture(GL_TEXTURE_2D, id); + t->clearLastBoundId(); return true; - } - else - { + } else { return false; } } -bool EntityRenderer::bindTexture(const std::wstring& urlTexture, const std::wstring& backupTexture) -{ - Textures *t = entityRenderDispatcher->textures; +bool EntityRenderer::bindTexture(const std::wstring& urlTexture, + const std::wstring& backupTexture) { + Textures* t = entityRenderDispatcher->textures; - // 4J-PB - no http textures on the xbox, mem textures instead - - //int id = t->loadHttpTexture(urlTexture, backupTexture); - int id = t->loadMemTexture(urlTexture, backupTexture); + // 4J-PB - no http textures on the xbox, mem textures instead - if (id >= 0) - { - glBindTexture(GL_TEXTURE_2D, id); - t->clearLastBoundId(); + // int id = t->loadHttpTexture(urlTexture, backupTexture); + int id = t->loadMemTexture(urlTexture, backupTexture); + + if (id >= 0) { + glBindTexture(GL_TEXTURE_2D, id); + t->clearLastBoundId(); return true; - } - else - { + } else { return false; } } -void EntityRenderer::renderFlame(std::shared_ptr e, double x, double y, double z, float a) -{ +void EntityRenderer::renderFlame(std::shared_ptr e, double x, double y, + double z, float a) { glDisable(GL_LIGHTING); - Icon *fire1 = Tile::fire->getTextureLayer(0); - Icon *fire2 = Tile::fire->getTextureLayer(1); + Icon* fire1 = Tile::fire->getTextureLayer(0); + Icon* fire2 = Tile::fire->getTextureLayer(1); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); float s = e->bbWidth * 1.4f; glScalef(s, s, s); - MemSect(31); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); float r = 0.5f; float xo = 0.0f; float h = e->bbHeight / s; - float yo = (float) (e->y - e->bb->y0); + float yo = (float)(e->y - e->bb->y0); glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); - glTranslatef(0, 0, -0.3f + ((int) h) * 0.02f); + glTranslatef(0, 0, -0.3f + ((int)h) * 0.02f); glColor4f(1, 1, 1, 1); float zo = 0; int ss = 0; t->begin(); - while (h > 0) - { - Icon *tex = NULL; - if (ss % 2 == 0) - { + while (h > 0) { + Icon* tex = NULL; + if (ss % 2 == 0) { tex = fire1; - } - else - { + } else { tex = fire2; } - float u0 = tex->getU0(); - float v0 = tex->getV0(); - float u1 = tex->getU1(); - float v1 = tex->getV1(); + float u0 = tex->getU0(); + float v0 = tex->getV0(); + float u1 = tex->getU1(); + float v1 = tex->getV1(); - if (ss / 2 % 2 == 0) - { + if (ss / 2 % 2 == 0) { float tmp = u1; u1 = u0; u0 = tmp; } - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( zo), (float)( u1), (float)( v1)); - t->vertexUV((float)(-r - xo), (float)( 0 - yo), (float)( zo), (float)( u0), (float)( v1)); - t->vertexUV((float)(-r - xo), (float)( 1.4f - yo), (float)( zo), (float)( u0), (float)( v0)); - t->vertexUV((float)(r - xo), (float)( 1.4f - yo), (float)( zo), (float)( u1), (float)( v0)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(zo), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-r - xo), (float)(0 - yo), (float)(zo), (float)(u0), + (float)(v1)); + t->vertexUV((float)(-r - xo), (float)(1.4f - yo), (float)(zo), + (float)(u0), (float)(v0)); + t->vertexUV((float)(r - xo), (float)(1.4f - yo), (float)(zo), + (float)(u1), (float)(v0)); h -= 0.45f; yo -= 0.45f; r *= 0.9f; @@ -144,57 +131,53 @@ void EntityRenderer::renderFlame(std::shared_ptr e, double x, double y, t->end(); glPopMatrix(); glEnable(GL_LIGHTING); - } -void EntityRenderer::renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a) -{ - glDisable(GL_LIGHTING); +void EntityRenderer::renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, float a) { + glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - MemSect(31); - entityRenderDispatcher->textures->bindTexture(TN__CLAMP__MISC_SHADOW);//L"%clamp%/misc/shadow.png")); - MemSect(0); + MemSect(31); + entityRenderDispatcher->textures->bindTexture( + TN__CLAMP__MISC_SHADOW); // L"%clamp%/misc/shadow.png")); + MemSect(0); - Level *level = getLevel(); + Level* level = getLevel(); glDepthMask(false); float r = shadowRadius; - std::shared_ptr mob = std::dynamic_pointer_cast(e); - bool isLocalPlayer = false; - float fYLocalPlayerShadowOffset=0.0f; + std::shared_ptr mob = std::dynamic_pointer_cast(e); + bool isLocalPlayer = false; + float fYLocalPlayerShadowOffset = 0.0f; - //if (std::dynamic_pointer_cast(e) != NULL) - if (mob != NULL) - { - //std::shared_ptr mob = std::dynamic_pointer_cast(e); - r *= mob->getSizeScale(); + // if (std::dynamic_pointer_cast(e) != NULL) + if (mob != NULL) { + // std::shared_ptr mob = std::dynamic_pointer_cast(e); + r *= mob->getSizeScale(); - std::shared_ptr animal = std::dynamic_pointer_cast(mob); - if (animal != NULL) - { - if (animal->isBaby()) - { - r *= 0.5f; - } - } + std::shared_ptr animal = std::dynamic_pointer_cast(mob); + if (animal != NULL) { + if (animal->isBaby()) { + r *= 0.5f; + } + } - if(std::dynamic_pointer_cast(mob)!=NULL) - { - isLocalPlayer=true; - } - } + if (std::dynamic_pointer_cast(mob) != NULL) { + isLocalPlayer = true; + } + } double ex = e->xOld + (e->x - e->xOld) * a; double ey = e->yOld + (e->y - e->yOld) * a + e->getShadowHeightOffs(); - // 4J-PB - local players seem to have a position at their head, and remote players have a foot position. - // get the shadow to render by changing the check here depending on the player type - if(isLocalPlayer) - { - ey-=1.62; - fYLocalPlayerShadowOffset=-1.62f; - } + // 4J-PB - local players seem to have a position at their head, and remote + // players have a foot position. get the shadow to render by changing the + // check here depending on the player type + if (isLocalPlayer) { + ey -= 1.62; + fYLocalPlayerShadowOffset = -1.62f; + } double ez = e->zOld + (e->z - e->zOld) * a; int x0 = Mth::floor(ex - r); @@ -205,45 +188,48 @@ void EntityRenderer::renderShadow(std::shared_ptr e, double x, double y, int z1 = Mth::floor(ez + r); double xo = x - ex; - double yo = y - ey; + double yo = y - ey; double zo = z - ez; - Tesselator *tt = Tesselator::getInstance(); + Tesselator* tt = Tesselator::getInstance(); tt->begin(); for (int xt = x0; xt <= x1; xt++) for (int yt = y0; yt <= y1; yt++) - for (int zt = z0; zt <= z1; zt++) - { - int t = level->getTile(xt, yt - 1, zt); - if (t > 0 && level->getRawBrightness(xt, yt, zt) > 3) - { - renderTileShadow(Tile::tiles[t], x, y + e->getShadowHeightOffs() + fYLocalPlayerShadowOffset, z, xt, yt , zt, pow, r, xo, yo + e->getShadowHeightOffs() + fYLocalPlayerShadowOffset, zo); - } + for (int zt = z0; zt <= z1; zt++) { + int t = level->getTile(xt, yt - 1, zt); + if (t > 0 && level->getRawBrightness(xt, yt, zt) > 3) { + renderTileShadow(Tile::tiles[t], x, + y + e->getShadowHeightOffs() + + fYLocalPlayerShadowOffset, + z, xt, yt, zt, pow, r, xo, + yo + e->getShadowHeightOffs() + + fYLocalPlayerShadowOffset, + zo); + } } tt->end(); glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); glDepthMask(true); - glEnable(GL_LIGHTING); - + glEnable(GL_LIGHTING); } -Level *EntityRenderer::getLevel() -{ - return entityRenderDispatcher->level; -} +Level* EntityRenderer::getLevel() { return entityRenderDispatcher->level; } -void EntityRenderer::renderTileShadow(Tile *tt, double x, double y, double z, int xt, int yt, int zt, float pow, float r, double xo, double yo, double zo) -{ - Tesselator *t = Tesselator::getInstance(); +void EntityRenderer::renderTileShadow(Tile* tt, double x, double y, double z, + int xt, int yt, int zt, float pow, + float r, double xo, double yo, + double zo) { + Tesselator* t = Tesselator::getInstance(); if (!tt->isCubeShaped()) return; - double a = ((pow - (y - (yt + yo)) / 2) * 0.5f) * getLevel()->getBrightness(xt, yt, zt); + double a = ((pow - (y - (yt + yo)) / 2) * 0.5f) * + getLevel()->getBrightness(xt, yt, zt); if (a < 0) return; if (a > 1) a = 1; - - t->color(1.0f, 1.0f, 1.0f, (float) a); + + t->color(1.0f, 1.0f, 1.0f, (float)a); // glColor4f(1, 1, 1, (float) a); double x0 = xt + tt->getShapeX0() + xo; @@ -252,159 +238,160 @@ void EntityRenderer::renderTileShadow(Tile *tt, double x, double y, double z, in double z0 = zt + tt->getShapeZ0() + zo; double z1 = zt + tt->getShapeZ1() + zo; - float u0 = (float) ((x - (x0)) / 2 / r + 0.5f); - float u1 = (float) ((x - (x1)) / 2 / r + 0.5f); - float v0 = (float) ((z - (z0)) / 2 / r + 0.5f); - float v1 = (float) ((z - (z1)) / 2 / r + 0.5f); + float u0 = (float)((x - (x0)) / 2 / r + 0.5f); + float u1 = (float)((x - (x1)) / 2 / r + 0.5f); + float v0 = (float)((z - (z0)) / 2 / r + 0.5f); + float v1 = (float)((z - (z1)) / 2 / r + 0.5f); // u0 = 0; // v0 = 0; // u1 = 1; // v1 = 1; - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( u0), (float)( v0)); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( u0), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( u1), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( u1), (float)( v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u1), + (float)(v0)); } -void EntityRenderer::render(AABB *bb, double xo, double yo, double zo) -{ +void EntityRenderer::render(AABB* bb, double xo, double yo, double zo) { glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glColor4f(1, 1, 1, 1); t->begin(); t->offset((float)xo, (float)yo, (float)zo); t->normal(0, 0, -1); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); t->normal(0, 0, 1); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); t->normal(0, -1, 0); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); t->normal(0, 1, 0); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); t->normal(-1, 0, 0); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); t->normal(1, 0, 0); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); t->offset(0, 0, 0); t->end(); glEnable(GL_TEXTURE_2D); // model.render(0, 1) } -void EntityRenderer::renderFlat(AABB *bb) -{ - Tesselator *t = Tesselator::getInstance(); +void EntityRenderer::renderFlat(AABB* bb) { + Tesselator* t = Tesselator::getInstance(); t->begin(); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x0), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x0), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z0)); - t->vertex((float)(bb->x1), (float)( bb->y1), (float)( bb->z1)); - t->vertex((float)(bb->x1), (float)( bb->y0), (float)( bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x0), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x0), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z0)); + t->vertex((float)(bb->x1), (float)(bb->y1), (float)(bb->z1)); + t->vertex((float)(bb->x1), (float)(bb->y0), (float)(bb->z1)); t->end(); } -void EntityRenderer::renderFlat(float x0, float y0, float z0, float x1, float y1, float z1) -{ - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->vertex(x0, y1, z0); - t->vertex(x1, y1, z0); - t->vertex(x1, y0, z0); - t->vertex(x0, y0, z0); - t->vertex(x0, y0, z1); - t->vertex(x1, y0, z1); - t->vertex(x1, y1, z1); - t->vertex(x0, y1, z1); - t->vertex(x0, y0, z0); - t->vertex(x1, y0, z0); - t->vertex(x1, y0, z1); - t->vertex(x0, y0, z1); - t->vertex(x0, y1, z1); - t->vertex(x1, y1, z1); - t->vertex(x1, y1, z0); - t->vertex(x0, y1, z0); - t->vertex(x0, y0, z1); - t->vertex(x0, y1, z1); - t->vertex(x0, y1, z0); - t->vertex(x0, y0, z0); - t->vertex(x1, y0, z0); - t->vertex(x1, y1, z0); - t->vertex(x1, y1, z1); - t->vertex(x1, y0, z1); - t->end(); +void EntityRenderer::renderFlat(float x0, float y0, float z0, float x1, + float y1, float z1) { + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->vertex(x0, y1, z0); + t->vertex(x1, y1, z0); + t->vertex(x1, y0, z0); + t->vertex(x0, y0, z0); + t->vertex(x0, y0, z1); + t->vertex(x1, y0, z1); + t->vertex(x1, y1, z1); + t->vertex(x0, y1, z1); + t->vertex(x0, y0, z0); + t->vertex(x1, y0, z0); + t->vertex(x1, y0, z1); + t->vertex(x0, y0, z1); + t->vertex(x0, y1, z1); + t->vertex(x1, y1, z1); + t->vertex(x1, y1, z0); + t->vertex(x0, y1, z0); + t->vertex(x0, y0, z1); + t->vertex(x0, y1, z1); + t->vertex(x0, y1, z0); + t->vertex(x0, y0, z0); + t->vertex(x1, y0, z0); + t->vertex(x1, y1, z0); + t->vertex(x1, y1, z1); + t->vertex(x1, y0, z1); + t->end(); } -void EntityRenderer::init(EntityRenderDispatcher *entityRenderDispatcher) -{ - this->entityRenderDispatcher = entityRenderDispatcher; +void EntityRenderer::init(EntityRenderDispatcher* entityRenderDispatcher) { + this->entityRenderDispatcher = entityRenderDispatcher; } -void EntityRenderer::postRender(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bRenderPlayerShadow) -{ - if( !entityRenderDispatcher->isGuiRender ) // 4J - added, don't render shadow in gui as it uses its own blending, and we have globally enabled blending for interface opacity - { - if (bRenderPlayerShadow && entityRenderDispatcher->options->fancyGraphics && shadowRadius > 0 && !entity->isInvisible()) - { - double dist = entityRenderDispatcher->distanceToSqr(entity->x, entity->y, entity->z); - float pow = (float) ((1 - dist / (16.0f * 16.0f)) * shadowStrength); - if (pow > 0) - { - renderShadow(entity, x, y, z, pow, a); - } - } - } - if (entity->isOnFire()) renderFlame(entity, x, y, z, a); +void EntityRenderer::postRender(std::shared_ptr entity, double x, + double y, double z, float rot, float a, + bool bRenderPlayerShadow) { + if (!entityRenderDispatcher + ->isGuiRender) // 4J - added, don't render shadow in gui as it + // uses its own blending, and we have globally + // enabled blending for interface opacity + { + if (bRenderPlayerShadow && + entityRenderDispatcher->options->fancyGraphics && + shadowRadius > 0 && !entity->isInvisible()) { + double dist = entityRenderDispatcher->distanceToSqr( + entity->x, entity->y, entity->z); + float pow = (float)((1 - dist / (16.0f * 16.0f)) * shadowStrength); + if (pow > 0) { + renderShadow(entity, x, y, z, pow, a); + } + } + } + if (entity->isOnFire()) renderFlame(entity, x, y, z, a); } -Font *EntityRenderer::getFont() -{ - return entityRenderDispatcher->getFont(); -} +Font* EntityRenderer::getFont() { return entityRenderDispatcher->getFont(); } -void EntityRenderer::registerTerrainTextures(IconRegister *iconRegister) -{ -} \ No newline at end of file +void EntityRenderer::registerTerrainTextures(IconRegister* iconRegister) {} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h index 4337d84d1..21a7969ce 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityRenderer.h @@ -11,55 +11,69 @@ class Level; class AABB; class IconRegister; - - class EntityRenderDispatcher; class Font; // 4J - this was originally a generic of type EntityRenderer -class EntityRenderer -{ - friend class PlayerRenderer; // 4J Added to allow PlayerRenderer to call renderShadow +class EntityRenderer { + friend class PlayerRenderer; // 4J Added to allow PlayerRenderer to call + // renderShadow protected: - EntityRenderDispatcher *entityRenderDispatcher; + EntityRenderDispatcher* entityRenderDispatcher; private: - Model *model; // 4J - TODO - check why exactly this is here, it seems to get shadowed by classes inheriting from this by their own + Model* model; // 4J - TODO - check why exactly this is here, it seems to + // get shadowed by classes inheriting from this by their own protected: - TileRenderer *tileRenderer; // 4J - changed to protected so derived classes can use instead of shadowing their own + TileRenderer* tileRenderer; // 4J - changed to protected so derived classes + // can use instead of shadowing their own protected: - float shadowRadius; + float shadowRadius; float shadowStrength; public: - EntityRenderer(); // 4J - added - virtual ~EntityRenderer(); + EntityRenderer(); // 4J - added + virtual ~EntityRenderer(); + public: - virtual void render(std::shared_ptr entity, double x, double y, double z, float rot, float a) = 0; + virtual void render(std::shared_ptr entity, double x, double y, + double z, float rot, float a) = 0; + protected: - virtual void bindTexture(int resourceName); // 4J - added - virtual void bindTexture(const std::wstring& resourceName); + virtual void bindTexture(int resourceName); // 4J - added + virtual void bindTexture(const std::wstring& resourceName); + + virtual bool bindTexture(const std::wstring& urlTexture, + int backupTexture); // 4J added + virtual bool bindTexture(const std::wstring& urlTexture, + const std::wstring& backupTexture); - virtual bool bindTexture(const std::wstring& urlTexture, int backupTexture); // 4J added - virtual bool bindTexture(const std::wstring& urlTexture, const std::wstring& backupTexture); private: - virtual void renderFlame(std::shared_ptr e, double x, double y, double z, float a); - virtual void renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a); + virtual void renderFlame(std::shared_ptr e, double x, double y, + double z, float a); + virtual void renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, float a); - virtual Level *getLevel(); - virtual void renderTileShadow(Tile *tt, double x, double y, double z, int xt, int yt, int zt, float pow, float r, double xo, double yo, double zo); -public: - virtual void render(AABB *bb, double xo, double yo, double zo); - static void renderFlat(AABB *bb); - static void renderFlat(float x0, float y0, float z0, float x1, float y1, float z1); - virtual void init(EntityRenderDispatcher *entityRenderDispatcher); - virtual void postRender(std::shared_ptr entity, double x, double y, double z, float rot, float a, bool bRenderPlayerShadow); - virtual Font *getFont(); - virtual void registerTerrainTextures(IconRegister *iconRegister); + virtual Level* getLevel(); + virtual void renderTileShadow(Tile* tt, double x, double y, double z, + int xt, int yt, int zt, float pow, float r, + double xo, double yo, double zo); public: - // 4J Added - virtual Model *getModel() { return model; } - virtual void SetItemFrame(bool bSet) {} + virtual void render(AABB* bb, double xo, double yo, double zo); + static void renderFlat(AABB* bb); + static void renderFlat(float x0, float y0, float z0, float x1, float y1, + float z1); + virtual void init(EntityRenderDispatcher* entityRenderDispatcher); + virtual void postRender(std::shared_ptr entity, double x, double y, + double z, float rot, float a, + bool bRenderPlayerShadow); + virtual Font* getFont(); + virtual void registerTerrainTextures(IconRegister* iconRegister); + +public: + // 4J Added + virtual Model* getModel() { return model; } + virtual void SetItemFrame(bool bSet) {} }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp index 844260ea5..0d6423815 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.cpp @@ -3,22 +3,21 @@ #include "TileEntityRenderDispatcher.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.entity.h" -EntityTileRenderer *EntityTileRenderer::instance = new EntityTileRenderer; +EntityTileRenderer* EntityTileRenderer::instance = new EntityTileRenderer; -EntityTileRenderer::EntityTileRenderer() -{ - chest = std::shared_ptr(new ChestTileEntity()); - enderChest = std::shared_ptr(new EnderChestTileEntity()); +EntityTileRenderer::EntityTileRenderer() { + chest = std::shared_ptr(new ChestTileEntity()); + enderChest = + std::shared_ptr(new EnderChestTileEntity()); } -void EntityTileRenderer::render(Tile *tile, int data, float brightness, float alpha, bool setColor, bool useCompiled) -{ - if (tile->id == Tile::enderChest_Id) - { - TileEntityRenderDispatcher::instance->render(enderChest, 0, 0, 0, 0, setColor, alpha, useCompiled); - } - else - { - TileEntityRenderDispatcher::instance->render(chest, 0, 0, 0, 0, setColor, alpha, useCompiled); - } +void EntityTileRenderer::render(Tile* tile, int data, float brightness, + float alpha, bool setColor, bool useCompiled) { + if (tile->id == Tile::enderChest_Id) { + TileEntityRenderDispatcher::instance->render( + enderChest, 0, 0, 0, 0, setColor, alpha, useCompiled); + } else { + TileEntityRenderDispatcher::instance->render( + chest, 0, 0, 0, 0, setColor, alpha, useCompiled); + } } diff --git a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h index 14ba6bfc6..a9d5ab6e1 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/EntityTileRenderer.h @@ -4,16 +4,19 @@ class ChestTileEntity; class EnderChestTileEntity; class Tile; -class EntityTileRenderer - { - public: - static EntityTileRenderer *instance; +class EntityTileRenderer { +public: + static EntityTileRenderer* instance; - private: - std::shared_ptr chest; - std::shared_ptr enderChest; +private: + std::shared_ptr chest; + std::shared_ptr enderChest; - public: - EntityTileRenderer(); - void render(Tile *tile, int data, float brightness, float alpha, bool setColor = true, bool useCompiled = true); // 4J - added setColor parameter and alpha for chest in the crafting menu, and added useCompiled +public: + EntityTileRenderer(); + void render(Tile* tile, int data, float brightness, float alpha, + bool setColor = true, + bool useCompiled = + true); // 4J - added setColor parameter and alpha for chest + // in the crafting menu, and added useCompiled }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp index 78ec3bceb..a5e767353 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.cpp @@ -8,84 +8,78 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Util/JavaMath.h" -ExperienceOrbRenderer::ExperienceOrbRenderer() -{ - // 4J In class Java initialisors - tileRenderer = new TileRenderer(); - setColor = true; +ExperienceOrbRenderer::ExperienceOrbRenderer() { + // 4J In class Java initialisors + tileRenderer = new TileRenderer(); + setColor = true; - this->shadowRadius = 0.15f; - this->shadowStrength = 0.75f; + this->shadowRadius = 0.15f; + this->shadowStrength = 0.75f; } +void ExperienceOrbRenderer::render(std::shared_ptr _orb, double x, + double y, double z, float rot, float a) { + std::shared_ptr orb = + std::dynamic_pointer_cast(_orb); + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); -void ExperienceOrbRenderer::render(std::shared_ptr _orb, double x, double y, double z, float rot, float a) -{ - std::shared_ptr orb = std::dynamic_pointer_cast(_orb); - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + int icon = orb->getIcon(); + bindTexture(TN_ITEM_EXPERIENCE_ORB); // 4J was L"/item/xporb.png" + Tesselator* t = Tesselator::getInstance(); - int icon = orb->getIcon(); - bindTexture(TN_ITEM_EXPERIENCE_ORB); // 4J was L"/item/xporb.png" - Tesselator *t = Tesselator::getInstance(); + float u0 = ((icon % 4) * 16 + 0) / 64.0f; + float u1 = ((icon % 4) * 16 + 16) / 64.0f; + float v0 = ((icon / 4) * 16 + 0) / 64.0f; + float v1 = ((icon / 4) * 16 + 16) / 64.0f; - float u0 = ((icon % 4) * 16 + 0) / 64.0f; - float u1 = ((icon % 4) * 16 + 16) / 64.0f; - float v0 = ((icon / 4) * 16 + 0) / 64.0f; - float v1 = ((icon / 4) * 16 + 16) / 64.0f; + float r = 1.0f; + float xo = 0.5f; + float yo = 0.25f; + if (SharedConstants::TEXTURE_LIGHTING) { + int col = orb->getLightColor(a); + int u = col % 65536; + int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } else { + float br = orb->getBrightness(a); + glColor4f(br, br, br, 1); + } + float br = 255.0f; + float rr = (orb->tickCount + a) / 2; + int rc = (int)((Mth::sin(rr + 0 * PI * 2 / 3) + 1) * 0.5f * br); + int gc = (int)(br); + int bc = (int)((Mth::sin(rr + 2 * PI * 2 / 3) + 1) * 0.1f * br); + int col = rc << 16 | gc << 8 | bc; + glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); + glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); + float s = 0.3f; + glScalef(s, s, s); + t->begin(); + t->color(col, 128); + t->normal(0, 1, 0); + t->vertexUV(0 - xo, 0 - yo, 0, u0, v1); + t->vertexUV(r - xo, 0 - yo, 0, u1, v1); + t->vertexUV(r - xo, 1 - yo, 0, u1, v0); + t->vertexUV(0 - xo, 1 - yo, 0, u0, v0); + t->end(); - float r = 1.0f; - float xo = 0.5f; - float yo = 0.25f; - - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = orb->getLightColor(a); - int u = col % 65536; - int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } - else - { - float br = orb->getBrightness(a); - glColor4f(br, br, br, 1); - } - float br = 255.0f; - float rr = (orb->tickCount + a) / 2; - int rc = (int) ((Mth::sin(rr + 0 * PI * 2 / 3) + 1) * 0.5f * br); - int gc = (int) (br); - int bc = (int) ((Mth::sin(rr + 2 * PI * 2 / 3) + 1) * 0.1f * br); - int col = rc << 16 | gc << 8 | bc; - glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); - glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); - float s = 0.3f; - glScalef(s, s, s); - t->begin(); - t->color(col, 128); - t->normal(0, 1, 0); - t->vertexUV(0 - xo, 0 - yo, 0, u0, v1); - t->vertexUV(r - xo, 0 - yo, 0, u1, v1); - t->vertexUV(r - xo, 1 - yo, 0, u1, v0); - t->vertexUV(0 - xo, 1 - yo, 0, u0, v0); - t->end(); - - glDisable(GL_BLEND); - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); + glDisable(GL_BLEND); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); } -void ExperienceOrbRenderer::blit(int x, int y, int sx, int sy, int w, int h) -{ - float blitOffset = 0; - float us = 1 / 256.0f; - float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->vertexUV(x + 0, y + h, blitOffset, (sx + 0) * us, (sy + h) * vs); - t->vertexUV(x + w, y + h, blitOffset, (sx + w) * us, (sy + h) * vs); - t->vertexUV(x + w, y + 0, blitOffset, (sx + w) * us, (sy + 0) * vs); - t->vertexUV(x + 0, y + 0, blitOffset, (sx + 0) * us, (sy + 0) * vs); - t->end(); +void ExperienceOrbRenderer::blit(int x, int y, int sx, int sy, int w, int h) { + float blitOffset = 0; + float us = 1 / 256.0f; + float vs = 1 / 256.0f; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->vertexUV(x + 0, y + h, blitOffset, (sx + 0) * us, (sy + h) * vs); + t->vertexUV(x + w, y + h, blitOffset, (sx + w) * us, (sy + h) * vs); + t->vertexUV(x + w, y + 0, blitOffset, (sx + w) * us, (sy + 0) * vs); + t->vertexUV(x + 0, y + 0, blitOffset, (sx + 0) * us, (sy + 0) * vs); + t->end(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h index 5237ecb8d..2812f9280 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ExperienceOrbRenderer.h @@ -2,16 +2,16 @@ #include "EntityRenderer.h" -class ExperienceOrbRenderer : public EntityRenderer -{ +class ExperienceOrbRenderer : public EntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - bool setColor; + bool setColor; - ExperienceOrbRenderer(); + ExperienceOrbRenderer(); - void render(std::shared_ptr _orb, double x, double y, double z, float rot, float a); - void blit(int x, int y, int sx, int sy, int w, int h); + void render(std::shared_ptr _orb, double x, double y, double z, + float rot, float a); + void blit(int x, int y, int sx, int sy, int w, int h); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp index dc046ec1f..d47bf7efa 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.cpp @@ -6,51 +6,57 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" #include "EntityRenderDispatcher.h" -FallingTileRenderer::FallingTileRenderer() : EntityRenderer() -{ - tileRenderer = new TileRenderer(); - this->shadowRadius = 0.5f; +FallingTileRenderer::FallingTileRenderer() : EntityRenderer() { + tileRenderer = new TileRenderer(); + this->shadowRadius = 0.5f; } -void FallingTileRenderer::render(std::shared_ptr _tile, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr tile = std::dynamic_pointer_cast(_tile); - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); +void FallingTileRenderer::render(std::shared_ptr _tile, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr tile = + std::dynamic_pointer_cast(_tile); + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - Tile *tt = Tile::tiles[tile->tile]; + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + Tile* tt = Tile::tiles[tile->tile]; - Level *level = tile->getLevel(); + Level* level = tile->getLevel(); - glDisable(GL_LIGHTING); - glColor4f(1, 1, 1, 1); // 4J added - this wouldn't be needed in real opengl as the block render has vertex colours and so this isn't use, but our pretend gl always modulates with this - if (tt == Tile::anvil && tt->getRenderShape() == Tile::SHAPE_ANVIL) - { - tileRenderer->level = level; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, -Mth::floor(tile->z) - 0.5f); - tileRenderer->tesselateAnvilInWorld((AnvilTile *) tt, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z), tile->data); - t->offset(0, 0, 0); - t->end(); - } - else if (tt == Tile::dragonEgg) - { - tileRenderer->level = level; - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, -Mth::floor(tile->z) - 0.5f); - tileRenderer->tesselateInWorld(tt, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z)); - t->offset(0, 0, 0); - t->end(); - } - else if( tt != NULL ) - { - tileRenderer->setShape(tt); - tileRenderer->renderBlock(tt, level, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z), tile->data); - } - glEnable(GL_LIGHTING); - glPopMatrix(); + glDisable(GL_LIGHTING); + glColor4f(1, 1, 1, + 1); // 4J added - this wouldn't be needed in real opengl as the + // block render has vertex colours and so this isn't use, but + // our pretend gl always modulates with this + if (tt == Tile::anvil && tt->getRenderShape() == Tile::SHAPE_ANVIL) { + tileRenderer->level = level; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, + -Mth::floor(tile->z) - 0.5f); + tileRenderer->tesselateAnvilInWorld((AnvilTile*)tt, Mth::floor(tile->x), + Mth::floor(tile->y), + Mth::floor(tile->z), tile->data); + t->offset(0, 0, 0); + t->end(); + } else if (tt == Tile::dragonEgg) { + tileRenderer->level = level; + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->offset(-Mth::floor(tile->x) - 0.5f, -Mth::floor(tile->y) - 0.5f, + -Mth::floor(tile->z) - 0.5f); + tileRenderer->tesselateInWorld( + tt, Mth::floor(tile->x), Mth::floor(tile->y), Mth::floor(tile->z)); + t->offset(0, 0, 0); + t->end(); + } else if (tt != NULL) { + tileRenderer->setShape(tt); + tileRenderer->renderBlock(tt, level, Mth::floor(tile->x), + Mth::floor(tile->y), Mth::floor(tile->z), + tile->data); + } + glEnable(GL_LIGHTING); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h index c3181c968..30772c7de 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/FallingTileRenderer.h @@ -1,14 +1,13 @@ #pragma once #include "EntityRenderer.h" - -class FallingTileRenderer : public EntityRenderer -{ +class FallingTileRenderer : public EntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - FallingTileRenderer(); + FallingTileRenderer(); - virtual void render(std::shared_ptr _tile, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _tile, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp index cfbf5e334..32c72d991 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.cpp @@ -7,27 +7,27 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.phys.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -FireballRenderer::FireballRenderer(float scale) -{ - this->scale = scale; -} +FireballRenderer::FireballRenderer(float scale) { this->scale = scale; } -void FireballRenderer::render(std::shared_ptr _fireball, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr fireball = std::dynamic_pointer_cast(_fireball); +void FireballRenderer::render(std::shared_ptr _fireball, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr fireball = + std::dynamic_pointer_cast(_fireball); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glEnable(GL_RESCALE_NORMAL); float s = scale; glScalef(s / 1.0f, s / 1.0f, s / 1.0f); - Icon *icon = Item::fireball->getIcon(fireball->GetType()==eTYPE_DRAGON_FIREBALL?1:0);//14 + 2 * 16; - MemSect(31); - bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + Icon* icon = Item::fireball->getIcon( + fireball->GetType() == eTYPE_DRAGON_FIREBALL ? 1 : 0); // 14 + 2 * 16; + MemSect(31); + bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); float u0 = icon->getU0(); float u1 = icon->getU1(); @@ -42,66 +42,72 @@ void FireballRenderer::render(std::shared_ptr _fireball, double x, doubl glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1 - yo), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1 - yo), (float)(0), (float)(u0), + (float)(v0)); t->end(); glDisable(GL_RESCALE_NORMAL); glPopMatrix(); - } // 4J Added override. Based on EntityRenderer::renderFlame -void FireballRenderer::renderFlame(std::shared_ptr e, double x, double y, double z, float a) -{ - glDisable(GL_LIGHTING); - Icon *tex = Tile::fire->getTextureLayer(0); +void FireballRenderer::renderFlame(std::shared_ptr e, double x, + double y, double z, float a) { + glDisable(GL_LIGHTING); + Icon* tex = Tile::fire->getTextureLayer(0); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); float s = e->bbWidth * 1.4f; glScalef(s, s, s); - MemSect(31); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); float r = 1.0f; float xo = 0.5f; -// float yo = 0.0f; + // float yo = 0.0f; float h = e->bbHeight / s; - float yo = (float) (e->y - e->bb->y0); + float yo = (float)(e->y - e->bb->y0); - //glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); + // glRotatef(-entityRenderDispatcher->playerRotY, 0, 1, 0); - glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); - glTranslatef(0,0,0.1f); - //glTranslatef(0, 0, -0.3f + ((int) h) * 0.02f); + glTranslatef(0, 0, 0.1f); + // glTranslatef(0, 0, -0.3f + ((int) h) * 0.02f); glColor4f(1, 1, 1, 1); // glRotatef(-playerRotX, 1, 0, 0); float zo = 0; t->begin(); - t->normal(0, 1, 0); + t->normal(0, 1, 0); - float u0 = tex->getU0(); - float v0 = tex->getV0(); - float u1 = tex->getU1(); - float v1 = tex->getV1(); + float u0 = tex->getU0(); + float v0 = tex->getV0(); + float u1 = tex->getU1(); + float v1 = tex->getV1(); - float tmp = u1; - u1 = u0; - u0 = tmp; + float tmp = u1; + u1 = u0; + u0 = tmp; - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1.4f - yo), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1.4f - yo), (float)( 0), (float)( u1), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1.4f - yo), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1.4f - yo), (float)(0), (float)(u1), + (float)(v0)); t->end(); glPopMatrix(); diff --git a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h index 201e3aad1..cbe2fb37d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/FireballRenderer.h @@ -1,17 +1,18 @@ #pragma once #include "EntityRenderer.h" -class FireballRenderer : public EntityRenderer -{ +class FireballRenderer : public EntityRenderer { private: - float scale; + float scale; public: - FireballRenderer(float scale); + FireballRenderer(float scale); - virtual void render(std::shared_ptr _fireball, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _fireball, double x, double y, + double z, float rot, float a); private: - // 4J Added override - virtual void renderFlame(std::shared_ptr e, double x, double y, double z, float a); + // 4J Added override + virtual void renderFlame(std::shared_ptr e, double x, double y, + double z, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp index 4f30ed9cf..b329752fd 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.cpp @@ -8,27 +8,28 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../Player/MultiPlayerLocalPlayer.h" -void FishingHookRenderer::render(std::shared_ptr _hook, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr hook = std::dynamic_pointer_cast(_hook); +void FishingHookRenderer::render(std::shared_ptr _hook, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr hook = + std::dynamic_pointer_cast(_hook); glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glEnable(GL_RESCALE_NORMAL); glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); int xi = 1; int yi = 2; - bindTexture(TN_PARTICLES); // 4J was L"/particles.png" - Tesselator *t = Tesselator::getInstance(); + bindTexture(TN_PARTICLES); // 4J was L"/particles.png" + Tesselator* t = Tesselator::getInstance(); float u0 = ((xi) * 8 + 0) / 128.0f; float u1 = ((xi) * 8 + 8) / 128.0f; float v0 = ((yi) * 8 + 0) / 128.0f; float v1 = ((yi) * 8 + 8) / 128.0f; - float r = 1.0f; float xo = 0.5f; float yo = 0.5f; @@ -37,62 +38,79 @@ void FishingHookRenderer::render(std::shared_ptr _hook, double x, double glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1 - yo), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1 - yo), (float)(0), (float)(u0), + (float)(v0)); t->end(); glDisable(GL_RESCALE_NORMAL); glPopMatrix(); - - if (hook->owner != NULL) - { + if (hook->owner != NULL) { float swing = hook->owner->getAttackAnim(a); - float swing2 = (float) Mth::sin((sqrt(swing)) * PI); + float swing2 = (float)Mth::sin((sqrt(swing)) * PI); - - Vec3 *vv = Vec3::newTemp(-0.5, 0.03, 0.8); - vv->xRot(-(hook->owner->xRotO + (hook->owner->xRot - hook->owner->xRotO) * a) * PI / 180); - vv->yRot(-(hook->owner->yRotO + (hook->owner->yRot - hook->owner->yRotO) * a) * PI / 180); + Vec3* vv = Vec3::newTemp(-0.5, 0.03, 0.8); + vv->xRot(-(hook->owner->xRotO + + (hook->owner->xRot - hook->owner->xRotO) * a) * + PI / 180); + vv->yRot(-(hook->owner->yRotO + + (hook->owner->yRot - hook->owner->yRotO) * a) * + PI / 180); vv->yRot(swing2 * 0.5f); vv->xRot(-swing2 * 0.7f); - double xp = hook->owner->xo + (hook->owner->x - hook->owner->xo) * a + vv->x; - double yp = hook->owner->yo + (hook->owner->y - hook->owner->yo) * a + vv->y; - double zp = hook->owner->zo + (hook->owner->z - hook->owner->zo) * a + vv->z; - double yOffset = hook->owner != std::dynamic_pointer_cast(Minecraft::GetInstance()->player) ? hook->owner->getHeadHeight() : 0; + double xp = + hook->owner->xo + (hook->owner->x - hook->owner->xo) * a + vv->x; + double yp = + hook->owner->yo + (hook->owner->y - hook->owner->yo) * a + vv->y; + double zp = + hook->owner->zo + (hook->owner->z - hook->owner->zo) * a + vv->z; + double yOffset = hook->owner != std::dynamic_pointer_cast( + Minecraft::GetInstance()->player) + ? hook->owner->getHeadHeight() + : 0; - // 4J-PB - changing this to be per player - //if (this->entityRenderDispatcher->options->thirdPersonView) - if (hook->owner->ThirdPersonView() > 0) - { - float rr = (float) (hook->owner->yBodyRotO + (hook->owner->yBodyRot - hook->owner->yBodyRotO) * a) * PI / 180; - double ss = Mth::sin((float) rr); - double cc = Mth::cos((float) rr); - xp = hook->owner->xo + (hook->owner->x - hook->owner->xo) * a - cc * 0.35 - ss * 0.85; - yp = hook->owner->yo + yOffset + (hook->owner->y - hook->owner->yo) * a - 0.45; - zp = hook->owner->zo + (hook->owner->z - hook->owner->zo) * a - ss * 0.35 + cc * 0.85; + // 4J-PB - changing this to be per player + // if (this->entityRenderDispatcher->options->thirdPersonView) + if (hook->owner->ThirdPersonView() > 0) { + float rr = + (float)(hook->owner->yBodyRotO + + (hook->owner->yBodyRot - hook->owner->yBodyRotO) * a) * + PI / 180; + double ss = Mth::sin((float)rr); + double cc = Mth::cos((float)rr); + xp = hook->owner->xo + (hook->owner->x - hook->owner->xo) * a - + cc * 0.35 - ss * 0.85; + yp = hook->owner->yo + yOffset + + (hook->owner->y - hook->owner->yo) * a - 0.45; + zp = hook->owner->zo + (hook->owner->z - hook->owner->zo) * a - + ss * 0.35 + cc * 0.85; } double xh = hook->xo + (hook->x - hook->xo) * a; double yh = hook->yo + (hook->y - hook->yo) * a + 4 / 16.0f; double zh = hook->zo + (hook->z - hook->zo) * a; - double xa = (float) (xp - xh); - double ya = (float) (yp - yh); - double za = (float) (zp - zh); + double xa = (float)(xp - xh); + double ya = (float)(yp - yh); + double za = (float)(zp - zh); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); t->begin(GL_LINE_STRIP); t->color(0x000000); int steps = 16; - for (int i = 0; i <= steps; i++) - { - float aa = i / (float) steps; - t->vertex((float)(x + xa * aa), (float)( y + ya * (aa * aa + aa) * 0.5 + 4 / 16.0f), (float)( z + za * aa)); + for (int i = 0; i <= steps; i++) { + float aa = i / (float)steps; + t->vertex((float)(x + xa * aa), + (float)(y + ya * (aa * aa + aa) * 0.5 + 4 / 16.0f), + (float)(z + za * aa)); } t->end(); glEnable(GL_LIGHTING); diff --git a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h index 338bc6046..9e49dcf46 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/FishingHookRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class FishingHookRenderer : public EntityRenderer -{ -public: - virtual void render(std::shared_ptr _hook, double x, double y, double z, float rot, float a); +class FishingHookRenderer : public EntityRenderer { +public: + virtual void render(std::shared_ptr _hook, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp index 059d5ef02..29637645d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.cpp @@ -3,19 +3,16 @@ #include "../Models/GhastModel.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" -GhastRenderer::GhastRenderer() : MobRenderer(new GhastModel(), 0.5f) -{ -} +GhastRenderer::GhastRenderer() : MobRenderer(new GhastModel(), 0.5f) {} -void GhastRenderer::scale(std::shared_ptr mob, float a) -{ - std::shared_ptr ghast = std::dynamic_pointer_cast(mob); - - float ss = (ghast->oCharge+(ghast->charge-ghast->oCharge)*a)/20.0f; - if (ss<0) ss = 0; - ss = 1/(ss*ss*ss*ss*ss*2+1); - float s = (8+ss)/2; - float hs = (8+1/ss)/2; - glScalef(hs, s, hs); - glColor4f(1, 1, 1, 1); +void GhastRenderer::scale(std::shared_ptr mob, float a) { + std::shared_ptr ghast = std::dynamic_pointer_cast(mob); + + float ss = (ghast->oCharge + (ghast->charge - ghast->oCharge) * a) / 20.0f; + if (ss < 0) ss = 0; + ss = 1 / (ss * ss * ss * ss * ss * 2 + 1); + float s = (8 + ss) / 2; + float hs = (8 + 1 / ss) / 2; + glScalef(hs, s, hs); + glColor4f(1, 1, 1, 1); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h index 1bd3131f8..d552871fd 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/GhastRenderer.h @@ -1,11 +1,10 @@ #pragma once #include "MobRenderer.h" -class GhastRenderer : public MobRenderer -{ +class GhastRenderer : public MobRenderer { public: - GhastRenderer(); + GhastRenderer(); protected: - virtual void scale(std::shared_ptr mob, float a); + virtual void scale(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp index 8bbd3d2fd..7e6035b0d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.cpp @@ -1,12 +1,11 @@ #include "../../Platform/stdafx.h" -#include "GiantMobRenderer.h" +#include "GiantMobRenderer.h" -GiantMobRenderer::GiantMobRenderer(Model *model, float shadow, float _scale) : MobRenderer(model, shadow *_scale) -{ - this->_scale = _scale; +GiantMobRenderer::GiantMobRenderer(Model* model, float shadow, float _scale) + : MobRenderer(model, shadow * _scale) { + this->_scale = _scale; } -void GiantMobRenderer::scale(std::shared_ptr mob, float a) -{ - glScalef(_scale, _scale, _scale); +void GiantMobRenderer::scale(std::shared_ptr mob, float a) { + glScalef(_scale, _scale, _scale); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h index c40708631..872592147 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/GiantMobRenderer.h @@ -1,14 +1,13 @@ #pragma once #include "MobRenderer.h" -class GiantMobRenderer : public MobRenderer -{ +class GiantMobRenderer : public MobRenderer { private: - float _scale; + float _scale; public: - GiantMobRenderer(Model *model, float shadow, float scale); + GiantMobRenderer(Model* model, float shadow, float scale); protected: - virtual void scale(std::shared_ptr mob, float a); + virtual void scale(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp index f5c357940..2b9406c30 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.cpp @@ -10,121 +10,115 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../../../Minecraft.World/Headers/net.minecraft.h" -void HumanoidMobRenderer::_init(HumanoidModel *humanoidModel, float scale) -{ - this->humanoidModel = humanoidModel; - this->_scale = scale; - armorParts1 = NULL; - armorParts2 = NULL; +void HumanoidMobRenderer::_init(HumanoidModel* humanoidModel, float scale) { + this->humanoidModel = humanoidModel; + this->_scale = scale; + armorParts1 = NULL; + armorParts2 = NULL; } -HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow) : MobRenderer(humanoidModel, shadow) -{ - _init(humanoidModel, 1.0f); +HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel* humanoidModel, + float shadow) + : MobRenderer(humanoidModel, shadow) { + _init(humanoidModel, 1.0f); } -HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow, float scale) : MobRenderer(humanoidModel, shadow) -{ - _init(humanoidModel, scale); +HumanoidMobRenderer::HumanoidMobRenderer(HumanoidModel* humanoidModel, + float shadow, float scale) + : MobRenderer(humanoidModel, shadow) { + _init(humanoidModel, scale); - createArmorParts(); + createArmorParts(); } -void HumanoidMobRenderer::createArmorParts() -{ - armorParts1 = new HumanoidModel(1.0f); - armorParts2 = new HumanoidModel(0.5f); +void HumanoidMobRenderer::createArmorParts() { + armorParts1 = new HumanoidModel(1.0f); + armorParts2 = new HumanoidModel(0.5f); } -void HumanoidMobRenderer::additionalRendering(std::shared_ptr mob, float a) -{ - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : mob->getBrightness(a); - glColor3f(brightness, brightness, brightness); +void HumanoidMobRenderer::additionalRendering(std::shared_ptr mob, + float a) { + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1 : mob->getBrightness(a); + glColor3f(brightness, brightness, brightness); std::shared_ptr item = mob->getCarriedItem(); - std::shared_ptr headGear = mob->getArmor(3); + std::shared_ptr headGear = mob->getArmor(3); - if (headGear != NULL) - { - // don't render the pumpkin of skulls for the skins with that disabled - // 4J-PB - need to disable rendering armour/skulls/pumpkins for some special skins (Daleks) + if (headGear != NULL) { + // don't render the pumpkin of skulls for the skins with that disabled + // 4J-PB - need to disable rendering armour/skulls/pumpkins for some + // special skins (Daleks) - if((mob->getAnimOverrideBitmask()&(1<head->translateTo(1 / 16.0f); + if ((mob->getAnimOverrideBitmask() & + (1 << HumanoidModel::eAnim_DontRenderArmour)) == 0) { + glPushMatrix(); + humanoidModel->head->translateTo(1 / 16.0f); - if (headGear->getItem()->id < 256) - { - if (Tile::tiles[headGear->id] != NULL && TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) - { - float s = 10 / 16.0f; - glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); - glRotatef(90, 0, 1, 0); - glScalef(s, -s, -s); - } + if (headGear->getItem()->id < 256) { + if (Tile::tiles[headGear->id] != NULL && + TileRenderer::canRender( + Tile::tiles[headGear->id]->getRenderShape())) { + float s = 10 / 16.0f; + glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); + glRotatef(90, 0, 1, 0); + glScalef(s, -s, -s); + } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, headGear, 0); - } - else if (headGear->getItem()->id == Item::skull_Id) - { - float s = 17 / 16.0f; - glScalef(s, -s, -s); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, headGear, 0); + } else if (headGear->getItem()->id == Item::skull_Id) { + float s = 17 / 16.0f; + glScalef(s, -s, -s); - std::wstring extra = L""; - if (headGear->hasTag() && headGear->getTag()->contains(L"SkullOwner")) - { - extra = headGear->getTag()->getString(L"SkullOwner"); - } - SkullTileRenderer::instance->renderSkull(-0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), extra); - } + std::wstring extra = L""; + if (headGear->hasTag() && + headGear->getTag()->contains(L"SkullOwner")) { + extra = headGear->getTag()->getString(L"SkullOwner"); + } + SkullTileRenderer::instance->renderSkull( + -0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), + extra); + } - glPopMatrix(); - } - } + glPopMatrix(); + } + } - if (item != NULL) - { + if (item != NULL) { glPushMatrix(); - if (model->young) - { - float s = 0.5f; - glTranslatef(0 / 16.0f, 10 / 16.0f, 0 / 16.0f); - glRotatef(-20, -1, 0, 0); - glScalef(s, s, s); - } + if (model->young) { + float s = 0.5f; + glTranslatef(0 / 16.0f, 10 / 16.0f, 0 / 16.0f); + glRotatef(-20, -1, 0, 0); + glScalef(s, s, s); + } humanoidModel->arm0->translateTo(1 / 16.0f); glTranslatef(-1 / 16.0f, 7 / 16.0f, 1 / 16.0f); - if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) - { + if (item->id < 256 && + TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { float s = 8 / 16.0f; glTranslatef(-0 / 16.0f, 3 / 16.0f, -5 / 16.0f); s *= 0.75f; glRotatef(20, 1, 0, 0); glRotatef(45, 0, 1, 0); glScalef(-s, -s, s); - } - else if (item->id == Item::bow_Id) - { - float s = 10 / 16.0f; - glTranslatef(0/16.0f, 2 / 16.0f, 5 / 16.0f); - glRotatef(-20, 0, 1, 0); - glScalef(s, -s, s); - glRotatef(-100, 1, 0, 0); - glRotatef(45, 0, 1, 0); - } - else if (Item::items[item->id]->isHandEquipped()) - { + } else if (item->id == Item::bow_Id) { + float s = 10 / 16.0f; + glTranslatef(0 / 16.0f, 2 / 16.0f, 5 / 16.0f); + glRotatef(-20, 0, 1, 0); + glScalef(s, -s, s); + glRotatef(-100, 1, 0, 0); + glRotatef(45, 0, 1, 0); + } else if (Item::items[item->id]->isHandEquipped()) { float s = 10 / 16.0f; glTranslatef(0, 3 / 16.0f, 0); glScalef(s, -s, s); glRotatef(-100, 1, 0, 0); glRotatef(45, 0, 1, 0); - } - else - { + } else { float s = 6 / 16.0f; glTranslatef(+4 / 16.0f, +3 / 16.0f, -3 / 16.0f); glScalef(s, s, s); @@ -133,18 +127,17 @@ void HumanoidMobRenderer::additionalRendering(std::shared_ptr mob, float a) glRotatef(20, 0, 0, 1); } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, 0); - if (item->getItem()->hasMultipleSpriteLayers()) - { - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, 1); - } - + this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, + 0); + if (item->getItem()->hasMultipleSpriteLayers()) { + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, item, 1); + } + glPopMatrix(); } - } -void HumanoidMobRenderer::scale(std::shared_ptr mob, float a) -{ - glScalef(_scale, _scale, _scale); +void HumanoidMobRenderer::scale(std::shared_ptr mob, float a) { + glScalef(_scale, _scale, _scale); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h index 76c9169b5..42488e2d9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/HumanoidMobRenderer.h @@ -3,20 +3,22 @@ class HumanoidModel; class Giant; -class HumanoidMobRenderer : public MobRenderer -{ +class HumanoidMobRenderer : public MobRenderer { protected: - HumanoidModel *humanoidModel; - float _scale; - HumanoidModel *armorParts1; - HumanoidModel *armorParts2; + HumanoidModel* humanoidModel; + float _scale; + HumanoidModel* armorParts1; + HumanoidModel* armorParts2; + + void _init(HumanoidModel* humanoidModel, float scale); - void _init(HumanoidModel *humanoidModel, float scale); public: - HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow); - HumanoidMobRenderer(HumanoidModel *humanoidModel, float shadow, float scale); + HumanoidMobRenderer(HumanoidModel* humanoidModel, float shadow); + HumanoidMobRenderer(HumanoidModel* humanoidModel, float shadow, + float scale); + protected: - virtual void createArmorParts(); - virtual void additionalRendering(std::shared_ptr mob, float a); - void scale(std::shared_ptr mob, float a); + virtual void createArmorParts(); + virtual void additionalRendering(std::shared_ptr mob, float a); + void scale(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp index fb077f206..d9846a6a0 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.cpp @@ -2,7 +2,7 @@ #include "ItemRenderer.h" #include "TileRenderer.h" #include "EntityRenderDispatcher.h" -//#include "ItemFrame" +// #include "ItemFrame" #include "ItemFrameRenderer.h" #include "../../../Minecraft.World/Util/JavaMath.h" @@ -18,167 +18,175 @@ #include "../../Textures/CompassTexture.h" #include "../Minimap.h" -void ItemFrameRenderer::registerTerrainTextures(IconRegister *iconRegister) -{ - backTexture = iconRegister->registerIcon(L"itemframe_back"); +void ItemFrameRenderer::registerTerrainTextures(IconRegister* iconRegister) { + backTexture = iconRegister->registerIcon(L"itemframe_back"); } -void ItemFrameRenderer::render(std::shared_ptr _itemframe, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type EnderCrystal rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr itemFrame = std::dynamic_pointer_cast(_itemframe); +void ItemFrameRenderer::render(std::shared_ptr _itemframe, double x, + double y, double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type EnderCrystal rather than std::shared_ptr we have here - do + // some casting around instead + std::shared_ptr itemFrame = + std::dynamic_pointer_cast(_itemframe); - glPushMatrix(); - float xOffs = (float) (itemFrame->x - x) - 0.5f; - float yOffs = (float) (itemFrame->y - y) - 0.5f; - float zOffs = (float) (itemFrame->z - z) - 0.5f; + glPushMatrix(); + float xOffs = (float)(itemFrame->x - x) - 0.5f; + float yOffs = (float)(itemFrame->y - y) - 0.5f; + float zOffs = (float)(itemFrame->z - z) - 0.5f; - int xt = itemFrame->xTile + Direction::STEP_X[itemFrame->dir]; - int yt = itemFrame->yTile; - int zt = itemFrame->zTile + Direction::STEP_Z[itemFrame->dir]; + int xt = itemFrame->xTile + Direction::STEP_X[itemFrame->dir]; + int yt = itemFrame->yTile; + int zt = itemFrame->zTile + Direction::STEP_Z[itemFrame->dir]; - glTranslatef((float) xt - xOffs, (float) yt - yOffs, (float) zt - zOffs); + glTranslatef((float)xt - xOffs, (float)yt - yOffs, (float)zt - zOffs); - drawFrame(itemFrame); - drawItem(itemFrame); + drawFrame(itemFrame); + drawItem(itemFrame); - glPopMatrix(); + glPopMatrix(); } +void ItemFrameRenderer::drawFrame(std::shared_ptr itemFrame) { + Minecraft* pMinecraft = Minecraft::GetInstance(); -void ItemFrameRenderer::drawFrame(std::shared_ptr itemFrame) -{ - Minecraft *pMinecraft=Minecraft::GetInstance(); + glPushMatrix(); + entityRenderDispatcher->textures->bindTexture(TN_TERRAIN); + glRotatef(itemFrame->yRot, 0, 1, 0); - glPushMatrix(); - entityRenderDispatcher->textures->bindTexture(TN_TERRAIN); - glRotatef(itemFrame->yRot, 0, 1, 0); + Tile* wood = Tile::wood; + float depth = 1.0f / 16.0f; + float width = 12.0f / 16.0f; + float widthHalf = width / 2.0f; - Tile *wood = Tile::wood; - float depth = 1.0f / 16.0f; - float width = 12.0f / 16.0f; - float widthHalf = width / 2.0f; + // Back + glPushMatrix(); - // Back - glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf + 1.0f / 16.0f, + 0.5f - widthHalf + 1.0f / 16.0f, depth * .5f, + 0.5f + widthHalf - 1.0f / 16.0f, + 0.5f + widthHalf - 1.0f / 16.0f); + tileRenderer->setFixedTexture(backTexture); + tileRenderer->renderTile(wood, 0, 1); + tileRenderer->clearFixedTexture(); + tileRenderer->clearFixedShape(); + glPopMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf + 1.0f / 16.0f, 0.5f - widthHalf + 1.0f / 16.0f, depth * .5f, 0.5f + widthHalf - 1.0f / 16.0f, 0.5f + widthHalf - 1.0f / 16.0f); - tileRenderer->setFixedTexture(backTexture); - tileRenderer->renderTile(wood, 0, 1); - tileRenderer->clearFixedTexture(); - tileRenderer->clearFixedShape(); - glPopMatrix(); + tileRenderer->setFixedTexture( + Tile::wood->getTexture(Facing::UP, TreeTile::BIRCH_TRUNK)); - tileRenderer->setFixedTexture(Tile::wood->getTexture(Facing::UP, TreeTile::BIRCH_TRUNK)); + // Bottom + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, + depth + 0.0001f, depth + 0.5f - widthHalf, + 0.5f + widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Bottom - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, depth + 0.0001f, depth + 0.5f - widthHalf, 0.5f + widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + // Top + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f + widthHalf - depth, 0.5f - widthHalf, + depth + 0.0001f, 0.5f + widthHalf, + 0.5f + widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Top - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f + widthHalf - depth, 0.5f - widthHalf, depth + 0.0001f, 0.5f + widthHalf, 0.5f + widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + // Right + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, depth, + 0.5f + widthHalf, depth + 0.5f - widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Right - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f - widthHalf, depth, 0.5f + widthHalf, depth + 0.5f - widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + // Left + glPushMatrix(); + tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f + widthHalf - depth, + depth, 0.5f + widthHalf, 0.5f + widthHalf); + tileRenderer->renderTile(wood, 0, 1); + glPopMatrix(); - // Left - glPushMatrix(); - tileRenderer->setFixedShape(0, 0.5f - widthHalf, 0.5f + widthHalf - depth, depth, 0.5f + widthHalf, 0.5f + widthHalf); - tileRenderer->renderTile(wood, 0, 1); - glPopMatrix(); + tileRenderer->clearFixedShape(); + tileRenderer->clearFixedTexture(); - tileRenderer->clearFixedShape(); - tileRenderer->clearFixedTexture(); - - glPopMatrix(); + glPopMatrix(); } -void ItemFrameRenderer::drawItem(std::shared_ptr entity) -{ - Minecraft *pMinecraft=Minecraft::GetInstance(); +void ItemFrameRenderer::drawItem(std::shared_ptr entity) { + Minecraft* pMinecraft = Minecraft::GetInstance(); - std::shared_ptr instance = entity->getItem(); - if (instance == NULL) return; + std::shared_ptr instance = entity->getItem(); + if (instance == NULL) return; - std::shared_ptr itemEntity = std::shared_ptr(new ItemEntity(entity->level, 0, 0, 0, instance)); - itemEntity->getItem()->count = 1; - itemEntity->bobOffs = 0; + std::shared_ptr itemEntity = std::shared_ptr( + new ItemEntity(entity->level, 0, 0, 0, instance)); + itemEntity->getItem()->count = 1; + itemEntity->bobOffs = 0; - glPushMatrix(); + glPushMatrix(); - glTranslatef((-7.25f / 16.0f) * Direction::STEP_X[entity->dir], -0.18f, (-7.25f / 16.0f) * Direction::STEP_Z[entity->dir]); - glRotatef(180 + entity->yRot, 0, 1, 0); - glRotatef(-90 * entity->getRotation(), 0, 0, 1); + glTranslatef((-7.25f / 16.0f) * Direction::STEP_X[entity->dir], -0.18f, + (-7.25f / 16.0f) * Direction::STEP_Z[entity->dir]); + glRotatef(180 + entity->yRot, 0, 1, 0); + glRotatef(-90 * entity->getRotation(), 0, 0, 1); - switch (entity->getRotation()) - { - case 1: - glTranslatef(-0.16f, -0.16f, 0); - break; - case 2: - glTranslatef(0, -0.32f, 0); - break; - case 3: - glTranslatef(0.16f, -0.16f, 0); - break; - } + switch (entity->getRotation()) { + case 1: + glTranslatef(-0.16f, -0.16f, 0); + break; + case 2: + glTranslatef(0, -0.32f, 0); + break; + case 3: + glTranslatef(0.16f, -0.16f, 0); + break; + } - if (itemEntity->getItem()->getItem() == Item::map) - { - entityRenderDispatcher->textures->bindTexture(TN_MISC_MAPBG); - Tesselator *t = Tesselator::getInstance(); + if (itemEntity->getItem()->getItem() == Item::map) { + entityRenderDispatcher->textures->bindTexture(TN_MISC_MAPBG); + Tesselator* t = Tesselator::getInstance(); - glRotatef(180, 0, 1, 0); - glRotatef(180, 0, 0, 1); - glScalef(1.0f / 256.0f, 1.0f / 256.0f, 1.0f / 256.0f); - glTranslatef(-65, -107, -3); - glNormal3f(0, 0, -1); - t->begin(); - int vo = 7; - t->vertexUV(0 - vo, 128 + vo, 0, 0, 1); - t->vertexUV(128 + vo, 128 + vo, 0, 1, 1); - t->vertexUV(128 + vo, 0 - vo, 0, 1, 0); - t->vertexUV(0 - vo, 0 - vo, 0, 0, 0); - t->end(); + glRotatef(180, 0, 1, 0); + glRotatef(180, 0, 0, 1); + glScalef(1.0f / 256.0f, 1.0f / 256.0f, 1.0f / 256.0f); + glTranslatef(-65, -107, -3); + glNormal3f(0, 0, -1); + t->begin(); + int vo = 7; + t->vertexUV(0 - vo, 128 + vo, 0, 0, 1); + t->vertexUV(128 + vo, 128 + vo, 0, 1, 1); + t->vertexUV(128 + vo, 0 - vo, 0, 1, 0); + t->vertexUV(0 - vo, 0 - vo, 0, 0, 0); + t->end(); - std::shared_ptr data = Item::map->getSavedData(itemEntity->getItem(), entity->level); - if (data != NULL) - { - entityRenderDispatcher->itemInHandRenderer->minimap->render(nullptr, entityRenderDispatcher->textures, data, entity->entityId); - } - } - else - { - if (itemEntity->getItem()->getItem() == Item::compass) - { - CompassTexture *ct = CompassTexture::instance; - double compassRot = ct->rot; - double compassRotA = ct->rota; - ct->rot = 0; - ct->rota = 0; - ct->updateFromPosition(entity->level, entity->x, entity->z, Mth::wrapDegrees( (float)(180 + entity->dir * 90) ), false, true); - ct->rot = compassRot; - ct->rota = compassRotA; - } + std::shared_ptr data = + Item::map->getSavedData(itemEntity->getItem(), entity->level); + if (data != NULL) { + entityRenderDispatcher->itemInHandRenderer->minimap->render( + nullptr, entityRenderDispatcher->textures, data, + entity->entityId); + } + } else { + if (itemEntity->getItem()->getItem() == Item::compass) { + CompassTexture* ct = CompassTexture::instance; + double compassRot = ct->rot; + double compassRotA = ct->rota; + ct->rot = 0; + ct->rota = 0; + ct->updateFromPosition( + entity->level, entity->x, entity->z, + Mth::wrapDegrees((float)(180 + entity->dir * 90)), false, true); + ct->rot = compassRot; + ct->rota = compassRotA; + } - EntityRenderDispatcher::instance->render(itemEntity, 0, 0, 0, 0, 0, true); + EntityRenderDispatcher::instance->render(itemEntity, 0, 0, 0, 0, 0, + true); - if (itemEntity->getItem()->getItem() == Item::compass) - { - CompassTexture *ct = CompassTexture::instance; - ct->cycleFrames(); - } - } - - glPopMatrix(); + if (itemEntity->getItem()->getItem() == Item::compass) { + CompassTexture* ct = CompassTexture::instance; + ct->cycleFrames(); + } + } + + glPopMatrix(); } - diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h index 263344138..12626a614 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemFrameRenderer.h @@ -1,17 +1,17 @@ #pragma once #include "EntityRenderer.h" -class ItemFrameRenderer : public EntityRenderer -{ +class ItemFrameRenderer : public EntityRenderer { private: - Icon *backTexture; + Icon* backTexture; - //@Override + //@Override public: - void registerTerrainTextures(IconRegister *iconRegister); - virtual void render(std::shared_ptr _itemframe, double x, double y, double z, float rot, float a); + void registerTerrainTextures(IconRegister* iconRegister); + virtual void render(std::shared_ptr _itemframe, double x, double y, + double z, float rot, float a); private: - void drawFrame(std::shared_ptr itemFrame); - void drawItem(std::shared_ptr entity); + void drawFrame(std::shared_ptr itemFrame); + void drawItem(std::shared_ptr entity); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp index bdefd3748..92e3fa52d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.cpp @@ -20,151 +20,153 @@ int ItemInHandRenderer::list = -1; int ItemInHandRenderer::listGlint = -1; -ItemInHandRenderer::ItemInHandRenderer(Minecraft *mc, bool optimisedMinimap) -{ - // 4J - added - height = 0; - oHeight = 0; - selectedItem = nullptr; - tileRenderer = new TileRenderer(); - lastSlot = -1; +ItemInHandRenderer::ItemInHandRenderer(Minecraft* mc, bool optimisedMinimap) { + // 4J - added + height = 0; + oHeight = 0; + selectedItem = nullptr; + tileRenderer = new TileRenderer(); + lastSlot = -1; this->mc = mc; - minimap = new Minimap(mc->font, mc->options, mc->textures, optimisedMinimap); + minimap = + new Minimap(mc->font, mc->options, mc->textures, optimisedMinimap); - // 4J - replaced mesh that is used to render held items with individual cubes, so we can make it all join up properly without seams. This - // has a lot more quads in it than the original, so is now precompiled with a UV matrix offset to put it in the final place for the - // current icon. Compile it on demand for the first ItemInHandRenderer (list is static) - if( list == -1 ) - { - list = MemoryTracker::genLists(1); - float dd = 1 / 16.0f; + // 4J - replaced mesh that is used to render held items with individual + // cubes, so we can make it all join up properly without seams. This has a + // lot more quads in it than the original, so is now precompiled with a UV + // matrix offset to put it in the final place for the current icon. Compile + // it on demand for the first ItemInHandRenderer (list is static) + if (list == -1) { + list = MemoryTracker::genLists(1); + float dd = 1 / 16.0f; - glNewList(list, GL_COMPILE); - Tesselator *t = Tesselator::getInstance(); - t->begin(); - for( int yp = 0; yp < 16; yp++ ) - for( int xp = 0; xp < 16; xp++ ) - { - float u = (15-xp) / 256.0f; - float v = (15-yp) / 256.0f; - u += 0.5f / 256.0f; - v += 0.5f / 256.0f; - float x0 = xp / 16.0f; - float x1 = x0 + 1.0f/16.0f; - float y0 = yp / 16.0f; - float y1 = y0 + 1.0f/16.0f; - float z0 = 0.0f; - float z1 = -dd; + glNewList(list, GL_COMPILE); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + for (int yp = 0; yp < 16; yp++) + for (int xp = 0; xp < 16; xp++) { + float u = (15 - xp) / 256.0f; + float v = (15 - yp) / 256.0f; + u += 0.5f / 256.0f; + v += 0.5f / 256.0f; + float x0 = xp / 16.0f; + float x1 = x0 + 1.0f / 16.0f; + float y0 = yp / 16.0f; + float y1 = y0 + 1.0f / 16.0f; + float z0 = 0.0f; + float z1 = -dd; - t->normal(0, 0, 1); - t->vertexUV(x0, y0, z0, u, v); - t->vertexUV(x1, y0, z0, u, v); - t->vertexUV(x1, y1, z0, u, v); - t->vertexUV(x0, y1, z0, u, v); - t->normal(0, 0, -1); - t->vertexUV(x0, y1, z1, u, v); - t->vertexUV(x1, y1, z1, u, v); - t->vertexUV(x1, y0, z1, u, v); - t->vertexUV(x0, y0, z1, u, v); - t->normal(-1, 0, 0); - t->vertexUV(x0, y0, z1, u, v); - t->vertexUV(x0, y0, z0, u, v); - t->vertexUV(x0, y1, z0, u, v); - t->vertexUV(x0, y1, z1, u, v); - t->normal(1, 0, 0); - t->vertexUV(x1, y1, z1, u, v); - t->vertexUV(x1, y1, z0, u, v); - t->vertexUV(x1, y0, z0, u, v); - t->vertexUV(x1, y0, z1, u, v); - t->normal(0, 1, 0); - t->vertexUV(x1, y0, z0, u, v); - t->vertexUV(x0, y0, z0, u, v); - t->vertexUV(x0, y0, z1, u, v); - t->vertexUV(x1, y0, z1, u, v); - t->normal(0, -1, 0); - t->vertexUV(x1, y1, z1, u, v); - t->vertexUV(x0, y1, z1, u, v); - t->vertexUV(x0, y1, z0, u, v); - t->vertexUV(x1, y1, z0, u, v); - } - t->end(); - glEndList(); - } + t->normal(0, 0, 1); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->normal(0, 0, -1); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->vertexUV(x0, y0, z1, u, v); + t->normal(-1, 0, 0); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x0, y1, z1, u, v); + t->normal(1, 0, 0); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->normal(0, 1, 0); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->normal(0, -1, 0); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + } + t->end(); + glEndList(); + } - // Also create special object for glint overlays - this is the same as the previous one, with a different UV scalings, and depth test set to equal - if( listGlint == -1 ) - { - listGlint = MemoryTracker::genLists(1); - float dd = 1 / 16.0f; + // Also create special object for glint overlays - this is the same as the + // previous one, with a different UV scalings, and depth test set to equal + if (listGlint == -1) { + listGlint = MemoryTracker::genLists(1); + float dd = 1 / 16.0f; - glNewList(listGlint, GL_COMPILE); - glDepthFunc(GL_EQUAL); - Tesselator *t = Tesselator::getInstance(); - t->begin(); - for( int yp = 0; yp < 16; yp++ ) - for( int xp = 0; xp < 16; xp++ ) - { - float u0 = (15-xp) / 16.0f; - float v0 = (15-yp) / 16.0f; - float u1 = u0 - (1.0f/16.0f); - float v1 = v0 - (1.0f/16.0f);; + glNewList(listGlint, GL_COMPILE); + glDepthFunc(GL_EQUAL); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + for (int yp = 0; yp < 16; yp++) + for (int xp = 0; xp < 16; xp++) { + float u0 = (15 - xp) / 16.0f; + float v0 = (15 - yp) / 16.0f; + float u1 = u0 - (1.0f / 16.0f); + float v1 = v0 - (1.0f / 16.0f); + ; - float x0 = xp / 16.0f; - float x1 = x0 + 1.0f/16.0f; - float y0 = yp / 16.0f; - float y1 = y0 + 1.0f/16.0f; - float z0 = 0.0f; - float z1 = -dd; + float x0 = xp / 16.0f; + float x1 = x0 + 1.0f / 16.0f; + float y0 = yp / 16.0f; + float y1 = y0 + 1.0f / 16.0f; + float z0 = 0.0f; + float z1 = -dd; - float br = 0.76f; - t->color(0.5f * br, 0.25f * br, 0.8f * br, 1.0f); // MGH - added the color here, as the glColour below wasn't making it through to render - - t->normal(0, 0, 1); - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x1, y1, z0, u1, v1); - t->vertexUV(x0, y1, z0, u0, v1); - t->normal(0, 0, -1); - t->vertexUV(x0, y1, z1, u0, v1); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x1, y0, z1, u1, v0); - t->vertexUV(x0, y0, z1, u0, v0); - t->normal(-1, 0, 0); - t->vertexUV(x0, y0, z1, u0, v0); - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x0, y1, z0, u0, v1); - t->vertexUV(x0, y1, z1, u0, v1); - t->normal(1, 0, 0); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x1, y1, z0, u1, v1); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x1, y0, z1, u1, v0); - t->normal(0, 1, 0); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x0, y0, z1, u0, v0); - t->vertexUV(x1, y0, z1, u1, v0); - t->normal(0, -1, 0); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x0, y1, z1, u0, v1); - t->vertexUV(x0, y1, z0, u0, v1); - t->vertexUV(x1, y1, z0, u1, v1); - } - t->end(); - glDepthFunc(GL_LEQUAL); - glEndList(); - } + float br = 0.76f; + t->color(0.5f * br, 0.25f * br, 0.8f * br, + 1.0f); // MGH - added the color here, as the glColour + // below wasn't making it through to render + t->normal(0, 0, 1); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y1, z0, u1, v1); + t->vertexUV(x0, y1, z0, u0, v1); + t->normal(0, 0, -1); + t->vertexUV(x0, y1, z1, u0, v1); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x1, y0, z1, u1, v0); + t->vertexUV(x0, y0, z1, u0, v0); + t->normal(-1, 0, 0); + t->vertexUV(x0, y0, z1, u0, v0); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x0, y1, z0, u0, v1); + t->vertexUV(x0, y1, z1, u0, v1); + t->normal(1, 0, 0); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x1, y1, z0, u1, v1); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y0, z1, u1, v0); + t->normal(0, 1, 0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x0, y0, z1, u0, v0); + t->vertexUV(x1, y0, z1, u1, v0); + t->normal(0, -1, 0); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x0, y1, z1, u0, v1); + t->vertexUV(x0, y1, z0, u0, v1); + t->vertexUV(x1, y1, z0, u1, v1); + } + t->end(); + glDepthFunc(GL_LEQUAL); + glEndList(); + } } -void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptr item, int layer, bool setColor/* = true*/) -{ - // 4J - code borrowed from render method below, although not factoring in brightness as that should already be being taken into account - // by texture lighting. This is for colourising things held in 3rd person view. - if ( (setColor) && (item != NULL) ) - { - int col = Item::items[item->id]->getColor(item,0); +void ItemInHandRenderer::renderItem(std::shared_ptr mob, + std::shared_ptr item, + int layer, bool setColor /* = true*/) { + // 4J - code borrowed from render method below, although not factoring in + // brightness as that should already be being taken into account by texture + // lighting. This is for colourising things held in 3rd person view. + if ((setColor) && (item != NULL)) { + int col = Item::items[item->id]->getColor(item, 0); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; @@ -173,57 +175,57 @@ void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptrid]; - if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && TileRenderer::canRender(tile->getRenderShape())) - { - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - tileRenderer->renderTile(tile, item->getAuxValue(), SharedConstants::TEXTURE_LIGHTING ? 1.0f : mob->getBrightness(1)); // 4J - change brought forward from 1.8.2 - } - else - { - MemSect(31); - Icon *icon = mob->getItemInHandIcon(item, layer); - if (icon == NULL) - { - glPopMatrix(); - MemSect(0); - return; - } - - if (item->getIconType() == Icon::TYPE_TERRAIN) - { - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + Tile* tile = Tile::tiles[item->id]; + if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && + TileRenderer::canRender(tile->getRenderShape())) { + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + tileRenderer->renderTile( + tile, item->getAuxValue(), + SharedConstants::TEXTURE_LIGHTING + ? 1.0f + : mob->getBrightness( + 1)); // 4J - change brought forward from 1.8.2 + } else { + MemSect(31); + Icon* icon = mob->getItemInHandIcon(item, layer); + if (icon == NULL) { + glPopMatrix(); + MemSect(0); + return; } - else - { - mc->textures->bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + + if (item->getIconType() == Icon::TYPE_TERRAIN) { + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + } else { + mc->textures->bindTexture( + TN_GUI_ITEMS); // 4J was L"/gui/items.png" } - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(0); + Tesselator* t = Tesselator::getInstance(); - // Consider forcing the mipmap LOD level to use, if this is to be rendered from a larger than standard source texture. - int iconWidth = icon->getWidth(); - int LOD = -1; // Default to not doing anything special with LOD forcing - if( iconWidth == 32 ) - { - LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 map - } - else if( iconWidth == 64 ) - { - LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 map - } - RenderManager.StateSetForceLOD(LOD); + // Consider forcing the mipmap LOD level to use, if this is to be + // rendered from a larger than standard source texture. + int iconWidth = icon->getWidth(); + int LOD = -1; // Default to not doing anything special with LOD forcing + if (iconWidth == 32) { + LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 + // map + } else if (iconWidth == 64) { + LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 + // map + } + RenderManager.StateSetForceLOD(LOD); - // 4J Original comment - // Yes, these are backwards. - // No, I don't know why. - // 4J Stu - Make them the right way round...u coords were swapped - float u0 = icon->getU0(); - float u1 = icon->getU1(); - float v0 = icon->getV0(); - float v1 = icon->getV1(); + // 4J Original comment + // Yes, these are backwards. + // No, I don't know why. + // 4J Stu - Make them the right way round...u coords were swapped + float u0 = icon->getU0(); + float u1 = icon->getU1(); + float v0 = icon->getV0(); + float v1 = icon->getV1(); float xo = 0.0f; float yo = 0.3f; @@ -238,30 +240,35 @@ void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptrgetSourceWidth(), icon->getSourceHeight(), 1 / 16.0f, false); + renderItem3D(t, u0, v0, u1, v1, icon->getSourceWidth(), + icon->getSourceHeight(), 1 / 16.0f, false); - if (item != NULL && item->isFoil() && layer == 0) - { + if (item != NULL && item->isFoil() && layer == 0) { glDepthFunc(GL_EQUAL); glDisable(GL_LIGHTING); - mc->textures->bind(mc->textures->loadTexture(TN__BLUR__MISC_GLINT)); // 4J was L"%blur%/misc/glint.png" + mc->textures->bind(mc->textures->loadTexture( + TN__BLUR__MISC_GLINT)); // 4J was L"%blur%/misc/glint.png" glEnable(GL_BLEND); glBlendFunc(GL_SRC_COLOR, GL_ONE); float br = 0.76f; - glColor4f(0.5f * br, 0.25f * br, 0.8f * br, 1); // MGH - for some reason this colour isn't making it through to the render, so I've added to the tesselator for the glint geom above - glMatrixMode(GL_TEXTURE); - glPushMatrix(); - float ss = 1 / 8.0f; - glScalef(ss, ss, ss); - float sx = Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; - glTranslatef(sx, 0, 0); - glRotatef(-50, 0, 0, 1); + glColor4f(0.5f * br, 0.25f * br, 0.8f * br, + 1); // MGH - for some reason this colour isn't making it + // through to the render, so I've added to the + // tesselator for the glint geom above + glMatrixMode(GL_TEXTURE); + glPushMatrix(); + float ss = 1 / 8.0f; + glScalef(ss, ss, ss); + float sx = Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; + glTranslatef(sx, 0, 0); + glRotatef(-50, 0, 0, 1); renderItem3D(t, 0, 0, 1, 1, 256, 256, 1 / 16.0f, true); glPopMatrix(); glPushMatrix(); glScalef(ss, ss, ss); - sx = System::currentTimeMillis() % (3000 + 1873) / (3000 + 1873.0f) * 8; + sx = System::currentTimeMillis() % (3000 + 1873) / + (3000 + 1873.0f) * 8; glTranslatef(-sx, 0, 0); glRotatef(10, 0, 0, 1); renderItem3D(t, 0, 0, 1, 1, 256, 256, 1 / 16.0f, true); @@ -272,7 +279,7 @@ void ItemInHandRenderer::renderItem(std::shared_ptr mob, std::shared_ptr mob, std::shared_ptrplayer || !mc->level) return; @@ -318,26 +325,28 @@ void ItemInHandRenderer::render(float a) float h = oHeight + (height - oHeight) * a; std::shared_ptr player = mc->player; - // 4J - added so we can adjust the position of the hands for horizontal & vertical split screens - float fudgeX = 0.0f; - float fudgeY = 0.0f; - float fudgeZ = 0.0f; - bool splitHoriz = false; - std::shared_ptr localPlayer = std::dynamic_pointer_cast(player); - if( localPlayer ) - { - if( localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM || - localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_TOP ) - { - fudgeY = 0.08f; - splitHoriz = true; - } - else if( localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT || - localPlayer->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT ) - { - fudgeX = -0.18f; - } - } + // 4J - added so we can adjust the position of the hands for horizontal & + // vertical split screens + float fudgeX = 0.0f; + float fudgeY = 0.0f; + float fudgeZ = 0.0f; + bool splitHoriz = false; + std::shared_ptr localPlayer = + std::dynamic_pointer_cast(player); + if (localPlayer) { + if (localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM || + localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_TOP) { + fudgeY = 0.08f; + splitHoriz = true; + } else if (localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_LEFT || + localPlayer->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT) { + fudgeX = -0.18f; + } + } float xr = player->xRotO + (player->xRot - player->xRotO) * a; @@ -347,60 +356,61 @@ void ItemInHandRenderer::render(float a) Lighting::turnOn(); glPopMatrix(); - if (localPlayer) - { - float xrr = localPlayer->xBobO + (localPlayer->xBob - localPlayer->xBobO) * a; - float yrr = localPlayer->yBobO + (localPlayer->yBob - localPlayer->yBobO) * a; - // 4J - was using player->xRot and yRot directly here rather than interpolating between old & current with a - float yr = player->yRotO + (player->yRot - player->yRotO) * a; + if (localPlayer) { + float xrr = + localPlayer->xBobO + (localPlayer->xBob - localPlayer->xBobO) * a; + float yrr = + localPlayer->yBobO + (localPlayer->yBob - localPlayer->yBobO) * a; + // 4J - was using player->xRot and yRot directly here rather than + // interpolating between old & current with a + float yr = player->yRotO + (player->yRot - player->yRotO) * a; glRotatef((xr - xrr) * 0.1f, 1, 0, 0); glRotatef((yr - yrr) * 0.1f, 0, 1, 0); } std::shared_ptr item = selectedItem; - float br = mc->level->getBrightness(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - // 4J - change brought forward from 1.8.2 - if (SharedConstants::TEXTURE_LIGHTING) - { + float br = mc->level->getBrightness( + Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { br = 1; - int col = mc->level->getLightColor(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z), 0); + int col = mc->level->getLightColor(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z), 0); int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); } - if (item != NULL) - { - int col = Item::items[item->id]->getColor(item,0); + if (item != NULL) { + int col = Item::items[item->id]->getColor(item, 0); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; glColor4f(br * red, br * g, br * b, 1); + } else { + glColor4f(br, br, br, 1); } - else - { - glColor4f(br, br, br, 1); - } - if (item != NULL && item->id == Item::map->id) - { + if (item != NULL && item->id == Item::map->id) { glPushMatrix(); float d = 0.8f; - // 4J - move the map away a bit if we're in horizontal split screen, so it doesn't clip out of the save zone - if( splitHoriz ) - { - glTranslatef(0.0f, 0.0f, -0.3f ); - } + // 4J - move the map away a bit if we're in horizontal split screen, so + // it doesn't clip out of the save zone + if (splitHoriz) { + glTranslatef(0.0f, 0.0f, -0.3f); + } { float swing = player->getAttackAnim(a); float swing1 = Mth::sin(swing * PI); float swing2 = Mth::sin((sqrt(swing)) * PI); - glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, -swing1 * 0.2f); + glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, + -swing1 * 0.2f); } float tilt = 1 - xr / 45.0f + 0.1f; @@ -408,20 +418,23 @@ void ItemInHandRenderer::render(float a) if (tilt > 1) tilt = 1; tilt = -Mth::cos(tilt * PI) * 0.5f + 0.5f; - glTranslatef(0.0f, 0.0f * d - (1 - h) * 1.2f - tilt * 0.5f + 0.04f, -0.9f * d); + glTranslatef(0.0f, 0.0f * d - (1 - h) * 1.2f - tilt * 0.5f + 0.04f, + -0.9f * d); glRotatef(90, 0, 1, 0); glRotatef((tilt) * -85, 0, 0, 1); glEnable(GL_RESCALE_NORMAL); - { - // 4J-PB - if we've got a player texture, use that - //glBindTexture(GL_TEXTURE_2D, mc->textures->loadHttpTexture(mc->player->customTextureUrl, mc->player->getTexture())); - glBindTexture(GL_TEXTURE_2D, mc->textures->loadMemTexture(mc->player->customTextureUrl, mc->player->getTexture())); - mc->textures->clearLastBoundId(); - for (int i = 0; i < 2; i++) - { + // 4J-PB - if we've got a player texture, use that + // glBindTexture(GL_TEXTURE_2D, + // mc->textures->loadHttpTexture(mc->player->customTextureUrl, + // mc->player->getTexture())); + glBindTexture(GL_TEXTURE_2D, mc->textures->loadMemTexture( + mc->player->customTextureUrl, + mc->player->getTexture())); + mc->textures->clearLastBoundId(); + for (int i = 0; i < 2; i++) { int flip = i * 2 - 1; glPushMatrix(); @@ -431,17 +444,21 @@ void ItemInHandRenderer::render(float a) glRotatef(59, 0, 0, 1); glRotatef((float)(-65 * flip), 0, 1, 0); - EntityRenderer *er = EntityRenderDispatcher::instance->getRenderer(mc->player); - PlayerRenderer *playerRenderer = (PlayerRenderer *) er; + EntityRenderer* er = + EntityRenderDispatcher::instance->getRenderer(mc->player); + PlayerRenderer* playerRenderer = (PlayerRenderer*)er; float ss = 1; glScalef(ss, ss, ss); - // Can't turn off the hand if the player is holding a map - std::shared_ptr itemInstance = player->inventory->getSelected(); - if ((itemInstance && (itemInstance->getItem()->id==Item::map_Id)) || app.GetGameSettings(localPlayer->GetXboxPad(),eGameSetting_DisplayHand)!=0 ) - { - playerRenderer->renderHand(); - } + // Can't turn off the hand if the player is holding a map + std::shared_ptr itemInstance = + player->inventory->getSelected(); + if ((itemInstance && + (itemInstance->getItem()->id == Item::map_Id)) || + app.GetGameSettings(localPlayer->GetXboxPad(), + eGameSetting_DisplayHand) != 0) { + playerRenderer->renderHand(); + } glPopMatrix(); } } @@ -466,43 +483,48 @@ void ItemInHandRenderer::render(float a) float s = 2 / 128.0f; glScalef(s, s, s); - MemSect(31); - mc->textures->bindTexture(TN_MISC_MAPBG); // 4J was L"/misc/mapbg.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + mc->textures->bindTexture(TN_MISC_MAPBG); // 4J was L"/misc/mapbg.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); -// glNormal3f(0, 0, -1); // 4J - changed to use tesselator + // glNormal3f(0, 0, -1); // 4J - changed to use tesselator t->begin(); - int vo = 7; - t->normal(0,0,-1); - t->vertexUV((float)(0 - vo), (float)( 128 + vo), (float)( 0), (float)( 0), (float)( 1)); - t->vertexUV((float)(128 + vo), (float)( 128 + vo), (float)( 0), (float)( 1), (float)( 1)); - t->vertexUV((float)(128 + vo), (float)( 0 - vo), (float)( 0), (float)( 1), (float)( 0)); - t->vertexUV((float)(0 - vo), (float)( 0 - vo), (float)( 0), (float)( 0), (float)( 0)); + int vo = 7; + t->normal(0, 0, -1); + t->vertexUV((float)(0 - vo), (float)(128 + vo), (float)(0), (float)(0), + (float)(1)); + t->vertexUV((float)(128 + vo), (float)(128 + vo), (float)(0), + (float)(1), (float)(1)); + t->vertexUV((float)(128 + vo), (float)(0 - vo), (float)(0), (float)(1), + (float)(0)); + t->vertexUV((float)(0 - vo), (float)(0 - vo), (float)(0), (float)(0), + (float)(0)); t->end(); - std::shared_ptr data = Item::map->getSavedData(item, mc->level); - PIXBeginNamedEvent(0,"Minimap render"); - if(data != NULL) minimap->render(mc->player, mc->textures, data, mc->player->entityId); - PIXEndNamedEvent(); + std::shared_ptr data = + Item::map->getSavedData(item, mc->level); + PIXBeginNamedEvent(0, "Minimap render"); + if (data != NULL) + minimap->render(mc->player, mc->textures, data, + mc->player->entityId); + PIXEndNamedEvent(); glPopMatrix(); - } - else if (item != NULL) - { + } else if (item != NULL) { glPushMatrix(); float d = 0.8f; #if defined __ORBIS__ || defined __PS3__ - static const float swingPowFactor = 1.0f; + static const float swingPowFactor = 1.0f; #else - static const float swingPowFactor = 4.0f; // 4J added, to slow the swing down when nearest the player for avoiding luminance flash issues + static const float swingPowFactor = + 4.0f; // 4J added, to slow the swing down when nearest the player + // for avoiding luminance flash issues #endif - if (player->getUseItemDuration() > 0) - { + if (player->getUseItemDuration() > 0) { UseAnim anim = item->getUseAnimation(); - if ( (anim == UseAnim_eat) || (anim == UseAnim_drink) ) - { + if ((anim == UseAnim_eat) || (anim == UseAnim_drink)) { float t = (player->getUseItemDuration() - a + 1); float swing = 1 - (t / item->getUseDuration()); @@ -511,63 +533,62 @@ void ItemInHandRenderer::render(float a) is = is * is * is; is = is * is * is; float iss = 1 - is; - glTranslatef(0, Mth::abs(Mth::cos(t / 4 * PI) * 0.1f) * (swing > 0.2 ? 1 : 0), 0); + glTranslatef(0, + Mth::abs(Mth::cos(t / 4 * PI) * 0.1f) * + (swing > 0.2 ? 1 : 0), + 0); glTranslatef(iss * 0.6f, -iss * 0.5f, 0); glRotatef(iss * 90, 0, 1, 0); glRotatef(iss * 10, 1, 0, 0); glRotatef(iss * 30, 0, 0, 1); } + } else { + float swing = powf(player->getAttackAnim(a), swingPowFactor); + + float swing1 = Mth::sin(swing * PI); + float swing2 = Mth::sin((sqrt(swing)) * PI); + glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, + -swing1 * 0.2f); } - else - { - float swing = powf(player->getAttackAnim(a),swingPowFactor); - - float swing1 = Mth::sin(swing * PI); - float swing2 = Mth::sin((sqrt(swing)) * PI); - glTranslatef(-swing2 * 0.4f, Mth::sin(sqrt(swing) * PI * 2) * 0.2f, -swing1 * 0.2f); - - } glTranslatef(0.7f * d, -0.65f * d - (1 - h) * 0.6f, -0.9f * d); - glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added + glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added glRotatef(45, 0, 1, 0); glEnable(GL_RESCALE_NORMAL); - float swing = powf(player->getAttackAnim(a),swingPowFactor); - float swing3 = Mth::sin(swing * swing * PI); - float swing2 = Mth::sin(sqrt(swing) * PI); - glRotatef(-swing3 * 20, 0, 1, 0); - glRotatef(-swing2 * 20, 0, 0, 1); - glRotatef(-swing2 * 80, 1, 0, 0); + float swing = powf(player->getAttackAnim(a), swingPowFactor); + float swing3 = Mth::sin(swing * swing * PI); + float swing2 = Mth::sin(sqrt(swing) * PI); + glRotatef(-swing3 * 20, 0, 1, 0); + glRotatef(-swing2 * 20, 0, 0, 1); + glRotatef(-swing2 * 80, 1, 0, 0); float ss = 0.4f; glScalef(ss, ss, ss); - if (player->getUseItemDuration() > 0) - { + if (player->getUseItemDuration() > 0) { UseAnim anim = item->getUseAnimation(); - if (anim == UseAnim_block) - { + if (anim == UseAnim_block) { glTranslatef(-0.5f, 0.2f, 0.0f); glRotatef(30, 0, 1, 0); glRotatef(-80, 1, 0, 0); glRotatef(60, 0, 1, 0); - } - else if (anim == UseAnim_bow) - { - + } else if (anim == UseAnim_bow) { glRotatef(-18, 0, 0, 1); glRotatef(-12, 0, 1, 0); glRotatef(-8, 1, 0, 0); glTranslatef(-0.9f, 0.2f, 0.0f); - float timeHeld = (item->getUseDuration() - (player->getUseItemDuration() - a + 1)); - float pow = timeHeld / (float) (BowItem::MAX_DRAW_DURATION); + float timeHeld = (item->getUseDuration() - + (player->getUseItemDuration() - a + 1)); + float pow = timeHeld / (float)(BowItem::MAX_DRAW_DURATION); pow = ((pow * pow) + pow * 2) / 3; if (pow > 1) pow = 1; - if (pow > 0.1f) - { - glTranslatef(0, Mth::sin((timeHeld - 0.1f) * 1.3f) * 0.01f * (pow - 0.1f), 0); + if (pow > 0.1f) { + glTranslatef(0, + Mth::sin((timeHeld - 0.1f) * 1.3f) * 0.01f * + (pow - 0.1f), + 0); } glTranslatef(0, 0, pow * 0.1f); @@ -582,35 +603,28 @@ void ItemInHandRenderer::render(float a) } } - - if (item->getItem()->isMirroredArt()) - { + if (item->getItem()->isMirroredArt()) { glRotatef(180, 0, 1, 0); } - if (item->getItem()->hasMultipleSpriteLayers()) - { + if (item->getItem()->hasMultipleSpriteLayers()) { // special case for potions, refactor this when we get more // items that have two layers renderItem(player, item, 0, false); - int col = Item::items[item->id]->getColor(item, 1); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + int col = Item::items[item->id]->getColor(item, 1); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - glColor4f(br * red, br * g, br * b, 1); + glColor4f(br * red, br * g, br * b, 1); renderItem(player, item, 1, false); - } - else - { + } else { renderItem(player, item, 0, false); } glPopMatrix(); - } - else if (!player->isInvisible()) - { + } else if (!player->isInvisible()) { glPushMatrix(); float d = 0.8f; @@ -619,11 +633,12 @@ void ItemInHandRenderer::render(float a) float swing1 = Mth::sin(swing * PI); float swing2 = Mth::sin((sqrt(swing)) * PI); - glTranslatef(-swing2 * 0.3f, Mth::sin(sqrt(swing) * PI * 2) * 0.4f, -swing1 * 0.4f); + glTranslatef(-swing2 * 0.3f, Mth::sin(sqrt(swing) * PI * 2) * 0.4f, + -swing1 * 0.4f); } glTranslatef(0.8f * d, -0.75f * d - (1 - h) * 0.6f, -0.9f * d); - glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added + glTranslatef(fudgeX, fudgeY, fudgeZ); // 4J added glRotatef(45, 0, 1, 0); glEnable(GL_RESCALE_NORMAL); @@ -635,14 +650,18 @@ void ItemInHandRenderer::render(float a) glRotatef(-swing3 * 20, 0, 0, 1); } - // 4J-PB - if we've got a player texture, use that + // 4J-PB - if we've got a player texture, use that - //glBindTexture(GL_TEXTURE_2D, mc->textures->loadHttpTexture(mc->player->customTextureUrl, mc->player->getTexture())); + // glBindTexture(GL_TEXTURE_2D, + // mc->textures->loadHttpTexture(mc->player->customTextureUrl, + // mc->player->getTexture())); - MemSect(31); - glBindTexture(GL_TEXTURE_2D, mc->textures->loadMemTexture(mc->player->customTextureUrl, mc->player->getTexture())); - MemSect(0); - mc->textures->clearLastBoundId(); + MemSect(31); + glBindTexture(GL_TEXTURE_2D, + mc->textures->loadMemTexture(mc->player->customTextureUrl, + mc->player->getTexture())); + MemSect(0); + mc->textures->clearLastBoundId(); glTranslatef(-1.0f, +3.6f, +3.5f); glRotatef(120, 0, 0, 1); glRotatef(180 + 20, 1, 0, 0); @@ -650,87 +669,79 @@ void ItemInHandRenderer::render(float a) glScalef(1.5f / 24.0f * 16, 1.5f / 24.0f * 16, 1.5f / 24.0f * 16); glTranslatef(5.6f, 0, 0); - EntityRenderer *er = EntityRenderDispatcher::instance->getRenderer(mc->player); - PlayerRenderer *playerRenderer = (PlayerRenderer *) er; + EntityRenderer* er = + EntityRenderDispatcher::instance->getRenderer(mc->player); + PlayerRenderer* playerRenderer = (PlayerRenderer*)er; float ss = 1; glScalef(ss, ss, ss); - MemSect(31); - // Can't turn off the hand if the player is holding a map - std::shared_ptr itemInstance = player->inventory->getSelected(); + MemSect(31); + // Can't turn off the hand if the player is holding a map + std::shared_ptr itemInstance = + player->inventory->getSelected(); - if ( (itemInstance && (itemInstance->getItem()->id==Item::map_Id)) || app.GetGameSettings(localPlayer->GetXboxPad(),eGameSetting_DisplayHand)!=0 ) - { - playerRenderer->renderHand(); - } - MemSect(0); + if ((itemInstance && (itemInstance->getItem()->id == Item::map_Id)) || + app.GetGameSettings(localPlayer->GetXboxPad(), + eGameSetting_DisplayHand) != 0) { + playerRenderer->renderHand(); + } + MemSect(0); glPopMatrix(); } glDisable(GL_RESCALE_NORMAL); Lighting::turnOff(); - } -void ItemInHandRenderer::renderScreenEffect(float a) -{ +void ItemInHandRenderer::renderScreenEffect(float a) { glDisable(GL_ALPHA_TEST); - if (mc->player->isOnFire()) - { - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); + if (mc->player->isOnFire()) { + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); renderFire(a); } - - if (mc->player->isInWall()) // Inside a tile + if (mc->player->isInWall()) // Inside a tile { int x = Mth::floor(mc->player->x); int y = Mth::floor(mc->player->y); int z = Mth::floor(mc->player->z); - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); int tile = mc->level->getTile(x, y, z); - if (mc->level->isSolidBlockingTile(x, y, z)) - { + if (mc->level->isSolidBlockingTile(x, y, z)) { renderTex(a, Tile::tiles[tile]->getTexture(2)); - } - else - { - for (int i = 0; i < 8; i++) - { + } else { + for (int i = 0; i < 8; i++) { float xo = ((i >> 0) % 2 - 0.5f) * mc->player->bbWidth * 0.9f; float yo = ((i >> 1) % 2 - 0.5f) * mc->player->bbHeight * 0.2f; float zo = ((i >> 2) % 2 - 0.5f) * mc->player->bbWidth * 0.9f; int xt = Mth::floor(x + xo); int yt = Mth::floor(y + yo); int zt = Mth::floor(z + zo); - if (mc->level->isSolidBlockingTile(xt, yt, zt)) - { + if (mc->level->isSolidBlockingTile(xt, yt, zt)) { tile = mc->level->getTile(xt, yt, zt); } } } - if (Tile::tiles[tile] != NULL) renderTex(a, Tile::tiles[tile]->getTexture(2)); + if (Tile::tiles[tile] != NULL) + renderTex(a, Tile::tiles[tile]->getTexture(2)); } - if (mc->player->isUnderLiquid(Material::water)) - { - MemSect(31); - mc->textures->bindTexture(TN_MISC_WATER); // 4J was L"/misc/water.png" - MemSect(0); + if (mc->player->isUnderLiquid(Material::water)) { + MemSect(31); + mc->textures->bindTexture(TN_MISC_WATER); // 4J was L"/misc/water.png" + MemSect(0); renderWater(a); } glEnable(GL_ALPHA_TEST); - } -void ItemInHandRenderer::renderTex(float a, Icon *slot) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemInHandRenderer::renderTex(float a, Icon* slot) { + Tesselator* t = Tesselator::getInstance(); float br = 0.1f; br = 0.1f; @@ -751,20 +762,22 @@ void ItemInHandRenderer::renderTex(float a, Icon *slot) float v1 = slot->getV1(); t->begin(); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( u1), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( u0), (float)( v1)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( u0), (float)( v0)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( u1), (float)( v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u1), + (float)(v0)); t->end(); glPopMatrix(); glColor4f(1, 1, 1, 1); - } -void ItemInHandRenderer::renderWater(float a) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemInHandRenderer::renderWater(float a) { + Tesselator* t = Tesselator::getInstance(); float br = mc->player->getBrightness(a); glColor4f(br, br, br, 0.5f); @@ -785,35 +798,36 @@ void ItemInHandRenderer::renderWater(float a) float vo = +mc->player->xRot / 64.0f; t->begin(); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( size + uo), (float)( size + vo)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( 0 + uo), (float)( size + vo)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( 0 + uo), (float)( 0 + vo)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( size + uo), (float)( 0 + vo)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(size + uo), + (float)(size + vo)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(0 + uo), + (float)(size + vo)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(0 + uo), + (float)(0 + vo)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(size + uo), + (float)(0 + vo)); t->end(); glPopMatrix(); glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); - } -void ItemInHandRenderer::renderFire(float a) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemInHandRenderer::renderFire(float a) { + Tesselator* t = Tesselator::getInstance(); glColor4f(1, 1, 1, 0.9f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); float size = 1; - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { glPushMatrix(); - Icon *slot = Tile::fire->getTextureLayer(1); + Icon* slot = Tile::fire->getTextureLayer(1); - float u0 = slot->getU0(true); - float u1 = slot->getU1(true); - float v0 = slot->getV0(true); - float v1 = slot->getV1(true); + float u0 = slot->getU0(true); + float u1 = slot->getU1(true); + float v0 = slot->getV0(true); + float v1 = slot->getV1(true); float x0 = (0 - size) / 2; float x1 = x0 + size; @@ -824,33 +838,35 @@ void ItemInHandRenderer::renderFire(float a) glRotatef((i * 2 - 1) * 10.0f, 0, 1, 0); t->begin(); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( u1), (float)( v1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( u0), (float)( v1)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( u0), (float)( v0)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( u1), (float)( v0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u1), + (float)(v0)); t->end(); glPopMatrix(); } glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); - } -void ItemInHandRenderer::tick() -{ +void ItemInHandRenderer::tick() { oHeight = height; - std::shared_ptr player = mc->player; std::shared_ptr nextTile = player->inventory->getSelected(); - bool matches = lastSlot == player->inventory->selected && nextTile == selectedItem; - if (selectedItem == NULL && nextTile == NULL) - { + bool matches = + lastSlot == player->inventory->selected && nextTile == selectedItem; + if (selectedItem == NULL && nextTile == NULL) { matches = true; } - if (nextTile != NULL && selectedItem != NULL && nextTile != selectedItem && nextTile->id == selectedItem->id && nextTile->getAuxValue() == selectedItem->getAuxValue()) - { + if (nextTile != NULL && selectedItem != NULL && nextTile != selectedItem && + nextTile->id == selectedItem->id && + nextTile->getAuxValue() == selectedItem->getAuxValue()) { selectedItem = nextTile; matches = true; } @@ -862,21 +878,12 @@ void ItemInHandRenderer::tick() if (dd > max) dd = max; height += dd; - if (height < 0.1f) - { + if (height < 0.1f) { selectedItem = nextTile; lastSlot = player->inventory->selected; } - } -void ItemInHandRenderer::itemPlaced() -{ - height = 0; -} - -void ItemInHandRenderer::itemUsed() -{ - height = 0; -} +void ItemInHandRenderer::itemPlaced() { height = 0; } +void ItemInHandRenderer::itemUsed() { height = 0; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h index 975dd3606..682b3c183 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemInHandRenderer.h @@ -7,34 +7,41 @@ class Mob; class TileRenderer; class Tesselator; -class ItemInHandRenderer -{ +class ItemInHandRenderer { private: - Minecraft *mc; + Minecraft* mc; std::shared_ptr selectedItem; float height; float oHeight; - TileRenderer *tileRenderer; - static int list, listGlint; + TileRenderer* tileRenderer; + static int list, listGlint; public: - // 4J Stu - Made public so we can use it from ItemFramRenderer - Minimap *minimap; + // 4J Stu - Made public so we can use it from ItemFramRenderer + Minimap* minimap; public: - ItemInHandRenderer(Minecraft *mc, bool optimisedMinimap = true); // 4J Added optimisedMinimap param - void renderItem(std::shared_ptr mob, std::shared_ptr item, int layer, bool setColor = true); // 4J added setColor parameter - static void renderItem3D(Tesselator *t, float u0, float v0, float u1, float v1, int width, int height, float depth, bool isGlint); // 4J added isGlint parameter + ItemInHandRenderer( + Minecraft* mc, + bool optimisedMinimap = true); // 4J Added optimisedMinimap param + void renderItem(std::shared_ptr mob, + std::shared_ptr item, int layer, + bool setColor = true); // 4J added setColor parameter + static void renderItem3D(Tesselator* t, float u0, float v0, float u1, + float v1, int width, int height, float depth, + bool isGlint); // 4J added isGlint parameter public: void render(float a); void renderScreenEffect(float a); + private: - void renderTex(float a, Icon *slot); + void renderTex(float a, Icon* slot); void renderWater(float a); void renderFire(float a); int lastSlot; + public: - void tick(); + void tick(); void itemPlaced(); void itemUsed(); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp index bcf70eeb2..cdfeab6fb 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.cpp @@ -11,172 +11,162 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.h" #include "../../GameState/Options.h" -ItemRenderer::ItemRenderer() : EntityRenderer() -{ +ItemRenderer::ItemRenderer() : EntityRenderer() { random = new Random(); setColor = true; - blitOffset = 0; + blitOffset = 0; this->shadowRadius = 0.15f; this->shadowStrength = 0.75f; - // 4J added - m_bItemFrame= false; + // 4J added + m_bItemFrame = false; } -ItemRenderer::~ItemRenderer() -{ - delete random; -} +ItemRenderer::~ItemRenderer() { delete random; } -void ItemRenderer::render(std::shared_ptr _itemEntity, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr itemEntity = std::dynamic_pointer_cast(_itemEntity); +void ItemRenderer::render(std::shared_ptr _itemEntity, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr itemEntity = + std::dynamic_pointer_cast(_itemEntity); random->setSeed(187); std::shared_ptr item = itemEntity->getItem(); glPushMatrix(); - float bob = Mth::sin((itemEntity->age + a) / 10.0f + itemEntity->bobOffs) * 0.1f + 0.1f; - float spin = ((itemEntity->age + a) / 20.0f + itemEntity->bobOffs) * Mth::RADDEG; + float bob = + Mth::sin((itemEntity->age + a) / 10.0f + itemEntity->bobOffs) * 0.1f + + 0.1f; + float spin = + ((itemEntity->age + a) / 20.0f + itemEntity->bobOffs) * Mth::RADDEG; int count = 1; if (itemEntity->getItem()->count > 1) count = 2; if (itemEntity->getItem()->count > 5) count = 3; if (itemEntity->getItem()->count > 20) count = 4; - glTranslatef((float) x, (float) y + bob, (float) z); + glTranslatef((float)x, (float)y + bob, (float)z); glEnable(GL_RESCALE_NORMAL); - Tile *tile = Tile::tiles[item->id]; - if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && TileRenderer::canRender(tile->getRenderShape())) - { + Tile* tile = Tile::tiles[item->id]; + if (item->getIconType() == Icon::TYPE_TERRAIN && tile != NULL && + TileRenderer::canRender(tile->getRenderShape())) { glRotatef(spin, 0, 1, 0); - if (m_bItemFrame) - { - glScalef(1.25f, 1.25f, 1.25f); - glTranslatef(0, 0.05f, 0); - glRotatef(-90, 0, 1, 0); - } + if (m_bItemFrame) { + glScalef(1.25f, 1.25f, 1.25f); + glTranslatef(0, 0.05f, 0); + glRotatef(-90, 0, 1, 0); + } - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" float s = 1 / 4.0f; - int shape = tile->getRenderShape(); - if (shape == Tile::SHAPE_CROSS_TEXTURE || shape == Tile::SHAPE_STEM || shape == Tile::SHAPE_LEVER || shape == Tile::SHAPE_TORCH ) - { + int shape = tile->getRenderShape(); + if (shape == Tile::SHAPE_CROSS_TEXTURE || shape == Tile::SHAPE_STEM || + shape == Tile::SHAPE_LEVER || shape == Tile::SHAPE_TORCH) { s = 0.5f; } glScalef(s, s, s); - for (int i = 0; i < count; i++) - { + for (int i = 0; i < count; i++) { glPushMatrix(); - if (i > 0) - { + if (i > 0) { float xo = (random->nextFloat() * 2 - 1) * 0.2f / s; float yo = (random->nextFloat() * 2 - 1) * 0.2f / s; float zo = (random->nextFloat() * 2 - 1) * 0.2f / s; glTranslatef(xo, yo, zo); } - // 4J - change brought forward from 1.8.2 - float br = SharedConstants::TEXTURE_LIGHTING ? 1.0f : itemEntity->getBrightness(a); + // 4J - change brought forward from 1.8.2 + float br = SharedConstants::TEXTURE_LIGHTING + ? 1.0f + : itemEntity->getBrightness(a); tileRenderer->renderTile(tile, item->getAuxValue(), br); glPopMatrix(); } - } - else if (item->getItem()->hasMultipleSpriteLayers()) - { - if (m_bItemFrame) - { - glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); - glTranslatef(0, -0.05f, 0); - glDisable(GL_LIGHTING); - } - else - { - glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); - } - - bindTexture(TN_GUI_ITEMS); // 4J was "/gui/items.png" - - for (int layer = 0; layer <= 1; layer++) - { - random->setSeed(187); - Icon *icon = item->getItem()->getLayerIcon(item->getAuxValue(), layer); - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : itemEntity->getBrightness(a); - if (setColor) - { - int col = Item::items[item->id]->getColor(item, layer); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; - - glColor4f(red * brightness, g * brightness, b * brightness, 1); - renderItemBillboard(itemEntity, icon, count, a, red * brightness, g * brightness, b * brightness); - } - else - { - renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); - } - } - } - else - { - if (m_bItemFrame) - { - glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); - glTranslatef(0, -0.05f, 0); - glDisable(GL_LIGHTING); - } - else - { - glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); - } - - // 4J Stu - For rendering the static compass, we give it a non-zero aux value - if(item->id == Item::compass_Id) item->setAuxValue(255); - Icon *icon = item->getIcon(); - if(item->id == Item::compass_Id) item->setAuxValue(0); - if (item->getIconType() == Icon::TYPE_TERRAIN) - { - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + } else if (item->getItem()->hasMultipleSpriteLayers()) { + if (m_bItemFrame) { + glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); + glTranslatef(0, -0.05f, 0); + glDisable(GL_LIGHTING); + } else { + glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); } - else - { - bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + + bindTexture(TN_GUI_ITEMS); // 4J was "/gui/items.png" + + for (int layer = 0; layer <= 1; layer++) { + random->setSeed(187); + Icon* icon = + item->getItem()->getLayerIcon(item->getAuxValue(), layer); + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : itemEntity->getBrightness(a); + if (setColor) { + int col = Item::items[item->id]->getColor(item, layer); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; + + glColor4f(red * brightness, g * brightness, b * brightness, 1); + renderItemBillboard(itemEntity, icon, count, a, + red * brightness, g * brightness, + b * brightness); + } else { + renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); + } + } + } else { + if (m_bItemFrame) { + glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); + glTranslatef(0, -0.05f, 0); + glDisable(GL_LIGHTING); + } else { + glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); } - if (setColor) - { - int col = Item::items[item->id]->getColor(item,0); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : itemEntity->getBrightness(a); - glColor4f(red * brightness, g * brightness, b * brightness, 1); - renderItemBillboard(itemEntity, icon, count, a, red * brightness, g * brightness, b * brightness); - } - else - { - renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); - } + // 4J Stu - For rendering the static compass, we give it a non-zero aux + // value + if (item->id == Item::compass_Id) item->setAuxValue(255); + Icon* icon = item->getIcon(); + if (item->id == Item::compass_Id) item->setAuxValue(0); + if (item->getIconType() == Icon::TYPE_TERRAIN) { + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + } else { + bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + } + if (setColor) { + int col = Item::items[item->id]->getColor(item, 0); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : itemEntity->getBrightness(a); - } - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); - if( m_bItemFrame ) - { - glEnable(GL_LIGHTING); - } + glColor4f(red * brightness, g * brightness, b * brightness, 1); + renderItemBillboard(itemEntity, icon, count, a, red * brightness, + g * brightness, b * brightness); + } else { + renderItemBillboard(itemEntity, icon, count, a, 1, 1, 1); + } + } + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); + if (m_bItemFrame) { + glEnable(GL_LIGHTING); + } } -void ItemRenderer::renderItemBillboard(std::shared_ptr entity, Icon *icon, int count, float a, float red, float green, float blue) -{ - Tesselator *t = Tesselator::getInstance(); +void ItemRenderer::renderItemBillboard(std::shared_ptr entity, + Icon* icon, int count, float a, + float red, float green, float blue) { + Tesselator* t = Tesselator::getInstance(); - if (icon == NULL) icon = entityRenderDispatcher->textures->getMissingIcon(entity->getItem()->getIconType()); + if (icon == NULL) + icon = entityRenderDispatcher->textures->getMissingIcon( + entity->getItem()->getIconType()); float u0 = icon->getU0(); float u1 = icon->getU1(); float v0 = icon->getV0(); @@ -186,430 +176,450 @@ void ItemRenderer::renderItemBillboard(std::shared_ptr entity, Icon float xo = 0.5f; float yo = 0.25f; - if (entityRenderDispatcher->options->fancyGraphics) - { - // Consider forcing the mipmap LOD level to use, if this is to be rendered from a larger than standard source texture. - int iconWidth = icon->getWidth(); - int LOD = -1; // Default to not doing anything special with LOD forcing - if( iconWidth == 32 ) - { - LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 map - } - else if( iconWidth == 64 ) - { - LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 map - } - RenderManager.StateSetForceLOD(LOD); + if (entityRenderDispatcher->options->fancyGraphics) { + // Consider forcing the mipmap LOD level to use, if this is to be + // rendered from a larger than standard source texture. + int iconWidth = icon->getWidth(); + int LOD = -1; // Default to not doing anything special with LOD forcing + if (iconWidth == 32) { + LOD = 1; // Force LOD level 1 to achieve texture reads from 256x256 + // map + } else if (iconWidth == 64) { + LOD = 2; // Force LOD level 2 to achieve texture reads from 256x256 + // map + } + RenderManager.StateSetForceLOD(LOD); - glPushMatrix(); - if (m_bItemFrame) - { - glRotatef(180, 0, 1, 0); - } - else - { - glRotatef(((entity->age + a) / 20.0f + entity->bobOffs) * Mth::RADDEG, 0, 1, 0); - } + glPushMatrix(); + if (m_bItemFrame) { + glRotatef(180, 0, 1, 0); + } else { + glRotatef( + ((entity->age + a) / 20.0f + entity->bobOffs) * Mth::RADDEG, 0, + 1, 0); + } - float width = 1 / 16.0f; - float margin = 0.35f / 16.0f; - std::shared_ptr item = entity->getItem(); - int items = item->count; + float width = 1 / 16.0f; + float margin = 0.35f / 16.0f; + std::shared_ptr item = entity->getItem(); + int items = item->count; - if (items < 2) - { - count = 1; - } - else if (items < 16) - { - count = 2; - } - else if (items < 32) - { - count = 3; - } - else - { - count = 4; - } + if (items < 2) { + count = 1; + } else if (items < 16) { + count = 2; + } else if (items < 32) { + count = 3; + } else { + count = 4; + } - glTranslatef(-xo, -yo, -((width + margin) * count / 2)); + glTranslatef(-xo, -yo, -((width + margin) * count / 2)); - for (int i = 0; i < count; i++) - { - glTranslatef(0, 0, width + margin); - if (item->getIconType() == Icon::TYPE_TERRAIN && Tile::tiles[item->id] != NULL) - { - bindTexture(TN_TERRAIN); // Was L"/terrain.png"); - } - else - { - bindTexture(TN_GUI_ITEMS); //L"/gui/items.png"); - } - glColor4f(red, green, blue, 1); - // 4J Stu - u coords were swapped in Java - //ItemInHandRenderer::renderItem3D(t, u1, v0, u0, v1, icon->getSourceWidth(), icon->getSourceHeight(), width, false); - ItemInHandRenderer::renderItem3D(t, u0, v0, u1, v1, icon->getSourceWidth(), icon->getSourceHeight(), width, false); + for (int i = 0; i < count; i++) { + glTranslatef(0, 0, width + margin); + if (item->getIconType() == Icon::TYPE_TERRAIN && + Tile::tiles[item->id] != NULL) { + bindTexture(TN_TERRAIN); // Was L"/terrain.png"); + } else { + bindTexture(TN_GUI_ITEMS); // L"/gui/items.png"); + } + glColor4f(red, green, blue, 1); + // 4J Stu - u coords were swapped in Java + // ItemInHandRenderer::renderItem3D(t, u1, v0, u0, v1, + // icon->getSourceWidth(), icon->getSourceHeight(), width, false); + ItemInHandRenderer::renderItem3D( + t, u0, v0, u1, v1, icon->getSourceWidth(), + icon->getSourceHeight(), width, false); - if (item != NULL && item->isFoil()) - { - glDepthFunc(GL_EQUAL); - glDisable(GL_LIGHTING); - entityRenderDispatcher->textures->bindTexture(TN__BLUR__MISC_GLINT); // was L"%blur%/misc/glint.png"); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_COLOR, GL_ONE); - float br = 0.76f; - glColor4f(0.5f * br, 0.25f * br, 0.8f * br, 1); - glMatrixMode(GL_TEXTURE); - glPushMatrix(); - float ss = 1 / 8.0f; - glScalef(ss, ss, ss); - float sx = Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; - glTranslatef(sx, 0, 0); - glRotatef(-50, 0, 0, 1); + if (item != NULL && item->isFoil()) { + glDepthFunc(GL_EQUAL); + glDisable(GL_LIGHTING); + entityRenderDispatcher->textures->bindTexture( + TN__BLUR__MISC_GLINT); // was L"%blur%/misc/glint.png"); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_COLOR, GL_ONE); + float br = 0.76f; + glColor4f(0.5f * br, 0.25f * br, 0.8f * br, 1); + glMatrixMode(GL_TEXTURE); + glPushMatrix(); + float ss = 1 / 8.0f; + glScalef(ss, ss, ss); + float sx = + Minecraft::currentTimeMillis() % (3000) / (3000.0f) * 8; + glTranslatef(sx, 0, 0); + glRotatef(-50, 0, 0, 1); - ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, true); - glPopMatrix(); - glPushMatrix(); - glScalef(ss, ss, ss); - sx = Minecraft::currentTimeMillis() % (3000 + 1873) / (3000 + 1873.0f) * 8; - glTranslatef(-sx, 0, 0); - glRotatef(10, 0, 0, 1); - ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, true); - glPopMatrix(); - glMatrixMode(GL_MODELVIEW); - glDisable(GL_BLEND); - glEnable(GL_LIGHTING); - glDepthFunc(GL_LEQUAL); - } - } + ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, + true); + glPopMatrix(); + glPushMatrix(); + glScalef(ss, ss, ss); + sx = Minecraft::currentTimeMillis() % (3000 + 1873) / + (3000 + 1873.0f) * 8; + glTranslatef(-sx, 0, 0); + glRotatef(10, 0, 0, 1); + ItemInHandRenderer::renderItem3D(t, 0, 0, 1, 1, 255, 255, width, + true); + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glDisable(GL_BLEND); + glEnable(GL_LIGHTING); + glDepthFunc(GL_LEQUAL); + } + } - glPopMatrix(); + glPopMatrix(); - RenderManager.StateSetForceLOD(-1); - } - else - { - for (int i = 0; i < count; i++) - { - glPushMatrix(); - if (i > 0) - { - float _xo = (random->nextFloat() * 2 - 1) * 0.3f; - float _yo = (random->nextFloat() * 2 - 1) * 0.3f; - float _zo = (random->nextFloat() * 2 - 1) * 0.3f; - glTranslatef(_xo, _yo, _zo); - } - if (!m_bItemFrame) glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); - glColor4f(red, green, blue, 1); - t->begin(); - t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 1 - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( 1 - yo), (float)( 0), (float)( u0), (float)( v0)); - t->end(); + RenderManager.StateSetForceLOD(-1); + } else { + for (int i = 0; i < count; i++) { + glPushMatrix(); + if (i > 0) { + float _xo = (random->nextFloat() * 2 - 1) * 0.3f; + float _yo = (random->nextFloat() * 2 - 1) * 0.3f; + float _zo = (random->nextFloat() * 2 - 1) * 0.3f; + glTranslatef(_xo, _yo, _zo); + } + if (!m_bItemFrame) + glRotatef(180 - entityRenderDispatcher->playerRotY, 0, 1, 0); + glColor4f(red, green, blue, 1); + t->begin(); + t->normal(0, 1, 0); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), + (float)(u0), (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), + (float)(u1), (float)(v1)); + t->vertexUV((float)(r - xo), (float)(1 - yo), (float)(0), + (float)(u1), (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(1 - yo), (float)(0), + (float)(u0), (float)(v0)); + t->end(); - glPopMatrix(); - } -} + glPopMatrix(); + } + } } -void ItemRenderer::renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScale, float fAlpha) -{ - renderGuiItem(font,textures,item,x,y,fScale,fScale,fAlpha, true); +void ItemRenderer::renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, + float y, float fScale, float fAlpha) { + renderGuiItem(font, textures, item, x, y, fScale, fScale, fAlpha, true); } #ifdef _XBOX -extern IDirect3DDevice9 *g_pD3DDevice; +extern IDirect3DDevice9* g_pD3DDevice; #endif -// 4J - this used to take x and y as ints, and no scale and alpha - but this interface is now implemented as a wrapper round this more fully featured one -void ItemRenderer::renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScaleX,float fScaleY, float fAlpha, bool useCompiled) -{ - int itemId = item->id; - int itemAuxValue = item->getAuxValue(); - Icon *itemIcon = item->getIcon(); +// 4J - this used to take x and y as ints, and no scale and alpha - but this +// interface is now implemented as a wrapper round this more fully featured one +void ItemRenderer::renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, + float y, float fScaleX, float fScaleY, + float fAlpha, bool useCompiled) { + int itemId = item->id; + int itemAuxValue = item->getAuxValue(); + Icon* itemIcon = item->getIcon(); - if (item->getIconType() == Icon::TYPE_TERRAIN && TileRenderer::canRender(Tile::tiles[itemId]->getRenderShape())) - { - PIXBeginNamedEvent(0,"3D gui item render %d\n",itemId); - MemSect(31); - textures->bindTexture(TN_TERRAIN);//L"/terrain.png")); - MemSect(0); + if (item->getIconType() == Icon::TYPE_TERRAIN && + TileRenderer::canRender(Tile::tiles[itemId]->getRenderShape())) { + PIXBeginNamedEvent(0, "3D gui item render %d\n", itemId); + MemSect(31); + textures->bindTexture(TN_TERRAIN); // L"/terrain.png")); + MemSect(0); - Tile *tile = Tile::tiles[itemId]; + Tile* tile = Tile::tiles[itemId]; glPushMatrix(); - // 4J - original code left here for reference - // 4jcraft: re-enable said original code to fix hotbar block rendering + // 4J - original code left here for reference + // 4jcraft: re-enable said original code to fix hotbar block rendering #if 1 - glTranslatef((float)(x), (float)(y), 0.0f); - //glScalef(fScale, fScale, fScale); - glScalef(fScaleX, fScaleY, 1.0f); // 4jcraft: tweaked to use the new variables - glTranslatef(-2.0f,3.0f, -3.0f + blitOffset); - glScalef(10.0f, 10.0f, 10.0f); + glTranslatef((float)(x), (float)(y), 0.0f); + // glScalef(fScale, fScale, fScale); + glScalef(fScaleX, fScaleY, + 1.0f); // 4jcraft: tweaked to use the new variables + glTranslatef(-2.0f, 3.0f, -3.0f + blitOffset); + glScalef(10.0f, 10.0f, 10.0f); glTranslatef(1.0f, 0.5f, 8.0f); glScalef(1.0f, 1.0f, -1.0f); glRotatef(180.0f + 30.0f, 1.0f, 0.0f, 0.0f); glRotatef(45.0f, 0.0f, 1.0f, 0.0f); #else - glTranslatef(x, y, 0.0f); // Translate to screen coords - glScalef(16.0f*fScaleX, 16.0f*fScaleY, 1.0f); // Scale to 0 to 16*scale range - glTranslatef(0.5f,0.5f,0.0f); // Translate to 0 to 1 range - glScalef(0.55f,0.55f, -1.0f); // Scale to occupy full -0.5 to 0.5 bounding region (just touching top & bottom) - // 0.55 comes from 1/(1+sqrt(2)/sqrt(3)) which is determined by the angles that the cube is rotated in an orthographic projection - glRotatef(180.0f + 30.0f, 1.0f, 0.0f, 0.0f); // Rotate round x axis (centre at origin) - glRotatef(45.0f, 0.0f, 1.0f, 0.0f); // Rotate round y axis (centre at origin) + glTranslatef(x, y, 0.0f); // Translate to screen coords + glScalef(16.0f * fScaleX, 16.0f * fScaleY, + 1.0f); // Scale to 0 to 16*scale range + glTranslatef(0.5f, 0.5f, 0.0f); // Translate to 0 to 1 range + glScalef( + 0.55f, 0.55f, + -1.0f); // Scale to occupy full -0.5 to 0.5 bounding region (just + // touching top & bottom) 0.55 comes from + // 1/(1+sqrt(2)/sqrt(3)) which is determined by the angles + // that the cube is rotated in an orthographic projection + glRotatef(180.0f + 30.0f, 1.0f, 0.0f, + 0.0f); // Rotate round x axis (centre at origin) + glRotatef(45.0f, 0.0f, 1.0f, + 0.0f); // Rotate round y axis (centre at origin) #endif - // 4J-PB - pass the alpha value in - the grass block render has the top surface coloured differently to the rest of the block + // 4J-PB - pass the alpha value in - the grass block render has the top + // surface coloured differently to the rest of the block glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); tileRenderer->renderTile(tile, itemAuxValue, 1, fAlpha, useCompiled); glPopMatrix(); - PIXEndNamedEvent(); - } - else if (Item::items[itemId]->hasMultipleSpriteLayers()) - { - PIXBeginNamedEvent(0,"Potion gui item render %d\n",itemIcon); - // special double-layered - glDisable(GL_LIGHTING); - textures->bindTexture(TN_GUI_ITEMS); // "/gui/items.png" - - for (int layer = 0; layer <= 1; layer++) - { - Icon *fillingIcon = Item::items[itemId]->getLayerIcon(itemAuxValue, layer); - - int col = Item::items[itemId]->getColor(item, layer); - float r = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; - - if (setColor) glColor4f(r, g, b, fAlpha); - // scale the x and y by the scale factor - if((fScaleX!=1.0f) ||(fScaleY!=1.0f)) - { - blit(x, y, fillingIcon, 16 * fScaleX, 16 * fScaleY); - } - else - { - blit((int)x, (int)y, fillingIcon, 16, 16); - } - } - glEnable(GL_LIGHTING); - PIXEndNamedEvent(); - } - else - { - PIXBeginNamedEvent(0,"2D gui item render %d\n",itemIcon); + PIXEndNamedEvent(); + } else if (Item::items[itemId]->hasMultipleSpriteLayers()) { + PIXBeginNamedEvent(0, "Potion gui item render %d\n", itemIcon); + // special double-layered glDisable(GL_LIGHTING); - MemSect(31); - if (item->getIconType() == Icon::TYPE_TERRAIN) - { - textures->bindTexture(TN_TERRAIN);//L"/terrain.png")); + textures->bindTexture(TN_GUI_ITEMS); // "/gui/items.png" + + for (int layer = 0; layer <= 1; layer++) { + Icon* fillingIcon = + Item::items[itemId]->getLayerIcon(itemAuxValue, layer); + + int col = Item::items[itemId]->getColor(item, layer); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; + + if (setColor) glColor4f(r, g, b, fAlpha); + // scale the x and y by the scale factor + if ((fScaleX != 1.0f) || (fScaleY != 1.0f)) { + blit(x, y, fillingIcon, 16 * fScaleX, 16 * fScaleY); + } else { + blit((int)x, (int)y, fillingIcon, 16, 16); + } } - else - { - textures->bindTexture(TN_GUI_ITEMS);//L"/gui/items.png")); + glEnable(GL_LIGHTING); + PIXEndNamedEvent(); + } else { + PIXBeginNamedEvent(0, "2D gui item render %d\n", itemIcon); + glDisable(GL_LIGHTING); + MemSect(31); + if (item->getIconType() == Icon::TYPE_TERRAIN) { + textures->bindTexture(TN_TERRAIN); // L"/terrain.png")); + } else { + textures->bindTexture( + TN_GUI_ITEMS); // L"/gui/items.png")); #ifdef _XBOX - // 4J - make sure we've got linear sampling on minification here as non-mipmapped things like this currently - // default to having point sampling, which makes very small icons render rather badly - g_pD3DDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); + // 4J - make sure we've got linear sampling on + // minification here as non-mipmapped things + // like this currently + // default to having point sampling, which makes very small icons + // render rather badly + g_pD3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); #endif + } + MemSect(0); - } - MemSect(0); + if (itemIcon == NULL) { + itemIcon = textures->getMissingIcon(item->getIconType()); + } - if (itemIcon == NULL) - { - itemIcon = textures->getMissingIcon(item->getIconType()); - } - - int col = Item::items[itemId]->getColor(item,0); + int col = Item::items[itemId]->getColor(item, 0); float r = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; if (setColor) glColor4f(r, g, b, fAlpha); - // scale the x and y by the scale factor - if((fScaleX!=1.0f) ||(fScaleY!=1.0f)) - { - blit(x, y, itemIcon, 16 * fScaleX, 16 * fScaleY); - } - else - { - blit((int)x, (int)y, itemIcon, 16, 16); - } + // scale the x and y by the scale factor + if ((fScaleX != 1.0f) || (fScaleY != 1.0f)) { + blit(x, y, itemIcon, 16 * fScaleX, 16 * fScaleY); + } else { + blit((int)x, (int)y, itemIcon, 16, 16); + } glEnable(GL_LIGHTING); - PIXEndNamedEvent(); - + PIXEndNamedEvent(); } glEnable(GL_CULL_FACE); - } // 4J - original interface, now just a wrapper for preceding overload -void ItemRenderer::renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, int x, int y) -{ - renderGuiItem(font, textures, item, (float)x, (float)y, 1.0f, 1.0f ); +void ItemRenderer::renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, int x, + int y) { + renderGuiItem(font, textures, item, (float)x, (float)y, 1.0f, 1.0f); } -// 4J - this used to take x and y as ints, and no scale, alpha or foil - but this interface is now implemented as a wrapper round this more fully featured one -void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y,float fScale,float fAlpha, bool isFoil) -{ - if(item==NULL) return; - renderAndDecorateItem(font, textures, item, x, y,fScale, fScale, fAlpha, isFoil, true); +// 4J - this used to take x and y as ints, and no scale, alpha or foil - but +// this interface is now implemented as a wrapper round this more fully featured +// one +void ItemRenderer::renderAndDecorateItem( + Font* font, Textures* textures, const std::shared_ptr item, + float x, float y, float fScale, float fAlpha, bool isFoil) { + if (item == NULL) return; + renderAndDecorateItem(font, textures, item, x, y, fScale, fScale, fAlpha, + isFoil, true); } -// 4J - added isConstantBlended and blendFactor parameters. This is true if the gui item is being rendered from a context where it already has blending enabled to do general interface fading -// (ie from the gui rather than xui). In this case we dno't want to enable/disable blending, and do need to restore the blend state when we are done. -void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y,float fScaleX, float fScaleY,float fAlpha, bool isFoil, bool isConstantBlended, bool useCompiled) -{ - if (item == NULL) - { +// 4J - added isConstantBlended and blendFactor parameters. This is true if the +// gui item is being rendered from a context where it already has blending +// enabled to do general interface fading (ie from the gui rather than xui). In +// this case we dno't want to enable/disable blending, and do need to restore +// the blend state when we are done. +void ItemRenderer::renderAndDecorateItem( + Font* font, Textures* textures, const std::shared_ptr item, + float x, float y, float fScaleX, float fScaleY, float fAlpha, bool isFoil, + bool isConstantBlended, bool useCompiled) { + if (item == NULL) { return; } - renderGuiItem(font, textures, item, x, y,fScaleX,fScaleY,fAlpha, useCompiled); - - if (isFoil || item->isFoil()) - { - glDepthFunc(GL_GREATER); - glDisable(GL_LIGHTING); - glDepthMask(false); - textures->bindTexture(TN__BLUR__MISC_GLINT); // 4J was "%blur%/misc/glint.png" - blitOffset -= 50; - if( !isConstantBlended ) glEnable(GL_BLEND); - - glBlendFunc(GL_DST_COLOR, GL_ONE); // 4J - changed blend equation from GL_DST_COLOR, GL_DST_COLOR so we can fade this out + renderGuiItem(font, textures, item, x, y, fScaleX, fScaleY, fAlpha, + useCompiled); - float blendFactor = isConstantBlended ? Gui::currentGuiBlendFactor : 1.0f; + if (isFoil || item->isFoil()) { + glDepthFunc(GL_GREATER); + glDisable(GL_LIGHTING); + glDepthMask(false); + textures->bindTexture( + TN__BLUR__MISC_GLINT); // 4J was "%blur%/misc/glint.png" + blitOffset -= 50; + if (!isConstantBlended) glEnable(GL_BLEND); - glColor4f(0.5f * blendFactor, 0.25f * blendFactor, 0.8f * blendFactor, 1); // 4J - scale back colourisation with blendFactor - // scale the x and y by the scale factor - if((fScaleX!=1.0f) ||(fScaleY!=1.0f)) - { - // 4J Stu - Scales were multiples of 20, making 16 to not overlap in xui scenes - blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, 16 * fScaleX, 16 * fScaleY); - } - else - { - blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, 20, 20); - } - glColor4f(1.0f, 1.0f, 1.0f, 1); // 4J added - if( !isConstantBlended ) glDisable(GL_BLEND); + glBlendFunc(GL_DST_COLOR, + GL_ONE); // 4J - changed blend equation from GL_DST_COLOR, + // GL_DST_COLOR so we can fade this out - glDepthMask(true); - blitOffset += 50; - glEnable(GL_LIGHTING); - glDepthFunc(GL_LEQUAL); + float blendFactor = + isConstantBlended ? Gui::currentGuiBlendFactor : 1.0f; - if( isConstantBlended ) glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - } + glColor4f(0.5f * blendFactor, 0.25f * blendFactor, 0.8f * blendFactor, + 1); // 4J - scale back colourisation with blendFactor + // scale the x and y by the scale factor + if ((fScaleX != 1.0f) || (fScaleY != 1.0f)) { + // 4J Stu - Scales were multiples of 20, making 16 to not overlap in + // xui scenes + blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, + 16 * fScaleX, 16 * fScaleY); + } else { + blitGlint(x * 431278612.0f + y * 32178161.0f, x - 2, y - 2, 20, 20); + } + glColor4f(1.0f, 1.0f, 1.0f, 1); // 4J added + if (!isConstantBlended) glDisable(GL_BLEND); + + glDepthMask(true); + blitOffset += 50; + glEnable(GL_LIGHTING); + glDepthFunc(GL_LEQUAL); + + if (isConstantBlended) + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + } } // 4J - original interface, now just a wrapper for preceding overload -void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, int x, int y) -{ - renderAndDecorateItem( font, textures, item, (float)x, (float)y, 1.0f, 1.0f, item->isFoil() ); +void ItemRenderer::renderAndDecorateItem( + Font* font, Textures* textures, const std::shared_ptr item, + int x, int y) { + renderAndDecorateItem(font, textures, item, (float)x, (float)y, 1.0f, 1.0f, + item->isFoil()); } -// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering accuracy), and to align -// final pixels to the final screen resolution -void ItemRenderer::blitGlint(int id, float x, float y, float w, float h) -{ - float us = 1.0f / 64.0f / 4; - float vs = 1.0f / 64.0f / 4; +// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering +// accuracy), and to align final pixels to the final screen resolution +void ItemRenderer::blitGlint(int id, float x, float y, float w, float h) { + float us = 1.0f / 64.0f / 4; + float vs = 1.0f / 64.0f / 4; - // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; - float xx0 = x * sfx; - float xx1 = ( x + w ) * sfx; - float yy0 = y * sfy; - float yy1 = ( y + h ) * sfy; - // Round to whole pixels - rounding inwards so that we don't overlap any surrounding graphics - xx0 = ceilf(xx0); - xx1 = floorf(xx1); - yy0 = ceilf(yy0); - yy1 = floorf(yy1); - // Offset by half to get actual centre of pixel - again moving inwards to avoid overlap with surrounding graphics - xx0 += 0.5f; - xx1 -= 0.5f; - yy0 += 0.5f; - yy1 -= 0.5f; - // Convert back to game coordinate space - float xx0f = xx0 / sfx; - float xx1f = xx1 / sfx; - float yy0f = yy0 / sfy; - float yy1f = yy1 / sfy; + // 4J - calculate what the pixel coordinates will be in final screen + // coordinates + float sfx = (float)Minecraft::GetInstance()->width / + (float)Minecraft::GetInstance()->width_phys; + float sfy = (float)Minecraft::GetInstance()->height / + (float)Minecraft::GetInstance()->height_phys; + float xx0 = x * sfx; + float xx1 = (x + w) * sfx; + float yy0 = y * sfy; + float yy1 = (y + h) * sfy; + // Round to whole pixels - rounding inwards so that we don't overlap any + // surrounding graphics + xx0 = ceilf(xx0); + xx1 = floorf(xx1); + yy0 = ceilf(yy0); + yy1 = floorf(yy1); + // Offset by half to get actual centre of pixel - again moving inwards to + // avoid overlap with surrounding graphics + xx0 += 0.5f; + xx1 -= 0.5f; + yy0 += 0.5f; + yy1 -= 0.5f; + // Convert back to game coordinate space + float xx0f = xx0 / sfx; + float xx1f = xx1 / sfx; + float yy0f = yy0 / sfy; + float yy1f = yy1 / sfy; - for (int i = 0; i < 2; i++) - { - if (i == 0) glBlendFunc(GL_SRC_COLOR, GL_ONE); - if (i == 1) glBlendFunc(GL_SRC_COLOR, GL_ONE); - float sx = Minecraft::currentTimeMillis() % (3000 + i * 1873) / (3000.0f + i * 1873) * 256; - float sy = 0; - Tesselator *t = Tesselator::getInstance(); - float vv = 4; - if (i == 1) vv = -1; - t->begin(); - t->vertexUV(xx0f, yy1f, blitOffset, (sx + h * vv) * us, (sy + h) * vs); - t->vertexUV(xx1f, yy1f, blitOffset, (sx + w + h * vv) * us, (sy + h) * vs); - t->vertexUV(xx1f, yy0f, blitOffset, (sx + w) * us, (sy + 0) * vs); - t->vertexUV(xx0f, yy0f, blitOffset, (sx + 0) * us, (sy + 0) * vs); - t->end(); - } + for (int i = 0; i < 2; i++) { + if (i == 0) glBlendFunc(GL_SRC_COLOR, GL_ONE); + if (i == 1) glBlendFunc(GL_SRC_COLOR, GL_ONE); + float sx = Minecraft::currentTimeMillis() % (3000 + i * 1873) / + (3000.0f + i * 1873) * 256; + float sy = 0; + Tesselator* t = Tesselator::getInstance(); + float vv = 4; + if (i == 1) vv = -1; + t->begin(); + t->vertexUV(xx0f, yy1f, blitOffset, (sx + h * vv) * us, (sy + h) * vs); + t->vertexUV(xx1f, yy1f, blitOffset, (sx + w + h * vv) * us, + (sy + h) * vs); + t->vertexUV(xx1f, yy0f, blitOffset, (sx + w) * us, (sy + 0) * vs); + t->vertexUV(xx0f, yy0f, blitOffset, (sx + 0) * us, (sy + 0) * vs); + t->end(); + } } -void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, float fAlpha) -{ - renderGuiItemDecorations(font, textures, item, x, y, L"", fAlpha); +void ItemRenderer::renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, + int x, int y, float fAlpha) { + renderGuiItemDecorations(font, textures, item, x, y, L"", fAlpha); } -void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, const std::wstring &countText, float fAlpha) -{ - if (item == NULL) - { +void ItemRenderer::renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, + int x, int y, + const std::wstring& countText, + float fAlpha) { + if (item == NULL) { return; } - - glEnable(GL_BLEND); - RenderManager.StateSetBlendFactor(0xffffff |(((unsigned int)(fAlpha * 0xff))<<24)); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - if (item->count > 1 || !countText.empty() || item->GetForceNumberDisplay()) - { - MemSect(31); + + glEnable(GL_BLEND); + RenderManager.StateSetBlendFactor(0xffffff | + (((unsigned int)(fAlpha * 0xff)) << 24)); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + if (item->count > 1 || !countText.empty() || + item->GetForceNumberDisplay()) { + MemSect(31); std::wstring amount = countText; - if(amount.empty()) - { - int count = item->count; - if(count > 64) - { - amount = _toString(64) + L"+"; - } - else - { - amount = _toString(item->count); - } - } - MemSect(0); + if (amount.empty()) { + int count = item->count; + if (count > 64) { + amount = _toString(64) + L"+"; + } else { + amount = _toString(item->count); + } + } + MemSect(0); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); - font->drawShadow(amount, x + 19 - 2 - font->width(amount), y + 6 + 3, 0xffffff); + font->drawShadow(amount, x + 19 - 2 - font->width(amount), y + 6 + 3, + 0xffffff); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); } - if (item->isDamaged()) - { - int p = (int) Math::round(13.0 - (double) item->getDamageValue() * 13.0 / (double) item->getMaxDamage()); - int cc = (int) Math::round(255.0 - (double) item->getDamageValue() * 255.0 / (double) item->getMaxDamage()); + if (item->isDamaged()) { + int p = (int)Math::round(13.0 - (double)item->getDamageValue() * 13.0 / + (double)item->getMaxDamage()); + int cc = + (int)Math::round(255.0 - (double)item->getDamageValue() * 255.0 / + (double)item->getMaxDamage()); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); int ca = (255 - cc) << 16 | (cc) << 8; int cb = ((255 - cc) / 4) << 16 | (255 / 4) << 8; @@ -617,127 +627,140 @@ void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, std: fillRect(t, x + 2, y + 13, 12, 1, cb); fillRect(t, x + 2, y + 13, p, 1, ca); + glEnable(GL_TEXTURE_2D); + glEnable(GL_LIGHTING); + glEnable(GL_DEPTH_TEST); + glColor4f(1, 1, 1, 1); + } else if (item->hasPotionStrengthBar()) { + glDisable(GL_LIGHTING); + glDisable(GL_DEPTH_TEST); + glDisable(GL_TEXTURE_2D); + + Tesselator* t = Tesselator::getInstance(); + + fillRect(t, x + 3, y + 13, 11, 2, 0x000000); + // fillRect(t, x + 2, y + 13, 13, 1, 0x1dabc0); + fillRect(t, x + 3, y + 13, + m_iPotionStrengthBarWidth[item->GetPotionStrength()], 2, + 0x00e1eb); + fillRect(t, x + 2 + 3, y + 13, 1, 2, 0x000000); + fillRect(t, x + 2 + 3 + 3, y + 13, 1, 2, 0x000000); + fillRect(t, x + 2 + 3 + 3 + 3, y + 13, 1, 2, 0x000000); + glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glColor4f(1, 1, 1, 1); } - else if(item->hasPotionStrengthBar()) - { - glDisable(GL_LIGHTING); - glDisable(GL_DEPTH_TEST); - glDisable(GL_TEXTURE_2D); - - Tesselator *t = Tesselator::getInstance(); - - fillRect(t, x + 3, y + 13, 11, 2, 0x000000); - //fillRect(t, x + 2, y + 13, 13, 1, 0x1dabc0); - fillRect(t, x + 3, y + 13, m_iPotionStrengthBarWidth[item->GetPotionStrength()], 2, 0x00e1eb); - fillRect(t, x + 2 + 3, y + 13, 1, 2, 0x000000); - fillRect(t, x + 2 + 3+3, y + 13, 1, 2, 0x000000); - fillRect(t, x + 2 + 3+3+3, y + 13, 1, 2, 0x000000); - - - glEnable(GL_TEXTURE_2D); - glEnable(GL_LIGHTING); - glEnable(GL_DEPTH_TEST); - glColor4f(1, 1, 1, 1); - } - glDisable(GL_BLEND); + glDisable(GL_BLEND); } -const int ItemRenderer::m_iPotionStrengthBarWidth[]= -{ - 3,6,9,11 -}; +const int ItemRenderer::m_iPotionStrengthBarWidth[] = {3, 6, 9, 11}; -void ItemRenderer::fillRect(Tesselator *t, int x, int y, int w, int h, int c) -{ - t->begin(); - t->color(c); - t->vertex((float)(x + 0), (float)( y + 0), (float)( 0)); - t->vertex((float)(x + 0), (float)( y + h), (float)( 0)); - t->vertex((float)(x + w), (float)( y + h), (float)( 0)); - t->vertex((float)(x + w), (float)( y + 0), (float)( 0)); - t->end(); +void ItemRenderer::fillRect(Tesselator* t, int x, int y, int w, int h, int c) { + t->begin(); + t->color(c); + t->vertex((float)(x + 0), (float)(y + 0), (float)(0)); + t->vertex((float)(x + 0), (float)(y + h), (float)(0)); + t->vertex((float)(x + w), (float)(y + h), (float)(0)); + t->vertex((float)(x + w), (float)(y + 0), (float)(0)); + t->end(); } -// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering accuracy), and to align -// final pixels to the final screen resolution -void ItemRenderer::blit(float x, float y, int sx, int sy, float w, float h) -{ - float us = 1 / 256.0f; - float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); - t->begin(); +// 4J - a few changes here to get x, y, w, h in as floats (for xui rendering +// accuracy), and to align final pixels to the final screen resolution +void ItemRenderer::blit(float x, float y, int sx, int sy, float w, float h) { + float us = 1 / 256.0f; + float vs = 1 / 256.0f; + Tesselator* t = Tesselator::getInstance(); + t->begin(); - // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; - float xx0 = x * sfx; - float xx1 = ( x + w ) * sfx; - float yy0 = y * sfy; - float yy1 = ( y + h ) * sfy; - // Round to whole pixels - rounding inwards so that we don't overlap any surrounding graphics - xx0 = ceilf(xx0); - xx1 = floorf(xx1); - yy0 = ceilf(yy0); - yy1 = floorf(yy1); - // Offset by half to get actual centre of pixel - again moving inwards to avoid overlap with surrounding graphics - xx0 += 0.5f; - xx1 -= 0.5f; - yy0 += 0.5f; - yy1 -= 0.5f; - // Convert back to game coordinate space - float xx0f = xx0 / sfx; - float xx1f = xx1 / sfx; - float yy0f = yy0 / sfy; - float yy1f = yy1 / sfy; + // 4J - calculate what the pixel coordinates will be in final screen + // coordinates + float sfx = (float)Minecraft::GetInstance()->width / + (float)Minecraft::GetInstance()->width_phys; + float sfy = (float)Minecraft::GetInstance()->height / + (float)Minecraft::GetInstance()->height_phys; + float xx0 = x * sfx; + float xx1 = (x + w) * sfx; + float yy0 = y * sfy; + float yy1 = (y + h) * sfy; + // Round to whole pixels - rounding inwards so that we don't overlap any + // surrounding graphics + xx0 = ceilf(xx0); + xx1 = floorf(xx1); + yy0 = ceilf(yy0); + yy1 = floorf(yy1); + // Offset by half to get actual centre of pixel - again moving inwards to + // avoid overlap with surrounding graphics + xx0 += 0.5f; + xx1 -= 0.5f; + yy0 += 0.5f; + yy1 -= 0.5f; + // Convert back to game coordinate space + float xx0f = xx0 / sfx; + float xx1f = xx1 / sfx; + float yy0f = yy0 / sfy; + float yy1f = yy1 / sfy; - // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float f = ( 0.5f * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; + // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for + // physical & game width) from each x & y coordinate to compensate for + // centre of pixels in directx vs openGL + float f = (0.5f * (float)Minecraft::GetInstance()->width) / + (float)Minecraft::GetInstance()->width_phys; - t->vertexUV(xx0f, yy1f, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + 16) * vs)); - t->vertexUV(xx1f, yy1f, (float)( blitOffset), (float)( (sx + 16) * us), (float)( (sy + 16) * vs)); - t->vertexUV(xx1f, yy0f, (float)( blitOffset), (float)( (sx + 16) * us), (float)( (sy + 0) * vs)); - t->vertexUV(xx0f, yy0f, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); - t->end(); + t->vertexUV(xx0f, yy1f, (float)(blitOffset), (float)((sx + 0) * us), + (float)((sy + 16) * vs)); + t->vertexUV(xx1f, yy1f, (float)(blitOffset), (float)((sx + 16) * us), + (float)((sy + 16) * vs)); + t->vertexUV(xx1f, yy0f, (float)(blitOffset), (float)((sx + 16) * us), + (float)((sy + 0) * vs)); + t->vertexUV(xx0f, yy0f, (float)(blitOffset), (float)((sx + 0) * us), + (float)((sy + 0) * vs)); + t->end(); } -void ItemRenderer::blit(float x, float y, Icon *tex, float w, float h) -{ - Tesselator *t = Tesselator::getInstance(); - t->begin(); +void ItemRenderer::blit(float x, float y, Icon* tex, float w, float h) { + Tesselator* t = Tesselator::getInstance(); + t->begin(); - // 4J - calculate what the pixel coordinates will be in final screen coordinates - float sfx = (float)Minecraft::GetInstance()->width / (float)Minecraft::GetInstance()->width_phys; - float sfy = (float)Minecraft::GetInstance()->height / (float)Minecraft::GetInstance()->height_phys; - float xx0 = x * sfx; - float xx1 = ( x + w ) * sfx; - float yy0 = y * sfy; - float yy1 = ( y + h ) * sfy; - // Round to whole pixels - rounding inwards so that we don't overlap any surrounding graphics - xx0 = ceilf(xx0); - xx1 = floorf(xx1); - yy0 = ceilf(yy0); - yy1 = floorf(yy1); - // Offset by half to get actual centre of pixel - again moving inwards to avoid overlap with surrounding graphics - xx0 += 0.5f; - xx1 -= 0.5f; - yy0 += 0.5f; - yy1 -= 0.5f; - // Convert back to game coordinate space - float xx0f = xx0 / sfx; - float xx1f = xx1 / sfx; - float yy0f = yy0 / sfy; - float yy1f = yy1 / sfy; + // 4J - calculate what the pixel coordinates will be in final screen + // coordinates + float sfx = (float)Minecraft::GetInstance()->width / + (float)Minecraft::GetInstance()->width_phys; + float sfy = (float)Minecraft::GetInstance()->height / + (float)Minecraft::GetInstance()->height_phys; + float xx0 = x * sfx; + float xx1 = (x + w) * sfx; + float yy0 = y * sfy; + float yy1 = (y + h) * sfy; + // Round to whole pixels - rounding inwards so that we don't overlap any + // surrounding graphics + xx0 = ceilf(xx0); + xx1 = floorf(xx1); + yy0 = ceilf(yy0); + yy1 = floorf(yy1); + // Offset by half to get actual centre of pixel - again moving inwards to + // avoid overlap with surrounding graphics + xx0 += 0.5f; + xx1 -= 0.5f; + yy0 += 0.5f; + yy1 -= 0.5f; + // Convert back to game coordinate space + float xx0f = xx0 / sfx; + float xx1f = xx1 / sfx; + float yy0f = yy0 / sfy; + float yy1f = yy1 / sfy; - // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float f = ( 0.5f * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; + // 4J - subtracting 0.5f (actual screen pixels, so need to compensate for + // physical & game width) from each x & y coordinate to compensate for + // centre of pixels in directx vs openGL + float f = (0.5f * (float)Minecraft::GetInstance()->width) / + (float)Minecraft::GetInstance()->width_phys; - t->vertexUV(xx0f, yy1f, blitOffset, tex->getU0(true), tex->getV1(true)); - t->vertexUV(xx1f, yy1f, blitOffset, tex->getU1(true), tex->getV1(true)); - t->vertexUV(xx1f, yy0f, blitOffset, tex->getU1(true), tex->getV0(true)); - t->vertexUV(xx0f, yy0f, blitOffset, tex->getU0(true), tex->getV0(true)); - t->end(); + t->vertexUV(xx0f, yy1f, blitOffset, tex->getU0(true), tex->getV1(true)); + t->vertexUV(xx1f, yy1f, blitOffset, tex->getU1(true), tex->getV1(true)); + t->vertexUV(xx1f, yy0f, blitOffset, tex->getU1(true), tex->getV0(true)); + t->vertexUV(xx0f, yy0f, blitOffset, tex->getU0(true), tex->getV0(true)); + t->end(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h index f2f68a254..d3e0df372 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemRenderer.h @@ -6,47 +6,77 @@ class ItemInstance; class Random; class ItemEntity; -class ItemRenderer : public EntityRenderer -{ +class ItemRenderer : public EntityRenderer { private: -// TileRenderer *tileRenderer; // 4J - removed - this is shadowing the tilerenderer from entityrenderer - Random *random; - bool m_bItemFrame; + // TileRenderer *tileRenderer; // 4J - removed - this is shadowing the + //tilerenderer from entityrenderer + Random* random; + bool m_bItemFrame; + public: - bool setColor; - float blitOffset; + bool setColor; + float blitOffset; ItemRenderer(); - virtual ~ItemRenderer(); - virtual void render(std::shared_ptr _itemEntity, double x, double y, double z, float rot, float a); + virtual ~ItemRenderer(); + virtual void render(std::shared_ptr _itemEntity, double x, double y, + double z, float rot, float a); private: - virtual void renderItemBillboard(std::shared_ptr entity, Icon *icon, int count, float a, float red, float green, float blue); + virtual void renderItemBillboard(std::shared_ptr entity, + Icon* icon, int count, float a, float red, + float green, float blue); public: - // 4J - original 2 interface variants - void renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, int x, int y); - void renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, int x, int y); - // 4J - new interfaces added - void renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScale, float fAlpha); - void renderGuiItem(Font *font, Textures *textures, std::shared_ptr item, float x, float y, float fScaleX,float fScaleY, float fAlpha, bool useCompiled); // 4J Added useCompiled - void renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y, float fScale, float fAlpha, bool isFoil); - void renderAndDecorateItem(Font *font, Textures *textures, const std::shared_ptr item, float x, float y, float fScaleX, float fScaleY, float fAlpha, bool isFoil, bool isConstantBlended, bool useCompiled = true); // 4J - added isConstantBlended and useCompiled + // 4J - original 2 interface variants + void renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, int x, int y); + void renderAndDecorateItem(Font* font, Textures* textures, + const std::shared_ptr item, int x, + int y); + // 4J - new interfaces added + void renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, float y, + float fScale, float fAlpha); + void renderGuiItem(Font* font, Textures* textures, + std::shared_ptr item, float x, float y, + float fScaleX, float fScaleY, float fAlpha, + bool useCompiled); // 4J Added useCompiled + void renderAndDecorateItem(Font* font, Textures* textures, + const std::shared_ptr item, + float x, float y, float fScale, float fAlpha, + bool isFoil); + void renderAndDecorateItem( + Font* font, Textures* textures, + const std::shared_ptr item, float x, float y, + float fScaleX, float fScaleY, float fAlpha, bool isFoil, + bool isConstantBlended, + bool useCompiled = + true); // 4J - added isConstantBlended and useCompiled - // 4J Added - virtual void SetItemFrame(bool bSet) {m_bItemFrame=bSet;} + // 4J Added + virtual void SetItemFrame(bool bSet) { m_bItemFrame = bSet; } - static const int m_iPotionStrengthBarWidth[4]; + static const int m_iPotionStrengthBarWidth[4]; private: - void blitGlint(int id, float x, float y, float w, float h); // 4J - changed x,y,w,h to floats + void blitGlint(int id, float x, float y, float w, + float h); // 4J - changed x,y,w,h to floats public: - void renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, float fAlpha = 1.0f); - void renderGuiItemDecorations(Font *font, Textures *textures, std::shared_ptr item, int x, int y, const std::wstring &countText, float fAlpha = 1.0f); + void renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, int x, + int y, float fAlpha = 1.0f); + void renderGuiItemDecorations(Font* font, Textures* textures, + std::shared_ptr item, int x, + int y, const std::wstring& countText, + float fAlpha = 1.0f); + private: - void fillRect(Tesselator *t, int x, int y, int w, int h, int c); + void fillRect(Tesselator* t, int x, int y, int w, int h, int c); + public: - void blit(float x, float y, int sx, int sy, float w, float h); // 4J - changed x,y,w,h to floats - void blit(float x, float y, Icon *tex, float w, float h); + void blit(float x, float y, int sx, int sy, float w, + float h); // 4J - changed x,y,w,h to floats + void blit(float x, float y, Icon* tex, float w, float h); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp index 0966845a2..51d3a9ba3 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.cpp @@ -6,58 +6,57 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -ItemSpriteRenderer::ItemSpriteRenderer(Item *sourceItem, int sourceItemAuxValue /*= 0*/) : EntityRenderer() -{ - this->sourceItem = sourceItem; - this->sourceItemAuxValue = sourceItemAuxValue; +ItemSpriteRenderer::ItemSpriteRenderer(Item* sourceItem, + int sourceItemAuxValue /*= 0*/) + : EntityRenderer() { + this->sourceItem = sourceItem; + this->sourceItemAuxValue = sourceItemAuxValue; } -//ItemSpriteRenderer::ItemSpriteRenderer(int icon) : EntityRenderer() +// ItemSpriteRenderer::ItemSpriteRenderer(int icon) : EntityRenderer() //{ // this(sourceItem, 0); -//} +// } -void ItemSpriteRenderer::render(std::shared_ptr e, double x, double y, double z, float rot, float a) -{ - // the icon is already cached in the item object, so there should not be any performance impact by not caching it here - Icon *icon = sourceItem->getIcon(sourceItemAuxValue); - if (icon == NULL) - { - return; - } +void ItemSpriteRenderer::render(std::shared_ptr e, double x, double y, + double z, float rot, float a) { + // the icon is already cached in the item object, so there should not be any + // performance impact by not caching it here + Icon* icon = sourceItem->getIcon(sourceItemAuxValue); + if (icon == NULL) { + return; + } glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glEnable(GL_RESCALE_NORMAL); glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); - bindTexture(TN_GUI_ITEMS); // 4J - was L"/gui/items.png" - Tesselator *t = Tesselator::getInstance(); + bindTexture(TN_GUI_ITEMS); // 4J - was L"/gui/items.png" + Tesselator* t = Tesselator::getInstance(); - if (icon == PotionItem::getTexture(PotionItem::THROWABLE_ICON) ) - { + if (icon == PotionItem::getTexture(PotionItem::THROWABLE_ICON)) { + int col = PotionBrewing::getColorValue( + (std::dynamic_pointer_cast(e))->getPotionValue(), + false); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - int col = PotionBrewing::getColorValue((std::dynamic_pointer_cast(e) )->getPotionValue(), false); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + glColor3f(red, g, b); + glPushMatrix(); + renderIcon(t, PotionItem::getTexture(PotionItem::CONTENTS_ICON)); + glPopMatrix(); + glColor3f(1, 1, 1); + } + renderIcon(t, icon); - glColor3f(red, g, b); - glPushMatrix(); - renderIcon(t, PotionItem::getTexture(PotionItem::CONTENTS_ICON)); - glPopMatrix(); - glColor3f(1, 1, 1); - } - - renderIcon(t, icon); - - glDisable(GL_RESCALE_NORMAL); - glPopMatrix(); + glDisable(GL_RESCALE_NORMAL); + glPopMatrix(); } -void ItemSpriteRenderer::renderIcon(Tesselator *t, Icon *icon) -{ +void ItemSpriteRenderer::renderIcon(Tesselator* t, Icon* icon) { float u0 = icon->getU0(); float u1 = icon->getU1(); float v0 = icon->getV0(); @@ -71,9 +70,13 @@ void ItemSpriteRenderer::renderIcon(Tesselator *t, Icon *icon) glRotatef(-entityRenderDispatcher->playerRotX, 1, 0, 0); t->begin(); t->normal(0, 1, 0); - t->vertexUV((float)(0 - xo), (float)( 0 - yo), (float)( 0), (float)( u0), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( 0 - yo), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(r - xo), (float)( r - yo), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(0 - xo), (float)( r - yo), (float)( 0), (float)( u0), (float)( v0)); + t->vertexUV((float)(0 - xo), (float)(0 - yo), (float)(0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(0 - yo), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(r - xo), (float)(r - yo), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(0 - xo), (float)(r - yo), (float)(0), (float)(u0), + (float)(v0)); t->end(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h index e83597839..103e5aaa6 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ItemSpriteRenderer.h @@ -3,16 +3,17 @@ class Item; -class ItemSpriteRenderer : public EntityRenderer -{ +class ItemSpriteRenderer : public EntityRenderer { private: - Item *sourceItem; - int sourceItemAuxValue; + Item* sourceItem; + int sourceItemAuxValue; + public: - ItemSpriteRenderer(Item *sourceItem, int sourceItemAuxValue = 0); - //ItemSpriteRenderer(Item *icon); - virtual void render(std::shared_ptr e, double x, double y, double z, float rot, float a); + ItemSpriteRenderer(Item* sourceItem, int sourceItemAuxValue = 0); + // ItemSpriteRenderer(Item *icon); + virtual void render(std::shared_ptr e, double x, double y, double z, + float rot, float a); private: - void renderIcon(Tesselator *t, Icon *icon); + void renderIcon(Tesselator* t, Icon* icon); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp index 27987b9ac..b75b36ae5 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.cpp @@ -3,34 +3,36 @@ #include "../Models/LavaSlimeModel.h" #include "LavaSlimeRenderer.h" -LavaSlimeRenderer::LavaSlimeRenderer() : MobRenderer(new LavaSlimeModel(), .25f) -{ - this->modelVersion = ((LavaSlimeModel *) model)->getModelVersion(); +LavaSlimeRenderer::LavaSlimeRenderer() + : MobRenderer(new LavaSlimeModel(), .25f) { + this->modelVersion = ((LavaSlimeModel*)model)->getModelVersion(); } -void LavaSlimeRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type LavaSlime rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - int modelVersion = ((LavaSlimeModel *) model)->getModelVersion(); - if (modelVersion != this->modelVersion) - { - this->modelVersion = modelVersion; - model = new LavaSlimeModel(); - app.DebugPrintf("new lava slime model\n"); - } - MobRenderer::render(mob, x, y, z, rot, a); +void LavaSlimeRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type LavaSlime rather than std::shared_ptr we have here - do + // some casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + int modelVersion = ((LavaSlimeModel*)model)->getModelVersion(); + if (modelVersion != this->modelVersion) { + this->modelVersion = modelVersion; + model = new LavaSlimeModel(); + app.DebugPrintf("new lava slime model\n"); + } + MobRenderer::render(mob, x, y, z, rot, a); } -void LavaSlimeRenderer::scale(std::shared_ptr _slime, float a) -{ - // 4J - original version used generics and thus had an input parameter of type LavaSlime rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr slime = std::dynamic_pointer_cast(_slime); - int size = slime->getSize(); - float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / (size * 0.5f + 1); - float w = 1 / (ss + 1); - float s = size; - glScalef(w * s, 1 / w * s, w * s); +void LavaSlimeRenderer::scale(std::shared_ptr _slime, float a) { + // 4J - original version used generics and thus had an input parameter of + // type LavaSlime rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr slime = + std::dynamic_pointer_cast(_slime); + int size = slime->getSize(); + float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / + (size * 0.5f + 1); + float w = 1 / (ss + 1); + float s = size; + glScalef(w * s, 1 / w * s, w * s); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h index 29afb390e..0afc0b515 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/LavaSlimeRenderer.h @@ -2,16 +2,16 @@ #include "MobRenderer.h" -class LavaSlimeRenderer : public MobRenderer -{ +class LavaSlimeRenderer : public MobRenderer { private: - int modelVersion; + int modelVersion; public: - LavaSlimeRenderer(); + LavaSlimeRenderer(); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); protected: - virtual void scale(std::shared_ptr _slime, float a); + virtual void scale(std::shared_ptr _slime, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp index cb5ba79ee..fe4321e12 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.cpp @@ -3,27 +3,27 @@ #include "../Tesselator.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.global.h" -void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr bolt = std::dynamic_pointer_cast(_bolt); +void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr bolt = + std::dynamic_pointer_cast(_bolt); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); - double xOffs[8]; double zOffs[8]; double xOff = 0; double zOff = 0; { - Random *random = new Random(bolt->seed); - for (int h = 7; h >= 0; h--) - { + Random* random = new Random(bolt->seed); + for (int h = 7; h >= 0; h--) { xOffs[h] = xOff; zOffs[h] = zOff; xOff += random->nextInt(11) - 5; @@ -31,28 +31,22 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub } } - for (int r = 0; r < 4; r++) - { - Random *random = new Random(bolt->seed); - for (int p = 0; p < 3; p++) - { + for (int r = 0; r < 4; r++) { + Random* random = new Random(bolt->seed); + for (int p = 0; p < 3; p++) { int hs = 7; int ht = 0; if (p > 0) hs = 7 - p; if (p > 0) ht = hs - 2; double xo0 = xOffs[hs] - xOff; double zo0 = zOffs[hs] - zOff; - for (int h = hs; h >= ht; h--) - { + for (int h = hs; h >= ht; h--) { double xo1 = xo0; double zo1 = zo0; - if (p == 0) - { + if (p == 0) { xo0 += random->nextInt(11) - 5; zo0 += random->nextInt(11) - 5; - } - else - { + } else { xo0 += random->nextInt(31) - 15; zo0 += random->nextInt(31) - 15; } @@ -65,10 +59,9 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub if (p == 0) rr1 *= (h * 0.1 + 1); double rr2 = (0.1 + r * 0.2); - if (p == 0) rr2 *= ((h-1) * 0.1 + 1); + if (p == 0) rr2 *= ((h - 1) * 0.1 + 1); - for (int i = 0; i < 5; i++) - { + for (int i = 0; i < 5; i++) { double xx1 = x + 0.5 - rr1; double zz1 = z + 0.5 - rr1; if (i == 1 || i == 2) xx1 += rr1 * 2; @@ -79,9 +72,10 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub if (i == 1 || i == 2) xx2 += rr2 * 2; if (i == 2 || i == 3) zz2 += rr2 * 2; - t->vertex((float)(xx2 + xo0), (float)( y + (h) * 16), (float)( zz2 + zo0)); - t->vertex((float)(xx1 + xo1), (float)( y + (h + 1) * 16), (float)( zz1 + zo1)); - + t->vertex((float)(xx2 + xo0), (float)(y + (h) * 16), + (float)(zz2 + zo0)); + t->vertex((float)(xx1 + xo1), (float)(y + (h + 1) * 16), + (float)(zz1 + zo1)); } t->end(); @@ -89,9 +83,7 @@ void LightningBoltRenderer::render(std::shared_ptr _bolt, double x, doub } } - glDisable(GL_BLEND); glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); - } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h index bf5c7c82c..a2437037e 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/LightningBoltRenderer.h @@ -1,8 +1,8 @@ #pragma once #include "EntityRenderer.h" -class LightningBoltRenderer : public EntityRenderer -{ +class LightningBoltRenderer : public EntityRenderer { public: - virtual void render(std::shared_ptr bolt, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr bolt, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp index e5928f55b..ddfdc0be9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.cpp @@ -4,28 +4,29 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -MinecartRenderer::MinecartRenderer() -{ +MinecartRenderer::MinecartRenderer() { this->shadowRadius = 0.5f; model = new MinecartModel(); } -void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr cart = std::dynamic_pointer_cast(_cart); +void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, + double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr cart = std::dynamic_pointer_cast(_cart); glPushMatrix(); - + // 4jcraft added a bunch of casts to prever overflow int64_t seed = (int64_t)((uint64_t)cart->entityId * 493286711ULL); - seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 4392167121ULL) + ((uint64_t)seed * 98761ULL)); + seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 4392167121ULL) + + ((uint64_t)seed * 98761ULL)); - float xo = ((((seed >> 16) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; - float yo = ((((seed >> 20) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; - float zo = ((((seed >> 24) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; + float xo = ((((seed >> 16) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; + float yo = ((((seed >> 20) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; + float zo = ((((seed >> 24) & 0x7) + 0.5f) / 8.0f - 0.5f) * 0.004f; - glTranslatef(xo, yo, zo); + glTranslatef(xo, yo, zo); double xx = cart->xOld + (cart->x - cart->xOld) * a; double yy = cart->yOld + (cart->y - cart->yOld) * a; @@ -33,14 +34,13 @@ void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, double r = 0.3f; - Vec3 *p = cart->getPos(xx, yy, zz); + Vec3* p = cart->getPos(xx, yy, zz); float xRot = cart->xRotO + (cart->xRot - cart->xRotO) * a; - if (p != NULL) - { - Vec3 *p0 = cart->getPosOffs(xx, yy, zz, r); - Vec3 *p1 = cart->getPosOffs(xx, yy, zz, -r); + if (p != NULL) { + Vec3* p0 = cart->getPosOffs(xx, yy, zz, r); + Vec3* p1 = cart->getPosOffs(xx, yy, zz, -r); if (p0 == NULL) p0 = p; if (p1 == NULL) p1 = p; @@ -48,60 +48,52 @@ void MinecartRenderer::render(std::shared_ptr _cart, double x, double y, y += (p0->y + p1->y) / 2 - yy; z += p->z - zz; - Vec3 *dir = p1->add(-p0->x, -p0->y, -p0->z); - if (dir->length() == 0) - { - } - else - { + Vec3* dir = p1->add(-p0->x, -p0->y, -p0->z); + if (dir->length() == 0) { + } else { dir = dir->normalize(); - rot = (float) (atan2(dir->z, dir->x) * 180 / PI); - xRot = (float) (atan(dir->y) * 73); + rot = (float)(atan2(dir->z, dir->x) * 180 / PI); + xRot = (float)(atan(dir->y) * 73); } } - glTranslatef((float) x, (float) y, (float) z); + glTranslatef((float)x, (float)y, (float)z); glRotatef(180 - rot, 0, 1, 0); glRotatef(-xRot, 0, 0, 1); float hurt = cart->getHurtTime() - a; float dmg = cart->getDamage() - a; if (dmg < 0) dmg = 0; - if (hurt > 0) - { - glRotatef(Mth::sin(hurt) * hurt * dmg / 10 * cart->getHurtDir(), 1, 0, 0); + if (hurt > 0) { + glRotatef(Mth::sin(hurt) * hurt * dmg / 10 * cart->getHurtDir(), 1, 0, + 0); } - if (cart->type != Minecart::RIDEABLE) - { - glPushMatrix(); - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + if (cart->type != Minecart::RIDEABLE) { + glPushMatrix(); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" float ss = 12 / 16.0f; glScalef(ss, ss, ss); - // 4J - changes here brought forward from 1.2.3 - if (cart->type == Minecart::CHEST) - { - glTranslatef(0 / 16.0f, 8 / 16.0f, 0 / 16.0f); - TileRenderer *tr = new TileRenderer(); - tr->renderTile(Tile::chest, 0, cart->getBrightness(a)); - delete tr; - } - else if (cart->type == Minecart::FURNACE) - { - glTranslatef(0, 6 / 16.0f, 0); - TileRenderer *tr = new TileRenderer(); - tr->renderTile(Tile::furnace, 0, cart->getBrightness(a)); - delete tr; - } - glPopMatrix(); - glColor4f(1, 1, 1, 1); + // 4J - changes here brought forward from 1.2.3 + if (cart->type == Minecart::CHEST) { + glTranslatef(0 / 16.0f, 8 / 16.0f, 0 / 16.0f); + TileRenderer* tr = new TileRenderer(); + tr->renderTile(Tile::chest, 0, cart->getBrightness(a)); + delete tr; + } else if (cart->type == Minecart::FURNACE) { + glTranslatef(0, 6 / 16.0f, 0); + TileRenderer* tr = new TileRenderer(); + tr->renderTile(Tile::furnace, 0, cart->getBrightness(a)); + delete tr; + } + glPopMatrix(); + glColor4f(1, 1, 1, 1); } - bindTexture(TN_ITEM_CART); // 4J - was L"/item/cart.png" + bindTexture(TN_ITEM_CART); // 4J - was L"/item/cart.png" glScalef(-1, -1, 1); // model.render(0, 0, cart->getLootContent() * 7.1f - 0.1f, 0, 0, 1 / -// 16.0f); + // 16.0f); model->render(cart, 0, 0, -0.1f, 0, 0, 1 / 16.0f, true); glPopMatrix(); - } diff --git a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h index 6902a3bf2..5c0ee7c35 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MinecartRenderer.h @@ -1,12 +1,12 @@ #pragma once #include "EntityRenderer.h" -class MinecartRenderer : public EntityRenderer -{ +class MinecartRenderer : public EntityRenderer { protected: - Model *model; + Model* model; public: - MinecartRenderer(); - void render(std::shared_ptr _cart, double x, double y, double z, float rot, float a); + MinecartRenderer(); + void render(std::shared_ptr _cart, double x, double y, double z, + float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp index f14e58f01..18493e235 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.cpp @@ -8,34 +8,28 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "EntityRenderDispatcher.h" -MobRenderer::MobRenderer(Model *model, float shadow) : EntityRenderer() -{ +MobRenderer::MobRenderer(Model* model, float shadow) : EntityRenderer() { this->model = model; this->shadowRadius = shadow; - this->armor = NULL; + this->armor = NULL; } -void MobRenderer::setArmor(Model *armor) -{ - this->armor = armor; +void MobRenderer::setArmor(Model* armor) { this->armor = armor; } + +float MobRenderer::rotlerp(float from, float to, float a) { + float diff = to - from; + while (diff < -180) diff += 360; + while (diff >= 180) diff -= 360; + return from + a * diff; } -float MobRenderer::rotlerp(float from, float to, float a) -{ - float diff = to - from; - while (diff < -180) - diff += 360; - while (diff >= 180) - diff -= 360; - return from + a * diff; -} - -void MobRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - added - this used to use generics so the input parameter could be a mob (or derived type), but we aren't - // able to do that so dynamically casting to get the more specific type here. - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void MobRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - added - this used to use generics so the input parameter could be a + // mob (or derived type), but we aren't able to do that so dynamically + // casting to get the more specific type here. + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); glPushMatrix(); glDisable(GL_CULL_FACE); @@ -43,235 +37,236 @@ void MobRenderer::render(std::shared_ptr _mob, double x, double y, doubl if (armor != NULL) armor->attackTime = model->attackTime; model->riding = mob->isRiding(); if (armor != NULL) armor->riding = model->riding; - model->young = mob->isBaby(); - if (armor != NULL) armor->young = model->young; + model->young = mob->isBaby(); + if (armor != NULL) armor->young = model->young; - // 4J - removed try/catch -// try -// { - float bodyRot = rotlerp(mob->yBodyRotO, mob->yBodyRot, a); - float headRot = rotlerp(mob->yHeadRotO, mob->yHeadRot, a); + // 4J - removed try/catch + // try + // { + float bodyRot = rotlerp(mob->yBodyRotO, mob->yBodyRot, a); + float headRot = rotlerp(mob->yHeadRotO, mob->yHeadRot, a); - if (mob->isRiding() && std::dynamic_pointer_cast(mob->riding)) - { - std::shared_ptr riding = std::dynamic_pointer_cast(mob->riding); - bodyRot = rotlerp(riding->yBodyRotO, riding->yBodyRot, a); + if (mob->isRiding() && std::dynamic_pointer_cast(mob->riding)) { + std::shared_ptr riding = + std::dynamic_pointer_cast(mob->riding); + bodyRot = rotlerp(riding->yBodyRotO, riding->yBodyRot, a); - float headDiff = Mth::wrapDegrees(headRot - bodyRot); - if (headDiff < -85) headDiff = -85; - if (headDiff >= 85) headDiff = +85; - bodyRot = headRot - headDiff; - if (headDiff * headDiff > 50 * 50) - { - bodyRot += headDiff * 0.2f; - } - } - - float headRotx = (mob->xRotO + (mob->xRot - mob->xRotO) * a); - - setupPosition(mob, x, y, z); - - float bob = getBob(mob, a); - setupRotations(mob, bob, bodyRot, a); - - float _scale = 1 / 16.0f; - glEnable(GL_RESCALE_NORMAL); - glScalef(-1, -1, 1); - - scale(mob, a); - glTranslatef(0, -24 * _scale - 0.125f / 16.0f, 0); - - - float ws = mob->walkAnimSpeedO + (mob->walkAnimSpeed - mob->walkAnimSpeedO) * a; - float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a); - if (mob->isBaby()) - { - wp *= 3.0f; - } - - if (ws > 1) ws = 1; - - MemSect(31); - bindTexture(mob->customTextureUrl, mob->getTexture()); - MemSect(0); - glEnable(GL_ALPHA_TEST); - - model->prepareMobModel(mob, wp, ws, a); - renderModel(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale); - for (int i = 0; i < MAX_ARMOR_LAYERS; i++) - { - int armorType = prepareArmor(mob, i, a); - if (armorType > 0) - { - armor->prepareMobModel(mob, wp, ws, a); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, true); - if ((armorType & 0xf0) == 16) - { - prepareSecondPassArmor(mob, i, a); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, true); - } - // 4J - added condition here for rendering player as part of the gui. Avoiding rendering the glint here as it involves using its own blending, and for gui rendering - // we are globally blending to be able to offer user configurable gui opacity. Note that I really don't know why GL_BLEND is turned off at the end of the first - // armour layer anyway, or why alpha testing is turned on... but we definitely don't want to be turning blending off during the gui render. - if( !entityRenderDispatcher->isGuiRender ) - { - if ((armorType & 0xf) == 0xf) //MGH - fix for missing enchantment glow - { - float time = mob->tickCount + a; - bindTexture(TN__BLUR__MISC_GLINT); // 4J was "%blur%/misc/glint.png" - glEnable(GL_BLEND); - float br = 0.5f; - glColor4f(br, br, br, 1); - glDepthFunc(GL_EQUAL); - glDepthMask(false); - - for (int j = 0; j < 2; j++) - { - glDisable(GL_LIGHTING); - float brr = 0.76f; - glColor4f(0.5f * brr, 0.25f * brr, 0.8f * brr, 1); - glBlendFunc(GL_SRC_COLOR, GL_ONE); - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - float uo = time * (0.001f + j * 0.003f) * 20; - float ss = 1 / 3.0f; - glScalef(ss, ss, ss); - glRotatef(30 - (j) * 60.0f, 0, 0, 1); - glTranslatef(0, uo, 0); - glMatrixMode(GL_MODELVIEW); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - } - - glColor4f(1, 1, 1, 1); - glMatrixMode(GL_TEXTURE); - glDepthMask(true); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glEnable(GL_LIGHTING); - glDisable(GL_BLEND); - glDepthFunc(GL_LEQUAL); - - } - glDisable(GL_BLEND); - } - glEnable(GL_ALPHA_TEST); - } + float headDiff = Mth::wrapDegrees(headRot - bodyRot); + if (headDiff < -85) headDiff = -85; + if (headDiff >= 85) headDiff = +85; + bodyRot = headRot - headDiff; + if (headDiff * headDiff > 50 * 50) { + bodyRot += headDiff * 0.2f; } + } - glDepthMask(true); + float headRotx = (mob->xRotO + (mob->xRot - mob->xRotO) * a); - additionalRendering(mob, a); - float br = mob->getBrightness(a); - int overlayColor = getOverlayColor(mob, br, a); - glActiveTexture(GL_TEXTURE1); - glDisable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE0); + setupPosition(mob, x, y, z); - if (((overlayColor >> 24) & 0xff) > 0 || mob->hurtTime > 0 || mob->deathTime > 0) - { - glDisable(GL_TEXTURE_2D); - glDisable(GL_ALPHA_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthFunc(GL_EQUAL); + float bob = getBob(mob, a); + setupRotations(mob, bob, bodyRot, a); - // 4J - changed these renders to not use the compiled version of their models, because otherwise the render states set - // about (in particular the depth & alpha test) don't work with our command buffer versions - if (mob->hurtTime > 0 || mob->deathTime > 0) - { - glColor4f(br, 0, 0, 0.4f); - model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - for (int i = 0; i < MAX_ARMOR_LAYERS; i++) - { - if (prepareArmorOverlay(mob, i, a) >= 0) - { - glColor4f(br, 0, 0, 0.4f); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - } - } + float _scale = 1 / 16.0f; + glEnable(GL_RESCALE_NORMAL); + glScalef(-1, -1, 1); + + scale(mob, a); + glTranslatef(0, -24 * _scale - 0.125f / 16.0f, 0); + + float ws = + mob->walkAnimSpeedO + (mob->walkAnimSpeed - mob->walkAnimSpeedO) * a; + float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a); + if (mob->isBaby()) { + wp *= 3.0f; + } + + if (ws > 1) ws = 1; + + MemSect(31); + bindTexture(mob->customTextureUrl, mob->getTexture()); + MemSect(0); + glEnable(GL_ALPHA_TEST); + + model->prepareMobModel(mob, wp, ws, a); + renderModel(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale); + for (int i = 0; i < MAX_ARMOR_LAYERS; i++) { + int armorType = prepareArmor(mob, i, a); + if (armorType > 0) { + armor->prepareMobModel(mob, wp, ws, a); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, + true); + if ((armorType & 0xf0) == 16) { + prepareSecondPassArmor(mob, i, a); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, + _scale, true); } + // 4J - added condition here for rendering player as part of the + // gui. Avoiding rendering the glint here as it involves using its + // own blending, and for gui rendering we are globally blending to + // be able to offer user configurable gui opacity. Note that I + // really don't know why GL_BLEND is turned off at the end of the + // first armour layer anyway, or why alpha testing is turned on... + // but we definitely don't want to be turning blending off during + // the gui render. + if (!entityRenderDispatcher->isGuiRender) { + if ((armorType & 0xf) == + 0xf) // MGH - fix for missing enchantment glow + { + float time = mob->tickCount + a; + bindTexture( + TN__BLUR__MISC_GLINT); // 4J was + // "%blur%/misc/glint.png" + glEnable(GL_BLEND); + float br = 0.5f; + glColor4f(br, br, br, 1); + glDepthFunc(GL_EQUAL); + glDepthMask(false); - if (((overlayColor >> 24) & 0xff) > 0) - { - float r = ((overlayColor >> 16) & 0xff) / 255.0f; - float g = ((overlayColor >> 8) & 0xff) / 255.0f; - float b = ((overlayColor) & 0xff) / 255.0f; - float aa = ((overlayColor >> 24) & 0xff) / 255.0f; - glColor4f(r, g, b, aa); - model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); - for (int i = 0; i < MAX_ARMOR_LAYERS; i++) - { - if (prepareArmorOverlay(mob, i, a) >= 0) - { - glColor4f(r, g, b, aa); - armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, false); + for (int j = 0; j < 2; j++) { + glDisable(GL_LIGHTING); + float brr = 0.76f; + glColor4f(0.5f * brr, 0.25f * brr, 0.8f * brr, 1); + glBlendFunc(GL_SRC_COLOR, GL_ONE); + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + float uo = time * (0.001f + j * 0.003f) * 20; + float ss = 1 / 3.0f; + glScalef(ss, ss, ss); + glRotatef(30 - (j) * 60.0f, 0, 0, 1); + glTranslatef(0, uo, 0); + glMatrixMode(GL_MODELVIEW); + armor->render(mob, wp, ws, bob, headRot - bodyRot, + headRotx, _scale, false); } - } - } - glDepthFunc(GL_LEQUAL); - glDisable(GL_BLEND); + glColor4f(1, 1, 1, 1); + glMatrixMode(GL_TEXTURE); + glDepthMask(true); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glEnable(GL_LIGHTING); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + } + glDisable(GL_BLEND); + } glEnable(GL_ALPHA_TEST); - glEnable(GL_TEXTURE_2D); } - glDisable(GL_RESCALE_NORMAL); -// } -//catch (Exception e) { - // // System.out.println("Failed: " + modelNames[model]); - // e.printStackTrace(); - // } - glActiveTexture(GL_TEXTURE1); - glEnable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE0); + } + + glDepthMask(true); + + additionalRendering(mob, a); + float br = mob->getBrightness(a); + int overlayColor = getOverlayColor(mob, br, a); + glActiveTexture(GL_TEXTURE1); + glDisable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE0); + + if (((overlayColor >> 24) & 0xff) > 0 || mob->hurtTime > 0 || + mob->deathTime > 0) { + glDisable(GL_TEXTURE_2D); + glDisable(GL_ALPHA_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDepthFunc(GL_EQUAL); + + // 4J - changed these renders to not use the compiled version of their + // models, because otherwise the render states set about (in particular + // the depth & alpha test) don't work with our command buffer versions + if (mob->hurtTime > 0 || mob->deathTime > 0) { + glColor4f(br, 0, 0, 0.4f); + model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, + false); + for (int i = 0; i < MAX_ARMOR_LAYERS; i++) { + if (prepareArmorOverlay(mob, i, a) >= 0) { + glColor4f(br, 0, 0, 0.4f); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, + _scale, false); + } + } + } + + if (((overlayColor >> 24) & 0xff) > 0) { + float r = ((overlayColor >> 16) & 0xff) / 255.0f; + float g = ((overlayColor >> 8) & 0xff) / 255.0f; + float b = ((overlayColor) & 0xff) / 255.0f; + float aa = ((overlayColor >> 24) & 0xff) / 255.0f; + glColor4f(r, g, b, aa); + model->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, _scale, + false); + for (int i = 0; i < MAX_ARMOR_LAYERS; i++) { + if (prepareArmorOverlay(mob, i, a) >= 0) { + glColor4f(r, g, b, aa); + armor->render(mob, wp, ws, bob, headRot - bodyRot, headRotx, + _scale, false); + } + } + } + + glDepthFunc(GL_LEQUAL); + glDisable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glEnable(GL_TEXTURE_2D); + } + glDisable(GL_RESCALE_NORMAL); + // } + // catch (Exception e) { + // // System.out.println("Failed: " + modelNames[model]); + // e.printStackTrace(); + // } + glActiveTexture(GL_TEXTURE1); + glEnable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE0); glEnable(GL_CULL_FACE); glPopMatrix(); - MemSect(31); + MemSect(31); renderName(mob, x, y, z); - MemSect(0); + MemSect(0); } -void MobRenderer::renderModel(std::shared_ptr mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale) -{ - std::shared_ptr player = std::dynamic_pointer_cast(Minecraft::GetInstance()->player); +void MobRenderer::renderModel(std::shared_ptr mob, float wp, float ws, + float bob, float headRotMinusBodyRot, + float headRotx, float scale) { + std::shared_ptr player = + std::dynamic_pointer_cast(Minecraft::GetInstance()->player); - bindTexture(mob->customTextureUrl, mob->getTexture()); - if (!mob->isInvisible()) - { - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); - } - else if ( !mob->isInvisibleTo(player) ) - { - glPushMatrix(); + bindTexture(mob->customTextureUrl, mob->getTexture()); + if (!mob->isInvisible()) { + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); + } else if (!mob->isInvisibleTo(player)) { + glPushMatrix(); glColor4f(1, 1, 1, 0.15f); glDepthMask(false); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glAlphaFunc(GL_GREATER, 1.0f / 255.0f); - model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, true); + model->render(mob, wp, ws, bob, headRotMinusBodyRot, headRotx, scale, + true); glDisable(GL_BLEND); glAlphaFunc(GL_GREATER, .1f); glPopMatrix(); glDepthMask(true); - } - else - { - model->setupAnim(wp, ws, bob, headRotMinusBodyRot, headRotx, scale);//, mob); - } + } else { + model->setupAnim(wp, ws, bob, headRotMinusBodyRot, headRotx, + scale); //, mob); + } } -void MobRenderer::setupPosition(std::shared_ptr mob, double x, double y, double z) -{ - glTranslatef((float) x, (float) y, (float) z); +void MobRenderer::setupPosition(std::shared_ptr mob, double x, double y, + double z) { + glTranslatef((float)x, (float)y, (float)z); } -void MobRenderer::setupRotations(std::shared_ptr mob, float bob, float bodyRot, float a) -{ +void MobRenderer::setupRotations(std::shared_ptr mob, float bob, + float bodyRot, float a) { glRotatef(180 - bodyRot, 0, 1, 0); - if (mob->deathTime > 0) - { + if (mob->deathTime > 0) { float fall = (mob->deathTime + a - 1) / 20.0f * 1.6f; fall = (float)sqrt(fall); if (fall > 1) fall = 1; @@ -279,86 +274,71 @@ void MobRenderer::setupRotations(std::shared_ptr mob, float bob, float body } } -float MobRenderer::getAttackAnim(std::shared_ptr mob, float a) -{ - return mob->getAttackAnim(a); +float MobRenderer::getAttackAnim(std::shared_ptr mob, float a) { + return mob->getAttackAnim(a); } -float MobRenderer::getBob(std::shared_ptr mob, float a) -{ - return (mob->tickCount + a); +float MobRenderer::getBob(std::shared_ptr mob, float a) { + return (mob->tickCount + a); } -void MobRenderer::additionalRendering(std::shared_ptr mob, float a) -{ +void MobRenderer::additionalRendering(std::shared_ptr mob, float a) {} + +int MobRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, + float a) { + return prepareArmor(mob, layer, a); } -int MobRenderer::prepareArmorOverlay(std::shared_ptr mob, int layer, float a) -{ - return prepareArmor(mob, layer, a); +int MobRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) { + return -1; } -int MobRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) -{ - return -1; +void MobRenderer::prepareSecondPassArmor(std::shared_ptr mob, int layer, + float a) {} + +float MobRenderer::getFlipDegrees(std::shared_ptr mob) { return 90; } + +int MobRenderer::getOverlayColor(std::shared_ptr mob, float br, float a) { + return 0; } -void MobRenderer::prepareSecondPassArmor(std::shared_ptr mob, int layer, float a) -{ -} +void MobRenderer::scale(std::shared_ptr mob, float a) {} -float MobRenderer::getFlipDegrees(std::shared_ptr mob) -{ - return 90; -} - -int MobRenderer::getOverlayColor(std::shared_ptr mob, float br, float a) -{ - return 0; -} - -void MobRenderer::scale(std::shared_ptr mob, float a) -{ -} - -void MobRenderer::renderName(std::shared_ptr mob, double x, double y, double z) -{ - if (Minecraft::renderDebug()) - { - //renderNameTag(mob, _toString(mob->entityId), x, y, z, 64); +void MobRenderer::renderName(std::shared_ptr mob, double x, double y, + double z) { + if (Minecraft::renderDebug()) { + // renderNameTag(mob, _toString(mob->entityId), x, y, z, 64); } } // 4J Added parameter for color here so that we can colour players names -void MobRenderer::renderNameTag(std::shared_ptr mob, const std::wstring& OriginalName, double x, double y, double z, int maxDist, int color /*= 0xffffffff*/) -{ - - if ( app.GetGameSettings(eGameSetting_DisplayHUD)==0 ) - { - // 4J-PB - turn off gamertag render - return; - } - - if(app.GetGameHostOption(eGameHostOption_Gamertags)==0) - { - // turn off gamertags if the host has set them off - return; - } - - float dist = mob->distanceTo(entityRenderDispatcher->cameraEntity); - - if (dist > maxDist) - { +void MobRenderer::renderNameTag(std::shared_ptr mob, + const std::wstring& OriginalName, double x, + double y, double z, int maxDist, + int color /*= 0xffffffff*/) { + if (app.GetGameSettings(eGameSetting_DisplayHUD) == 0) { + // 4J-PB - turn off gamertag render return; } - Font *font = getFont(); + if (app.GetGameHostOption(eGameHostOption_Gamertags) == 0) { + // turn off gamertags if the host has set them off + return; + } + + float dist = mob->distanceTo(entityRenderDispatcher->cameraEntity); + + if (dist > maxDist) { + return; + } + + Font* font = getFont(); float size = 1.60f; float s = 1 / 60.0f * size; glPushMatrix(); - glTranslatef((float) x + 0, (float) y + 2.3f, (float) z); + glTranslatef((float)x + 0, (float)y + 2.3f, (float)z); glNormal3f(0, 1, 0); glRotatef(-this->entityRenderDispatcher->playerRotY, 0, 1, 0); @@ -367,147 +347,134 @@ void MobRenderer::renderNameTag(std::shared_ptr mob, const std::wstring& Or glScalef(-s, -s, s); glDisable(GL_LIGHTING); - // 4J Stu - If it's beyond readable distance, then just render a coloured box - int readableDist = PLAYER_NAME_READABLE_FULLSCREEN; - if( !RenderManager.IsHiDef() ) - { - readableDist = PLAYER_NAME_READABLE_DISTANCE_SD; - } - else if ( app.GetLocalPlayerCount() > 2 ) - { - readableDist = PLAYER_NAME_READABLE_DISTANCE_SPLITSCREEN; - } + // 4J Stu - If it's beyond readable distance, then just render a coloured + // box + int readableDist = PLAYER_NAME_READABLE_FULLSCREEN; + if (!RenderManager.IsHiDef()) { + readableDist = PLAYER_NAME_READABLE_DISTANCE_SD; + } else if (app.GetLocalPlayerCount() > 2) { + readableDist = PLAYER_NAME_READABLE_DISTANCE_SPLITSCREEN; + } - float textOpacity = 1.0f; - if( dist >= readableDist ) - { - int diff = dist - readableDist; + float textOpacity = 1.0f; + if (dist >= readableDist) { + int diff = dist - readableDist; - textOpacity /= (diff/2); + textOpacity /= (diff / 2); - if( diff > readableDist ) textOpacity = 0.0f; - } + if (diff > readableDist) textOpacity = 0.0f; + } - if( textOpacity < 0.0f ) textOpacity = 0.0f; - if( textOpacity > 1.0f ) textOpacity = 1.0f; - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Tesselator *t = Tesselator::getInstance(); + if (textOpacity < 0.0f) textOpacity = 0.0f; + if (textOpacity > 1.0f) textOpacity = 1.0f; - int offs = 0; - std::shared_ptr player = std::dynamic_pointer_cast(mob); - if (player != NULL && app.isXuidDeadmau5( player->getXuid() ) ) offs = -10; + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Tesselator* t = Tesselator::getInstance(); - std::wstring playerName; - WCHAR wchName[2]; + int offs = 0; + std::shared_ptr player = std::dynamic_pointer_cast(mob); + if (player != NULL && app.isXuidDeadmau5(player->getXuid())) offs = -10; + + std::wstring playerName; + WCHAR wchName[2]; #if defined(__PS3__) || defined(__ORBIS__) - // Check we have all the font characters for this player name - switch(player->GetPlayerNameValidState()) - { - case Player::ePlayerNameValid_NotSet: - if(font->AllCharactersValid(OriginalName)) - { - playerName=OriginalName; - player->SetPlayerNameValidState(true); - } - else - { - memset(wchName,0,sizeof(WCHAR)*2); - swprintf(wchName, 2, L"%d",player->getPlayerIndex()+1); - playerName=wchName; - player->SetPlayerNameValidState(false); - } - break; - case Player::ePlayerNameValid_True: - playerName=OriginalName; - break; - case Player::ePlayerNameValid_False: - memset(wchName,0,sizeof(WCHAR)*2); - swprintf(wchName, 2, L"%d",player->getPlayerIndex()+1); - playerName=wchName; - break; - } + // Check we have all the font characters for this player name + switch (player->GetPlayerNameValidState()) { + case Player::ePlayerNameValid_NotSet: + if (font->AllCharactersValid(OriginalName)) { + playerName = OriginalName; + player->SetPlayerNameValidState(true); + } else { + memset(wchName, 0, sizeof(WCHAR) * 2); + swprintf(wchName, 2, L"%d", player->getPlayerIndex() + 1); + playerName = wchName; + player->SetPlayerNameValidState(false); + } + break; + case Player::ePlayerNameValid_True: + playerName = OriginalName; + break; + case Player::ePlayerNameValid_False: + memset(wchName, 0, sizeof(WCHAR) * 2); + swprintf(wchName, 2, L"%d", player->getPlayerIndex() + 1); + playerName = wchName; + break; + } #else - playerName=OriginalName; + playerName = OriginalName; #endif - if( textOpacity > 0.0f ) - { - glColor4f(1.0f,1.0f,1.0f,textOpacity); + if (textOpacity > 0.0f) { + glColor4f(1.0f, 1.0f, 1.0f, textOpacity); - glDepthMask(false); - glDisable(GL_DEPTH_TEST); + glDepthMask(false); + glDisable(GL_DEPTH_TEST); - glDisable(GL_TEXTURE_2D); + glDisable(GL_TEXTURE_2D); - t->begin(); - int w = font->width(playerName) / 2; + t->begin(); + int w = font->width(playerName) / 2; - if( textOpacity < 1.0f ) - { - t->color(color, 255 * textOpacity); - } - else - { - t->color(0.0f, 0.0f, 0.0f, 0.25f); - } - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); - t->end(); - - glEnable(GL_DEPTH_TEST); - glDepthMask(true); - glDepthFunc(GL_ALWAYS); - glLineWidth(2.0f); - t->begin(GL_LINE_STRIP); - t->color(color, 255 * textOpacity); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs + 1), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->end(); - glDepthFunc(GL_LEQUAL); - glDepthMask(false); - glDisable(GL_DEPTH_TEST); + if (textOpacity < 1.0f) { + t->color(color, 255 * textOpacity); + } else { + t->color(0.0f, 0.0f, 0.0f, 0.25f); + } + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1 + offs), (float)(0)); + t->end(); - glEnable(GL_TEXTURE_2D); - font->draw(playerName, -font->width(playerName) / 2, offs, 0x20ffffff); - glEnable(GL_DEPTH_TEST); - - glDepthMask(true); - } + glEnable(GL_DEPTH_TEST); + glDepthMask(true); + glDepthFunc(GL_ALWAYS); + glLineWidth(2.0f); + t->begin(GL_LINE_STRIP); + t->color(color, 255 * textOpacity); + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8 + offs + 1), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->end(); + glDepthFunc(GL_LEQUAL); + glDepthMask(false); + glDisable(GL_DEPTH_TEST); + + glEnable(GL_TEXTURE_2D); + font->draw(playerName, -font->width(playerName) / 2, offs, 0x20ffffff); + glEnable(GL_DEPTH_TEST); + + glDepthMask(true); + } + + if (textOpacity < 1.0f) { + glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + glDisable(GL_TEXTURE_2D); + glDepthFunc(GL_ALWAYS); + t->begin(); + int w = font->width(playerName) / 2; + t->color(color, 255); + t->vertex((float)(-w - 1), (float)(-1 + offs), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8 + offs), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8 + offs), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1 + offs), (float)(0)); + t->end(); + glDepthFunc(GL_LEQUAL); + glEnable(GL_TEXTURE_2D); - if( textOpacity < 1.0f ) - { - glColor4f(1.0f,1.0f,1.0f,1.0f); - glDisable(GL_TEXTURE_2D); - glDepthFunc(GL_ALWAYS); - t->begin(); - int w = font->width(playerName) / 2; - t->color(color, 255); - t->vertex((float)(-w - 1), (float)( -1 + offs), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8 + offs), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8 + offs), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1 + offs), (float)( 0)); - t->end(); - glDepthFunc(GL_LEQUAL); - glEnable(GL_TEXTURE_2D); - glTranslatef(0.0f, 0.0f, -0.04f); - } + } + + if (textOpacity > 0.0f) { + int textColor = (((int)(textOpacity * 255) << 24) | 0xffffff); + font->draw(playerName, -font->width(playerName) / 2, offs, textColor); + } - if( textOpacity > 0.0f ) - { - int textColor = ( ( (int)(textOpacity*255) << 24 ) | 0xffffff ); - font->draw(playerName, -font->width(playerName) / 2, offs, textColor); - } - glEnable(GL_LIGHTING); glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h index 7cefa63e7..3f432ccd6 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MobRenderer.h @@ -2,45 +2,57 @@ #include "EntityRenderer.h" class Mob; - #define PLAYER_NAME_READABLE_FULLSCREEN 16 #define PLAYER_NAME_READABLE_DISTANCE_SPLITSCREEN 8 #define PLAYER_NAME_READABLE_DISTANCE_SD 8 -// 4J - this used to be a generic : public class MobRenderer extends EntityRenderer -class MobRenderer : public EntityRenderer -{ +// 4J - this used to be a generic : public class MobRenderer +// extends EntityRenderer +class MobRenderer : public EntityRenderer { private: - static const int MAX_ARMOR_LAYERS = 4; + static const int MAX_ARMOR_LAYERS = 4; protected: - Model *model; - Model *armor; + Model* model; + Model* armor; public: - MobRenderer(Model *model, float shadow); - virtual void setArmor(Model *armor); + MobRenderer(Model* model, float shadow); + virtual void setArmor(Model* armor); + private: - float rotlerp(float from, float to, float a); + float rotlerp(float from, float to, float a); + public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); + protected: - virtual void renderModel(std::shared_ptr mob, float wp, float ws, float bob, float headRotMinusBodyRot, float headRotx, float scale); - virtual void setupPosition(std::shared_ptr mob, double x, double y, double z); - virtual void setupRotations(std::shared_ptr mob, float bob, float bodyRot, float a); + virtual void renderModel(std::shared_ptr mob, float wp, float ws, + float bob, float headRotMinusBodyRot, + float headRotx, float scale); + virtual void setupPosition(std::shared_ptr mob, double x, double y, + double z); + virtual void setupRotations(std::shared_ptr mob, float bob, + float bodyRot, float a); virtual float getAttackAnim(std::shared_ptr mob, float a); virtual float getBob(std::shared_ptr mob, float a); virtual void additionalRendering(std::shared_ptr mob, float a); - virtual int prepareArmorOverlay(std::shared_ptr mob, int layer, float a); + virtual int prepareArmorOverlay(std::shared_ptr mob, int layer, + float a); virtual int prepareArmor(std::shared_ptr mob, int layer, float a); - virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, float a); + virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, + float a); virtual float getFlipDegrees(std::shared_ptr mob); virtual int getOverlayColor(std::shared_ptr mob, float br, float a); virtual void scale(std::shared_ptr mob, float a); - virtual void renderName(std::shared_ptr mob, double x, double y, double z); - virtual void renderNameTag(std::shared_ptr mob, const std::wstring& name, double x, double y, double z, int maxDist, int color = 0xff000000); + virtual void renderName(std::shared_ptr mob, double x, double y, + double z); + virtual void renderNameTag(std::shared_ptr mob, + const std::wstring& name, double x, double y, + double z, int maxDist, int color = 0xff000000); public: - // 4J Added - virtual Model *getModel() { return model; } + // 4J Added + virtual Model* getModel() { return model; } }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp index aa82227dd..9cad4a1eb 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.cpp @@ -5,21 +5,25 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.entity.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.h" -void MobSpawnerRenderer::render(std::shared_ptr _spawner, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr spawner = std::dynamic_pointer_cast(_spawner); +void MobSpawnerRenderer::render(std::shared_ptr _spawner, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr spawner = + std::dynamic_pointer_cast(_spawner); - glPushMatrix(); - glTranslatef((float) x + 0.5f, (float) y, (float) z + 0.5f); + glPushMatrix(); + glTranslatef((float)x + 0.5f, (float)y, (float)z + 0.5f); std::shared_ptr e = spawner->getDisplayEntity(); - if (e != NULL) - { + if (e != NULL) { e->setLevel(spawner->level); float s = 7 / 16.0f; glTranslatef(0, 0.4f, 0); - glRotatef((float) (spawner->oSpin + (spawner->spin - spawner->oSpin) * a) * 10, 0, 1, 0); + glRotatef( + (float)(spawner->oSpin + (spawner->spin - spawner->oSpin) * a) * 10, + 0, 1, 0); glRotatef(-30, 1, 0, 0); glTranslatef(0, -0.4f, 0); glScalef(s, s, s); diff --git a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h index 1b6b6109e..b66593105 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MobSpawnerRenderer.h @@ -1,11 +1,13 @@ #pragma once #include "TileEntityRenderer.h" - -class MobSpawnerRenderer : public TileEntityRenderer -{ +class MobSpawnerRenderer : public TileEntityRenderer { private: - std::unordered_map > models; + std::unordered_map > models; + public: - virtual void render(std::shared_ptr _spawner, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + virtual void render(std::shared_ptr _spawner, double x, + double y, double z, float a, bool setColor, + float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp index a1efc1cc9..50ea811e6 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.cpp @@ -5,46 +5,49 @@ #include "../Models/ModelPart.h" #include "MushroomCowRenderer.h" -MushroomCowRenderer::MushroomCowRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ +MushroomCowRenderer::MushroomCowRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void MushroomCowRenderer::render(std::shared_ptr _mob, double x, + double y, double z, float rot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type MushroomCow rather than std::shared_ptr we have here - do + // some casting around instead + // std::shared_ptr mob = + // std::dynamic_pointer_cast(_mob); + + // 4J Stu - No need to do the cast, just pass through as-is + MobRenderer::render(_mob, x, y, z, rot, a); } -void MushroomCowRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type MushroomCow rather than std::shared_ptr we have here - - // do some casting around instead - //std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void MushroomCowRenderer::additionalRendering(std::shared_ptr _mob, + float a) { + // 4J - original version used generics and thus had an input parameter of + // type MushroomCow rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::additionalRendering(mob, a); + if (mob->isBaby()) return; + bindTexture(TN_TERRAIN); // 4J was "/terrain.png" + glEnable(GL_CULL_FACE); + glPushMatrix(); + glScalef(1, -1, 1); + glTranslatef(0.2f, 0.4f, 0.5f); + glRotatef(42, 0, 1, 0); + tileRenderer->renderTile(Tile::mushroom2, 0, 1); + glTranslatef(0.1f, 0, -0.6f); + glRotatef(42, 0, 1, 0); + tileRenderer->renderTile(Tile::mushroom2, 0, 1); + glPopMatrix(); - // 4J Stu - No need to do the cast, just pass through as-is - MobRenderer::render(_mob, x, y, z, rot, a); -} + glPushMatrix(); + ((QuadrupedModel*)model)->head->translateTo(1 / 16.0f); + glScalef(1, -1, 1); + glTranslatef(0, 0.75f, -0.2f); + glRotatef(12, 0, 1, 0); + tileRenderer->renderTile(Tile::mushroom2, 0, 1); + glPopMatrix(); -void MushroomCowRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type MushroomCow rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - if (mob->isBaby()) return; - bindTexture(TN_TERRAIN); // 4J was "/terrain.png" - glEnable(GL_CULL_FACE); - glPushMatrix(); - glScalef(1, -1, 1); - glTranslatef(0.2f, 0.4f, 0.5f); - glRotatef(42, 0, 1, 0); - tileRenderer->renderTile(Tile::mushroom2, 0, 1); - glTranslatef(0.1f, 0, -0.6f); - glRotatef(42, 0, 1, 0); - tileRenderer->renderTile(Tile::mushroom2, 0, 1); - glPopMatrix(); - - glPushMatrix(); - ((QuadrupedModel *) model)->head->translateTo(1 / 16.0f); - glScalef(1, -1, 1); - glTranslatef(0, 0.75f, -0.2f); - glRotatef(12, 0, 1, 0); - tileRenderer->renderTile(Tile::mushroom2, 0, 1); - glPopMatrix(); - - glDisable(GL_CULL_FACE); + glDisable(GL_CULL_FACE); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h index 8d01ea818..3631d5456 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/MushroomCowRenderer.h @@ -2,13 +2,13 @@ #include "MobRenderer.h" -class MushroomCowRenderer : public MobRenderer -{ +class MushroomCowRenderer : public MobRenderer { public: - MushroomCowRenderer(Model *model, float shadow); + MushroomCowRenderer(Model* model, float shadow); - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); protected: - virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp index 8b36de448..385caed40 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.cpp @@ -2,23 +2,21 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" #include "OcelotRenderer.h" -OzelotRenderer::OzelotRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ +OzelotRenderer::OzelotRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void OzelotRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } -void OzelotRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); -} - -void OzelotRenderer::scale(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::scale(mob, a); - if (mob->isTame()) - { - glScalef(.8f, .8f, .8f); - } +void OzelotRenderer::scale(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + MobRenderer::scale(mob, a); + if (mob->isTame()) { + glScalef(.8f, .8f, .8f); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h index a9fc1223b..e262f6a2d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/OcelotRenderer.h @@ -2,13 +2,13 @@ #include "MobRenderer.h" -class OzelotRenderer : public MobRenderer -{ +class OzelotRenderer : public MobRenderer { public: - OzelotRenderer(Model *model, float shadow); + OzelotRenderer(Model* model, float shadow); - void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr _mob, double x, double y, double z, + float rot, float a); protected: - void scale(std::shared_ptr _mob, float a); + void scale(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp index 4e948f5d1..04870f3b9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.cpp @@ -6,25 +6,24 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Util/Mth.h" -PaintingRenderer::PaintingRenderer() -{ - random = new Random(); -} +PaintingRenderer::PaintingRenderer() { random = new Random(); } + +void PaintingRenderer::render(std::shared_ptr _painting, double x, + double y, double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr painting = + std::dynamic_pointer_cast(_painting); -void PaintingRenderer::render(std::shared_ptr _painting, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr painting = std::dynamic_pointer_cast(_painting); - random->setSeed(187); glPushMatrix(); glTranslatef((float)x, (float)y, (float)z); glRotatef(rot, 0, 1, 0); glEnable(GL_RESCALE_NORMAL); - bindTexture(TN_ART_KZ); // 4J was L"/art/kz.png" + bindTexture(TN_ART_KZ); // 4J was L"/art/kz.png" - Painting::Motive *motive = painting->motive; + Painting::Motive* motive = painting->motive; float s = 1 / 16.0f; glScalef(s, s, s); @@ -33,8 +32,8 @@ void PaintingRenderer::render(std::shared_ptr _painting, double x, doubl glPopMatrix(); } -void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, int h, int uo, int vo) -{ +void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, + int h, int uo, int vo) { float xx0 = -w / 2.0f; float yy0 = -h / 2.0f; @@ -42,8 +41,7 @@ void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, float z1 = +0.5f; for (int xs = 0; xs < w / 16; xs++) - for (int ys = 0; ys < h / 16; ys++) - { + for (int ys = 0; ys < h / 16; ys++) { float x0 = xx0 + (xs + 1) * 16; float x1 = xx0 + (xs) * 16; float y0 = yy0 + (ys + 1) * 16; @@ -71,57 +69,80 @@ void PaintingRenderer::renderPainting(std::shared_ptr painting, int w, float sv0 = (0) / 256.0f; float sv1 = (0 + 16) / 256.0f; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); t->normal(0, 0, -1); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( fu1), (float)( fv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( fu0), (float)( fv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( fu0), (float)( fv1)); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( fu1), (float)( fv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(fu1), + (float)(fv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(fu0), + (float)(fv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(fu0), + (float)(fv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(fu1), + (float)(fv1)); t->normal(0, 0, 1); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( bu0), (float)( bv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( bu1), (float)( bv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z1), (float)( bu1), (float)( bv1)); - t->vertexUV((float)(x0), (float)( y1), (float)( z1), (float)( bu0), (float)( bv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(bu0), + (float)(bv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(bu1), + (float)(bv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(bu1), + (float)(bv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(bu0), + (float)(bv1)); t->normal(0, 1, 0); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( uu0), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( uu1), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( uu1), (float)( uv1)); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( uu0), (float)( uv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(uu0), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(uu1), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(uu1), + (float)(uv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(uu0), + (float)(uv1)); t->normal(0, -1, 0); - t->vertexUV((float)(x0), (float)( y1), (float)( z1), (float)( uu0), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z1), (float)( uu1), (float)( uv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( uu1), (float)( uv1)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( uu0), (float)( uv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(uu0), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(uu1), + (float)(uv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(uu1), + (float)(uv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(uu0), + (float)(uv1)); t->normal(-1, 0, 0); - t->vertexUV((float)(x0), (float)( y0), (float)( z1), (float)( su1), (float)( sv0)); - t->vertexUV((float)(x0), (float)( y1), (float)( z1), (float)( su1), (float)( sv1)); - t->vertexUV((float)(x0), (float)( y1), (float)( z0), (float)( su0), (float)( sv1)); - t->vertexUV((float)(x0), (float)( y0), (float)( z0), (float)( su0), (float)( sv0)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(su1), + (float)(sv0)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(su1), + (float)(sv1)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(su0), + (float)(sv1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(su0), + (float)(sv0)); t->normal(1, 0, 0); - t->vertexUV((float)(x1), (float)( y0), (float)( z0), (float)( su1), (float)( sv0)); - t->vertexUV((float)(x1), (float)( y1), (float)( z0), (float)( su1), (float)( sv1)); - t->vertexUV((float)(x1), (float)( y1), (float)( z1), (float)( su0), (float)( sv1)); - t->vertexUV((float)(x1), (float)( y0), (float)( z1), (float)( su0), (float)( sv0)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(su1), + (float)(sv0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(su1), + (float)(sv1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(su0), + (float)(sv1)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(su0), + (float)(sv0)); t->end(); } - } -void PaintingRenderer::setBrightness(std::shared_ptr painting, float ss, float ya) -{ +void PaintingRenderer::setBrightness(std::shared_ptr painting, + float ss, float ya) { int x = Mth::floor(painting->x); - int y = Mth::floor(painting->y + ya/16.0f); + int y = Mth::floor(painting->y + ya / 16.0f); int z = Mth::floor(painting->z); - if (painting->dir == 0) x = Mth::floor(painting->x + ss/16.0f); - if (painting->dir == 1) z = Mth::floor(painting->z - ss/16.0f); - if (painting->dir == 2) x = Mth::floor(painting->x - ss/16.0f); - if (painting->dir == 3) z = Mth::floor(painting->z + ss/16.0f); + if (painting->dir == 0) x = Mth::floor(painting->x + ss / 16.0f); + if (painting->dir == 1) z = Mth::floor(painting->z - ss / 16.0f); + if (painting->dir == 2) x = Mth::floor(painting->x - ss / 16.0f); + if (painting->dir == 3) z = Mth::floor(painting->z + ss / 16.0f); int col = this->entityRenderDispatcher->level->getLightColor(x, y, z, 0); int u = col % 65536; diff --git a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h index f940c1694..43c65e7ef 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PaintingRenderer.h @@ -4,16 +4,17 @@ class Painting; class Random; -class PaintingRenderer : public EntityRenderer -{ +class PaintingRenderer : public EntityRenderer { private: - Random *random; + Random* random; public: - PaintingRenderer(); // 4J -added - virtual void render(std::shared_ptr _painting, double x, double y, double z, float rot, float a); + PaintingRenderer(); // 4J -added + virtual void render(std::shared_ptr _painting, double x, double y, + double z, float rot, float a); private: - void renderPainting(std::shared_ptr painting, int w, int h, int uo, int vo); + void renderPainting(std::shared_ptr painting, int w, int h, + int uo, int vo); void setBrightness(std::shared_ptr painting, float ss, float ya); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp index 047877d04..648b4b5fd 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.cpp @@ -2,23 +2,23 @@ #include "PigRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -PigRenderer::PigRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model,shadow) -{ - setArmor(armor); +PigRenderer::PigRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + setArmor(armor); } -int PigRenderer::prepareArmor(std::shared_ptr _pig, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr pig = std::dynamic_pointer_cast(_pig); +int PigRenderer::prepareArmor(std::shared_ptr _pig, int layer, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr pig = std::dynamic_pointer_cast(_pig); - MemSect(31); - bindTexture(TN_MOB_SADDLE); // 4J was L"/mob/saddle.png" - MemSect(0); + MemSect(31); + bindTexture(TN_MOB_SADDLE); // 4J was L"/mob/saddle.png" + MemSect(0); return (layer == 0 && pig->hasSaddle()) ? 1 : -1; } -void PigRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); -} \ No newline at end of file +void PigRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); +} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h index 9dc3edfac..a209366f5 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PigRenderer.h @@ -1,13 +1,14 @@ #pragma once #include "MobRenderer.h" -class PigRenderer : public MobRenderer -{ +class PigRenderer : public MobRenderer { public: - PigRenderer(Model *model, Model *armor, float shadow); + PigRenderer(Model* model, Model* armor, float shadow); + protected: - virtual int prepareArmor(std::shared_ptr _pig, int layer, float a); + virtual int prepareArmor(std::shared_ptr _pig, int layer, float a); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp index a50dfe886..40c68bfaf 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.cpp @@ -7,24 +7,31 @@ #include "../../../Minecraft.World/Blocks/TileEntities/PistonPieceTileEntity.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -PistonPieceRenderer::PistonPieceRenderer() -{ - tileRenderer = NULL; -} +PistonPieceRenderer::PistonPieceRenderer() { tileRenderer = NULL; } -void PistonPieceRenderer::render(std::shared_ptr _entity, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr entity = std::dynamic_pointer_cast(_entity); +void PistonPieceRenderer::render(std::shared_ptr _entity, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr entity = + std::dynamic_pointer_cast(_entity); - Tile *tile = Tile::tiles[entity->getId()]; - if (tile != NULL && entity->getProgress(a) <= 1) // 4J - changed condition from < to <= as our chunk update is async to main thread and so we can have to render these with progress of 1 - { - Tesselator *t = Tesselator::getInstance(); + Tile* tile = Tile::tiles[entity->getId()]; + if (tile != NULL && + entity->getProgress(a) <= + 1) // 4J - changed condition from < to <= as our chunk update is + // async to main thread and so we can have to render these with + // progress of 1 + { + Tesselator* t = Tesselator::getInstance(); bindTexture(TN_TERRAIN); Lighting::turnOff(); - glColor4f(1, 1, 1, 1); // 4J added - this wouldn't be needed in real opengl as the block render has vertex colours and so this isn't use, but our pretend gl always modulates with this + glColor4f(1, 1, 1, + 1); // 4J added - this wouldn't be needed in real opengl as + // the block render has vertex colours and so this isn't + // use, but our pretend gl always modulates with this glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); @@ -32,37 +39,41 @@ void PistonPieceRenderer::render(std::shared_ptr _entity, double x, t->begin(); - t->offset((float) x - entity->x + entity->getXOff(a), (float) y - entity->y + entity->getYOff(a), (float) z - entity->z + entity->getZOff(a)); + t->offset((float)x - entity->x + entity->getXOff(a), + (float)y - entity->y + entity->getYOff(a), + (float)z - entity->z + entity->getZOff(a)); t->color(1, 1, 1); - if (tile == Tile::pistonExtension && entity->getProgress(a) < 0.5f) - { + if (tile == Tile::pistonExtension && entity->getProgress(a) < 0.5f) { // extending arms may appear through the base block - tileRenderer->tesselatePistonArmNoCulling(tile, entity->x, entity->y, entity->z, false, entity->getData()); - } - else if (entity->isSourcePiston() && !entity->isExtending()) - { + tileRenderer->tesselatePistonArmNoCulling(tile, entity->x, + entity->y, entity->z, + false, entity->getData()); + } else if (entity->isSourcePiston() && !entity->isExtending()) { // special case for withdrawing the arm back into the base - Tile::pistonExtension->setOverrideTopTexture(((PistonBaseTile *) tile)->getPlatformTexture()); - tileRenderer->tesselatePistonArmNoCulling(Tile::pistonExtension, entity->x, entity->y, entity->z, entity->getProgress(a) < 0.5f, entity->getData()); + Tile::pistonExtension->setOverrideTopTexture( + ((PistonBaseTile*)tile)->getPlatformTexture()); + tileRenderer->tesselatePistonArmNoCulling( + Tile::pistonExtension, entity->x, entity->y, entity->z, + entity->getProgress(a) < 0.5f, entity->getData()); Tile::pistonExtension->clearOverrideTopTexture(); - t->offset((float) x - entity->x, (float) y - entity->y, (float) z - entity->z); - tileRenderer->tesselatePistonBaseForceExtended(tile, entity->x, entity->y, entity->z, entity->getData()); - } - else - { - tileRenderer->tesselateInWorldNoCulling(tile, entity->x, entity->y, entity->z, entity->getData(), entity); + t->offset((float)x - entity->x, (float)y - entity->y, + (float)z - entity->z); + tileRenderer->tesselatePistonBaseForceExtended( + tile, entity->x, entity->y, entity->z, entity->getData()); + } else { + tileRenderer->tesselateInWorldNoCulling(tile, entity->x, entity->y, + entity->z, + entity->getData(), entity); } t->offset(0, 0, 0); t->end(); Lighting::turnOn(); } +} -} - -void PistonPieceRenderer::onNewLevel(Level *level) -{ - delete tileRenderer; - tileRenderer = new TileRenderer(level); +void PistonPieceRenderer::onNewLevel(Level* level) { + delete tileRenderer; + tileRenderer = new TileRenderer(level); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h index 90061b109..fbeeba4ae 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PistonPieceRenderer.h @@ -3,13 +3,14 @@ class PistonPieceEntity; class TileRenderer; -class PistonPieceRenderer : public TileEntityRenderer -{ +class PistonPieceRenderer : public TileEntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - PistonPieceRenderer(); - virtual void render(std::shared_ptr _entity, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param - virtual void onNewLevel(Level *level); + PistonPieceRenderer(); + virtual void render(std::shared_ptr _entity, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param + virtual void onNewLevel(Level* level); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp index bc0bbb6ab..88c8b3c07 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.cpp @@ -13,61 +13,60 @@ #include "../../../Minecraft.World/Headers/net.minecraft.h" #include "../../../Minecraft.World/Util/StringHelpers.h" -const unsigned int PlayerRenderer::s_nametagColors[MINECRAFT_NET_MAX_PLAYERS] = -{ - 0xff000000, // WHITE (represents the "white" player, but using black as the colour) - 0xff33cc33, // GREEN - 0xffcc3333, // RED - 0xff3333cc, // BLUE -#ifndef __PSVITA__ // only 4 player on Vita - 0xffcc33cc, // PINK - 0xffcc6633, // ORANGE - 0xffcccc33, // YELLOW - 0xff33dccc, // TURQUOISE +const unsigned int PlayerRenderer::s_nametagColors[MINECRAFT_NET_MAX_PLAYERS] = + { + 0xff000000, // WHITE (represents the "white" player, but using black as + // the colour) + 0xff33cc33, // GREEN + 0xffcc3333, // RED + 0xff3333cc, // BLUE +#ifndef __PSVITA__ // only 4 player on Vita + 0xffcc33cc, // PINK + 0xffcc6633, // ORANGE + 0xffcccc33, // YELLOW + 0xff33dccc, // TURQUOISE #endif }; -const std::wstring PlayerRenderer::MATERIAL_NAMES[5] = { L"cloth", L"chain", L"iron", L"diamond", L"gold" }; +const std::wstring PlayerRenderer::MATERIAL_NAMES[5] = { + L"cloth", L"chain", L"iron", L"diamond", L"gold"}; -PlayerRenderer::PlayerRenderer() : MobRenderer( new HumanoidModel(0), 0.5f ) -{ - humanoidModel = (HumanoidModel *) model; +PlayerRenderer::PlayerRenderer() : MobRenderer(new HumanoidModel(0), 0.5f) { + humanoidModel = (HumanoidModel*)model; armorParts1 = new HumanoidModel(1.0f); armorParts2 = new HumanoidModel(0.5f); } -unsigned int PlayerRenderer::getNametagColour(int index) -{ - if( index >= 0 && index < MINECRAFT_NET_MAX_PLAYERS) - { - return s_nametagColors[index]; - } - return 0xFF000000; +unsigned int PlayerRenderer::getNametagColour(int index) { + if (index >= 0 && index < MINECRAFT_NET_MAX_PLAYERS) { + return s_nametagColors[index]; + } + return 0xFF000000; } -int PlayerRenderer::prepareArmor(std::shared_ptr _player, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr player = std::dynamic_pointer_cast(_player); +int PlayerRenderer::prepareArmor(std::shared_ptr _player, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr player = std::dynamic_pointer_cast(_player); - // 4J-PB - need to disable rendering armour for some special skins (Daleks) - unsigned int uiAnimOverrideBitmask=player->getAnimOverrideBitmask(); - if(uiAnimOverrideBitmask&(1<getAnimOverrideBitmask(); + if (uiAnimOverrideBitmask & (1 << HumanoidModel::eAnim_DontRenderArmour)) { + return -1; + } - std::shared_ptr itemInstance = player->inventory->getArmor(3 - layer); - if (itemInstance != NULL) - { - Item *item = itemInstance->getItem(); - if (dynamic_cast(item)) - { - ArmorItem *armorItem = dynamic_cast(item); - bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + L"_" + _toString(layer == 2 ? 2 : 1) + L".png"); + std::shared_ptr itemInstance = + player->inventory->getArmor(3 - layer); + if (itemInstance != NULL) { + Item* item = itemInstance->getItem(); + if (dynamic_cast(item)) { + ArmorItem* armorItem = dynamic_cast(item); + bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + + L"_" + _toString(layer == 2 ? 2 : 1) + L".png"); - HumanoidModel *armor = layer == 2 ? armorParts2 : armorParts1; + HumanoidModel* armor = layer == 2 ? armorParts2 : armorParts1; armor->head->visible = layer == 0; armor->hair->visible = layer == 0; @@ -78,197 +77,196 @@ int PlayerRenderer::prepareArmor(std::shared_ptr _player, int layer, float armor->leg1->visible = layer == 2 || layer == 3; setArmor(armor); - if (armor != NULL) armor->attackTime = model->attackTime; - if (armor != NULL) armor->riding = model->riding; - if (armor != NULL) armor->young = model->young; + if (armor != NULL) armor->attackTime = model->attackTime; + if (armor != NULL) armor->riding = model->riding; + if (armor != NULL) armor->young = model->young; - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : player->getBrightness(a); - if (armorItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) - { - int color = armorItem->getColor(itemInstance); - float red = (float) ((color >> 16) & 0xFF) / 0xFF; - float green = (float) ((color >> 8) & 0xFF) / 0xFF; - float blue = (float) (color & 0xFF) / 0xFF; - glColor3f(brightness * red, brightness * green, brightness * blue); + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : player->getBrightness(a); + if (armorItem->getMaterial() == ArmorItem::ArmorMaterial::CLOTH) { + int color = armorItem->getColor(itemInstance); + float red = (float)((color >> 16) & 0xFF) / 0xFF; + float green = (float)((color >> 8) & 0xFF) / 0xFF; + float blue = (float)(color & 0xFF) / 0xFF; + glColor3f(brightness * red, brightness * green, + brightness * blue); - if (itemInstance->isEnchanted()) return 0x1f; - return 0x10; - } - else - { - glColor3f(brightness, brightness, brightness); - } + if (itemInstance->isEnchanted()) return 0x1f; + return 0x10; + } else { + glColor3f(brightness, brightness, brightness); + } - if (itemInstance->isEnchanted()) return 0xf; + if (itemInstance->isEnchanted()) return 0xf; return 1; } } return -1; - } -void PlayerRenderer::prepareSecondPassArmor(std::shared_ptr _player, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr player = std::dynamic_pointer_cast(_player); - std::shared_ptr itemInstance = player->inventory->getArmor(3 - layer); - if (itemInstance != NULL) - { - Item *item = itemInstance->getItem(); - if (dynamic_cast(item)) - { - ArmorItem *armorItem = dynamic_cast(item); - bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + L"_" + _toString(layer == 2 ? 2 : 1) + L"_b.png"); +void PlayerRenderer::prepareSecondPassArmor(std::shared_ptr _player, + int layer, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr player = std::dynamic_pointer_cast(_player); + std::shared_ptr itemInstance = + player->inventory->getArmor(3 - layer); + if (itemInstance != NULL) { + Item* item = itemInstance->getItem(); + if (dynamic_cast(item)) { + ArmorItem* armorItem = dynamic_cast(item); + bindTexture(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex] + + L"_" + _toString(layer == 2 ? 2 : 1) + L"_b.png"); - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : player->getBrightness(a); - glColor3f(brightness, brightness, brightness); - } - } + float brightness = SharedConstants::TEXTURE_LIGHTING + ? 1 + : player->getBrightness(a); + glColor3f(brightness, brightness, brightness); + } + } } -void PlayerRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if(mob->hasInvisiblePrivilege()) return; + if (mob->hasInvisiblePrivilege()) return; std::shared_ptr item = mob->inventory->getSelected(); - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = item != NULL ? 1 : 0; - if (item != NULL) - { - if (mob->getUseItemDuration() > 0) - { - UseAnim anim = item->getUseAnimation(); - if (anim == UseAnim_block) - { - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = 3; - } - else if (anim == UseAnim_bow) - { - armorParts1->bowAndArrow = armorParts2->bowAndArrow = humanoidModel->bowAndArrow = true; - } - } - } - // 4J added, for 3rd person view of eating - if( item != NULL && mob->getUseItemDuration() > 0 && item->getUseAnimation() == UseAnim_eat ) - { - // These factors are largely lifted from ItemInHandRenderer to try and keep the 3rd person eating animation as similar as possible + armorParts1->holdingRightHand = armorParts2->holdingRightHand = + humanoidModel->holdingRightHand = item != NULL ? 1 : 0; + if (item != NULL) { + if (mob->getUseItemDuration() > 0) { + UseAnim anim = item->getUseAnimation(); + if (anim == UseAnim_block) { + armorParts1->holdingRightHand = armorParts2->holdingRightHand = + humanoidModel->holdingRightHand = 3; + } else if (anim == UseAnim_bow) { + armorParts1->bowAndArrow = armorParts2->bowAndArrow = + humanoidModel->bowAndArrow = true; + } + } + } + // 4J added, for 3rd person view of eating + if (item != NULL && mob->getUseItemDuration() > 0 && + item->getUseAnimation() == UseAnim_eat) { + // These factors are largely lifted from ItemInHandRenderer to try and + // keep the 3rd person eating animation as similar as possible float t = (mob->getUseItemDuration() - a + 1); float swing = 1 - (t / item->getUseDuration()); - armorParts1->eating = armorParts2->eating = humanoidModel->eating = true; - armorParts1->eating_t = armorParts2->eating_t = humanoidModel->eating_t = t; - armorParts1->eating_swing = armorParts2->eating_swing = humanoidModel->eating_swing = swing; - } - else - { - armorParts1->eating = armorParts2->eating = humanoidModel->eating = false; - } + armorParts1->eating = armorParts2->eating = humanoidModel->eating = + true; + armorParts1->eating_t = armorParts2->eating_t = + humanoidModel->eating_t = t; + armorParts1->eating_swing = armorParts2->eating_swing = + humanoidModel->eating_swing = swing; + } else { + armorParts1->eating = armorParts2->eating = humanoidModel->eating = + false; + } - armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = mob->isSneaking(); + armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = + mob->isSneaking(); double yp = y - mob->heightOffset; - if (mob->isSneaking() && (std::dynamic_pointer_cast(mob) == NULL)) - { + if (mob->isSneaking() && + (std::dynamic_pointer_cast(mob) == NULL)) { yp -= 2 / 16.0f; } - // Check if an idle animation is needed - if(mob->getAnimOverrideBitmask()&(1<isIdle()) - { - humanoidModel->idle=true; - armorParts1->idle=true; - armorParts2->idle=true; - } - else - { - humanoidModel->idle=false; - armorParts1->idle=false; - armorParts2->idle=false; - } - } - else - { - humanoidModel->idle=false; - armorParts1->idle=false; - armorParts2->idle=false; - } + // Check if an idle animation is needed + if (mob->getAnimOverrideBitmask() & (1 << HumanoidModel::eAnim_HasIdle)) { + if (mob->isIdle()) { + humanoidModel->idle = true; + armorParts1->idle = true; + armorParts2->idle = true; + } else { + humanoidModel->idle = false; + armorParts1->idle = false; + armorParts2->idle = false; + } + } else { + humanoidModel->idle = false; + armorParts1->idle = false; + armorParts2->idle = false; + } - // 4J-PB - any additional parts to turn on for this player (skin dependent) - std::vector *pAdditionalModelParts=mob->GetAdditionalModelParts(); - //turn them on - if(pAdditionalModelParts!=NULL) - { - for(AUTO_VAR(it, pAdditionalModelParts->begin()); it != pAdditionalModelParts->end(); ++it) - { - ModelPart *pModelPart=*it; + // 4J-PB - any additional parts to turn on for this player (skin dependent) + std::vector* pAdditionalModelParts = + mob->GetAdditionalModelParts(); + // turn them on + if (pAdditionalModelParts != NULL) { + for (AUTO_VAR(it, pAdditionalModelParts->begin()); + it != pAdditionalModelParts->end(); ++it) { + ModelPart* pModelPart = *it; - pModelPart->visible=true; - } - } + pModelPart->visible = true; + } + } MobRenderer::render(mob, x, yp, z, rot, a); - // turn them off again - if(pAdditionalModelParts && pAdditionalModelParts->size()!=0) - { - for(AUTO_VAR(it, pAdditionalModelParts->begin()); it != pAdditionalModelParts->end(); ++it) - { - ModelPart *pModelPart=*it; - - pModelPart->visible=false; - } - } - armorParts1->bowAndArrow = armorParts2->bowAndArrow = humanoidModel->bowAndArrow = false; - armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = false; - armorParts1->holdingRightHand = armorParts2->holdingRightHand = humanoidModel->holdingRightHand = 0; + // turn them off again + if (pAdditionalModelParts && pAdditionalModelParts->size() != 0) { + for (AUTO_VAR(it, pAdditionalModelParts->begin()); + it != pAdditionalModelParts->end(); ++it) { + ModelPart* pModelPart = *it; + pModelPart->visible = false; + } + } + armorParts1->bowAndArrow = armorParts2->bowAndArrow = + humanoidModel->bowAndArrow = false; + armorParts1->sneaking = armorParts2->sneaking = humanoidModel->sneaking = + false; + armorParts1->holdingRightHand = armorParts2->holdingRightHand = + humanoidModel->holdingRightHand = 0; } -void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, double z) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, + double z) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (Minecraft::renderNames() && mob != entityRenderDispatcher->cameraEntity - && !mob->isInvisibleTo(Minecraft::GetInstance()->player) ) // 4J-JEV: Todo, move to LivingEntityRenderer. - { + if (Minecraft::renderNames() && + mob != entityRenderDispatcher->cameraEntity && + !mob->isInvisibleTo( + Minecraft::GetInstance() + ->player)) // 4J-JEV: Todo, move to LivingEntityRenderer. + { float size = 1.60f; float s = 1 / 60.0f * size; double dist = mob->distanceToSqr(entityRenderDispatcher->cameraEntity); float maxDist = mob->isSneaking() ? 32.0f : 64.0f; - if (dist < maxDist * maxDist) - { - // Truncate display names longer than 16 char + if (dist < maxDist * maxDist) { + // Truncate display names longer than 16 char std::wstring msg = mob->getDisplayName(); - if (msg.length() > 16) - { - msg.resize(16); - msg += L"..."; - } + if (msg.length() > 16) { + msg.resize(16); + msg += L"..."; + } - if (mob->isSneaking()) - { - if ( app.GetGameSettings(eGameSetting_DisplayHUD)==0 ) - { - // 4J-PB - turn off gamertag render - return; - } + if (mob->isSneaking()) { + if (app.GetGameSettings(eGameSetting_DisplayHUD) == 0) { + // 4J-PB - turn off gamertag render + return; + } - if(app.GetGameHostOption(eGameHostOption_Gamertags)==0) - { - // turn off gamertags if the host has set them off - return; - } + if (app.GetGameHostOption(eGameHostOption_Gamertags) == 0) { + // turn off gamertags if the host has set them off + return; + } - Font *font = getFont(); + Font* font = getFont(); glPushMatrix(); - glTranslatef((float) x + 0, (float) y + 2.3f, (float) z); + glTranslatef((float)x + 0, (float)y + 2.3f, (float)z); glNormal3f(0, 1, 0); glRotatef(-this->entityRenderDispatcher->playerRotY, 0, 1, 0); @@ -277,20 +275,20 @@ void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, d glScalef(-s, -s, s); glDisable(GL_LIGHTING); - glTranslatef(0, (float) 0.25f / s, 0); + glTranslatef(0, (float)0.25f / s, 0); glDepthMask(false); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glDisable(GL_TEXTURE_2D); t->begin(); int w = font->width(msg) / 2; t->color(0.0f, 0.0f, 0.0f, 0.25f); - t->vertex((float)(-w - 1), (float)( -1), (float)( 0)); - t->vertex((float)(-w - 1), (float)( +8), (float)( 0)); - t->vertex((float)(+w + 1), (float)( +8), (float)( 0)); - t->vertex((float)(+w + 1), (float)( -1), (float)( 0)); + t->vertex((float)(-w - 1), (float)(-1), (float)(0)); + t->vertex((float)(-w - 1), (float)(+8), (float)(0)); + t->vertex((float)(+w + 1), (float)(+8), (float)(0)); + t->vertex((float)(+w + 1), (float)(-1), (float)(0)); t->end(); glEnable(GL_TEXTURE_2D); glDepthMask(true); @@ -299,76 +297,72 @@ void PlayerRenderer::renderName(std::shared_ptr _mob, double x, double y, d glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); glPopMatrix(); - } - else - { - if (mob->isSleeping()) - { - renderNameTag(mob, msg, x, y - 1.5f, z, 64, s_nametagColors[mob->getPlayerIndex()]); - } - else - { - renderNameTag(mob, msg, x, y, z, 64, s_nametagColors[mob->getPlayerIndex()]); + } else { + if (mob->isSleeping()) { + renderNameTag(mob, msg, x, y - 1.5f, z, 64, + s_nametagColors[mob->getPlayerIndex()]); + } else { + renderNameTag(mob, msg, x, y, z, 64, + s_nametagColors[mob->getPlayerIndex()]); } } } } - } -void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - MobRenderer::additionalRendering(_mob,a); +void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) { + MobRenderer::additionalRendering(_mob, a); - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); std::shared_ptr headGear = mob->inventory->getArmor(3); - if (headGear != NULL) - { - // don't render the pumpkin for the skins - unsigned int uiAnimOverrideBitmask = mob->getSkinAnimOverrideBitmask( mob->getCustomSkin()); + if (headGear != NULL) { + // don't render the pumpkin for the skins + unsigned int uiAnimOverrideBitmask = + mob->getSkinAnimOverrideBitmask(mob->getCustomSkin()); - if((uiAnimOverrideBitmask&(1<head->translateTo(1 / 16.0f); + if ((uiAnimOverrideBitmask & + (1 << HumanoidModel::eAnim_DontRenderArmour)) == 0) { + glPushMatrix(); + humanoidModel->head->translateTo(1 / 16.0f); - if(headGear->getItem()->id < 256) - { - if (TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) - { - float s = 10 / 16.0f; - glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); - glRotatef(90, 0, 1, 0); - glScalef(s, -s, s); - } + if (headGear->getItem()->id < 256) { + if (TileRenderer::canRender( + Tile::tiles[headGear->id]->getRenderShape())) { + float s = 10 / 16.0f; + glTranslatef(-0 / 16.0f, -4 / 16.0f, 0 / 16.0f); + glRotatef(90, 0, 1, 0); + glScalef(s, -s, s); + } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, headGear, 0); - } - else if (headGear->getItem()->id == Item::skull_Id) - { - float s = 17 / 16.0f; - glScalef(s, -s, -s); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, headGear, 0); + } else if (headGear->getItem()->id == Item::skull_Id) { + float s = 17 / 16.0f; + glScalef(s, -s, -s); - std::wstring extra = L""; - if (headGear->hasTag() && headGear->getTag()->contains(L"SkullOwner")) - { - extra = headGear->getTag()->getString(L"SkullOwner"); - } - SkullTileRenderer::instance->renderSkull(-0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), extra); - } + std::wstring extra = L""; + if (headGear->hasTag() && + headGear->getTag()->contains(L"SkullOwner")) { + extra = headGear->getTag()->getString(L"SkullOwner"); + } + SkullTileRenderer::instance->renderSkull( + -0.5f, 0, -0.5f, Facing::UP, 180, headGear->getAuxValue(), + extra); + } - glPopMatrix(); - } + glPopMatrix(); + } } - // need to add a custom texture for deadmau5 - if (mob != NULL && app.isXuidDeadmau5( mob->getXuid() ) && bindTexture(mob->customTextureUrl, L"" )) - { - for (int i = 0; i < 2; i++) - { - float yr = (mob->yRotO + (mob->yRot - mob->yRotO) * a) - (mob->yBodyRotO + (mob->yBodyRot - mob->yBodyRotO) * a); + // need to add a custom texture for deadmau5 + if (mob != NULL && app.isXuidDeadmau5(mob->getXuid()) && + bindTexture(mob->customTextureUrl, L"")) { + for (int i = 0; i < 2; i++) { + float yr = (mob->yRotO + (mob->yRot - mob->yRotO) * a) - + (mob->yBodyRotO + (mob->yBodyRot - mob->yBodyRotO) * a); float xr = mob->xRotO + (mob->xRot - mob->xRotO) * a; glPushMatrix(); glRotatef(yr, 0, 1, 0); @@ -380,116 +374,107 @@ void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) float s = 8 / 6.0f; glScalef(s, s, s); - humanoidModel->renderEars(1 / 16.0f,true); + humanoidModel->renderEars(1 / 16.0f, true); glPopMatrix(); } } -//4J-PB -// if (bindTexture(mob->cloakTexture, L"" )) - if (bindTexture(mob->customTextureUrl2, L"" ) && !mob->isInvisible()) - { + // 4J-PB + // if (bindTexture(mob->cloakTexture, L"" )) + if (bindTexture(mob->customTextureUrl2, L"") && !mob->isInvisible()) { glPushMatrix(); glTranslatef(0, 0, 2 / 16.0f); - double xd = (mob->xCloakO + (mob->xCloak - mob->xCloakO) * a) - (mob->xo + (mob->x - mob->xo) * a); - double yd = (mob->yCloakO + (mob->yCloak - mob->yCloakO) * a) - (mob->yo + (mob->y - mob->yo) * a); - double zd = (mob->zCloakO + (mob->zCloak - mob->zCloakO) * a) - (mob->zo + (mob->z - mob->zo) * a); + double xd = (mob->xCloakO + (mob->xCloak - mob->xCloakO) * a) - + (mob->xo + (mob->x - mob->xo) * a); + double yd = (mob->yCloakO + (mob->yCloak - mob->yCloakO) * a) - + (mob->yo + (mob->y - mob->yo) * a); + double zd = (mob->zCloakO + (mob->zCloak - mob->zCloakO) * a) - + (mob->zo + (mob->z - mob->zo) * a); float yr = mob->yBodyRotO + (mob->yBodyRot - mob->yBodyRotO) * a; double xa = Mth::sin(yr * PI / 180); double za = -Mth::cos(yr * PI / 180); - float flap = (float) yd * 10; + float flap = (float)yd * 10; if (flap < -6) flap = -6; if (flap > 32) flap = 32; - float lean = (float) (xd * xa + zd * za) * 100; - float lean2 = (float) (xd * za - zd * xa) * 100; + float lean = (float)(xd * xa + zd * za) * 100; + float lean2 = (float)(xd * za - zd * xa) * 100; if (lean < 0) lean = 0; float pow = mob->oBob + (mob->bob - mob->oBob) * a; - flap += sin((mob->walkDistO + (mob->walkDist - mob->walkDistO) * a) * 6) * 32 * pow; - if (mob->isSneaking()) - { + flap += + sin((mob->walkDistO + (mob->walkDist - mob->walkDistO) * a) * 6) * + 32 * pow; + if (mob->isSneaking()) { flap += 25; } - // 4J Stu - Fix for sprint-flying causing the cape to rotate up by 180 degrees or more - float xRot = 6.0f + lean / 2 + flap; - if(xRot > 64.0f) xRot = 64.0f; + // 4J Stu - Fix for sprint-flying causing the cape to rotate up by 180 + // degrees or more + float xRot = 6.0f + lean / 2 + flap; + if (xRot > 64.0f) xRot = 64.0f; glRotatef(xRot, 1, 0, 0); glRotatef(lean2 / 2, 0, 0, 1); glRotatef(-lean2 / 2, 0, 1, 0); glRotatef(180, 0, 1, 0); - humanoidModel->renderCloak(1 / 16.0f,true); + humanoidModel->renderCloak(1 / 16.0f, true); glPopMatrix(); } - std::shared_ptr item = mob->inventory->getSelected(); - if (item != NULL) - { + if (item != NULL) { glPushMatrix(); humanoidModel->arm0->translateTo(1 / 16.0f); glTranslatef(-1 / 16.0f, 7 / 16.0f, 1 / 16.0f); - if (mob->fishing != NULL) - { - item = std::shared_ptr( new ItemInstance(Item::stick) ); + if (mob->fishing != NULL) { + item = std::shared_ptr(new ItemInstance(Item::stick)); } - UseAnim anim = UseAnim_none;//null; - if (mob->getUseItemDuration() > 0) - { - anim = item->getUseAnimation(); - } + UseAnim anim = UseAnim_none; // null; + if (mob->getUseItemDuration() > 0) { + anim = item->getUseAnimation(); + } - if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) - { + if (item->id < 256 && + TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { float s = 8 / 16.0f; glTranslatef(-0 / 16.0f, 3 / 16.0f, -5 / 16.0f); s *= 0.75f; glRotatef(20, 1, 0, 0); glRotatef(45, 0, 1, 0); glScalef(s, -s, s); - } - else if (item->id == Item::bow->id) - { - float s = 10 / 16.0f; - glTranslatef(0 / 16.0f, 2 / 16.0f, 5 / 16.0f); - glRotatef(-20, 0, 1, 0); - glScalef(s, -s, s); - glRotatef(-100, 1, 0, 0); - glRotatef(45, 0, 1, 0); - } - else if (Item::items[item->id]->isHandEquipped()) - { - float s = 10 / 16.0f; - if (Item::items[item->id]->isMirroredArt()) - { - glRotatef(180, 0, 0, 1); - glTranslatef(0, -2 / 16.0f, 0); - } - if (mob->getUseItemDuration() > 0) - { - if (anim == UseAnim_block) - { - glTranslatef(0.05f, 0, -0.1f); - glRotatef(-50, 0, 1, 0); - glRotatef(-10, 1, 0, 0); - glRotatef(-60, 0, 0, 1); - } - } - glTranslatef(0, 3 / 16.0f, 0); - glScalef(s, -s, s); - glRotatef(-100, 1, 0, 0); - glRotatef(45, 0, 1, 0); - } - else - { + } else if (item->id == Item::bow->id) { + float s = 10 / 16.0f; + glTranslatef(0 / 16.0f, 2 / 16.0f, 5 / 16.0f); + glRotatef(-20, 0, 1, 0); + glScalef(s, -s, s); + glRotatef(-100, 1, 0, 0); + glRotatef(45, 0, 1, 0); + } else if (Item::items[item->id]->isHandEquipped()) { + float s = 10 / 16.0f; + if (Item::items[item->id]->isMirroredArt()) { + glRotatef(180, 0, 0, 1); + glTranslatef(0, -2 / 16.0f, 0); + } + if (mob->getUseItemDuration() > 0) { + if (anim == UseAnim_block) { + glTranslatef(0.05f, 0, -0.1f); + glRotatef(-50, 0, 1, 0); + glRotatef(-10, 1, 0, 0); + glRotatef(-60, 0, 0, 1); + } + } + glTranslatef(0, 3 / 16.0f, 0); + glScalef(s, -s, s); + glRotatef(-100, 1, 0, 0); + glRotatef(45, 0, 1, 0); + } else { float s = 6 / 16.0f; glTranslatef(+4 / 16.0f, +3 / 16.0f, -3 / 16.0f); glScalef(s, s, s); @@ -498,88 +483,81 @@ void PlayerRenderer::additionalRendering(std::shared_ptr _mob, float a) glRotatef(20, 0, 0, 1); } - if (item->getItem()->hasMultipleSpriteLayers()) - { - for (int layer = 0; layer <= 1; layer++) - { - int col = item->getItem()->getColor(item,layer); - float red = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + if (item->getItem()->hasMultipleSpriteLayers()) { + for (int layer = 0; layer <= 1; layer++) { + int col = item->getItem()->getColor(item, layer); + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - glColor4f(red, g, b, 1); - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, layer, false); - } - } - else - { - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, item, 0); - } + glColor4f(red, g, b, 1); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, item, layer, false); + } + } else { + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, item, 0); + } glPopMatrix(); } - } -void PlayerRenderer::scale(std::shared_ptr player, float a) -{ +void PlayerRenderer::scale(std::shared_ptr player, float a) { float s = 15 / 16.0f; glScalef(s, s, s); } -void PlayerRenderer::renderHand() -{ - humanoidModel->m_uiAnimOverrideBitmask = Minecraft::GetInstance()->player->getAnimOverrideBitmask(); - armorParts1->eating = armorParts2->eating = humanoidModel->eating = humanoidModel->idle = false; +void PlayerRenderer::renderHand() { + humanoidModel->m_uiAnimOverrideBitmask = + Minecraft::GetInstance()->player->getAnimOverrideBitmask(); + armorParts1->eating = armorParts2->eating = humanoidModel->eating = + humanoidModel->idle = false; humanoidModel->attackTime = 0; humanoidModel->setupAnim(0, 0, 0, 0, 0, 1 / 16.0f); - // 4J-PB - does this skin have its arm0 disabled? (Dalek, etc) - if((humanoidModel->m_uiAnimOverrideBitmask&(1<arm0->render(1 / 16.0f,true); - } + // 4J-PB - does this skin have its arm0 disabled? (Dalek, etc) + if ((humanoidModel->m_uiAnimOverrideBitmask & + (1 << HumanoidModel::eAnim_DisableRenderArm0)) == 0) { + humanoidModel->arm0->render(1 / 16.0f, true); + } } -void PlayerRenderer::setupPosition(std::shared_ptr _mob, double x, double y, double z) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::setupPosition(std::shared_ptr _mob, double x, + double y, double z) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isAlive() && mob->isSleeping()) - { - MobRenderer::setupPosition(mob, x + mob->bedOffsetX, y + mob->bedOffsetY, z + mob->bedOffsetZ); + if (mob->isAlive() && mob->isSleeping()) { + MobRenderer::setupPosition(mob, x + mob->bedOffsetX, + y + mob->bedOffsetY, z + mob->bedOffsetZ); - } - else - { + } else { MobRenderer::setupPosition(mob, x, y, z); } } -void PlayerRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void PlayerRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isAlive() && mob->isSleeping()) - { + if (mob->isAlive() && mob->isSleeping()) { glRotatef(mob->getSleepRotation(), 0, 1, 0); glRotatef(getFlipDegrees(mob), 0, 0, 1); glRotatef(270, 0, 1, 0); - } - else - { + } else { MobRenderer::setupRotations(mob, bob, bodyRot, a); } } // 4J Added override to stop rendering shadow if player is invisible -void PlayerRenderer::renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a) -{ - if(app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) > 0) - { - std::shared_ptr player = std::dynamic_pointer_cast(e); - if(player != NULL && player->hasInvisiblePrivilege()) return; - } - EntityRenderer::renderShadow(e,x,y,z,pow,a); +void PlayerRenderer::renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, float a) { + if (app.GetGameHostOption(eGameHostOption_HostCanBeInvisible) > 0) { + std::shared_ptr player = std::dynamic_pointer_cast(e); + if (player != NULL && player->hasInvisiblePrivilege()) return; + } + EntityRenderer::renderShadow(e, x, y, z, pow, a); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h index b47d36238..3d2118366 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/PlayerRenderer.h @@ -3,40 +3,49 @@ #include "../../../Minecraft.World/Player/Player.h" class HumanoidModel; - -class PlayerRenderer : public MobRenderer -{ +class PlayerRenderer : public MobRenderer { private: - // 4J Added - static const unsigned int s_nametagColors[MINECRAFT_NET_MAX_PLAYERS]; + // 4J Added + static const unsigned int s_nametagColors[MINECRAFT_NET_MAX_PLAYERS]; - HumanoidModel *humanoidModel; - HumanoidModel *armorParts1; - HumanoidModel *armorParts2; + HumanoidModel* humanoidModel; + HumanoidModel* armorParts1; + HumanoidModel* armorParts2; public: - PlayerRenderer(); + PlayerRenderer(); - static unsigned int getNametagColour(int index); + static unsigned int getNametagColour(int index); private: - static const std::wstring MATERIAL_NAMES[5]; + static const std::wstring MATERIAL_NAMES[5]; protected: - virtual int prepareArmor(std::shared_ptr _player, int layer, float a); - virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, float a); + virtual int prepareArmor(std::shared_ptr _player, int layer, float a); + virtual void prepareSecondPassArmor(std::shared_ptr mob, int layer, + float a); + public: - virtual void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a); + protected: - virtual void renderName(std::shared_ptr _mob, double x, double y, double z); + virtual void renderName(std::shared_ptr _mob, double x, double y, + double z); virtual void additionalRendering(std::shared_ptr _mob, float a); virtual void scale(std::shared_ptr _player, float a); -public: - void renderHand(); -protected: - virtual void setupPosition(std::shared_ptr _mob, double x, double y, double z); - virtual void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); -private: - virtual void renderShadow(std::shared_ptr e, double x, double y, double z, float pow, float a); // 4J Added override +public: + void renderHand(); + +protected: + virtual void setupPosition(std::shared_ptr _mob, double x, double y, + double z); + virtual void setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a); + +private: + virtual void renderShadow(std::shared_ptr e, double x, double y, + double z, float pow, + float a); // 4J Added override }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp index 50619a156..2cb865c0d 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.cpp @@ -6,41 +6,37 @@ CRITICAL_SECTION ProgressRenderer::s_progress; -ProgressRenderer::ProgressRenderer(Minecraft *minecraft) -{ - status = -1; - title = -1; - lastTime = System::currentTimeMillis(); - noAbort = false; - this->minecraft = minecraft; - this->m_eType=eProgressStringType_ID; +ProgressRenderer::ProgressRenderer(Minecraft* minecraft) { + status = -1; + title = -1; + lastTime = System::currentTimeMillis(); + noAbort = false; + this->minecraft = minecraft; + this->m_eType = eProgressStringType_ID; } -void ProgressRenderer::progressStart(int title) -{ - noAbort = false; - _progressStart(title); +void ProgressRenderer::progressStart(int title) { + noAbort = false; + _progressStart(title); } -void ProgressRenderer::progressStartNoAbort(int string) -{ - noAbort = true; +void ProgressRenderer::progressStartNoAbort(int string) { + noAbort = true; _progressStart(string); } -void ProgressRenderer::_progressStart(int title) -{ - // 4J Stu - Removing all progressRenderer rendering. This will be replaced on the xbox - if (!minecraft->running) - { +void ProgressRenderer::_progressStart(int title) { + // 4J Stu - Removing all progressRenderer rendering. This will be replaced + // on the xbox + if (!minecraft->running) { if (noAbort) return; -// throw new StopGameException(); // 4J - removed + // throw new StopGameException(); // 4J - removed } - - EnterCriticalSection( &ProgressRenderer::s_progress ); - lastPercent = 0; + + EnterCriticalSection(&ProgressRenderer::s_progress); + lastPercent = 0; this->title = title; - LeaveCriticalSection( &ProgressRenderer::s_progress ); + LeaveCriticalSection(&ProgressRenderer::s_progress); #if 0 ScreenSizeCalculator ssc(minecraft->options, minecraft->width, minecraft->height); @@ -55,30 +51,27 @@ void ProgressRenderer::_progressStart(int title) #endif } -void ProgressRenderer::progressStage(int status) -{ - if (!minecraft->running) - { +void ProgressRenderer::progressStage(int status) { + if (!minecraft->running) { if (noAbort) return; -// throw new StopGameException(); // 4J - removed + // throw new StopGameException(); // 4J - removed } - lastTime = 0; - EnterCriticalSection( &ProgressRenderer::s_progress ); - setType(eProgressStringType_ID); + EnterCriticalSection(&ProgressRenderer::s_progress); + setType(eProgressStringType_ID); this->status = status; - LeaveCriticalSection( &ProgressRenderer::s_progress ); + LeaveCriticalSection(&ProgressRenderer::s_progress); progressStagePercentage(-1); lastTime = 0; } -void ProgressRenderer::progressStagePercentage(int i) -{ - // 4J Stu - Removing all progressRenderer rendering. This will be replaced on the xbox - EnterCriticalSection( &ProgressRenderer::s_progress ); - lastPercent = i; - LeaveCriticalSection( &ProgressRenderer::s_progress ); +void ProgressRenderer::progressStagePercentage(int i) { + // 4J Stu - Removing all progressRenderer rendering. This will be replaced + // on the xbox + EnterCriticalSection(&ProgressRenderer::s_progress); + lastPercent = i; + LeaveCriticalSection(&ProgressRenderer::s_progress); #if 0 if (!minecraft->running) @@ -155,60 +148,51 @@ void ProgressRenderer::progressStagePercentage(int i) #endif } -int ProgressRenderer::getCurrentPercent() -{ - int returnValue = 0; - EnterCriticalSection( &ProgressRenderer::s_progress ); - returnValue = lastPercent; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +int ProgressRenderer::getCurrentPercent() { + int returnValue = 0; + EnterCriticalSection(&ProgressRenderer::s_progress); + returnValue = lastPercent; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -int ProgressRenderer::getCurrentTitle() -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - int returnValue = title; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +int ProgressRenderer::getCurrentTitle() { + EnterCriticalSection(&ProgressRenderer::s_progress); + int returnValue = title; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -int ProgressRenderer::getCurrentStatus() -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - int returnValue = status; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +int ProgressRenderer::getCurrentStatus() { + EnterCriticalSection(&ProgressRenderer::s_progress); + int returnValue = status; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -ProgressRenderer::eProgressStringType ProgressRenderer::getType() -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - eProgressStringType returnValue = m_eType; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return returnValue; +ProgressRenderer::eProgressStringType ProgressRenderer::getType() { + EnterCriticalSection(&ProgressRenderer::s_progress); + eProgressStringType returnValue = m_eType; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return returnValue; } -void ProgressRenderer::setType(eProgressStringType eType) -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - m_eType=eType; - LeaveCriticalSection( &ProgressRenderer::s_progress ); +void ProgressRenderer::setType(eProgressStringType eType) { + EnterCriticalSection(&ProgressRenderer::s_progress); + m_eType = eType; + LeaveCriticalSection(&ProgressRenderer::s_progress); } -void ProgressRenderer::progressStage(std::wstring &wstrText) -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - m_wstrText=wstrText; - setType(eProgressStringType_String); - LeaveCriticalSection( &ProgressRenderer::s_progress ); +void ProgressRenderer::progressStage(std::wstring& wstrText) { + EnterCriticalSection(&ProgressRenderer::s_progress); + m_wstrText = wstrText; + setType(eProgressStringType_String); + LeaveCriticalSection(&ProgressRenderer::s_progress); } -std::wstring& ProgressRenderer::getProgressString(void) -{ - EnterCriticalSection( &ProgressRenderer::s_progress ); - std::wstring &temp=m_wstrText; - LeaveCriticalSection( &ProgressRenderer::s_progress ); - return temp; +std::wstring& ProgressRenderer::getProgressString(void) { + EnterCriticalSection(&ProgressRenderer::s_progress); + std::wstring& temp = m_wstrText; + LeaveCriticalSection(&ProgressRenderer::s_progress); + return temp; } - - diff --git a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h index bb3446c4c..28ba3c68b 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ProgressRenderer.h @@ -1,43 +1,42 @@ #pragma once #include "../../../Minecraft.World/Util/ProgressListener.h" -class ProgressRenderer : public ProgressListener -{ +class ProgressRenderer : public ProgressListener { public: - enum eProgressStringType - { - eProgressStringType_ID, - eProgressStringType_String, // 4J-PB added for updating the bytes read on a save transfer - }; + enum eProgressStringType { + eProgressStringType_ID, + eProgressStringType_String, // 4J-PB added for updating the bytes read + // on a save transfer + }; - static CRITICAL_SECTION s_progress; + static CRITICAL_SECTION s_progress; - int getCurrentPercent(); - int getCurrentTitle(); - int getCurrentStatus(); - std::wstring& getProgressString(void); - ProgressRenderer::eProgressStringType getType(); + int getCurrentPercent(); + int getCurrentTitle(); + int getCurrentStatus(); + std::wstring& getProgressString(void); + ProgressRenderer::eProgressStringType getType(); private: - int lastPercent; + int lastPercent; private: - int status; - Minecraft *minecraft; + int status; + Minecraft* minecraft; int title; __int64 lastTime; bool noAbort; - std::wstring m_wstrText; - eProgressStringType m_eType; + std::wstring m_wstrText; + eProgressStringType m_eType; - void setType(eProgressStringType eType); + void setType(eProgressStringType eType); public: - ProgressRenderer(Minecraft *minecraft); + ProgressRenderer(Minecraft* minecraft); virtual void progressStart(int title); virtual void progressStartNoAbort(int string); void _progressStart(int title); - virtual void progressStage(int status); - virtual void progressStage(std::wstring &wstrText); + virtual void progressStage(int status); + virtual void progressStage(std::wstring& wstrText); virtual void progressStagePercentage(int i); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp index c0c65d6f3..7a99f5a43 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.cpp @@ -3,32 +3,39 @@ #include "../../Player/MultiPlayerLocalPlayer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -SheepRenderer::SheepRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model, shadow) -{ - setArmor(armor); +SheepRenderer::SheepRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + setArmor(armor); } -int SheepRenderer::prepareArmor(std::shared_ptr _sheep, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr sheep = std::dynamic_pointer_cast(_sheep); +int SheepRenderer::prepareArmor(std::shared_ptr _sheep, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr sheep = std::dynamic_pointer_cast(_sheep); if (layer == 0 && !sheep->isSheared() && - !sheep->isInvisibleTo(Minecraft::GetInstance()->player)) // 4J-JEV: Todo, merge with java fix (for invisible sheep armour) in '1.7.5'. - { - MemSect(31); - bindTexture(TN_MOB_SHEEP_FUR); // 4J was L"/mob/sheep_fur.png" - MemSect(0); - // 4J - change brought forward from 1.8.2 - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1.0f : sheep->getBrightness(a); + !sheep->isInvisibleTo( + Minecraft::GetInstance() + ->player)) // 4J-JEV: Todo, merge with java fix (for invisible + // sheep armour) in '1.7.5'. + { + MemSect(31); + bindTexture(TN_MOB_SHEEP_FUR); // 4J was L"/mob/sheep_fur.png" + MemSect(0); + // 4J - change brought forward from 1.8.2 + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1.0f : sheep->getBrightness(a); int color = sheep->getColor(); - glColor3f(brightness * Sheep::COLOR[color][0], brightness * Sheep::COLOR[color][1], brightness * Sheep::COLOR[color][2]); + glColor3f(brightness * Sheep::COLOR[color][0], + brightness * Sheep::COLOR[color][1], + brightness * Sheep::COLOR[color][2]); return 1; } return -1; } -void SheepRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); -} +void SheepRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); +} diff --git a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h index 637c53d04..cd4ff0e97 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SheepRenderer.h @@ -1,14 +1,14 @@ #pragma once #include "MobRenderer.h" -class SheepRenderer : public MobRenderer -{ +class SheepRenderer : public MobRenderer { public: - SheepRenderer(Model *model, Model *armor, float shadow); + SheepRenderer(Model* model, Model* armor, float shadow); protected: - virtual int prepareArmor(std::shared_ptr _sheep, int layer, float a); + virtual int prepareArmor(std::shared_ptr _sheep, int layer, float a); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp index d49f23f17..3d1ecd2e9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.cpp @@ -7,30 +7,26 @@ #include "../../../Minecraft.World/Entities/Entity.h" #include "../../../Minecraft.World/Level/Level.h" +SignRenderer::SignRenderer() { signModel = new SignModel(); } -SignRenderer::SignRenderer() -{ - signModel = new SignModel(); -} +void SignRenderer::render(std::shared_ptr _sign, double x, double y, + double z, float a, bool setColor, float alpha, + bool useCompiled) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr sign = + std::dynamic_pointer_cast(_sign); -void SignRenderer::render(std::shared_ptr _sign, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr sign = std::dynamic_pointer_cast(_sign); - - Tile *tile = sign->getTile(); + Tile* tile = sign->getTile(); glPushMatrix(); float size = 16 / 24.0f; - if (tile == Tile::sign) - { - glTranslatef((float) x + 0.5f, (float) y + 0.75f * size, (float) z + 0.5f); + if (tile == Tile::sign) { + glTranslatef((float)x + 0.5f, (float)y + 0.75f * size, (float)z + 0.5f); float rot = sign->getData() * 360 / 16.0f; glRotatef(-rot, 0, 1, 0); signModel->cube2->visible = true; - } - else - { + } else { int face = sign->getData(); float rot = 0; @@ -38,20 +34,20 @@ void SignRenderer::render(std::shared_ptr _sign, double x, double y, if (face == 4) rot = 90; if (face == 5) rot = -90; - glTranslatef((float) x + 0.5f, (float) y + 0.75f * size, (float) z + 0.5f); + glTranslatef((float)x + 0.5f, (float)y + 0.75f * size, (float)z + 0.5f); glRotatef(-rot, 0, 1, 0); glTranslatef(0, -5 / 16.0f, -7 / 16.0f); signModel->cube2->visible = false; } - bindTexture(TN_ITEM_SIGN); // 4J was L"/item/sign.png" + bindTexture(TN_ITEM_SIGN); // 4J was L"/item/sign.png" glPushMatrix(); glScalef(size, -size, -size); signModel->render(true); glPopMatrix(); - Font *font = getFont(); + Font* font = getFont(); float s = 1 / 60.0f * size; glTranslatef(0, 0.5f * size, 0.07f * size); @@ -59,62 +55,56 @@ void SignRenderer::render(std::shared_ptr _sign, double x, double y, glNormal3f(0, 0, -1 * s); glDepthMask(false); - int col = Minecraft::GetInstance()->getColourTable()->getColor(eMinecraftColour_Sign_Text); - std::wstring msg; - // need to send the new data - // Get the current language setting from the console - std::uint32_t dwLanguage = XGetLanguage( ); + int col = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Sign_Text); + std::wstring msg; + // need to send the new data + // Get the current language setting from the console + std::uint32_t dwLanguage = XGetLanguage(); - for (int i = 0; i < MAX_SIGN_LINES; i++) // 4J - was sign.messages.length - { - if(sign->IsVerified()) - { - if(sign->IsCensored()) - { - switch(dwLanguage) - { - case XC_LANGUAGE_KOREAN: - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - msg = L"Censored";// In-game font, so English only - break; - default: - msg = app.GetString(IDS_STRINGVERIFY_CENSORED); - break; - } - } - else - { - msg = sign->GetMessage(i); - } - } - else - { - switch(dwLanguage) - { - case XC_LANGUAGE_KOREAN: - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - msg = L"Awaiting Approval";// In-game font, so English only - break; - default: - msg = app.GetString(IDS_STRINGVERIFY_AWAITING_APPROVAL); - break; - } - } - - if (i == sign->GetSelectedLine()) - { - msg = L"> " + msg + L" <"; - font->draw(msg, -font->width(msg) / 2, i * 10 - (MAX_SIGN_LINES) * 5, col); // 4J - (MAX_SIGN_LINES) was sign.messages.length + for (int i = 0; i < MAX_SIGN_LINES; i++) // 4J - was sign.messages.length + { + if (sign->IsVerified()) { + if (sign->IsCensored()) { + switch (dwLanguage) { + case XC_LANGUAGE_KOREAN: + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + msg = L"Censored"; // In-game font, so English only + break; + default: + msg = app.GetString(IDS_STRINGVERIFY_CENSORED); + break; + } + } else { + msg = sign->GetMessage(i); + } + } else { + switch (dwLanguage) { + case XC_LANGUAGE_KOREAN: + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + msg = + L"Awaiting Approval"; // In-game font, so English only + break; + default: + msg = app.GetString(IDS_STRINGVERIFY_AWAITING_APPROVAL); + break; + } } - else - { - font->draw(msg, -font->width(msg) / 2, i * 10 - (MAX_SIGN_LINES) * 5, col); // 4J - (MAX_SIGN_LINES) was sign.messages.length + + if (i == sign->GetSelectedLine()) { + msg = L"> " + msg + L" <"; + font->draw(msg, -font->width(msg) / 2, + i * 10 - (MAX_SIGN_LINES) * 5, + col); // 4J - (MAX_SIGN_LINES) was sign.messages.length + } else { + font->draw(msg, -font->width(msg) / 2, + i * 10 - (MAX_SIGN_LINES) * 5, + col); // 4J - (MAX_SIGN_LINES) was sign.messages.length } } glDepthMask(true); glColor4f(1, 1, 1, 1); glPopMatrix(); - } diff --git a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h index d7411af43..cc763391b 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SignRenderer.h @@ -2,11 +2,13 @@ #include "TileEntityRenderer.h" class SignModel; -class SignRenderer : public TileEntityRenderer -{ +class SignRenderer : public TileEntityRenderer { private: - SignModel *signModel; + SignModel* signModel; + public: - SignRenderer(); // 4J - added - virtual void render(std::shared_ptr sign, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); // 4J added setColor param + SignRenderer(); // 4J - added + virtual void render(std::shared_ptr sign, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); // 4J added setColor param }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp index 6da4ed073..61df0e757 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.cpp @@ -3,21 +3,19 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "../Models/SilverfishModel.h" -SilverfishRenderer::SilverfishRenderer() : MobRenderer(new SilverfishModel(), 0.3f) -{ +SilverfishRenderer::SilverfishRenderer() + : MobRenderer(new SilverfishModel(), 0.3f) {} + +float SilverfishRenderer::getFlipDegrees(std::shared_ptr spider) { + return 180; } -float SilverfishRenderer::getFlipDegrees(std::shared_ptr spider) -{ - return 180; +void SilverfishRenderer::render(std::shared_ptr _mob, double x, + double y, double z, float rot, float a) { + MobRenderer::render(_mob, x, y, z, rot, a); } -void SilverfishRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(_mob, x, y, z, rot, a); -} - -int SilverfishRenderer::prepareArmor(std::shared_ptr _silverfish, int layer, float a) -{ - return -1; +int SilverfishRenderer::prepareArmor(std::shared_ptr _silverfish, + int layer, float a) { + return -1; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h index 91ff2e456..eadf51cfe 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SilverfishRenderer.h @@ -4,20 +4,20 @@ class Silverfish; -class SilverfishRenderer : public MobRenderer -{ +class SilverfishRenderer : public MobRenderer { private: - //int modelVersion; + // int modelVersion; public: - SilverfishRenderer(); + SilverfishRenderer(); protected: - float getFlipDegrees(std::shared_ptr spider); + float getFlipDegrees(std::shared_ptr spider); public: - void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr _mob, double x, double y, double z, + float rot, float a); protected: - int prepareArmor(std::shared_ptr _silverfish, int layer, float a); + int prepareArmor(std::shared_ptr _silverfish, int layer, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp index 8d389f87a..ef501bb4a 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.cpp @@ -5,108 +5,110 @@ #include "../Models/SkeletonHeadModel.h" #include "SkullTileRenderer.h" -SkullTileRenderer *SkullTileRenderer::instance = NULL; +SkullTileRenderer* SkullTileRenderer::instance = NULL; -SkullTileRenderer::SkullTileRenderer() -{ - skeletonModel = new SkeletonHeadModel(0, 0, 64, 32); - zombieModel = new SkeletonHeadModel(0, 0, 64, 64); +SkullTileRenderer::SkullTileRenderer() { + skeletonModel = new SkeletonHeadModel(0, 0, 64, 32); + zombieModel = new SkeletonHeadModel(0, 0, 64, 64); } -SkullTileRenderer::~SkullTileRenderer() -{ - delete skeletonModel; - delete zombieModel; +SkullTileRenderer::~SkullTileRenderer() { + delete skeletonModel; + delete zombieModel; } -void SkullTileRenderer::render(std::shared_ptr _skull, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - std::shared_ptr skull = std::dynamic_pointer_cast(_skull); - renderSkull((float) x, (float) y, (float) z, skull->getData() & SkullTile::PLACEMENT_MASK, skull->getRotation() * 360 / 16.0f, skull->getSkullType(), skull->getExtraType()); +void SkullTileRenderer::render(std::shared_ptr _skull, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + std::shared_ptr skull = + std::dynamic_pointer_cast(_skull); + renderSkull((float)x, (float)y, (float)z, + skull->getData() & SkullTile::PLACEMENT_MASK, + skull->getRotation() * 360 / 16.0f, skull->getSkullType(), + skull->getExtraType()); } -void SkullTileRenderer::init(TileEntityRenderDispatcher *tileEntityRenderDispatcher) -{ - TileEntityRenderer::init(tileEntityRenderDispatcher); - instance = this; +void SkullTileRenderer::init( + TileEntityRenderDispatcher* tileEntityRenderDispatcher) { + TileEntityRenderer::init(tileEntityRenderDispatcher); + instance = this; } -void SkullTileRenderer::renderSkull(float x, float y, float z, int face, float rot, int type, const std::wstring &extra) -{ - Model *model = skeletonModel; +void SkullTileRenderer::renderSkull(float x, float y, float z, int face, + float rot, int type, + const std::wstring& extra) { + Model* model = skeletonModel; - switch (type) - { - case SkullTileEntity::TYPE_WITHER: - bindTexture(TN_MOB_WITHER_SKELETON); - break; - case SkullTileEntity::TYPE_ZOMBIE: - bindTexture(TN_MOB_ZOMBIE); - //model = zombieModel; - break; - case SkullTileEntity::TYPE_CHAR: - //if (!extra.empty()) - //{ - // std::wstring url = "http://skins.minecraft.net/MinecraftSkins/" + StringUtil.stripColor(extra) + ".png"; + switch (type) { + case SkullTileEntity::TYPE_WITHER: + bindTexture(TN_MOB_WITHER_SKELETON); + break; + case SkullTileEntity::TYPE_ZOMBIE: + bindTexture(TN_MOB_ZOMBIE); + // model = zombieModel; + break; + case SkullTileEntity::TYPE_CHAR: + // if (!extra.empty()) + //{ + // std::wstring url = "http://skins.minecraft.net/MinecraftSkins/" + //+ StringUtil.stripColor(extra) + ".png"; - // if (!instance->tileEntityRenderDispatcher->textures->hasHttpTexture(url)) - // { - // instance->tileEntityRenderDispatcher->textures->addHttpTexture(url, new MobSkinTextureProcessor()); - // } + // if + //(!instance->tileEntityRenderDispatcher->textures->hasHttpTexture(url)) + // { + // instance->tileEntityRenderDispatcher->textures->addHttpTexture(url, + //new MobSkinTextureProcessor()); + // } - // bindTexture(url, "/mob/char.png"); - //} - //else - { - bindTexture(TN_MOB_CHAR); - } - break; - case SkullTileEntity::TYPE_CREEPER: - bindTexture(TN_MOB_CREEPER); - break; - case SkullTileEntity::TYPE_SKELETON: - default: - bindTexture(TN_MOB_SKELETON); - break; - } + // bindTexture(url, "/mob/char.png"); + //} + // else + { + bindTexture(TN_MOB_CHAR); + } + break; + case SkullTileEntity::TYPE_CREEPER: + bindTexture(TN_MOB_CREEPER); + break; + case SkullTileEntity::TYPE_SKELETON: + default: + bindTexture(TN_MOB_SKELETON); + break; + } - glPushMatrix(); - glDisable(GL_CULL_FACE); + glPushMatrix(); + glDisable(GL_CULL_FACE); - if (face != Facing::UP) - { - switch (face) - { - case Facing::NORTH: - glTranslatef(x + 0.5f, y + .25f, z + 0.74f); - break; - case Facing::SOUTH: - glTranslatef(x + 0.5f, y + .25f, z + 0.26f); - rot = 180.0f; - break; - case Facing::WEST: - glTranslatef(x + 0.74f, y + .25f, z + 0.5f); - rot = 270.0f; - break; - case Facing::EAST: - default: - glTranslatef(x + 0.26f, y + .25f, z + 0.5f); - rot = 90.0f; - break; - } - } - else - { - glTranslatef(x + 0.5f, y, z + 0.5f); - } + if (face != Facing::UP) { + switch (face) { + case Facing::NORTH: + glTranslatef(x + 0.5f, y + .25f, z + 0.74f); + break; + case Facing::SOUTH: + glTranslatef(x + 0.5f, y + .25f, z + 0.26f); + rot = 180.0f; + break; + case Facing::WEST: + glTranslatef(x + 0.74f, y + .25f, z + 0.5f); + rot = 270.0f; + break; + case Facing::EAST: + default: + glTranslatef(x + 0.26f, y + .25f, z + 0.5f); + rot = 90.0f; + break; + } + } else { + glTranslatef(x + 0.5f, y, z + 0.5f); + } - float scale = 1 / 16.0f; - glEnable(GL_RESCALE_NORMAL); - glScalef(-1, -1, 1); + float scale = 1 / 16.0f; + glEnable(GL_RESCALE_NORMAL); + glScalef(-1, -1, 1); - glEnable(GL_ALPHA_TEST); + glEnable(GL_ALPHA_TEST); - model->render(nullptr, 0, 0, 0, rot, 0, scale,true); + model->render(nullptr, 0, 0, 0, rot, 0, scale, true); - glPopMatrix(); + glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h index e2ef38605..8f47eb6da 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SkullTileRenderer.h @@ -4,21 +4,22 @@ class SkeletonHeadModel; -class SkullTileRenderer : public TileEntityRenderer -{ +class SkullTileRenderer : public TileEntityRenderer { public: - static SkullTileRenderer *instance; + static SkullTileRenderer* instance; private: - // note: this head fits most mobs, just change texture - SkeletonHeadModel *skeletonModel; - SkeletonHeadModel *zombieModel; + // note: this head fits most mobs, just change texture + SkeletonHeadModel* skeletonModel; + SkeletonHeadModel* zombieModel; public: - SkullTileRenderer(); - ~SkullTileRenderer(); + SkullTileRenderer(); + ~SkullTileRenderer(); - void render(std::shared_ptr skull, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled = true); - void init(TileEntityRenderDispatcher *tileEntityRenderDispatcher); - void renderSkull(float x, float y, float z, int face, float rot, int type, const std::wstring &extra); + void render(std::shared_ptr skull, double x, double y, double z, + float a, bool setColor, float alpha, bool useCompiled = true); + void init(TileEntityRenderDispatcher* tileEntityRenderDispatcher); + void renderSkull(float x, float y, float z, int face, float rot, int type, + const std::wstring& extra); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp index 77f03f7c9..19ee0cad0 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.cpp @@ -1,21 +1,21 @@ #include "../../Platform/stdafx.h" -#include "SlimeRenderer.h" +#include "SlimeRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" -SlimeRenderer::SlimeRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model, shadow) -{ - this->armor = armor; +SlimeRenderer::SlimeRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + this->armor = armor; } -int SlimeRenderer::prepareArmor(std::shared_ptr _slime, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr slime = std::dynamic_pointer_cast(_slime); +int SlimeRenderer::prepareArmor(std::shared_ptr _slime, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr slime = std::dynamic_pointer_cast(_slime); - if (slime->isInvisible()) return 0; + if (slime->isInvisible()) return 0; - if (layer == 0) - { + if (layer == 0) { setArmor(armor); glEnable(GL_NORMALIZE); @@ -24,21 +24,21 @@ int SlimeRenderer::prepareArmor(std::shared_ptr _slime, int layer, float a) return 1; } - if (layer == 1) - { + if (layer == 1) { glDisable(GL_BLEND); glColor4f(1, 1, 1, 1); } return -1; } -void SlimeRenderer::scale(std::shared_ptr _slime, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr slime = std::dynamic_pointer_cast(_slime); +void SlimeRenderer::scale(std::shared_ptr _slime, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr slime = std::dynamic_pointer_cast(_slime); - float size = (float) slime->getSize(); - float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / (size * 0.5f + 1); + float size = (float)slime->getSize(); + float ss = (slime->oSquish + (slime->squish - slime->oSquish) * a) / + (size * 0.5f + 1); float w = 1 / (ss + 1); glScalef(w * size, 1 / w * size, w * size); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h index 86de3a76e..0ab5ae7a9 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SlimeRenderer.h @@ -1,13 +1,14 @@ #pragma once #include "MobRenderer.h" -class SlimeRenderer : public MobRenderer -{ +class SlimeRenderer : public MobRenderer { private: - Model *armor; + Model* armor; + public: - SlimeRenderer(Model *model, Model *armor, float shadow); + SlimeRenderer(Model* model, Model* armor, float shadow); + protected: - virtual int prepareArmor(std::shared_ptr _slime, int layer, float a); + virtual int prepareArmor(std::shared_ptr _slime, int layer, float a); virtual void scale(std::shared_ptr _slime, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp index 0032a6e5e..039ec74d8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.cpp @@ -7,35 +7,35 @@ #include "EntityRenderDispatcher.h" #include "SnowManRenderer.h" -SnowManRenderer::SnowManRenderer() : MobRenderer(new SnowManModel(), 0.5f) -{ - model = (SnowManModel *) MobRenderer::model; - this->setArmor(model); +SnowManRenderer::SnowManRenderer() : MobRenderer(new SnowManModel(), 0.5f) { + model = (SnowManModel*)MobRenderer::model; + this->setArmor(model); } -void SnowManRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type SnowMan rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void SnowManRenderer::additionalRendering(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type SnowMan rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - std::shared_ptr headGear = std::shared_ptr( new ItemInstance(Tile::pumpkin, 1) ); - if (headGear != NULL && headGear->getItem()->id < 256) - { - glPushMatrix(); - model->head->translateTo(1 / 16.0f); + MobRenderer::additionalRendering(mob, a); + std::shared_ptr headGear = + std::shared_ptr(new ItemInstance(Tile::pumpkin, 1)); + if (headGear != NULL && headGear->getItem()->id < 256) { + glPushMatrix(); + model->head->translateTo(1 / 16.0f); - if (TileRenderer::canRender(Tile::tiles[headGear->id]->getRenderShape())) - { - float s = 10 / 16.0f; - glTranslatef(-0 / 16.0f, -5.5f / 16.0f, 0 / 16.0f); - glRotatef(90, 0, 1, 0); - glScalef(s, -s, s); - } + if (TileRenderer::canRender( + Tile::tiles[headGear->id]->getRenderShape())) { + float s = 10 / 16.0f; + glTranslatef(-0 / 16.0f, -5.5f / 16.0f, 0 / 16.0f); + glRotatef(90, 0, 1, 0); + glScalef(s, -s, s); + } - this->entityRenderDispatcher->itemInHandRenderer->renderItem(mob, headGear, 0); + this->entityRenderDispatcher->itemInHandRenderer->renderItem( + mob, headGear, 0); - glPopMatrix(); - } + glPopMatrix(); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h index ab003fe68..62a14b0e7 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SnowManRenderer.h @@ -4,14 +4,13 @@ class SnowManModel; -class SnowManRenderer : public MobRenderer -{ +class SnowManRenderer : public MobRenderer { private: - SnowManModel *model; + SnowManModel* model; public: - SnowManRenderer(); + SnowManRenderer(); protected: - virtual void additionalRendering(std::shared_ptr _mob, float a); + virtual void additionalRendering(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp index dcfa2fd1d..527e77034 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.cpp @@ -3,59 +3,63 @@ #include "../Models/SpiderModel.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" -SpiderRenderer::SpiderRenderer() : MobRenderer(new SpiderModel(), 1.0f) -{ - this->setArmor(new SpiderModel()); +SpiderRenderer::SpiderRenderer() : MobRenderer(new SpiderModel(), 1.0f) { + this->setArmor(new SpiderModel()); } -float SpiderRenderer::getFlipDegrees(std::shared_ptr spider) -{ - return 180; +float SpiderRenderer::getFlipDegrees(std::shared_ptr spider) { + return 180; } -int SpiderRenderer::prepareArmor(std::shared_ptr _spider, int layer, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr spider = std::dynamic_pointer_cast(_spider); +int SpiderRenderer::prepareArmor(std::shared_ptr _spider, int layer, + float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr spider = std::dynamic_pointer_cast(_spider); - if (layer!=0) return -1; - MemSect(31); - bindTexture(TN_MOB_SPIDER_EYES); // 4J was L"/mob/spider_eyes.png" - MemSect(0); - // 4J - changes brought forward from 1.8.2 - float br = 1.0f; // was (1-spider->getBrightness(1))*0.5f; + if (layer != 0) return -1; + MemSect(31); + bindTexture(TN_MOB_SPIDER_EYES); // 4J was L"/mob/spider_eyes.png" + MemSect(0); + // 4J - changes brought forward from 1.8.2 + float br = 1.0f; // was (1-spider->getBrightness(1))*0.5f; glEnable(GL_BLEND); - // 4J Stu - We probably don't need to do this on 360 either (as we force it back on the renderer) - // However we do want it off for other platforms that don't force it on in the render lib CBuff handling - // Several texture packs have fully transparent bits that break if this is off + // 4J Stu - We probably don't need to do this on 360 either (as we force it + // back on the renderer) However we do want it off for other platforms that + // don't force it on in the render lib CBuff handling Several texture packs + // have fully transparent bits that break if this is off #ifdef _XBOX glDisable(GL_ALPHA_TEST); #endif - // 4J - changes brought forward from 1.8.2 - glBlendFunc(GL_ONE, GL_ONE); - if (spider->isInvisible()) glDepthMask(false); - else glDepthMask(true); + // 4J - changes brought forward from 1.8.2 + glBlendFunc(GL_ONE, GL_ONE); + if (spider->isInvisible()) + glDepthMask(false); + else + glDepthMask(true); - if (SharedConstants::TEXTURE_LIGHTING) - { - // 4J - was 0xf0f0 but that looks like it is a mistake - maybe meant to be 0xf000f0 to enable both sky & block lighting? choosing 0x00f0 here instead - // as most likely replicates what the java game does, without breaking our lighting (which doesn't like UVs out of the 0 to 255 range) - int col = 0x00f0; + if (SharedConstants::TEXTURE_LIGHTING) { + // 4J - was 0xf0f0 but that looks like it is a mistake - maybe meant to + // be 0xf000f0 to enable both sky & block lighting? choosing 0x00f0 here + // instead as most likely replicates what the java game does, without + // breaking our lighting (which doesn't like UVs out of the 0 to 255 + // range) + int col = 0x00f0; int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); } - // 4J - this doesn't seem right - surely there should be an else in here? + // 4J - this doesn't seem right - surely there should be an else in here? glColor4f(1, 1, 1, br); return 1; } -void SpiderRenderer::scale(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - float scale = mob->getModelScale(); - glScalef(scale, scale, scale); +void SpiderRenderer::scale(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + float scale = mob->getModelScale(); + glScalef(scale, scale, scale); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h index 7946ed467..cf7906472 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SpiderRenderer.h @@ -1,12 +1,12 @@ #pragma once #include "MobRenderer.h" -class SpiderRenderer : public MobRenderer -{ +class SpiderRenderer : public MobRenderer { public: - SpiderRenderer(); + SpiderRenderer(); + protected: - virtual float getFlipDegrees(std::shared_ptr spider); + virtual float getFlipDegrees(std::shared_ptr spider); virtual int prepareArmor(std::shared_ptr _spider, int layer, float a); - void scale(std::shared_ptr _mob, float a); + void scale(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp index 12cb1a2c2..aa140dd6c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.cpp @@ -2,19 +2,19 @@ #include "SquidRenderer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -SquidRenderer::SquidRenderer(Model *model, float shadow) : MobRenderer(model, shadow) -{ +SquidRenderer::SquidRenderer(Model* model, float shadow) + : MobRenderer(model, shadow) {} + +void SquidRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); } -void SquidRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); -} - -void SquidRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +void SquidRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); float bodyXRot = (mob->xBodyRotO + (mob->xBodyRot - mob->xBodyRotO) * a); float bodyZRot = (mob->zBodyRotO + (mob->zBodyRot - mob->zBodyRotO) * a); @@ -26,10 +26,11 @@ void SquidRenderer::setupRotations(std::shared_ptr _mob, float bob, float b glTranslatef(0, -1.2f, 0); } -float SquidRenderer::getBob(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +float SquidRenderer::getBob(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - return mob->oldTentacleAngle + (mob->tentacleAngle - mob->oldTentacleAngle) * a; + return mob->oldTentacleAngle + + (mob->tentacleAngle - mob->oldTentacleAngle) * a; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h index 13270b5f1..0da4dddd8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/SquidRenderer.h @@ -1,15 +1,16 @@ #pragma once #include "MobRenderer.h" -class SquidRenderer : public MobRenderer -{ +class SquidRenderer : public MobRenderer { public: - SquidRenderer(Model *model, float shadow); + SquidRenderer(Model* model, float shadow); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); protected: - virtual void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); + virtual void setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a); virtual float getBob(std::shared_ptr _mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp index a9971f71d..f39b3297c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.cpp @@ -7,123 +7,127 @@ #include "../../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "TheEndPortalRenderer.h" -void TheEndPortalRenderer::render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) -{ - // 4J Convert as we aren't using a templated class - std::shared_ptr table = std::dynamic_pointer_cast(_table); - float xx = (float) (tileEntityRenderDispatcher->xPlayer); - float yy = (float) (tileEntityRenderDispatcher->yPlayer); - float zz = (float) (tileEntityRenderDispatcher->zPlayer); +void TheEndPortalRenderer::render(std::shared_ptr _table, double x, + double y, double z, float a, bool setColor, + float alpha, bool useCompiled) { + // 4J Convert as we aren't using a templated class + std::shared_ptr table = + std::dynamic_pointer_cast(_table); + float xx = (float)(tileEntityRenderDispatcher->xPlayer); + float yy = (float)(tileEntityRenderDispatcher->yPlayer); + float zz = (float)(tileEntityRenderDispatcher->zPlayer); - glDisable(GL_LIGHTING); + glDisable(GL_LIGHTING); - Random random(31100); + Random random(31100); - float hoff = (12) / 16.0f; - for (int i = 0; i < 16; i++) - { - glPushMatrix(); + float hoff = (12) / 16.0f; + for (int i = 0; i < 16; i++) { + glPushMatrix(); - float dist = (16 - (i)); - float sscale = 1 / 16.0f; + float dist = (16 - (i)); + float sscale = 1 / 16.0f; - float br = 1.0f / (dist + 1); - if (i == 0) - { - this->bindTexture(TN_MISC_TUNNEL); // 4J was "/misc/tunnel.png" - br = 0.1f; - dist = 65; - sscale = 1 / 8.0f; - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - if (i == 1) - { - this->bindTexture(TN_MISC_PARTICLEFIELD); // 4J was "/misc/particlefield.png" - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE); - sscale = 1 / 2.0f; - } + float br = 1.0f / (dist + 1); + if (i == 0) { + this->bindTexture(TN_MISC_TUNNEL); // 4J was "/misc/tunnel.png" + br = 0.1f; + dist = 65; + sscale = 1 / 8.0f; + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + if (i == 1) { + this->bindTexture( + TN_MISC_PARTICLEFIELD); // 4J was "/misc/particlefield.png" + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); + sscale = 1 / 2.0f; + } - float dd = (float) -(y + hoff); - { - float ss1 = (float) (dd + Camera::yPlayerOffs); - float ss2 = (float) (dd + dist + Camera::yPlayerOffs); - float s = ss1 / ss2; - s = (float) (y + hoff) + s; + float dd = (float)-(y + hoff); + { + float ss1 = (float)(dd + Camera::yPlayerOffs); + float ss2 = (float)(dd + dist + Camera::yPlayerOffs); + float s = ss1 / ss2; + s = (float)(y + hoff) + s; - glTranslatef(xx, s, zz); - } - // 4J - note that the glTexGeni/glEnable calls don't actually do anything in our opengl wrapper version, everything is currently just inferred from the glTexGen calls. + glTranslatef(xx, s, zz); + } + // 4J - note that the glTexGeni/glEnable calls don't actually do + // anything in our opengl wrapper version, everything is currently just + // inferred from the glTexGen calls. - glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); - glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); + glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); + glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); + glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); + glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); - glTexGen(GL_S, GL_OBJECT_PLANE, getBuffer(1, 0, 0, 0)); - glTexGen(GL_T, GL_OBJECT_PLANE, getBuffer(0, 0, 1, 0)); - glTexGen(GL_R, GL_OBJECT_PLANE, getBuffer(0, 0, 0, 1)); - glTexGen(GL_Q, GL_EYE_PLANE, getBuffer(0, 1, 0, 0)); + glTexGen(GL_S, GL_OBJECT_PLANE, getBuffer(1, 0, 0, 0)); + glTexGen(GL_T, GL_OBJECT_PLANE, getBuffer(0, 0, 1, 0)); + glTexGen(GL_R, GL_OBJECT_PLANE, getBuffer(0, 0, 0, 1)); + glTexGen(GL_Q, GL_EYE_PLANE, getBuffer(0, 1, 0, 0)); - glEnable(GL_TEXTURE_GEN_S); - glEnable(GL_TEXTURE_GEN_T); - glEnable(GL_TEXTURE_GEN_R); - glEnable(GL_TEXTURE_GEN_Q); + glEnable(GL_TEXTURE_GEN_S); + glEnable(GL_TEXTURE_GEN_T); + glEnable(GL_TEXTURE_GEN_R); + glEnable(GL_TEXTURE_GEN_Q); + glPopMatrix(); + glMatrixMode(GL_TEXTURE); - glPopMatrix(); - glMatrixMode(GL_TEXTURE); + glPushMatrix(); + glLoadIdentity(); - glPushMatrix(); - glLoadIdentity(); + glTranslatef(0, (System::currentTimeMillis() % 700000 / 700000.0f), 0); + glScalef(sscale, sscale, sscale); + glTranslatef(0.5f, 0.5f, 0); + glRotatef((i * i * 4321 + i * 9) * 2.0f, 0, 0, 1); + glTranslatef(-0.5f, -0.5f, 0); + glTranslatef(-xx, -zz, -yy); + float ss1 = (float)(dd + Camera::yPlayerOffs); + glTranslatef(Camera::xPlayerOffs * dist / ss1, + Camera::zPlayerOffs * dist / ss1, -yy); - glTranslatef(0, (System::currentTimeMillis() % 700000 / 700000.0f), 0); - glScalef(sscale, sscale, sscale); - glTranslatef(0.5f, 0.5f, 0); - glRotatef((i * i * 4321 + i * 9) * 2.0f, 0, 0, 1); - glTranslatef(-0.5f, -0.5f, 0); - glTranslatef(-xx, -zz, -yy); - float ss1 = (float) (dd + Camera::yPlayerOffs); - glTranslatef(Camera::xPlayerOffs * dist / ss1, Camera::zPlayerOffs * dist / ss1, -yy); + Tesselator* t = Tesselator::getInstance(); + t->useProjectedTexture( + true); // 4J added - turns on both the generation of texture + // coordinates in the vertex shader & perspective divide of + // the texture coord in the pixel shader + t->begin(); - Tesselator *t = Tesselator::getInstance(); - t->useProjectedTexture(true); // 4J added - turns on both the generation of texture coordinates in the vertex shader & perspective divide of the texture coord in the pixel shader - t->begin(); + float r = random.nextFloat() * 0.5f + 0.1f; + float g = random.nextFloat() * 0.5f + 0.4f; + float b = random.nextFloat() * 0.5f + 0.5f; + if (i == 0) r = g = b = 1; + t->color(r * br, g * br, b * br, 1.0f); + t->vertex(x, y + hoff, z); + t->vertex(x, y + hoff, z + 1); + t->vertex(x + 1, y + hoff, z + 1); + t->vertex(x + 1, y + hoff, z); + t->end(); - float r = random.nextFloat() * 0.5f + 0.1f; - float g = random.nextFloat() * 0.5f + 0.4f; - float b = random.nextFloat() * 0.5f + 0.5f; - if (i == 0) r = g = b = 1; - t->color(r * br, g * br, b * br, 1.0f); - t->vertex(x, y + hoff, z); - t->vertex(x, y + hoff, z + 1); - t->vertex(x + 1, y + hoff, z + 1); - t->vertex(x + 1, y + hoff, z); - t->end(); + t->useProjectedTexture(false); // 4J added + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + } + glDisable(GL_BLEND); - t->useProjectedTexture(false); // 4J added - glPopMatrix(); - glMatrixMode(GL_MODELVIEW); - } - glDisable(GL_BLEND); - - glDisable(GL_TEXTURE_GEN_S); - glDisable(GL_TEXTURE_GEN_T); - glDisable(GL_TEXTURE_GEN_R); - glDisable(GL_TEXTURE_GEN_Q); - glEnable(GL_LIGHTING); + glDisable(GL_TEXTURE_GEN_S); + glDisable(GL_TEXTURE_GEN_T); + glDisable(GL_TEXTURE_GEN_R); + glDisable(GL_TEXTURE_GEN_Q); + glEnable(GL_LIGHTING); } -TheEndPortalRenderer::TheEndPortalRenderer() -{ - lb = MemoryTracker::createFloatBuffer(16); +TheEndPortalRenderer::TheEndPortalRenderer() { + lb = MemoryTracker::createFloatBuffer(16); } -FloatBuffer *TheEndPortalRenderer::getBuffer(float a, float b, float c, float d) -{ - lb->clear(); - lb->put(a)->put(b)->put(c)->put(d); - lb->flip(); - return lb; +FloatBuffer* TheEndPortalRenderer::getBuffer(float a, float b, float c, + float d) { + lb->clear(); + lb->put(a)->put(b)->put(c)->put(d); + lb->flip(); + return lb; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h index fe489275e..e2b9ed564 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TheEndPortalRenderer.h @@ -2,15 +2,16 @@ #include "TileEntityRenderer.h" -class TheEndPortalRenderer : public TileEntityRenderer -{ +class TheEndPortalRenderer : public TileEntityRenderer { public: - virtual void render(std::shared_ptr _table, double x, double y, double z, float a, bool setColor, float alpha=1.0f, bool useCompiled = true); + virtual void render(std::shared_ptr _table, double x, double y, + double z, float a, bool setColor, float alpha = 1.0f, + bool useCompiled = true); - FloatBuffer *lb; + FloatBuffer* lb; - TheEndPortalRenderer(); + TheEndPortalRenderer(); private: - FloatBuffer *getBuffer(float a, float b, float c, float d); + FloatBuffer* getBuffer(float a, float b, float c, float d); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp index b55ff111a..9d82d0885 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.cpp @@ -14,89 +14,89 @@ #include "SkullTileRenderer.h" #include "EnderChestRenderer.h" -TileEntityRenderDispatcher *TileEntityRenderDispatcher::instance = NULL; +TileEntityRenderDispatcher* TileEntityRenderDispatcher::instance = NULL; double TileEntityRenderDispatcher::xOff = 0; double TileEntityRenderDispatcher::yOff = 0; double TileEntityRenderDispatcher::zOff = 0; -void TileEntityRenderDispatcher::staticCtor() -{ - instance = new TileEntityRenderDispatcher(); +void TileEntityRenderDispatcher::staticCtor() { + instance = new TileEntityRenderDispatcher(); } -TileEntityRenderDispatcher::TileEntityRenderDispatcher() -{ - // 4J -a dded - font = NULL; +TileEntityRenderDispatcher::TileEntityRenderDispatcher() { + // 4J -a dded + font = NULL; textures = NULL; level = NULL; cameraEntity = nullptr; playerRotY = 0.0f; - playerRotX = 0.0f;; + playerRotX = 0.0f; + ; xPlayer = yPlayer = zPlayer = 0; - glEnable(GL_LIGHTING); - renderers[eTYPE_SIGNTILEENTITY] = new SignRenderer(); - renderers[eTYPE_MOBSPAWNERTILEENTITY] = new MobSpawnerRenderer(); - renderers[eTYPE_PISTONPIECEENTITY] = new PistonPieceRenderer(); - renderers[eTYPE_CHESTTILEENTITY] = new ChestRenderer(); - renderers[eTYPE_ENDERCHESTTILEENTITY] = new EnderChestRenderer(); - renderers[eTYPE_ENCHANTMENTTABLEENTITY] = new EnchantTableRenderer(); - renderers[eTYPE_THEENDPORTALTILEENTITY] = new TheEndPortalRenderer(); - renderers[eTYPE_SKULLTILEENTITY] = new SkullTileRenderer(); - renderers[eTYPE_FURNACETILEENTITY] = NULL; - glDisable(GL_LIGHTING); + glEnable(GL_LIGHTING); + renderers[eTYPE_SIGNTILEENTITY] = new SignRenderer(); + renderers[eTYPE_MOBSPAWNERTILEENTITY] = new MobSpawnerRenderer(); + renderers[eTYPE_PISTONPIECEENTITY] = new PistonPieceRenderer(); + renderers[eTYPE_CHESTTILEENTITY] = new ChestRenderer(); + renderers[eTYPE_ENDERCHESTTILEENTITY] = new EnderChestRenderer(); + renderers[eTYPE_ENCHANTMENTTABLEENTITY] = new EnchantTableRenderer(); + renderers[eTYPE_THEENDPORTALTILEENTITY] = new TheEndPortalRenderer(); + renderers[eTYPE_SKULLTILEENTITY] = new SkullTileRenderer(); + renderers[eTYPE_FURNACETILEENTITY] = NULL; + glDisable(GL_LIGHTING); - AUTO_VAR(itEnd, renderers.end()); - for( classToTileRendererMap::iterator it = renderers.begin(); it != itEnd; it++ ) - { - if(it->second) it->second->init(this); + AUTO_VAR(itEnd, renderers.end()); + for (classToTileRendererMap::iterator it = renderers.begin(); it != itEnd; + it++) { + if (it->second) it->second->init(this); } } -TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(eINSTANCEOF e) -{ - TileEntityRenderer *r = NULL; - //TileEntityRenderer *r = renderers[e]; - AUTO_VAR(it, renderers.find( e )); // 4J Stu - The .at and [] accessors insert elements if they don't exist +TileEntityRenderer* TileEntityRenderDispatcher::getRenderer(eINSTANCEOF e) { + TileEntityRenderer* r = NULL; + // TileEntityRenderer *r = renderers[e]; + AUTO_VAR(it, renderers.find(e)); // 4J Stu - The .at and [] accessors + // insert elements if they don't exist - if( it == renderers.end() ) - { - return NULL; - } - -/* 4J - not doing this hierarchical search anymore. We need to explicitly add renderers for any eINSTANCEOF type that we want to be able to render - if (it == renderers.end() && e != TileEntity::_class) - { - r = getRenderer(dynamic_cast( e->getSuperclass() )); - // 4J - added condition here to only add if a valid renderer found - if( r ) renderers.insert( classToTileRendererMap::value_type( e, r ) ); - //assert(false); + if (it == renderers.end()) { + return NULL; } - else if(it != renderers.end() && e != TileEntity::_class) - r = (*it).second; - */ - return it->second; + /* 4J - not doing this hierarchical search anymore. We need to explicitly + add renderers for any eINSTANCEOF type that we want to be able to render + if (it == renderers.end() && e != TileEntity::_class) + { + r = getRenderer(dynamic_cast( + e->getSuperclass() )); + // 4J - added condition here to only add if a valid renderer + found if( r ) renderers.insert( classToTileRendererMap::value_type( e, r + ) ); + //assert(false); + } + else if(it != renderers.end() && e != TileEntity::_class) + r = (*it).second; + */ + + return it->second; } -bool TileEntityRenderDispatcher::hasRenderer(std::shared_ptr e) -{ - return getRenderer(e) != NULL; +bool TileEntityRenderDispatcher::hasRenderer(std::shared_ptr e) { + return getRenderer(e) != NULL; } -TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(std::shared_ptr e) -{ +TileEntityRenderer* TileEntityRenderDispatcher::getRenderer( + std::shared_ptr e) { if (e == NULL) return NULL; return getRenderer(e->GetType()); } -void TileEntityRenderDispatcher::prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, float a) -{ - if( this->level != level ) - { - setLevel( level ); - } +void TileEntityRenderDispatcher::prepare(Level* level, Textures* textures, + Font* font, + std::shared_ptr player, float a) { + if (this->level != level) { + setLevel(level); + } this->textures = textures; this->cameraEntity = player; this->font = font; @@ -109,21 +109,17 @@ void TileEntityRenderDispatcher::prepare(Level *level, Textures *textures, Font zPlayer = player->zOld + (player->z - player->zOld) * a; } -void TileEntityRenderDispatcher::render(std::shared_ptr e, float a, bool setColor/*=true*/) -{ - if (e->distanceToSqr(xPlayer, yPlayer, zPlayer) < 64 * 64) - { - // 4J - changes brought forward from 1.8.2 - if (SharedConstants::TEXTURE_LIGHTING) - { +void TileEntityRenderDispatcher::render(std::shared_ptr e, float a, + bool setColor /*=true*/) { + if (e->distanceToSqr(xPlayer, yPlayer, zPlayer) < 64 * 64) { + // 4J - changes brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { int col = level->getLightColor(e->x, e->y, e->z, 0); int u = col % 65536; int v = col / 65536; glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); - } - else - { + } else { float br = level->getBrightness(e->x, e->y, e->z); glColor4f(br, br, br, 1); } @@ -131,34 +127,29 @@ void TileEntityRenderDispatcher::render(std::shared_ptr e, float a, } } -void TileEntityRenderDispatcher::render(std::shared_ptr entity, double x, double y, double z, float a, bool setColor/*=true*/, float alpha, bool useCompiled) -{ - TileEntityRenderer *renderer = getRenderer(entity); - if (renderer != NULL) - { +void TileEntityRenderDispatcher::render(std::shared_ptr entity, + double x, double y, double z, float a, + bool setColor /*=true*/, float alpha, + bool useCompiled) { + TileEntityRenderer* renderer = getRenderer(entity); + if (renderer != NULL) { renderer->render(entity, x, y, z, a, setColor, alpha, useCompiled); } } -void TileEntityRenderDispatcher::setLevel(Level *level) -{ - this->level = level; +void TileEntityRenderDispatcher::setLevel(Level* level) { + this->level = level; - for( AUTO_VAR(it, renderers.begin()); it != renderers.end(); it++ ) - { - if(it->second) it->second->onNewLevel(level); - } + for (AUTO_VAR(it, renderers.begin()); it != renderers.end(); it++) { + if (it->second) it->second->onNewLevel(level); + } } -double TileEntityRenderDispatcher::distanceToSqr(double x, double y, double z) -{ +double TileEntityRenderDispatcher::distanceToSqr(double x, double y, double z) { double xd = x - xPlayer; double yd = y - yPlayer; double zd = z - zPlayer; return xd * xd + yd * yd + zd * zd; } -Font *TileEntityRenderDispatcher::getFont() -{ - return font; -} +Font* TileEntityRenderDispatcher::getFont() { return font; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h index 01eaa3652..b23e78aa8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderDispatcher.h @@ -6,41 +6,46 @@ class Level; class TileEntityRenderer; class TileEntity; -class TileEntityRenderDispatcher -{ +class TileEntityRenderDispatcher { public: - static void staticCtor(); // 4J added + static void staticCtor(); // 4J added private: - typedef std::unordered_map classToTileRendererMap; - classToTileRendererMap renderers; + typedef std::unordered_map + classToTileRendererMap; + classToTileRendererMap renderers; public: - static TileEntityRenderDispatcher *instance; + static TileEntityRenderDispatcher* instance; + private: - Font *font; + Font* font; public: - static double xOff, yOff, zOff; + static double xOff, yOff, zOff; - Textures *textures; - Level *level; + Textures* textures; + Level* level; std::shared_ptr cameraEntity; float playerRotY; float playerRotX; double xPlayer, yPlayer, zPlayer; private: - TileEntityRenderDispatcher(); + TileEntityRenderDispatcher(); public: - TileEntityRenderer *getRenderer(eINSTANCEOF e); + TileEntityRenderer* getRenderer(eINSTANCEOF e); bool hasRenderer(std::shared_ptr e); - TileEntityRenderer * getRenderer(std::shared_ptr e); - void prepare(Level *level, Textures *textures, Font *font, std::shared_ptr player, float a); - void render(std::shared_ptr e, float a, bool setColor = true); - void render(std::shared_ptr entity, double x, double y, double z, float a, bool setColor = true, float alpha=1.0f, bool useCompiled = true); // 4J Added useCompiled - void setLevel(Level *level); - double distanceToSqr(double x, double y, double z); - Font *getFont(); + TileEntityRenderer* getRenderer(std::shared_ptr e); + void prepare(Level* level, Textures* textures, Font* font, + std::shared_ptr player, float a); + void render(std::shared_ptr e, float a, bool setColor = true); + void render(std::shared_ptr entity, double x, double y, + double z, float a, bool setColor = true, float alpha = 1.0f, + bool useCompiled = true); // 4J Added useCompiled + void setLevel(Level* level); + double distanceToSqr(double x, double y, double z); + Font* getFont(); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp index 62621fada..08af4cbb7 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.cpp @@ -2,29 +2,26 @@ #include "TileEntityRenderer.h" #include "TileEntityRenderDispatcher.h" -void TileEntityRenderer::bindTexture(int resourceName) -{ - Textures *t = tileEntityRenderDispatcher->textures; - if(t != NULL) t->bind(t->loadTexture(resourceName)); +void TileEntityRenderer::bindTexture(int resourceName) { + Textures* t = tileEntityRenderDispatcher->textures; + if (t != NULL) t->bind(t->loadTexture(resourceName)); } -void TileEntityRenderer::bindTexture(const std::wstring& urlTexture, int backupTexture) -{ - Textures *t = tileEntityRenderDispatcher->textures; - if(t != NULL) t->bind(t->loadHttpTexture(urlTexture, backupTexture)); +void TileEntityRenderer::bindTexture(const std::wstring& urlTexture, + int backupTexture) { + Textures* t = tileEntityRenderDispatcher->textures; + if (t != NULL) t->bind(t->loadHttpTexture(urlTexture, backupTexture)); } -Level *TileEntityRenderer::getLevel() -{ - return tileEntityRenderDispatcher->level; +Level* TileEntityRenderer::getLevel() { + return tileEntityRenderDispatcher->level; } -void TileEntityRenderer::init(TileEntityRenderDispatcher *tileEntityRenderDispatcher) -{ - this->tileEntityRenderDispatcher = tileEntityRenderDispatcher; +void TileEntityRenderer::init( + TileEntityRenderDispatcher* tileEntityRenderDispatcher) { + this->tileEntityRenderDispatcher = tileEntityRenderDispatcher; } -Font *TileEntityRenderer::getFont() -{ - return tileEntityRenderDispatcher->getFont(); +Font* TileEntityRenderer::getFont() { + return tileEntityRenderDispatcher->getFont(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h index e9c4c1887..005ae2c26 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TileEntityRenderer.h @@ -5,19 +5,27 @@ class TileEntity; class Level; class Font; -class TileEntityRenderer -{ +class TileEntityRenderer { protected: - TileEntityRenderDispatcher *tileEntityRenderDispatcher; + TileEntityRenderDispatcher* tileEntityRenderDispatcher; + public: - virtual void render(std::shared_ptr entity, double x, double y, double z, float a, bool setColor, float alpha, bool useCompiled) = 0; // 4J added setColor param and alpha and useCompiled - virtual void onNewLevel(Level *level) {} + virtual void render(std::shared_ptr entity, double x, double y, + double z, float a, bool setColor, float alpha, + bool useCompiled) = 0; // 4J added setColor param and + // alpha and useCompiled + virtual void onNewLevel(Level* level) {} + protected: - void bindTexture(int resourceName); // 4J - changed from std::wstring to int - void bindTexture(const std::wstring& urlTexture, int backupTexture); // 4J - changed from std::wstring to int + void bindTexture( + int resourceName); // 4J - changed from std::wstring to int + void bindTexture( + const std::wstring& urlTexture, + int backupTexture); // 4J - changed from std::wstring to int private: - Level *getLevel(); + Level* getLevel(); + public: - virtual void init(TileEntityRenderDispatcher *tileEntityRenderDispatcher); - Font *getFont(); + virtual void init(TileEntityRenderDispatcher* tileEntityRenderDispatcher); + Font* getFont(); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp index a5961ab02..0b082a170 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.cpp @@ -15,432 +15,429 @@ bool TileRenderer::fancy = true; -const float smallUV = ( 1.0f / 16.0f ); +const float smallUV = (1.0f / 16.0f); -void TileRenderer::_init() -{ - fixedTexture = NULL; - xFlipTexture = false; - noCulling = false; - blsmooth = 1; - applyAmbienceOcclusion = false; - setColor = true; - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; +void TileRenderer::_init() { + fixedTexture = NULL; + xFlipTexture = false; + noCulling = false; + blsmooth = 1; + applyAmbienceOcclusion = false; + setColor = true; + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; - tileShapeX0 = 0.0; - tileShapeX1 = 0.0; - tileShapeY0 = 0.0; - tileShapeY1 = 0.0; - tileShapeZ0 = 0.0; - tileShapeZ1 = 0.0; - fixedShape = false; - smoothShapeLighting = false; - minecraft = Minecraft::GetInstance(); + tileShapeX0 = 0.0; + tileShapeX1 = 0.0; + tileShapeY0 = 0.0; + tileShapeY1 = 0.0; + tileShapeZ0 = 0.0; + tileShapeZ1 = 0.0; + fixedShape = false; + smoothShapeLighting = false; + minecraft = Minecraft::GetInstance(); - xMin = 0; - yMin = 0; - zMin = 0; - cache = NULL; + xMin = 0; + yMin = 0; + zMin = 0; + cache = NULL; } -bool TileRenderer::isTranslucentAt(LevelSource *level, int x, int y, int z) -{ - if( cache ) - { - int id = ( ( x - xMin2) << 10 ) + ( ( y - yMin2 ) << 5 ) + ( z - zMin2 ); - if ( ( id & 0xffff8000) == 0 ) // Check 0 <= id <= 32767 - { - assert (id >= 0 ); - assert (id <= 32 * 32 * 32); - if( cache[id] & cache_isTranslucentAt_valid ) return ( ( cache[id] & cache_isTranslucentAt_flag ) == cache_isTranslucentAt_flag ); +bool TileRenderer::isTranslucentAt(LevelSource* level, int x, int y, int z) { + if (cache) { + int id = ((x - xMin2) << 10) + ((y - yMin2) << 5) + (z - zMin2); + if ((id & 0xffff8000) == 0) // Check 0 <= id <= 32767 + { + assert(id >= 0); + assert(id <= 32 * 32 * 32); + if (cache[id] & cache_isTranslucentAt_valid) + return ((cache[id] & cache_isTranslucentAt_flag) == + cache_isTranslucentAt_flag); - bool ret = Tile::transculent[level->getTile(x,y,z)]; + bool ret = Tile::transculent[level->getTile(x, y, z)]; - if( ret ) - { - cache[id] |= cache_isTranslucentAt_valid | cache_isTranslucentAt_flag; - } - else - { - cache[id] |= cache_isTranslucentAt_valid; - } - return ret; - } - } - return Tile::transculent[level->getTile(x,y,z)]; + if (ret) { + cache[id] |= + cache_isTranslucentAt_valid | cache_isTranslucentAt_flag; + } else { + cache[id] |= cache_isTranslucentAt_valid; + } + return ret; + } + } + return Tile::transculent[level->getTile(x, y, z)]; } -float TileRenderer::getShadeBrightness(Tile *tt, LevelSource *level, int x, int y, int z) -{ - if( cache ) - { - int id = ( ( x - xMin2) << 10 ) + ( ( y - yMin2 ) << 5 ) + ( z - zMin2 ); - if ( ( id & 0xffff8000) == 0 ) // Check 0 <= id <= 32767 - { - if( cache[id] & cache_isSolidBlockingTile_valid ) return ( ( cache[id] & cache_isSolidBlockingTile_flag ) ? 0.2f : 1.0f); +float TileRenderer::getShadeBrightness(Tile* tt, LevelSource* level, int x, + int y, int z) { + if (cache) { + int id = ((x - xMin2) << 10) + ((y - yMin2) << 5) + (z - zMin2); + if ((id & 0xffff8000) == 0) // Check 0 <= id <= 32767 + { + if (cache[id] & cache_isSolidBlockingTile_valid) + return ((cache[id] & cache_isSolidBlockingTile_flag) ? 0.2f + : 1.0f); - bool isSolidBlocking = level->isSolidBlockingTile(x, y, z); + bool isSolidBlocking = level->isSolidBlockingTile(x, y, z); - if( isSolidBlocking ) - { - cache[id] |= cache_isSolidBlockingTile_valid | cache_isSolidBlockingTile_flag; - } - else - { - cache[id] |= cache_isSolidBlockingTile_valid; - } - return ( isSolidBlocking ? 0.2f : 1.0f); - } - } - return tt->getShadeBrightness(level, x, y, z); + if (isSolidBlocking) { + cache[id] |= cache_isSolidBlockingTile_valid | + cache_isSolidBlockingTile_flag; + } else { + cache[id] |= cache_isSolidBlockingTile_valid; + } + return (isSolidBlocking ? 0.2f : 1.0f); + } + } + return tt->getShadeBrightness(level, x, y, z); } -int TileRenderer::getLightColor( Tile *tt, LevelSource *level, int x, int y, int z) -{ - if( cache ) - { - int id = ( ( x - xMin2) << 10 ) + ( ( y - yMin2 ) << 5 ) + ( z - zMin2 ); - if ( ( id & 0xffff8000) == 0 ) // Check 0 <= id <= 32767 - { - // Don't use the cache for liquid tiles, as they are the only type that seem to have their own implementation of getLightColor that actually is important. - // Without this we get patches of dark water where their lighting value is 0, it needs to pull in light from the tile above to work - if( ( tt->id >= Tile::water_Id ) && ( tt->id <= Tile::calmLava_Id ) ) return tt->getLightColor(level, x, y, z); +int TileRenderer::getLightColor(Tile* tt, LevelSource* level, int x, int y, + int z) { + if (cache) { + int id = ((x - xMin2) << 10) + ((y - yMin2) << 5) + (z - zMin2); + if ((id & 0xffff8000) == 0) // Check 0 <= id <= 32767 + { + // Don't use the cache for liquid tiles, as they are the only type + // that seem to have their own implementation of getLightColor that + // actually is important. Without this we get patches of dark water + // where their lighting value is 0, it needs to pull in light from + // the tile above to work + if ((tt->id >= Tile::water_Id) && (tt->id <= Tile::calmLava_Id)) + return tt->getLightColor(level, x, y, z); - if( cache[id] & cache_getLightColor_valid ) return cache[id] & cache_getLightColor_mask; + if (cache[id] & cache_getLightColor_valid) + return cache[id] & cache_getLightColor_mask; - // Not in cache. Have we got the tile type cached? We can pass this as a parameter to Tile::getLightColor( or -1 if we don't) so that underlying things - // don't have to get the tile again. - int tileId = -1; - int xx = x - xMin; - int zz = z - zMin; - if( ( xx >= 0 ) && ( xx <= 15 ) && ( zz >= 0 ) && ( zz <= 15 ) && ( y >= 0 ) && ( y < Level::maxBuildHeight ) ) - { - int indexY = y; - int offset = 0; - if(indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) - { - indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; - offset = Level::COMPRESSED_CHUNK_SECTION_TILES; - } + // Not in cache. Have we got the tile type cached? We can pass this + // as a parameter to Tile::getLightColor( or -1 if we don't) so that + // underlying things don't have to get the tile again. + int tileId = -1; + int xx = x - xMin; + int zz = z - zMin; + if ((xx >= 0) && (xx <= 15) && (zz >= 0) && (zz <= 15) && + (y >= 0) && (y < Level::maxBuildHeight)) { + int indexY = y; + int offset = 0; + if (indexY >= Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { + indexY -= Level::COMPRESSED_CHUNK_SECTION_HEIGHT; + offset = Level::COMPRESSED_CHUNK_SECTION_TILES; + } - unsigned char ucTileId = tileIds[ offset + ( ( ( xx + 0 ) << 11 ) | ( ( zz + 0 ) << 7 ) | ( indexY + 0 ) ) ]; - // Tiles that were determined to be invisible (by being surrounded by solid stuff) will be set to 255 rather than their actual ID - if( ucTileId != 255 ) - { - tileId = (int)ucTileId; - } - } - int ret = tt->getLightColor(level, x, y, z, tileId); - cache[id] |= ( ( ret & cache_getLightColor_mask ) | cache_getLightColor_valid ); - return ret; - } - } - return tt->getLightColor(level, x, y, z); + unsigned char ucTileId = + tileIds[offset + (((xx + 0) << 11) | ((zz + 0) << 7) | + (indexY + 0))]; + // Tiles that were determined to be invisible (by being + // surrounded by solid stuff) will be set to 255 rather than + // their actual ID + if (ucTileId != 255) { + tileId = (int)ucTileId; + } + } + int ret = tt->getLightColor(level, x, y, z, tileId); + cache[id] |= + ((ret & cache_getLightColor_mask) | cache_getLightColor_valid); + return ret; + } + } + return tt->getLightColor(level, x, y, z); } -TileRenderer::TileRenderer( LevelSource* level, int xMin, int yMin, int zMin, unsigned char *tileIds ) -{ - this->level = level; - _init(); - this->xMin = xMin; - this->yMin = yMin; - this->zMin = zMin; - this->xMin2 = xMin-2; - this->yMin2 = yMin-2; - this->zMin2 = zMin-2; - this->tileIds = tileIds; - cache = new unsigned int[32*32*32]; - XMemSet(cache,0,32*32*32*sizeof(unsigned int)); +TileRenderer::TileRenderer(LevelSource* level, int xMin, int yMin, int zMin, + unsigned char* tileIds) { + this->level = level; + _init(); + this->xMin = xMin; + this->yMin = yMin; + this->zMin = zMin; + this->xMin2 = xMin - 2; + this->yMin2 = yMin - 2; + this->zMin2 = zMin - 2; + this->tileIds = tileIds; + cache = new unsigned int[32 * 32 * 32]; + XMemSet(cache, 0, 32 * 32 * 32 * sizeof(unsigned int)); } -TileRenderer::~TileRenderer() -{ - delete[] cache; //4jcraft, changed to [] +TileRenderer::~TileRenderer() { + delete[] cache; // 4jcraft, changed to [] } -TileRenderer::TileRenderer( LevelSource* level ) -{ - this->level = level; - _init(); +TileRenderer::TileRenderer(LevelSource* level) { + this->level = level; + _init(); } -TileRenderer::TileRenderer() -{ - this->level = NULL; - _init(); +TileRenderer::TileRenderer() { + this->level = NULL; + _init(); } -void TileRenderer::setFixedTexture( Icon *fixedTexture ) -{ - this->fixedTexture = fixedTexture; +void TileRenderer::setFixedTexture(Icon* fixedTexture) { + this->fixedTexture = fixedTexture; } -void TileRenderer::clearFixedTexture() -{ - this->fixedTexture = NULL; +void TileRenderer::clearFixedTexture() { this->fixedTexture = NULL; } + +bool TileRenderer::hasFixedTexture() { return fixedTexture != NULL; } + +void TileRenderer::setShape(float x0, float y0, float z0, float x1, float y1, + float z1) { + if (!fixedShape) { + tileShapeX0 = x0; + tileShapeX1 = x1; + tileShapeY0 = y0; + tileShapeY1 = y1; + tileShapeZ0 = z0; + tileShapeZ1 = z1; + smoothShapeLighting = + (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || + tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); + } } -bool TileRenderer::hasFixedTexture() -{ - return fixedTexture != NULL; +void TileRenderer::setShape(Tile* tt) { + if (!fixedShape) { + tileShapeX0 = tt->getShapeX0(); + tileShapeX1 = tt->getShapeX1(); + tileShapeY0 = tt->getShapeY0(); + tileShapeY1 = tt->getShapeY1(); + tileShapeZ0 = tt->getShapeZ0(); + tileShapeZ1 = tt->getShapeZ1(); + smoothShapeLighting = + (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || + tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); + } } -void TileRenderer::setShape(float x0, float y0, float z0, float x1, float y1, float z1) -{ - if (!fixedShape) - { - tileShapeX0 = x0; - tileShapeX1 = x1; - tileShapeY0 = y0; - tileShapeY1 = y1; - tileShapeZ0 = z0; - tileShapeZ1 = z1; - smoothShapeLighting = (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); - } +void TileRenderer::setFixedShape(float x0, float y0, float z0, float x1, + float y1, float z1) { + tileShapeX0 = x0; + tileShapeX1 = x1; + tileShapeY0 = y0; + tileShapeY1 = y1; + tileShapeZ0 = z0; + tileShapeZ1 = z1; + fixedShape = true; + + smoothShapeLighting = + (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || + tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); } -void TileRenderer::setShape(Tile *tt) +void TileRenderer::clearFixedShape() { fixedShape = false; } + +void TileRenderer::tesselateInWorldFixedTexture( + Tile* tile, int x, int y, int z, + Icon* fixedTexture) // 4J renamed to differentiate from tesselateInWorld { - if (!fixedShape) - { - tileShapeX0 = tt->getShapeX0(); - tileShapeX1 = tt->getShapeX1(); - tileShapeY0 = tt->getShapeY0(); - tileShapeY1 = tt->getShapeY1(); - tileShapeZ0 = tt->getShapeZ0(); - tileShapeZ1 = tt->getShapeZ1(); - smoothShapeLighting = (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); - } + this->setFixedTexture(fixedTexture); + tesselateInWorld(tile, x, y, z); + this->clearFixedTexture(); } -void TileRenderer::setFixedShape(float x0, float y0, float z0, float x1, float y1, float z1) +void TileRenderer::tesselateInWorldNoCulling( + Tile* tile, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - tileShapeX0 = x0; - tileShapeX1 = x1; - tileShapeY0 = y0; - tileShapeY1 = y1; - tileShapeZ0 = z0; - tileShapeZ1 = z1; - fixedShape = true; - - smoothShapeLighting = (tileShapeX0 > 0 || tileShapeX1 < 1 || tileShapeY0 > 0 || tileShapeY1 < 1 || tileShapeZ0 > 0 || tileShapeZ1 < 1); + noCulling = true; + tesselateInWorld(tile, x, y, z, forceData); + noCulling = false; } -void TileRenderer::clearFixedShape() +bool TileRenderer::tesselateInWorld( + Tile* tt, int x, int y, int z, int forceData, + std::shared_ptr + forceEntity) // 4J added forceData, forceEntity param { - fixedShape = false; + Tesselator* t = Tesselator::getInstance(); + int shape = tt->getRenderShape(); + tt->updateShape(level, x, y, z, forceData, forceEntity); + // AP - now that the culling is done earlier we don't need to call setShape + // until later on (only for SHAPE_BLOCK) + if (shape != Tile::SHAPE_BLOCK) { + setShape(tt); + } + t->setMipmapEnable(Tile::mipmapEnable[tt->id]); // 4J added + + bool retVal = false; + switch (shape) { + case Tile::SHAPE_BLOCK: { + // 4J - added these faceFlags so we can detect whether this block is + // going to have no visible faces and early out the original code + // checked noCulling and shouldRenderFace directly where faceFlags + // is used now AP - I moved this check from + // tesselateBlockInWorldWithAmbienceOcclusionTexLighting to be even + // earlier to speed up early rejection. The flags are then passed + // down to avoid creating them again. These changes in combination + // have more than halved the time it takes to reject a block on Vita + int faceFlags = 0; + if (noCulling) { + faceFlags = 0x3f; + } else { + // these block types can take advantage of a faster version of + // shouldRenderFace there are others but this is an easy check + // which covers the majority Note: This now covers rock, grass, + // dirt, stoneBrice, wood, sapling, unbreakable, sand, gravel, + // goldOre, ironOre, coalOre, treeTrunk + if ((tt->id <= Tile::unbreakable_Id) || + ((tt->id >= Tile::sand_Id) && + (tt->id <= Tile::treeTrunk_Id))) { + faceFlags = tt->getFaceFlags(level, x, y, z); + } else { + faceFlags |= + tt->shouldRenderFace(level, x, y - 1, z, 0) ? 0x01 : 0; + faceFlags |= + tt->shouldRenderFace(level, x, y + 1, z, 1) ? 0x02 : 0; + faceFlags |= + tt->shouldRenderFace(level, x, y, z - 1, 2) ? 0x04 : 0; + faceFlags |= + tt->shouldRenderFace(level, x, y, z + 1, 3) ? 0x08 : 0; + faceFlags |= + tt->shouldRenderFace(level, x - 1, y, z, 4) ? 0x10 : 0; + faceFlags |= + tt->shouldRenderFace(level, x + 1, y, z, 5) ? 0x20 : 0; + } + } + if (faceFlags == 0) { + retVal = false; + break; + } + + // now we need to set the shape + setShape(tt); + + retVal = tesselateBlockInWorld(tt, x, y, z, faceFlags); + } break; + case Tile::SHAPE_TREE: + retVal = tesselateTreeInWorld(tt, x, y, z); + break; + case Tile::SHAPE_QUARTZ: + retVal = tesselateQuartzInWorld(tt, x, y, z); + break; + case Tile::SHAPE_WATER: + retVal = tesselateWaterInWorld(tt, x, y, z); + break; + case Tile::SHAPE_CACTUS: + retVal = tesselateCactusInWorld(tt, x, y, z); + break; + case Tile::SHAPE_CROSS_TEXTURE: + retVal = tesselateCrossInWorld(tt, x, y, z); + break; + case Tile::SHAPE_STEM: + retVal = tesselateStemInWorld(tt, x, y, z); + break; + case Tile::SHAPE_LILYPAD: + retVal = tesselateLilypadInWorld(tt, x, y, z); + break; + case Tile::SHAPE_ROWS: + retVal = tesselateRowInWorld(tt, x, y, z); + break; + case Tile::SHAPE_TORCH: + retVal = tesselateTorchInWorld(tt, x, y, z); + break; + case Tile::SHAPE_FIRE: + retVal = tesselateFireInWorld((FireTile*)tt, x, y, z); + break; + case Tile::SHAPE_RED_DUST: + retVal = tesselateDustInWorld(tt, x, y, z); + break; + case Tile::SHAPE_LADDER: + retVal = tesselateLadderInWorld(tt, x, y, z); + break; + case Tile::SHAPE_DOOR: + retVal = tesselateDoorInWorld(tt, x, y, z); + break; + case Tile::SHAPE_RAIL: + retVal = tesselateRailInWorld((RailTile*)tt, x, y, z); + break; + case Tile::SHAPE_STAIRS: + retVal = tesselateStairsInWorld((StairTile*)tt, x, y, z); + break; + case Tile::SHAPE_EGG: + retVal = tesselateEggInWorld((EggTile*)tt, x, y, z); + break; + case Tile::SHAPE_FENCE: + retVal = tesselateFenceInWorld((FenceTile*)tt, x, y, z); + break; + case Tile::SHAPE_WALL: + retVal = tesselateWallInWorld((WallTile*)tt, x, y, z); + break; + case Tile::SHAPE_LEVER: + retVal = tesselateLeverInWorld(tt, x, y, z); + break; + case Tile::SHAPE_TRIPWIRE_SOURCE: + retVal = tesselateTripwireSourceInWorld(tt, x, y, z); + break; + case Tile::SHAPE_TRIPWIRE: + retVal = tesselateTripwireInWorld(tt, x, y, z); + break; + case Tile::SHAPE_BED: + retVal = tesselateBedInWorld(tt, x, y, z); + break; + case Tile::SHAPE_DIODE: + retVal = tesselateDiodeInWorld((DiodeTile*)tt, x, y, z); + break; + case Tile::SHAPE_PISTON_BASE: + retVal = tesselatePistonBaseInWorld(tt, x, y, z, false, forceData); + break; + case Tile::SHAPE_PISTON_EXTENSION: + retVal = + tesselatePistonExtensionInWorld(tt, x, y, z, true, forceData); + break; + case Tile::SHAPE_IRON_FENCE: + retVal = tesselateThinFenceInWorld((ThinFenceTile*)tt, x, y, z); + break; + case Tile::SHAPE_VINE: + retVal = tesselateVineInWorld(tt, x, y, z); + break; + case Tile::SHAPE_FENCE_GATE: + retVal = tesselateFenceGateInWorld((FenceGateTile*)tt, x, y, z); + break; + case Tile::SHAPE_CAULDRON: + retVal = tesselateCauldronInWorld((CauldronTile*)tt, x, y, z); + break; + case Tile::SHAPE_FLOWER_POT: + retVal = tesselateFlowerPotInWorld((FlowerPotTile*)tt, x, y, z); + break; + case Tile::SHAPE_ANVIL: + retVal = tesselateAnvilInWorld((AnvilTile*)tt, x, y, z); + break; + case Tile::SHAPE_BREWING_STAND: + retVal = + tesselateBrewingStandInWorld((BrewingStandTile*)tt, x, y, z); + break; + case Tile::SHAPE_PORTAL_FRAME: + retVal = tesselateAirPortalFrameInWorld((TheEndPortalFrameTile*)tt, + x, y, z); + break; + case Tile::SHAPE_COCOA: + retVal = tesselateCocoaInWorld((CocoaTile*)tt, x, y, z); + break; + }; + + t->setMipmapEnable(true); // 4J added + return retVal; } -void TileRenderer::tesselateInWorldFixedTexture( Tile* tile, int x, int y, int z, Icon *fixedTexture ) // 4J renamed to differentiate from tesselateInWorld -{ - this->setFixedTexture(fixedTexture); - tesselateInWorld( tile, x, y, z ); - this->clearFixedTexture(); -} - -void TileRenderer::tesselateInWorldNoCulling( Tile* tile, int x, int y, int z, int forceData, - std::shared_ptr< TileEntity > forceEntity ) // 4J added forceData, forceEntity param -{ - noCulling = true; - tesselateInWorld( tile, x, y, z, forceData ); - noCulling = false; -} - -bool TileRenderer::tesselateInWorld( Tile* tt, int x, int y, int z, int forceData, - std::shared_ptr< TileEntity > forceEntity ) // 4J added forceData, forceEntity param -{ - Tesselator* t = Tesselator::getInstance(); - int shape = tt->getRenderShape(); - tt->updateShape( level, x, y, z, forceData, forceEntity ); - // AP - now that the culling is done earlier we don't need to call setShape until later on (only for SHAPE_BLOCK) - if( shape != Tile::SHAPE_BLOCK ) - { - setShape(tt); - } - t->setMipmapEnable( Tile::mipmapEnable[tt->id] ); // 4J added - - bool retVal = false; - switch(shape) - { - case Tile::SHAPE_BLOCK: - { - // 4J - added these faceFlags so we can detect whether this block is going to have no visible faces and early out - // the original code checked noCulling and shouldRenderFace directly where faceFlags is used now - // AP - I moved this check from tesselateBlockInWorldWithAmbienceOcclusionTexLighting to be even earlier to speed up early rejection. - // The flags are then passed down to avoid creating them again. - // These changes in combination have more than halved the time it takes to reject a block on Vita - int faceFlags = 0; - if ( noCulling ) - { - faceFlags = 0x3f; - } - else - { - // these block types can take advantage of a faster version of shouldRenderFace - // there are others but this is an easy check which covers the majority - // Note: This now covers rock, grass, dirt, stoneBrice, wood, sapling, unbreakable, sand, gravel, goldOre, ironOre, coalOre, treeTrunk - if( ( tt->id <= Tile::unbreakable_Id ) || - ( ( tt->id >= Tile::sand_Id ) && ( tt->id <= Tile::treeTrunk_Id ) ) ) - { - faceFlags = tt->getFaceFlags( level, x, y, z ); - } - else - { - faceFlags |= tt->shouldRenderFace( level, x, y - 1, z, 0 ) ? 0x01 : 0; - faceFlags |= tt->shouldRenderFace( level, x, y + 1, z, 1 ) ? 0x02 : 0; - faceFlags |= tt->shouldRenderFace( level, x, y, z - 1, 2 ) ? 0x04 : 0; - faceFlags |= tt->shouldRenderFace( level, x, y, z + 1, 3 ) ? 0x08 : 0; - faceFlags |= tt->shouldRenderFace( level, x - 1, y, z, 4 ) ? 0x10 : 0; - faceFlags |= tt->shouldRenderFace( level, x + 1, y, z, 5 ) ? 0x20 : 0; - } - } - if ( faceFlags == 0 ) - { - retVal = false; - break; - } - - // now we need to set the shape - setShape(tt); - - retVal = tesselateBlockInWorld( tt, x, y, z, faceFlags ); - } - break; - case Tile::SHAPE_TREE: - retVal = tesselateTreeInWorld(tt, x, y, z); - break; - case Tile::SHAPE_QUARTZ: - retVal = tesselateQuartzInWorld(tt, x, y, z); - break; - case Tile::SHAPE_WATER: - retVal = tesselateWaterInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_CACTUS: - retVal = tesselateCactusInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_CROSS_TEXTURE: - retVal = tesselateCrossInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_STEM: - retVal = tesselateStemInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_LILYPAD: - retVal = tesselateLilypadInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_ROWS: - retVal = tesselateRowInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_TORCH: - retVal = tesselateTorchInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_FIRE: - retVal = tesselateFireInWorld( (FireTile *)tt, x, y, z ); - break; - case Tile::SHAPE_RED_DUST: - retVal = tesselateDustInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_LADDER: - retVal = tesselateLadderInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_DOOR: - retVal = tesselateDoorInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_RAIL: - retVal = tesselateRailInWorld( ( RailTile* )tt, x, y, z ); - break; - case Tile::SHAPE_STAIRS: - retVal = tesselateStairsInWorld( (StairTile *)tt, x, y, z ); - break; - case Tile::SHAPE_EGG: - retVal = tesselateEggInWorld((EggTile*) tt, x, y, z); - break; - case Tile::SHAPE_FENCE: - retVal = tesselateFenceInWorld( ( FenceTile* )tt, x, y, z ); - break; - case Tile::SHAPE_WALL: - retVal = tesselateWallInWorld( (WallTile *) tt, x, y, z); - break; - case Tile::SHAPE_LEVER: - retVal = tesselateLeverInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_TRIPWIRE_SOURCE: - retVal = tesselateTripwireSourceInWorld(tt, x, y, z); - break; - case Tile::SHAPE_TRIPWIRE: - retVal = tesselateTripwireInWorld(tt, x, y, z); - break; - case Tile::SHAPE_BED: - retVal = tesselateBedInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_DIODE: - retVal = tesselateDiodeInWorld( (DiodeTile *)tt, x, y, z ); - break; - case Tile::SHAPE_PISTON_BASE: - retVal = tesselatePistonBaseInWorld( tt, x, y, z, false, forceData ); - break; - case Tile::SHAPE_PISTON_EXTENSION: - retVal = tesselatePistonExtensionInWorld( tt, x, y, z, true, forceData ); - break; - case Tile::SHAPE_IRON_FENCE: - retVal = tesselateThinFenceInWorld( ( ThinFenceTile* )tt, x, y, z ); - break; - case Tile::SHAPE_VINE: - retVal = tesselateVineInWorld( tt, x, y, z ); - break; - case Tile::SHAPE_FENCE_GATE: - retVal = tesselateFenceGateInWorld( ( FenceGateTile* )tt, x, y, z ); - break; - case Tile::SHAPE_CAULDRON: - retVal = tesselateCauldronInWorld((CauldronTile* ) tt, x, y, z); - break; - case Tile::SHAPE_FLOWER_POT: - retVal = tesselateFlowerPotInWorld((FlowerPotTile *) tt, x, y, z); - break; - case Tile::SHAPE_ANVIL: - retVal = tesselateAnvilInWorld((AnvilTile *) tt, x, y, z); - break; - case Tile::SHAPE_BREWING_STAND: - retVal = tesselateBrewingStandInWorld((BrewingStandTile* ) tt, x, y, z); - break; - case Tile::SHAPE_PORTAL_FRAME: - retVal = tesselateAirPortalFrameInWorld((TheEndPortalFrameTile *)tt, x, y, z); - break; - case Tile::SHAPE_COCOA: - retVal = tesselateCocoaInWorld((CocoaTile *) tt, x, y, z); - break; - }; - - - t->setMipmapEnable( true ); // 4J added - return retVal; - -} - -bool TileRenderer::tesselateAirPortalFrameInWorld(TheEndPortalFrameTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateAirPortalFrameInWorld(TheEndPortalFrameTile* tt, + int x, int y, int z) { int data = level->getData(x, y, z); int direction = data & 3; - if (direction == Direction::SOUTH) - { + if (direction == Direction::SOUTH) { upFlip = FLIP_180; - } - else if (direction == Direction::EAST) - { + } else if (direction == Direction::EAST) { upFlip = FLIP_CW; - } - else if (direction == Direction::WEST) - { + } else if (direction == Direction::WEST) { upFlip = FLIP_CCW; } - if (!TheEndPortalFrameTile::hasEye(data)) - { + if (!TheEndPortalFrameTile::hasEye(data)) { setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); tesselateBlockInWorld(tt, x, y, z); @@ -448,283 +445,263 @@ bool TileRenderer::tesselateAirPortalFrameInWorld(TheEndPortalFrameTile *tt, int return true; } - noCulling = true; + noCulling = true; setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); tesselateBlockInWorld(tt, x, y, z); setFixedTexture(tt->getEye()); - setShape(4.0f / 16.0f, 13.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, 1, 12.0f / 16.0f); + setShape(4.0f / 16.0f, 13.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, 1, + 12.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); - noCulling = false; + noCulling = false; clearFixedTexture(); upFlip = FLIP_NONE; return true; } -bool TileRenderer::tesselateBedInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateBedInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - int data = level->getData( x, y, z ); - int direction = BedTile::getDirection( data ); - bool isHead = BedTile::isHeadPiece( data ); + int data = level->getData(x, y, z); + int direction = BedTile::getDirection(data); + bool isHead = BedTile::isHeadPiece(data); - float c10 = 0.5f; - float c11 = 1.0f; - float c2 = 0.8f; - float c3 = 0.6f; + float c10 = 0.5f; + float c11 = 1.0f; + float c2 = 0.8f; + float c3 = 0.6f; - float r11 = c11; - float g11 = c11; - float b11 = c11; + float r11 = c11; + float g11 = c11; + float b11 = c11; - float r10 = c10; - float r2 = c2; - float r3 = c3; + float r10 = c10; + float r2 = c2; + float r3 = c3; - float g10 = c10; - float g2 = c2; - float g3 = c3; + float g10 = c10; + float g2 = c2; + float g3 = c3; - float b10 = c10; - float b2 = c2; - float b3 = c3; + float b10 = c10; + float b2 = c2; + float b3 = c3; - // 4J - change brought forward from 1.8.2 - int centerColor; - float centerBrightness; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + // 4J - change brought forward from 1.8.2 + int centerColor; + float centerBrightness; + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } - // render wooden underside - { - // 4J - change brought forward from 1.8.2 - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( centerColor ); - t->color( r10, g10, b10 ); - } - else - { - t->color( r10 * centerBrightness, g10 * centerBrightness, b10 * centerBrightness ); - } + // render wooden underside + { + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(centerColor); + t->color(r10, g10, b10); + } else { + t->color(r10 * centerBrightness, g10 * centerBrightness, + b10 * centerBrightness); + } - Icon *tex = getTexture( tt, level, x, y, z, Facing::DOWN ); + Icon* tex = getTexture(tt, level, x, y, z, Facing::DOWN); - float u0 = tex->getU0(true); - float u1 = tex->getU1(true); - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float u1 = tex->getU1(true); + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); - float x0 = x + tileShapeX0; - float x1 = x + tileShapeX1; - float y0 = y + tileShapeY0 + 3.0 / 16.0; - float z0 = z + tileShapeZ0; - float z1 = z + tileShapeZ1; + float x0 = x + tileShapeX0; + float x1 = x + tileShapeX1; + float y0 = y + tileShapeY0 + 3.0 / 16.0; + float z0 = z + tileShapeZ0; + float z1 = z + tileShapeZ1; - t->vertexUV( x0 , y0 , z1 , u0 , v1 ); - t->vertexUV( x0 , y0 , z0 , u0 , v0 ); - t->vertexUV( x1 , y0 , z0 , u1 , v0 ); - t->vertexUV( x1 , y0 , z1 , u1 , v1 ); - } + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y0, z1, u1, v1); + } - // render bed top - // 4J - change brought forward from 1.8.2 - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y + 1, z ) ); - t->color( r11, g11, b11 ); - } - else - { - float brightness = tt->getBrightness( level, x, y + 1, z ); - t->color( r11 * brightness, g11 * brightness, b11 * brightness ); - } + // render bed top + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y + 1, z)); + t->color(r11, g11, b11); + } else { + float brightness = tt->getBrightness(level, x, y + 1, z); + t->color(r11 * brightness, g11 * brightness, b11 * brightness); + } - Icon *tex = getTexture( tt, level, x, y, z, Facing::UP ); + Icon* tex = getTexture(tt, level, x, y, z, Facing::UP); - float u0 = tex->getU0(true); - float u1 = tex->getU1(true); - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float u1 = tex->getU1(true); + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); - float topLeftU = u0; - float topRightU = u1; - float topLeftV = v0; - float topRightV = v0; - float bottomLeftU = u0; - float bottomRightU = u1; - float bottomLeftV = v1; - float bottomRightV = v1; + float topLeftU = u0; + float topRightU = u1; + float topLeftV = v0; + float topRightV = v0; + float bottomLeftU = u0; + float bottomRightU = u1; + float bottomLeftV = v1; + float bottomRightV = v1; - if ( direction == Direction::SOUTH ) - { - // rotate 90 degrees clockwise - topRightU = u0; - topLeftV = v1; - bottomLeftU = u1; - bottomRightV = v0; - } - else if ( direction == Direction::NORTH ) - { - // rotate 90 degrees counter-clockwise - topLeftU = u1; - topRightV = v1; - bottomRightU = u0; - bottomLeftV = v0; - } - else if ( direction == Direction::EAST ) - { - // rotate 180 degrees - topLeftU = u1; - topRightV = v1; - bottomRightU = u0; - bottomLeftV = v0; - topRightU = u0; - topLeftV = v1; - bottomLeftU = u1; - bottomRightV = v0; - } + if (direction == Direction::SOUTH) { + // rotate 90 degrees clockwise + topRightU = u0; + topLeftV = v1; + bottomLeftU = u1; + bottomRightV = v0; + } else if (direction == Direction::NORTH) { + // rotate 90 degrees counter-clockwise + topLeftU = u1; + topRightV = v1; + bottomRightU = u0; + bottomLeftV = v0; + } else if (direction == Direction::EAST) { + // rotate 180 degrees + topLeftU = u1; + topRightV = v1; + bottomRightU = u0; + bottomLeftV = v0; + topRightU = u0; + topLeftV = v1; + bottomLeftU = u1; + bottomRightV = v0; + } - float x0 = x + tileShapeX0; - float x1 = x + tileShapeX1; - float y1 = y + tileShapeY1; - float z0 = z + tileShapeZ0; - float z1 = z + tileShapeZ1; + float x0 = x + tileShapeX0; + float x1 = x + tileShapeX1; + float y1 = y + tileShapeY1; + float z0 = z + tileShapeZ0; + float z1 = z + tileShapeZ1; - t->vertexUV( x1 , y1 , z1 , bottomLeftU ,bottomLeftV ); - t->vertexUV( x1 , y1 , z0 , topLeftU , topLeftV ); - t->vertexUV( x0 , y1 , z0 , topRightU ,topRightV ); - t->vertexUV( x0 , y1 , z1 , bottomRightU ,bottomRightV ); + t->vertexUV(x1, y1, z1, bottomLeftU, bottomLeftV); + t->vertexUV(x1, y1, z0, topLeftU, topLeftV); + t->vertexUV(x0, y1, z0, topRightU, topRightV); + t->vertexUV(x0, y1, z1, bottomRightU, bottomRightV); - // determine which edge to skip (the one between foot and head piece) - int skipEdge = Direction::DIRECTION_FACING[direction]; - if ( isHead ) - { - skipEdge = Direction::DIRECTION_FACING[Direction::DIRECTION_OPPOSITE[direction]]; - } - // and which edge to x-flip - int flipEdge = Facing::WEST; - switch ( direction ) - { - case Direction::NORTH: - break; - case Direction::SOUTH: - flipEdge = Facing::EAST; - break; - case Direction::EAST: - flipEdge = Facing::NORTH; - break; - case Direction::WEST: - flipEdge = Facing::SOUTH; - break; - } + // determine which edge to skip (the one between foot and head piece) + int skipEdge = Direction::DIRECTION_FACING[direction]; + if (isHead) { + skipEdge = Direction::DIRECTION_FACING + [Direction::DIRECTION_OPPOSITE[direction]]; + } + // and which edge to x-flip + int flipEdge = Facing::WEST; + switch (direction) { + case Direction::NORTH: + break; + case Direction::SOUTH: + flipEdge = Facing::EAST; + break; + case Direction::EAST: + flipEdge = Facing::NORTH; + break; + case Direction::WEST: + flipEdge = Facing::SOUTH; + break; + } - if ( ( skipEdge != Facing::NORTH ) && ( noCulling || tt->shouldRenderFace( level, x, y, z - 1, Facing::NORTH ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } - xFlipTexture = flipEdge == Facing::NORTH; - renderNorth( tt, x, y, z, getTexture( tt, level, x, y, z, 2 ) ); - } + if ((skipEdge != Facing::NORTH) && + (noCulling || + tt->shouldRenderFace(level, x, y, z - 1, Facing::NORTH))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } + xFlipTexture = flipEdge == Facing::NORTH; + renderNorth(tt, x, y, z, getTexture(tt, level, x, y, z, 2)); + } - if ( ( skipEdge != Facing::SOUTH ) && ( noCulling || tt->shouldRenderFace( level, x, y, z + 1, Facing::SOUTH ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } + if ((skipEdge != Facing::SOUTH) && + (noCulling || + tt->shouldRenderFace(level, x, y, z + 1, Facing::SOUTH))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } - xFlipTexture = flipEdge == Facing::SOUTH; - renderSouth( tt, x, y, z, getTexture( tt, level, x, y, z, 3 ) ); - } + xFlipTexture = flipEdge == Facing::SOUTH; + renderSouth(tt, x, y, z, getTexture(tt, level, x, y, z, 3)); + } - if ( ( skipEdge != Facing::WEST ) && ( noCulling || tt->shouldRenderFace( level, x - 1, y, z, Facing::WEST ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - xFlipTexture = flipEdge == Facing::WEST; - renderWest( tt, x, y, z, getTexture( tt, level, x, y, z, 4 ) ); - } - - if ( ( skipEdge != Facing::EAST ) && ( noCulling || tt->shouldRenderFace( level, x + 1, y, z, Facing::EAST ) ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - xFlipTexture = flipEdge == Facing::EAST; - renderEast( tt, x, y, z, getTexture( tt, level, x, y, z, 5 ) ); - } - xFlipTexture = false; - return true; + if ((skipEdge != Facing::WEST) && + (noCulling || tt->shouldRenderFace(level, x - 1, y, z, Facing::WEST))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + xFlipTexture = flipEdge == Facing::WEST; + renderWest(tt, x, y, z, getTexture(tt, level, x, y, z, 4)); + } + if ((skipEdge != Facing::EAST) && + (noCulling || tt->shouldRenderFace(level, x + 1, y, z, Facing::EAST))) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + xFlipTexture = flipEdge == Facing::EAST; + renderEast(tt, x, y, z, getTexture(tt, level, x, y, z, 5)); + } + xFlipTexture = false; + return true; } -bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile* tt, int x, + int y, int z) { // bounding box first - setShape(7.0f / 16.0f, 0.0f, 7.0f / 16.0f, 9.0f / 16.0f, 14.0f / 16.0f, 9.0f / 16.0f); + setShape(7.0f / 16.0f, 0.0f, 7.0f / 16.0f, 9.0f / 16.0f, 14.0f / 16.0f, + 9.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); setFixedTexture(tt->getBaseTexture()); - setShape(9.0f / 16.0f, 0.0f, 5.0f / 16.0f, 15.0f / 16.0f, 2 / 16.0f, 11.0f / 16.0f); + setShape(9.0f / 16.0f, 0.0f, 5.0f / 16.0f, 15.0f / 16.0f, 2 / 16.0f, + 11.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); - setShape(2.0f / 16.0f, 0.0f, 1.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, 7.0f / 16.0f); + setShape(2.0f / 16.0f, 0.0f, 1.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, + 7.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); - setShape(2.0f / 16.0f, 0.0f, 9.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, 15.0f / 16.0f); + setShape(2.0f / 16.0f, 0.0f, 9.0f / 16.0f, 8.0f / 16.0f, 2 / 16.0f, + 15.0f / 16.0f); tesselateBlockInWorld(tt, x, y, z); clearFixedTexture(); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); float br; - if (SharedConstants::TEXTURE_LIGHTING) - { + if (SharedConstants::TEXTURE_LIGHTING) { t->tex2(getLightColor(tt, level, x, y, z)); br = 1; - } - else - { + } else { br = tt->getBrightness(level, x, y, z); } int col = tt->getColor(level, x, y, z); @@ -734,30 +711,27 @@ bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int t->color(br * r, br * g, br * b); - Icon *tex = getTexture(tt, 0, 0); + Icon* tex = getTexture(tt, 0, 0); - if (hasFixedTexture()) tex = fixedTexture; - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); int data = level->getData(x, y, z); - for (int arm = 0; arm < 3; arm++) - { - + for (int arm = 0; arm < 3; arm++) { float angle = arm * PI * 2.0f / 3.0f + PI * 0.5f; - float u0 = tex->getU(8, true); - float u1 = tex->getU1(true); - if ((data & (1 << arm)) != 0) - { + float u0 = tex->getU(8, true); + float u1 = tex->getU1(true); + if ((data & (1 << arm)) != 0) { u1 = tex->getU0(true); } - float x0 = x + 8.0f / 16.0f; - float x1 = x + 8.0f / 16.0f + sin(angle) * 8.0f / 16.0f; - float z0 = z + 8.0f / 16.0f; - float z1 = z + 8.0f / 16.0f + cos(angle) * 8.0f / 16.0f; + float x0 = x + 8.0f / 16.0f; + float x1 = x + 8.0f / 16.0f + sin(angle) * 8.0f / 16.0f; + float z0 = z + 8.0f / 16.0f; + float z1 = z + 8.0f / 16.0f + cos(angle) * 8.0f / 16.0f; t->vertexUV(x0, y + 1.0f, z0, u0, v0); t->vertexUV(x0, y + 0.0f, z0, u0, v1); @@ -775,21 +749,18 @@ bool TileRenderer::tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int return true; } -bool TileRenderer::tesselateCauldronInWorld(CauldronTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateCauldronInWorld(CauldronTile* tt, int x, int y, + int z) { // bounding box first tesselateBlockInWorld(tt, x, y, z); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); float br; - if (SharedConstants::TEXTURE_LIGHTING) - { + if (SharedConstants::TEXTURE_LIGHTING) { t->tex2(getLightColor(tt, level, x, y, z)); br = 1; - } - else - { + } else { br = tt->getBrightness(level, x, y, z); } int col = tt->getColor(level, x, y, z); @@ -800,3034 +771,3032 @@ bool TileRenderer::tesselateCauldronInWorld(CauldronTile *tt, int x, int y, int t->color(br * r, br * g, br * b); // render inside - Icon *insideTex = tt->getTexture(Facing::NORTH); - const float cWidth = ( 2.0f / 16.0f ) - ( 1.0f / 128.0f ); // 4J - Moved by 1/128th (smallest movement possible with our vertex storage) to remove gap at edge of cauldron + Icon* insideTex = tt->getTexture(Facing::NORTH); + const float cWidth = + (2.0f / 16.0f) - + (1.0f / + 128.0f); // 4J - Moved by 1/128th (smallest movement possible with our + // vertex storage) to remove gap at edge of cauldron renderEast(tt, x - 1.0f + cWidth, y, z, insideTex); renderWest(tt, x + 1.0f - cWidth, y, z, insideTex); renderSouth(tt, x, y, z - 1.0f + cWidth, insideTex); renderNorth(tt, x, y, z + 1.0f - cWidth, insideTex); - Icon *bottomTex = CauldronTile::getTexture(CauldronTile::TEXTURE_INSIDE); + Icon* bottomTex = CauldronTile::getTexture(CauldronTile::TEXTURE_INSIDE); renderFaceUp(tt, x, y - 1.0f + 4.0f / 16.0f, z, bottomTex); renderFaceDown(tt, x, y + 1.0f - 12.0f / 16.0f, z, bottomTex); int waterLevel = level->getData(x, y, z); - if (waterLevel > 0) - { - Icon *liquidTex = LiquidTile::getTexture(LiquidTile::TEXTURE_WATER_STILL); + if (waterLevel > 0) { + Icon* liquidTex = + LiquidTile::getTexture(LiquidTile::TEXTURE_WATER_STILL); - if (waterLevel > 3) - { + if (waterLevel > 3) { waterLevel = 3; } - renderFaceUp(tt, x, y - 1.0f + (6.0f + waterLevel * 3.0f) / 16.0f, z, liquidTex); + renderFaceUp(tt, x, y - 1.0f + (6.0f + waterLevel * 3.0f) / 16.0f, z, + liquidTex); } return true; - } -bool TileRenderer::tesselateFlowerPotInWorld(FlowerPotTile *tt, int x, int y, int z) -{ - // bounding box first - tesselateBlockInWorld(tt, x, y, z); +bool TileRenderer::tesselateFlowerPotInWorld(FlowerPotTile* tt, int x, int y, + int z) { + // bounding box first + tesselateBlockInWorld(tt, x, y, z); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - float br; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - br = 1; - } - else - { - br = tt->getBrightness(level, x, y, z); - } - int col = tt->getColor(level, x, y, z); - Icon *tex = getTexture(tt, 0); - float r = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + Icon* tex = getTexture(tt, 0); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if (GameRenderer::anaglyph3d) - { - float cr = (r * 30 + g * 59 + b * 11) / 100; - float cg = (r * 30 + g * 70) / (100); - float cb = (r * 30 + b * 70) / (100); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color(br * r, br * g, br * b); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - // render inside + // render inside - float halfWidth = (6.0f / 16.0f) / 2 - 0.001f; - renderEast(tt, x - 0.5f + halfWidth, y, z, tex); - renderWest(tt, x + 0.5f - halfWidth, y, z, tex); - renderSouth(tt, x, y, z - 0.5f + halfWidth, tex); - renderNorth(tt, x, y, z + 0.5f - halfWidth, tex); + float halfWidth = (6.0f / 16.0f) / 2 - 0.001f; + renderEast(tt, x - 0.5f + halfWidth, y, z, tex); + renderWest(tt, x + 0.5f - halfWidth, y, z, tex); + renderSouth(tt, x, y, z - 0.5f + halfWidth, tex); + renderNorth(tt, x, y, z + 0.5f - halfWidth, tex); - renderFaceUp(tt, x, y - 0.5f + halfWidth + 3.0f / 16.0f, z, getTexture(Tile::dirt)); + renderFaceUp(tt, x, y - 0.5f + halfWidth + 3.0f / 16.0f, z, + getTexture(Tile::dirt)); - int type = level->getData(x, y, z); + int type = level->getData(x, y, z); - if (type != 0) - { - float xOff = 0; - float yOff = 4; - float zOff = 0; - Tile *plant = NULL; + if (type != 0) { + float xOff = 0; + float yOff = 4; + float zOff = 0; + Tile* plant = NULL; - switch (type) - { - case FlowerPotTile::TYPE_FLOWER_RED: - plant = Tile::rose; - break; - case FlowerPotTile::TYPE_FLOWER_YELLOW: - plant = Tile::flower; - break; - case FlowerPotTile::TYPE_MUSHROOM_BROWN: - plant = Tile::mushroom1; - break; - case FlowerPotTile::TYPE_MUSHROOM_RED: - plant = Tile::mushroom2; - break; - } + switch (type) { + case FlowerPotTile::TYPE_FLOWER_RED: + plant = Tile::rose; + break; + case FlowerPotTile::TYPE_FLOWER_YELLOW: + plant = Tile::flower; + break; + case FlowerPotTile::TYPE_MUSHROOM_BROWN: + plant = Tile::mushroom1; + break; + case FlowerPotTile::TYPE_MUSHROOM_RED: + plant = Tile::mushroom2; + break; + } - t->addOffset(xOff / 16.0f, yOff / 16.0f, zOff / 16.0f); + t->addOffset(xOff / 16.0f, yOff / 16.0f, zOff / 16.0f); - if (plant != NULL) - { - tesselateInWorld(plant, x, y, z); - } - else - { - if (type == FlowerPotTile::TYPE_CACTUS) - { + if (plant != NULL) { + tesselateInWorld(plant, x, y, z); + } else { + if (type == FlowerPotTile::TYPE_CACTUS) { + // Force drawing of all faces else the cactus misses faces + // when a block is adjacent + noCulling = true; - // Force drawing of all faces else the cactus misses faces - // when a block is adjacent - noCulling = true; + float halfSize = 0.25f / 2; + setShape(0.5f - halfSize, 0.0f, 0.5f - halfSize, + 0.5f + halfSize, 0.25f, 0.5f + halfSize); + tesselateBlockInWorld(Tile::cactus, x, y, z); + setShape(0.5f - halfSize, 0.25f, 0.5f - halfSize, + 0.5f + halfSize, 0.5f, 0.5f + halfSize); + tesselateBlockInWorld(Tile::cactus, x, y, z); + setShape(0.5f - halfSize, 0.5f, 0.5f - halfSize, + 0.5f + halfSize, 0.75f, 0.5f + halfSize); + tesselateBlockInWorld(Tile::cactus, x, y, z); - float halfSize = 0.25f / 2; - setShape(0.5f - halfSize, 0.0f, 0.5f - halfSize, 0.5f + halfSize, 0.25f, 0.5f + halfSize); - tesselateBlockInWorld(Tile::cactus, x, y, z); - setShape(0.5f - halfSize, 0.25f, 0.5f - halfSize, 0.5f + halfSize, 0.5f, 0.5f + halfSize); - tesselateBlockInWorld(Tile::cactus, x, y, z); - setShape(0.5f - halfSize, 0.5f, 0.5f - halfSize, 0.5f + halfSize, 0.75f, 0.5f + halfSize); - tesselateBlockInWorld(Tile::cactus, x, y, z); + noCulling = false; - noCulling = false; + setShape(0, 0, 0, 1, 1, 1); + } else if (type == FlowerPotTile::TYPE_SAPLING_DEFAULT) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_DEFAULT, x, + y, z, 0.75f); + } else if (type == FlowerPotTile::TYPE_SAPLING_BIRCH) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_BIRCH, x, y, + z, 0.75f); + } else if (type == FlowerPotTile::TYPE_SAPLING_EVERGREEN) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_EVERGREEN, x, + y, z, 0.75f); + } else if (type == FlowerPotTile::TYPE_SAPLING_JUNGLE) { + tesselateCrossTexture(Tile::sapling, Sapling::TYPE_JUNGLE, x, y, + z, 0.75f); + } else if (type == FlowerPotTile::TYPE_FERN) { + col = Tile::tallgrass->getColor(level, x, y, z); + r = ((col >> 16) & 0xff) / 255.0f; + g = ((col >> 8) & 0xff) / 255.0f; + b = ((col) & 0xff) / 255.0f; + t->color(br * r, br * g, br * b); + tesselateCrossTexture(Tile::tallgrass, TallGrass::FERN, x, y, z, + 0.75f); + } else if (type == FlowerPotTile::TYPE_DEAD_BUSH) { + tesselateCrossTexture(Tile::deadBush, TallGrass::FERN, x, y, z, + 0.75f); + } + } - setShape(0, 0, 0, 1, 1, 1); - } - else if (type == FlowerPotTile::TYPE_SAPLING_DEFAULT) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_DEFAULT, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_SAPLING_BIRCH) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_BIRCH, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_SAPLING_EVERGREEN) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_EVERGREEN, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_SAPLING_JUNGLE) - { - tesselateCrossTexture(Tile::sapling, Sapling::TYPE_JUNGLE, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_FERN) - { - col = Tile::tallgrass->getColor(level, x, y, z); - r = ((col >> 16) & 0xff) / 255.0f; - g = ((col >> 8) & 0xff) / 255.0f; - b = ((col) & 0xff) / 255.0f; - t->color(br * r, br * g, br * b); - tesselateCrossTexture(Tile::tallgrass, TallGrass::FERN, x, y, z, 0.75f); - } - else if (type == FlowerPotTile::TYPE_DEAD_BUSH) - { - tesselateCrossTexture(Tile::deadBush, TallGrass::FERN, x, y, z, 0.75f); - } - } + t->addOffset(-xOff / 16.0f, -yOff / 16.0f, -zOff / 16.0f); + } - t->addOffset(-xOff / 16.0f, -yOff / 16.0f, -zOff / 16.0f); - } - - return true; + return true; } -bool TileRenderer::tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z) -{ - return tesselateAnvilInWorld(tt, x, y, z, level->getData(x, y, z)); - +bool TileRenderer::tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z) { + return tesselateAnvilInWorld(tt, x, y, z, level->getData(x, y, z)); } -bool TileRenderer::tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, + int data) { + Tesselator* t = Tesselator::getInstance(); - float br; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - br = 1; - } - else - { - br = tt->getBrightness(level, x, y, z); - } - int col = tt->getColor(level, x, y, z); - float r = ((col >> 16) & 0xff) / 255.0f; - float g = ((col >> 8) & 0xff) / 255.0f; - float b = ((col) & 0xff) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if (GameRenderer::anaglyph3d) - { - float cr = (r * 30 + g * 59 + b * 11) / 100; - float cg = (r * 30 + g * 70) / (100); - float cb = (r * 30 + b * 70) / (100); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color(br * r, br * g, br * b); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - return tesselateAnvilInWorld(tt, x, y, z, data, false); + return tesselateAnvilInWorld(tt, x, y, z, data, false); } -bool TileRenderer::tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data, bool render) -{ - int facing = render ? 0 : data & 3; - bool rotate = false; - float bottom = 0; +bool TileRenderer::tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, + int data, bool render) { + int facing = render ? 0 : data & 3; + bool rotate = false; + float bottom = 0; - switch (facing) - { - case Direction::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - break; - case Direction::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - break; - case Direction::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - rotate = true; - break; - case Direction::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - rotate = true; - break; - } + switch (facing) { + case Direction::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + break; + case Direction::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + break; + case Direction::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + rotate = true; + break; + case Direction::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + rotate = true; + break; + } - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_BASE, bottom, 12.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, rotate, render, data); - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_JOINT, bottom, 8.0f / 16.0f, 1.0f / 16.0f, 10.0f / 16.0f, rotate, render, data); - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_COLUMN, bottom, 4.0f / 16.0f, 5.0f / 16.0f, 8.0f / 16.0f, rotate, render, data); - bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_TOP, bottom, 10.0f / 16.0f, 6.0f / 16.0f, 16.0f / 16.0f, rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_BASE, bottom, + 12.0f / 16.0f, 4.0f / 16.0f, 12.0f / 16.0f, + rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_JOINT, bottom, + 8.0f / 16.0f, 1.0f / 16.0f, 10.0f / 16.0f, + rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_COLUMN, bottom, + 4.0f / 16.0f, 5.0f / 16.0f, 8.0f / 16.0f, + rotate, render, data); + bottom = tesselateAnvilPiece(tt, x, y, z, AnvilTile::PART_TOP, bottom, + 10.0f / 16.0f, 6.0f / 16.0f, 16.0f / 16.0f, + rotate, render, data); - setShape(0, 0, 0, 1, 1, 1); - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; + setShape(0, 0, 0, 1, 1, 1); + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; - return true; + return true; } -float TileRenderer::tesselateAnvilPiece(AnvilTile *tt, int x, int y, int z, int part, float bottom, float width, float height, float length, bool rotate, bool render, int data) -{ - if (rotate) - { - float swap = width; - width = length; - length = swap; - } +float TileRenderer::tesselateAnvilPiece(AnvilTile* tt, int x, int y, int z, + int part, float bottom, float width, + float height, float length, bool rotate, + bool render, int data) { + if (rotate) { + float swap = width; + width = length; + length = swap; + } - width /= 2; - length /= 2; + width /= 2; + length /= 2; - tt->part = part; - setShape(0.5f - width, bottom, 0.5f - length, 0.5f + width, bottom + height, 0.5f + length); + tt->part = part; + setShape(0.5f - width, bottom, 0.5f - length, 0.5f + width, bottom + height, + 0.5f + length); - if (render) - { - Tesselator *t = Tesselator::getInstance(); - t->begin(); - t->normal(0, -1, 0); - renderFaceDown(tt, 0, 0, 0, getTexture(tt, 0, data)); - t->end(); + if (render) { + Tesselator* t = Tesselator::getInstance(); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tt, 0, 0, 0, getTexture(tt, 0, data)); + t->end(); - t->begin(); - t->normal(0, 1, 0); - renderFaceUp(tt, 0, 0, 0, getTexture(tt, 1, data)); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tt, 0, 0, 0, getTexture(tt, 1, data)); + t->end(); - t->begin(); - t->normal(0, 0, -1); - renderNorth(tt, 0, 0, 0, getTexture(tt, 2, data)); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tt, 0, 0, 0, getTexture(tt, 2, data)); + t->end(); - t->begin(); - t->normal(0, 0, 1); - renderSouth(tt, 0, 0, 0, getTexture(tt, 3, data)); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tt, 0, 0, 0, getTexture(tt, 3, data)); + t->end(); - t->begin(); - t->normal(-1, 0, 0); - renderWest(tt, 0, 0, 0, getTexture(tt, 4, data)); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tt, 0, 0, 0, getTexture(tt, 4, data)); + t->end(); - t->begin(); - t->normal(1, 0, 0); - renderEast(tt, 0, 0, 0, getTexture(tt, 5, data)); - t->end(); - } - else - { - tesselateBlockInWorld(tt, x, y, z); - } + t->begin(); + t->normal(1, 0, 0); + renderEast(tt, 0, 0, 0, getTexture(tt, 5, data)); + t->end(); + } else { + tesselateBlockInWorld(tt, x, y, z); + } - return bottom + height; + return bottom + height; } -bool TileRenderer::tesselateTorchInWorld( Tile* tt, int x, int y, int z ) -{ - int dir = level->getData( x, y, z ); +bool TileRenderer::tesselateTorchInWorld(Tile* tt, int x, int y, int z) { + int dir = level->getData(x, y, z); - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( br, br, br ); - } - - float r = 0.40f; - float r2 = 0.5f - r; - float h = 0.20f; - if ( dir == 1 ) - { - tesselateTorch( tt, (float)x - r2, (float)y + h, (float)z, -r, 0.0f, 0 ); - } - else if ( dir == 2 ) - { - tesselateTorch( tt, (float)x + r2, (float)y + h, (float)z, +r, 0.0f, 0 ); - } - else if ( dir == 3 ) - { - tesselateTorch( tt, (float)x, (float)y + h, z - r2, 0.0f, -r, 0 ); - } - else if ( dir == 4 ) - { - tesselateTorch( tt, (float)x, (float)y + h, (float)z + r2, 0.0f, +r, 0 ); - } - else - { - tesselateTorch( tt, (float)x, (float)y, (float)z, 0.0f, 0.0f, 0 ); - } - return true; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + } + float r = 0.40f; + float r2 = 0.5f - r; + float h = 0.20f; + if (dir == 1) { + tesselateTorch(tt, (float)x - r2, (float)y + h, (float)z, -r, 0.0f, 0); + } else if (dir == 2) { + tesselateTorch(tt, (float)x + r2, (float)y + h, (float)z, +r, 0.0f, 0); + } else if (dir == 3) { + tesselateTorch(tt, (float)x, (float)y + h, z - r2, 0.0f, -r, 0); + } else if (dir == 4) { + tesselateTorch(tt, (float)x, (float)y + h, (float)z + r2, 0.0f, +r, 0); + } else { + tesselateTorch(tt, (float)x, (float)y, (float)z, 0.0f, 0.0f, 0); + } + return true; } -bool TileRenderer::tesselateDiodeInWorld(DiodeTile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - tesselateDiodeInWorld(tt, x, y, z, level->getData(x, y, z) & DiodeTile::DIRECTION_MASK); + tesselateDiodeInWorld(tt, x, y, z, + level->getData(x, y, z) & DiodeTile::DIRECTION_MASK); - return true; + return true; } -void TileRenderer::tesselateDiodeInWorld( DiodeTile* tt, int x, int y, int z, int dir ) -{ - // render half-block edges - tesselateBlockInWorld( tt, x, y, z ); +void TileRenderer::tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z, + int dir) { + // render half-block edges + tesselateBlockInWorld(tt, x, y, z); - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( br, br, br ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + } - int data = level->getData(x, y, z); + int data = level->getData(x, y, z); - // 4J Stu - This block gets moved in a later version, but we don't need that yet - // BEGIN TORCH SECTION - { - int dir = data & DiodeTile::DIRECTION_MASK; - int delay = ( data & DiodeTile::DELAY_MASK ) >> DiodeTile::DELAY_SHIFT; - float h = -3.0f / 16.0f; - float transmitterX = 0.0f; - float transmitterZ = 0.0f; - float receiverX = 0.0f; - float receiverZ = 0.0f; + // 4J Stu - This block gets moved in a later version, but we don't need that + // yet BEGIN TORCH SECTION + { + int dir = data & DiodeTile::DIRECTION_MASK; + int delay = (data & DiodeTile::DELAY_MASK) >> DiodeTile::DELAY_SHIFT; + float h = -3.0f / 16.0f; + float transmitterX = 0.0f; + float transmitterZ = 0.0f; + float receiverX = 0.0f; + float receiverZ = 0.0f; - switch ( dir ) - { - case Direction::SOUTH: - receiverZ = -5.0f / 16.0f; - transmitterZ = DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::NORTH: - receiverZ = 5.0f / 16.0f; - transmitterZ = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::EAST: - receiverX = -5.0f / 16.0f; - transmitterX = DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - case Direction::WEST: - receiverX = 5.0f / 16.0f; - transmitterX = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; - break; - } + switch (dir) { + case Direction::SOUTH: + receiverZ = -5.0f / 16.0f; + transmitterZ = DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::NORTH: + receiverZ = 5.0f / 16.0f; + transmitterZ = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::EAST: + receiverX = -5.0f / 16.0f; + transmitterX = DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + case Direction::WEST: + receiverX = 5.0f / 16.0f; + transmitterX = -DiodeTile::DELAY_RENDER_OFFSETS[delay]; + break; + } - // render transmitter - tesselateTorch( tt, x + transmitterX, y + h, z + transmitterZ, 0.0f, 0.0f, 0 ); - // render receiver - tesselateTorch( tt, x + receiverX, y + h, z + receiverZ, 0.0f, 0.0f, 0 ); - } - // END TORCH SECTION + // render transmitter + tesselateTorch(tt, x + transmitterX, y + h, z + transmitterZ, 0.0f, + 0.0f, 0); + // render receiver + tesselateTorch(tt, x + receiverX, y + h, z + receiverZ, 0.0f, 0.0f, 0); + } + // END TORCH SECTION - Icon *tex = getTexture(tt, Facing::UP, data); - float u0 = tex->getU0(true); - float u1 = tex->getU1(true); - float v0 = tex->getV0(true); - float v1 = tex->getV1(true); + Icon* tex = getTexture(tt, Facing::UP, data); + float u0 = tex->getU0(true); + float u1 = tex->getU1(true); + float v0 = tex->getV0(true); + float v1 = tex->getV1(true); - float r = 2.0f / 16.0f; + float r = 2.0f / 16.0f; - float x0 = ( float )( x + 1.0f ); - float x1 = ( float )( x + 1.0f ); - float x2 = ( float )( x + 0.0f ); - float x3 = ( float )( x + 0.0f ); + float x0 = (float)(x + 1.0f); + float x1 = (float)(x + 1.0f); + float x2 = (float)(x + 0.0f); + float x3 = (float)(x + 0.0f); - float z0 = ( float )( z + 0.0f ); - float z1 = ( float )( z + 1.0f ); - float z2 = ( float )( z + 1.0f ); - float z3 = ( float )( z + 0.0f ); + float z0 = (float)(z + 0.0f); + float z1 = (float)(z + 1.0f); + float z2 = (float)(z + 1.0f); + float z3 = (float)(z + 0.0f); - float y0 = ( float )( y + r ); + float y0 = (float)(y + r); - if ( dir == Direction::NORTH ) - { - // rotate 180 degrees - x0 = x1 = ( float )( x + 0.0f ); - x2 = x3 = ( float )( x + 1.0f ); - z0 = z3 = ( float )( z + 1.0f ); - z1 = z2 = ( float )( z + 0.0f ); - } - else if ( dir == Direction::EAST ) - { - // rotate 90 degrees counter-clockwise - x0 = x3 = ( float )( x + 0.0f ); - x1 = x2 = ( float )( x + 1.0f ); - z0 = z1 = ( float )( z + 0.0f ); - z2 = z3 = ( float )( z + 1.0f ); - } - else if ( dir == Direction::WEST ) - { - // rotate 90 degrees clockwise - x0 = x3 = ( float )( x + 1.0f ); - x1 = x2 = ( float )( x + 0.0f ); - z0 = z1 = ( float )( z + 1.0f ); - z2 = z3 = ( float )( z + 0.0f ); - } + if (dir == Direction::NORTH) { + // rotate 180 degrees + x0 = x1 = (float)(x + 0.0f); + x2 = x3 = (float)(x + 1.0f); + z0 = z3 = (float)(z + 1.0f); + z1 = z2 = (float)(z + 0.0f); + } else if (dir == Direction::EAST) { + // rotate 90 degrees counter-clockwise + x0 = x3 = (float)(x + 0.0f); + x1 = x2 = (float)(x + 1.0f); + z0 = z1 = (float)(z + 0.0f); + z2 = z3 = (float)(z + 1.0f); + } else if (dir == Direction::WEST) { + // rotate 90 degrees clockwise + x0 = x3 = (float)(x + 1.0f); + x1 = x2 = (float)(x + 0.0f); + z0 = z1 = (float)(z + 1.0f); + z2 = z3 = (float)(z + 0.0f); + } - t->vertexUV( x3 , y0 , z3 , u0 , v0 ); - t->vertexUV( x2 , y0 , z2 , u0 , v1 ); - t->vertexUV( x1 , y0 , z1 , u1 , v1 ); - t->vertexUV( x0 , y0 , z0 , u1 , v0 ); + t->vertexUV(x3, y0, z3, u0, v0); + t->vertexUV(x2, y0, z2, u0, v1); + t->vertexUV(x1, y0, z1, u1, v1); + t->vertexUV(x0, y0, z0, u1, v0); } -void TileRenderer::tesselatePistonBaseForceExtended( Tile* tile, int x, int y, int z, int forceData ) // 4J added forceData param +void TileRenderer::tesselatePistonBaseForceExtended( + Tile* tile, int x, int y, int z, int forceData) // 4J added forceData param { - noCulling = true; - tesselatePistonBaseInWorld( tile, x, y, z, true, forceData ); - noCulling = false; + noCulling = true; + tesselatePistonBaseInWorld(tile, x, y, z, true, forceData); + noCulling = false; } -bool TileRenderer::tesselatePistonBaseInWorld( Tile* tt, int x, int y, int z, bool forceExtended, int forceData ) // 4J added forceData param +bool TileRenderer::tesselatePistonBaseInWorld( + Tile* tt, int x, int y, int z, bool forceExtended, + int forceData) // 4J added forceData param { - int data = ( forceData == -1 ) ? level->getData( x, y, z ) : forceData; - bool extended = forceExtended || ( data & PistonBaseTile::EXTENDED_BIT ) != 0; - int facing = PistonBaseTile::getFacing( data ); + int data = (forceData == -1) ? level->getData(x, y, z) : forceData; + bool extended = forceExtended || (data & PistonBaseTile::EXTENDED_BIT) != 0; + int facing = PistonBaseTile::getFacing(data); - const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; + const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; - if ( extended ) - { - switch ( facing ) - { - case Facing::DOWN: - northFlip = FLIP_180; - southFlip = FLIP_180; - eastFlip = FLIP_180; - westFlip = FLIP_180; - setShape( 0.0f, thickness, 0.0f, 1.0f, 1.0f, 1.0f ); - break; - case Facing::UP: - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f - thickness, 1.0f ); - break; - case Facing::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - setShape( 0.0f, 0.0f, thickness, 1.0f, 1.0f, 1.0f ); - break; - case Facing::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f - thickness ); - break; - case Facing::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - setShape( thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f ); - break; - case Facing::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - setShape( 0.0f, 0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f ); - break; - } - // weird way of telling the piston to use the - // "inside" texture for the forward-facing edge - ((PistonBaseTile *) tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); - tesselateBlockInWorld( tt, x, y, z ); - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; - ((PistonBaseTile *) tt)->updateShape((float) tileShapeX0, (float) tileShapeY0, (float) tileShapeZ0, (float) tileShapeX1, (float) tileShapeY1, (float) tileShapeZ1); - } - else - { - switch ( facing ) - { - case Facing::DOWN: - northFlip = FLIP_180; - southFlip = FLIP_180; - eastFlip = FLIP_180; - westFlip = FLIP_180; - break; - case Facing::UP: - break; - case Facing::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - break; - case Facing::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - break; - case Facing::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - break; - case Facing::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - break; - } - tesselateBlockInWorld( tt, x, y, z ); - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; - } - - return true; + if (extended) { + switch (facing) { + case Facing::DOWN: + northFlip = FLIP_180; + southFlip = FLIP_180; + eastFlip = FLIP_180; + westFlip = FLIP_180; + setShape(0.0f, thickness, 0.0f, 1.0f, 1.0f, 1.0f); + break; + case Facing::UP: + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f - thickness, 1.0f); + break; + case Facing::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + setShape(0.0f, 0.0f, thickness, 1.0f, 1.0f, 1.0f); + break; + case Facing::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f - thickness); + break; + case Facing::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + setShape(thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); + break; + case Facing::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + setShape(0.0f, 0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f); + break; + } + // weird way of telling the piston to use the + // "inside" texture for the forward-facing edge + ((PistonBaseTile*)tt) + ->updateShape((float)tileShapeX0, (float)tileShapeY0, + (float)tileShapeZ0, (float)tileShapeX1, + (float)tileShapeY1, (float)tileShapeZ1); + tesselateBlockInWorld(tt, x, y, z); + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; + ((PistonBaseTile*)tt) + ->updateShape((float)tileShapeX0, (float)tileShapeY0, + (float)tileShapeZ0, (float)tileShapeX1, + (float)tileShapeY1, (float)tileShapeZ1); + } else { + switch (facing) { + case Facing::DOWN: + northFlip = FLIP_180; + southFlip = FLIP_180; + eastFlip = FLIP_180; + westFlip = FLIP_180; + break; + case Facing::UP: + break; + case Facing::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + break; + case Facing::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + break; + case Facing::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + break; + case Facing::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + break; + } + tesselateBlockInWorld(tt, x, y, z); + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; + } + return true; } -void TileRenderer::renderPistonArmUpDown( float x0, float x1, float y0, float y1, float z0, float z1, float br, - float armLengthPixels ) -{ - Icon *armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); - if (hasFixedTexture()) armTex = fixedTexture; +void TileRenderer::renderPistonArmUpDown(float x0, float x1, float y0, float y1, + float z0, float z1, float br, + float armLengthPixels) { + Icon* armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); + if (hasFixedTexture()) armTex = fixedTexture; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - // upwards arm - float u00 = armTex->getU0(true); - float v00 = armTex->getV0(true); - float u11 = armTex->getU(armLengthPixels, true); - float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); + // upwards arm + float u00 = armTex->getU0(true); + float v00 = armTex->getV0(true); + float u11 = armTex->getU(armLengthPixels, true); + float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); - t->color( br, br, br ); - - t->vertexUV( x0, y1, z0, u11, v00 ); - t->vertexUV( x0, y0, z0, u00, v00 ); - t->vertexUV( x1, y0, z1, u00, v11 ); - t->vertexUV( x1, y1, z1, u11, v11 ); + t->color(br, br, br); + t->vertexUV(x0, y1, z0, u11, v00); + t->vertexUV(x0, y0, z0, u00, v00); + t->vertexUV(x1, y0, z1, u00, v11); + t->vertexUV(x1, y1, z1, u11, v11); } -void TileRenderer::renderPistonArmNorthSouth( float x0, float x1, float y0, float y1, float z0, float z1, - float br, float armLengthPixels ) -{ - Icon *armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); - if (hasFixedTexture()) armTex = fixedTexture; +void TileRenderer::renderPistonArmNorthSouth(float x0, float x1, float y0, + float y1, float z0, float z1, + float br, float armLengthPixels) { + Icon* armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); + if (hasFixedTexture()) armTex = fixedTexture; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - // upwards arm - float u00 = armTex->getU0(true); - float v00 = armTex->getV0(true); - float u11 = armTex->getU(armLengthPixels, true); - float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); + // upwards arm + float u00 = armTex->getU0(true); + float v00 = armTex->getV0(true); + float u11 = armTex->getU(armLengthPixels, true); + float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); - t->color( br, br, br ); + t->color(br, br, br); - t->vertexUV( x0, y0, z1, u11, v00 ); - t->vertexUV( x0, y0, z0, u00, v00 ); - t->vertexUV( x1, y1, z0, u00, v11 ); - t->vertexUV( x1, y1, z1, u11, v11 ); + t->vertexUV(x0, y0, z1, u11, v00); + t->vertexUV(x0, y0, z0, u00, v00); + t->vertexUV(x1, y1, z0, u00, v11); + t->vertexUV(x1, y1, z1, u11, v11); } -void TileRenderer::renderPistonArmEastWest( float x0, float x1, float y0, float y1, float z0, float z1, float br, - float armLengthPixels ) -{ - Icon *armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); - if (hasFixedTexture()) armTex = fixedTexture; +void TileRenderer::renderPistonArmEastWest(float x0, float x1, float y0, + float y1, float z0, float z1, + float br, float armLengthPixels) { + Icon* armTex = PistonBaseTile::getTexture(PistonBaseTile::EDGE_TEX); + if (hasFixedTexture()) armTex = fixedTexture; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - // upwards arm - float u00 = armTex->getU0(true); - float v00 = armTex->getV0(true); - float u11 = armTex->getU(armLengthPixels, true); - float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); + // upwards arm + float u00 = armTex->getU0(true); + float v00 = armTex->getV0(true); + float u11 = armTex->getU(armLengthPixels, true); + float v11 = armTex->getV(PistonBaseTile::PLATFORM_THICKNESS, true); - t->color( br, br, br ); + t->color(br, br, br); - t->vertexUV( x1, y0, z0, u11, v00 ); - t->vertexUV( x0, y0, z0, u00, v00 ); - t->vertexUV( x0, y1, z1, u00, v11 ); - t->vertexUV( x1, y1, z1, u11, v11 ); + t->vertexUV(x1, y0, z0, u11, v00); + t->vertexUV(x0, y0, z0, u00, v00); + t->vertexUV(x0, y1, z1, u00, v11); + t->vertexUV(x1, y1, z1, u11, v11); } -void TileRenderer::tesselatePistonArmNoCulling( Tile* tile, int x, int y, int z, bool fullArm, int forceData ) // 4J added forceData param +void TileRenderer::tesselatePistonArmNoCulling( + Tile* tile, int x, int y, int z, bool fullArm, + int forceData) // 4J added forceData param { - noCulling = true; - tesselatePistonExtensionInWorld( tile, x, y, z, fullArm ); - noCulling = false; + noCulling = true; + tesselatePistonExtensionInWorld(tile, x, y, z, fullArm); + noCulling = false; } -bool TileRenderer::tesselatePistonExtensionInWorld( Tile* tt, int x, int y, int z, bool fullArm, int forceData ) // 4J added forceData param +bool TileRenderer::tesselatePistonExtensionInWorld( + Tile* tt, int x, int y, int z, bool fullArm, + int forceData) // 4J added forceData param { - int data = ( forceData == -1 ) ? level->getData( x, y, z ) : forceData; - int facing = PistonExtensionTile::getFacing( data ); + int data = (forceData == -1) ? level->getData(x, y, z) : forceData; + int facing = PistonExtensionTile::getFacing(data); - const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; - const float leftEdge = ( 8.0f - ( PistonBaseTile::PLATFORM_THICKNESS / 2.0f ) ) / 16.0f; - const float rightEdge = ( 8.0f + ( PistonBaseTile::PLATFORM_THICKNESS / 2.0f ) ) / 16.0f; - const float br = tt->getBrightness( level, x, y, z ); - const float armLength = fullArm ? 1.0f : 0.5f; - const float armLengthPixels = fullArm ? 16.0f : 8.0f; + const float thickness = PistonBaseTile::PLATFORM_THICKNESS / 16.0f; + const float leftEdge = + (8.0f - (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; + const float rightEdge = + (8.0f + (PistonBaseTile::PLATFORM_THICKNESS / 2.0f)) / 16.0f; + const float br = tt->getBrightness(level, x, y, z); + const float armLength = fullArm ? 1.0f : 0.5f; + const float armLengthPixels = fullArm ? 16.0f : 8.0f; - Tesselator* t = Tesselator::getInstance(); - switch ( facing ) - { - case Facing::DOWN: - northFlip = FLIP_180; - southFlip = FLIP_180; - eastFlip = FLIP_180; - westFlip = FLIP_180; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, thickness, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + Tesselator* t = Tesselator::getInstance(); + switch (facing) { + case Facing::DOWN: + northFlip = FLIP_180; + southFlip = FLIP_180; + eastFlip = FLIP_180; + westFlip = FLIP_180; + setShape(0.0f, 0.0f, 0.0f, 1.0f, thickness, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmUpDown( x + leftEdge, x + rightEdge, y + thickness, y + thickness + armLength, - z + rightEdge, z + rightEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + leftEdge, y + thickness, y + thickness + armLength, z + leftEdge, - z + leftEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + leftEdge, x + leftEdge, y + thickness, y + thickness + armLength, z + leftEdge, - z + rightEdge, br * 0.6f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + rightEdge, y + thickness, y + thickness + armLength, - z + rightEdge, z + leftEdge, br * 0.6f, armLengthPixels ); + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmUpDown(x + leftEdge, x + rightEdge, y + thickness, + y + thickness + armLength, z + rightEdge, + z + rightEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + leftEdge, y + thickness, + y + thickness + armLength, z + leftEdge, + z + leftEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + leftEdge, x + leftEdge, y + thickness, + y + thickness + armLength, z + leftEdge, + z + rightEdge, br * 0.6f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + rightEdge, y + thickness, + y + thickness + armLength, z + rightEdge, + z + leftEdge, br * 0.6f, armLengthPixels); - break; - case Facing::UP: - setShape( 0.0f, 1.0f - thickness, 0.0f, 1.0f, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + break; + case Facing::UP: + setShape(0.0f, 1.0f - thickness, 0.0f, 1.0f, 1.0f, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmUpDown( x + leftEdge, x + rightEdge, y - thickness + 1.0f - armLength, y - thickness + 1.0f, - z + rightEdge, z + rightEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + leftEdge, y - thickness + 1.0f - armLength, y - thickness + 1.0f, - z + leftEdge, z + leftEdge, br * 0.8f, armLengthPixels ); - renderPistonArmUpDown( x + leftEdge, x + leftEdge, y - thickness + 1.0f - armLength, y - thickness + 1.0f, - z + leftEdge, z + rightEdge, br * 0.6f, armLengthPixels ); - renderPistonArmUpDown( x + rightEdge, x + rightEdge, y - thickness + 1.0f - armLength, - y - thickness + 1.0f, z + rightEdge, z + leftEdge, br * 0.6f, armLengthPixels ); - break; - case Facing::NORTH: - eastFlip = FLIP_CW; - westFlip = FLIP_CCW; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, thickness ); - tesselateBlockInWorld( tt, x, y, z ); + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmUpDown(x + leftEdge, x + rightEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + rightEdge, + z + rightEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + leftEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + leftEdge, + z + leftEdge, br * 0.8f, armLengthPixels); + renderPistonArmUpDown(x + leftEdge, x + leftEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + leftEdge, + z + rightEdge, br * 0.6f, armLengthPixels); + renderPistonArmUpDown(x + rightEdge, x + rightEdge, + y - thickness + 1.0f - armLength, + y - thickness + 1.0f, z + rightEdge, + z + leftEdge, br * 0.6f, armLengthPixels); + break; + case Facing::NORTH: + eastFlip = FLIP_CW; + westFlip = FLIP_CCW; + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, thickness); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmNorthSouth( x + leftEdge, x + leftEdge, y + rightEdge, y + leftEdge, z + thickness, - z + thickness + armLength, br * 0.6f, armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + rightEdge, y + leftEdge, y + rightEdge, z + thickness, - z + thickness + armLength, br * 0.6f, armLengthPixels ); - renderPistonArmNorthSouth( x + leftEdge, x + rightEdge, y + leftEdge, y + leftEdge, z + thickness, - z + thickness + armLength, br * 0.5f, armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, z + thickness, - z + thickness + armLength, br, armLengthPixels ); - break; - case Facing::SOUTH: - eastFlip = FLIP_CCW; - westFlip = FLIP_CW; - upFlip = FLIP_180; - downFlip = FLIP_180; - setShape( 0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmNorthSouth(x + leftEdge, x + leftEdge, y + rightEdge, + y + leftEdge, z + thickness, + z + thickness + armLength, br * 0.6f, + armLengthPixels); + renderPistonArmNorthSouth(x + rightEdge, x + rightEdge, + y + leftEdge, y + rightEdge, + z + thickness, z + thickness + armLength, + br * 0.6f, armLengthPixels); + renderPistonArmNorthSouth(x + leftEdge, x + rightEdge, y + leftEdge, + y + leftEdge, z + thickness, + z + thickness + armLength, br * 0.5f, + armLengthPixels); + renderPistonArmNorthSouth( + x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, + z + thickness, z + thickness + armLength, br, armLengthPixels); + break; + case Facing::SOUTH: + eastFlip = FLIP_CCW; + westFlip = FLIP_CW; + upFlip = FLIP_180; + downFlip = FLIP_180; + setShape(0.0f, 0.0f, 1.0f - thickness, 1.0f, 1.0f, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmNorthSouth( x + leftEdge, x + leftEdge, y + rightEdge, y + leftEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br * 0.6f, - armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + rightEdge, y + leftEdge, y + rightEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br * 0.6f, - armLengthPixels ); - renderPistonArmNorthSouth( x + leftEdge, x + rightEdge, y + leftEdge, y + leftEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br * 0.5f, - armLengthPixels ); - renderPistonArmNorthSouth( x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, - z - thickness + 1.0f - armLength, z - thickness + 1.0f, br, armLengthPixels ); - break; - case Facing::WEST: - northFlip = FLIP_CW; - southFlip = FLIP_CCW; - upFlip = FLIP_CCW; - downFlip = FLIP_CW; - setShape( 0.0f, 0.0f, 0.0f, thickness, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmNorthSouth( + x + leftEdge, x + leftEdge, y + rightEdge, y + leftEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, + br * 0.6f, armLengthPixels); + renderPistonArmNorthSouth( + x + rightEdge, x + rightEdge, y + leftEdge, y + rightEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, + br * 0.6f, armLengthPixels); + renderPistonArmNorthSouth( + x + leftEdge, x + rightEdge, y + leftEdge, y + leftEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, + br * 0.5f, armLengthPixels); + renderPistonArmNorthSouth( + x + rightEdge, x + leftEdge, y + rightEdge, y + rightEdge, + z - thickness + 1.0f - armLength, z - thickness + 1.0f, br, + armLengthPixels); + break; + case Facing::WEST: + northFlip = FLIP_CW; + southFlip = FLIP_CCW; + upFlip = FLIP_CCW; + downFlip = FLIP_CW; + setShape(0.0f, 0.0f, 0.0f, thickness, 1.0f, 1.0f); + tesselateBlockInWorld( + tt, x, y, + z); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld - t->tex2( getLightColor(tt, level, x, y , z ) ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + leftEdge, y + leftEdge, - z + rightEdge, z + leftEdge, br * 0.5f, armLengthPixels ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + rightEdge, y + rightEdge, - z + leftEdge, z + rightEdge, br, armLengthPixels ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + leftEdge, y + rightEdge, - z + leftEdge, z + leftEdge, br * 0.6f, armLengthPixels ); - renderPistonArmEastWest( x + thickness, x + thickness + armLength, y + rightEdge, y + leftEdge, - z + rightEdge, z + rightEdge, br * 0.6f, armLengthPixels ); - break; - case Facing::EAST: - northFlip = FLIP_CCW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CCW; - setShape( 1.0f - thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f ); - tesselateBlockInWorld( tt, x, y, z ); + t->tex2(getLightColor(tt, level, x, y, z)); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + leftEdge, y + leftEdge, z + rightEdge, + z + leftEdge, br * 0.5f, armLengthPixels); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + rightEdge, y + rightEdge, z + leftEdge, + z + rightEdge, br, armLengthPixels); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + leftEdge, y + rightEdge, z + leftEdge, + z + leftEdge, br * 0.6f, armLengthPixels); + renderPistonArmEastWest(x + thickness, x + thickness + armLength, + y + rightEdge, y + leftEdge, z + rightEdge, + z + rightEdge, br * 0.6f, armLengthPixels); + break; + case Facing::EAST: + northFlip = FLIP_CCW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CCW; + setShape(1.0f - thickness, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); + tesselateBlockInWorld(tt, x, y, z); - t->tex2( getLightColor(tt, level, x, y , z ) ); // 4J added - renderPistonArmDown doesn't set its own tex2 so just inherited from previous tesselateBlockInWorld - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + leftEdge, - y + leftEdge, z + rightEdge, z + leftEdge, br * 0.5f, armLengthPixels ); - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + rightEdge, - y + rightEdge, z + leftEdge, z + rightEdge, br, armLengthPixels ); - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + leftEdge, - y + rightEdge, z + leftEdge, z + leftEdge, br * 0.6f, armLengthPixels ); - renderPistonArmEastWest( x - thickness + 1.0f - armLength, x - thickness + 1.0f, y + rightEdge, - y + leftEdge, z + rightEdge, z + rightEdge, br * 0.6f, armLengthPixels ); - break; - } - northFlip = FLIP_NONE; - southFlip = FLIP_NONE; - eastFlip = FLIP_NONE; - westFlip = FLIP_NONE; - upFlip = FLIP_NONE; - downFlip = FLIP_NONE; - setShape( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f ); - - return true; + t->tex2(getLightColor( + tt, level, x, y, + z)); // 4J added - renderPistonArmDown doesn't set its own tex2 + // so just inherited from previous tesselateBlockInWorld + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + leftEdge, + y + leftEdge, z + rightEdge, z + leftEdge, + br * 0.5f, armLengthPixels); + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + rightEdge, + y + rightEdge, z + leftEdge, z + rightEdge, + br, armLengthPixels); + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + leftEdge, + y + rightEdge, z + leftEdge, z + leftEdge, + br * 0.6f, armLengthPixels); + renderPistonArmEastWest(x - thickness + 1.0f - armLength, + x - thickness + 1.0f, y + rightEdge, + y + leftEdge, z + rightEdge, z + rightEdge, + br * 0.6f, armLengthPixels); + break; + } + northFlip = FLIP_NONE; + southFlip = FLIP_NONE; + eastFlip = FLIP_NONE; + westFlip = FLIP_NONE; + upFlip = FLIP_NONE; + downFlip = FLIP_NONE; + setShape(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); + return true; } -bool TileRenderer::tesselateLeverInWorld( Tile* tt, int x, int y, int z ) -{ - int data = level->getData( x, y, z ); +bool TileRenderer::tesselateLeverInWorld(Tile* tt, int x, int y, int z) { + int data = level->getData(x, y, z); - int dir = data & 7; - bool flipped = ( data & 8 ) > 0; + int dir = data & 7; + bool flipped = (data & 8) > 0; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - bool hadFixed = hasFixedTexture(); - if (!hadFixed) this->setFixedTexture(getTexture(Tile::stoneBrick)); - float w1 = 4.0f / 16.0f; - float w2 = 3.0f / 16.0f; - float h = 3.0f / 16.0f; + bool hadFixed = hasFixedTexture(); + if (!hadFixed) this->setFixedTexture(getTexture(Tile::stoneBrick)); + float w1 = 4.0f / 16.0f; + float w2 = 3.0f / 16.0f; + float h = 3.0f / 16.0f; - if ( dir == 5 ) - { - setShape( 0.5f - w2, 0.0f, 0.5f - w1, 0.5f + w2, h, 0.5f + w1 ); - } - else if ( dir == 6 ) - { - setShape( 0.5f - w1, 0.0f, 0.5f - w2, 0.5f + w1, h, 0.5f + w2 ); - } - else if ( dir == 4 ) - { - setShape( 0.5f - w2, 0.5f - w1, 1.0f - h, 0.5f + w2, 0.5f + w1, 1.0f ); - } - else if ( dir == 3 ) - { - setShape( 0.5f - w2, 0.5f - w1, 0, 0.5f + w2, 0.5f + w1, h ); - } - else if ( dir == 2 ) - { - setShape( 1.0f - h, 0.5f - w1, 0.5f - w2, 1.0f, 0.5f + w1, 0.5f + w2 ); - } - else if ( dir == 1 ) - { - setShape( 0, 0.5f - w1, 0.5f - w2, h, 0.5f + w1, 0.5f + w2 ); - } - else if (dir == 0) - { - setShape(0.5f - w1, 1 - h, 0.5f - w2, 0.5f + w1, 1, 0.5f + w2); - } - else if (dir == 7) - { - setShape(0.5f - w2, 1 - h, 0.5f - w1, 0.5f + w2, 1, 0.5f + w1); - } - this->tesselateBlockInWorld( tt, x, y, z ); + if (dir == 5) { + setShape(0.5f - w2, 0.0f, 0.5f - w1, 0.5f + w2, h, 0.5f + w1); + } else if (dir == 6) { + setShape(0.5f - w1, 0.0f, 0.5f - w2, 0.5f + w1, h, 0.5f + w2); + } else if (dir == 4) { + setShape(0.5f - w2, 0.5f - w1, 1.0f - h, 0.5f + w2, 0.5f + w1, 1.0f); + } else if (dir == 3) { + setShape(0.5f - w2, 0.5f - w1, 0, 0.5f + w2, 0.5f + w1, h); + } else if (dir == 2) { + setShape(1.0f - h, 0.5f - w1, 0.5f - w2, 1.0f, 0.5f + w1, 0.5f + w2); + } else if (dir == 1) { + setShape(0, 0.5f - w1, 0.5f - w2, h, 0.5f + w1, 0.5f + w2); + } else if (dir == 0) { + setShape(0.5f - w1, 1 - h, 0.5f - w2, 0.5f + w1, 1, 0.5f + w2); + } else if (dir == 7) { + setShape(0.5f - w2, 1 - h, 0.5f - w1, 0.5f + w2, 1, 0.5f + w1); + } + this->tesselateBlockInWorld(tt, x, y, z); - if ( !hadFixed ) this->clearFixedTexture(); + if (!hadFixed) this->clearFixedTexture(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( br, br, br ); - Icon *tex = getTexture(tt, 0); + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - Vec3* corners[8]; - float xv = 1.0f / 16.0f; - float zv = 1.0f / 16.0f; - float yv = 10.0f / 16.0f; - corners[0] = Vec3::newTemp( -xv, -0, -zv ); - corners[1] = Vec3::newTemp( +xv, -0, -zv ); - corners[2] = Vec3::newTemp( +xv, -0, +zv ); - corners[3] = Vec3::newTemp( -xv, -0, +zv ); - corners[4] = Vec3::newTemp( -xv, +yv, -zv ); - corners[5] = Vec3::newTemp( +xv, +yv, -zv ); - corners[6] = Vec3::newTemp( +xv, +yv, +zv ); - corners[7] = Vec3::newTemp( -xv, +yv, +zv ); + Vec3* corners[8]; + float xv = 1.0f / 16.0f; + float zv = 1.0f / 16.0f; + float yv = 10.0f / 16.0f; + corners[0] = Vec3::newTemp(-xv, -0, -zv); + corners[1] = Vec3::newTemp(+xv, -0, -zv); + corners[2] = Vec3::newTemp(+xv, -0, +zv); + corners[3] = Vec3::newTemp(-xv, -0, +zv); + corners[4] = Vec3::newTemp(-xv, +yv, -zv); + corners[5] = Vec3::newTemp(+xv, +yv, -zv); + corners[6] = Vec3::newTemp(+xv, +yv, +zv); + corners[7] = Vec3::newTemp(-xv, +yv, +zv); - for ( int i = 0; i < 8; i++ ) - { - if ( flipped ) - { - corners[i]->z -= 1 / 16.0f; - corners[i]->xRot( 40 * PI / 180 ); - } - else - { - corners[i]->z += 1 / 16.0f; - corners[i]->xRot( -40 * PI / 180 ); - } - if (dir == 0 || dir == 7) - { - corners[i]->zRot(180 * PI / 180); - } - if ( dir == 6 || dir == 0 ) - { - corners[i]->yRot( 90 * PI / 180 ); - } + for (int i = 0; i < 8; i++) { + if (flipped) { + corners[i]->z -= 1 / 16.0f; + corners[i]->xRot(40 * PI / 180); + } else { + corners[i]->z += 1 / 16.0f; + corners[i]->xRot(-40 * PI / 180); + } + if (dir == 0 || dir == 7) { + corners[i]->zRot(180 * PI / 180); + } + if (dir == 6 || dir == 0) { + corners[i]->yRot(90 * PI / 180); + } - if ( dir > 0 && dir < 5 ) - { - corners[i]->y -= 6 / 16.0f; - corners[i]->xRot( 90 * PI / 180 ); + if (dir > 0 && dir < 5) { + corners[i]->y -= 6 / 16.0f; + corners[i]->xRot(90 * PI / 180); - if ( dir == 4 ) corners[i]->yRot( 0 * PI / 180 ); - if ( dir == 3 ) corners[i]->yRot( 180 * PI / 180 ); - if ( dir == 2 ) corners[i]->yRot( 90 * PI / 180 ); - if ( dir == 1 ) corners[i]->yRot( -90 * PI / 180 ); + if (dir == 4) corners[i]->yRot(0 * PI / 180); + if (dir == 3) corners[i]->yRot(180 * PI / 180); + if (dir == 2) corners[i]->yRot(90 * PI / 180); + if (dir == 1) corners[i]->yRot(-90 * PI / 180); - corners[i]->x += x + 0.5; - corners[i]->y += y + 8 / 16.0f; - corners[i]->z += z + 0.5; - } - else if (dir == 0 || dir == 7) - { - corners[i]->x += x + 0.5; - corners[i]->y += y + 14 / 16.0f; - corners[i]->z += z + 0.5; - } - else - { - corners[i]->x += x + 0.5; - corners[i]->y += y + 2 / 16.0f; - corners[i]->z += z + 0.5; - } - } - - Vec3* c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; - for ( int i = 0; i < 6; i++ ) - { - if ( i == 0 ) - { - u0 = tex->getU(7, true); - v0 = tex->getV(6, true); - u1 = tex->getU(9, true); - v1 = tex->getV(8, true); - } - else if ( i == 2 ) - { - u0 = tex->getU(7, true); - v0 = tex->getV(6, true); - u1 = tex->getU(9, true); - v1 = tex->getV1(true); - } - if ( i == 0 ) - { - c0 = corners[0]; - c1 = corners[1]; - c2 = corners[2]; - c3 = corners[3]; - } - else if ( i == 1 ) - { - c0 = corners[7]; - c1 = corners[6]; - c2 = corners[5]; - c3 = corners[4]; - } - else if ( i == 2 ) - { - c0 = corners[1]; - c1 = corners[0]; - c2 = corners[4]; - c3 = corners[5]; - } - else if ( i == 3 ) - { - c0 = corners[2]; - c1 = corners[1]; - c2 = corners[5]; - c3 = corners[6]; - } - else if ( i == 4 ) - { - c0 = corners[3]; - c1 = corners[2]; - c2 = corners[6]; - c3 = corners[7]; - } - else if ( i == 5 ) - { - c0 = corners[0]; - c1 = corners[3]; - c2 = corners[7]; - c3 = corners[4]; - } - t->vertexUV( ( float )( c0->x ), ( float )( c0->y ), ( float )( c0->z ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( c1->x ), ( float )( c1->y ), ( float )( c1->z ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( c2->x ), ( float )( c2->y ), ( float )( c2->z ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( c3->x ), ( float )( c3->y ), ( float )( c3->z ), ( float )( u0 ), ( float )( v0 ) ); - } - return true; + corners[i]->x += x + 0.5; + corners[i]->y += y + 8 / 16.0f; + corners[i]->z += z + 0.5; + } else if (dir == 0 || dir == 7) { + corners[i]->x += x + 0.5; + corners[i]->y += y + 14 / 16.0f; + corners[i]->z += z + 0.5; + } else { + corners[i]->x += x + 0.5; + corners[i]->y += y + 2 / 16.0f; + corners[i]->z += z + 0.5; + } + } + Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + for (int i = 0; i < 6; i++) { + if (i == 0) { + u0 = tex->getU(7, true); + v0 = tex->getV(6, true); + u1 = tex->getU(9, true); + v1 = tex->getV(8, true); + } else if (i == 2) { + u0 = tex->getU(7, true); + v0 = tex->getV(6, true); + u1 = tex->getU(9, true); + v1 = tex->getV1(true); + } + if (i == 0) { + c0 = corners[0]; + c1 = corners[1]; + c2 = corners[2]; + c3 = corners[3]; + } else if (i == 1) { + c0 = corners[7]; + c1 = corners[6]; + c2 = corners[5]; + c3 = corners[4]; + } else if (i == 2) { + c0 = corners[1]; + c1 = corners[0]; + c2 = corners[4]; + c3 = corners[5]; + } else if (i == 3) { + c0 = corners[2]; + c1 = corners[1]; + c2 = corners[5]; + c3 = corners[6]; + } else if (i == 4) { + c0 = corners[3]; + c1 = corners[2]; + c2 = corners[6]; + c3 = corners[7]; + } else if (i == 5) { + c0 = corners[0]; + c1 = corners[3]; + c2 = corners[7]; + c3 = corners[4]; + } + t->vertexUV((float)(c0->x), (float)(c0->y), (float)(c0->z), (float)(u0), + (float)(v1)); + t->vertexUV((float)(c1->x), (float)(c1->y), (float)(c1->z), (float)(u1), + (float)(v1)); + t->vertexUV((float)(c2->x), (float)(c2->y), (float)(c2->z), (float)(u1), + (float)(v0)); + t->vertexUV((float)(c3->x), (float)(c3->y), (float)(c3->z), (float)(u0), + (float)(v0)); + } + return true; } -bool TileRenderer::tesselateTripwireSourceInWorld(Tile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); - int data = level->getData(x, y, z); - int dir = data & TripWireSourceTile::MASK_DIR; - bool attached = (data & TripWireSourceTile::MASK_ATTACHED) == TripWireSourceTile::MASK_ATTACHED; - bool powered = (data & TripWireSourceTile::MASK_POWERED) == TripWireSourceTile::MASK_POWERED; - bool suspended = !level->isTopSolidBlocking(x, y - 1, z); +bool TileRenderer::tesselateTripwireSourceInWorld(Tile* tt, int x, int y, + int z) { + Tesselator* t = Tesselator::getInstance(); + int data = level->getData(x, y, z); + int dir = data & TripWireSourceTile::MASK_DIR; + bool attached = (data & TripWireSourceTile::MASK_ATTACHED) == + TripWireSourceTile::MASK_ATTACHED; + bool powered = (data & TripWireSourceTile::MASK_POWERED) == + TripWireSourceTile::MASK_POWERED; + bool suspended = !level->isTopSolidBlocking(x, y - 1, z); - bool hadFixed = hasFixedTexture(); - if (!hadFixed) this->setFixedTexture(getTexture(Tile::wood)); + bool hadFixed = hasFixedTexture(); + if (!hadFixed) this->setFixedTexture(getTexture(Tile::wood)); - float boxHeight = 4 / 16.0f; - float boxWidth = 2 / 16.0f; - float boxDepth = 2 / 16.0f; + float boxHeight = 4 / 16.0f; + float boxWidth = 2 / 16.0f; + float boxDepth = 2 / 16.0f; - float boxy0 = 0.3f - boxHeight; - float boxy1 = 0.3f + boxHeight; - if (dir == Direction::NORTH) - { - setShape(0.5f - boxWidth, boxy0, 1 - boxDepth, 0.5f + boxWidth, boxy1, 1); - } - else if (dir == Direction::SOUTH) - { - setShape(0.5f - boxWidth, boxy0, 0, 0.5f + boxWidth, boxy1, boxDepth); - } - else if (dir == Direction::WEST) - { - setShape(1 - boxDepth, boxy0, 0.5f - boxWidth, 1, boxy1, 0.5f + boxWidth); - } - else if (dir == Direction::EAST) - { - setShape(0, boxy0, 0.5f - boxWidth, boxDepth, boxy1, 0.5f + boxWidth); - } + float boxy0 = 0.3f - boxHeight; + float boxy1 = 0.3f + boxHeight; + if (dir == Direction::NORTH) { + setShape(0.5f - boxWidth, boxy0, 1 - boxDepth, 0.5f + boxWidth, boxy1, + 1); + } else if (dir == Direction::SOUTH) { + setShape(0.5f - boxWidth, boxy0, 0, 0.5f + boxWidth, boxy1, boxDepth); + } else if (dir == Direction::WEST) { + setShape(1 - boxDepth, boxy0, 0.5f - boxWidth, 1, boxy1, + 0.5f + boxWidth); + } else if (dir == Direction::EAST) { + setShape(0, boxy0, 0.5f - boxWidth, boxDepth, boxy1, 0.5f + boxWidth); + } - this->tesselateBlockInWorld(tt, x, y, z); - if (!hadFixed) this->clearFixedTexture(); + this->tesselateBlockInWorld(tt, x, y, z); + if (!hadFixed) this->clearFixedTexture(); - float brightness; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - brightness = 1; - } - else - { - brightness = tt->getBrightness(level, x, y, z); - } - if (Tile::lightEmission[tt->id] > 0) brightness = 1.0f; - t->color(brightness, brightness, brightness); - Icon *tex = getTexture(tt, 0); + float brightness; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + brightness = 1; + } else { + brightness = tt->getBrightness(level, x, y, z); + } + if (Tile::lightEmission[tt->id] > 0) brightness = 1.0f; + t->color(brightness, brightness, brightness); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; - double u0 = tex->getU0(); - double v0 = tex->getV0(); - double u1 = tex->getU1(); - double v1 = tex->getV1(); + if (hasFixedTexture()) tex = fixedTexture; + double u0 = tex->getU0(); + double v0 = tex->getV0(); + double u1 = tex->getU1(); + double v1 = tex->getV1(); - Vec3 *corners[8]; - float stickWidth = 0.75f / 16.0f; - float stickHeight = 0.75f / 16.0f; - float stickLength = 5 / 16.0f; - corners[0] = Vec3::newTemp(-stickWidth, -0, -stickHeight); - corners[1] = Vec3::newTemp(+stickWidth, -0, -stickHeight); - corners[2] = Vec3::newTemp(+stickWidth, -0, +stickHeight); - corners[3] = Vec3::newTemp(-stickWidth, -0, +stickHeight); - corners[4] = Vec3::newTemp(-stickWidth, +stickLength, -stickHeight); - corners[5] = Vec3::newTemp(+stickWidth, +stickLength, -stickHeight); - corners[6] = Vec3::newTemp(+stickWidth, +stickLength, +stickHeight); - corners[7] = Vec3::newTemp(-stickWidth, +stickLength, +stickHeight); + Vec3* corners[8]; + float stickWidth = 0.75f / 16.0f; + float stickHeight = 0.75f / 16.0f; + float stickLength = 5 / 16.0f; + corners[0] = Vec3::newTemp(-stickWidth, -0, -stickHeight); + corners[1] = Vec3::newTemp(+stickWidth, -0, -stickHeight); + corners[2] = Vec3::newTemp(+stickWidth, -0, +stickHeight); + corners[3] = Vec3::newTemp(-stickWidth, -0, +stickHeight); + corners[4] = Vec3::newTemp(-stickWidth, +stickLength, -stickHeight); + corners[5] = Vec3::newTemp(+stickWidth, +stickLength, -stickHeight); + corners[6] = Vec3::newTemp(+stickWidth, +stickLength, +stickHeight); + corners[7] = Vec3::newTemp(-stickWidth, +stickLength, +stickHeight); - for (int i = 0; i < 8; i++) - { - corners[i]->z += 1 / 16.0f; + for (int i = 0; i < 8; i++) { + corners[i]->z += 1 / 16.0f; - if (powered) - { - corners[i]->xRot(30 * PI / 180); - corners[i]->y -= 7 / 16.0f; - } - else if (attached) - { - corners[i]->xRot(5 * PI / 180); - corners[i]->y -= 7 / 16.0f; - } - else - { - corners[i]->xRot(-40 * PI / 180); - corners[i]->y -= 6 / 16.0f; - } + if (powered) { + corners[i]->xRot(30 * PI / 180); + corners[i]->y -= 7 / 16.0f; + } else if (attached) { + corners[i]->xRot(5 * PI / 180); + corners[i]->y -= 7 / 16.0f; + } else { + corners[i]->xRot(-40 * PI / 180); + corners[i]->y -= 6 / 16.0f; + } - corners[i]->xRot(90 * PI / 180); + corners[i]->xRot(90 * PI / 180); - if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); - if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); - if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); - if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); + if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); + if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); + if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); + if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); - corners[i]->x += x + 0.5; - corners[i]->y += y + 5 / 16.0f; - corners[i]->z += z + 0.5; - } + corners[i]->x += x + 0.5; + corners[i]->y += y + 5 / 16.0f; + corners[i]->z += z + 0.5; + } - Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; - int stickX0 = 7; - int stickX1 = 9; - int stickY0 = 9; - int stickY1 = 16; + Vec3 *c0 = NULL, *c1 = NULL, *c2 = NULL, *c3 = NULL; + int stickX0 = 7; + int stickX1 = 9; + int stickY0 = 9; + int stickY1 = 16; - for (int i = 0; i < 6; i++) - { - if (i == 0) - { - c0 = corners[0]; - c1 = corners[1]; - c2 = corners[2]; - c3 = corners[3]; - u0 = tex->getU(stickX0); - v0 = tex->getV(stickY0); - u1 = tex->getU(stickX1); - v1 = tex->getV(stickY0 + 2); - } - else if (i == 1) - { - c0 = corners[7]; - c1 = corners[6]; - c2 = corners[5]; - c3 = corners[4]; - } - else if (i == 2) - { - c0 = corners[1]; - c1 = corners[0]; - c2 = corners[4]; - c3 = corners[5]; - u0 = tex->getU(stickX0); - v0 = tex->getV(stickY0); - u1 = tex->getU(stickX1); - v1 = tex->getV(stickY1); - } - else if (i == 3) - { - c0 = corners[2]; - c1 = corners[1]; - c2 = corners[5]; - c3 = corners[6]; - } - else if (i == 4) - { - c0 = corners[3]; - c1 = corners[2]; - c2 = corners[6]; - c3 = corners[7]; - } - else if (i == 5) - { - c0 = corners[0]; - c1 = corners[3]; - c2 = corners[7]; - c3 = corners[4]; - } - t->vertexUV(c0->x, c0->y, c0->z, u0, v1); - t->vertexUV(c1->x, c1->y, c1->z, u1, v1); - t->vertexUV(c2->x, c2->y, c2->z, u1, v0); - t->vertexUV(c3->x, c3->y, c3->z, u0, v0); - } + for (int i = 0; i < 6; i++) { + if (i == 0) { + c0 = corners[0]; + c1 = corners[1]; + c2 = corners[2]; + c3 = corners[3]; + u0 = tex->getU(stickX0); + v0 = tex->getV(stickY0); + u1 = tex->getU(stickX1); + v1 = tex->getV(stickY0 + 2); + } else if (i == 1) { + c0 = corners[7]; + c1 = corners[6]; + c2 = corners[5]; + c3 = corners[4]; + } else if (i == 2) { + c0 = corners[1]; + c1 = corners[0]; + c2 = corners[4]; + c3 = corners[5]; + u0 = tex->getU(stickX0); + v0 = tex->getV(stickY0); + u1 = tex->getU(stickX1); + v1 = tex->getV(stickY1); + } else if (i == 3) { + c0 = corners[2]; + c1 = corners[1]; + c2 = corners[5]; + c3 = corners[6]; + } else if (i == 4) { + c0 = corners[3]; + c1 = corners[2]; + c2 = corners[6]; + c3 = corners[7]; + } else if (i == 5) { + c0 = corners[0]; + c1 = corners[3]; + c2 = corners[7]; + c3 = corners[4]; + } + t->vertexUV(c0->x, c0->y, c0->z, u0, v1); + t->vertexUV(c1->x, c1->y, c1->z, u1, v1); + t->vertexUV(c2->x, c2->y, c2->z, u1, v0); + t->vertexUV(c3->x, c3->y, c3->z, u0, v0); + } + float hoopWidth = 1.5f / 16.0f; + float hoopHeight = 1.5f / 16.0f; + float hoopLength = 0.5f / 16.0f; + corners[0] = Vec3::newTemp(-hoopWidth, -0, -hoopHeight); + corners[1] = Vec3::newTemp(+hoopWidth, -0, -hoopHeight); + corners[2] = Vec3::newTemp(+hoopWidth, -0, +hoopHeight); + corners[3] = Vec3::newTemp(-hoopWidth, -0, +hoopHeight); + corners[4] = Vec3::newTemp(-hoopWidth, +hoopLength, -hoopHeight); + corners[5] = Vec3::newTemp(+hoopWidth, +hoopLength, -hoopHeight); + corners[6] = Vec3::newTemp(+hoopWidth, +hoopLength, +hoopHeight); + corners[7] = Vec3::newTemp(-hoopWidth, +hoopLength, +hoopHeight); - float hoopWidth = 1.5f / 16.0f; - float hoopHeight = 1.5f / 16.0f; - float hoopLength = 0.5f / 16.0f; - corners[0] = Vec3::newTemp(-hoopWidth, -0, -hoopHeight); - corners[1] = Vec3::newTemp(+hoopWidth, -0, -hoopHeight); - corners[2] = Vec3::newTemp(+hoopWidth, -0, +hoopHeight); - corners[3] = Vec3::newTemp(-hoopWidth, -0, +hoopHeight); - corners[4] = Vec3::newTemp(-hoopWidth, +hoopLength, -hoopHeight); - corners[5] = Vec3::newTemp(+hoopWidth, +hoopLength, -hoopHeight); - corners[6] = Vec3::newTemp(+hoopWidth, +hoopLength, +hoopHeight); - corners[7] = Vec3::newTemp(-hoopWidth, +hoopLength, +hoopHeight); + for (int i = 0; i < 8; i++) { + corners[i]->z += 3.5f / 16.0f; - for (int i = 0; i < 8; i++) - { - corners[i]->z += 3.5f / 16.0f; + if (powered) { + corners[i]->y -= 1.5 / 16.0f; + corners[i]->z -= 2.6 / 16.0f; + corners[i]->xRot(0 * PI / 180); + } else if (attached) { + corners[i]->y += 0.25 / 16.0f; + corners[i]->z -= 2.75 / 16.0f; + corners[i]->xRot(10 * PI / 180); + } else { + corners[i]->xRot(50 * PI / 180); + } - if (powered) - { - corners[i]->y -= 1.5 / 16.0f; - corners[i]->z -= 2.6 / 16.0f; - corners[i]->xRot(0 * PI / 180); - } - else if (attached) - { - corners[i]->y += 0.25 / 16.0f; - corners[i]->z -= 2.75 / 16.0f; - corners[i]->xRot(10 * PI / 180); - } - else - { - corners[i]->xRot(50 * PI / 180); - } + if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); + if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); + if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); + if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); - if (dir == Direction::NORTH) corners[i]->yRot(0 * PI / 180); - if (dir == Direction::SOUTH) corners[i]->yRot(180 * PI / 180); - if (dir == Direction::WEST) corners[i]->yRot(90 * PI / 180); - if (dir == Direction::EAST) corners[i]->yRot(-90 * PI / 180); + corners[i]->x += x + 0.5; + corners[i]->y += y + 5 / 16.0f; + corners[i]->z += z + 0.5; + } - corners[i]->x += x + 0.5; - corners[i]->y += y + 5 / 16.0f; - corners[i]->z += z + 0.5; - } + int hoopX0 = 5; + int hoopX1 = 11; + int hoopY0 = 3; + int hoopY1 = 9; - int hoopX0 = 5; - int hoopX1 = 11; - int hoopY0 = 3; - int hoopY1 = 9; + for (int i = 0; i < 6; i++) { + if (i == 0) { + c0 = corners[0]; + c1 = corners[1]; + c2 = corners[2]; + c3 = corners[3]; + u0 = tex->getU(hoopX0); + v0 = tex->getV(hoopY0); + u1 = tex->getU(hoopX1); + v1 = tex->getV(hoopY1); + } else if (i == 1) { + c0 = corners[7]; + c1 = corners[6]; + c2 = corners[5]; + c3 = corners[4]; + } else if (i == 2) { + c0 = corners[1]; + c1 = corners[0]; + c2 = corners[4]; + c3 = corners[5]; + u0 = tex->getU(hoopX0); + v0 = tex->getV(hoopY0); + u1 = tex->getU(hoopX1); + v1 = tex->getV(hoopY0 + 2); + } else if (i == 3) { + c0 = corners[2]; + c1 = corners[1]; + c2 = corners[5]; + c3 = corners[6]; + } else if (i == 4) { + c0 = corners[3]; + c1 = corners[2]; + c2 = corners[6]; + c3 = corners[7]; + } else if (i == 5) { + c0 = corners[0]; + c1 = corners[3]; + c2 = corners[7]; + c3 = corners[4]; + } + t->vertexUV(c0->x, c0->y, c0->z, u0, v1); + t->vertexUV(c1->x, c1->y, c1->z, u1, v1); + t->vertexUV(c2->x, c2->y, c2->z, u1, v0); + t->vertexUV(c3->x, c3->y, c3->z, u0, v0); + } - for (int i = 0; i < 6; i++) - { - if (i == 0) - { - c0 = corners[0]; - c1 = corners[1]; - c2 = corners[2]; - c3 = corners[3]; - u0 = tex->getU(hoopX0); - v0 = tex->getV(hoopY0); - u1 = tex->getU(hoopX1); - v1 = tex->getV(hoopY1); - } - else if (i == 1) - { - c0 = corners[7]; - c1 = corners[6]; - c2 = corners[5]; - c3 = corners[4]; - } - else if (i == 2) - { - c0 = corners[1]; - c1 = corners[0]; - c2 = corners[4]; - c3 = corners[5]; - u0 = tex->getU(hoopX0); - v0 = tex->getV(hoopY0); - u1 = tex->getU(hoopX1); - v1 = tex->getV(hoopY0 + 2); - } - else if (i == 3) - { - c0 = corners[2]; - c1 = corners[1]; - c2 = corners[5]; - c3 = corners[6]; - } - else if (i == 4) - { - c0 = corners[3]; - c1 = corners[2]; - c2 = corners[6]; - c3 = corners[7]; - } - else if (i == 5) - { - c0 = corners[0]; - c1 = corners[3]; - c2 = corners[7]; - c3 = corners[4]; - } - t->vertexUV(c0->x, c0->y, c0->z, u0, v1); - t->vertexUV(c1->x, c1->y, c1->z, u1, v1); - t->vertexUV(c2->x, c2->y, c2->z, u1, v0); - t->vertexUV(c3->x, c3->y, c3->z, u0, v0); - } + if (attached) { + double hoopBottomY = corners[0]->y; + float width = 0.5f / 16.0f; + float top = 0.5f - (width / 2); + float bottom = top + width; + Icon* wireTex = getTexture(Tile::tripWire); + double wireX0 = wireTex->getU0(); + double wireY0 = wireTex->getV(attached ? 2 : 0); + double wireX1 = wireTex->getU1(); + double wireY1 = wireTex->getV(attached ? 4 : 2); + double floating = (suspended ? 3.5f : 1.5f) / 16.0; - if (attached) - { - double hoopBottomY = corners[0]->y; - float width = 0.5f / 16.0f; - float top = 0.5f - (width / 2); - float bottom = top + width; - Icon *wireTex = getTexture(Tile::tripWire); - double wireX0 = wireTex->getU0(); - double wireY0 = wireTex->getV(attached ? 2 : 0); - double wireX1 = wireTex->getU1(); - double wireY1 = wireTex->getV(attached ? 4 : 2); - double floating = (suspended ? 3.5f : 1.5f) / 16.0; + brightness = tt->getBrightness(level, x, y, z) * 0.75f; + t->color(brightness, brightness, brightness); - brightness = tt->getBrightness(level, x, y, z) * 0.75f; - t->color(brightness, brightness, brightness); + if (dir == Direction::NORTH) { + t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z, wireX1, wireY0); - if (dir == Direction::NORTH) - { - t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z, wireX1, wireY0); + t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX0, wireY0); + t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); + } else if (dir == Direction::SOUTH) { + t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); + t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX1, wireY1); + t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX1, wireY0); - t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX0, wireY0); - t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); - } - else if (dir == Direction::SOUTH) - { - t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); - t->vertexUV(x + bottom, hoopBottomY, z + 0.5, wireX1, wireY1); - t->vertexUV(x + top, hoopBottomY, z + 0.5, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); + } else if (dir == Direction::WEST) { + t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); - } - else if (dir == Direction::WEST) - { - t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX1, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); + } else { + t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX0, wireY0); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX1, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); - } - else - { - t->vertexUV(x + 0.5, hoopBottomY, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.5, hoopBottomY, z + top, wireX0, wireY0); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); + } + } - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); - } - } - - return true; + return true; } -bool TileRenderer::tesselateTripwireInWorld(Tile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0); - int data = level->getData(x, y, z); - bool attached = (data & TripWireTile::MASK_ATTACHED) == TripWireTile::MASK_ATTACHED; - bool suspended = (data & TripWireTile::MASK_SUSPENDED) == TripWireTile::MASK_SUSPENDED; +bool TileRenderer::tesselateTripwireInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); + Icon* tex = getTexture(tt, 0); + int data = level->getData(x, y, z); + bool attached = + (data & TripWireTile::MASK_ATTACHED) == TripWireTile::MASK_ATTACHED; + bool suspended = + (data & TripWireTile::MASK_SUSPENDED) == TripWireTile::MASK_SUSPENDED; - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; - float brightness; - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(tt->getLightColor(level, x, y, z)); - } - brightness = tt->getBrightness(level, x, y, z) * 0.75f; - t->color(brightness, brightness, brightness); + float brightness; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tt->getLightColor(level, x, y, z)); + } + brightness = tt->getBrightness(level, x, y, z) * 0.75f; + t->color(brightness, brightness, brightness); - double wireX0 = tex->getU0(); - double wireY0 = tex->getV(attached ? 2 : 0); - double wireX1 = tex->getU1(); - double wireY1 = tex->getV(attached ? 4 : 2); - double floating = (suspended ? 3.5f : 1.5f) / 16.0; + double wireX0 = tex->getU0(); + double wireY0 = tex->getV(attached ? 2 : 0); + double wireX1 = tex->getU1(); + double wireY1 = tex->getV(attached ? 4 : 2); + double floating = (suspended ? 3.5f : 1.5f) / 16.0; - bool w = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::WEST); - bool e = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::EAST); - bool n = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::NORTH); - bool s = TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::SOUTH); + bool w = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::WEST); + bool e = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::EAST); + bool n = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::NORTH); + bool s = + TripWireTile::shouldConnectTo(level, x, y, z, data, Direction::SOUTH); - float width = 0.5f / 16.0f; - float top = 0.5f - (width / 2); - float bottom = top + width; + float width = 0.5f / 16.0f; + float top = 0.5f - (width / 2); + float bottom = top + width; - if (!n && !e && !s && !w) - { - n = true; - s = true; - } + if (!n && !e && !s && !w) { + n = true; + s = true; + } - if (n) - { - t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z, wireX1, wireY0); + if (n) { + t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); - } - if (n || (s && !e && !w)) - { - t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 0.25, wireX0, wireY0); + } + if (n || (s && !e && !w)) { + t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); - } - if (s || (n && !e && !w)) - { - t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z + 0.25, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.25, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 0.5, wireX0, wireY0); + } + if (s || (n && !e && !w)) { + t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); - } - if (s) - { - t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); - t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); - t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); + t->vertexUV(x + top, y + floating, z + 0.5, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.5, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 0.75, wireX0, wireY0); + } + if (s) { + t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); + t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); + t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); - t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); - t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); - t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); - t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); - } + t->vertexUV(x + top, y + floating, z + 0.75, wireX1, wireY0); + t->vertexUV(x + bottom, y + floating, z + 0.75, wireX1, wireY1); + t->vertexUV(x + bottom, y + floating, z + 1, wireX0, wireY1); + t->vertexUV(x + top, y + floating, z + 1, wireX0, wireY0); + } - if (w) - { - t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x, y + floating, z + top, wireX0, wireY0); + if (w) { + t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); - } - if (w || (e && !n && !s)) - { - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x, y + floating, z + bottom, wireX0, wireY1); + } + if (w || (e && !n && !s)) { + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); - } - if (e || (w && !n && !s)) - { - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.25, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.5, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.25, y + floating, z + bottom, wireX0, wireY1); + } + if (e || (w && !n && !s)) { + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); - } - if (e) - { - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); - t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.5, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 0.75, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.5, y + floating, z + bottom, wireX0, wireY1); + } + if (e) { + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); + t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); - t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); - t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); - t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); - } + t->vertexUV(x + 0.75, y + floating, z + top, wireX0, wireY0); + t->vertexUV(x + 1, y + floating, z + top, wireX1, wireY0); + t->vertexUV(x + 1, y + floating, z + bottom, wireX1, wireY1); + t->vertexUV(x + 0.75, y + floating, z + bottom, wireX0, wireY1); + } - return true; + return true; } -bool TileRenderer::tesselateFireInWorld( FireTile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateFireInWorld(FireTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *firstTex = tt->getTextureLayer(0); - Icon *secondTex = tt->getTextureLayer(1); - Icon *tex = firstTex; + Icon* firstTex = tt->getTextureLayer(0); + Icon* secondTex = tt->getTextureLayer(1); + Icon* tex = firstTex; - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->color( 1.0f, 1.0f, 1.0f ); - t->tex2( getLightColor(tt, level, x, y, z ) ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); - float h = 1.4f; + if (SharedConstants::TEXTURE_LIGHTING) { + t->color(1.0f, 1.0f, 1.0f); + t->tex2(getLightColor(tt, level, x, y, z)); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); + float h = 1.4f; - if ( level->isTopSolidBlocking( x, y - 1, z ) || Tile::fire->canBurn( level, x, y - 1, z ) ) - { - float x0 = x + 0.5f + 0.2f; - float x1 = x + 0.5f - 0.2f; - float z0 = z + 0.5f + 0.2f; - float z1 = z + 0.5f - 0.2f; + if (level->isTopSolidBlocking(x, y - 1, z) || + Tile::fire->canBurn(level, x, y - 1, z)) { + float x0 = x + 0.5f + 0.2f; + float x1 = x + 0.5f - 0.2f; + float z0 = z + 0.5f + 0.2f; + float z1 = z + 0.5f - 0.2f; - float x0_ = x + 0.5f - 0.3f; - float x1_ = x + 0.5f + 0.3f; - float z0_ = z + 0.5f - 0.3f; - float z1_ = z + 0.5f + 0.3f; + float x0_ = x + 0.5f - 0.3f; + float x1_ = x + 0.5f + 0.3f; + float z0_ = z + 0.5f - 0.3f; + float z1_ = z + 0.5f + 0.3f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 1), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 0), (float)(u0), + (float)(v0)); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 1), (float)(u0), + (float)(v0)); - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z1_), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z1_), (float)(u0), + (float)(v0)); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z0_), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z0_), (float)(u0), + (float)(v0)); - x0 = x + 0.5f - 0.5f; - x1 = x + 0.5f + 0.5f; - z0 = z + 0.5f - 0.5f; - z1 = z + 0.5f + 0.5f; + x0 = x + 0.5f - 0.5f; + x1 = x + 0.5f + 0.5f; + z0 = z + 0.5f - 0.5f; + z1 = z + 0.5f + 0.5f; - x0_ = x + 0.5f - 0.4f; - x1_ = x + 0.5f + 0.4f; - z0_ = z + 0.5f - 0.4f; - z1_ = z + 0.5f + 0.4f; + x0_ = x + 0.5f - 0.4f; + x1_ = x + 0.5f + 0.4f; + z0_ = z + 0.5f - 0.4f; + z1_ = z + 0.5f + 0.4f; - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + 0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z + 0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 0), (float)(u1), + (float)(v0)); - tex = firstTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = firstTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z1_), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z1_), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x + 1 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - } - else - { - float r = 0.2f; - float yo = 1 / 16.0f; - if ( ( ( x + y + z ) & 1 ) == 1 ) - { - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); - } - if ( ( ( x / 2 + y / 2 + z / 2 ) & 1 ) == 1 ) - { - float tmp = u1; - u1 = u0; - u0 = tmp; - } - if ( Tile::fire->canBurn( level, x - 1, y, z ) ) - { - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1), (float)(y + h), (float)(z0_), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x + 0), (float)(y + h), (float)(z0_), (float)(u1), + (float)(v0)); + } else { + float r = 0.2f; + float yo = 1 / 16.0f; + if (((x + y + z) & 1) == 1) { + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); + } + if (((x / 2 + y / 2 + z / 2) & 1) == 1) { + float tmp = u1; + u1 = u0; + u0 = tmp; + } + if (Tile::fire->canBurn(level, x - 1, y, z)) { + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 1.0f), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 0.0f), + (float)(u0), (float)(v0)); - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x + 1, y, z ) ) - { - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - 0 ), ( float )( y + 0 + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 0.0f), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + h + yo), (float)(z + 1.0f), + (float)(u1), (float)(v0)); + } + if (Tile::fire->canBurn(level, x + 1, y, z)) { + t->vertexUV((float)(x + 1 - r), (float)(y + h + yo), + (float)(z + 0.0f), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1 - 0), (float)(y + 0 + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1 - 0), (float)(y + 0 + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1 - r), (float)(y + h + yo), + (float)(z + 1.0f), (float)(u1), (float)(v0)); - t->vertexUV( ( float )( x + 1.0f - r ), ( float )( y + h + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f - 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f - 0 ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f - r ), ( float )( y + h + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x, y, z - 1 ) ) - { - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1.0f - r), (float)(y + h + yo), + (float)(z + 1.0f), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 1.0f - 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f - 0), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f - r), (float)(y + h + yo), + (float)(z + 0.0f), (float)(u0), (float)(v0)); + } + if (Tile::fire->canBurn(level, x, y, z - 1)) { + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), (float)(z + r), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), (float)(z + r), + (float)(u0), (float)(v0)); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + - r ), ( float )( u1 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x, y, z + 1 ) ) - { - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), (float)(z + r), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), (float)(z + r), + (float)(u1), (float)(v0)); + } + if (Tile::fire->canBurn(level, x, y, z + 1)) { + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u1), (float)(v0)); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + 0.0f + yo ), ( float )( z + 1.0f - - 0.0f ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h + yo ), ( float )( z + 1.0f - - r ), ( float )( u0 ), ( float )( v0 ) ); - } - if ( Tile::fire->canBurn( level, x, y + 1.0f, z ) ) - { - double x0 = x + 0.5f + 0.5f; - double x1 = x + 0.5f - 0.5f; - double z0 = z + 0.5f + 0.5f; - double z1 = z + 0.5f - 0.5f; + t->vertexUV((float)(x + 0.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f + yo), + (float)(z + 1.0f - 0.0f), (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + h + yo), + (float)(z + 1.0f - r), (float)(u0), (float)(v0)); + } + if (Tile::fire->canBurn(level, x, y + 1.0f, z)) { + double x0 = x + 0.5f + 0.5f; + double x1 = x + 0.5f - 0.5f; + double z0 = z + 0.5f + 0.5f; + double z1 = z + 0.5f - 0.5f; - double x0_ = x + 0.5f - 0.5f; - double x1_ = x + 0.5f + 0.5f; - double z0_ = z + 0.5f - 0.5f; - double z1_ = z + 0.5f + 0.5f; + double x0_ = x + 0.5f - 0.5f; + double x1_ = x + 0.5f + 0.5f; + double z0_ = z + 0.5f - 0.5f; + double z1_ = z + 0.5f + 0.5f; - tex = firstTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = firstTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - y += 1; - h = -0.2f; + y += 1; + h = -0.2f; - if ( ( ( x + y + z ) & 1 ) == 0 ) - { - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0_ ), ( float )( y + h ), ( float )( z + - 1 ), ( float )( u0 ), ( float )( v0 ) ); + if (((x + y + z) & 1) == 0) { + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 0), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 0), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z + 1), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x0_), (float)(y + h), (float)(z + 1), + (float)(u0), (float)(v0)); - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + - 1.0f ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0.0f ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1_ ), ( float )( y + h ), ( float )( z + - 0 ), ( float )( u0 ), ( float )( v0 ) ); - } - else - { - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - h ), ( float )( z1_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - 0.0f ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - 0.0f ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - h ), ( float )( z1_ ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 1.0f), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0.0f), (float)(z + 1.0f), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0.0f), (float)(z + 0), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x1_), (float)(y + h), (float)(z + 0), + (float)(u0), (float)(v0)); + } else { + t->vertexUV((float)(x + 0.0f), (float)(y + h), (float)(z1_), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f), (float)(z1), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f), (float)(z1), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 1.0f), (float)(y + h), (float)(z1_), + (float)(u0), (float)(v0)); - tex = secondTex; - u0 = tex->getU0(true); - v0 = tex->getV0(true); - u1 = tex->getU1(true); - v1 = tex->getV1(true); + tex = secondTex; + u0 = tex->getU0(true); + v0 = tex->getV0(true); + u1 = tex->getU1(true); + v1 = tex->getV1(true); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - h ), ( float )( z0_ ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + - 0.0f ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - 0.0f ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + - h ), ( float )( z0_ ), ( float )( u0 ), ( float )( v0 ) ); - } - } - } - - return true; + t->vertexUV((float)(x + 1.0f), (float)(y + h), (float)(z0_), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 1.0f), (float)(y + 0.0f), (float)(z0), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + 0.0f), (float)(z0), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0.0f), (float)(y + h), (float)(z0_), + (float)(u0), (float)(v0)); + } + } + } + return true; } -bool TileRenderer::tesselateDustInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateDustInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - int data = level->getData( x, y, z ); - Icon *crossTexture = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS); - Icon *lineTexture = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE); - Icon *crossTextureOverlay = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS_OVERLAY); - Icon *lineTextureOverlay = RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE_OVERLAY); + int data = level->getData(x, y, z); + Icon* crossTexture = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS); + Icon* lineTexture = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE); + Icon* crossTextureOverlay = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_CROSS_OVERLAY); + Icon* lineTextureOverlay = + RedStoneDustTile::getTexture(RedStoneDustTile::TEXTURE_LINE_OVERLAY); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - // 4J Stu - not used any more - //float pow = ( data / 15.0f ); - //float red = pow * 0.6f + 0.4f; - //if ( data == 0 ) red = 0.3f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + // 4J Stu - not used any more + // float pow = ( data / 15.0f ); + // float red = pow * 0.6f + 0.4f; + // if ( data == 0 ) red = 0.3f; - //float green = pow * pow * 0.7f - 0.5f; - //float blue = pow * pow * 0.6f - 0.7f; - //if ( green < 0 ) green = 0; - //if ( blue < 0 ) blue = 0; + // float green = pow * pow * 0.7f - 0.5f; + // float blue = pow * pow * 0.6f - 0.7f; + // if ( green < 0 ) green = 0; + // if ( blue < 0 ) blue = 0; - unsigned int colour = 0; - if(data == 0) - { - colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustUnlit ); - } - else - { - unsigned int minColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustLitMin ); - unsigned int maxColour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Tile_RedstoneDustLitMax ); + unsigned int colour = 0; + if (data == 0) { + colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustUnlit); + } else { + unsigned int minColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustLitMin); + unsigned int maxColour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Tile_RedstoneDustLitMax); - uint8_t redComponent = ((minColour>>16)&0xFF) + (( (maxColour>>16)&0xFF - (minColour>>16)&0xFF)*( (data-1)/14.0f)); - uint8_t greenComponent = ((minColour>>8)&0xFF) + (( (maxColour>>8)&0xFF - (minColour>>8)&0xFF)*( (data-1)/14.0f)); - uint8_t blueComponent = ((minColour)&0xFF) + (( (maxColour)&0xFF - (minColour)&0xFF)*( (data-1)/14.0f)); + uint8_t redComponent = + ((minColour >> 16) & 0xFF) + + (((maxColour >> 16) & 0xFF - (minColour >> 16) & 0xFF) * + ((data - 1) / 14.0f)); + uint8_t greenComponent = + ((minColour >> 8) & 0xFF) + + (((maxColour >> 8) & 0xFF - (minColour >> 8) & 0xFF) * + ((data - 1) / 14.0f)); + uint8_t blueComponent = + ((minColour) & 0xFF) + + (((maxColour) & 0xFF - (minColour) & 0xFF) * ((data - 1) / 14.0f)); - colour = redComponent<<16 | greenComponent<<8 | blueComponent; - } + colour = redComponent << 16 | greenComponent << 8 | blueComponent; + } - float red = ((colour>>16)&0xFF)/255.0f; - float green = ((colour>>8)&0xFF)/255.0f; - float blue = (colour&0xFF)/255.0f; + float red = ((colour >> 16) & 0xFF) / 255.0f; + float green = ((colour >> 8) & 0xFF) / 255.0f; + float blue = (colour & 0xFF) / 255.0f; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->color( red, green, blue ); - } - else - { - t->color( br * red, br * green, br * blue ); - } - const float dustOffset = 0.25f / 16.0f; - const float overlayOffset = 0.25f / 16.0f; + if (SharedConstants::TEXTURE_LIGHTING) { + t->color(red, green, blue); + } else { + t->color(br * red, br * green, br * blue); + } + const float dustOffset = 0.25f / 16.0f; + const float overlayOffset = 0.25f / 16.0f; - bool w = RedStoneDustTile::shouldConnectTo( level, x - 1, y, z, Direction::WEST ) - || ( !level->isSolidBlockingTile( x - 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x - 1, y - 1, z, - Direction::UNDEFINED ) ); - bool e = RedStoneDustTile::shouldConnectTo( level, x + 1, y, z, Direction::EAST ) - || ( !level->isSolidBlockingTile( x + 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x + 1, y - 1, z, - Direction::UNDEFINED ) ); - bool n = RedStoneDustTile::shouldConnectTo( level, x, y, z - 1, Direction::NORTH ) - || ( !level->isSolidBlockingTile( x, y, z - 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y - 1, z - 1, - Direction::UNDEFINED ) ); - bool s = RedStoneDustTile::shouldConnectTo( level, x, y, z + 1, Direction::SOUTH ) - || ( !level->isSolidBlockingTile( x, y, z + 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y - 1, z + 1, - Direction::UNDEFINED ) ); - if ( !level->isSolidBlockingTile( x, y + 1, z ) ) - { - if ( level->isSolidBlockingTile( x - 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x - 1, y + 1, z, - Direction::UNDEFINED ) ) w - = true; - if ( level->isSolidBlockingTile( x + 1, y, z ) && RedStoneDustTile::shouldConnectTo( level, x + 1, y + 1, z, - Direction::UNDEFINED ) ) e - = true; - if ( level->isSolidBlockingTile( x, y, z - 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y + 1, z - 1, - Direction::UNDEFINED ) ) n - = true; - if ( level->isSolidBlockingTile( x, y, z + 1 ) && RedStoneDustTile::shouldConnectTo( level, x, y + 1, z + 1, - Direction::UNDEFINED ) ) s - = true; - } - float x0 = ( float )( x + 0.0f ); - float x1 = ( float )( x + 1.0f ); - float z0 = ( float )( z + 0.0f ); - float z1 = ( float )( z + 1.0f ); + bool w = RedStoneDustTile::shouldConnectTo(level, x - 1, y, z, + Direction::WEST) || + (!level->isSolidBlockingTile(x - 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x - 1, y - 1, z, + Direction::UNDEFINED)); + bool e = RedStoneDustTile::shouldConnectTo(level, x + 1, y, z, + Direction::EAST) || + (!level->isSolidBlockingTile(x + 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x + 1, y - 1, z, + Direction::UNDEFINED)); + bool n = RedStoneDustTile::shouldConnectTo(level, x, y, z - 1, + Direction::NORTH) || + (!level->isSolidBlockingTile(x, y, z - 1) && + RedStoneDustTile::shouldConnectTo(level, x, y - 1, z - 1, + Direction::UNDEFINED)); + bool s = RedStoneDustTile::shouldConnectTo(level, x, y, z + 1, + Direction::SOUTH) || + (!level->isSolidBlockingTile(x, y, z + 1) && + RedStoneDustTile::shouldConnectTo(level, x, y - 1, z + 1, + Direction::UNDEFINED)); + if (!level->isSolidBlockingTile(x, y + 1, z)) { + if (level->isSolidBlockingTile(x - 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x - 1, y + 1, z, + Direction::UNDEFINED)) + w = true; + if (level->isSolidBlockingTile(x + 1, y, z) && + RedStoneDustTile::shouldConnectTo(level, x + 1, y + 1, z, + Direction::UNDEFINED)) + e = true; + if (level->isSolidBlockingTile(x, y, z - 1) && + RedStoneDustTile::shouldConnectTo(level, x, y + 1, z - 1, + Direction::UNDEFINED)) + n = true; + if (level->isSolidBlockingTile(x, y, z + 1) && + RedStoneDustTile::shouldConnectTo(level, x, y + 1, z + 1, + Direction::UNDEFINED)) + s = true; + } + float x0 = (float)(x + 0.0f); + float x1 = (float)(x + 1.0f); + float z0 = (float)(z + 0.0f); + float z1 = (float)(z + 1.0f); - int pic = 0; - if ( ( w || e ) && ( !n && !s ) ) pic = 1; - if ( ( n || s ) && ( !e && !w ) ) pic = 2; + int pic = 0; + if ((w || e) && (!n && !s)) pic = 1; + if ((n || s) && (!e && !w)) pic = 2; - if ( pic == 0 ) - { -// if ( e || n || s || w ) - int u0 = 0; - int v0 = 0; - int u1 = SharedConstants::WORLD_RESOLUTION; - int v1 = SharedConstants::WORLD_RESOLUTION; + if (pic == 0) { + // if ( e || n || s || w ) + int u0 = 0; + int v0 = 0; + int u1 = SharedConstants::WORLD_RESOLUTION; + int v1 = SharedConstants::WORLD_RESOLUTION; - int cutDistance = 5; - if (!w) x0 += cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!w) u0 += cutDistance; - if (!e) x1 -= cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!e) u1 -= cutDistance; - if (!n) z0 += cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!n) v0 += cutDistance; - if (!s) z1 -= cutDistance / (float) SharedConstants::WORLD_RESOLUTION; - if (!s) v1 -= cutDistance; - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTexture->getU(u1, true), crossTexture->getV(v1) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTexture->getU(u1, true), crossTexture->getV(v0) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTexture->getU(u0, true), crossTexture->getV(v0) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTexture->getU(u0, true), crossTexture->getV(v1) ); + int cutDistance = 5; + if (!w) x0 += cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!w) u0 += cutDistance; + if (!e) x1 -= cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!e) u1 -= cutDistance; + if (!n) z0 += cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!n) v0 += cutDistance; + if (!s) z1 -= cutDistance / (float)SharedConstants::WORLD_RESOLUTION; + if (!s) v1 -= cutDistance; + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + crossTexture->getU(u1, true), crossTexture->getV(v1)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + crossTexture->getU(u1, true), crossTexture->getV(v0)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + crossTexture->getU(u0, true), crossTexture->getV(v0)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + crossTexture->getU(u0, true), crossTexture->getV(v1)); - t->color( br, br, br ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTextureOverlay->getU(u1, true), crossTextureOverlay->getV(v1, true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTextureOverlay->getU(u1, true), crossTextureOverlay->getV(v0, true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), crossTextureOverlay->getU(u0, true), crossTextureOverlay->getV(v0, true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), crossTextureOverlay->getU(u0, true), crossTextureOverlay->getV(v1, true) ); - } - else if ( pic == 1 ) - { - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU0(true), lineTexture->getV1(true) ); + t->color(br, br, br); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + crossTextureOverlay->getU(u1, true), + crossTextureOverlay->getV(v1, true)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + crossTextureOverlay->getU(u1, true), + crossTextureOverlay->getV(v0, true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + crossTextureOverlay->getU(u0, true), + crossTextureOverlay->getV(v0, true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + crossTextureOverlay->getU(u0, true), + crossTextureOverlay->getV(v1, true)); + } else if (pic == 1) { + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + lineTexture->getU1(true), lineTexture->getV1(true)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + lineTexture->getU1(true), lineTexture->getV0(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + lineTexture->getU0(true), lineTexture->getV0(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + lineTexture->getU0(true), lineTexture->getV1(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - } - else - { - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z0 ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + dustOffset ), ( float )( z1 ), lineTexture->getU1(true), lineTexture->getV0(true) ); + t->color(br, br, br); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + } else { + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z1), + lineTexture->getU1(true), lineTexture->getV1(true)); + t->vertexUV((float)(x1), (float)(y + dustOffset), (float)(z0), + lineTexture->getU0(true), lineTexture->getV1(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z0), + lineTexture->getU0(true), lineTexture->getV0(true)); + t->vertexUV((float)(x0), (float)(y + dustOffset), (float)(z1), + lineTexture->getU1(true), lineTexture->getV0(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x1 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x0 ), ( float )( y + overlayOffset ), ( float )( z1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - } + t->color(br, br, br); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x1), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z0), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x0), (float)(y + overlayOffset), (float)(z1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + } - if ( !level->isSolidBlockingTile( x, y + 1, z ) ) - { - const float yStretch = .35f / 16.0f; + if (!level->isSolidBlockingTile(x, y + 1, z)) { + const float yStretch = .35f / 16.0f; - if ( level->isSolidBlockingTile( x - 1, y, z ) && level->getTile( x - 1, y + 1, z ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTexture->getU1(true), lineTexture->getV1(true) ); + if (level->isSolidBlockingTile(x - 1, y, z) && + level->getTile(x - 1, y + 1, z) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + dustOffset), (float)(y + 1 + yStretch), + (float)(z + 1), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + dustOffset), (float)(y + 0), (float)(z + 1), + lineTexture->getU0(true), lineTexture->getV0(true)); + t->vertexUV((float)(x + dustOffset), (float)(y + 0), (float)(z + 0), + lineTexture->getU0(true), lineTexture->getV1(true)); + t->vertexUV((float)(x + dustOffset), (float)(y + 1 + yStretch), + (float)(z + 0), lineTexture->getU1(true), + lineTexture->getV1(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - } - if ( level->isSolidBlockingTile( x + 1, y, z ) && level->getTile( x + 1, y + 1, z ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 1 - dustOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->color(br, br, br); + t->vertexUV((float)(x + overlayOffset), (float)(y + 1 + yStretch), + (float)(z + 1), lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + overlayOffset), (float)(y + 0), + (float)(z + 1), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + overlayOffset), (float)(y + 0), + (float)(z + 0), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + overlayOffset), (float)(y + 1 + yStretch), + (float)(z + 0), lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + } + if (level->isSolidBlockingTile(x + 1, y, z) && + level->getTile(x + 1, y + 1, z) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 0), + (float)(z + 1), lineTexture->getU0(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 1 + yStretch), + (float)(z + 1), lineTexture->getU1(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 1 + yStretch), + (float)(z + 0), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 1 - dustOffset), (float)(y + 0), + (float)(z + 0), lineTexture->getU0(true), + lineTexture->getV0(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 0 ), ( float )( z + 1 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 1 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 1 + yStretch ), ( float )( z + 0 ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 1 - overlayOffset ), ( float )( y + 0 ), ( float )( z + 0 ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - } - if ( level->isSolidBlockingTile( x, y, z - 1 ) && level->getTile( x, y + 1, z - 1 ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); + t->color(br, br, br); + t->vertexUV((float)(x + 1 - overlayOffset), (float)(y + 0), + (float)(z + 1), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 1 - overlayOffset), + (float)(y + 1 + yStretch), (float)(z + 1), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 1 - overlayOffset), + (float)(y + 1 + yStretch), (float)(z + 0), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 1 - overlayOffset), (float)(y + 0), + (float)(z + 0), lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + } + if (level->isSolidBlockingTile(x, y, z - 1) && + level->getTile(x, y + 1, z - 1) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + 1), (float)(y + 0), (float)(z + dustOffset), + lineTexture->getU0(true), lineTexture->getV1(true)); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + dustOffset), lineTexture->getU1(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + dustOffset), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), (float)(z + dustOffset), + lineTexture->getU0(true), lineTexture->getV0(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - } - if ( level->isSolidBlockingTile( x, y, z + 1 ) && level->getTile( x, y + 1, z + 1 ) == Tile::redStoneDust_Id ) - { - t->color( br * red, br * green, br * blue ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + 1 - dustOffset ), lineTexture->getU0(true), lineTexture->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - dustOffset ), lineTexture->getU1(true), lineTexture->getV1(true) ); + t->color(br, br, br); + t->vertexUV((float)(x + 1), (float)(y + 0), + (float)(z + overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), + (float)(z + overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + } + if (level->isSolidBlockingTile(x, y, z + 1) && + level->getTile(x, y + 1, z + 1) == Tile::redStoneDust_Id) { + t->color(br * red, br * green, br * blue); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + 1 - dustOffset), lineTexture->getU1(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 1), (float)(y + 0), + (float)(z + 1 - dustOffset), lineTexture->getU0(true), + lineTexture->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), + (float)(z + 1 - dustOffset), lineTexture->getU0(true), + lineTexture->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + 1 - dustOffset), lineTexture->getU1(true), + lineTexture->getV1(true)); - t->color( br, br, br ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 1 ), ( float )( y + 0 ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV0(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 0 ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU0(true), lineTextureOverlay->getV1(true) ); - t->vertexUV( ( float )( x + 0 ), ( float )( y + 1 + yStretch ), ( float )( z + 1 - overlayOffset ), lineTextureOverlay->getU1(true), lineTextureOverlay->getV1(true) ); - } - } - - - return true; + t->color(br, br, br); + t->vertexUV((float)(x + 1), (float)(y + 1 + yStretch), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 1), (float)(y + 0), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV0(true)); + t->vertexUV((float)(x + 0), (float)(y + 0), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU0(true), + lineTextureOverlay->getV1(true)); + t->vertexUV((float)(x + 0), (float)(y + 1 + yStretch), + (float)(z + 1 - overlayOffset), + lineTextureOverlay->getU1(true), + lineTextureOverlay->getV1(true)); + } + } + return true; } -bool TileRenderer::tesselateRailInWorld( RailTile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); - int data = level->getData( x, y, z ); +bool TileRenderer::tesselateRailInWorld(RailTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); + int data = level->getData(x, y, z); - Icon *tex = getTexture(tt, 0, data); - if (hasFixedTexture()) tex = fixedTexture; + Icon* tex = getTexture(tt, 0, data); + if (hasFixedTexture()) tex = fixedTexture; - if ( tt->isUsesDataBit() ) - { - data &= RailTile::RAIL_DIRECTION_MASK; - } + if (tt->isUsesDataBit()) { + data &= RailTile::RAIL_DIRECTION_MASK; + } - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float r = 1 / 16.0f; + float r = 1 / 16.0f; - float x0 = ( float )( x + 1 ); - float x1 = ( float )( x + 1 ); - float x2 = ( float )( x + 0 ); - float x3 = ( float )( x + 0 ); + float x0 = (float)(x + 1); + float x1 = (float)(x + 1); + float x2 = (float)(x + 0); + float x3 = (float)(x + 0); - float z0 = ( float )( z + 0 ); - float z1 = ( float )( z + 1 ); - float z2 = ( float )( z + 1 ); - float z3 = ( float )( z + 0 ); + float z0 = (float)(z + 0); + float z1 = (float)(z + 1); + float z2 = (float)(z + 1); + float z3 = (float)(z + 0); - float y0 = ( float )( y + r ); - float y1 = ( float )( y + r ); - float y2 = ( float )( y + r ); - float y3 = ( float )( y + r ); + float y0 = (float)(y + r); + float y1 = (float)(y + r); + float y2 = (float)(y + r); + float y3 = (float)(y + r); - if ( data == 1 || data == 2 || data == 3 || data == 7 ) - { - x0 = x3 = ( float )( x + 1 ); - x1 = x2 = ( float )( x + 0 ); - z0 = z1 = ( float )( z + 1 ); - z2 = z3 = ( float )( z + 0 ); - } - else if ( data == 8 ) - { - x0 = x1 = ( float )( x + 0 ); - x2 = x3 = ( float )( x + 1 ); - z0 = z3 = ( float )( z + 1 ); - z1 = z2 = ( float )( z + 0 ); - } - else if ( data == 9 ) - { - x0 = x3 = ( float )( x + 0 ); - x1 = x2 = ( float )( x + 1 ); - z0 = z1 = ( float )( z + 0 ); - z2 = z3 = ( float )( z + 1 ); - } + if (data == 1 || data == 2 || data == 3 || data == 7) { + x0 = x3 = (float)(x + 1); + x1 = x2 = (float)(x + 0); + z0 = z1 = (float)(z + 1); + z2 = z3 = (float)(z + 0); + } else if (data == 8) { + x0 = x1 = (float)(x + 0); + x2 = x3 = (float)(x + 1); + z0 = z3 = (float)(z + 1); + z1 = z2 = (float)(z + 0); + } else if (data == 9) { + x0 = x3 = (float)(x + 0); + x1 = x2 = (float)(x + 1); + z0 = z1 = (float)(z + 0); + z2 = z3 = (float)(z + 1); + } - if ( data == 2 || data == 4 ) - { - y0 += 1; - y3 += 1; - } - else if ( data == 3 || data == 5 ) - { - y1 += 1; - y2 += 1; - } + if (data == 2 || data == 4) { + y0 += 1; + y3 += 1; + } else if (data == 3 || data == 5) { + y1 += 1; + y2 += 1; + } - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x2 ), ( float )( y2 ), ( float )( z2 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x3 ), ( float )( y3 ), ( float )( z3 ), ( float )( u0 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x2), (float)(y2), (float)(z2), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x3), (float)(y3), (float)(z3), (float)(u0), + (float)(v0)); - t->vertexUV( ( float )( x3 ), ( float )( y3 ), ( float )( z3 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x2 ), ( float )( y2 ), ( float )( z2 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - - return true; + t->vertexUV((float)(x3), (float)(y3), (float)(z3), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x2), (float)(y2), (float)(z2), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u1), + (float)(v0)); + return true; } -bool TileRenderer::tesselateLadderInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateLadderInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - float br = 1; - t->color( br, br, br ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + float br = 1; + t->color(br, br, br); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - int face = level->getData( x, y, z ); + int face = level->getData(x, y, z); - float o = 0 / 16.0f; - float r = 0.05f; - if ( face == 5 ) - { - t->vertexUV( ( float )( x + r ), ( float )( y + 1 + o ), ( float )( z + 1 + - o ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 0 - o ), ( float )( z + 1 + - o ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 0 - o ), ( float )( z + 0 - - o ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 1 + o ), ( float )( z + 0 - - o ), ( float )( u1 ), ( float )( v0 ) ); - } - if ( face == 4 ) - { - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 0 - o ), ( float )( z + 1 + - o ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 1 + o ), ( float )( z + 1 + - o ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 1 + o ), ( float )( z + 0 - - o ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 - r ), ( float )( y + 0 - o ), ( float )( z + 0 - - o ), ( float )( u0 ), ( float )( v1 ) ); - } - if ( face == 3 ) - { - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 0 - o ), ( float )( z + - r ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 1 + o ), ( float )( z + - r ), ( float )( u1 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 1 + o ), ( float )( z + - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 0 - o ), ( float )( z + - r ), ( float )( u0 ), ( float )( v1 ) ); - } - if ( face == 2 ) - { - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 1 + o ), ( float )( z + 1 - - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + 1 + o ), ( float )( y + 0 - o ), ( float )( z + 1 - - r ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 0 - o ), ( float )( z + 1 - - r ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + 0 - o ), ( float )( y + 1 + o ), ( float )( z + 1 - - r ), ( float )( u1 ), ( float )( v0 ) ); - } - - return true; + float o = 0 / 16.0f; + float r = 0.05f; + if (face == 5) { + t->vertexUV((float)(x + r), (float)(y + 1 + o), (float)(z + 1 + o), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + r), (float)(y + 0 - o), (float)(z + 1 + o), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + 0 - o), (float)(z + 0 - o), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + 1 + o), (float)(z + 0 - o), + (float)(u1), (float)(v0)); + } + if (face == 4) { + t->vertexUV((float)(x + 1 - r), (float)(y + 0 - o), (float)(z + 1 + o), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1 - r), (float)(y + 1 + o), (float)(z + 1 + o), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 1 - r), (float)(y + 1 + o), (float)(z + 0 - o), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1 - r), (float)(y + 0 - o), (float)(z + 0 - o), + (float)(u0), (float)(v1)); + } + if (face == 3) { + t->vertexUV((float)(x + 1 + o), (float)(y + 0 - o), (float)(z + r), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 1 + o), (float)(y + 1 + o), (float)(z + r), + (float)(u1), (float)(v0)); + t->vertexUV((float)(x + 0 - o), (float)(y + 1 + o), (float)(z + r), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 0 - o), (float)(y + 0 - o), (float)(z + r), + (float)(u0), (float)(v1)); + } + if (face == 2) { + t->vertexUV((float)(x + 1 + o), (float)(y + 1 + o), (float)(z + 1 - r), + (float)(u0), (float)(v0)); + t->vertexUV((float)(x + 1 + o), (float)(y + 0 - o), (float)(z + 1 - r), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + 0 - o), (float)(y + 0 - o), (float)(z + 1 - r), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + 0 - o), (float)(y + 1 + o), (float)(z + 1 - r), + (float)(u1), (float)(v0)); + } + return true; } -bool TileRenderer::tesselateVineInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateVineInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0); + Icon* tex = getTexture(tt, 0); - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; + float br = 1; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + } else { + br = tt->getBrightness(level, x, y, z); + } + { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - float br = 1; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - { - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + t->color(br * r, br * g, br * b); + } - t->color( br * r, br * g, br * b ); - } + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float r = 0.05f; + int facings = level->getData(x, y, z); - float r = 0.05f; - int facings = level->getData( x, y, z ); + if ((facings & VineTile::VINE_WEST) != 0) { + t->vertexUV(x + r, y + 1, z + 1, u0, v0); + t->vertexUV(x + r, y + 0, z + 1, u0, v1); + t->vertexUV(x + r, y + 0, z + 0, u1, v1); + t->vertexUV(x + r, y + 1, z + 0, u1, v0); - if ( ( facings & VineTile::VINE_WEST ) != 0 ) - { - t->vertexUV( x + r, y + 1, z + 1, u0, v0 ); - t->vertexUV( x + r, y + 0, z + 1, u0, v1 ); - t->vertexUV( x + r, y + 0, z + 0, u1, v1 ); - t->vertexUV( x + r, y + 1, z + 0, u1, v0 ); + t->vertexUV(x + r, y + 1, z + 0, u1, v0); + t->vertexUV(x + r, y + 0, z + 0, u1, v1); + t->vertexUV(x + r, y + 0, z + 1, u0, v1); + t->vertexUV(x + r, y + 1, z + 1, u0, v0); + } + if ((facings & VineTile::VINE_EAST) != 0) { + t->vertexUV(x + 1 - r, y + 0, z + 1, u1, v1); + t->vertexUV(x + 1 - r, y + 1, z + 1, u1, v0); + t->vertexUV(x + 1 - r, y + 1, z + 0, u0, v0); + t->vertexUV(x + 1 - r, y + 0, z + 0, u0, v1); - t->vertexUV( x + r, y + 1, z + 0, u1, v0 ); - t->vertexUV( x + r, y + 0, z + 0, u1, v1 ); - t->vertexUV( x + r, y + 0, z + 1, u0, v1 ); - t->vertexUV( x + r, y + 1, z + 1, u0, v0 ); - } - if ( ( facings & VineTile::VINE_EAST ) != 0 ) - { - t->vertexUV( x + 1 - r, y + 0, z + 1, u1, v1 ); - t->vertexUV( x + 1 - r, y + 1, z + 1, u1, v0 ); - t->vertexUV( x + 1 - r, y + 1, z + 0, u0, v0 ); - t->vertexUV( x + 1 - r, y + 0, z + 0, u0, v1 ); + t->vertexUV(x + 1 - r, y + 0, z + 0, u0, v1); + t->vertexUV(x + 1 - r, y + 1, z + 0, u0, v0); + t->vertexUV(x + 1 - r, y + 1, z + 1, u1, v0); + t->vertexUV(x + 1 - r, y + 0, z + 1, u1, v1); + } + if ((facings & VineTile::VINE_NORTH) != 0) { + t->vertexUV(x + 1, y + 0, z + r, u1, v1); + t->vertexUV(x + 1, y + 1, z + r, u1, v0); + t->vertexUV(x + 0, y + 1, z + r, u0, v0); + t->vertexUV(x + 0, y + 0, z + r, u0, v1); - t->vertexUV( x + 1 - r, y + 0, z + 0, u0, v1 ); - t->vertexUV( x + 1 - r, y + 1, z + 0, u0, v0 ); - t->vertexUV( x + 1 - r, y + 1, z + 1, u1, v0 ); - t->vertexUV( x + 1 - r, y + 0, z + 1, u1, v1 ); - } - if ( ( facings & VineTile::VINE_NORTH ) != 0 ) - { - t->vertexUV( x + 1, y + 0, z + r, u1, v1 ); - t->vertexUV( x + 1, y + 1, z + r, u1, v0 ); - t->vertexUV( x + 0, y + 1, z + r, u0, v0 ); - t->vertexUV( x + 0, y + 0, z + r, u0, v1 ); + t->vertexUV(x + 0, y + 0, z + r, u0, v1); + t->vertexUV(x + 0, y + 1, z + r, u0, v0); + t->vertexUV(x + 1, y + 1, z + r, u1, v0); + t->vertexUV(x + 1, y + 0, z + r, u1, v1); + } + if ((facings & VineTile::VINE_SOUTH) != 0) { + t->vertexUV(x + 1, y + 1, z + 1 - r, u0, v0); + t->vertexUV(x + 1, y + 0, z + 1 - r, u0, v1); + t->vertexUV(x + 0, y + 0, z + 1 - r, u1, v1); + t->vertexUV(x + 0, y + 1, z + 1 - r, u1, v0); - t->vertexUV( x + 0, y + 0, z + r, u0, v1 ); - t->vertexUV( x + 0, y + 1, z + r, u0, v0 ); - t->vertexUV( x + 1, y + 1, z + r, u1, v0 ); - t->vertexUV( x + 1, y + 0, z + r, u1, v1 ); - } - if ( ( facings & VineTile::VINE_SOUTH ) != 0 ) - { - t->vertexUV( x + 1, y + 1, z + 1 - r, u0, v0 ); - t->vertexUV( x + 1, y + 0, z + 1 - r, u0, v1 ); - t->vertexUV( x + 0, y + 0, z + 1 - r, u1, v1 ); - t->vertexUV( x + 0, y + 1, z + 1 - r, u1, v0 ); + t->vertexUV(x + 0, y + 1, z + 1 - r, u1, v0); + t->vertexUV(x + 0, y + 0, z + 1 - r, u1, v1); + t->vertexUV(x + 1, y + 0, z + 1 - r, u0, v1); + t->vertexUV(x + 1, y + 1, z + 1 - r, u0, v0); + } + if (level->isSolidBlockingTile(x, y + 1, z)) { + t->vertexUV(x + 1, y + 1 - r, z + 0, u0, v0); + t->vertexUV(x + 1, y + 1 - r, z + 1, u0, v1); + t->vertexUV(x + 0, y + 1 - r, z + 1, u1, v1); + t->vertexUV(x + 0, y + 1 - r, z + 0, u1, v0); + } - t->vertexUV( x + 0, y + 1, z + 1 - r, u1, v0 ); - t->vertexUV( x + 0, y + 0, z + 1 - r, u1, v1 ); - t->vertexUV( x + 1, y + 0, z + 1 - r, u0, v1 ); - t->vertexUV( x + 1, y + 1, z + 1 - r, u0, v0 ); - } - if ( level->isSolidBlockingTile( x, y + 1, z ) ) - { - t->vertexUV( x + 1, y + 1 - r, z + 0, u0, v0 ); - t->vertexUV( x + 1, y + 1 - r, z + 1, u0, v1 ); - t->vertexUV( x + 0, y + 1 - r, z + 1, u1, v1 ); - t->vertexUV( x + 0, y + 1 - r, z + 0, u1, v0 ); - } - - return true; + return true; } -bool TileRenderer::tesselateThinFenceInWorld( ThinFenceTile* tt, int x, int y, int z ) -{ - int depth = level->getMaxBuildHeight(); - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateThinFenceInWorld(ThinFenceTile* tt, int x, int y, + int z) { + int depth = level->getMaxBuildHeight(); + Tesselator* t = Tesselator::getInstance(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color( br * r, br * g, br * b ); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - Icon *tex; - Icon *edgeTex; + Icon* tex; + Icon* edgeTex; - if ( hasFixedTexture() ) - { - tex = fixedTexture; - edgeTex = fixedTexture; - } - else - { - int data = level->getData( x, y, z ); - tex = getTexture( tt, 0, data ); - edgeTex = tt->getEdgeTexture(); - } + if (hasFixedTexture()) { + tex = fixedTexture; + edgeTex = fixedTexture; + } else { + int data = level->getData(x, y, z); + tex = getTexture(tt, 0, data); + edgeTex = tt->getEdgeTexture(); + } - int xt = tex->getX(); - int yt = tex->getY(); - float u0 = tex->getU0(true); - float u1 = tex->getU(8, true); - float u2 = tex->getU1(true); - float v0 = tex->getV0(true); - float v2 = tex->getV1(true); + int xt = tex->getX(); + int yt = tex->getY(); + float u0 = tex->getU0(true); + float u1 = tex->getU(8, true); + float u2 = tex->getU1(true); + float v0 = tex->getV0(true); + float v2 = tex->getV1(true); - int xet = edgeTex->getX(); - int yet = edgeTex->getY(); + int xet = edgeTex->getX(); + int yet = edgeTex->getY(); - float iu0 = edgeTex->getU(7, true); - float iu1 = edgeTex->getU(9, true); - float iv0 = edgeTex->getV0(true); - float iv1 = edgeTex->getV(8, true); - float iv2 = edgeTex->getV1(true); + float iu0 = edgeTex->getU(7, true); + float iu1 = edgeTex->getU(9, true); + float iv0 = edgeTex->getV0(true); + float iv1 = edgeTex->getV(8, true); + float iv2 = edgeTex->getV1(true); - float x0 = (float)x; - float x1 = x + 0.5f; - float x2 = x + 1.0f; - float z0 = (float)z; - float z1 = z + 0.5f; - float z2 = z + 1.0f; - float ix0 = x + 0.5f - 1.0f / 16.0f; - float ix1 = x + 0.5f + 1.0f / 16.0f; - float iz0 = z + 0.5f - 1.0f / 16.0f; - float iz1 = z + 0.5f + 1.0f / 16.0f; + float x0 = (float)x; + float x1 = x + 0.5f; + float x2 = x + 1.0f; + float z0 = (float)z; + float z1 = z + 0.5f; + float z2 = z + 1.0f; + float ix0 = x + 0.5f - 1.0f / 16.0f; + float ix1 = x + 0.5f + 1.0f / 16.0f; + float iz0 = z + 0.5f - 1.0f / 16.0f; + float iz1 = z + 0.5f + 1.0f / 16.0f; - bool n = tt->attachsTo( level->getTile( x, y, z - 1 ) ); - bool s = tt->attachsTo( level->getTile( x, y, z + 1 ) ); - bool w = tt->attachsTo( level->getTile( x - 1, y, z ) ); - bool e = tt->attachsTo( level->getTile( x + 1, y, z ) ); + bool n = tt->attachsTo(level->getTile(x, y, z - 1)); + bool s = tt->attachsTo(level->getTile(x, y, z + 1)); + bool w = tt->attachsTo(level->getTile(x - 1, y, z)); + bool e = tt->attachsTo(level->getTile(x + 1, y, z)); - bool up = tt->shouldRenderFace( level, x, y + 1, z, Facing::UP ); - bool down = tt->shouldRenderFace( level, x, y - 1, z, Facing::DOWN ); + bool up = tt->shouldRenderFace(level, x, y + 1, z, Facing::UP); + bool down = tt->shouldRenderFace(level, x, y - 1, z, Facing::DOWN); - const float noZFightingOffset = 0.01f; - const float noZFightingOffsetB = 0.005; + const float noZFightingOffset = 0.01f; + const float noZFightingOffsetB = 0.005; - if ( ( w && e ) || ( !w && !e && !n && !s ) ) - { - t->vertexUV( x0, y + 1, z1, u0, v0 ); - t->vertexUV( x0, y + 0, z1, u0, v2 ); - t->vertexUV( x2, y + 0, z1, u2, v2 ); - t->vertexUV( x2, y + 1, z1, u2, v0 ); + if ((w && e) || (!w && !e && !n && !s)) { + t->vertexUV(x0, y + 1, z1, u0, v0); + t->vertexUV(x0, y + 0, z1, u0, v2); + t->vertexUV(x2, y + 0, z1, u2, v2); + t->vertexUV(x2, y + 1, z1, u2, v0); - t->vertexUV( x2, y + 1, z1, u0, v0 ); - t->vertexUV( x2, y + 0, z1, u0, v2 ); - t->vertexUV( x0, y + 0, z1, u2, v2 ); - t->vertexUV( x0, y + 1, z1, u2, v0 ); + t->vertexUV(x2, y + 1, z1, u0, v0); + t->vertexUV(x2, y + 0, z1, u0, v2); + t->vertexUV(x0, y + 0, z1, u2, v2); + t->vertexUV(x0, y + 1, z1, u2, v0); - if ( up ) - { - // small edge texture - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); + if (up) { + // small edge texture + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv2); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - } - else - { - if ( y < ( depth - 1 ) && level->isEmptyTile( x - 1, y + 1, z ) ) - { - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv2); + } else { + if (y < (depth - 1) && level->isEmptyTile(x - 1, y + 1, z)) { + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - } - if ( y < ( depth - 1 ) && level->isEmptyTile( x + 1, y + 1, z ) ) - { - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + } + if (y < (depth - 1) && level->isEmptyTile(x + 1, y + 1, z)) { + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - } - } - if ( down ) - { - // small edge texture - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv2 ); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv0); + } + } + if (down) { + // small edge texture + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv2); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv2 ); - } - else - { - if ( y > 1 && level->isEmptyTile( x - 1, y - 1, z ) ) - { - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv1 ); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv2); + } else { + if (y > 1 && level->isEmptyTile(x - 1, y - 1, z)) { + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - } - if ( y > 1 && level->isEmptyTile( x + 1, y - 1, z ) ) - { - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv0 ); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + } + if (y > 1 && level->isEmptyTile(x + 1, y - 1, z)) { + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv0 ); - } - } - } - else if ( w && !e ) - { - // half-step towards west - t->vertexUV( x0, y + 1, z1, u0, v0 ); - t->vertexUV( x0, y + 0, z1, u0, v2 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 1, z1, u1, v0 ); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv0); + } + } + } else if (w && !e) { + // half-step towards west + t->vertexUV(x0, y + 1, z1, u0, v0); + t->vertexUV(x0, y + 0, z1, u0, v2); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 1, z1, u1, v0); - t->vertexUV( x1, y + 1, z1, u0, v0 ); - t->vertexUV( x1, y + 0, z1, u0, v2 ); - t->vertexUV( x0, y + 0, z1, u1, v2 ); - t->vertexUV( x0, y + 1, z1, u1, v0 ); + t->vertexUV(x1, y + 1, z1, u0, v0); + t->vertexUV(x1, y + 0, z1, u0, v2); + t->vertexUV(x0, y + 0, z1, u1, v2); + t->vertexUV(x0, y + 1, z1, u1, v0); - // small edge texture - if ( !s && !n ) - { - t->vertexUV( x1, y + 1, iz1, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz1, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz0, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz0, iu1, iv0 ); + // small edge texture + if (!s && !n) { + t->vertexUV(x1, y + 1, iz1, iu0, iv0); + t->vertexUV(x1, y + 0, iz1, iu0, iv2); + t->vertexUV(x1, y + 0, iz0, iu1, iv2); + t->vertexUV(x1, y + 1, iz0, iu1, iv0); - t->vertexUV( x1, y + 1, iz0, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz1, iu1, iv0 ); - } + t->vertexUV(x1, y + 1, iz0, iu0, iv0); + t->vertexUV(x1, y + 0, iz0, iu0, iv2); + t->vertexUV(x1, y + 0, iz1, iu1, iv2); + t->vertexUV(x1, y + 1, iz1, iu1, iv0); + } - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x - 1, y + 1, z ) ) ) - { - // small edge texture - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); + if (up || (y < (depth - 1) && level->isEmptyTile(x - 1, y + 1, z))) { + // small edge texture + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y + 1 + noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - } - if ( down || ( y > 1 && level->isEmptyTile( x - 1, y - 1, z ) ) ) - { - // small edge texture - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv1 ); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y + 1 + noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + } + if (down || (y > 1 && level->isEmptyTile(x - 1, y - 1, z))) { + // small edge texture + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv1); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x0, y - noZFightingOffset, iz1, iu1, iv2 ); - t->vertexUV( x0, y - noZFightingOffset, iz0, iu0, iv2 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - } + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x0, y - noZFightingOffset, iz1, iu1, iv2); + t->vertexUV(x0, y - noZFightingOffset, iz0, iu0, iv2); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + } - } - else if ( !w && e ) - { - // half-step towards east - t->vertexUV( x1, y + 1, z1, u1, v0 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x2, y + 0, z1, u2, v2 ); - t->vertexUV( x2, y + 1, z1, u2, v0 ); + } else if (!w && e) { + // half-step towards east + t->vertexUV(x1, y + 1, z1, u1, v0); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x2, y + 0, z1, u2, v2); + t->vertexUV(x2, y + 1, z1, u2, v0); - t->vertexUV( x2, y + 1, z1, u1, v0 ); - t->vertexUV( x2, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 0, z1, u2, v2 ); - t->vertexUV( x1, y + 1, z1, u2, v0 ); + t->vertexUV(x2, y + 1, z1, u1, v0); + t->vertexUV(x2, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 0, z1, u2, v2); + t->vertexUV(x1, y + 1, z1, u2, v0); - // small edge texture - if ( !s && !n ) - { - t->vertexUV( x1, y + 1, iz0, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz0, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz1, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz1, iu1, iv0 ); + // small edge texture + if (!s && !n) { + t->vertexUV(x1, y + 1, iz0, iu0, iv0); + t->vertexUV(x1, y + 0, iz0, iu0, iv2); + t->vertexUV(x1, y + 0, iz1, iu1, iv2); + t->vertexUV(x1, y + 1, iz1, iu1, iv0); - t->vertexUV( x1, y + 1, iz1, iu0, iv0 ); - t->vertexUV( x1, y + 0, iz1, iu0, iv2 ); - t->vertexUV( x1, y + 0, iz0, iu1, iv2 ); - t->vertexUV( x1, y + 1, iz0, iu1, iv0 ); - } + t->vertexUV(x1, y + 1, iz1, iu0, iv0); + t->vertexUV(x1, y + 0, iz1, iu0, iv2); + t->vertexUV(x1, y + 0, iz0, iu1, iv2); + t->vertexUV(x1, y + 1, iz0, iu1, iv0); + } - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x + 1, y + 1, z ) ) ) - { - // small edge texture - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); + if (up || (y < (depth - 1) && level->isEmptyTile(x + 1, y + 1, z))) { + // small edge texture + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y + 1 + noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y + 1 + noZFightingOffset, iz0, iu0, iv0 ); - } - if ( down || ( y > 1 && level->isEmptyTile( x + 1, y - 1, z ) ) ) - { - // small edge texture - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv0 ); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y + 1 + noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y + 1 + noZFightingOffset, iz0, iu0, iv0); + } + if (down || (y > 1 && level->isEmptyTile(x + 1, y - 1, z))) { + // small edge texture + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv0); - t->vertexUV( x2, y - noZFightingOffset, iz1, iu1, iv0 ); - t->vertexUV( x1, y - noZFightingOffset, iz1, iu1, iv1 ); - t->vertexUV( x1, y - noZFightingOffset, iz0, iu0, iv1 ); - t->vertexUV( x2, y - noZFightingOffset, iz0, iu0, iv0 ); - } + t->vertexUV(x2, y - noZFightingOffset, iz1, iu1, iv0); + t->vertexUV(x1, y - noZFightingOffset, iz1, iu1, iv1); + t->vertexUV(x1, y - noZFightingOffset, iz0, iu0, iv1); + t->vertexUV(x2, y - noZFightingOffset, iz0, iu0, iv0); + } + } - } + if ((n && s) || (!w && !e && !n && !s)) { + // straight north-south + t->vertexUV(x1, y + 1, z2, u0, v0); + t->vertexUV(x1, y + 0, z2, u0, v2); + t->vertexUV(x1, y + 0, z0, u2, v2); + t->vertexUV(x1, y + 1, z0, u2, v0); - if ( ( n && s ) || ( !w && !e && !n && !s ) ) - { - // straight north-south - t->vertexUV( x1, y + 1, z2, u0, v0 ); - t->vertexUV( x1, y + 0, z2, u0, v2 ); - t->vertexUV( x1, y + 0, z0, u2, v2 ); - t->vertexUV( x1, y + 1, z0, u2, v0 ); + t->vertexUV(x1, y + 1, z0, u0, v0); + t->vertexUV(x1, y + 0, z0, u0, v2); + t->vertexUV(x1, y + 0, z2, u2, v2); + t->vertexUV(x1, y + 1, z2, u2, v0); - t->vertexUV( x1, y + 1, z0, u0, v0 ); - t->vertexUV( x1, y + 0, z0, u0, v2 ); - t->vertexUV( x1, y + 0, z2, u2, v2 ); - t->vertexUV( x1, y + 1, z2, u2, v0 ); + if (up) { + // small edge texture + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu0, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv2); - if ( up ) - { - // small edge texture - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu0, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv2 ); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu0, iv2); + } else { + if (y < (depth - 1) && level->isEmptyTile(x, y + 1, z - 1)) { + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv0); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu0, iv2 ); - } - else - { - if ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z - 1 ) ) - { - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv0); + } + if (y < (depth - 1) && level->isEmptyTile(x, y + 1, z + 1)) { + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv1); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv0 ); - } - if ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z + 1 ) ) - { - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv1); + } + } + if (down) { + // small edge texture + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu0, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv2); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv1 ); - } - } - if ( down ) - { - // small edge texture - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu0, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv2 ); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu0, iv2); + } else { + if (y > 1 && level->isEmptyTile(x, y - 1, z - 1)) { + // north half-step + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv0); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu0, iv2 ); - } - else - { - if ( y > 1 && level->isEmptyTile( x, y - 1, z - 1 ) ) - { - // north half-step - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv0); + } + if (y > 1 && level->isEmptyTile(x, y - 1, z + 1)) { + // south half-step + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv1); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv0 ); - } - if ( y > 1 && level->isEmptyTile( x, y - 1, z + 1 ) ) - { - // south half-step - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv1); + } + } - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv1 ); - } - } + } else if (n && !s) { + // half-step towards north + t->vertexUV(x1, y + 1, z0, u0, v0); + t->vertexUV(x1, y + 0, z0, u0, v2); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 1, z1, u1, v0); - } - else if ( n && !s ) - { - // half-step towards north - t->vertexUV( x1, y + 1, z0, u0, v0 ); - t->vertexUV( x1, y + 0, z0, u0, v2 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 1, z1, u1, v0 ); + t->vertexUV(x1, y + 1, z1, u0, v0); + t->vertexUV(x1, y + 0, z1, u0, v2); + t->vertexUV(x1, y + 0, z0, u1, v2); + t->vertexUV(x1, y + 1, z0, u1, v0); - t->vertexUV( x1, y + 1, z1, u0, v0 ); - t->vertexUV( x1, y + 0, z1, u0, v2 ); - t->vertexUV( x1, y + 0, z0, u1, v2 ); - t->vertexUV( x1, y + 1, z0, u1, v0 ); + // small edge texture + if (!e && !w) { + t->vertexUV(ix0, y + 1, z1, iu0, iv0); + t->vertexUV(ix0, y + 0, z1, iu0, iv2); + t->vertexUV(ix1, y + 0, z1, iu1, iv2); + t->vertexUV(ix1, y + 1, z1, iu1, iv0); - // small edge texture - if ( !e && !w ) - { - t->vertexUV( ix0, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix0, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1, z1, iu1, iv0 ); + t->vertexUV(ix1, y + 1, z1, iu0, iv0); + t->vertexUV(ix1, y + 0, z1, iu0, iv2); + t->vertexUV(ix0, y + 0, z1, iu1, iv2); + t->vertexUV(ix0, y + 1, z1, iu1, iv0); + } - t->vertexUV( ix1, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix1, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix0, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix0, y + 1, z1, iu1, iv0 ); - } + if (up || (y < (depth - 1) && level->isEmptyTile(x, y + 1, z - 1))) { + // small edge texture + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv0); - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z - 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu0, iv0); + } - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu0, iv0 ); - } + if (down || (y > 1 && level->isEmptyTile(x, y - 1, z - 1))) { + // small edge texture + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv0); - if ( down || ( y > 1 && level->isEmptyTile( x, y - 1, z - 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv0 ); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu1, iv0); + t->vertexUV(ix0, y - noZFightingOffset, z0, iu1, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z0, iu0, iv1); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu0, iv0); + } - t->vertexUV( ix0, y - noZFightingOffset, z1, iu1, iv0 ); - t->vertexUV( ix0, y - noZFightingOffset, z0, iu1, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z0, iu0, iv1 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu0, iv0 ); - } + } else if (!n && s) { + // half-step towards south + t->vertexUV(x1, y + 1, z1, u1, v0); + t->vertexUV(x1, y + 0, z1, u1, v2); + t->vertexUV(x1, y + 0, z2, u2, v2); + t->vertexUV(x1, y + 1, z2, u2, v0); - } - else if ( !n && s ) - { - // half-step towards south - t->vertexUV( x1, y + 1, z1, u1, v0 ); - t->vertexUV( x1, y + 0, z1, u1, v2 ); - t->vertexUV( x1, y + 0, z2, u2, v2 ); - t->vertexUV( x1, y + 1, z2, u2, v0 ); + t->vertexUV(x1, y + 1, z2, u1, v0); + t->vertexUV(x1, y + 0, z2, u1, v2); + t->vertexUV(x1, y + 0, z1, u2, v2); + t->vertexUV(x1, y + 1, z1, u2, v0); - t->vertexUV( x1, y + 1, z2, u1, v0 ); - t->vertexUV( x1, y + 0, z2, u1, v2 ); - t->vertexUV( x1, y + 0, z1, u2, v2 ); - t->vertexUV( x1, y + 1, z1, u2, v0 ); + // small edge texture + if (!e && !w) { + t->vertexUV(ix1, y + 1, z1, iu0, iv0); + t->vertexUV(ix1, y + 0, z1, iu0, iv2); + t->vertexUV(ix0, y + 0, z1, iu1, iv2); + t->vertexUV(ix0, y + 1, z1, iu1, iv0); - // small edge texture - if ( !e && !w ) - { - t->vertexUV( ix1, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix1, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix0, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix0, y + 1, z1, iu1, iv0 ); + t->vertexUV(ix0, y + 1, z1, iu0, iv0); + t->vertexUV(ix0, y + 0, z1, iu0, iv2); + t->vertexUV(ix1, y + 0, z1, iu1, iv2); + t->vertexUV(ix1, y + 1, z1, iu1, iv0); + } - t->vertexUV( ix0, y + 1, z1, iu0, iv0 ); - t->vertexUV( ix0, y + 0, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 0, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1, z1, iu1, iv0 ); - } + if (up || (y < (depth - 1) && level->isEmptyTile(x, y + 1, z + 1))) { + // small edge texture + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv1); - if ( up || ( y < ( depth - 1 ) && level->isEmptyTile( x, y + 1, z + 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y + 1 + noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y + 1 + noZFightingOffset, z2, iu1, iv1); + } + if (down || (y > 1 && level->isEmptyTile(x, y - 1, z + 1))) { + // small edge texture + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv1); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y + 1 + noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y + 1 + noZFightingOffset, z2, iu1, iv1 ); - } - if ( down || ( y > 1 && level->isEmptyTile( x, y - 1, z + 1 ) ) ) - { - // small edge texture - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv1 ); + t->vertexUV(ix0, y - noZFightingOffset, z2, iu0, iv1); + t->vertexUV(ix0, y - noZFightingOffset, z1, iu0, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z1, iu1, iv2); + t->vertexUV(ix1, y - noZFightingOffset, z2, iu1, iv1); + } + } - t->vertexUV( ix0, y - noZFightingOffset, z2, iu0, iv1 ); - t->vertexUV( ix0, y - noZFightingOffset, z1, iu0, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z1, iu1, iv2 ); - t->vertexUV( ix1, y - noZFightingOffset, z2, iu1, iv1 ); - } - - } - - return true; + return true; } -bool TileRenderer::tesselateCrossInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateCrossInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } - t->color( br * r, br * g, br * b ); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - float xt = (float)x; - float yt = (float)y; - float zt = (float)z; + float xt = (float)x; + float yt = (float)y; + float zt = (float)z; - if (tt == Tile::tallgrass) - { - // 4jcraft add a bunch of casts to prevent overflow (i pray to god) - int64_t seed = ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); - seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + ((uint64_t)seed * 11ULL)); + if (tt == Tile::tallgrass) { + // 4jcraft add a bunch of casts to prevent overflow (i pray to god) + int64_t seed = + ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); + seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + + ((uint64_t)seed * 11ULL)); - xt += ((((seed >> 16) & 0xf) / 15.0f) - 0.5f) * 0.5f; - yt += ((((seed >> 20) & 0xf) / 15.0f) - 1.0f) * 0.2f; - zt += ((((seed >> 24) & 0xf) / 15.0f) - 0.5f) * 0.5f; - } + xt += ((((seed >> 16) & 0xf) / 15.0f) - 0.5f) * 0.5f; + yt += ((((seed >> 20) & 0xf) / 15.0f) - 1.0f) * 0.2f; + zt += ((((seed >> 24) & 0xf) / 15.0f) - 0.5f) * 0.5f; + } - tesselateCrossTexture( tt, level->getData( x, y, z ), xt, yt, zt, 1 ); - return true; + tesselateCrossTexture(tt, level->getData(x, y, z), xt, yt, zt, 1); + return true; } -bool TileRenderer::tesselateStemInWorld( Tile* _tt, int x, int y, int z ) -{ - StemTile* tt = ( StemTile* )_tt; - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateStemInWorld(Tile* _tt, int x, int y, int z) { + StemTile* tt = (StemTile*)_tt; + Tesselator* t = Tesselator::getInstance(); - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30.0f + g * 59.0f + b * 11.0f ) / 100.0f; - float cg = ( r * 30.0f + g * 70.0f ) / ( 100.0f ); - float cb = ( r * 30.0f + b * 70.0f ) / ( 100.0f ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30.0f + g * 59.0f + b * 11.0f) / 100.0f; + float cg = (r * 30.0f + g * 70.0f) / (100.0f); + float cb = (r * 30.0f + b * 70.0f) / (100.0f); - r = cr; - g = cg; - b = cb; - } - t->color( br * r, br * g, br * b ); + r = cr; + g = cg; + b = cb; + } + t->color(br * r, br * g, br * b); - tt->updateShape( level, x, y, z ); - int dir = tt->getConnectDir( level, x, y, z ); - if ( dir < 0 ) - { - tesselateStemTexture( tt, level->getData( x, y, z ), tileShapeY1, x, y - 1 / 16.0f, z ); - } - else - { - tesselateStemTexture( tt, level->getData( x, y, z ), 0.5f, x, y - 1 / 16.0f, z ); - tesselateStemDirTexture( tt, level->getData( x, y, z ), dir, tileShapeY1, x, y - 1 / 16.0f, z ); - } - return true; + tt->updateShape(level, x, y, z); + int dir = tt->getConnectDir(level, x, y, z); + if (dir < 0) { + tesselateStemTexture(tt, level->getData(x, y, z), tileShapeY1, x, + y - 1 / 16.0f, z); + } else { + tesselateStemTexture(tt, level->getData(x, y, z), 0.5f, x, + y - 1 / 16.0f, z); + tesselateStemDirTexture(tt, level->getData(x, y, z), dir, tileShapeY1, + x, y - 1 / 16.0f, z); + } + return true; } -bool TileRenderer::tesselateRowInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateRowInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - t->color( 1.0f, 1.0f, 1.0f ); - } - else - { - float br = tt->getBrightness( level, x, y, z ); - t->color( br, br, br ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + t->color(br, br, br); + } - tesselateRowTexture( tt, level->getData( x, y, z ), x, y - 1.0f / 16.0f, z ); - return true; + tesselateRowTexture(tt, level->getData(x, y, z), x, y - 1.0f / 16.0f, z); + return true; } -void TileRenderer::tesselateTorch( Tile* tt, float x, float y, float z, float xxa, float zza, int data ) -{ - Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, Facing::DOWN, data); +void TileRenderer::tesselateTorch(Tile* tt, float x, float y, float z, + float xxa, float zza, int data) { + Tesselator* t = Tesselator::getInstance(); + Icon* tex = getTexture(tt, Facing::DOWN, data); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float ut0 = tex->getU(7, true); - float vt0 = tex->getV(6, true); - float ut1 = tex->getU(9, true); - float vt1 = tex->getV(8, true); + float ut0 = tex->getU(7, true); + float vt0 = tex->getV(6, true); + float ut1 = tex->getU(9, true); + float vt1 = tex->getV(8, true); - float ub0 = tex->getU(7, true); - float vb0 = tex->getV(13, true); - float ub1 = tex->getU(9, true); - float vb1 = tex->getV(15, true); + float ub0 = tex->getU(7, true); + float vb0 = tex->getV(13, true); + float ub1 = tex->getU(9, true); + float vb1 = tex->getV(15, true); - x += 0.5f; - z += 0.5f; + x += 0.5f; + z += 0.5f; - float x0 = x - 0.5f; - float x1 = x + 0.5f; - float z0 = z - 0.5f; - float z1 = z + 0.5f; - float r = 1 / 16.0f; + float x0 = x - 0.5f; + float x1 = x + 0.5f; + float z0 = z - 0.5f; + float z1 = z + 0.5f; + float r = 1 / 16.0f; - float h = 10.0f / 16.0f; - t->vertexUV( ( float )( x + xxa * ( 1 - h ) - r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) - r ), ut0, vt0 ); - t->vertexUV( ( float )( x + xxa * ( 1 - h ) - r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) + r ), ut0, vt1 ); - t->vertexUV( ( float )( x + xxa * ( 1 - h ) + r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) + r ), ut1, vt1 ); - t->vertexUV( ( float )( x + xxa * ( 1 - h ) + r ), ( float )( y + h ), ( float )( z + zza * ( 1 - h ) - r ), ut1, vt0 ); + float h = 10.0f / 16.0f; + t->vertexUV((float)(x + xxa * (1 - h) - r), (float)(y + h), + (float)(z + zza * (1 - h) - r), ut0, vt0); + t->vertexUV((float)(x + xxa * (1 - h) - r), (float)(y + h), + (float)(z + zza * (1 - h) + r), ut0, vt1); + t->vertexUV((float)(x + xxa * (1 - h) + r), (float)(y + h), + (float)(z + zza * (1 - h) + r), ut1, vt1); + t->vertexUV((float)(x + xxa * (1 - h) + r), (float)(y + h), + (float)(z + zza * (1 - h) - r), ut1, vt0); - t->vertexUV( (float)(x + r + xxa), (float) y, (float)(z - r + zza), ub1, vb0); - t->vertexUV( (float)(x + r + xxa), (float) y, (float)(z + r + zza), ub1, vb1); - t->vertexUV( (float)(x - r + xxa), (float) y, (float)(z + r + zza), ub0, vb1); - t->vertexUV( (float)(x - r + xxa), (float) y, (float)(z - r + zza), ub0, vb0); + t->vertexUV((float)(x + r + xxa), (float)y, (float)(z - r + zza), ub1, vb0); + t->vertexUV((float)(x + r + xxa), (float)y, (float)(z + r + zza), ub1, vb1); + t->vertexUV((float)(x - r + xxa), (float)y, (float)(z + r + zza), ub0, vb1); + t->vertexUV((float)(x - r + xxa), (float)y, (float)(z - r + zza), ub0, vb0); - t->vertexUV( ( float )( x - r ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x - r + xxa ), ( float )( y + 0 ), ( float )( z0 + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x - r + xxa ), ( float )( y + 0 ), ( float )( z1 + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x - r ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x - r), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x - r + xxa), (float)(y + 0), (float)(z0 + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x - r + xxa), (float)(y + 0), (float)(z1 + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x - r), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x + r ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x + xxa + r ), ( float )( y + 0 ), ( float )( z1 + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + xxa + r ), ( float )( y + 0 ), ( float )( z0 + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x + r ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x + r), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x + xxa + r), (float)(y + 0), (float)(z1 + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x + xxa + r), (float)(y + 0), (float)(z0 + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x + r), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z + r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 + xxa ), ( float )( y + 0 ), ( float )( z + r + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 + xxa ), ( float )( y + 0 ), ( float )( z + r + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z + r ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z + r), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0 + xxa), (float)(y + 0), (float)(z + r + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x1 + xxa), (float)(y + 0), (float)(z + r + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z + r), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z - r ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 + xxa ), ( float )( y + 0 ), ( float )( z - r + - zza ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 + xxa ), ( float )( y + 0 ), ( float )( z - r + - zza ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z - r ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z - r), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1 + xxa), (float)(y + 0), (float)(z - r + zza), + (float)(u0), (float)(v1)); + t->vertexUV((float)(x0 + xxa), (float)(y + 0), (float)(z - r + zza), + (float)(u1), (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z - r), (float)(u1), + (float)(v0)); } -void TileRenderer::tesselateCrossTexture( Tile* tt, int data, float x, float y, float z, float scale ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::tesselateCrossTexture(Tile* tt, int data, float x, float y, + float z, float scale) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0, data); + Icon* tex = getTexture(tt, 0, data); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float width = 0.45 * scale; - float x0 = x + 0.5 - width; - float x1 = x + 0.5 + width; - float z0 = z + 0.5 - width; - float z1 = z + 0.5 + width; + float width = 0.45 * scale; + float x0 = x + 0.5 - width; + float x1 = x + 0.5 + width; + float z0 = z + 0.5 - width; + float z1 = z + 0.5 + width; - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - - t->vertexUV( ( float )( x1 ), ( float )( y + scale ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + scale ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + scale), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + scale), (float)(z1), (float)(u1), + (float)(v0)); } -void TileRenderer::tesselateStemTexture( Tile* tt, int data, float h, float x, float y, float z ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::tesselateStemTexture(Tile* tt, int data, float h, float x, + float y, float z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, 0, data); + Icon* tex = getTexture(tt, 0, data); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV(h * SharedConstants::WORLD_RESOLUTION, true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV(h * SharedConstants::WORLD_RESOLUTION, true); - float x0 = x + 0.5f - 0.45f; - float x1 = x + 0.5f + 0.45f; - float z0 = z + 0.5f - 0.45f; - float z1 = z + 0.5f + 0.45f; + float x0 = x + 0.5f - 0.45f; + float x1 = x + 0.5f + 0.45f; + float z0 = z + 0.5f - 0.45f; + float z1 = z + 0.5f + 0.45f; - t->vertexUV( x0, y + h, z0, u0, v0 ); - t->vertexUV( x0, y + 0, z0, u0, v1 ); - t->vertexUV( x1, y + 0, z1, u1, v1 ); - t->vertexUV( x1, y + h, z1, u1, v0 ); + t->vertexUV(x0, y + h, z0, u0, v0); + t->vertexUV(x0, y + 0, z0, u0, v1); + t->vertexUV(x1, y + 0, z1, u1, v1); + t->vertexUV(x1, y + h, z1, u1, v0); - t->vertexUV( x1, y + h, z1, u0, v0 ); - t->vertexUV( x1, y + 0, z1, u0, v1 ); - t->vertexUV( x0, y + 0, z0, u1, v1 ); - t->vertexUV( x0, y + h, z0, u1, v0 ); + t->vertexUV(x1, y + h, z1, u0, v0); + t->vertexUV(x1, y + 0, z1, u0, v1); + t->vertexUV(x0, y + 0, z0, u1, v1); + t->vertexUV(x0, y + h, z0, u1, v0); - t->vertexUV( x0, y + h, z1, u0, v0 ); - t->vertexUV( x0, y + 0, z1, u0, v1 ); - t->vertexUV( x1, y + 0, z0, u1, v1 ); - t->vertexUV( x1, y + h, z0, u1, v0 ); + t->vertexUV(x0, y + h, z1, u0, v0); + t->vertexUV(x0, y + 0, z1, u0, v1); + t->vertexUV(x1, y + 0, z0, u1, v1); + t->vertexUV(x1, y + h, z0, u1, v0); - t->vertexUV( x1, y + h, z0, u0, v0 ); - t->vertexUV( x1, y + 0, z0, u0, v1 ); - t->vertexUV( x0, y + 0, z1, u1, v1 ); - t->vertexUV( x0, y + h, z1, u1, v0 ); + t->vertexUV(x1, y + h, z0, u0, v0); + t->vertexUV(x1, y + 0, z0, u0, v1); + t->vertexUV(x0, y + 0, z1, u1, v1); + t->vertexUV(x0, y + h, z1, u1, v0); } -bool TileRenderer::tesselateLilypadInWorld(Tile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateLilypadInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = getTexture(tt, Facing::UP); + Icon* tex = getTexture(tt, Facing::UP); - if (hasFixedTexture()) tex = fixedTexture; + if (hasFixedTexture()) tex = fixedTexture; float h = 0.25f / 16.0f; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); // 4jcraft add a bunch of casts to prevent overflow (i pray to god) - int64_t seed = ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); - seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + ((uint64_t)seed * 11ULL)); - int dir = (int) ((seed >> 16) & 0x3); - - + int64_t seed = + ((int64_t)x * 3129871) ^ ((int64_t)z * 116129781L) ^ ((int64_t)y); + seed = (int64_t)(((uint64_t)seed * (uint64_t)seed * 42317861ULL) + + ((uint64_t)seed * 11ULL)); + int dir = (int)((seed >> 16) & 0x3); t->tex2(getLightColor(tt, level, x, y, z)); @@ -3848,2128 +3817,2111 @@ bool TileRenderer::tesselateLilypadInWorld(Tile *tt, int x, int y, int z) t->vertexUV(xx + c + s, y + h, zz - c + s, u1, v0); t->vertexUV(xx + c - s, y + h, zz + c + s, u0, v0); - return true; } -void TileRenderer::tesselateStemDirTexture( StemTile* tt, int data, int dir, float h, float x, float y, float z ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::tesselateStemDirTexture(StemTile* tt, int data, int dir, + float h, float x, float y, float z) { + Tesselator* t = Tesselator::getInstance(); - Icon *tex = tt->getAngledTexture(); + Icon* tex = tt->getAngledTexture(); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - float x0 = x + 0.5f - 0.5f; - float x1 = x + 0.5f + 0.5f; - float z0 = z + 0.5f - 0.5f; - float z1 = z + 0.5f + 0.5f; + float x0 = x + 0.5f - 0.5f; + float x1 = x + 0.5f + 0.5f; + float z0 = z + 0.5f - 0.5f; + float z1 = z + 0.5f + 0.5f; - float xm = x + 0.5f; - float zm = z + 0.5f; + float xm = x + 0.5f; + float zm = z + 0.5f; - if ( ( dir + 1 ) / 2 % 2 == 1 ) - { - float tmp = u1; - u1 = u0; - u0 = tmp; - } + if ((dir + 1) / 2 % 2 == 1) { + float tmp = u1; + u1 = u0; + u0 = tmp; + } - if ( dir < 2 ) - { - t->vertexUV( x0, y + h, zm, u0, v0 ); - t->vertexUV( x0, y + 0, zm, u0, v1 ); - t->vertexUV( x1, y + 0, zm, u1, v1 ); - t->vertexUV( x1, y + h, zm, u1, v0 ); + if (dir < 2) { + t->vertexUV(x0, y + h, zm, u0, v0); + t->vertexUV(x0, y + 0, zm, u0, v1); + t->vertexUV(x1, y + 0, zm, u1, v1); + t->vertexUV(x1, y + h, zm, u1, v0); - t->vertexUV( x1, y + h, zm, u1, v0 ); - t->vertexUV( x1, y + 0, zm, u1, v1 ); - t->vertexUV( x0, y + 0, zm, u0, v1 ); - t->vertexUV( x0, y + h, zm, u0, v0 ); - } - else - { - t->vertexUV( xm, y + h, z1, u0, v0 ); - t->vertexUV( xm, y + 0, z1, u0, v1 ); - t->vertexUV( xm, y + 0, z0, u1, v1 ); - t->vertexUV( xm, y + h, z0, u1, v0 ); + t->vertexUV(x1, y + h, zm, u1, v0); + t->vertexUV(x1, y + 0, zm, u1, v1); + t->vertexUV(x0, y + 0, zm, u0, v1); + t->vertexUV(x0, y + h, zm, u0, v0); + } else { + t->vertexUV(xm, y + h, z1, u0, v0); + t->vertexUV(xm, y + 0, z1, u0, v1); + t->vertexUV(xm, y + 0, z0, u1, v1); + t->vertexUV(xm, y + h, z0, u1, v0); - t->vertexUV( xm, y + h, z0, u1, v0 ); - t->vertexUV( xm, y + 0, z0, u1, v1 ); - t->vertexUV( xm, y + 0, z1, u0, v1 ); - t->vertexUV( xm, y + h, z1, u0, v0 ); - } + t->vertexUV(xm, y + h, z0, u1, v0); + t->vertexUV(xm, y + 0, z0, u1, v1); + t->vertexUV(xm, y + 0, z1, u0, v1); + t->vertexUV(xm, y + h, z1, u0, v0); + } } +void TileRenderer::tesselateRowTexture(Tile* tt, int data, float x, float y, + float z) { + Tesselator* t = Tesselator::getInstance(); -void TileRenderer::tesselateRowTexture( Tile* tt, int data, float x, float y, float z ) -{ - Tesselator* t = Tesselator::getInstance(); + Icon* tex = getTexture(tt, 0, data); - Icon *tex = getTexture(tt, 0, data); + if (hasFixedTexture()) tex = fixedTexture; + float u0 = tex->getU0(true); + float v0 = tex->getV0(true); + float u1 = tex->getU1(true); + float v1 = tex->getV1(true); - if (hasFixedTexture()) tex = fixedTexture; - float u0 = tex->getU0(true); - float v0 = tex->getV0(true); - float u1 = tex->getU1(true); - float v1 = tex->getV1(true); + float x0 = x + 0.5f - 0.25f; + float x1 = x + 0.5f + 0.25f; + float z0 = z + 0.5f - 0.5f; + float z1 = z + 0.5f + 0.5f; - float x0 = x + 0.5f - 0.25f; - float x1 = x + 0.5f + 0.25f; - float z0 = z + 0.5f - 0.5f; - float z1 = z + 0.5f + 0.5f; + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + x0 = x + 0.5f - 0.5f; + x1 = x + 0.5f + 0.5f; + z0 = z + 0.5f - 0.25f; + z1 = z + 0.5f + 0.25f; - x0 = x + 0.5f - 0.5f; - x1 = x + 0.5f + 0.5f; - z0 = z + 0.5f - 0.25f; - z1 = z + 0.5f + 0.25f; + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z0), (float)(u1), + (float)(v0)); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z0 ), ( float )( u1 ), ( float )( v0 ) ); - - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); - - t->vertexUV( ( float )( x0 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u0 ), ( float )( v0 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u0 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v0 ) ); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 1), (float)(z1), (float)(u0), + (float)(v0)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z1), (float)(u0), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x1), (float)(y + 1), (float)(z1), (float)(u1), + (float)(v0)); } -bool TileRenderer::tesselateWaterInWorld( Tile* tt, int x, int y, int z ) -{ - // 4J Java comment - // TODO: This all needs to change. Somehow. - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateWaterInWorld(Tile* tt, int x, int y, int z) { + // 4J Java comment + // TODO: This all needs to change. Somehow. + Tesselator* t = Tesselator::getInstance(); - int col = tt->getColor( level, x, y, z ); - float r = ( col >> 16 & 0xff ) / 255.0f; - float g = ( col >> 8 & 0xff ) / 255.0f; - float b = ( col & 0xff ) / 255.0f; - bool up = tt->shouldRenderFace( level, x, y + 1, z, 1 ); - bool down = tt->shouldRenderFace( level, x, y - 1, z, 0 ); - bool dirs[4]; - dirs[0] = tt->shouldRenderFace( level, x, y, z - 1, 2 ); - dirs[1] = tt->shouldRenderFace( level, x, y, z + 1, 3 ); - dirs[2] = tt->shouldRenderFace( level, x - 1, y, z, 4 ); - dirs[3] = tt->shouldRenderFace( level, x + 1, y, z, 5 ); + int col = tt->getColor(level, x, y, z); + float r = (col >> 16 & 0xff) / 255.0f; + float g = (col >> 8 & 0xff) / 255.0f; + float b = (col & 0xff) / 255.0f; + bool up = tt->shouldRenderFace(level, x, y + 1, z, 1); + bool down = tt->shouldRenderFace(level, x, y - 1, z, 0); + bool dirs[4]; + dirs[0] = tt->shouldRenderFace(level, x, y, z - 1, 2); + dirs[1] = tt->shouldRenderFace(level, x, y, z + 1, 3); + dirs[2] = tt->shouldRenderFace(level, x - 1, y, z, 4); + dirs[3] = tt->shouldRenderFace(level, x + 1, y, z, 5); - if ( !up && !down && !dirs[0] && !dirs[1] && !dirs[2] && !dirs[3] ) return false; + if (!up && !down && !dirs[0] && !dirs[1] && !dirs[2] && !dirs[3]) + return false; - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - double yo0 = 0; - double yo1 = 1; + double yo0 = 0; + double yo1 = 1; - Material* m = tt->material; - int data = level->getData( x, y, z ); + Material* m = tt->material; + int data = level->getData(x, y, z); - float h0 = getWaterHeight( x, y, z, m ); - float h1 = getWaterHeight( x, y, z + 1, m ); - float h2 = getWaterHeight( x + 1, y, z + 1, m ); - float h3 = getWaterHeight( x + 1, y, z, m ); + float h0 = getWaterHeight(x, y, z, m); + float h1 = getWaterHeight(x, y, z + 1, m); + float h2 = getWaterHeight(x + 1, y, z + 1, m); + float h3 = getWaterHeight(x + 1, y, z, m); float offs = 0.001f; - // 4J - added. Farm tiles often found beside water, but they consider themselves non-solid as they only extend up to 15.0f / 16.0f. - // If the max height of this water is below that level, don't bother rendering sides bordering onto farmland. - float maxh = h0; - if ( h1 > maxh ) maxh = h1; - if ( h2 > maxh ) maxh = h2; - if ( h3 > maxh ) maxh = h3; - if ( maxh <= ( 15.0f / 16.0f ) ) - { - if ( level->getTile( x, y, z - 1 ) == Tile::farmland_Id ) - { - dirs[0] = false; - } - if ( level->getTile( x, y, z + 1 ) == Tile::farmland_Id ) - { - dirs[1] = false; - } - if ( level->getTile( x - 1, y, z ) == Tile::farmland_Id ) - { - dirs[2] = false; - } - if ( level->getTile( x + 1, y, z ) == Tile::farmland_Id ) - { - dirs[3] = false; - } - } + // 4J - added. Farm tiles often found beside water, but they consider + // themselves non-solid as they only extend up to 15.0f / 16.0f. If the max + // height of this water is below that level, don't bother rendering sides + // bordering onto farmland. + float maxh = h0; + if (h1 > maxh) maxh = h1; + if (h2 > maxh) maxh = h2; + if (h3 > maxh) maxh = h3; + if (maxh <= (15.0f / 16.0f)) { + if (level->getTile(x, y, z - 1) == Tile::farmland_Id) { + dirs[0] = false; + } + if (level->getTile(x, y, z + 1) == Tile::farmland_Id) { + dirs[1] = false; + } + if (level->getTile(x - 1, y, z) == Tile::farmland_Id) { + dirs[2] = false; + } + if (level->getTile(x + 1, y, z) == Tile::farmland_Id) { + dirs[3] = false; + } + } - if ( noCulling || up ) - { - changed = true; - Icon *tex = getTexture( tt, 1, data ); - float angle = ( float )LiquidTile::getSlopeAngle( level, x, y, z, m ); - if ( angle > -999 ) - { - tex = getTexture( tt, 2, data ); - } + if (noCulling || up) { + changed = true; + Icon* tex = getTexture(tt, 1, data); + float angle = (float)LiquidTile::getSlopeAngle(level, x, y, z, m); + if (angle > -999) { + tex = getTexture(tt, 2, data); + } h0 -= offs; h1 -= offs; h2 -= offs; h3 -= offs; - float u00, u01, u10, u11; - float v00, v01, v10, v11; - if ( angle < -999 ) - { - u00 = tex->getU(0, true); - v00 = tex->getV(0, true); - u01 = u00; - v01 = tex->getV(SharedConstants::WORLD_RESOLUTION, true); - u10 = tex->getU(SharedConstants::WORLD_RESOLUTION, true); - v10 = v01; - u11 = u10; - v11 = v00; - } - else - { - float s = Mth::sin(angle) * .25f; - float c = Mth::cos(angle) * .25f; - float cc = SharedConstants::WORLD_RESOLUTION * .5f; - u00 = tex->getU(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); - v00 = tex->getV(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); - u01 = tex->getU(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); - v01 = tex->getV(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); - u10 = tex->getU(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); - v10 = tex->getV(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); - u11 = tex->getU(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); - v11 = tex->getV(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); - } + float u00, u01, u10, u11; + float v00, v01, v10, v11; + if (angle < -999) { + u00 = tex->getU(0, true); + v00 = tex->getV(0, true); + u01 = u00; + v01 = tex->getV(SharedConstants::WORLD_RESOLUTION, true); + u10 = tex->getU(SharedConstants::WORLD_RESOLUTION, true); + v10 = v01; + u11 = u10; + v11 = v00; + } else { + float s = Mth::sin(angle) * .25f; + float c = Mth::cos(angle) * .25f; + float cc = SharedConstants::WORLD_RESOLUTION * .5f; + u00 = tex->getU(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); + v00 = tex->getV(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); + u01 = tex->getU(cc + (-c + s) * SharedConstants::WORLD_RESOLUTION); + v01 = tex->getV(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); + u10 = tex->getU(cc + (+c + s) * SharedConstants::WORLD_RESOLUTION); + v10 = tex->getV(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); + u11 = tex->getU(cc + (+c - s) * SharedConstants::WORLD_RESOLUTION); + v11 = tex->getV(cc + (-c - s) * SharedConstants::WORLD_RESOLUTION); + } - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y, z ); - } - t->color( c11 * br * r, c11 * br * g, c11 * br * b ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h0 ), ( float )( z + 0.0f ), u00, v00 ); - t->vertexUV( ( float )( x + 0.0f ), ( float )( y + h1 ), ( float )( z + 1.0f ), u01, v01 ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h2 ), ( float )( z + 1.0f ), u10, v10 ); - t->vertexUV( ( float )( x + 1.0f ), ( float )( y + h3 ), ( float )( z + 0.0f ), u11, v11 ); - } + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y, z); + } + t->color(c11 * br * r, c11 * br * g, c11 * br * b); + t->vertexUV((float)(x + 0.0f), (float)(y + h0), (float)(z + 0.0f), u00, + v00); + t->vertexUV((float)(x + 0.0f), (float)(y + h1), (float)(z + 1.0f), u01, + v01); + t->vertexUV((float)(x + 1.0f), (float)(y + h2), (float)(z + 1.0f), u10, + v10); + t->vertexUV((float)(x + 1.0f), (float)(y + h3), (float)(z + 0.0f), u11, + v11); + } - if ( noCulling || down ) - { - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y - 1, z ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, x, y - 1, z ); - } - t->color( c10 * br, c10 * br, c10 * br ); - renderFaceDown( tt, x, y + offs, z, getTexture( tt, 0 ) ); - changed = true; - } + if (noCulling || down) { + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y - 1, z)); + br = 1; + } else { + br = tt->getBrightness(level, x, y - 1, z); + } + t->color(c10 * br, c10 * br, c10 * br); + renderFaceDown(tt, x, y + offs, z, getTexture(tt, 0)); + changed = true; + } - for ( int face = 0; face < 4; face++ ) - { - int xt = x; - int yt = y; - int zt = z; + for (int face = 0; face < 4; face++) { + int xt = x; + int yt = y; + int zt = z; - if ( face == 0 ) zt--; - if ( face == 1 ) zt++; - if ( face == 2 ) xt--; - if ( face == 3 ) xt++; + if (face == 0) zt--; + if (face == 1) zt++; + if (face == 2) xt--; + if (face == 3) xt++; - Icon *tex = getTexture(tt, face + 2, data); + Icon* tex = getTexture(tt, face + 2, data); - if ( noCulling || dirs[face] ) - { - float hh0; - float hh1; - float x0, z0, x1, z1; - if ( face == 0 ) - { - hh0 = ( float )( h0 ); - hh1 = ( float )( h3 ); - x0 = ( float )( x ); - x1 = ( float )( x + 1 ); - z0 = ( float )( z + offs); - z1 = ( float )( z + offs); - } - else if ( face == 1 ) - { - hh0 = ( float )( h2 ); - hh1 = ( float )( h1 ); - x0 = ( float )( x + 1 ); - x1 = ( float )( x ); - z0 = ( float )( z + 1 - offs); - z1 = ( float )( z + 1 - offs); - } - else if ( face == 2 ) - { - hh0 = ( float )( h1 ); - hh1 = ( float )( h0 ); - x0 = ( float )( x + offs); - x1 = ( float )( x + offs); - z0 = ( float )( z + 1 ); - z1 = ( float )( z ); - } - else - { - hh0 = ( float )( h3 ); - hh1 = ( float )( h2 ); - x0 = ( float )( x + 1 - offs); - x1 = ( float )( x + 1 - offs); - z0 = ( float )( z ); - z1 = ( float )( z + 1 ); - } + if (noCulling || dirs[face]) { + float hh0; + float hh1; + float x0, z0, x1, z1; + if (face == 0) { + hh0 = (float)(h0); + hh1 = (float)(h3); + x0 = (float)(x); + x1 = (float)(x + 1); + z0 = (float)(z + offs); + z1 = (float)(z + offs); + } else if (face == 1) { + hh0 = (float)(h2); + hh1 = (float)(h1); + x0 = (float)(x + 1); + x1 = (float)(x); + z0 = (float)(z + 1 - offs); + z1 = (float)(z + 1 - offs); + } else if (face == 2) { + hh0 = (float)(h1); + hh1 = (float)(h0); + x0 = (float)(x + offs); + x1 = (float)(x + offs); + z0 = (float)(z + 1); + z1 = (float)(z); + } else { + hh0 = (float)(h3); + hh1 = (float)(h2); + x0 = (float)(x + 1 - offs); + x1 = (float)(x + 1 - offs); + z0 = (float)(z); + z1 = (float)(z + 1); + } + changed = true; + float u0 = tex->getU(0, true); + float u1 = tex->getU(SharedConstants::WORLD_RESOLUTION * .5f, true); - changed = true; - float u0 = tex->getU(0, true); - float u1 = tex->getU(SharedConstants::WORLD_RESOLUTION * .5f, true); + int yTex = tex->getY(); + float v01 = + tex->getV((1 - hh0) * SharedConstants::WORLD_RESOLUTION * .5f); + float v02 = + tex->getV((1 - hh1) * SharedConstants::WORLD_RESOLUTION * .5f); + float v1 = tex->getV(SharedConstants::WORLD_RESOLUTION * .5f, true); - int yTex = tex->getY(); - float v01 = tex->getV((1 - hh0) * SharedConstants::WORLD_RESOLUTION * .5f); - float v02 = tex->getV((1 - hh1) * SharedConstants::WORLD_RESOLUTION * .5f); - float v1 = tex->getV(SharedConstants::WORLD_RESOLUTION * .5f, true); + float br; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, xt, yt, zt)); + br = 1; + } else { + br = tt->getBrightness(level, xt, yt, zt); + } + if (face < 2) + br *= c2; + else + br *= c3; - float br; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, xt, yt, zt ) ); - br = 1; - } - else - { - br = tt->getBrightness( level, xt, yt, zt ); - } - if ( face < 2 ) br *= c2; - else - br *= c3; + t->color(c11 * br * r, c11 * br * g, c11 * br * b); + t->vertexUV((float)(x0), (float)(y + hh0), (float)(z0), (float)(u0), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y + hh1), (float)(z1), (float)(u1), + (float)(v02)); + t->vertexUV((float)(x1), (float)(y + 0), (float)(z1), (float)(u1), + (float)(v1)); + t->vertexUV((float)(x0), (float)(y + 0), (float)(z0), (float)(u0), + (float)(v1)); + } + } - t->color( c11 * br * r, c11 * br * g, c11 * br * b ); - t->vertexUV( ( float )( x0 ), ( float )( y + hh0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + hh1 ), ( float )( z1 ), ( float )( u1 ), ( float )( v02 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y + 0 ), ( float )( z1 ), ( float )( u1 ), ( float )( v1 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y + 0 ), ( float )( z0 ), ( float )( u0 ), ( float )( v1 ) ); - - } - - } - - tileShapeY0 = yo0; - tileShapeY1 = yo1; - - return changed; + tileShapeY0 = yo0; + tileShapeY1 = yo1; + return changed; } -float TileRenderer::getWaterHeight( int x, int y, int z, Material* m ) -{ - int count = 0; - float h = 0; - for ( int i = 0; i < 4; i++ ) - { - int xx = x - ( i & 1 ); - int yy = y; - int zz = z - ( ( i >> 1 ) & 1 ); - if ( level->getMaterial( xx, yy + 1, zz ) == m ) - { - return 1; - } - Material* tm = level->getMaterial( xx, yy, zz ); - if ( tm == m ) - { - int d = level->getData( xx, yy, zz ); - if ( d >= 8 || d == 0 ) - { - h += ( LiquidTile::getHeight( d ) )* 10; - count += 10; - } - h += LiquidTile::getHeight( d ); - count++; - } - else if ( !tm->isSolid() ) - { - h += 1; - count++; - } - } - return 1 - h / count; +float TileRenderer::getWaterHeight(int x, int y, int z, Material* m) { + int count = 0; + float h = 0; + for (int i = 0; i < 4; i++) { + int xx = x - (i & 1); + int yy = y; + int zz = z - ((i >> 1) & 1); + if (level->getMaterial(xx, yy + 1, zz) == m) { + return 1; + } + Material* tm = level->getMaterial(xx, yy, zz); + if (tm == m) { + int d = level->getData(xx, yy, zz); + if (d >= 8 || d == 0) { + h += (LiquidTile::getHeight(d)) * 10; + count += 10; + } + h += LiquidTile::getHeight(d); + count++; + } else if (!tm->isSolid()) { + h += 1; + count++; + } + } + return 1 - h / count; } -void TileRenderer::renderBlock( Tile* tt, Level* level, int x, int y, int z ) -{ - renderBlock(tt, level, x, y, z, 0); +void TileRenderer::renderBlock(Tile* tt, Level* level, int x, int y, int z) { + renderBlock(tt, level, x, y, z, 0); } -void TileRenderer::renderBlock(Tile *tt, Level *level, int x, int y, int z, int data) -{ - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; +void TileRenderer::renderBlock(Tile* tt, Level* level, int x, int y, int z, + int data) { + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - Tesselator* t = Tesselator::getInstance(); - t->begin(); - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( getLightColor(tt, level, x, y, z ) ); - } - float center = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y, z ); - float br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y - 1, z ); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + } + float center = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y, z); + float br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y - 1, z); - if ( br < center ) br = center; - t->color( c10 * br, c10 * br, c10 * br ); - renderFaceDown( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 0, data ) ); + if (br < center) br = center; + t->color(c10 * br, c10 * br, c10 * br); + renderFaceDown(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 0, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y + 1, z ); - if ( br < center ) br = center; - t->color( c11 * br, c11 * br, c11 * br ); - renderFaceUp( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 1, data ) ); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y + 1, z); + if (br < center) br = center; + t->color(c11 * br, c11 * br, c11 * br); + renderFaceUp(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 1, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y, z - 1 ); - if ( br < center ) br = center; - t->color( c2 * br, c2 * br, c2 * br ); - renderNorth( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 2, data ) ); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y, z - 1); + if (br < center) br = center; + t->color(c2 * br, c2 * br, c2 * br); + renderNorth(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 2, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x, y, z + 1 ); - if ( br < center ) br = center; - t->color( c2 * br, c2 * br, c2 * br ); - renderSouth( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 3, data ) ); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x, y, z + 1); + if (br < center) br = center; + t->color(c2 * br, c2 * br, c2 * br); + renderSouth(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 3, data)); - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x - 1, y, z ); - if ( br < center ) br = center; - t->color( c3 * br, c3 * br, c3 * br ); - renderWest( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 4, data ) ); - - br = SharedConstants::TEXTURE_LIGHTING ? 1 : tt->getBrightness( level, x + 1, y, z ); - if ( br < center ) br = center; - t->color( c3 * br, c3 * br, c3 * br ); - renderEast( tt, -0.5f, -0.5f, -0.5f, getTexture( tt, 5, data ) ); - t->end(); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x - 1, y, z); + if (br < center) br = center; + t->color(c3 * br, c3 * br, c3 * br); + renderWest(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 4, data)); + br = SharedConstants::TEXTURE_LIGHTING + ? 1 + : tt->getBrightness(level, x + 1, y, z); + if (br < center) br = center; + t->color(c3 * br, c3 * br, c3 * br); + renderEast(tt, -0.5f, -0.5f, -0.5f, getTexture(tt, 5, data)); + t->end(); } -bool TileRenderer::tesselateBlockInWorld( Tile* tt, int x, int y, int z ) -{ - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; +bool TileRenderer::tesselateBlockInWorld(Tile* tt, int x, int y, int z) { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } + r = cr; + g = cg; + b = cb; + } - if ( Tile::lightEmission[tt->id] == 0 )//4J - TODO/remove (Minecraft::useAmbientOcclusion()) - { - return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( tt, x, y, z, r, g, b, 0 ); - } - else - { - return tesselateBlockInWorld( tt, x, y, z, r, g, b ); - } + if (Tile::lightEmission[tt->id] == + 0) // 4J - TODO/remove (Minecraft::useAmbientOcclusion()) + { + return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + tt, x, y, z, r, g, b, 0); + } else { + return tesselateBlockInWorld(tt, x, y, z, r, g, b); + } } // AP - added this version to be able to pass the face flags down -bool TileRenderer::tesselateBlockInWorld( Tile* tt, int x, int y, int z, int faceFlags ) -{ - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; +bool TileRenderer::tesselateBlockInWorld(Tile* tt, int x, int y, int z, + int faceFlags) { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } + r = cr; + g = cg; + b = cb; + } - if ( Tile::lightEmission[tt->id] == 0 )//4J - TODO/remove (Minecraft::useAmbientOcclusion()) - { - return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( tt, x, y, z, r, g, b, faceFlags ); - } - else - { - return tesselateBlockInWorld( tt, x, y, z, r, g, b ); - } + if (Tile::lightEmission[tt->id] == + 0) // 4J - TODO/remove (Minecraft::useAmbientOcclusion()) + { + return tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + tt, x, y, z, r, g, b, faceFlags); + } else { + return tesselateBlockInWorld(tt, x, y, z, r, g, b); + } } -bool TileRenderer::tesselateTreeInWorld(Tile *tt, int x, int y, int z) -{ - int data = level->getData(x, y, z); - int facing = data & TreeTile::MASK_FACING; +bool TileRenderer::tesselateTreeInWorld(Tile* tt, int x, int y, int z) { + int data = level->getData(x, y, z); + int facing = data & TreeTile::MASK_FACING; - if (facing == TreeTile::FACING_X) - { - northFlip = FLIP_CW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CW; - } - else if (facing == TreeTile::FACING_Z) - { - eastFlip = FLIP_CW; - westFlip = FLIP_CW; - } + if (facing == TreeTile::FACING_X) { + northFlip = FLIP_CW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CW; + } else if (facing == TreeTile::FACING_Z) { + eastFlip = FLIP_CW; + westFlip = FLIP_CW; + } - bool result = tesselateBlockInWorld(tt, x, y, z); + bool result = tesselateBlockInWorld(tt, x, y, z); - eastFlip = 0; - northFlip = 0; - southFlip = 0; - westFlip = 0; - upFlip = 0; - downFlip = 0; + eastFlip = 0; + northFlip = 0; + southFlip = 0; + westFlip = 0; + upFlip = 0; + downFlip = 0; - return result; + return result; } -bool TileRenderer::tesselateQuartzInWorld(Tile *tt, int x, int y, int z) -{ - int data = level->getData(x, y, z); +bool TileRenderer::tesselateQuartzInWorld(Tile* tt, int x, int y, int z) { + int data = level->getData(x, y, z); - if (data == QuartzBlockTile::TYPE_LINES_X) - { - northFlip = FLIP_CW; - southFlip = FLIP_CW; - upFlip = FLIP_CW; - downFlip = FLIP_CW; - } - else if (data == QuartzBlockTile::TYPE_LINES_Z) - { - eastFlip = FLIP_CW; - westFlip = FLIP_CW; - } + if (data == QuartzBlockTile::TYPE_LINES_X) { + northFlip = FLIP_CW; + southFlip = FLIP_CW; + upFlip = FLIP_CW; + downFlip = FLIP_CW; + } else if (data == QuartzBlockTile::TYPE_LINES_Z) { + eastFlip = FLIP_CW; + westFlip = FLIP_CW; + } - bool result = tesselateBlockInWorld(tt, x, y, z); + bool result = tesselateBlockInWorld(tt, x, y, z); - eastFlip = 0; - northFlip = 0; - southFlip = 0; - westFlip = 0; - upFlip = 0; - downFlip = 0; + eastFlip = 0; + northFlip = 0; + southFlip = 0; + westFlip = 0; + upFlip = 0; + downFlip = 0; - return result; + return result; } -bool TileRenderer::tesselateCocoaInWorld(CocoaTile *tt, int x, int y, int z) -{ - Tesselator *t = Tesselator::getInstance(); +bool TileRenderer::tesselateCocoaInWorld(CocoaTile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - if (SharedConstants::TEXTURE_LIGHTING) - { - t->tex2(getLightColor(tt, level, x, y, z)); - t->color(1.0f, 1.0f, 1.0f); - } - else - { - float br = tt->getBrightness(level, x, y, z); - if (Tile::lightEmission[tt->id] > 0) br = 1.0f; - t->color(br, br, br); - } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(getLightColor(tt, level, x, y, z)); + t->color(1.0f, 1.0f, 1.0f); + } else { + float br = tt->getBrightness(level, x, y, z); + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(br, br, br); + } - int data = level->getData(x, y, z); - int dir = DirectionalTile::getDirection(data); - int age = CocoaTile::getAge(data); - Icon *tex = tt->getTextureForAge(age); + int data = level->getData(x, y, z); + int dir = DirectionalTile::getDirection(data); + int age = CocoaTile::getAge(data); + Icon* tex = tt->getTextureForAge(age); - int cocoaWidth = 4 + age * 2; - int cocoaHeight = 5 + age * 2; + int cocoaWidth = 4 + age * 2; + int cocoaHeight = 5 + age * 2; - double us = 15.0 - cocoaWidth; - double ue = 15.0; - double vs = 4.0; - double ve = 4.0 + cocoaHeight; - double u0 = tex->getU(us, true); - double u1 = tex->getU(ue, true); - double v0 = tex->getV(vs, true); - double v1 = tex->getV(ve, true); + double us = 15.0 - cocoaWidth; + double ue = 15.0; + double vs = 4.0; + double ve = 4.0 + cocoaHeight; + double u0 = tex->getU(us, true); + double u1 = tex->getU(ue, true); + double v0 = tex->getV(vs, true); + double v1 = tex->getV(ve, true); + double offX = 0; + double offZ = 0; - double offX = 0; - double offZ = 0; + switch (dir) { + case Direction::NORTH: + offX = 8.0 - cocoaWidth / 2; + offZ = 1.0; + break; + case Direction::SOUTH: + offX = 8.0 - cocoaWidth / 2; + offZ = 15.0 - cocoaWidth; + break; + case Direction::EAST: + offX = 15.0 - cocoaWidth; + offZ = 8.0 - cocoaWidth / 2; + break; + case Direction::WEST: + offX = 1.0; + offZ = 8.0 - cocoaWidth / 2; + break; + } - switch (dir) - { - case Direction::NORTH: - offX = 8.0 - cocoaWidth / 2; - offZ = 1.0; - break; - case Direction::SOUTH: - offX = 8.0 - cocoaWidth / 2; - offZ = 15.0 - cocoaWidth; - break; - case Direction::EAST: - offX = 15.0 - cocoaWidth; - offZ = 8.0 - cocoaWidth / 2; - break; - case Direction::WEST: - offX = 1.0; - offZ = 8.0 - cocoaWidth / 2; - break; - } + double x0 = x + offX / 16.0; + double x1 = x + (offX + cocoaWidth) / 16.0; + double y0 = y + (12.0 - cocoaHeight) / 16.0; + double y1 = y + 12.0 / 16.0; + double z0 = z + offZ / 16.0; + double z1 = z + (offZ + cocoaWidth) / 16.0; - double x0 = x + offX / 16.0; - double x1 = x + (offX + cocoaWidth) / 16.0; - double y0 = y + (12.0 - cocoaHeight) / 16.0; - double y1 = y + 12.0 / 16.0; - double z0 = z + offZ / 16.0; - double z1 = z + (offZ + cocoaWidth) / 16.0; + // west + { + t->vertexUV(x0, y0, z0, u0, v1); + t->vertexUV(x0, y0, z1, u1, v1); + t->vertexUV(x0, y1, z1, u1, v0); + t->vertexUV(x0, y1, z0, u0, v0); + } + // east + { + t->vertexUV(x1, y0, z1, u0, v1); + t->vertexUV(x1, y0, z0, u1, v1); + t->vertexUV(x1, y1, z0, u1, v0); + t->vertexUV(x1, y1, z1, u0, v0); + } + // north + { + t->vertexUV(x1, y0, z0, u0, v1); + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y1, z0, u1, v0); + t->vertexUV(x1, y1, z0, u0, v0); + } + // south + { + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x1, y0, z1, u1, v1); + t->vertexUV(x1, y1, z1, u1, v0); + t->vertexUV(x0, y1, z1, u0, v0); + } - // west - { - t->vertexUV(x0, y0, z0, u0, v1); - t->vertexUV(x0, y0, z1, u1, v1); - t->vertexUV(x0, y1, z1, u1, v0); - t->vertexUV(x0, y1, z0, u0, v0); - } - // east - { - t->vertexUV(x1, y0, z1, u0, v1); - t->vertexUV(x1, y0, z0, u1, v1); - t->vertexUV(x1, y1, z0, u1, v0); - t->vertexUV(x1, y1, z1, u0, v0); - } - // north - { - t->vertexUV(x1, y0, z0, u0, v1); - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y1, z0, u1, v0); - t->vertexUV(x1, y1, z0, u0, v0); - } - // south - { - t->vertexUV(x0, y0, z1, u0, v1); - t->vertexUV(x1, y0, z1, u1, v1); - t->vertexUV(x1, y1, z1, u1, v0); - t->vertexUV(x0, y1, z1, u0, v0); - } + int topWidth = cocoaWidth; + if (age >= 2) { + // special case because the top piece didn't fit + topWidth--; + } - int topWidth = cocoaWidth; - if (age >= 2) - { - // special case because the top piece didn't fit - topWidth--; - } + u0 = tex->getU0(true); + u1 = tex->getU(topWidth, true); + v0 = tex->getV0(true); + v1 = tex->getV(topWidth, true); - u0 = tex->getU0(true); - u1 = tex->getU(topWidth, true); - v0 = tex->getV0(true); - v1 = tex->getV(topWidth, true); + // top + { + t->vertexUV(x0, y1, z1, u0, v1); + t->vertexUV(x1, y1, z1, u1, v1); + t->vertexUV(x1, y1, z0, u1, v0); + t->vertexUV(x0, y1, z0, u0, v0); + } + // bottom + { + t->vertexUV(x0, y0, z0, u0, v0); + t->vertexUV(x1, y0, z0, u1, v0); + t->vertexUV(x1, y0, z1, u1, v1); + t->vertexUV(x0, y0, z1, u0, v1); + } - // top - { - t->vertexUV(x0, y1, z1, u0, v1); - t->vertexUV(x1, y1, z1, u1, v1); - t->vertexUV(x1, y1, z0, u1, v0); - t->vertexUV(x0, y1, z0, u0, v0); - } - // bottom - { - t->vertexUV(x0, y0, z0, u0, v0); - t->vertexUV(x1, y0, z0, u1, v0); - t->vertexUV(x1, y0, z1, u1, v1); - t->vertexUV(x0, y0, z1, u0, v1); - } + // stalk + u0 = tex->getU(12, true); + u1 = tex->getU1(true); + v0 = tex->getV0(true); + v1 = tex->getV(4, true); - // stalk - u0 = tex->getU(12, true); - u1 = tex->getU1(true); - v0 = tex->getV0(true); - v1 = tex->getV(4, true); + offX = 8; + offZ = 0; - offX = 8; - offZ = 0; + switch (dir) { + case Direction::NORTH: + offX = 8.0; + offZ = 0.0; + break; + case Direction::SOUTH: + offX = 8; + offZ = 12; + { + double temp = u0; + u0 = u1; + u1 = temp; + } + break; + case Direction::EAST: + offX = 12.0; + offZ = 8.0; + { + double temp = u0; + u0 = u1; + u1 = temp; + } + break; + case Direction::WEST: + offX = 0.0; + offZ = 8.0; + break; + } - switch (dir) - { - case Direction::NORTH: - offX = 8.0; - offZ = 0.0; - break; - case Direction::SOUTH: - offX = 8; - offZ = 12; - { - double temp = u0; - u0 = u1; - u1 = temp; - } - break; - case Direction::EAST: - offX = 12.0; - offZ = 8.0; - { - double temp = u0; - u0 = u1; - u1 = temp; - } - break; - case Direction::WEST: - offX = 0.0; - offZ = 8.0; - break; - } + x0 = x + offX / 16.0; + x1 = x + (offX + 4.0) / 16.0; + y0 = y + 12.0 / 16.0; + y1 = y + 16.0 / 16.0; + z0 = z + offZ / 16.0; + z1 = z + (offZ + 4.0) / 16.0; + if (dir == Direction::NORTH || dir == Direction::SOUTH) { + // west + { + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x0, y1, z1, u0, v0); + t->vertexUV(x0, y1, z0, u1, v0); + } + // east + { + t->vertexUV(x0, y0, z1, u0, v1); + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y1, z0, u1, v0); + t->vertexUV(x0, y1, z1, u0, v0); + } + } else if (dir == Direction::WEST || dir == Direction::EAST) { + // north + { + t->vertexUV(x1, y0, z0, u0, v1); + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x0, y1, z0, u1, v0); + t->vertexUV(x1, y1, z0, u0, v0); + } + // south + { + t->vertexUV(x0, y0, z0, u1, v1); + t->vertexUV(x1, y0, z0, u0, v1); + t->vertexUV(x1, y1, z0, u0, v0); + t->vertexUV(x0, y1, z0, u1, v0); + } + } - x0 = x + offX / 16.0; - x1 = x + (offX + 4.0) / 16.0; - y0 = y + 12.0 / 16.0; - y1 = y + 16.0 / 16.0; - z0 = z + offZ / 16.0; - z1 = z + (offZ + 4.0) / 16.0; - if (dir == Direction::NORTH || dir == Direction::SOUTH) - { - // west - { - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y0, z1, u0, v1); - t->vertexUV(x0, y1, z1, u0, v0); - t->vertexUV(x0, y1, z0, u1, v0); - } - // east - { - t->vertexUV(x0, y0, z1, u0, v1); - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y1, z0, u1, v0); - t->vertexUV(x0, y1, z1, u0, v0); - } - } - else if (dir == Direction::WEST || dir == Direction::EAST) - { - // north - { - t->vertexUV(x1, y0, z0, u0, v1); - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x0, y1, z0, u1, v0); - t->vertexUV(x1, y1, z0, u0, v0); - } - // south - { - t->vertexUV(x0, y0, z0, u1, v1); - t->vertexUV(x1, y0, z0, u0, v1); - t->vertexUV(x1, y1, z0, u0, v0); - t->vertexUV(x0, y1, z0, u1, v0); - } - } - - - return true; + return true; } // 4J - brought changes forward from 1.8.2 -bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* tt, int pX, int pY, int pZ, - float pBaseRed, float pBaseGreen, - float pBaseBlue, int faceFlags ) -{ - // 4J - the texture is (originally) obtained for each face in the block, if those faces are visible. For a lot of blocks, - // the textures don't vary from face to face - this is particularly an issue for leaves as they not only don't vary between faces, - // but they also happen to draw a lot of faces, and the code for determining which texture to use is more complex than in most - // cases. Optimisation here then to store a uniform texture where appropriate (could be extended beyond leaves) that will stop - // any other faces being evaluated. - Icon *uniformTex = NULL; - int id = tt->id; - if( id == Tile::leaves_Id ) - { - uniformTex = getTexture(tt, level, pX, pY, pZ, 0); - } - // 4J - added these faceFlags so we can detect whether this block is going to have no visible faces and early out - // the original code checked noCulling and shouldRenderFace directly where faceFlags is used now - // AP - I moved a copy of these face checks to have an even earlier out - // check if the faceFlags have indeed been set - if( faceFlags == 0 ) - { - if ( noCulling ) - { - faceFlags = 0x3f; - } - else - { - faceFlags |= tt->shouldRenderFace( level, pX, pY - 1, pZ, 0 ) ? 0x01 : 0; - faceFlags |= tt->shouldRenderFace( level, pX, pY + 1, pZ, 1 ) ? 0x02 : 0; - faceFlags |= tt->shouldRenderFace( level, pX, pY, pZ - 1, 2 ) ? 0x04 : 0; - faceFlags |= tt->shouldRenderFace( level, pX, pY, pZ + 1, 3 ) ? 0x08 : 0; - faceFlags |= tt->shouldRenderFace( level, pX - 1, pY, pZ, 4 ) ? 0x10 : 0; - faceFlags |= tt->shouldRenderFace( level, pX + 1, pY, pZ, 5 ) ? 0x20 : 0; - } - if ( faceFlags == 0 ) - { - return false; - } - } - // If we are only rendering the bottom face and we're at the bottom of the world, we shouldn't be able to see this - don't render anything - if( ( faceFlags == 1 ) && ( pY == 0 ) ) - { - return false; - } +bool TileRenderer::tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + Tile* tt, int pX, int pY, int pZ, float pBaseRed, float pBaseGreen, + float pBaseBlue, int faceFlags) { + // 4J - the texture is (originally) obtained for each face in the block, if + // those faces are visible. For a lot of blocks, the textures don't vary + // from face to face - this is particularly an issue for leaves as they not + // only don't vary between faces, but they also happen to draw a lot of + // faces, and the code for determining which texture to use is more complex + // than in most cases. Optimisation here then to store a uniform texture + // where appropriate (could be extended beyond leaves) that will stop any + // other faces being evaluated. + Icon* uniformTex = NULL; + int id = tt->id; + if (id == Tile::leaves_Id) { + uniformTex = getTexture(tt, level, pX, pY, pZ, 0); + } + // 4J - added these faceFlags so we can detect whether this block is going + // to have no visible faces and early out the original code checked + // noCulling and shouldRenderFace directly where faceFlags is used now AP - + // I moved a copy of these face checks to have an even earlier out check if + // the faceFlags have indeed been set + if (faceFlags == 0) { + if (noCulling) { + faceFlags = 0x3f; + } else { + faceFlags |= + tt->shouldRenderFace(level, pX, pY - 1, pZ, 0) ? 0x01 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX, pY + 1, pZ, 1) ? 0x02 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX, pY, pZ - 1, 2) ? 0x04 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX, pY, pZ + 1, 3) ? 0x08 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX - 1, pY, pZ, 4) ? 0x10 : 0; + faceFlags |= + tt->shouldRenderFace(level, pX + 1, pY, pZ, 5) ? 0x20 : 0; + } + if (faceFlags == 0) { + return false; + } + } + // If we are only rendering the bottom face and we're at the bottom of the + // world, we shouldn't be able to see this - don't render anything + if ((faceFlags == 1) && (pY == 0)) { + return false; + } - applyAmbienceOcclusion = true; - float ll1 = ll000; - float ll2 = ll000; - float ll3 = ll000; - float ll4 = ll000; - bool tint0 = true; - bool tint1 = true; - bool tint2 = true; - bool tint3 = true; - bool tint4 = true; - bool tint5 = true; + applyAmbienceOcclusion = true; + float ll1 = ll000; + float ll2 = ll000; + float ll3 = ll000; + float ll4 = ll000; + bool tint0 = true; + bool tint1 = true; + bool tint2 = true; + bool tint3 = true; + bool tint4 = true; + bool tint5 = true; + ll000 = getShadeBrightness(tt, level, pX, pY, pZ); + llx00 = getShadeBrightness(tt, level, pX - 1, pY, pZ); + ll0y0 = getShadeBrightness(tt, level, pX, pY - 1, pZ); + ll00z = getShadeBrightness(tt, level, pX, pY, pZ - 1); + llX00 = getShadeBrightness(tt, level, pX + 1, pY, pZ); + ll0Y0 = getShadeBrightness(tt, level, pX, pY + 1, pZ); + ll00Z = getShadeBrightness(tt, level, pX, pY, pZ + 1); - ll000 = getShadeBrightness(tt, level, pX, pY, pZ ); - llx00 = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - ll0y0 = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - ll00z = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - llX00 = getShadeBrightness(tt, level, pX + 1, pY, pZ ); - ll0Y0 = getShadeBrightness(tt, level, pX, pY + 1, pZ ); - ll00Z = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); + // 4J - these changes brought forward from 1.2.3 + int centerColor = getLightColor(tt, level, pX, pY, pZ); + int ccx00 = centerColor; + int cc0y0 = centerColor; + int cc00z = centerColor; + int ccX00 = centerColor; + int cc0Y0 = centerColor; + int cc00Z = centerColor; - // 4J - these changes brought forward from 1.2.3 - int centerColor = getLightColor(tt, level, pX, pY, pZ ); - int ccx00 = centerColor; - int cc0y0 = centerColor; - int cc00z = centerColor; - int ccX00 = centerColor; - int cc0Y0 = centerColor; - int cc00Z = centerColor; + if (tileShapeY0 <= 0 || !level->isSolidRenderTile(pX, pY - 1, pZ)) + cc0y0 = getLightColor(tt, level, pX, pY - 1, pZ); + if (tileShapeY1 >= 1 || !level->isSolidRenderTile(pX, pY + 1, pZ)) + cc0Y0 = getLightColor(tt, level, pX, pY + 1, pZ); + if (tileShapeX0 <= 0 || !level->isSolidRenderTile(pX - 1, pY, pZ)) + ccx00 = getLightColor(tt, level, pX - 1, pY, pZ); + if (tileShapeX1 >= 1 || !level->isSolidRenderTile(pX + 1, pY, pZ)) + ccX00 = getLightColor(tt, level, pX + 1, pY, pZ); + if (tileShapeZ0 <= 0 || !level->isSolidRenderTile(pX, pY, pZ - 1)) + cc00z = getLightColor(tt, level, pX, pY, pZ - 1); + if (tileShapeZ1 >= 1 || !level->isSolidRenderTile(pX, pY, pZ + 1)) + cc00Z = getLightColor(tt, level, pX, pY, pZ + 1); - if (tileShapeY0 <= 0 || !level->isSolidRenderTile(pX, pY - 1, pZ)) cc0y0 = getLightColor(tt, level, pX, pY - 1, pZ); - if (tileShapeY1 >= 1 || !level->isSolidRenderTile(pX, pY + 1, pZ)) cc0Y0 = getLightColor(tt, level, pX, pY + 1, pZ); - if (tileShapeX0 <= 0 || !level->isSolidRenderTile(pX - 1, pY, pZ)) ccx00 = getLightColor(tt, level, pX - 1, pY, pZ); - if (tileShapeX1 >= 1 || !level->isSolidRenderTile(pX + 1, pY, pZ)) ccX00 = getLightColor(tt, level, pX + 1, pY, pZ); - if (tileShapeZ0 <= 0 || !level->isSolidRenderTile(pX, pY, pZ - 1)) cc00z = getLightColor(tt, level, pX, pY, pZ - 1); - if (tileShapeZ1 >= 1 || !level->isSolidRenderTile(pX, pY, pZ + 1)) cc00Z = getLightColor(tt, level, pX, pY, pZ + 1); + Tesselator* t = Tesselator::getInstance(); + t->tex2(0xf000f); - Tesselator* t = Tesselator::getInstance(); - t->tex2( 0xf000f ); + llTransXY0 = isTranslucentAt(level, pX + 1, pY + 1, pZ); + llTransXy0 = isTranslucentAt(level, pX + 1, pY - 1, pZ); + llTransX0Z = isTranslucentAt(level, pX + 1, pY, pZ + 1); + llTransX0z = isTranslucentAt(level, pX + 1, pY, pZ - 1); + llTransxY0 = isTranslucentAt(level, pX - 1, pY + 1, pZ); + llTransxy0 = isTranslucentAt(level, pX - 1, pY - 1, pZ); + llTransx0z = isTranslucentAt(level, pX - 1, pY, pZ - 1); + llTransx0Z = isTranslucentAt(level, pX - 1, pY, pZ + 1); + llTrans0YZ = isTranslucentAt(level, pX, pY + 1, pZ + 1); + llTrans0Yz = isTranslucentAt(level, pX, pY + 1, pZ - 1); + llTrans0yZ = isTranslucentAt(level, pX, pY - 1, pZ + 1); + llTrans0yz = isTranslucentAt(level, pX, pY - 1, pZ - 1); - llTransXY0 = isTranslucentAt( level, pX + 1, pY + 1, pZ ); - llTransXy0 = isTranslucentAt( level, pX + 1, pY - 1, pZ ); - llTransX0Z = isTranslucentAt( level, pX + 1, pY, pZ + 1 ); - llTransX0z = isTranslucentAt( level, pX + 1, pY, pZ - 1 ); - llTransxY0 = isTranslucentAt( level, pX - 1, pY + 1, pZ ); - llTransxy0 = isTranslucentAt( level, pX - 1, pY - 1, pZ ); - llTransx0z = isTranslucentAt( level, pX - 1, pY, pZ - 1 ); - llTransx0Z = isTranslucentAt( level, pX - 1, pY, pZ + 1 ); - llTrans0YZ = isTranslucentAt( level, pX, pY + 1, pZ + 1 ); - llTrans0Yz = isTranslucentAt( level, pX, pY + 1, pZ - 1 ); - llTrans0yZ = isTranslucentAt( level, pX, pY - 1, pZ + 1 ); - llTrans0yz = isTranslucentAt( level, pX, pY - 1, pZ - 1 ); + if (uniformTex == NULL) { + if (getTexture(tt)->getFlags() == Icon::IS_GRASS_TOP) + tint0 = tint2 = tint3 = tint4 = tint5 = false; + } + if (hasFixedTexture()) tint0 = tint2 = tint3 = tint4 = tint5 = false; - if( uniformTex == NULL ) - { - if ( getTexture(tt)->getFlags() == Icon::IS_GRASS_TOP ) tint0 = tint2 = tint3 = tint4 = tint5 = false; - } - if ( hasFixedTexture() ) tint0 = tint2 = tint3 = tint4 = tint5 = false; + if (faceFlags & 0x01) { + if (blsmooth > 0) { + if (tileShapeY0 <= 0) + pY--; // 4J - condition brought forward from 1.2.3 - if ( faceFlags & 0x01 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeY0 <= 0 ) pY--; // 4J - condition brought forward from 1.2.3 + ccxy0 = getLightColor(tt, level, pX - 1, pY, pZ); + cc0yz = getLightColor(tt, level, pX, pY, pZ - 1); + cc0yZ = getLightColor(tt, level, pX, pY, pZ + 1); + ccXy0 = getLightColor(tt, level, pX + 1, pY, pZ); - ccxy0 = getLightColor(tt, level, pX - 1, pY, pZ ); - cc0yz = getLightColor(tt, level, pX, pY, pZ - 1 ); - cc0yZ = getLightColor(tt, level, pX, pY, pZ + 1 ); - ccXy0 = getLightColor(tt, level, pX + 1, pY, pZ ); + llxy0 = getShadeBrightness(tt, level, pX - 1, pY, pZ); + ll0yz = getShadeBrightness(tt, level, pX, pY, pZ - 1); + ll0yZ = getShadeBrightness(tt, level, pX, pY, pZ + 1); + llXy0 = getShadeBrightness(tt, level, pX + 1, pY, pZ); - llxy0 = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - ll0yz = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - ll0yZ = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); - llXy0 = getShadeBrightness(tt, level, pX + 1, pY, pZ ); + if (llTrans0yz || llTransxy0) { + llxyz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1); + ccxyz = getLightColor(tt, level, pX - 1, pY, pZ - 1); + } else { + llxyz = llxy0; + ccxyz = ccxy0; + } + if (llTrans0yZ || llTransxy0) { + llxyZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1); + ccxyZ = getLightColor(tt, level, pX - 1, pY, pZ + 1); + } else { + llxyZ = llxy0; + ccxyZ = ccxy0; + } + if (llTrans0yz || llTransXy0) { + llXyz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1); + ccXyz = getLightColor(tt, level, pX + 1, pY, pZ - 1); + } else { + llXyz = llXy0; + ccXyz = ccXy0; + } + if (llTrans0yZ || llTransXy0) { + llXyZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1); + ccXyZ = getLightColor(tt, level, pX + 1, pY, pZ + 1); + } else { + llXyZ = llXy0; + ccXyZ = ccXy0; + } - if ( llTrans0yz || llTransxy0 ) - { - llxyz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1 ); - ccxyz = getLightColor(tt, level, pX - 1, pY, pZ - 1 ); - } - else - { - llxyz = llxy0; - ccxyz = ccxy0; - } - if ( llTrans0yZ || llTransxy0 ) - { - llxyZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1 ); - ccxyZ = getLightColor(tt, level, pX - 1, pY, pZ + 1 ); - } - else - { - llxyZ = llxy0; - ccxyZ = ccxy0; - } - if ( llTrans0yz || llTransXy0 ) - { - llXyz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1 ); - ccXyz = getLightColor(tt, level, pX + 1, pY, pZ - 1 ); - } - else - { - llXyz = llXy0; - ccXyz = ccXy0; - } - if ( llTrans0yZ || llTransXy0 ) - { - llXyZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1 ); - ccXyZ = getLightColor(tt, level, pX + 1, pY, pZ + 1 ); - } - else - { - llXyZ = llXy0; - ccXyZ = ccXy0; - } + if (tileShapeY0 <= 0) + pY++; // 4J - condition brought forward from 1.2.3 + ll1 = (llxyZ + llxy0 + ll0yZ + ll0y0) / 4.0f; + ll4 = (ll0yZ + ll0y0 + llXyZ + llXy0) / 4.0f; + ll3 = (ll0y0 + ll0yz + llXy0 + llXyz) / 4.0f; + ll2 = (llxy0 + llxyz + ll0y0 + ll0yz) / 4.0f; - if ( tileShapeY0 <= 0 ) pY++; // 4J - condition brought forward from 1.2.3 - ll1 = ( llxyZ + llxy0 + ll0yZ + ll0y0 ) / 4.0f; - ll4 = ( ll0yZ + ll0y0 + llXyZ + llXy0 ) / 4.0f; - ll3 = ( ll0y0 + ll0yz + llXy0 + llXyz ) / 4.0f; - ll2 = ( llxy0 + llxyz + ll0y0 + ll0yz ) / 4.0f; + tc1 = blend(ccxyZ, ccxy0, cc0yZ, cc0y0); + tc4 = blend(cc0yZ, ccXyZ, ccXy0, cc0y0); + tc3 = blend(cc0yz, ccXy0, ccXyz, cc0y0); + tc2 = blend(ccxy0, ccxyz, cc0yz, cc0y0); + } else { + ll1 = ll2 = ll3 = ll4 = ll0y0; + tc1 = tc2 = tc3 = tc4 = ccxy0; + } + c1r = c2r = c3r = c4r = (tint0 ? pBaseRed : 1.0f) * 0.5f; + c1g = c2g = c3g = c4g = (tint0 ? pBaseGreen : 1.0f) * 0.5f; + c1b = c2b = c3b = c4b = (tint0 ? pBaseBlue : 1.0f) * 0.5f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; - tc1 = blend( ccxyZ, ccxy0, cc0yZ, cc0y0 ); - tc4 = blend( cc0yZ, ccXyZ, ccXy0, cc0y0 ); - tc3 = blend( cc0yz, ccXy0, ccXyz, cc0y0 ); - tc2 = blend( ccxy0, ccxyz, cc0yz, cc0y0 ); - } - else - { - ll1 = ll2 = ll3 = ll4 = ll0y0; - tc1 = tc2 = tc3 = tc4 = ccxy0; - } - c1r = c2r = c3r = c4r = ( tint0 ? pBaseRed : 1.0f ) * 0.5f; - c1g = c2g = c3g = c4g = ( tint0 ? pBaseGreen : 1.0f ) * 0.5f; - c1b = c2b = c3b = c4b = ( tint0 ? pBaseBlue : 1.0f ) * 0.5f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; + renderFaceDown( + tt, (double)pX, (double)pY, (double)pZ, + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 0)); + } + if (faceFlags & 0x02) { + if (blsmooth > 0) { + if (tileShapeY1 >= 1) + pY++; // 4J - condition brought forward from 1.2.3 - renderFaceDown( tt, ( double )pX, ( double )pY, ( double )pZ, uniformTex ? uniformTex : getTexture( tt, level, pX, pY, pZ, 0 ) ); - } - if ( faceFlags & 0x02 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeY1 >= 1 ) pY++; // 4J - condition brought forward from 1.2.3 + ccxY0 = getLightColor(tt, level, pX - 1, pY, pZ); + ccXY0 = getLightColor(tt, level, pX + 1, pY, pZ); + cc0Yz = getLightColor(tt, level, pX, pY, pZ - 1); + cc0YZ = getLightColor(tt, level, pX, pY, pZ + 1); - ccxY0 = getLightColor(tt, level, pX - 1, pY, pZ ); - ccXY0 = getLightColor(tt, level, pX + 1, pY, pZ ); - cc0Yz = getLightColor(tt, level, pX, pY, pZ - 1 ); - cc0YZ = getLightColor(tt, level, pX, pY, pZ + 1 ); + llxY0 = getShadeBrightness(tt, level, pX - 1, pY, pZ); + llXY0 = getShadeBrightness(tt, level, pX + 1, pY, pZ); + ll0Yz = getShadeBrightness(tt, level, pX, pY, pZ - 1); + ll0YZ = getShadeBrightness(tt, level, pX, pY, pZ + 1); - llxY0 = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - llXY0 = getShadeBrightness(tt, level, pX + 1, pY, pZ ); - ll0Yz = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - ll0YZ = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); + if (llTrans0Yz || llTransxY0) { + llxYz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1); + ccxYz = getLightColor(tt, level, pX - 1, pY, pZ - 1); + } else { + llxYz = llxY0; + ccxYz = ccxY0; + } + if (llTrans0Yz || llTransXY0) { + llXYz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1); + ccXYz = getLightColor(tt, level, pX + 1, pY, pZ - 1); + } else { + llXYz = llXY0; + ccXYz = ccXY0; + } + if (llTrans0YZ || llTransxY0) { + llxYZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1); + ccxYZ = getLightColor(tt, level, pX - 1, pY, pZ + 1); + } else { + llxYZ = llxY0; + ccxYZ = ccxY0; + } + if (llTrans0YZ || llTransXY0) { + llXYZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1); + ccXYZ = getLightColor(tt, level, pX + 1, pY, pZ + 1); + } else { + llXYZ = llXY0; + ccXYZ = ccXY0; + } + if (tileShapeY1 >= 1) + pY--; // 4J - condition brought forward from 1.2.3 - if ( llTrans0Yz || llTransxY0 ) - { - llxYz = getShadeBrightness(tt, level, pX - 1, pY, pZ - 1 ); - ccxYz = getLightColor(tt, level, pX - 1, pY, pZ - 1 ); - } - else - { - llxYz = llxY0; - ccxYz = ccxY0; - } - if ( llTrans0Yz || llTransXY0 ) - { - llXYz = getShadeBrightness(tt, level, pX + 1, pY, pZ - 1 ); - ccXYz = getLightColor(tt, level, pX + 1, pY, pZ - 1 ); - } - else - { - llXYz = llXY0; - ccXYz = ccXY0; - } - if ( llTrans0YZ || llTransxY0 ) - { - llxYZ = getShadeBrightness(tt, level, pX - 1, pY, pZ + 1 ); - ccxYZ = getLightColor(tt, level, pX - 1, pY, pZ + 1 ); - } - else - { - llxYZ = llxY0; - ccxYZ = ccxY0; - } - if ( llTrans0YZ || llTransXY0 ) - { - llXYZ = getShadeBrightness(tt, level, pX + 1, pY, pZ + 1 ); - ccXYZ = getLightColor(tt, level, pX + 1, pY, pZ + 1 ); - } - else - { - llXYZ = llXY0; - ccXYZ = ccXY0; - } - if ( tileShapeY1 >= 1 ) pY--; // 4J - condition brought forward from 1.2.3 + ll4 = (llxYZ + llxY0 + ll0YZ + ll0Y0) / 4.0f; + ll1 = (ll0YZ + ll0Y0 + llXYZ + llXY0) / 4.0f; + ll2 = (ll0Y0 + ll0Yz + llXY0 + llXYz) / 4.0f; + ll3 = (llxY0 + llxYz + ll0Y0 + ll0Yz) / 4.0f; - ll4 = ( llxYZ + llxY0 + ll0YZ + ll0Y0 ) / 4.0f; - ll1 = ( ll0YZ + ll0Y0 + llXYZ + llXY0 ) / 4.0f; - ll2 = ( ll0Y0 + ll0Yz + llXY0 + llXYz ) / 4.0f; - ll3 = ( llxY0 + llxYz + ll0Y0 + ll0Yz ) / 4.0f; + tc4 = blend(ccxYZ, ccxY0, cc0YZ, cc0Y0); + tc1 = blend(cc0YZ, ccXYZ, ccXY0, cc0Y0); + tc2 = blend(cc0Yz, ccXY0, ccXYz, cc0Y0); + tc3 = blend(ccxY0, ccxYz, cc0Yz, cc0Y0); + } else { + ll1 = ll2 = ll3 = ll4 = ll0Y0; + tc1 = tc2 = tc3 = tc4 = cc0Y0; + } + c1r = c2r = c3r = c4r = (tint1 ? pBaseRed : 1.0f); + c1g = c2g = c3g = c4g = (tint1 ? pBaseGreen : 1.0f); + c1b = c2b = c3b = c4b = (tint1 ? pBaseBlue : 1.0f); + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; + renderFaceUp( + tt, (double)pX, (double)pY, (double)pZ, + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 1)); + } + if (faceFlags & 0x04) { + if (blsmooth > 0) { + if (tileShapeZ0 <= 0) + pZ--; // 4J - condition brought forward from 1.2.3 + llx0z = getShadeBrightness(tt, level, pX - 1, pY, pZ); + ll0yz = getShadeBrightness(tt, level, pX, pY - 1, pZ); + ll0Yz = getShadeBrightness(tt, level, pX, pY + 1, pZ); + llX0z = getShadeBrightness(tt, level, pX + 1, pY, pZ); - tc4 = blend( ccxYZ, ccxY0, cc0YZ, cc0Y0 ); - tc1 = blend( cc0YZ, ccXYZ, ccXY0, cc0Y0 ); - tc2 = blend( cc0Yz, ccXY0, ccXYz, cc0Y0 ); - tc3 = blend( ccxY0, ccxYz, cc0Yz, cc0Y0 ); - } - else - { - ll1 = ll2 = ll3 = ll4 = ll0Y0; - tc1 = tc2 = tc3 = tc4 = cc0Y0; - } - c1r = c2r = c3r = c4r = ( tint1 ? pBaseRed : 1.0f ); - c1g = c2g = c3g = c4g = ( tint1 ? pBaseGreen : 1.0f ); - c1b = c2b = c3b = c4b = ( tint1 ? pBaseBlue : 1.0f ); - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; - renderFaceUp( tt, ( double )pX, ( double )pY, ( double )pZ, uniformTex ? uniformTex : getTexture( tt, level, pX, pY, pZ, 1 ) ); - } - if ( faceFlags & 0x04 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeZ0 <= 0 ) pZ--; // 4J - condition brought forward from 1.2.3 - llx0z = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - ll0yz = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - ll0Yz = getShadeBrightness(tt, level, pX, pY + 1, pZ ); - llX0z = getShadeBrightness(tt, level, pX + 1, pY, pZ ); + ccx0z = getLightColor(tt, level, pX - 1, pY, pZ); + cc0yz = getLightColor(tt, level, pX, pY - 1, pZ); + cc0Yz = getLightColor(tt, level, pX, pY + 1, pZ); + ccX0z = getLightColor(tt, level, pX + 1, pY, pZ); - ccx0z = getLightColor(tt, level, pX - 1, pY, pZ ); - cc0yz = getLightColor(tt, level, pX, pY - 1, pZ ); - cc0Yz = getLightColor(tt, level, pX, pY + 1, pZ ); - ccX0z = getLightColor(tt, level, pX + 1, pY, pZ ); + if (llTransx0z || llTrans0yz) { + llxyz = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ); + ccxyz = getLightColor(tt, level, pX - 1, pY - 1, pZ); + } else { + llxyz = llx0z; + ccxyz = ccx0z; + } + if (llTransx0z || llTrans0Yz) { + llxYz = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ); + ccxYz = getLightColor(tt, level, pX - 1, pY + 1, pZ); + } else { + llxYz = llx0z; + ccxYz = ccx0z; + } + if (llTransX0z || llTrans0yz) { + llXyz = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ); + ccXyz = getLightColor(tt, level, pX + 1, pY - 1, pZ); + } else { + llXyz = llX0z; + ccXyz = ccX0z; + } + if (llTransX0z || llTrans0Yz) { + llXYz = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ); + ccXYz = getLightColor(tt, level, pX + 1, pY + 1, pZ); + } else { + llXYz = llX0z; + ccXYz = ccX0z; + } + if (tileShapeZ0 <= 0) + pZ++; // 4J - condition brought forward from 1.2.3 - if ( llTransx0z || llTrans0yz ) - { - llxyz = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ ); - ccxyz = getLightColor(tt, level, pX - 1, pY - 1, pZ ); - } - else - { - llxyz = llx0z; - ccxyz = ccx0z; - } - if ( llTransx0z || llTrans0Yz ) - { - llxYz = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ ); - ccxYz = getLightColor(tt, level, pX - 1, pY + 1, pZ ); - } - else - { - llxYz = llx0z; - ccxYz = ccx0z; - } - if ( llTransX0z || llTrans0yz ) - { - llXyz = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ ); - ccXyz = getLightColor(tt, level, pX + 1, pY - 1, pZ ); - } - else - { - llXyz = llX0z; - ccXyz = ccX0z; - } - if ( llTransX0z || llTrans0Yz ) - { - llXYz = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ ); - ccXYz = getLightColor(tt, level, pX + 1, pY + 1, pZ ); - } - else - { - llXYz = llX0z; - ccXYz = ccX0z; - } - if ( tileShapeZ0 <= 0 ) pZ++; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX + // until we work out exactly what its peformance + // implications are/what it fixes + { + float _ll1 = (llx0z + llxYz + ll00z + ll0Yz) / 4.0f; + float _ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; + float _ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; + float _ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; + ll1 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + + _ll2 * tileShapeY0 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + + _ll4 * (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); + ll2 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + + _ll2 * tileShapeY1 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + + _ll4 * (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); + ll3 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + + _ll2 * tileShapeY0 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + + _ll4 * (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); + ll4 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + + _ll2 * tileShapeY0 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + + _ll4 * (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); - if (smoothShapeLighting && false) //minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll1 = (llx0z + llxYz + ll00z + ll0Yz) / 4.0f; - float _ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; - float _ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; - float _ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll2 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll4 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll2 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll2 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll4 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); + int _tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); + int _tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); + int _tc3 = blend(cc0yz, ccXyz, ccX0z, cc00z); + int _tc4 = blend(ccxyz, ccx0z, cc0yz, cc00z); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX0), + tileShapeY1 * tileShapeX0, + (1.0 - tileShapeY1) * tileShapeX0, + (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX1), + tileShapeY1 * tileShapeX1, + (1.0 - tileShapeY1) * tileShapeX1, + (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX1), + tileShapeY0 * tileShapeX1, + (1.0 - tileShapeY0) * tileShapeX1, + (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX0), + tileShapeY0 * tileShapeX0, + (1.0 - tileShapeY0) * tileShapeX0, + (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); + } else { + ll1 = (llx0z + llxYz + ll00z + ll0Yz) / 4.0f; + ll2 = (ll00z + ll0Yz + llX0z + llXYz) / 4.0f; + ll3 = (ll0yz + ll00z + llXyz + llX0z) / 4.0f; + ll4 = (llxyz + llx0z + ll0yz + ll00z) / 4.0f; - int _tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); - int _tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); - int _tc3 = blend(cc0yz, ccXyz, ccX0z, cc00z); - int _tc4 = blend(ccxyz, ccx0z, cc0yz, cc00z); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX0), tileShapeY1 * tileShapeX0, (1.0 - tileShapeY1) * tileShapeX0, (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX1), tileShapeY1 * tileShapeX1, (1.0 - tileShapeY1) * tileShapeX1, (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX1), tileShapeY0 * tileShapeX1, (1.0 - tileShapeY0) * tileShapeX1, (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX0), tileShapeY0 * tileShapeX0, (1.0 - tileShapeY0) * tileShapeX0, (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); - } else { - ll1 = ( llx0z + llxYz + ll00z + ll0Yz ) / 4.0f; - ll2 = ( ll00z + ll0Yz + llX0z + llXYz ) / 4.0f; - ll3 = ( ll0yz + ll00z + llXyz + llX0z ) / 4.0f; - ll4 = ( llxyz + llx0z + ll0yz + ll00z ) / 4.0f; + tc1 = blend(ccx0z, ccxYz, cc0Yz, cc00z); + tc2 = blend(cc0Yz, ccX0z, ccXYz, cc00z); + tc3 = blend(cc0yz, ccXyz, ccX0z, cc00z); + tc4 = blend(ccxyz, ccx0z, cc0yz, cc00z); + } + } else { + ll1 = ll2 = ll3 = ll4 = ll00z; + tc1 = tc2 = tc3 = tc4 = cc00z; + } + c1r = c2r = c3r = c4r = (tint2 ? pBaseRed : 1.0f) * 0.8f; + c1g = c2g = c3g = c4g = (tint2 ? pBaseGreen : 1.0f) * 0.8f; + c1b = c2b = c3b = c4b = (tint2 ? pBaseBlue : 1.0f) * 0.8f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; - tc1 = blend( ccx0z, ccxYz, cc0Yz, cc00z ); - tc2 = blend( cc0Yz, ccX0z, ccXYz, cc00z ); - tc3 = blend( cc0yz, ccXyz, ccX0z, cc00z ); - tc4 = blend( ccxyz, ccx0z, cc0yz, cc00z ); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = ll00z; - tc1 = tc2 = tc3 = tc4 = cc00z; - } - c1r = c2r = c3r = c4r = ( tint2 ? pBaseRed : 1.0f ) * 0.8f; - c1g = c2g = c3g = c4g = ( tint2 ? pBaseGreen : 1.0f ) * 0.8f; - c1b = c2b = c3b = c4b = ( tint2 ? pBaseBlue : 1.0f ) * 0.8f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 2); + renderNorth(tt, (double)pX, (double)pY, (double)pZ, tex); - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 2); - renderNorth( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderNorth(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + if (faceFlags & 0x08) { + if (blsmooth > 0) { + if (tileShapeZ1 >= 1) + pZ++; // 4J - condition brought forward from 1.2.3 - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderNorth( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - if ( faceFlags & 0x08 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeZ1 >= 1 ) pZ++; // 4J - condition brought forward from 1.2.3 + llx0Z = getShadeBrightness(tt, level, pX - 1, pY, pZ); + llX0Z = getShadeBrightness(tt, level, pX + 1, pY, pZ); + ll0yZ = getShadeBrightness(tt, level, pX, pY - 1, pZ); + ll0YZ = getShadeBrightness(tt, level, pX, pY + 1, pZ); - llx0Z = getShadeBrightness(tt, level, pX - 1, pY, pZ ); - llX0Z = getShadeBrightness(tt, level, pX + 1, pY, pZ ); - ll0yZ = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - ll0YZ = getShadeBrightness(tt, level, pX, pY + 1, pZ ); + ccx0Z = getLightColor(tt, level, pX - 1, pY, pZ); + ccX0Z = getLightColor(tt, level, pX + 1, pY, pZ); + cc0yZ = getLightColor(tt, level, pX, pY - 1, pZ); + cc0YZ = getLightColor(tt, level, pX, pY + 1, pZ); - ccx0Z = getLightColor(tt, level, pX - 1, pY, pZ ); - ccX0Z = getLightColor(tt, level, pX + 1, pY, pZ ); - cc0yZ = getLightColor(tt, level, pX, pY - 1, pZ ); - cc0YZ = getLightColor(tt, level, pX, pY + 1, pZ ); + if (llTransx0Z || llTrans0yZ) { + llxyZ = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ); + ccxyZ = getLightColor(tt, level, pX - 1, pY - 1, pZ); + } else { + llxyZ = llx0Z; + ccxyZ = ccx0Z; + } + if (llTransx0Z || llTrans0YZ) { + llxYZ = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ); + ccxYZ = getLightColor(tt, level, pX - 1, pY + 1, pZ); + } else { + llxYZ = llx0Z; + ccxYZ = ccx0Z; + } + if (llTransX0Z || llTrans0yZ) { + llXyZ = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ); + ccXyZ = getLightColor(tt, level, pX + 1, pY - 1, pZ); + } else { + llXyZ = llX0Z; + ccXyZ = ccX0Z; + } + if (llTransX0Z || llTrans0YZ) { + llXYZ = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ); + ccXYZ = getLightColor(tt, level, pX + 1, pY + 1, pZ); + } else { + llXYZ = llX0Z; + ccXYZ = ccX0Z; + } + if (tileShapeZ1 >= 1) + pZ--; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX until + // we work out exactly what its peformance implications + // are/what it fixes + { + float _ll1 = (llx0Z + llxYZ + ll00Z + ll0YZ) / 4.0f; + float _ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; + float _ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; + float _ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; + ll1 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + + _ll4 * tileShapeY1 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeX0)); + ll2 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + + _ll4 * tileShapeY0 * tileShapeX0 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeX0)); + ll3 = (float)(_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + + _ll4 * tileShapeY0 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeX1)); + ll4 = (float)(_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + + _ll4 * tileShapeY1 * tileShapeX1 + + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeX1)); - if ( llTransx0Z || llTrans0yZ ) - { - llxyZ = getShadeBrightness(tt, level, pX - 1, pY - 1, pZ ); - ccxyZ = getLightColor(tt, level, pX - 1, pY - 1, pZ ); - } - else - { - llxyZ = llx0Z; - ccxyZ = ccx0Z; - } - if ( llTransx0Z || llTrans0YZ ) - { - llxYZ = getShadeBrightness(tt, level, pX - 1, pY + 1, pZ ); - ccxYZ = getLightColor(tt, level, pX - 1, pY + 1, pZ ); - } - else - { - llxYZ = llx0Z; - ccxYZ = ccx0Z; - } - if ( llTransX0Z || llTrans0yZ ) - { - llXyZ = getShadeBrightness(tt, level, pX + 1, pY - 1, pZ ); - ccXyZ = getLightColor(tt, level, pX + 1, pY - 1, pZ ); - } - else - { - llXyZ = llX0Z; - ccXyZ = ccX0Z; - } - if ( llTransX0Z || llTrans0YZ ) - { - llXYZ = getShadeBrightness(tt, level, pX + 1, pY + 1, pZ ); - ccXYZ = getLightColor(tt, level, pX + 1, pY + 1, pZ ); - } - else - { - llXYZ = llX0Z; - ccXYZ = ccX0Z; - } - if ( tileShapeZ1 >= 1 ) pZ--; // 4J - condition brought forward from 1.2.3 - if (smoothShapeLighting && false)//minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll1 = (llx0Z + llxYZ + ll00Z + ll0YZ) / 4.0f; - float _ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; - float _ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; - float _ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX0) + _ll4 * tileShapeY1 * tileShapeX0 + _ll3 * (1.0 - tileShapeY1) * tileShapeX0 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX0)); - ll2 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX0) + _ll4 * tileShapeY0 * tileShapeX0 + _ll3 * (1.0 - tileShapeY0) * tileShapeX0 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX0)); - ll3 = (float) (_ll1 * tileShapeY0 * (1.0 - tileShapeX1) + _ll4 * tileShapeY0 * tileShapeX1 + _ll3 * (1.0 - tileShapeY0) * tileShapeX1 + _ll2 * (1.0 - tileShapeY0) - * (1.0 - tileShapeX1)); - ll4 = (float) (_ll1 * tileShapeY1 * (1.0 - tileShapeX1) + _ll4 * tileShapeY1 * tileShapeX1 + _ll3 * (1.0 - tileShapeY1) * tileShapeX1 + _ll2 * (1.0 - tileShapeY1) - * (1.0 - tileShapeX1)); + int _tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); + int _tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); + int _tc3 = blend(cc0yZ, ccXyZ, ccX0Z, cc00Z); + int _tc2 = blend(ccxyZ, ccx0Z, cc0yZ, cc00Z); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX0), + (1.0 - tileShapeY1) * (1.0 - tileShapeX0), + (1.0 - tileShapeY1) * tileShapeX0, + tileShapeY1 * tileShapeX0); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX0), + (1.0 - tileShapeY0) * (1.0 - tileShapeX0), + (1.0 - tileShapeY0) * tileShapeX0, + tileShapeY0 * tileShapeX0); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY0 * (1.0 - tileShapeX1), + (1.0 - tileShapeY0) * (1.0 - tileShapeX1), + (1.0 - tileShapeY0) * tileShapeX1, + tileShapeY0 * tileShapeX1); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, + tileShapeY1 * (1.0 - tileShapeX1), + (1.0 - tileShapeY1) * (1.0 - tileShapeX1), + (1.0 - tileShapeY1) * tileShapeX1, + tileShapeY1 * tileShapeX1); + } else { + ll1 = (llx0Z + llxYZ + ll00Z + ll0YZ) / 4.0f; + ll4 = (ll00Z + ll0YZ + llX0Z + llXYZ) / 4.0f; + ll3 = (ll0yZ + ll00Z + llXyZ + llX0Z) / 4.0f; + ll2 = (llxyZ + llx0Z + ll0yZ + ll00Z) / 4.0f; - int _tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); - int _tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); - int _tc3 = blend(cc0yZ, ccXyZ, ccX0Z, cc00Z); - int _tc2 = blend(ccxyZ, ccx0Z, cc0yZ, cc00Z); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX0), (1.0 - tileShapeY1) * (1.0 - tileShapeX0), (1.0 - tileShapeY1) * tileShapeX0, tileShapeY1 * tileShapeX0); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX0), (1.0 - tileShapeY0) * (1.0 - tileShapeX0), (1.0 - tileShapeY0) * tileShapeX0, tileShapeY0 * tileShapeX0); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * (1.0 - tileShapeX1), (1.0 - tileShapeY0) * (1.0 - tileShapeX1), (1.0 - tileShapeY0) * tileShapeX1, tileShapeY0 * tileShapeX1); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * (1.0 - tileShapeX1), (1.0 - tileShapeY1) * (1.0 - tileShapeX1), (1.0 - tileShapeY1) * tileShapeX1, tileShapeY1 * tileShapeX1); - } - else - { - ll1 = ( llx0Z + llxYZ + ll00Z + ll0YZ ) / 4.0f; - ll4 = ( ll00Z + ll0YZ + llX0Z + llXYZ ) / 4.0f; - ll3 = ( ll0yZ + ll00Z + llXyZ + llX0Z ) / 4.0f; - ll2 = ( llxyZ + llx0Z + ll0yZ + ll00Z ) / 4.0f; + tc1 = blend(ccx0Z, ccxYZ, cc0YZ, cc00Z); + tc4 = blend(cc0YZ, ccX0Z, ccXYZ, cc00Z); + tc3 = blend(cc0yZ, ccXyZ, ccX0Z, cc00Z); + tc2 = blend(ccxyZ, ccx0Z, cc0yZ, cc00Z); + } + } else { + ll1 = ll2 = ll3 = ll4 = ll00Z; + tc1 = tc2 = tc3 = tc4 = cc00Z; + } + c1r = c2r = c3r = c4r = (tint3 ? pBaseRed : 1.0f) * 0.8f; + c1g = c2g = c3g = c4g = (tint3 ? pBaseGreen : 1.0f) * 0.8f; + c1b = c2b = c3b = c4b = (tint3 ? pBaseBlue : 1.0f) * 0.8f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 3); + renderSouth(tt, (double)pX, (double)pY, (double)pZ, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderSouth(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + if (faceFlags & 0x10) { + if (blsmooth > 0) { + if (tileShapeX0 <= 0) + pX--; // 4J - condition brought forward from 1.2.3 + llxy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ); + llx0z = getShadeBrightness(tt, level, pX, pY, pZ - 1); + llx0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1); + llxY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ); - tc1 = blend( ccx0Z, ccxYZ, cc0YZ, cc00Z ); - tc4 = blend( cc0YZ, ccX0Z, ccXYZ, cc00Z ); - tc3 = blend( cc0yZ, ccXyZ, ccX0Z, cc00Z ); - tc2 = blend( ccxyZ, ccx0Z, cc0yZ, cc00Z ); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = ll00Z; - tc1 = tc2 = tc3 = tc4 = cc00Z; - } - c1r = c2r = c3r = c4r = ( tint3 ? pBaseRed : 1.0f ) * 0.8f; - c1g = c2g = c3g = c4g = ( tint3 ? pBaseGreen : 1.0f ) * 0.8f; - c1b = c2b = c3b = c4b = ( tint3 ? pBaseBlue : 1.0f ) * 0.8f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 3); - renderSouth( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderSouth( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - if ( faceFlags & 0x10 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeX0 <= 0 ) pX--; // 4J - condition brought forward from 1.2.3 - llxy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - llx0z = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - llx0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); - llxY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ ); + ccxy0 = getLightColor(tt, level, pX, pY - 1, pZ); + ccx0z = getLightColor(tt, level, pX, pY, pZ - 1); + ccx0Z = getLightColor(tt, level, pX, pY, pZ + 1); + ccxY0 = getLightColor(tt, level, pX, pY + 1, pZ); - ccxy0 = getLightColor(tt, level, pX, pY - 1, pZ ); - ccx0z = getLightColor(tt, level, pX, pY, pZ - 1 ); - ccx0Z = getLightColor(tt, level, pX, pY, pZ + 1 ); - ccxY0 = getLightColor(tt, level, pX, pY + 1, pZ ); + if (llTransx0z || llTransxy0) { + llxyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1); + ccxyz = getLightColor(tt, level, pX, pY - 1, pZ - 1); + } else { + llxyz = llx0z; + ccxyz = ccx0z; + } + if (llTransx0Z || llTransxy0) { + llxyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1); + ccxyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1); + } else { + llxyZ = llx0Z; + ccxyZ = ccx0Z; + } + if (llTransx0z || llTransxY0) { + llxYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1); + ccxYz = getLightColor(tt, level, pX, pY + 1, pZ - 1); + } else { + llxYz = llx0z; + ccxYz = ccx0z; + } + if (llTransx0Z || llTransxY0) { + llxYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1); + ccxYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1); + } else { + llxYZ = llx0Z; + ccxYZ = ccx0Z; + } + if (tileShapeX0 <= 0) + pX++; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX until we + // work out exactly what its peformance implications + // are/what it fixes + { + float _ll4 = (llxy0 + llxyZ + llx00 + llx0Z) / 4.0f; + float _ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; + float _ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; + float _ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; + ll1 = (float)(_ll1 * tileShapeY1 * tileShapeZ1 + + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + + _ll4 * (1.0 - tileShapeY1) * tileShapeZ1); + ll2 = (float)(_ll1 * tileShapeY1 * tileShapeZ0 + + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + + _ll4 * (1.0 - tileShapeY1) * tileShapeZ0); + ll3 = (float)(_ll1 * tileShapeY0 * tileShapeZ0 + + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + + _ll4 * (1.0 - tileShapeY0) * tileShapeZ0); + ll4 = (float)(_ll1 * tileShapeY0 * tileShapeZ1 + + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + + _ll4 * (1.0 - tileShapeY0) * tileShapeZ1); - if ( llTransx0z || llTransxy0 ) - { - llxyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1 ); - ccxyz = getLightColor(tt, level, pX, pY - 1, pZ - 1 ); - } - else - { - llxyz = llx0z; - ccxyz = ccx0z; - } - if ( llTransx0Z || llTransxy0 ) - { - llxyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1 ); - ccxyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1 ); - } - else - { - llxyZ = llx0Z; - ccxyZ = ccx0Z; - } - if ( llTransx0z || llTransxY0 ) - { - llxYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1 ); - ccxYz = getLightColor(tt, level, pX, pY + 1, pZ - 1 ); - } - else - { - llxYz = llx0z; - ccxYz = ccx0z; - } - if ( llTransx0Z || llTransxY0 ) - { - llxYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1 ); - ccxYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1 ); - } - else - { - llxYZ = llx0Z; - ccxYZ = ccx0Z; - } - if ( tileShapeX0 <= 0 ) pX++; // 4J - condition brought forward from 1.2.3 - if (smoothShapeLighting && false)//minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll4 = (llxy0 + llxyZ + llx00 + llx0Z) / 4.0f; - float _ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; - float _ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; - float _ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; - ll1 = (float) (_ll1 * tileShapeY1 * tileShapeZ1 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ1); - ll2 = (float) (_ll1 * tileShapeY1 * tileShapeZ0 + _ll2 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY1) - * tileShapeZ0); - ll3 = (float) (_ll1 * tileShapeY0 * tileShapeZ0 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ0); - ll4 = (float) (_ll1 * tileShapeY0 * tileShapeZ1 + _ll2 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll3 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll4 * (1.0 - tileShapeY0) - * tileShapeZ1); + int _tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); + int _tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); + int _tc2 = blend(ccx0z, ccxYz, ccxY0, ccx00); + int _tc3 = blend(ccxyz, ccxy0, ccx0z, ccx00); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ1, + tileShapeY1 * (1.0 - tileShapeZ1), + (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), + (1.0 - tileShapeY1) * tileShapeZ1); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ0, + tileShapeY1 * (1.0 - tileShapeZ0), + (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), + (1.0 - tileShapeY1) * tileShapeZ0); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ0, + tileShapeY0 * (1.0 - tileShapeZ0), + (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), + (1.0 - tileShapeY0) * tileShapeZ0); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ1, + tileShapeY0 * (1.0 - tileShapeZ1), + (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), + (1.0 - tileShapeY0) * tileShapeZ1); + } else { + ll4 = (llxy0 + llxyZ + llx00 + llx0Z) / 4.0f; + ll1 = (llx00 + llx0Z + llxY0 + llxYZ) / 4.0f; + ll2 = (llx0z + llx00 + llxYz + llxY0) / 4.0f; + ll3 = (llxyz + llxy0 + llx0z + llx00) / 4.0f; - int _tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); - int _tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); - int _tc2 = blend(ccx0z, ccxYz, ccxY0, ccx00); - int _tc3 = blend(ccxyz, ccxy0, ccx0z, ccx00); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ1, tileShapeY1 * (1.0 - tileShapeZ1), (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), (1.0 - tileShapeY1) * tileShapeZ1); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY1 * tileShapeZ0, tileShapeY1 * (1.0 - tileShapeZ0), (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), (1.0 - tileShapeY1) * tileShapeZ0); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ0, tileShapeY0 * (1.0 - tileShapeZ0), (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), (1.0 - tileShapeY0) * tileShapeZ0); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, tileShapeY0 * tileShapeZ1, tileShapeY0 * (1.0 - tileShapeZ1), (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), (1.0 - tileShapeY0) * tileShapeZ1); - } - else - { - ll4 = ( llxy0 + llxyZ + llx00 + llx0Z ) / 4.0f; - ll1 = ( llx00 + llx0Z + llxY0 + llxYZ ) / 4.0f; - ll2 = ( llx0z + llx00 + llxYz + llxY0 ) / 4.0f; - ll3 = ( llxyz + llxy0 + llx0z + llx00 ) / 4.0f; + tc4 = blend(ccxy0, ccxyZ, ccx0Z, ccx00); + tc1 = blend(ccx0Z, ccxY0, ccxYZ, ccx00); + tc2 = blend(ccx0z, ccxYz, ccxY0, ccx00); + tc3 = blend(ccxyz, ccxy0, ccx0z, ccx00); + } + } else { + ll1 = ll2 = ll3 = ll4 = llx00; + tc1 = tc2 = tc3 = tc4 = ccx00; + } + c1r = c2r = c3r = c4r = (tint4 ? pBaseRed : 1.0f) * 0.6f; + c1g = c2g = c3g = c4g = (tint4 ? pBaseGreen : 1.0f) * 0.6f; + c1b = c2b = c3b = c4b = (tint4 ? pBaseBlue : 1.0f) * 0.6f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 4); + renderWest(tt, (double)pX, (double)pY, (double)pZ, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderWest(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + if (faceFlags & 0x20) { + if (blsmooth > 0) { + if (tileShapeX1 >= 1) + pX++; // 4J - condition brought forward from 1.2.3 + llXy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ); + llX0z = getShadeBrightness(tt, level, pX, pY, pZ - 1); + llX0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1); + llXY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ); - tc4 = blend( ccxy0, ccxyZ, ccx0Z, ccx00 ); - tc1 = blend( ccx0Z, ccxY0, ccxYZ, ccx00 ); - tc2 = blend( ccx0z, ccxYz, ccxY0, ccx00 ); - tc3 = blend( ccxyz, ccxy0, ccx0z, ccx00 ); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = llx00; - tc1 = tc2 = tc3 = tc4 = ccx00; - } - c1r = c2r = c3r = c4r = ( tint4 ? pBaseRed : 1.0f ) * 0.6f; - c1g = c2g = c3g = c4g = ( tint4 ? pBaseGreen : 1.0f ) * 0.6f; - c1b = c2b = c3b = c4b = ( tint4 ? pBaseBlue : 1.0f ) * 0.6f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 4); - renderWest( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderWest( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - if ( faceFlags & 0x20 ) - { - if ( blsmooth > 0 ) - { - if ( tileShapeX1 >= 1 ) pX++; // 4J - condition brought forward from 1.2.3 - llXy0 = getShadeBrightness(tt, level, pX, pY - 1, pZ ); - llX0z = getShadeBrightness(tt, level, pX, pY, pZ - 1 ); - llX0Z = getShadeBrightness(tt, level, pX, pY, pZ + 1 ); - llXY0 = getShadeBrightness(tt, level, pX, pY + 1, pZ ); + ccXy0 = getLightColor(tt, level, pX, pY - 1, pZ); + ccX0z = getLightColor(tt, level, pX, pY, pZ - 1); + ccX0Z = getLightColor(tt, level, pX, pY, pZ + 1); + ccXY0 = getLightColor(tt, level, pX, pY + 1, pZ); - ccXy0 = getLightColor(tt, level, pX, pY - 1, pZ ); - ccX0z = getLightColor(tt, level, pX, pY, pZ - 1 ); - ccX0Z = getLightColor(tt, level, pX, pY, pZ + 1 ); - ccXY0 = getLightColor(tt, level, pX, pY + 1, pZ ); + if (llTransXy0 || llTransX0z) { + llXyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1); + ccXyz = getLightColor(tt, level, pX, pY - 1, pZ - 1); + } else { + llXyz = llX0z; + ccXyz = ccX0z; + } + if (llTransXy0 || llTransX0Z) { + llXyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1); + ccXyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1); + } else { + llXyZ = llX0Z; + ccXyZ = ccX0Z; + } + if (llTransXY0 || llTransX0z) { + llXYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1); + ccXYz = getLightColor(tt, level, pX, pY + 1, pZ - 1); + } else { + llXYz = llX0z; + ccXYz = ccX0z; + } + if (llTransXY0 || llTransX0Z) { + llXYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1); + ccXYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1); + } else { + llXYZ = llX0Z; + ccXYZ = ccX0Z; + } + if (tileShapeX1 >= 1) + pX--; // 4J - condition brought forward from 1.2.3 + if (smoothShapeLighting && + false) // minecraft->options->ambientOcclusion >= + // Options::AO_MAX) // 4J - disabling AO_MAX until we + // work out exactly what its peformance implications + // are/what it fixes + { + float _ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; + float _ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; + float _ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; + float _ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; + ll1 = (float)(_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + + _ll4 * tileShapeY0 * tileShapeZ1); + ll2 = (float)(_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + + _ll4 * tileShapeY0 * tileShapeZ0); + ll3 = (float)(_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + + _ll4 * tileShapeY1 * tileShapeZ0); + ll4 = (float)(_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + + _ll4 * tileShapeY1 * tileShapeZ1); - if ( llTransXy0 || llTransX0z ) - { - llXyz = getShadeBrightness(tt, level, pX, pY - 1, pZ - 1 ); - ccXyz = getLightColor(tt, level, pX, pY - 1, pZ - 1 ); - } - else - { - llXyz = llX0z; - ccXyz = ccX0z; - } - if ( llTransXy0 || llTransX0Z ) - { - llXyZ = getShadeBrightness(tt, level, pX, pY - 1, pZ + 1 ); - ccXyZ = getLightColor(tt, level, pX, pY - 1, pZ + 1 ); - } - else - { - llXyZ = llX0Z; - ccXyZ = ccX0Z; - } - if ( llTransXY0 || llTransX0z ) - { - llXYz = getShadeBrightness(tt, level, pX, pY + 1, pZ - 1 ); - ccXYz = getLightColor(tt, level, pX, pY + 1, pZ - 1 ); - } - else - { - llXYz = llX0z; - ccXYz = ccX0z; - } - if ( llTransXY0 || llTransX0Z ) - { - llXYZ = getShadeBrightness(tt, level, pX, pY + 1, pZ + 1 ); - ccXYZ = getLightColor(tt, level, pX, pY + 1, pZ + 1 ); - } - else - { - llXYZ = llX0Z; - ccXYZ = ccX0Z; - } - if ( tileShapeX1 >= 1 ) pX--; // 4J - condition brought forward from 1.2.3 - if (smoothShapeLighting && false)//minecraft->options->ambientOcclusion >= Options::AO_MAX) // 4J - disabling AO_MAX until we work out exactly what its peformance implications are/what it fixes - { - float _ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; - float _ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; - float _ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; - float _ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; - ll1 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY0 - * tileShapeZ1); - ll2 = (float) (_ll1 * (1.0 - tileShapeY0) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY0) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY0 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY0 - * tileShapeZ0); - ll3 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ0 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ0) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ0) + _ll4 * tileShapeY1 - * tileShapeZ0); - ll4 = (float) (_ll1 * (1.0 - tileShapeY1) * tileShapeZ1 + _ll2 * (1.0 - tileShapeY1) * (1.0 - tileShapeZ1) + _ll3 * tileShapeY1 * (1.0 - tileShapeZ1) + _ll4 * tileShapeY1 - * tileShapeZ1); + int _tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); + int _tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); + int _tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); + int _tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); + tc1 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY0) * tileShapeZ1, + (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), + tileShapeY0 * (1.0 - tileShapeZ1), + tileShapeY0 * tileShapeZ1); + tc2 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY0) * tileShapeZ0, + (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), + tileShapeY0 * (1.0 - tileShapeZ0), + tileShapeY0 * tileShapeZ0); + tc3 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY1) * tileShapeZ0, + (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), + tileShapeY1 * (1.0 - tileShapeZ0), + tileShapeY1 * tileShapeZ0); + tc4 = blend(_tc1, _tc2, _tc3, _tc4, + (1.0 - tileShapeY1) * tileShapeZ1, + (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), + tileShapeY1 * (1.0 - tileShapeZ1), + tileShapeY1 * tileShapeZ1); + } else { + ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; + ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; + ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; + ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; - int _tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); - int _tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); - int _tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); - int _tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); - tc1 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY0) * tileShapeZ1, (1.0 - tileShapeY0) * (1.0 - tileShapeZ1), tileShapeY0 * (1.0 - tileShapeZ1), tileShapeY0 * tileShapeZ1); - tc2 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY0) * tileShapeZ0, (1.0 - tileShapeY0) * (1.0 - tileShapeZ0), tileShapeY0 * (1.0 - tileShapeZ0), tileShapeY0 * tileShapeZ0); - tc3 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY1) * tileShapeZ0, (1.0 - tileShapeY1) * (1.0 - tileShapeZ0), tileShapeY1 * (1.0 - tileShapeZ0), tileShapeY1 * tileShapeZ0); - tc4 = blend(_tc1, _tc2, _tc3, _tc4, (1.0 - tileShapeY1) * tileShapeZ1, (1.0 - tileShapeY1) * (1.0 - tileShapeZ1), tileShapeY1 * (1.0 - tileShapeZ1), tileShapeY1 * tileShapeZ1); - } - else - { - ll1 = (llXy0 + llXyZ + llX00 + llX0Z) / 4.0f; - ll2 = (llXyz + llXy0 + llX0z + llX00) / 4.0f; - ll3 = (llX0z + llX00 + llXYz + llXY0) / 4.0f; - ll4 = (llX00 + llX0Z + llXY0 + llXYZ) / 4.0f; + tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); + tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); + tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); + tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); + } + } else { + ll1 = ll2 = ll3 = ll4 = llX00; + tc1 = tc2 = tc3 = tc4 = ccX00; + } + c1r = c2r = c3r = c4r = (tint5 ? pBaseRed : 1.0f) * 0.6f; + c1g = c2g = c3g = c4g = (tint5 ? pBaseGreen : 1.0f) * 0.6f; + c1b = c2b = c3b = c4b = (tint5 ? pBaseBlue : 1.0f) * 0.6f; + c1r *= ll1; + c1g *= ll1; + c1b *= ll1; + c2r *= ll2; + c2g *= ll2; + c2b *= ll2; + c3r *= ll3; + c3g *= ll3; + c3b *= ll3; + c4r *= ll4; + c4g *= ll4; + c4b *= ll4; - tc1 = blend(ccXy0, ccXyZ, ccX0Z, ccX00); - tc4 = blend(ccX0Z, ccXY0, ccXYZ, ccX00); - tc3 = blend(ccX0z, ccXYz, ccXY0, ccX00); - tc2 = blend(ccXyz, ccXy0, ccX0z, ccX00); - } - } - else - { - ll1 = ll2 = ll3 = ll4 = llX00; - tc1 = tc2 = tc3 = tc4 = ccX00; - } - c1r = c2r = c3r = c4r = ( tint5 ? pBaseRed : 1.0f ) * 0.6f; - c1g = c2g = c3g = c4g = ( tint5 ? pBaseGreen : 1.0f ) * 0.6f; - c1b = c2b = c3b = c4b = ( tint5 ? pBaseBlue : 1.0f ) * 0.6f; - c1r *= ll1; - c1g *= ll1; - c1b *= ll1; - c2r *= ll2; - c2g *= ll2; - c2b *= ll2; - c3r *= ll3; - c3g *= ll3; - c3b *= ll3; - c4r *= ll4; - c4g *= ll4; - c4b *= ll4; + Icon* tex = + uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 5); + renderEast(tt, (double)pX, (double)pY, (double)pZ, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + c1r *= pBaseRed; + c2r *= pBaseRed; + c3r *= pBaseRed; + c4r *= pBaseRed; + c1g *= pBaseGreen; + c2g *= pBaseGreen; + c3g *= pBaseGreen; + c4g *= pBaseGreen; + c1b *= pBaseBlue; + c2b *= pBaseBlue; + c3b *= pBaseBlue; + c4b *= pBaseBlue; - Icon *tex = uniformTex ? uniformTex : getTexture(tt, level, pX, pY, pZ, 5); - renderEast( tt, ( double )pX, ( double )pY, ( double )pZ, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture()) - { - c1r *= pBaseRed; - c2r *= pBaseRed; - c3r *= pBaseRed; - c4r *= pBaseRed; - c1g *= pBaseGreen; - c2g *= pBaseGreen; - c3g *= pBaseGreen; - c4g *= pBaseGreen; - c1b *= pBaseBlue; - c2b *= pBaseBlue; - c3b *= pBaseBlue; - c4b *= pBaseBlue; - - bool prev = t->setMipmapEnable( false ); // 4J added - this is rendering the little bit of grass at the top of the side of dirt, don't mipmap it - renderEast( tt, ( double )pX, ( double )pY, ( double )pZ, GrassTile::getSideTextureOverlay() ); - t->setMipmapEnable( prev ); - } - } - applyAmbienceOcclusion = false; - - return true; + bool prev = t->setMipmapEnable( + false); // 4J added - this is rendering the little bit of grass + // at the top of the side of dirt, don't mipmap it + renderEast(tt, (double)pX, (double)pY, (double)pZ, + GrassTile::getSideTextureOverlay()); + t->setMipmapEnable(prev); + } + } + applyAmbienceOcclusion = false; + return true; } // 4J - brought forward from 1.8.2 -int TileRenderer::blend( int a, int b, int c, int def ) -{ - if ( a == 0 ) a = def; - if ( b == 0 ) b = def; - if ( c == 0 ) c = def; - return ( ( a + b + c + def ) >> 2 ) & 0xff00ff; +int TileRenderer::blend(int a, int b, int c, int def) { + if (a == 0) a = def; + if (b == 0) b = def; + if (c == 0) c = def; + return ((a + b + c + def) >> 2) & 0xff00ff; } -int TileRenderer::blend(int a, int b, int c, int d, double fa, double fb, double fc, double fd) -{ - - int top = (int) ((double) ((a >> 16) & 0xff) * fa + (double) ((b >> 16) & 0xff) * fb + (double) ((c >> 16) & 0xff) * fc + (double) ((d >> 16) & 0xff) * fd) & 0xff; - int bottom = (int) ((double) (a & 0xff) * fa + (double) (b & 0xff) * fb + (double) (c & 0xff) * fc + (double) (d & 0xff) * fd) & 0xff; - return (top << 16) | bottom; +int TileRenderer::blend(int a, int b, int c, int d, double fa, double fb, + double fc, double fd) { + int top = (int)((double)((a >> 16) & 0xff) * fa + + (double)((b >> 16) & 0xff) * fb + + (double)((c >> 16) & 0xff) * fc + + (double)((d >> 16) & 0xff) * fd) & + 0xff; + int bottom = (int)((double)(a & 0xff) * fa + (double)(b & 0xff) * fb + + (double)(c & 0xff) * fc + (double)(d & 0xff) * fd) & + 0xff; + return (top << 16) | bottom; } -bool TileRenderer::tesselateBlockInWorld( Tile* tt, int x, int y, int z, float r, float g, float b ) -{ - applyAmbienceOcclusion = false; +bool TileRenderer::tesselateBlockInWorld(Tile* tt, int x, int y, int z, float r, + float g, float b) { + applyAmbienceOcclusion = false; - Tesselator* t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - float r11 = c11 * r; - float g11 = c11 * g; - float b11 = c11 * b; + float r11 = c11 * r; + float g11 = c11 * g; + float b11 = c11 * b; - float r10 = c10; - float r2 = c2; - float r3 = c3; + float r10 = c10; + float r2 = c2; + float r3 = c3; - float g10 = c10; - float g2 = c2; - float g3 = c3; + float g10 = c10; + float g2 = c2; + float g3 = c3; - float b10 = c10; - float b2 = c2; - float b3 = c3; + float b10 = c10; + float b2 = c2; + float b3 = c3; - if ( tt != Tile::grass ) - { - r10 *= r; - r2 *= r; - r3 *= r; + if (tt != Tile::grass) { + r10 *= r; + r2 *= r; + r3 *= r; - g10 *= g; - g2 *= g; - g3 *= g; + g10 *= g; + g2 *= g; + g3 *= g; - b10 *= b; - b2 *= b; - b3 *= b; - } + b10 *= b; + b2 *= b; + b3 *= b; + } - int centerColor = 0; - float centerBrightness = 0.0f; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + int centerColor = 0; + float centerBrightness = 0.0f; + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } - if ( noCulling || tt->shouldRenderFace( level, x, y - 1, z, Facing::DOWN ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY0 > 0 ? centerColor : getLightColor(tt, level, x, y - 1, z ) ); - t->color( r10, g10, b10 ); - } - else - { - float br = tt->getBrightness( level, x, y - 1, z ); - t->color( r10 * br, g10 * br, b10 * br ); - } - renderFaceDown( tt, x, y, z, getTexture(tt, level, x, y, z, 0 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y - 1, z, Facing::DOWN)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY0 > 0 ? centerColor + : getLightColor(tt, level, x, y - 1, z)); + t->color(r10, g10, b10); + } else { + float br = tt->getBrightness(level, x, y - 1, z); + t->color(r10 * br, g10 * br, b10 * br); + } + renderFaceDown(tt, x, y, z, getTexture(tt, level, x, y, z, 0)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y + 1, z, Facing::UP ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY1 < 1 ? centerColor : getLightColor(tt, level, x, y + 1, z ) ); - t->color( r11, g11, b11 ); - } - else - { - float br = tt->getBrightness( level, x, y + 1, z ); - if ( tileShapeY1 != 1 && !tt->material->isLiquid() ) br = centerBrightness; - t->color( r11 * br, g11 * br, b11 * br ); - } - renderFaceUp( tt, x, y, z, getTexture(tt, level, x, y, z, 1 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y + 1, z, Facing::UP)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY1 < 1 ? centerColor + : getLightColor(tt, level, x, y + 1, z)); + t->color(r11, g11, b11); + } else { + float br = tt->getBrightness(level, x, y + 1, z); + if (tileShapeY1 != 1 && !tt->material->isLiquid()) + br = centerBrightness; + t->color(r11 * br, g11 * br, b11 * br); + } + renderFaceUp(tt, x, y, z, getTexture(tt, level, x, y, z, 1)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z - 1, Facing::NORTH ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } + if (noCulling || tt->shouldRenderFace(level, x, y, z - 1, Facing::NORTH)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } - Icon *tex = getTexture(tt, level, x, y, z, 2); - renderNorth( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r2 * r, g2 * g, b2 * b ); - renderNorth( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } + Icon* tex = getTexture(tt, level, x, y, z, 2); + renderNorth(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r2 * r, g2 * g, b2 * b); + renderNorth(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z + 1, Facing::SOUTH ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 3); - renderSouth( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r2 * r, g2 * g, b2 * b ); - renderSouth( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y, z + 1, Facing::SOUTH)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 3); + renderSouth(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r2 * r, g2 * g, b2 * b); + renderSouth(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x - 1, y, z, Facing::WEST ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 4); - renderWest( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r3 * r, g3 * g, b3 * b ); - renderWest( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x - 1, y, z, Facing::WEST)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 4); + renderWest(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r3 * r, g3 * g, b3 * b); + renderWest(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x + 1, y, z, Facing::EAST ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 5); - renderEast( tt, x, y, z, tex ); - if ( fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && !hasFixedTexture() ) - { - t->color( r3 * r, g3 * g, b3 * b ); - renderEast( tt, x, y, z, GrassTile::getSideTextureOverlay() ); - } - changed = true; - } - - return changed; + if (noCulling || tt->shouldRenderFace(level, x + 1, y, z, Facing::EAST)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 5); + renderEast(tt, x, y, z, tex); + if (fancy && (tex->getFlags() == Icon::IS_GRASS_SIDE) && + !hasFixedTexture()) { + t->color(r3 * r, g3 * g, b3 * b); + renderEast(tt, x, y, z, GrassTile::getSideTextureOverlay()); + } + changed = true; + } + return changed; } -bool TileRenderer::tesselateCactusInWorld( Tile* tt, int x, int y, int z ) -{ - int col = tt->getColor( level, x, y, z ); - float r = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; +bool TileRenderer::tesselateCactusInWorld(Tile* tt, int x, int y, int z) { + int col = tt->getColor(level, x, y, z); + float r = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - if ( GameRenderer::anaglyph3d ) - { - float cr = ( r * 30 + g * 59 + b * 11 ) / 100; - float cg = ( r * 30 + g * 70 ) / ( 100 ); - float cb = ( r * 30 + b * 70 ) / ( 100 ); + if (GameRenderer::anaglyph3d) { + float cr = (r * 30 + g * 59 + b * 11) / 100; + float cg = (r * 30 + g * 70) / (100); + float cb = (r * 30 + b * 70) / (100); - r = cr; - g = cg; - b = cb; - } + r = cr; + g = cg; + b = cb; + } - return tesselateCactusInWorld( tt, x, y, z, r, g, b ); + return tesselateCactusInWorld(tt, x, y, z, r, g, b); } -bool TileRenderer::tesselateCactusInWorld( Tile* tt, int x, int y, int z, float r, float g, float b ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateCactusInWorld(Tile* tt, int x, int y, int z, + float r, float g, float b) { + Tesselator* t = Tesselator::getInstance(); - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - float r10 = c10 * r; - float r11 = c11 * r; - float r2 = c2 * r; - float r3 = c3 * r; + float r10 = c10 * r; + float r11 = c11 * r; + float r2 = c2 * r; + float r3 = c3 * r; - float g10 = c10 * g; - float g11 = c11 * g; - float g2 = c2 * g; - float g3 = c3 * g; + float g10 = c10 * g; + float g11 = c11 * g; + float g2 = c2 * g; + float g3 = c3 * g; - float b10 = c10 * b; - float b11 = c11 * b; - float b2 = c2 * b; - float b3 = c3 * b; + float b10 = c10 * b; + float b11 = c11 * b; + float b2 = c2 * b; + float b3 = c3 * b; - float s = 1 / 16.0f; + float s = 1 / 16.0f; - float centerBrightness = 0.0f; - int centerColor = 0; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + float centerBrightness = 0.0f; + int centerColor = 0; + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } - if ( noCulling || tt->shouldRenderFace( level, x, y - 1, z, 0 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY0 > 0 ? centerColor : getLightColor(tt, level, x, y - 1, z ) ); - t->color( r10, g10, b10 ); - } - else - { - float br = tt->getBrightness( level, x, y - 1, z ); - t->color( r10 * br, g10 * br, b10 * br ); - } - renderFaceDown( tt, x, y, z, getTexture( tt, level, x, y, z, 0 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y - 1, z, 0)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY0 > 0 ? centerColor + : getLightColor(tt, level, x, y - 1, z)); + t->color(r10, g10, b10); + } else { + float br = tt->getBrightness(level, x, y - 1, z); + t->color(r10 * br, g10 * br, b10 * br); + } + renderFaceDown(tt, x, y, z, getTexture(tt, level, x, y, z, 0)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y + 1, z, 1 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY1 < 1 ? centerColor : getLightColor(tt, level, x, y + 1, z ) ); - t->color( r11, g11, b11 ); - } - else - { - float br = tt->getBrightness( level, x, y + 1, z ); - if ( tileShapeY1 != 1 && !tt->material->isLiquid() ) br = centerBrightness; - t->color( r11 * br, g11 * br, b11 * br ); - } - renderFaceUp( tt, x, y, z, getTexture( tt, level, x, y, z, 1 ) ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y + 1, z, 1)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY1 < 1 ? centerColor + : getLightColor(tt, level, x, y + 1, z)); + t->color(r11, g11, b11); + } else { + float br = tt->getBrightness(level, x, y + 1, z); + if (tileShapeY1 != 1 && !tt->material->isLiquid()) + br = centerBrightness; + t->color(r11 * br, g11 * br, b11 * br); + } + renderFaceUp(tt, x, y, z, getTexture(tt, level, x, y, z, 1)); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z - 1, 2 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } - t->addOffset( 0, 0, s ); - renderNorth( tt, x, y, z, getTexture(tt, level, x, y, z, 2 ) ); - t->addOffset( 0, 0, -s ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x, y, z - 1, 2)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } + t->addOffset(0, 0, s); + renderNorth(tt, x, y, z, getTexture(tt, level, x, y, z, 2)); + t->addOffset(0, 0, -s); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x, y, z + 1, 3 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( r2, g2, b2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - t->color( r2 * br, g2 * br, b2 * br ); - } + if (noCulling || tt->shouldRenderFace(level, x, y, z + 1, 3)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(r2, g2, b2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + t->color(r2 * br, g2 * br, b2 * br); + } - t->addOffset( 0, 0, -s ); - renderSouth( tt, x, y, z, getTexture(tt, level, x, y, z, 3 ) ); - t->addOffset( 0, 0, s ); - changed = true; - } + t->addOffset(0, 0, -s); + renderSouth(tt, x, y, z, getTexture(tt, level, x, y, z, 3)); + t->addOffset(0, 0, s); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x - 1, y, z, 4 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - t->addOffset( s, 0, 0 ); - renderWest( tt, x, y, z, getTexture(tt, level, x, y, z, 4 ) ); - t->addOffset( -s, 0, 0 ); - changed = true; - } + if (noCulling || tt->shouldRenderFace(level, x - 1, y, z, 4)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + t->addOffset(s, 0, 0); + renderWest(tt, x, y, z, getTexture(tt, level, x, y, z, 4)); + t->addOffset(-s, 0, 0); + changed = true; + } - if ( noCulling || tt->shouldRenderFace( level, x + 1, y, z, 5 ) ) - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( r3, g3, b3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - t->color( r3 * br, g3 * br, b3 * br ); - } - t->addOffset( -s, 0, 0 ); - renderEast( tt, x, y, z, getTexture(tt, level, x, y, z, 5 ) ); - t->addOffset( s, 0, 0 ); - changed = true; - } - - return changed; + if (noCulling || tt->shouldRenderFace(level, x + 1, y, z, 5)) { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(r3, g3, b3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + t->color(r3 * br, g3 * br, b3 * br); + } + t->addOffset(-s, 0, 0); + renderEast(tt, x, y, z, getTexture(tt, level, x, y, z, 5)); + t->addOffset(s, 0, 0); + changed = true; + } + return changed; } -bool TileRenderer::tesselateFenceInWorld( FenceTile* tt, int x, int y, int z ) -{ - bool changed = false; +bool TileRenderer::tesselateFenceInWorld(FenceTile* tt, int x, int y, int z) { + bool changed = false; - float a = 6 / 16.0f; - float b = 10 / 16.0f; + float a = 6 / 16.0f; + float b = 10 / 16.0f; - setShape( a, 0, a, b, 1, b ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; + setShape(a, 0, a, b, 1, b); + tesselateBlockInWorld(tt, x, y, z); + changed = true; - bool vertical = false; - bool horizontal = false; + bool vertical = false; + bool horizontal = false; - if (tt->connectsTo(level, x - 1, y, z) || tt->connectsTo(level, x + 1, y, z)) vertical = true; - if (tt->connectsTo(level, x, y, z - 1) || tt->connectsTo(level, x, y, z + 1)) horizontal = true; + if (tt->connectsTo(level, x - 1, y, z) || + tt->connectsTo(level, x + 1, y, z)) + vertical = true; + if (tt->connectsTo(level, x, y, z - 1) || + tt->connectsTo(level, x, y, z + 1)) + horizontal = true; - bool l = tt->connectsTo(level, x - 1, y, z); - bool r = tt->connectsTo(level, x + 1, y, z); - bool u = tt->connectsTo(level, x, y, z - 1); - bool d = tt->connectsTo(level, x, y, z + 1); + bool l = tt->connectsTo(level, x - 1, y, z); + bool r = tt->connectsTo(level, x + 1, y, z); + bool u = tt->connectsTo(level, x, y, z - 1); + bool d = tt->connectsTo(level, x, y, z + 1); - if ( !vertical && !horizontal ) vertical = true; + if (!vertical && !horizontal) vertical = true; - a = 7 / 16.0f; - b = 9 / 16.0f; - float h0 = 12 / 16.0f; - float h1 = 15 / 16.0f; + a = 7 / 16.0f; + b = 9 / 16.0f; + float h0 = 12 / 16.0f; + float h1 = 15 / 16.0f; - float x0 = l ? 0 : a; - float x1 = r ? 1 : b; - float z0 = u ? 0 : a; - float z1 = d ? 1 : b; - if ( vertical ) - { - setShape( x0, h0, a, x1, h1, b ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } - if ( horizontal ) - { - setShape( a, h0, z0, b, h1, z1 ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } + float x0 = l ? 0 : a; + float x1 = r ? 1 : b; + float z0 = u ? 0 : a; + float z1 = d ? 1 : b; + if (vertical) { + setShape(x0, h0, a, x1, h1, b); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } + if (horizontal) { + setShape(a, h0, z0, b, h1, z1); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } - h0 = 6 / 16.0f; - h1 = 9 / 16.0f; - if ( vertical ) - { - setShape( x0, h0, a, x1, h1, b ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } - if ( horizontal ) - { - setShape( a, h0, z0, b, h1, z1 ); - tesselateBlockInWorld( tt, x, y, z ); - changed = true; - } + h0 = 6 / 16.0f; + h1 = 9 / 16.0f; + if (vertical) { + setShape(x0, h0, a, x1, h1, b); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } + if (horizontal) { + setShape(a, h0, z0, b, h1, z1); + tesselateBlockInWorld(tt, x, y, z); + changed = true; + } - tt->updateShape(level, x, y, z); + tt->updateShape(level, x, y, z); - return changed; + return changed; } -bool TileRenderer::tesselateWallInWorld(WallTile *tt, int x, int y, int z) -{ - bool w = tt->connectsTo(level, x - 1, y, z); - bool e = tt->connectsTo(level, x + 1, y, z); - bool n = tt->connectsTo(level, x, y, z - 1); - bool s = tt->connectsTo(level, x, y, z + 1); +bool TileRenderer::tesselateWallInWorld(WallTile* tt, int x, int y, int z) { + bool w = tt->connectsTo(level, x - 1, y, z); + bool e = tt->connectsTo(level, x + 1, y, z); + bool n = tt->connectsTo(level, x, y, z - 1); + bool s = tt->connectsTo(level, x, y, z + 1); - bool vertical = (n && s && !w && !e); - bool horizontal = (!n && !s && w && e); - bool emptyAbove = level->isEmptyTile(x, y + 1, z); + bool vertical = (n && s && !w && !e); + bool horizontal = (!n && !s && w && e); + bool emptyAbove = level->isEmptyTile(x, y + 1, z); - if ((!vertical && !horizontal) || !emptyAbove) - { - // center post - setShape(.5f - WallTile::POST_WIDTH, 0, .5f - WallTile::POST_WIDTH, .5f + WallTile::POST_WIDTH, WallTile::POST_HEIGHT, .5f + WallTile::POST_WIDTH); - tesselateBlockInWorld(tt, x, y, z); + if ((!vertical && !horizontal) || !emptyAbove) { + // center post + setShape(.5f - WallTile::POST_WIDTH, 0, .5f - WallTile::POST_WIDTH, + .5f + WallTile::POST_WIDTH, WallTile::POST_HEIGHT, + .5f + WallTile::POST_WIDTH); + tesselateBlockInWorld(tt, x, y, z); - if (w) - { - setShape(0, 0, .5f - WallTile::WALL_WIDTH, .5f - WallTile::POST_WIDTH, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } - if (e) - { - setShape(.5f + WallTile::POST_WIDTH, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } - if (n) - { - setShape(.5f - WallTile::WALL_WIDTH, 0, 0, .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, .5f - WallTile::POST_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } - if (s) - { - setShape(.5f - WallTile::WALL_WIDTH, 0, .5f + WallTile::POST_WIDTH, .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, 1); - tesselateBlockInWorld(tt, x, y, z); - } - } - else if (vertical) - { - // north-south wall - setShape(.5f - WallTile::WALL_WIDTH, 0, 0, .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, 1); - tesselateBlockInWorld(tt, x, y, z); - } - else - { - // west-east wall - setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - tesselateBlockInWorld(tt, x, y, z); - } + if (w) { + setShape(0, 0, .5f - WallTile::WALL_WIDTH, + .5f - WallTile::POST_WIDTH, WallTile::WALL_HEIGHT, + .5f + WallTile::WALL_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } + if (e) { + setShape(.5f + WallTile::POST_WIDTH, 0, .5f - WallTile::WALL_WIDTH, + 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } + if (n) { + setShape(.5f - WallTile::WALL_WIDTH, 0, 0, + .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, + .5f - WallTile::POST_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } + if (s) { + setShape(.5f - WallTile::WALL_WIDTH, 0, .5f + WallTile::POST_WIDTH, + .5f + WallTile::WALL_WIDTH, WallTile::WALL_HEIGHT, 1); + tesselateBlockInWorld(tt, x, y, z); + } + } else if (vertical) { + // north-south wall + setShape(.5f - WallTile::WALL_WIDTH, 0, 0, .5f + WallTile::WALL_WIDTH, + WallTile::WALL_HEIGHT, 1); + tesselateBlockInWorld(tt, x, y, z); + } else { + // west-east wall + setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, + .5f + WallTile::WALL_WIDTH); + tesselateBlockInWorld(tt, x, y, z); + } - tt->updateShape(level, x, y, z); - return true; + tt->updateShape(level, x, y, z); + return true; } -bool TileRenderer::tesselateEggInWorld(EggTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateEggInWorld(EggTile* tt, int x, int y, int z) { bool changed = false; int y0 = 0; - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { int ww = 0; int hh = 1; if (i == 0) ww = 2; if (i == 1) ww = 3; if (i == 2) ww = 4; - if (i == 3) - { + if (i == 3) { ww = 5; hh = 2; } - if (i == 4) - { + if (i == 4) { ww = 6; hh = 3; } - if (i == 5) - { + if (i == 5) { ww = 7; hh = 5; } - if (i == 6) - { + if (i == 6) { ww = 6; hh = 2; } @@ -5988,8 +5940,8 @@ bool TileRenderer::tesselateEggInWorld(EggTile *tt, int x, int y, int z) return changed; } -bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, int z) -{ +bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile* tt, int x, int y, + int z) { bool changed = true; int data = level->getData(x, y, z); @@ -6003,23 +5955,25 @@ bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, in float h20 = 5 / 16.0f; float h21 = 16 / 16.0f; - if (((direction == Direction::NORTH || direction == Direction::SOUTH) && level->getTile(x - 1, y, z) == Tile::cobbleWall_Id && level->getTile(x + 1, y, z) == Tile::cobbleWall_Id) - || ((direction == Direction::EAST || direction == Direction::WEST) && level->getTile(x, y, z - 1) == Tile::cobbleWall_Id && level->getTile(x, y, z + 1) == Tile::cobbleWall_Id)) - { - h00 -= 3.0f / 16.0f; - h01 -= 3.0f / 16.0f; - h10 -= 3.0f / 16.0f; - h11 -= 3.0f / 16.0f; - h20 -= 3.0f / 16.0f; - h21 -= 3.0f / 16.0f; - } + if (((direction == Direction::NORTH || direction == Direction::SOUTH) && + level->getTile(x - 1, y, z) == Tile::cobbleWall_Id && + level->getTile(x + 1, y, z) == Tile::cobbleWall_Id) || + ((direction == Direction::EAST || direction == Direction::WEST) && + level->getTile(x, y, z - 1) == Tile::cobbleWall_Id && + level->getTile(x, y, z + 1) == Tile::cobbleWall_Id)) { + h00 -= 3.0f / 16.0f; + h01 -= 3.0f / 16.0f; + h10 -= 3.0f / 16.0f; + h11 -= 3.0f / 16.0f; + h20 -= 3.0f / 16.0f; + h21 -= 3.0f / 16.0f; + } - noCulling = true; + noCulling = true; // edge sticks - if (direction == Direction::EAST || direction == Direction::WEST) - { - upFlip = FLIP_CW; + if (direction == Direction::EAST || direction == Direction::WEST) { + upFlip = FLIP_CW; float x0 = 7 / 16.0f; float x1 = 9 / 16.0f; float z0 = 0 / 16.0f; @@ -6031,10 +5985,8 @@ bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, in z1 = 16 / 16.0f; setShape(x0, h20, z0, x1, h21, z1); tesselateBlockInWorld(tt, x, y, z); - upFlip = FLIP_NONE; - } - else - { + upFlip = FLIP_NONE; + } else { float x0 = 0 / 16.0f; float x1 = 2 / 16.0f; float z0 = 7 / 16.0f; @@ -6047,1127 +5999,1117 @@ bool TileRenderer::tesselateFenceGateInWorld(FenceGateTile *tt, int x, int y, in setShape(x0, h20, z0, x1, h21, z1); tesselateBlockInWorld(tt, x, y, z); } - if (isOpen) - { - if (direction == Direction::NORTH || direction == Direction::SOUTH) - { - upFlip = FLIP_CW; - } - if (direction == Direction::EAST) - { + if (isOpen) { + if (direction == Direction::NORTH || direction == Direction::SOUTH) { + upFlip = FLIP_CW; + } + if (direction == Direction::EAST) { + const float z00 = 0 / 16.0f; + const float z01 = 2 / 16.0f; + const float z10 = 14 / 16.0f; + const float z11 = 16 / 16.0f; - const float z00 = 0 / 16.0f; - const float z01 = 2 / 16.0f; - const float z10 = 14 / 16.0f; - const float z11 = 16 / 16.0f; + const float x0 = 9 / 16.0f; + const float x1 = 13 / 16.0f; + const float x2 = 15 / 16.0f; - const float x0 = 9 / 16.0f; - const float x1 = 13 / 16.0f; - const float x2 = 15 / 16.0f; + setShape(x1, h00, z00, x2, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h00, z10, x2, h11, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z00, x2, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z10, x2, h11, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h00, z00, x1, h01, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h00, z10, x1, h01, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z00, x1, h01, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z10, x1, h01, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z00, x1, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z10, x1, h11, z11); + tesselateBlockInWorld(tt, x, y, z); + } else if (direction == Direction::WEST) { + const float z00 = 0 / 16.0f; + const float z01 = 2 / 16.0f; + const float z10 = 14 / 16.0f; + const float z11 = 16 / 16.0f; - setShape(x0, h10, z00, x1, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z10, x1, h11, z11); - tesselateBlockInWorld(tt, x, y, z); - } - else if (direction == Direction::WEST) - { - const float z00 = 0 / 16.0f; - const float z01 = 2 / 16.0f; - const float z10 = 14 / 16.0f; - const float z11 = 16 / 16.0f; + const float x0 = 1 / 16.0f; + const float x1 = 3 / 16.0f; + const float x2 = 7 / 16.0f; - const float x0 = 1 / 16.0f; - const float x1 = 3 / 16.0f; - const float x2 = 7 / 16.0f; + setShape(x0, h00, z00, x1, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h00, z10, x1, h11, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z00, x1, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h00, z10, x1, h11, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h00, z00, x2, h01, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h00, z10, x2, h01, z11); + tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z00, x2, h01, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h00, z10, x2, h01, z11); - tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h10, z00, x2, h11, z01); + tesselateBlockInWorld(tt, x, y, z); + setShape(x1, h10, z10, x2, h11, z11); + tesselateBlockInWorld(tt, x, y, z); + } else if (direction == Direction::SOUTH) { + const float x00 = 0 / 16.0f; + const float x01 = 2 / 16.0f; + const float x10 = 14 / 16.0f; + const float x11 = 16 / 16.0f; - setShape(x1, h10, z00, x2, h11, z01); - tesselateBlockInWorld(tt, x, y, z); - setShape(x1, h10, z10, x2, h11, z11); - tesselateBlockInWorld(tt, x, y, z); - } - else if (direction == Direction::SOUTH) - { + const float z0 = 9 / 16.0f; + const float z1 = 13 / 16.0f; + const float z2 = 15 / 16.0f; - const float x00 = 0 / 16.0f; - const float x01 = 2 / 16.0f; - const float x10 = 14 / 16.0f; - const float x11 = 16 / 16.0f; + setShape(x00, h00, z1, x01, h11, z2); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z1, x11, h11, z2); + tesselateBlockInWorld(tt, x, y, z); - const float z0 = 9 / 16.0f; - const float z1 = 13 / 16.0f; - const float z2 = 15 / 16.0f; + setShape(x00, h00, z0, x01, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z0, x11, h01, z1); + tesselateBlockInWorld(tt, x, y, z); - setShape(x00, h00, z1, x01, h11, z2); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z1, x11, h11, z2); - tesselateBlockInWorld(tt, x, y, z); + setShape(x00, h10, z0, x01, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h10, z0, x11, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + } else if (direction == Direction::NORTH) { + const float x00 = 0 / 16.0f; + const float x01 = 2 / 16.0f; + const float x10 = 14 / 16.0f; + const float x11 = 16 / 16.0f; - setShape(x00, h00, z0, x01, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z0, x11, h01, z1); - tesselateBlockInWorld(tt, x, y, z); + const float z0 = 1 / 16.0f; + const float z1 = 3 / 16.0f; + const float z2 = 7 / 16.0f; - setShape(x00, h10, z0, x01, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h10, z0, x11, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - } - else if (direction == Direction::NORTH) - { - const float x00 = 0 / 16.0f; - const float x01 = 2 / 16.0f; - const float x10 = 14 / 16.0f; - const float x11 = 16 / 16.0f; + setShape(x00, h00, z0, x01, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z0, x11, h11, z1); + tesselateBlockInWorld(tt, x, y, z); - const float z0 = 1 / 16.0f; - const float z1 = 3 / 16.0f; - const float z2 = 7 / 16.0f; + setShape(x00, h00, z1, x01, h01, z2); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h00, z1, x11, h01, z2); + tesselateBlockInWorld(tt, x, y, z); - setShape(x00, h00, z0, x01, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z0, x11, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - - setShape(x00, h00, z1, x01, h01, z2); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h00, z1, x11, h01, z2); - tesselateBlockInWorld(tt, x, y, z); - - setShape(x00, h10, z1, x01, h11, z2); - tesselateBlockInWorld(tt, x, y, z); - setShape(x10, h10, z1, x11, h11, z2); - tesselateBlockInWorld(tt, x, y, z); - } - } - else - { - if (direction == Direction::EAST || direction == Direction::WEST) - { - upFlip = FLIP_CW; - float x0 = 7 / 16.0f; - float x1 = 9 / 16.0f; - float z0 = 6 / 16.0f; - float z1 = 8 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - z0 = 8 / 16.0f; - z1 = 10 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - z0 = 10 / 16.0f; - z1 = 14 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - z0 = 2 / 16.0f; - z1 = 6 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - } - else - { - float x0 = 6 / 16.0f; - float x1 = 8 / 16.0f; - float z0 = 7 / 16.0f; - float z1 = 9 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - x0 = 8 / 16.0f; - x1 = 10 / 16.0f; - setShape(x0, h00, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - x0 = 10 / 16.0f; - x1 = 14 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - x0 = 2 / 16.0f; - x1 = 6 / 16.0f; - setShape(x0, h00, z0, x1, h01, z1); - tesselateBlockInWorld(tt, x, y, z); - setShape(x0, h10, z0, x1, h11, z1); - tesselateBlockInWorld(tt, x, y, z); - - } - } - noCulling = false; - upFlip = FLIP_NONE; + setShape(x00, h10, z1, x01, h11, z2); + tesselateBlockInWorld(tt, x, y, z); + setShape(x10, h10, z1, x11, h11, z2); + tesselateBlockInWorld(tt, x, y, z); + } + } else { + if (direction == Direction::EAST || direction == Direction::WEST) { + upFlip = FLIP_CW; + float x0 = 7 / 16.0f; + float x1 = 9 / 16.0f; + float z0 = 6 / 16.0f; + float z1 = 8 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + z0 = 8 / 16.0f; + z1 = 10 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + z0 = 10 / 16.0f; + z1 = 14 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + z0 = 2 / 16.0f; + z1 = 6 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + } else { + float x0 = 6 / 16.0f; + float x1 = 8 / 16.0f; + float z0 = 7 / 16.0f; + float z1 = 9 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + x0 = 8 / 16.0f; + x1 = 10 / 16.0f; + setShape(x0, h00, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + x0 = 10 / 16.0f; + x1 = 14 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + x0 = 2 / 16.0f; + x1 = 6 / 16.0f; + setShape(x0, h00, z0, x1, h01, z1); + tesselateBlockInWorld(tt, x, y, z); + setShape(x0, h10, z0, x1, h11, z1); + tesselateBlockInWorld(tt, x, y, z); + } + } + noCulling = false; + upFlip = FLIP_NONE; setShape(0, 0, 0, 1, 1, 1); return changed; } -bool TileRenderer::tesselateStairsInWorld( StairTile* tt, int x, int y, int z ) -{ - tt->setBaseShape(level, x, y, z); - setShape(tt); - tesselateBlockInWorld(tt, x, y, z); +bool TileRenderer::tesselateStairsInWorld(StairTile* tt, int x, int y, int z) { + tt->setBaseShape(level, x, y, z); + setShape(tt); + tesselateBlockInWorld(tt, x, y, z); - bool checkInnerPiece = tt->setStepShape(level, x, y, z); - setShape(tt); - tesselateBlockInWorld(tt, x, y, z); + bool checkInnerPiece = tt->setStepShape(level, x, y, z); + setShape(tt); + tesselateBlockInWorld(tt, x, y, z); - if (checkInnerPiece) - { - if (tt->setInnerPieceShape(level, x, y, z)) - { - setShape(tt); - tesselateBlockInWorld(tt, x, y, z); - } - } - return true; + if (checkInnerPiece) { + if (tt->setInnerPieceShape(level, x, y, z)) { + setShape(tt); + tesselateBlockInWorld(tt, x, y, z); + } + } + return true; } -bool TileRenderer::tesselateDoorInWorld( Tile* tt, int x, int y, int z ) -{ - Tesselator* t = Tesselator::getInstance(); +bool TileRenderer::tesselateDoorInWorld(Tile* tt, int x, int y, int z) { + Tesselator* t = Tesselator::getInstance(); - // skip rendering if the other half of the door is missing, - // to avoid rendering doors that are about to be removed - int data = level->getData(x, y, z); - if ((data & DoorTile::UPPER_BIT) != 0) - { - if (level->getTile(x, y - 1, z) != tt->id) - { - return false; - } - } - else { - if (level->getTile(x, y + 1, z) != tt->id) - { - return false; - } - } + // skip rendering if the other half of the door is missing, + // to avoid rendering doors that are about to be removed + int data = level->getData(x, y, z); + if ((data & DoorTile::UPPER_BIT) != 0) { + if (level->getTile(x, y - 1, z) != tt->id) { + return false; + } + } else { + if (level->getTile(x, y + 1, z) != tt->id) { + return false; + } + } - bool changed = false; - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + bool changed = false; + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - int centerColor = 0; - float centerBrightness = 0.0f; + int centerColor = 0; + float centerBrightness = 0.0f; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - centerColor = getLightColor(tt, level, x, y, z ); - } - else - { - centerBrightness = tt->getBrightness( level, x, y, z ); - } + if (SharedConstants::TEXTURE_LIGHTING) { + centerColor = getLightColor(tt, level, x, y, z); + } else { + centerBrightness = tt->getBrightness(level, x, y, z); + } + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY0 > 0 ? centerColor + : getLightColor(tt, level, x, y - 1, z)); + t->color(c10, c10, c10); + } else { + float br = tt->getBrightness(level, x, y - 1, z); + if (tileShapeY0 > 0) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c10 * br, c10 * br, c10 * br); + } + renderFaceDown(tt, x, y, z, getTexture(tt, level, x, y, z, 0)); + changed = true; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY0 > 0 ? centerColor : getLightColor(tt, level, x, y - 1, z ) ); - t->color( c10, c10, c10 ); - } - else - { - float br = tt->getBrightness( level, x, y - 1, z ); - if ( tileShapeY0 > 0 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c10 * br, c10 * br, c10 * br ); - } - renderFaceDown( tt, x, y, z, getTexture(tt, level, x, y, z, 0 ) ); - changed = true; + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeY1 < 1 ? centerColor + : getLightColor(tt, level, x, y + 1, z)); + t->color(c11, c11, c11); + } else { + float br = tt->getBrightness(level, x, y + 1, z); + if (tileShapeY1 < 1) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c11 * br, c11 * br, c11 * br); + } + renderFaceUp(tt, x, y, z, getTexture(tt, level, x, y, z, 1)); + changed = true; - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeY1 < 1 ? centerColor : getLightColor(tt, level, x, y + 1, z ) ); - t->color( c11, c11, c11 ); - } - else - { - float br = tt->getBrightness( level, x, y + 1, z ); - if ( tileShapeY1 < 1 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c11 * br, c11 * br, c11 * br ); - } - renderFaceUp( tt, x, y, z, getTexture(tt, level, x, y, z, 1 ) ); - changed = true; - - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ0 > 0 ? centerColor : getLightColor(tt, level, x, y, z - 1 ) ); - t->color( c2, c2, c2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z - 1 ); - if ( tileShapeZ0 > 0 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c2 * br, c2 * br, c2 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 2 ); - renderNorth( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeZ1 < 1 ? centerColor : getLightColor(tt, level, x, y, z + 1 ) ); - t->color( c2, c2, c2 ); - } - else - { - float br = tt->getBrightness( level, x, y, z + 1 ); - if ( tileShapeZ1 < 1 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c2 * br, c2 * br, c2 * br ); - } - Icon *tex = getTexture( tt, level, x, y, z, 3 ); - renderSouth( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX0 > 0 ? centerColor : getLightColor(tt, level, x - 1, y, z ) ); - t->color( c3, c3, c3 ); - } - else - { - float br = tt->getBrightness( level, x - 1, y, z ); - if ( tileShapeX0 > 0 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c3 * br, c3 * br, c3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 4 ); - renderWest( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - { - if ( SharedConstants::TEXTURE_LIGHTING ) - { - t->tex2( tileShapeX1 < 1 ? centerColor : getLightColor(tt, level, x + 1, y, z ) ); - t->color( c3, c3, c3 ); - } - else - { - float br = tt->getBrightness( level, x + 1, y, z ); - if ( tileShapeX1 < 1 ) br = centerBrightness; - if ( Tile::lightEmission[tt->id] > 0 ) br = 1.0f; - t->color( c3 * br, c3 * br, c3 * br ); - } - Icon *tex = getTexture(tt, level, x, y, z, 5 ); - renderEast( tt, x, y, z, tex ); - changed = true; - xFlipTexture = false; - } - return changed; + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ0 > 0 ? centerColor + : getLightColor(tt, level, x, y, z - 1)); + t->color(c2, c2, c2); + } else { + float br = tt->getBrightness(level, x, y, z - 1); + if (tileShapeZ0 > 0) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c2 * br, c2 * br, c2 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 2); + renderNorth(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeZ1 < 1 ? centerColor + : getLightColor(tt, level, x, y, z + 1)); + t->color(c2, c2, c2); + } else { + float br = tt->getBrightness(level, x, y, z + 1); + if (tileShapeZ1 < 1) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c2 * br, c2 * br, c2 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 3); + renderSouth(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX0 > 0 ? centerColor + : getLightColor(tt, level, x - 1, y, z)); + t->color(c3, c3, c3); + } else { + float br = tt->getBrightness(level, x - 1, y, z); + if (tileShapeX0 > 0) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c3 * br, c3 * br, c3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 4); + renderWest(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + { + if (SharedConstants::TEXTURE_LIGHTING) { + t->tex2(tileShapeX1 < 1 ? centerColor + : getLightColor(tt, level, x + 1, y, z)); + t->color(c3, c3, c3); + } else { + float br = tt->getBrightness(level, x + 1, y, z); + if (tileShapeX1 < 1) br = centerBrightness; + if (Tile::lightEmission[tt->id] > 0) br = 1.0f; + t->color(c3 * br, c3 * br, c3 * br); + } + Icon* tex = getTexture(tt, level, x, y, z, 5); + renderEast(tt, x, y, z, tex); + changed = true; + xFlipTexture = false; + } + return changed; } -void TileRenderer::renderFaceDown( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderFaceDown(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - float u00 = tex->getU(tileShapeX0 * 16.0f, true); - float u11 = tex->getU(tileShapeX1 * 16.0f, true); - float v00 = tex->getV(tileShapeZ0 * 16.0f, true); - float v11 = tex->getV(tileShapeZ1 * 16.0f, true); + if (hasFixedTexture()) tex = fixedTexture; + float u00 = tex->getU(tileShapeX0 * 16.0f, true); + float u11 = tex->getU(tileShapeX1 * 16.0f, true); + float v00 = tex->getV(tileShapeZ0 * 16.0f, true); + float v11 = tex->getV(tileShapeZ1 * 16.0f, true); - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( downFlip == FLIP_CCW ) - { - u00 = tex->getU(tileShapeZ0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - u11 = tex->getU(tileShapeZ1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + if (downFlip == FLIP_CCW) { + u00 = tex->getU(tileShapeZ0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + u11 = tex->getU(tileShapeZ1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( downFlip == FLIP_CW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(tileShapeX1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (downFlip == FLIP_CW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeX0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(tileShapeX1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( downFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (downFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c1r, c1g, c1b, tc1, - ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c3r, c3g, c3b, tc3, - ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10), c1r, c1g, c1b, tc1, (float)(x0), + (float)(y0), (float)(z0), (float)(u00), (float)(v00), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y0), + (float)(z0), (float)(u01), (float)(v01), c3r, c3g, c3b, + tc3, (float)(x1), (float)(y0), (float)(z1), + (float)(u11), (float)(v11), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } else { + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } } -void TileRenderer::renderFaceUp( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderFaceUp(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - float u00 = tex->getU(tileShapeX0 * 16.0f, true); - float u11 = tex->getU(tileShapeX1 * 16.0f, true); - float v00 = tex->getV(tileShapeZ0 * 16.0f, true); - float v11 = tex->getV(tileShapeZ1 * 16.0f, true); + if (hasFixedTexture()) tex = fixedTexture; + float u00 = tex->getU(tileShapeX0 * 16.0f, true); + float u11 = tex->getU(tileShapeX1 * 16.0f, true); + float v00 = tex->getV(tileShapeZ0 * 16.0f, true); + float v11 = tex->getV(tileShapeZ1 * 16.0f, true); - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - float u01 = u11, u10 = u00, v01 = v00, v10 = v11; + float u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( upFlip == FLIP_CW ) - { - u00 = tex->getU(tileShapeZ0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - u11 = tex->getU(tileShapeZ1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); + if (upFlip == FLIP_CW) { + u00 = tex->getU(tileShapeZ0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + u11 = tex->getU(tileShapeZ1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( upFlip == FLIP_CCW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(tileShapeX1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (upFlip == FLIP_CCW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeX0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(tileShapeX1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( upFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (upFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; - - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c1r, c1g, c1b, tc1, - ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c2r, c2g, c2b, tc2, - ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c3r, c3g, c3b, tc3, - ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x1), (float)(y1), (float)(z1), (float)(u11), + (float)(v11), c1r, c1g, c1b, tc1, (float)(x1), + (float)(y1), (float)(z0), (float)(u01), (float)(v01), + c2r, c2g, c2b, tc2, (float)(x0), (float)(y1), + (float)(z0), (float)(u00), (float)(v00), c3r, c3g, c3b, + tc3, (float)(x0), (float)(y1), (float)(z1), + (float)(u10), (float)(v10), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - } - else - { - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u11), + (float)(v11)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u10), + (float)(v10)); + } else { + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u11), + (float)(v11)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u10), + (float)(v10)); + } } -void TileRenderer::renderNorth( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderNorth(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeX0 * 16.0f, true); - double u11 = tex->getU(tileShapeX1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeX0 * 16.0f, true); + double u11 = tex->getU(tileShapeX1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( northFlip == FLIP_CCW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); + if (northFlip == FLIP_CCW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( northFlip == FLIP_CW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeX1 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeX0 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (northFlip == FLIP_CW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeX1 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeX0 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( northFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (northFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c1r, c1g, c1b, tc1, - ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ), c3r, c3g, c3b, tc3, - ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y1), (float)(z0), (float)(u01), + (float)(v01), c1r, c1g, c1b, tc1, (float)(x1), + (float)(y1), (float)(z0), (float)(u00), (float)(v00), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y0), + (float)(z0), (float)(u10), (float)(v10), c3r, c3g, c3b, + tc3, (float)(x0), (float)(y0), (float)(z0), + (float)(u11), (float)(v11), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + } else { + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + } } -void TileRenderer::renderSouth( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderSouth(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeX0 * 16.0f, true); - double u11 = tex->getU(tileShapeX1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeX0 * 16.0f, true); + double u11 = tex->getU(tileShapeX1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeX0 < 0 || tileShapeX1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeX0 < 0 || tileShapeX1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( southFlip == FLIP_CW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); + if (southFlip == FLIP_CW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( southFlip == FLIP_CCW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeX1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (southFlip == FLIP_CCW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeX0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeX1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( southFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (southFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeX1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } + double x0 = x + tileShapeX0; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z1 = z + tileShapeZ1; - double x0 = x + tileShapeX0; - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z1 = z + tileShapeZ1; - - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ), c1r, c1g, c1b, tc1, - ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c3r, c3g, c3b, tc3, - ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y1), (float)(z1), (float)(u00), + (float)(v00), c1r, c1g, c1b, tc1, (float)(x0), + (float)(y0), (float)(z1), (float)(u10), (float)(v10), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y0), + (float)(z1), (float)(u11), (float)(v11), c3r, c3g, c3b, + tc3, (float)(x1), (float)(y1), (float)(z1), + (float)(u01), (float)(v01), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + } else { + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + } } -void TileRenderer::renderWest( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderWest(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeZ0 * 16.0f, true); - double u11 = tex->getU(tileShapeZ1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeZ0 * 16.0f, true); + double u11 = tex->getU(tileShapeZ1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( westFlip == FLIP_CW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); + if (westFlip == FLIP_CW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( westFlip == FLIP_CCW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeZ0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeZ1 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (westFlip == FLIP_CCW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeZ0 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeZ1 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( westFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (westFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } - double x0 = x + tileShapeX0; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; + double x0 = x + tileShapeX0; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ), c1r, c1g, c1b, tc1, - ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ), c2r, c2g, c2b, tc2, - ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ), c3r, c3g, c3b, tc3, - ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x0), (float)(y1), (float)(z1), (float)(u01), + (float)(v01), c1r, c1g, c1b, tc1, (float)(x0), + (float)(y1), (float)(z0), (float)(u00), (float)(v00), + c2r, c2g, c2b, tc2, (float)(x0), (float)(y0), + (float)(z0), (float)(u10), (float)(v10), c3r, c3g, c3b, + tc3, (float)(x0), (float)(y0), (float)(z1), + (float)(u11), (float)(v11), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } - else - { - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z1 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y1 ), ( float )( z0 ), ( float )( u00 ), ( float )( v00 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z0 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x0 ), ( float )( y0 ), ( float )( z1 ), ( float )( u11 ), ( float )( v11 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } else { + t->vertexUV((float)(x0), (float)(y1), (float)(z1), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x0), (float)(y1), (float)(z0), (float)(u00), + (float)(v00)); + t->vertexUV((float)(x0), (float)(y0), (float)(z0), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x0), (float)(y0), (float)(z1), (float)(u11), + (float)(v11)); + } } -void TileRenderer::renderEast( Tile* tt, double x, double y, double z, Icon *tex ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderEast(Tile* tt, double x, double y, double z, + Icon* tex) { + Tesselator* t = Tesselator::getInstance(); - if (hasFixedTexture()) tex = fixedTexture; - double u00 = tex->getU(tileShapeZ0 * 16.0f, true); - double u11 = tex->getU(tileShapeZ1 * 16.0f, true); - double v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - double v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - if ( xFlipTexture ) - { - double tmp = u00; - u00 = u11; - u11 = tmp; - } + if (hasFixedTexture()) tex = fixedTexture; + double u00 = tex->getU(tileShapeZ0 * 16.0f, true); + double u11 = tex->getU(tileShapeZ1 * 16.0f, true); + double v00 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); + double v11 = tex->getV( + SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); + if (xFlipTexture) { + double tmp = u00; + u00 = u11; + u11 = tmp; + } - if ( tileShapeZ0 < 0 || tileShapeZ1 > 1 ) - { - u00 = tex->getU0(true); - u11 = tex->getU1(true); - } - if ( tileShapeY0 < 0 || tileShapeY1 > 1 ) - { - v00 = tex->getV0(true); - v11 = tex->getV1(true); - } + if (tileShapeZ0 < 0 || tileShapeZ1 > 1) { + u00 = tex->getU0(true); + u11 = tex->getU1(true); + } + if (tileShapeY0 < 0 || tileShapeY1 > 1) { + v00 = tex->getV0(true); + v11 = tex->getV1(true); + } - double u01 = u11, u10 = u00, v01 = v00, v10 = v11; + double u01 = u11, u10 = u00, v01 = v00, v10 = v11; - if ( eastFlip == FLIP_CCW ) - { - u00 = tex->getU(tileShapeY0 * 16.0f, true); - v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - u11 = tex->getU(tileShapeY1 * 16.0f, true); - v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); + if (eastFlip == FLIP_CCW) { + u00 = tex->getU(tileShapeY0 * 16.0f, true); + v00 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + u11 = tex->getU(tileShapeY1 * 16.0f, true); + v11 = tex->getV(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u01 = u00; - u10 = u11; - v00 = v11; - v11 = v01; - } - else if ( eastFlip == FLIP_CW ) - { - // reshape - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, true); - v00 = tex->getV(tileShapeZ1 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, true); - v11 = tex->getV(tileShapeZ0 * 16.0f, true); + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u01 = u00; + u10 = u11; + v00 = v11; + v11 = v01; + } else if (eastFlip == FLIP_CW) { + // reshape + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY1 * 16.0f, + true); + v00 = tex->getV(tileShapeZ1 * 16.0f, true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeY0 * 16.0f, + true); + v11 = tex->getV(tileShapeZ0 * 16.0f, true); - // rotate - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - u00 = u01; - u11 = u10; - v01 = v11; - v10 = v00; - } - else if ( eastFlip == FLIP_180 ) - { - u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, true); - u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, true); - v00 = tex->getV(tileShapeY1 * 16.0f, true); - v11 = tex->getV(tileShapeY0 * 16.0f, true); + // rotate + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + u00 = u01; + u11 = u10; + v01 = v11; + v10 = v00; + } else if (eastFlip == FLIP_180) { + u00 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ0 * 16.0f, + true); + u11 = tex->getU(SharedConstants::WORLD_RESOLUTION - tileShapeZ1 * 16.0f, + true); + v00 = tex->getV(tileShapeY1 * 16.0f, true); + v11 = tex->getV(tileShapeY0 * 16.0f, true); - u01 = u11; - u10 = u00; - v01 = v00; - v10 = v11; - } + u01 = u11; + u10 = u00; + v01 = v00; + v10 = v11; + } - double x1 = x + tileShapeX1; - double y0 = y + tileShapeY0; - double y1 = y + tileShapeY1; - double z0 = z + tileShapeZ0; - double z1 = z + tileShapeZ1; + double x1 = x + tileShapeX1; + double y0 = y + tileShapeY0; + double y1 = y + tileShapeY1; + double z0 = z + tileShapeZ0; + double z1 = z + tileShapeZ1; - if ( applyAmbienceOcclusion ) - { + if (applyAmbienceOcclusion) { #ifdef __PSVITA__ - if( t->getCompactVertices() ) - { - t->tileQuad(( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ), c1r, c1g, c1b, tc1, - ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ), c2r, c2g, c2b, tc2, - ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ), c3r, c3g, c3b, tc3, - ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ), c4r, c4g, c4b, tc4); - return; - } + if (t->getCompactVertices()) { + t->tileQuad((float)(x1), (float)(y0), (float)(z1), (float)(u10), + (float)(v10), c1r, c1g, c1b, tc1, (float)(x1), + (float)(y0), (float)(z0), (float)(u11), (float)(v11), + c2r, c2g, c2b, tc2, (float)(x1), (float)(y1), + (float)(z0), (float)(u01), (float)(v01), c3r, c3g, c3b, + tc3, (float)(x1), (float)(y1), (float)(z1), + (float)(u00), (float)(v00), c4r, c4g, c4b, tc4); + return; + } #endif - t->color( c1r, c1g, c1b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc1 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->color( c2r, c2g, c2b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc2 ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - t->color( c3r, c3g, c3b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc3 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->color( c4r, c4g, c4b ); - if ( SharedConstants::TEXTURE_LIGHTING ) t->tex2( tc4 ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - } - else - { - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z1 ), ( float )( u10 ), ( float )( v10 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y0 ), ( float )( z0 ), ( float )( u11 ), ( float )( v11 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z0 ), ( float )( u01 ), ( float )( v01 ) ); - t->vertexUV( ( float )( x1 ), ( float )( y1 ), ( float )( z1 ), ( float )( u00 ), ( float )( v00 ) ); - } - + t->color(c1r, c1g, c1b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc1); + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->color(c2r, c2g, c2b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc2); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + t->color(c3r, c3g, c3b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc3); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->color(c4r, c4g, c4b); + if (SharedConstants::TEXTURE_LIGHTING) t->tex2(tc4); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + } else { + t->vertexUV((float)(x1), (float)(y0), (float)(z1), (float)(u10), + (float)(v10)); + t->vertexUV((float)(x1), (float)(y0), (float)(z0), (float)(u11), + (float)(v11)); + t->vertexUV((float)(x1), (float)(y1), (float)(z0), (float)(u01), + (float)(v01)); + t->vertexUV((float)(x1), (float)(y1), (float)(z1), (float)(u00), + (float)(v00)); + } } -void TileRenderer::renderCube( Tile* tile, float alpha ) -{ - int shape = tile->getRenderShape(); - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderCube(Tile* tile, float alpha) { + int shape = tile->getRenderShape(); + Tesselator* t = Tesselator::getInstance(); - if ( shape == Tile::SHAPE_BLOCK ) - { - tile->updateDefaultShape(); - glTranslatef( -0.5f, -0.5f, -0.5f ); - float c10 = 0.5f; - float c11 = 1; - float c2 = 0.8f; - float c3 = 0.6f; + if (shape == Tile::SHAPE_BLOCK) { + tile->updateDefaultShape(); + glTranslatef(-0.5f, -0.5f, -0.5f); + float c10 = 0.5f; + float c11 = 1; + float c2 = 0.8f; + float c3 = 0.6f; - t->begin(); - t->color( c11, c11, c11, alpha ); - renderFaceDown( tile, 0, 0, 0,getTexture(tile, 0 ) ); - t->color( c10, c10, c10, alpha ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->color( c2, c2, c2, alpha ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->color( c3, c3, c3, alpha ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); + t->begin(); + t->color(c11, c11, c11, alpha); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->color(c10, c10, c10, alpha); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->color(c2, c2, c2, alpha); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->color(c3, c3, c3, alpha); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); - t->end(); - - glTranslatef( 0.5f, 0.5f, 0.5f ); - } + t->end(); + glTranslatef(0.5f, 0.5f, 0.5f); + } } -void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAlpha, bool useCompiled ) -{ - Tesselator* t = Tesselator::getInstance(); +void TileRenderer::renderTile(Tile* tile, int data, float brightness, + float fAlpha, bool useCompiled) { + Tesselator* t = Tesselator::getInstance(); - bool isGrass = tile->id == Tile::grass_Id; + bool isGrass = tile->id == Tile::grass_Id; - if (tile == Tile::dispenser || tile == Tile::furnace) // || tile == Tile.dropper - { - data = 3; - } + if (tile == Tile::dispenser || + tile == Tile::furnace) // || tile == Tile.dropper + { + data = 3; + } - if ( setColor ) - { - int col = tile->getColor( data ); - if (isGrass) - { + if (setColor) { + int col = tile->getColor(data); + if (isGrass) { col = 0xffffff; } - float red = ( ( col >> 16 ) & 0xff ) / 255.0f; - float g = ( ( col >> 8 ) & 0xff ) / 255.0f; - float b = ( ( col )& 0xff ) / 255.0f; + float red = ((col >> 16) & 0xff) / 255.0f; + float g = ((col >> 8) & 0xff) / 255.0f; + float b = ((col) & 0xff) / 255.0f; - glColor4f( red * brightness, g * brightness, b * brightness, fAlpha ); - } + glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); + } - int shape = tile->getRenderShape(); - setShape(tile); + int shape = tile->getRenderShape(); + setShape(tile); - t->setMipmapEnable( Tile::mipmapEnable[tile->id] ); // 4J added + t->setMipmapEnable(Tile::mipmapEnable[tile->id]); // 4J added - if ( shape == Tile::SHAPE_BLOCK || shape == Tile::SHAPE_TREE || shape == Tile::SHAPE_QUARTZ || shape == Tile::SHAPE_PISTON_BASE || shape == Tile::SHAPE_PORTAL_FRAME ) - { - if ( shape == Tile::SHAPE_PISTON_BASE ) - { - data = Facing::UP; - } + if (shape == Tile::SHAPE_BLOCK || shape == Tile::SHAPE_TREE || + shape == Tile::SHAPE_QUARTZ || shape == Tile::SHAPE_PISTON_BASE || + shape == Tile::SHAPE_PORTAL_FRAME) { + if (shape == Tile::SHAPE_PISTON_BASE) { + data = Facing::UP; + } - tile->updateDefaultShape(); - setShape(tile); - glRotatef(90, 0, 1, 0); + tile->updateDefaultShape(); + setShape(tile); + glRotatef(90, 0, 1, 0); - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0, data ) ); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7176,23 +7118,21 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); } - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1, data ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2, data ) ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7200,21 +7140,20 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3, data ) ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7222,21 +7161,20 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4, data ) ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; @@ -7244,196 +7182,172 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5, data ) ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5, data)); + t->end(); - if (isGrass && setColor) - { + if (isGrass && setColor) { int col = tile->getColor(data); float red = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; - glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); + glColor4f(red * brightness, g * brightness, b * brightness, fAlpha); - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, GrassTile::getSideTextureOverlay() ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, GrassTile::getSideTextureOverlay()); + t->end(); glColor4f(brightness, brightness, brightness, fAlpha); } - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - else if ( shape == Tile::SHAPE_CROSS_TEXTURE ) - { - t->begin(); - t->normal( 0, -1, 0 ); - tesselateCrossTexture( tile, data, -0.5f, -0.5f, -0.5f, 1 ); - t->end(); - } - else if (shape == Tile::SHAPE_STEM) - { - t->begin(); - t->normal(0, -1, 0); - tile->updateDefaultShape(); - tesselateStemTexture(tile, data, tileShapeY1, -0.5f, -0.5f, -0.5f); - t->end(); - } - else if (shape == Tile::SHAPE_LILYPAD) - { + glTranslatef(0.5f, 0.5f, 0.5f); + } else if (shape == Tile::SHAPE_CROSS_TEXTURE) { + t->begin(); + t->normal(0, -1, 0); + tesselateCrossTexture(tile, data, -0.5f, -0.5f, -0.5f, 1); + t->end(); + } else if (shape == Tile::SHAPE_STEM) { + t->begin(); + t->normal(0, -1, 0); + tile->updateDefaultShape(); + tesselateStemTexture(tile, data, tileShapeY1, -0.5f, -0.5f, -0.5f); + t->end(); + } else if (shape == Tile::SHAPE_LILYPAD) { t->begin(); t->normal(0, -1, 0); tile->updateDefaultShape(); t->end(); - } - else if ( shape == Tile::SHAPE_CACTUS ) - { - tile->updateDefaultShape(); - glTranslatef( -0.5f, -0.5f, -0.5f ); - float s = 1 / 16.0f; - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0 ) ); - t->end(); + } else if (shape == Tile::SHAPE_CACTUS) { + tile->updateDefaultShape(); + glTranslatef(-0.5f, -0.5f, -0.5f); + float s = 1 / 16.0f; + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->end(); - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->end(); - t->begin(); - t->normal( 0, 0, -1 ); - t->addOffset( 0, 0, s ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - t->addOffset( 0, 0, -s ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + t->addOffset(0, 0, s); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + t->addOffset(0, 0, -s); + t->end(); - t->begin(); - t->normal( 0, 0, 1 ); - t->addOffset( 0, 0, -s ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->addOffset( 0, 0, s ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + t->addOffset(0, 0, -s); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->addOffset(0, 0, s); + t->end(); - t->begin(); - t->normal( -1, 0, 0 ); - t->addOffset( s, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - t->addOffset( -s, 0, 0 ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + t->addOffset(s, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + t->addOffset(-s, 0, 0); + t->end(); - t->begin(); - t->normal( 1, 0, 0 ); - t->addOffset( -s, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); - t->addOffset( s, 0, 0 ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + t->addOffset(-s, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); + t->addOffset(s, 0, 0); + t->end(); - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - else if (shape == Tile::SHAPE_ENTITYTILE_ANIMATED) - { - glRotatef(90, 0, 1, 0); - glTranslatef(-0.5f, -0.5f, -0.5f); - EntityTileRenderer::instance->render(tile, data, brightness, fAlpha, setColor, useCompiled); - glEnable(GL_RESCALE_NORMAL); - } - else if ( shape == Tile::SHAPE_ROWS ) - { - t->begin(); - t->normal( 0, -1, 0 ); - tesselateRowTexture( tile, data, -0.5f, -0.5f, -0.5f ); - t->end(); - } - else if ( shape == Tile::SHAPE_TORCH ) - { - t->begin(); - t->normal( 0, -1, 0 ); - tesselateTorch( tile, -0.5f, -0.5f, -0.5f, 0, 0, 0 ); - t->end(); - } - else if ( shape == Tile::SHAPE_STAIRS ) - { - for ( int i = 0; i < 2; i++ ) - { - if ( i == 0 ) setShape( 0, 0, 0, 1, 1, 0.5f ); - if ( i == 1 ) setShape( 0, 0, 0.5f, 1, 0.5f, 1 ); + glTranslatef(0.5f, 0.5f, 0.5f); + } else if (shape == Tile::SHAPE_ENTITYTILE_ANIMATED) { + glRotatef(90, 0, 1, 0); + glTranslatef(-0.5f, -0.5f, -0.5f); + EntityTileRenderer::instance->render(tile, data, brightness, fAlpha, + setColor, useCompiled); + glEnable(GL_RESCALE_NORMAL); + } else if (shape == Tile::SHAPE_ROWS) { + t->begin(); + t->normal(0, -1, 0); + tesselateRowTexture(tile, data, -0.5f, -0.5f, -0.5f); + t->end(); + } else if (shape == Tile::SHAPE_TORCH) { + t->begin(); + t->normal(0, -1, 0); + tesselateTorch(tile, -0.5f, -0.5f, -0.5f, 0, 0, 0); + t->end(); + } else if (shape == Tile::SHAPE_STAIRS) { + for (int i = 0; i < 2; i++) { + if (i == 0) setShape(0, 0, 0, 1, 1, 0.5f); + if (i == 1) setShape(0, 0, 0.5f, 1, 0.5f, 1); - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0 ) ); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->end(); - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->end(); - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + t->end(); - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->end(); - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + t->end(); - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); + t->end(); - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - } - else if (shape == Tile::SHAPE_EGG) - { + glTranslatef(0.5f, 0.5f, 0.5f); + } + } else if (shape == Tile::SHAPE_EGG) { int y0 = 0; glTranslatef(-0.5f, -0.5f, -0.5f); t->begin(); - for (int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { int ww = 0; int hh = 1; if (i == 0) ww = 2; if (i == 1) ww = 3; if (i == 2) ww = 4; - if (i == 3) - { + if (i == 3) { ww = 5; hh = 2; } - if (i == 4) - { + if (i == 4) { ww = 6; hh = 3; } - if (i == 5) - { + if (i == 5) { ww = 7; hh = 5; } - if (i == 6) - { + if (i == 6) { ww = 6; hh = 2; } @@ -7444,73 +7358,72 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl y0 += hh; setShape(0.5f - w, yy0, 0.5f - w, 0.5f + w, yy1, 0.5f + w); t->normal(0, -1, 0); - renderFaceDown(tile, 0, 0, 0, getTexture(tile,0)); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); t->normal(0, 1, 0); - renderFaceUp(tile, 0, 0, 0, getTexture(tile,1)); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); t->normal(0, 0, -1); - renderNorth(tile, 0, 0, 0, getTexture(tile,2)); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); t->normal(0, 0, 1); - renderSouth(tile, 0, 0, 0, getTexture(tile,3)); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); t->normal(-1, 0, 0); - renderWest(tile, 0, 0, 0, getTexture(tile,4)); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); t->normal(1, 0, 0); - renderEast(tile, 0, 0, 0, getTexture(tile,5)); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); } t->end(); glTranslatef(0.5f, 0.5f, 0.5f); setShape(0, 0, 0, 1, 1, 1); - } - - else if ( shape == Tile::SHAPE_FENCE ) - { - for ( int i = 0; i < 4; i++ ) - { - float w = 2 / 16.0f; - if ( i == 0 ) setShape( 0.5f - w, 0, 0, 0.5f + w, 1, w * 2 ); - if ( i == 1 ) setShape( 0.5f - w, 0, 1 - w * 2, 0.5f + w, 1, 1 ); - w = 1 / 16.0f; - if ( i == 2 ) setShape( 0.5f - w, 1 - w * 3, -w * 2, 0.5f + w, 1 - w, 1 + w * 2 ); - if ( i == 3 ) setShape( 0.5f - w, 0.5f - w * 3, -w * 2, 0.5f + w, 0.5f - w, 1 + w * 2 ); - - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0 ) ); - t->end(); - - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1 ) ); - t->end(); - - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2 ) ); - t->end(); - - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3 ) ); - t->end(); - - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4 ) ); - t->end(); - - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5 ) ); - t->end(); - - glTranslatef( 0.5f, 0.5f, 0.5f ); - } - setShape( 0, 0, 0, 1, 1, 1 ); } - else if (shape == Tile::SHAPE_FENCE_GATE) - { - for (int i = 0; i < 3; i++) - { + + else if (shape == Tile::SHAPE_FENCE) { + for (int i = 0; i < 4; i++) { + float w = 2 / 16.0f; + if (i == 0) setShape(0.5f - w, 0, 0, 0.5f + w, 1, w * 2); + if (i == 1) setShape(0.5f - w, 0, 1 - w * 2, 0.5f + w, 1, 1); + w = 1 / 16.0f; + if (i == 2) + setShape(0.5f - w, 1 - w * 3, -w * 2, 0.5f + w, 1 - w, + 1 + w * 2); + if (i == 3) + setShape(0.5f - w, 0.5f - w * 3, -w * 2, 0.5f + w, 0.5f - w, + 1 + w * 2); + + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); + t->end(); + + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); + t->end(); + + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); + t->end(); + + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); + t->end(); + + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); + t->end(); + + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); + t->end(); + + glTranslatef(0.5f, 0.5f, 0.5f); + } + setShape(0, 0, 0, 1, 1, 1); + } else if (shape == Tile::SHAPE_FENCE_GATE) { + for (int i = 0; i < 3; i++) { float w = 1 / 16.0f; if (i == 0) setShape(0.5f - w, .3f, 0, 0.5f + w, 1, w * 2); if (i == 1) setShape(0.5f - w, .3f, 1 - w * 2, 0.5f + w, 1, 1); @@ -7520,176 +7433,170 @@ void TileRenderer::renderTile( Tile* tile, int data, float brightness, float fAl glTranslatef(-0.5f, -0.5f, -0.5f); t->begin(); t->normal(0, -1, 0); - renderFaceDown(tile, 0, 0, 0, getTexture(tile,0)); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0)); t->end(); t->begin(); t->normal(0, 1, 0); - renderFaceUp(tile, 0, 0, 0, getTexture(tile,1)); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1)); t->end(); t->begin(); t->normal(0, 0, -1); - renderNorth(tile, 0, 0, 0, getTexture(tile,2)); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2)); t->end(); t->begin(); t->normal(0, 0, 1); - renderSouth(tile, 0, 0, 0, getTexture(tile,3)); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3)); t->end(); t->begin(); t->normal(-1, 0, 0); - renderWest(tile, 0, 0, 0, getTexture(tile,4)); + renderWest(tile, 0, 0, 0, getTexture(tile, 4)); t->end(); t->begin(); t->normal(1, 0, 0); - renderEast(tile, 0, 0, 0, getTexture(tile,5)); + renderEast(tile, 0, 0, 0, getTexture(tile, 5)); t->end(); glTranslatef(0.5f, 0.5f, 0.5f); } - } - else if (shape == Tile::SHAPE_WALL) - { - for (int i = 0; i < 2; i++) - { - if (i == 0) setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); - if (i == 1) setShape(.5f - WallTile::POST_WIDTH, 0, .5f - WallTile::POST_WIDTH, .5f + WallTile::POST_WIDTH, WallTile::POST_HEIGHT, .5f + WallTile::POST_WIDTH); + } else if (shape == Tile::SHAPE_WALL) { + for (int i = 0; i < 2; i++) { + if (i == 0) + setShape(0, 0, .5f - WallTile::WALL_WIDTH, 1, + WallTile::WALL_HEIGHT, .5f + WallTile::WALL_WIDTH); + if (i == 1) + setShape(.5f - WallTile::POST_WIDTH, 0, + .5f - WallTile::POST_WIDTH, .5f + WallTile::POST_WIDTH, + WallTile::POST_HEIGHT, .5f + WallTile::POST_WIDTH); - glTranslatef(-0.5f, -0.5f, -0.5f); - t->begin(); - t->normal(0, -1, 0); - renderFaceDown(tile, 0, 0, 0, tile->getTexture(0, data)); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, tile->getTexture(0, data)); + t->end(); - t->begin(); - t->normal(0, 1, 0); - renderFaceUp(tile, 0, 0, 0, tile->getTexture(1, data)); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, tile->getTexture(1, data)); + t->end(); - t->begin(); - t->normal(0, 0, -1); - renderNorth(tile, 0, 0, 0, tile->getTexture(2, data)); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, tile->getTexture(2, data)); + t->end(); - t->begin(); - t->normal(0, 0, 1); - renderSouth(tile, 0, 0, 0, tile->getTexture(3, data)); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, tile->getTexture(3, data)); + t->end(); - t->begin(); - t->normal(-1, 0, 0); - renderWest(tile, 0, 0, 0, tile->getTexture(4, data)); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, tile->getTexture(4, data)); + t->end(); - t->begin(); - t->normal(1, 0, 0); - renderEast(tile, 0, 0, 0, tile->getTexture(5, data)); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, tile->getTexture(5, data)); + t->end(); - glTranslatef(0.5f, 0.5f, 0.5f); - } - setShape(0, 0, 0, 1, 1, 1); - } - else if (shape == Tile::SHAPE_ANVIL) - { - glTranslatef(-0.5f, -0.5f, -0.5f); - tesselateAnvilInWorld((AnvilTile *) tile, 0, 0, 0, data, true); - glTranslatef(0.5f, 0.5f, 0.5f); - } - else if ( shape == Tile::SHAPE_PORTAL_FRAME ) - { - // 4J added - setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); + glTranslatef(0.5f, 0.5f, 0.5f); + } + setShape(0, 0, 0, 1, 1, 1); + } else if (shape == Tile::SHAPE_ANVIL) { + glTranslatef(-0.5f, -0.5f, -0.5f); + tesselateAnvilInWorld((AnvilTile*)tile, 0, 0, 0, data, true); + glTranslatef(0.5f, 0.5f, 0.5f); + } else if (shape == Tile::SHAPE_PORTAL_FRAME) { + // 4J added + setShape(0, 0, 0, 1, 13.0f / 16.0f, 1); - glTranslatef( -0.5f, -0.5f, -0.5f ); - t->begin(); - t->normal( 0, -1, 0 ); - renderFaceDown( tile, 0, 0, 0, getTexture(tile, 0, 0 ) ); - t->end(); + glTranslatef(-0.5f, -0.5f, -0.5f); + t->begin(); + t->normal(0, -1, 0); + renderFaceDown(tile, 0, 0, 0, getTexture(tile, 0, 0)); + t->end(); - t->begin(); - t->normal( 0, 1, 0 ); - renderFaceUp( tile, 0, 0, 0, getTexture(tile, 1, 0 ) ); - t->end(); + t->begin(); + t->normal(0, 1, 0); + renderFaceUp(tile, 0, 0, 0, getTexture(tile, 1, 0)); + t->end(); - t->begin(); - t->normal( 0, 0, -1 ); - renderNorth( tile, 0, 0, 0, getTexture(tile, 2, 0 ) ); - t->end(); + t->begin(); + t->normal(0, 0, -1); + renderNorth(tile, 0, 0, 0, getTexture(tile, 2, 0)); + t->end(); - t->begin(); - t->normal( 0, 0, 1 ); - renderSouth( tile, 0, 0, 0, getTexture(tile, 3, 0 ) ); - t->end(); + t->begin(); + t->normal(0, 0, 1); + renderSouth(tile, 0, 0, 0, getTexture(tile, 3, 0)); + t->end(); - t->begin(); - t->normal( -1, 0, 0 ); - renderWest( tile, 0, 0, 0, getTexture(tile, 4, 0 ) ); - t->end(); + t->begin(); + t->normal(-1, 0, 0); + renderWest(tile, 0, 0, 0, getTexture(tile, 4, 0)); + t->end(); - t->begin(); - t->normal( 1, 0, 0 ); - renderEast( tile, 0, 0, 0, getTexture(tile, 5, 0 ) ); - t->end(); + t->begin(); + t->normal(1, 0, 0); + renderEast(tile, 0, 0, 0, getTexture(tile, 5, 0)); + t->end(); - glTranslatef( 0.5f, 0.5f, 0.5f ); + glTranslatef(0.5f, 0.5f, 0.5f); - tile->updateDefaultShape(); - - } - t->setMipmapEnable( true ); // 4J added + tile->updateDefaultShape(); + } + t->setMipmapEnable(true); // 4J added } -bool TileRenderer::canRender( int renderShape ) -{ - if ( renderShape == Tile::SHAPE_BLOCK ) return true; - if ( renderShape == Tile::SHAPE_TREE ) return true; - if ( renderShape == Tile::SHAPE_QUARTZ) return true; - if ( renderShape == Tile::SHAPE_CACTUS ) return true; - if ( renderShape == Tile::SHAPE_STAIRS ) return true; - if ( renderShape == Tile::SHAPE_FENCE ) return true; - if ( renderShape == Tile::SHAPE_EGG) return true; - if ( renderShape == Tile::SHAPE_ENTITYTILE_ANIMATED) return true; - if ( renderShape == Tile::SHAPE_FENCE_GATE) return true; - if ( renderShape == Tile::SHAPE_PISTON_BASE ) return true; - if ( renderShape == Tile::SHAPE_PORTAL_FRAME ) return true; - if ( renderShape == Tile::SHAPE_WALL) return true; - if ( renderShape == Tile::SHAPE_ANVIL) return true; - return false; +bool TileRenderer::canRender(int renderShape) { + if (renderShape == Tile::SHAPE_BLOCK) return true; + if (renderShape == Tile::SHAPE_TREE) return true; + if (renderShape == Tile::SHAPE_QUARTZ) return true; + if (renderShape == Tile::SHAPE_CACTUS) return true; + if (renderShape == Tile::SHAPE_STAIRS) return true; + if (renderShape == Tile::SHAPE_FENCE) return true; + if (renderShape == Tile::SHAPE_EGG) return true; + if (renderShape == Tile::SHAPE_ENTITYTILE_ANIMATED) return true; + if (renderShape == Tile::SHAPE_FENCE_GATE) return true; + if (renderShape == Tile::SHAPE_PISTON_BASE) return true; + if (renderShape == Tile::SHAPE_PORTAL_FRAME) return true; + if (renderShape == Tile::SHAPE_WALL) return true; + if (renderShape == Tile::SHAPE_ANVIL) return true; + return false; } -Icon *TileRenderer::getTexture(Tile *tile, LevelSource *level, int x, int y, int z, int face) -{ - return getTextureOrMissing(tile->getTexture(level, x, y, z, face)); +Icon* TileRenderer::getTexture(Tile* tile, LevelSource* level, int x, int y, + int z, int face) { + return getTextureOrMissing(tile->getTexture(level, x, y, z, face)); } -Icon *TileRenderer::getTexture(Tile *tile, int face, int data) -{ - return getTextureOrMissing(tile->getTexture(face, data)); +Icon* TileRenderer::getTexture(Tile* tile, int face, int data) { + return getTextureOrMissing(tile->getTexture(face, data)); } -Icon *TileRenderer::getTexture(Tile *tile, int face) -{ - return getTextureOrMissing(tile->getTexture(face)); +Icon* TileRenderer::getTexture(Tile* tile, int face) { + return getTextureOrMissing(tile->getTexture(face)); } -Icon *TileRenderer::getTexture(Tile *tile) -{ - return getTextureOrMissing(tile->getTexture(Facing::UP)); +Icon* TileRenderer::getTexture(Tile* tile) { + return getTextureOrMissing(tile->getTexture(Facing::UP)); } -Icon *TileRenderer::getTextureOrMissing(Icon *icon) -{ - if (icon == NULL) return minecraft->textures->getMissingIcon(Icon::TYPE_TERRAIN); +Icon* TileRenderer::getTextureOrMissing(Icon* icon) { + if (icon == NULL) + return minecraft->textures->getMissingIcon(Icon::TYPE_TERRAIN); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Pass on the Alpha Cut out flag to the tesselator - Tesselator* t = Tesselator::getInstance(); - t->setAlphaCutOut( icon->getFlags() & Icon::IS_ALPHA_CUT_OUT ); + // AP - alpha cut out is expensive on vita. Pass on the Alpha Cut out flag + // to the tesselator + Tesselator* t = Tesselator::getInstance(); + t->setAlphaCutOut(icon->getFlags() & Icon::IS_ALPHA_CUT_OUT); #endif - return icon; + return icon; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h index 34f926a7e..5f34f0989 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TileRenderer.h @@ -24,188 +24,233 @@ class WallTile; class Icon; class Minecraft; -class TileRenderer -{ - friend class FallingTileRenderer; - private: - LevelSource* level; - Icon *fixedTexture; - bool xFlipTexture; - bool noCulling; - public : - static bool fancy; - bool setColor; - - float tileShapeX0; - float tileShapeX1; - float tileShapeY0; - float tileShapeY1; - float tileShapeZ0; - float tileShapeZ1; - bool fixedShape; - bool smoothShapeLighting; - Minecraft *minecraft; - ///////////////////////////////////////// Data caching - std::unordered_map getLightColorCount; - int xMin, yMin, zMin; - int xMin2, yMin2, zMin2; - int getLightColor( Tile *tt, LevelSource *level, int x, int y, int z); - float getShadeBrightness( Tile *tt, LevelSource *level, int x, int y, int z); - bool isTranslucentAt( LevelSource *level, int x, int y, int z); - unsigned int *cache; - unsigned char *tileIds; - static const unsigned int cache_getLightColor_valid = 0x80000000; - static const unsigned int cache_isTranslucentAt_valid = 0x40000000; - static const unsigned int cache_isSolidBlockingTile_valid = 0x20000000; - static const unsigned int cache_getLightColor_mask = 0x00f000f0; - static const unsigned int cache_isTranslucentAt_flag = 0x00000001; - static const unsigned int cache_isSolidBlockingTile_flag = 0x00000002; - ///////////////////////////////////////// - - void _init(); - -public: - TileRenderer( LevelSource* level, int xMin, int yMin, int zMin, unsigned char *tileIds ); - TileRenderer( LevelSource* level ); - TileRenderer(); - ~TileRenderer(); - void setFixedTexture( Icon *fixedTexture ); - void clearFixedTexture(); - bool hasFixedTexture(); - void setShape(float x0, float y0, float z0, float x1, float y1, float z1); - void setShape(Tile *tt); - void setFixedShape(float x0, float y0, float z0, float x1, float y1, float z1); - void clearFixedShape(); - - void tesselateInWorldFixedTexture( Tile* tile, int x, int y, int z, Icon *fixedTexture ); // 4J renamed to differentiate from tesselateInWorld - void tesselateInWorldNoCulling( Tile* tile, int x, int y, int z, int forceData = -1, - std::shared_ptr< TileEntity > forceEntity = std::shared_ptr< TileEntity >() ); // 4J added forceData, forceEntity param - bool tesselateInWorld( Tile* tt, int x, int y, int z, int forceData = -1, std::shared_ptr< TileEntity > forceEntity = - std::shared_ptr< TileEntity >() ); // 4J added forceData, forceEntity param - - private: - bool tesselateAirPortalFrameInWorld(TheEndPortalFrameTile *tt, int x, int y, int z); - bool tesselateBedInWorld( Tile* tt, int x, int y, int z ); - bool tesselateBrewingStandInWorld(BrewingStandTile *tt, int x, int y, int z); - bool tesselateCauldronInWorld(CauldronTile *tt, int x, int y, int z); - bool tesselateFlowerPotInWorld(FlowerPotTile *tt, int x, int y, int z); - bool tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z); - -public: - bool tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data); +class TileRenderer { + friend class FallingTileRenderer; private: - bool tesselateAnvilInWorld(AnvilTile *tt, int x, int y, int z, int data, bool render); - float tesselateAnvilPiece(AnvilTile *tt, int x, int y, int z, int part, float bottom, float width, float height, float length, bool rotate, bool render, int data); + LevelSource* level; + Icon* fixedTexture; + bool xFlipTexture; + bool noCulling; public: - bool tesselateTorchInWorld( Tile* tt, int x, int y, int z ); + static bool fancy; + bool setColor; + + float tileShapeX0; + float tileShapeX1; + float tileShapeY0; + float tileShapeY1; + float tileShapeZ0; + float tileShapeZ1; + bool fixedShape; + bool smoothShapeLighting; + Minecraft* minecraft; + ///////////////////////////////////////// Data caching + std::unordered_map getLightColorCount; + int xMin, yMin, zMin; + int xMin2, yMin2, zMin2; + int getLightColor(Tile* tt, LevelSource* level, int x, int y, int z); + float getShadeBrightness(Tile* tt, LevelSource* level, int x, int y, int z); + bool isTranslucentAt(LevelSource* level, int x, int y, int z); + unsigned int* cache; + unsigned char* tileIds; + static const unsigned int cache_getLightColor_valid = 0x80000000; + static const unsigned int cache_isTranslucentAt_valid = 0x40000000; + static const unsigned int cache_isSolidBlockingTile_valid = 0x20000000; + static const unsigned int cache_getLightColor_mask = 0x00f000f0; + static const unsigned int cache_isTranslucentAt_flag = 0x00000001; + static const unsigned int cache_isSolidBlockingTile_flag = 0x00000002; + ///////////////////////////////////////// + + void _init(); + +public: + TileRenderer(LevelSource* level, int xMin, int yMin, int zMin, + unsigned char* tileIds); + TileRenderer(LevelSource* level); + TileRenderer(); + ~TileRenderer(); + void setFixedTexture(Icon* fixedTexture); + void clearFixedTexture(); + bool hasFixedTexture(); + void setShape(float x0, float y0, float z0, float x1, float y1, float z1); + void setShape(Tile* tt); + void setFixedShape(float x0, float y0, float z0, float x1, float y1, + float z1); + void clearFixedShape(); + + void tesselateInWorldFixedTexture( + Tile* tile, int x, int y, int z, + Icon* + fixedTexture); // 4J renamed to differentiate from tesselateInWorld + void tesselateInWorldNoCulling( + Tile* tile, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + bool tesselateInWorld( + Tile* tt, int x, int y, int z, int forceData = -1, + std::shared_ptr forceEntity = std::shared_ptr< + TileEntity>()); // 4J added forceData, forceEntity param + private: - bool tesselateDiodeInWorld(DiodeTile *tt, int x, int y, int z); - void tesselateDiodeInWorld( DiodeTile* tt, int x, int y, int z, int dir ); - static const int FLIP_NONE = 0, FLIP_CW = 1, FLIP_CCW = 2, FLIP_180 = 3; + bool tesselateAirPortalFrameInWorld(TheEndPortalFrameTile* tt, int x, int y, + int z); + bool tesselateBedInWorld(Tile* tt, int x, int y, int z); + bool tesselateBrewingStandInWorld(BrewingStandTile* tt, int x, int y, + int z); + bool tesselateCauldronInWorld(CauldronTile* tt, int x, int y, int z); + bool tesselateFlowerPotInWorld(FlowerPotTile* tt, int x, int y, int z); + bool tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z); - int northFlip; - int southFlip; - int eastFlip; - int westFlip; - int upFlip; - int downFlip; - public: - void tesselatePistonBaseForceExtended( Tile* tile, int x, int y, int z, int forceData = -1 ); // 4J added data param - private: - bool tesselatePistonBaseInWorld( Tile* tt, int x, int y, int z, bool forceExtended, int forceData = -1 ); // 4J added data param - void renderPistonArmUpDown( float x0, float x1, float y0, float y1, float z0, float z1, float br, float armLengthPixels ); - void renderPistonArmNorthSouth( float x0, float x1, float y0, float y1, float z0, float z1, float br, float armLengthPixels ); - void renderPistonArmEastWest( float x0, float x1, float y0, float y1, float z0, float z1, float br, float armLengthPixels ); - public: - void tesselatePistonArmNoCulling( Tile* tile, int x, int y, int z, bool fullArm, int forceData = -1 ); // 4J added data param - private: - bool tesselatePistonExtensionInWorld( Tile* tt, int x, int y, int z, bool fullArm, int forceData = -1 ); // 4J added data param - public: - bool tesselateLeverInWorld( Tile* tt, int x, int y, int z ); - bool tesselateTripwireSourceInWorld(Tile *tt, int x, int y, int z); - bool tesselateTripwireInWorld(Tile *tt, int x, int y, int z); - bool tesselateFireInWorld( FireTile* tt, int x, int y, int z ); - bool tesselateDustInWorld( Tile* tt, int x, int y, int z ); - bool tesselateRailInWorld( RailTile* tt, int x, int y, int z ); - bool tesselateLadderInWorld( Tile* tt, int x, int y, int z ); - bool tesselateVineInWorld( Tile* tt, int x, int y, int z ); - bool tesselateThinFenceInWorld( ThinFenceTile* tt, int x, int y, int z ); - bool tesselateCrossInWorld( Tile* tt, int x, int y, int z ); - bool tesselateStemInWorld( 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, int data ); - void tesselateCrossTexture( Tile* tt, int data, float x, float y, float z, float scale ); - void tesselateStemTexture( Tile* tt, int data, float h, float x, float y, float z ); - bool tesselateLilypadInWorld(Tile *tt, int x, int y, int z); - void tesselateStemDirTexture( StemTile* tt, int data, int dir, float h, float x, float y, float z ); +public: + bool tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, int data); - void tesselateRowTexture( Tile* tt, int data, float x, float y, float z ); - bool tesselateWaterInWorld( Tile* tt, int x, int y, int z ); - private: - float getWaterHeight( int x, int y, int z, Material* m ); - public: - void renderBlock( Tile* tt, Level* level, int x, int y, int z ); - void renderBlock(Tile *tt, Level *level, int x, int y, int z, int data); - bool tesselateBlockInWorld( Tile* tt, int x, int y, int z ); - // AP - added so we can cull earlier - bool tesselateBlockInWorld( Tile* tt, int x, int y, int z, int faceFlags ); - bool tesselateTreeInWorld(Tile *tt, int x, int y, int z); - bool tesselateQuartzInWorld(Tile *tt, int x, int y, int z); - bool tesselateCocoaInWorld(CocoaTile *tt, int x, int y, int z); +private: + bool tesselateAnvilInWorld(AnvilTile* tt, int x, int y, int z, int data, + bool render); + float tesselateAnvilPiece(AnvilTile* tt, int x, int y, int z, int part, + float bottom, float width, float height, + float length, bool rotate, bool render, int data); - private: - 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; - // 4J - brought forward changes from 1.8.2 - int ccx00, cc00z, cc0Y0, cc00Z; - int ccxyz, ccxy0, ccxyZ, cc0yz, cc0yZ, ccXyz, ccXy0; - int ccXyZ, ccxYz, ccxY0, ccxYZ, cc0Yz, ccXYz, ccXY0; - int cc0YZ, ccXYZ, ccx0z, ccX0z, ccx0Z, ccX0Z; - int blsmooth; - int tc1, tc2, tc3, tc4; // 4J - brought forward changes from 1.8.2 - 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; +public: + bool tesselateTorchInWorld(Tile* tt, int x, int y, int z); - public: - // 4J - brought forward changes from 1.8.2 - // AP - added faceFlags so we can cull earlier - bool tesselateBlockInWorldWithAmbienceOcclusionTexLighting( Tile* tt, int pX, int pY, int pZ, float pBaseRed, - float pBaseGreen, float pBaseBlue, int faceFlags ); - private: - int blend( int a, int b, int c, int def ); - int blend(int a, int b, int c, int d, double fa, double fb, double fc, double fd); - public: - bool tesselateBlockInWorld( Tile* tt, int x, int y, int z, float r, float g, float b ); - 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 tesselateFenceInWorld( FenceTile* tt, int x, int y, int z ); - bool tesselateWallInWorld(WallTile *tt, int x, int y, int z); - bool tesselateEggInWorld(EggTile *tt, int x, int y, int z); - bool tesselateFenceGateInWorld(FenceGateTile *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 ); - void renderFaceUp( Tile* tt, double x, double y, double z, Icon *tex ); - void renderFaceDown( Tile* tt, double x, double y, double z, Icon *tex ); - void renderNorth( Tile* tt, double x, double y, double z, Icon *tex ); - void renderSouth( Tile* tt, double x, double y, double z, Icon *tex ); - void renderWest( Tile* tt, double x, double y, double z, Icon *tex ); - void renderEast( Tile* tt, double x, double y, double z, Icon *tex ); - void renderCube( Tile* tile, float alpha ); - void renderTile( Tile* tile, int data, float brightness, float fAlpha = 1.0f, bool useCompiled = true ); // 4J Added useCompiled - static bool canRender( int renderShape ); - Icon *getTexture(Tile *tile, LevelSource *level, int x, int y, int z, int face); +private: + bool tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z); + void tesselateDiodeInWorld(DiodeTile* tt, int x, int y, int z, int dir); + static const int FLIP_NONE = 0, FLIP_CW = 1, FLIP_CCW = 2, FLIP_180 = 3; - Icon *getTexture(Tile *tile, int face, int data); - Icon *getTexture(Tile *tile, int face); - Icon *getTexture(Tile *tile); - Icon *getTextureOrMissing(Icon *icon); + int northFlip; + int southFlip; + int eastFlip; + int westFlip; + int upFlip; + int downFlip; + +public: + void tesselatePistonBaseForceExtended( + Tile* tile, int x, int y, int z, + int forceData = -1); // 4J added data param +private: + bool tesselatePistonBaseInWorld(Tile* tt, int x, int y, int z, + bool forceExtended, + int forceData = -1); // 4J added data param + void renderPistonArmUpDown(float x0, float x1, float y0, float y1, float z0, + float z1, float br, float armLengthPixels); + void renderPistonArmNorthSouth(float x0, float x1, float y0, float y1, + float z0, float z1, float br, + float armLengthPixels); + void renderPistonArmEastWest(float x0, float x1, float y0, float y1, + float z0, float z1, float br, + float armLengthPixels); + +public: + void tesselatePistonArmNoCulling( + Tile* tile, int x, int y, int z, bool fullArm, + int forceData = -1); // 4J added data param +private: + bool tesselatePistonExtensionInWorld( + Tile* tt, int x, int y, int z, bool fullArm, + int forceData = -1); // 4J added data param +public: + bool tesselateLeverInWorld(Tile* tt, int x, int y, int z); + bool tesselateTripwireSourceInWorld(Tile* tt, int x, int y, int z); + bool tesselateTripwireInWorld(Tile* tt, int x, int y, int z); + bool tesselateFireInWorld(FireTile* tt, int x, int y, int z); + bool tesselateDustInWorld(Tile* tt, int x, int y, int z); + bool tesselateRailInWorld(RailTile* tt, int x, int y, int z); + bool tesselateLadderInWorld(Tile* tt, int x, int y, int z); + bool tesselateVineInWorld(Tile* tt, int x, int y, int z); + bool tesselateThinFenceInWorld(ThinFenceTile* tt, int x, int y, int z); + bool tesselateCrossInWorld(Tile* tt, int x, int y, int z); + bool tesselateStemInWorld(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, int data); + void tesselateCrossTexture(Tile* tt, int data, float x, float y, float z, + float scale); + void tesselateStemTexture(Tile* tt, int data, float h, float x, float y, + float z); + bool tesselateLilypadInWorld(Tile* tt, int x, int y, int z); + void tesselateStemDirTexture(StemTile* 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); + bool tesselateWaterInWorld(Tile* tt, int x, int y, int z); + +private: + float getWaterHeight(int x, int y, int z, Material* m); + +public: + void renderBlock(Tile* tt, Level* level, int x, int y, int z); + void renderBlock(Tile* tt, Level* level, int x, int y, int z, int data); + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z); + // AP - added so we can cull earlier + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z, int faceFlags); + bool tesselateTreeInWorld(Tile* tt, int x, int y, int z); + bool tesselateQuartzInWorld(Tile* tt, int x, int y, int z); + bool tesselateCocoaInWorld(CocoaTile* tt, int x, int y, int z); + +private: + 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; + // 4J - brought forward changes from 1.8.2 + int ccx00, cc00z, cc0Y0, cc00Z; + int ccxyz, ccxy0, ccxyZ, cc0yz, cc0yZ, ccXyz, ccXy0; + int ccXyZ, ccxYz, ccxY0, ccxYZ, cc0Yz, ccXYz, ccXY0; + int cc0YZ, ccXYZ, ccx0z, ccX0z, ccx0Z, ccX0Z; + int blsmooth; + int tc1, tc2, tc3, tc4; // 4J - brought forward changes from 1.8.2 + 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; + +public: + // 4J - brought forward changes from 1.8.2 + // AP - added faceFlags so we can cull earlier + bool tesselateBlockInWorldWithAmbienceOcclusionTexLighting( + Tile* tt, int pX, int pY, int pZ, float pBaseRed, float pBaseGreen, + float pBaseBlue, int faceFlags); + +private: + int blend(int a, int b, int c, int def); + int blend(int a, int b, int c, int d, double fa, double fb, double fc, + double fd); + +public: + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z, float r, float g, + float b); + 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 tesselateFenceInWorld(FenceTile* tt, int x, int y, int z); + bool tesselateWallInWorld(WallTile* tt, int x, int y, int z); + bool tesselateEggInWorld(EggTile* tt, int x, int y, int z); + bool tesselateFenceGateInWorld(FenceGateTile* 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); + void renderFaceUp(Tile* tt, double x, double y, double z, Icon* tex); + void renderFaceDown(Tile* tt, double x, double y, double z, Icon* tex); + void renderNorth(Tile* tt, double x, double y, double z, Icon* tex); + void renderSouth(Tile* tt, double x, double y, double z, Icon* tex); + void renderWest(Tile* tt, double x, double y, double z, Icon* tex); + void renderEast(Tile* tt, double x, double y, double z, Icon* tex); + void renderCube(Tile* tile, float alpha); + void renderTile(Tile* tile, int data, float brightness, float fAlpha = 1.0f, + bool useCompiled = true); // 4J Added useCompiled + static bool canRender(int renderShape); + Icon* getTexture(Tile* tile, LevelSource* level, int x, int y, int z, + int face); + + Icon* getTexture(Tile* tile, int face, int data); + Icon* getTexture(Tile* tile, int face); + Icon* getTexture(Tile* tile); + Icon* getTextureOrMissing(Icon* icon); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp index 4bce1b017..0ceabb23a 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.cpp @@ -4,21 +4,20 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -TntRenderer::TntRenderer() -{ - tileRenderer = new TileRenderer(); - this->shadowRadius = 0.5f; +TntRenderer::TntRenderer() { + tileRenderer = new TileRenderer(); + this->shadowRadius = 0.5f; } -void TntRenderer::render(std::shared_ptr _tnt, double x, double y, double z, float rot, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr tnt = std::dynamic_pointer_cast(_tnt); +void TntRenderer::render(std::shared_ptr _tnt, double x, double y, + double z, float rot, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr tnt = std::dynamic_pointer_cast(_tnt); - glPushMatrix(); - glTranslatef((float) x, (float) y, (float) z); - if (tnt->life - a + 1 < 10) - { + glPushMatrix(); + glTranslatef((float)x, (float)y, (float)z); + if (tnt->life - a + 1 < 10) { float g = 1 - ((tnt->life - a + 1) / 10.0f); if (g < 0) g = 0; if (g > 1) g = 1; @@ -29,20 +28,22 @@ void TntRenderer::render(std::shared_ptr _tnt, double x, double y, doubl } float br = (1 - ((tnt->life - a + 1) / 100.0f)) * 0.8f; - bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - // 4J - change brought forward from 1.8.2 - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1.0f : tnt->getBrightness(a); + bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + // 4J - change brought forward from 1.8.2 + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1.0f : tnt->getBrightness(a); tileRenderer->renderTile(Tile::tnt, 0, brightness); - if (tnt->life / 5 % 2 == 0) - { + if (tnt->life / 5 % 2 == 0) { glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); glColor4f(1, 1, 1, br); - tileRenderer->setColor = false; // 4J added so that renderTile doesn't set its own colour here + tileRenderer->setColor = false; // 4J added so that renderTile doesn't + // set its own colour here tileRenderer->renderTile(Tile::tnt, 0, 1); - tileRenderer->setColor = true; // 4J added so that renderTile doesn't set its own colour here + tileRenderer->setColor = true; // 4J added so that renderTile doesn't + // set its own colour here glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); glEnable(GL_LIGHTING); diff --git a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h index 1f70c8dae..64a679364 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/TntRenderer.h @@ -1,12 +1,12 @@ #pragma once #include "EntityRenderer.h" -class TntRenderer : public EntityRenderer -{ +class TntRenderer : public EntityRenderer { private: - TileRenderer *tileRenderer; + TileRenderer* tileRenderer; public: - TntRenderer(); - virtual void render(std::shared_ptr _tnt, double x, double y, double z, float rot, float a); + TntRenderer(); + virtual void render(std::shared_ptr _tnt, double x, double y, + double z, float rot, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp index 2ec228b68..046b41d7c 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.cpp @@ -5,65 +5,69 @@ #include "../Models/ModelPart.h" #include "VillagerGolemRenderer.h" -VillagerGolemRenderer::VillagerGolemRenderer() : MobRenderer(new VillagerGolemModel(), 0.5f) -{ - golemModel = (VillagerGolemModel *) model; +VillagerGolemRenderer::VillagerGolemRenderer() + : MobRenderer(new VillagerGolemModel(), 0.5f) { + golemModel = (VillagerGolemModel*)model; } -int VillagerGolemRenderer::prepareArmor(VillagerGolemModel *villagerGolem, int layer, float a) -{ - return -1; +int VillagerGolemRenderer::prepareArmor(VillagerGolemModel* villagerGolem, + int layer, float a) { + return -1; } -void VillagerGolemRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); +void VillagerGolemRenderer::render(std::shared_ptr mob, double x, + double y, double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); } -void VillagerGolemRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::setupRotations(mob, bob, bodyRot, a); - if (mob->walkAnimSpeed < 0.01) return; +void VillagerGolemRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::setupRotations(mob, bob, bodyRot, a); + if (mob->walkAnimSpeed < 0.01) return; - float p = 13; - float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a) + 6; - float triangleWave = (abs(fmod(wp ,p) - p * 0.5f) - p * 0.25f) / (p * 0.25f); - glRotatef(6.5f * triangleWave, 0, 0, 1); + float p = 13; + float wp = mob->walkAnimPos - mob->walkAnimSpeed * (1 - a) + 6; + float triangleWave = + (abs(fmod(wp, p) - p * 0.5f) - p * 0.25f) / (p * 0.25f); + glRotatef(6.5f * triangleWave, 0, 0, 1); } -void VillagerGolemRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - MobRenderer::additionalRendering(mob, a); - if (mob->getOfferFlowerTick() == 0) return; +void VillagerGolemRenderer::additionalRendering(std::shared_ptr _mob, + float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = + std::dynamic_pointer_cast(_mob); + MobRenderer::additionalRendering(mob, a); + if (mob->getOfferFlowerTick() == 0) return; - glEnable(GL_RESCALE_NORMAL); - glPushMatrix(); + glEnable(GL_RESCALE_NORMAL); + glPushMatrix(); - // dont ask me how I got the flower into his hand. - glRotatef(5 + 180 * golemModel->arm0->xRot / PI, 1, 0, 0); - glTranslatef(-11 / 16.0f, 20 / 16.0f, -15 / 16.0f); - glRotatef(90, 1, 0, 0); - float s = 0.8f; - glScalef(s, -s, s); + // dont ask me how I got the flower into his hand. + glRotatef(5 + 180 * golemModel->arm0->xRot / PI, 1, 0, 0); + glTranslatef(-11 / 16.0f, 20 / 16.0f, -15 / 16.0f); + glRotatef(90, 1, 0, 0); + float s = 0.8f; + glScalef(s, -s, s); - if (SharedConstants::TEXTURE_LIGHTING) - { - int col = mob->getLightColor(a); - int u = col % 65536; - int v = col / 65536; - glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); - glColor4f(1, 1, 1, 1); - } + if (SharedConstants::TEXTURE_LIGHTING) { + int col = mob->getLightColor(a); + int u = col % 65536; + int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); + glColor4f(1, 1, 1, 1); + } - glColor4f(1, 1, 1, 1); - bindTexture(TN_TERRAIN); //"/terrain.png"); - tileRenderer->renderTile(Tile::rose, 0, 1); - glPopMatrix(); - glDisable(GL_RESCALE_NORMAL); + glColor4f(1, 1, 1, 1); + bindTexture(TN_TERRAIN); //"/terrain.png"); + tileRenderer->renderTile(Tile::rose, 0, 1); + glPopMatrix(); + glDisable(GL_RESCALE_NORMAL); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h index 185e38d4c..52c200940 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerGolemRenderer.h @@ -4,21 +4,22 @@ class VillagerGolemModel; -class VillagerGolemRenderer : public MobRenderer -{ +class VillagerGolemRenderer : public MobRenderer { private: - VillagerGolemModel *golemModel; + VillagerGolemModel* golemModel; public: - VillagerGolemRenderer(); + VillagerGolemRenderer(); protected: - int prepareArmor(VillagerGolemModel *villagerGolem, int layer, float a); + int prepareArmor(VillagerGolemModel* villagerGolem, int layer, float a); public: - void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr mob, double x, double y, double z, + float rot, float a); protected: - void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); - void additionalRendering(std::shared_ptr mob, float a); + void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, + float a); + void additionalRendering(std::shared_ptr mob, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp index 3dc0037e3..ebba76fed 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.cpp @@ -3,40 +3,37 @@ #include "../Models/VillagerModel.h" #include "VillagerRenderer.h" -VillagerRenderer::VillagerRenderer() : MobRenderer(new VillagerModel(0), 0.5f) -{ - villagerModel = (VillagerModel *) model; +VillagerRenderer::VillagerRenderer() : MobRenderer(new VillagerModel(0), 0.5f) { + villagerModel = (VillagerModel*)model; } -int VillagerRenderer::prepareArmor(std::shared_ptr villager, int layer, float a) -{ - return -1; +int VillagerRenderer::prepareArmor(std::shared_ptr villager, int layer, + float a) { + return -1; } -void VillagerRenderer::render(std::shared_ptr mob, double x, double y, double z, float rot, float a) -{ - MobRenderer::render(mob, x, y, z, rot, a); +void VillagerRenderer::render(std::shared_ptr mob, double x, double y, + double z, float rot, float a) { + MobRenderer::render(mob, x, y, z, rot, a); } -void VillagerRenderer::renderName(std::shared_ptr mob, double x, double y, double z) -{ +void VillagerRenderer::renderName(std::shared_ptr mob, double x, double y, + double z) {} + +void VillagerRenderer::additionalRendering(std::shared_ptr mob, float a) { + MobRenderer::additionalRendering(mob, a); } -void VillagerRenderer::additionalRendering(std::shared_ptr mob, float a) -{ - MobRenderer::additionalRendering(mob, a); -} - -void VillagerRenderer::scale(std::shared_ptr _mob, float a) -{ - // 4J - original version used generics and thus had an input parameter of type Blaze rather than std::shared_ptr we have here - - // do some casting around instead - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - float s = 15 / 16.0f; - if (mob->getAge() < 0) - { - s *= 0.5; - shadowRadius = 0.25f; - } else shadowRadius = 0.5f; - glScalef(s, s, s); +void VillagerRenderer::scale(std::shared_ptr _mob, float a) { + // 4J - original version used generics and thus had an input parameter of + // type Blaze rather than std::shared_ptr we have here - do some + // casting around instead + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + float s = 15 / 16.0f; + if (mob->getAge() < 0) { + s *= 0.5; + shadowRadius = 0.25f; + } else + shadowRadius = 0.5f; + glScalef(s, s, s); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h index 1263f4850..90d2591b8 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/VillagerRenderer.h @@ -4,22 +4,23 @@ class VillagerModel; -class VillagerRenderer : public MobRenderer -{ +class VillagerRenderer : public MobRenderer { protected: - VillagerModel *villagerModel; + VillagerModel* villagerModel; public: - VillagerRenderer(); + VillagerRenderer(); protected: - virtual int prepareArmor(std::shared_ptr villager, int layer, float a); + virtual int prepareArmor(std::shared_ptr villager, int layer, float a); public: - virtual void render(std::shared_ptr mob, double x, double y, double z, float rot, float a); + virtual void render(std::shared_ptr mob, double x, double y, + double z, float rot, float a); protected: - virtual void renderName(std::shared_ptr mob, double x, double y, double z); - virtual void additionalRendering(std::shared_ptr mob, float a); - virtual void scale(std::shared_ptr player, float a); + virtual void renderName(std::shared_ptr mob, double x, double y, + double z); + virtual void additionalRendering(std::shared_ptr mob, float a); + virtual void scale(std::shared_ptr player, float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp index 26a92255c..12731b706 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.cpp @@ -3,40 +3,41 @@ #include "../../Player/MultiPlayerLocalPlayer.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.animal.h" -WolfRenderer::WolfRenderer(Model *model, Model *armor, float shadow) : MobRenderer(model, shadow) -{ - setArmor(armor); +WolfRenderer::WolfRenderer(Model* model, Model* armor, float shadow) + : MobRenderer(model, shadow) { + setArmor(armor); } -float WolfRenderer::getBob(std::shared_ptr _mob, float a) -{ - // 4J - dynamic cast required because we aren't using templates/generics in our version - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); +float WolfRenderer::getBob(std::shared_ptr _mob, float a) { + // 4J - dynamic cast required because we aren't using templates/generics in + // our version + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - return mob->getTailAngle(); + return mob->getTailAngle(); } -int WolfRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) -{ - if (mob->isInvisibleTo(Minecraft::GetInstance()->player)) return -1; // 4J-JEV: Todo, merge with java fix in '1.7.5'. +int WolfRenderer::prepareArmor(std::shared_ptr mob, int layer, float a) { + if (mob->isInvisibleTo(Minecraft::GetInstance()->player)) + return -1; // 4J-JEV: Todo, merge with java fix in '1.7.5'. - std::shared_ptr wolf = std::dynamic_pointer_cast(mob); - if (layer == 0 && wolf->isWet()) - { - float brightness = wolf->getBrightness(a) * wolf->getWetShade(a); - bindTexture(wolf->getTexture()); - glColor3f(brightness, brightness, brightness); + std::shared_ptr wolf = std::dynamic_pointer_cast(mob); + if (layer == 0 && wolf->isWet()) { + float brightness = wolf->getBrightness(a) * wolf->getWetShade(a); + bindTexture(wolf->getTexture()); + glColor3f(brightness, brightness, brightness); - return 1; - } - if (layer == 1 && wolf->isTame()) - { - bindTexture(TN_MOB_WOLF_COLLAR); - float brightness = SharedConstants::TEXTURE_LIGHTING ? 1 : wolf->getBrightness(a); - int color = wolf->getCollarColor(); - glColor3f(brightness * Sheep::COLOR[color][0], brightness * Sheep::COLOR[color][1], brightness * Sheep::COLOR[color][2]); + return 1; + } + if (layer == 1 && wolf->isTame()) { + bindTexture(TN_MOB_WOLF_COLLAR); + float brightness = + SharedConstants::TEXTURE_LIGHTING ? 1 : wolf->getBrightness(a); + int color = wolf->getCollarColor(); + glColor3f(brightness * Sheep::COLOR[color][0], + brightness * Sheep::COLOR[color][1], + brightness * Sheep::COLOR[color][2]); - return 1; - } - return -1; + return 1; + } + return -1; } diff --git a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h index 218951c9e..45d5c264f 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/WolfRenderer.h @@ -1,11 +1,11 @@ #pragma once #include "MobRenderer.h" -class WolfRenderer : public MobRenderer -{ +class WolfRenderer : public MobRenderer { public: - WolfRenderer(Model *model, Model *armor, float shadow); + WolfRenderer(Model* model, Model* armor, float shadow); + protected: virtual float getBob(std::shared_ptr _mob, float a); - virtual int prepareArmor(std::shared_ptr mob, int layer, float a); + virtual int prepareArmor(std::shared_ptr mob, int layer, float a); }; diff --git a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp index 6831b2bd1..2fce366fb 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp +++ b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.cpp @@ -4,88 +4,81 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.monster.h" #include "ZombieRenderer.h" -ZombieRenderer::ZombieRenderer() : HumanoidMobRenderer(new ZombieModel(), .5f, 1.0f) -{ - modelVersion = 1; - defaultModel = humanoidModel; - villagerModel = new VillagerZombieModel(); +ZombieRenderer::ZombieRenderer() + : HumanoidMobRenderer(new ZombieModel(), .5f, 1.0f) { + modelVersion = 1; + defaultModel = humanoidModel; + villagerModel = new VillagerZombieModel(); - defaultArmorParts1 = NULL; - defaultArmorParts2 = NULL; + defaultArmorParts1 = NULL; + defaultArmorParts2 = NULL; - villagerArmorParts1 = NULL; - villagerArmorParts2 = NULL; + villagerArmorParts1 = NULL; + villagerArmorParts2 = NULL; - createArmorParts(); + createArmorParts(); } -void ZombieRenderer::createArmorParts() -{ - delete armorParts1; - delete armorParts2; +void ZombieRenderer::createArmorParts() { + delete armorParts1; + delete armorParts2; - armorParts1 = new ZombieModel(1.0f, true); - armorParts2 = new ZombieModel(0.5f, true); + armorParts1 = new ZombieModel(1.0f, true); + armorParts2 = new ZombieModel(0.5f, true); - defaultArmorParts1 = armorParts1; - defaultArmorParts2 = armorParts2; + defaultArmorParts1 = armorParts1; + defaultArmorParts2 = armorParts2; - villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); - villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); + villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); + villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); } -int ZombieRenderer::prepareArmor(std::shared_ptr _mob, int layer, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - swapArmor(mob); - return HumanoidMobRenderer::prepareArmor(_mob, layer, a); +int ZombieRenderer::prepareArmor(std::shared_ptr _mob, int layer, + float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + swapArmor(mob); + return HumanoidMobRenderer::prepareArmor(_mob, layer, a); } -void ZombieRenderer::render(std::shared_ptr _mob, double x, double y, double z, float rot, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - swapArmor(mob); - HumanoidMobRenderer::render(_mob, x, y, z, rot, a); +void ZombieRenderer::render(std::shared_ptr _mob, double x, double y, + double z, float rot, float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + swapArmor(mob); + HumanoidMobRenderer::render(_mob, x, y, z, rot, a); } -void ZombieRenderer::additionalRendering(std::shared_ptr _mob, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - swapArmor(mob); - HumanoidMobRenderer::additionalRendering(_mob, a); +void ZombieRenderer::additionalRendering(std::shared_ptr _mob, float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + swapArmor(mob); + HumanoidMobRenderer::additionalRendering(_mob, a); } -void ZombieRenderer::swapArmor(std::shared_ptr mob) -{ - if (mob->isVillager()) - { - //if (modelVersion != villagerModel->version()) - //{ - // villagerModel = new VillagerZombieModel(); - // modelVersion = villagerModel->version(); - // villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); - // villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); - //} - model = villagerModel; - armorParts1 = villagerArmorParts1; - armorParts2 = villagerArmorParts2; - } - else - { - model = defaultModel; - armorParts1 = defaultArmorParts1; - armorParts2 = defaultArmorParts2; - } +void ZombieRenderer::swapArmor(std::shared_ptr mob) { + if (mob->isVillager()) { + // if (modelVersion != villagerModel->version()) + //{ + // villagerModel = new VillagerZombieModel(); + // modelVersion = villagerModel->version(); + // villagerArmorParts1 = new VillagerZombieModel(1.0f, 0, true); + // villagerArmorParts2 = new VillagerZombieModel(0.5f, 0, true); + // } + model = villagerModel; + armorParts1 = villagerArmorParts1; + armorParts2 = villagerArmorParts2; + } else { + model = defaultModel; + armorParts1 = defaultArmorParts1; + armorParts2 = defaultArmorParts2; + } - humanoidModel = (HumanoidModel *) model; + humanoidModel = (HumanoidModel*)model; } -void ZombieRenderer::setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a) -{ - std::shared_ptr mob = std::dynamic_pointer_cast(_mob); - if (mob->isConverting()) - { - bodyRot += (float) (cos(mob->tickCount * 3.25) * PI * .25f); - } - HumanoidMobRenderer::setupRotations(mob, bob, bodyRot, a); +void ZombieRenderer::setupRotations(std::shared_ptr _mob, float bob, + float bodyRot, float a) { + std::shared_ptr mob = std::dynamic_pointer_cast(_mob); + if (mob->isConverting()) { + bodyRot += (float)(cos(mob->tickCount * 3.25) * PI * .25f); + } + HumanoidMobRenderer::setupRotations(mob, bob, bodyRot, a); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h index b727659a6..5ab79f053 100644 --- a/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h +++ b/Minecraft.Client/Rendering/EntityRenderers/ZombieRenderer.h @@ -5,37 +5,38 @@ class VillagerZombieModel; class Zombie; -class ZombieRenderer : public HumanoidMobRenderer -{ +class ZombieRenderer : public HumanoidMobRenderer { private: - HumanoidModel *defaultModel; - VillagerZombieModel *villagerModel; + HumanoidModel* defaultModel; + VillagerZombieModel* villagerModel; protected: - HumanoidModel *defaultArmorParts1; - HumanoidModel *defaultArmorParts2; - HumanoidModel *villagerArmorParts1; - HumanoidModel *villagerArmorParts2; + HumanoidModel* defaultArmorParts1; + HumanoidModel* defaultArmorParts2; + HumanoidModel* villagerArmorParts1; + HumanoidModel* villagerArmorParts2; private: - int modelVersion; + int modelVersion; public: - ZombieRenderer(); + ZombieRenderer(); protected: - void createArmorParts(); - int prepareArmor(std::shared_ptr _mob, int layer, float a); + void createArmorParts(); + int prepareArmor(std::shared_ptr _mob, int layer, float a); public: - void render(std::shared_ptr _mob, double x, double y, double z, float rot, float a); + void render(std::shared_ptr _mob, double x, double y, double z, + float rot, float a); protected: - void additionalRendering(std::shared_ptr _mob, float a); + void additionalRendering(std::shared_ptr _mob, float a); private: - void swapArmor(std::shared_ptr mob); + void swapArmor(std::shared_ptr mob); protected: - void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, float a); + void setupRotations(std::shared_ptr _mob, float bob, float bodyRot, + float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Frustum.cpp b/Minecraft.Client/Rendering/Frustum.cpp index c8d6655cc..1144a7d5f 100644 --- a/Minecraft.Client/Rendering/Frustum.cpp +++ b/Minecraft.Client/Rendering/Frustum.cpp @@ -2,39 +2,37 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "Frustum.h" -Frustum *Frustum::frustum = new Frustum(); +Frustum* Frustum::frustum = new Frustum(); -Frustum::Frustum() -{ - _proj = MemoryTracker::createFloatBuffer(16); - _modl = MemoryTracker::createFloatBuffer(16); - _clip = MemoryTracker::createFloatBuffer(16); +Frustum::Frustum() { + _proj = MemoryTracker::createFloatBuffer(16); + _modl = MemoryTracker::createFloatBuffer(16); + _clip = MemoryTracker::createFloatBuffer(16); } -Frustum::~Frustum() -{ - delete _proj; - delete _modl; - delete _clip; +Frustum::~Frustum() { + delete _proj; + delete _modl; + delete _clip; } - -FrustumData *Frustum::getFrustum() -{ - frustum->calculateFrustum(); +FrustumData* Frustum::getFrustum() { + frustum->calculateFrustum(); return frustum; } +///////////////////////////////// NORMALIZE PLANE +///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +///// +///// This normalizes a plane (A side) from a given frustum. +///// +///////////////////////////////// NORMALIZE PLANE +///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - ///// - ///// This normalizes a plane (A side) from a given frustum. - ///// - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - -void Frustum::normalizePlane(float **frustum, int side) -{ - float magnitude = (float) sqrt(frustum[side][A] * frustum[side][A] + frustum[side][B] * frustum[side][B] + frustum[side][C] * frustum[side][C]); +void Frustum::normalizePlane(float** frustum, int side) { + float magnitude = (float)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. @@ -44,8 +42,7 @@ void Frustum::normalizePlane(float **frustum, int side) frustum[side][D] /= magnitude; } -void Frustum::calculateFrustum() -{ +void Frustum::calculateFrustum() { _proj->clear(); _modl->clear(); _clip->clear(); @@ -58,34 +55,51 @@ void Frustum::calculateFrustum() // 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. + // 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[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[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[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]; + 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. diff --git a/Minecraft.Client/Rendering/Frustum.h b/Minecraft.Client/Rendering/Frustum.h index 4ce37160f..a556a919c 100644 --- a/Minecraft.Client/Rendering/Frustum.h +++ b/Minecraft.Client/Rendering/Frustum.h @@ -1,29 +1,30 @@ #pragma once #include "FrustumData.h" -class Frustum : public FrustumData -{ +class Frustum : public FrustumData { private: - static Frustum *frustum; + static Frustum* frustum; public: - static FrustumData *getFrustum(); + static FrustumData* getFrustum(); - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + ///////////////////////////////// NORMALIZE PLANE + ///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This normalizes a plane (A side) from a given frustum. ///// - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + ///////////////////////////////// NORMALIZE PLANE + ///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* private: - void normalizePlane(float **frustum, int side); + void normalizePlane(float** frustum, int side); - FloatBuffer *_proj; - FloatBuffer *_modl; - FloatBuffer *_clip; + FloatBuffer* _proj; + FloatBuffer* _modl; + FloatBuffer* _clip; void calculateFrustum(); - Frustum(); - ~Frustum(); + Frustum(); + ~Frustum(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/FrustumCuller.cpp b/Minecraft.Client/Rendering/FrustumCuller.cpp index d842e3cf3..e2ab78c7f 100644 --- a/Minecraft.Client/Rendering/FrustumCuller.cpp +++ b/Minecraft.Client/Rendering/FrustumCuller.cpp @@ -1,29 +1,26 @@ #include "../Platform/stdafx.h" #include "FrustumCuller.h" -FrustumCuller::FrustumCuller() -{ - frustum = Frustum::getFrustum(); -} +FrustumCuller::FrustumCuller() { frustum = Frustum::getFrustum(); } -void FrustumCuller::prepare(double xOff, double yOff, double zOff) -{ +void FrustumCuller::prepare(double xOff, double yOff, double zOff) { this->xOff = xOff; this->yOff = yOff; this->zOff = zOff; } -bool FrustumCuller::cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return frustum->cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); +bool FrustumCuller::cubeFullyInFrustum(double x0, double y0, double z0, + double x1, double y1, double z1) { + return frustum->cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, + x1 - xOff, y1 - yOff, z1 - zOff); } -bool FrustumCuller::cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1) -{ - return frustum->cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); +bool FrustumCuller::cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1) { + return frustum->cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, + y1 - yOff, z1 - zOff); } -bool FrustumCuller::isVisible(AABB *bb) -{ - return cubeInFrustum(bb->x0, bb->y0, bb->z0, bb->x1, bb->y1, bb->z1); +bool FrustumCuller::isVisible(AABB* bb) { + return cubeInFrustum(bb->x0, bb->y0, bb->z0, bb->x1, bb->y1, bb->z1); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/FrustumCuller.h b/Minecraft.Client/Rendering/FrustumCuller.h index 5197ef10d..a14814c1d 100644 --- a/Minecraft.Client/Rendering/FrustumCuller.h +++ b/Minecraft.Client/Rendering/FrustumCuller.h @@ -3,15 +3,17 @@ #include "Culling/Culler.h" #include "Frustum.h" -class FrustumCuller : public Culler -{ +class FrustumCuller : public Culler { public: - FrustumData *frustum; - FrustumCuller(); - double xOff, yOff, zOff; + FrustumData* frustum; + FrustumCuller(); + double xOff, yOff, zOff; + public: - virtual void prepare(double xOff, double yOff, double zOff); - virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, double y1, double z1); - virtual bool isVisible(AABB *bb); + virtual void prepare(double xOff, double yOff, double zOff); + virtual bool cubeFullyInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool cubeInFrustum(double x0, double y0, double z0, double x1, + double y1, double z1); + virtual bool isVisible(AABB* bb); }; diff --git a/Minecraft.Client/Rendering/FrustumData.cpp b/Minecraft.Client/Rendering/FrustumData.cpp index 525785fae..a5f11b768 100644 --- a/Minecraft.Client/Rendering/FrustumData.cpp +++ b/Minecraft.Client/Rendering/FrustumData.cpp @@ -1,90 +1,131 @@ #include "../Platform/stdafx.h" -#include "FrustumData.h" +#include "FrustumData.h" float** m_Frustum; - -FrustumData::FrustumData() -{ - m_Frustum = new float *[16]; - for( int i = 0; i < 16; i++ ) m_Frustum[i] = new float[16]; - proj = floatArray( 16 ); - modl = floatArray( 16 ); - clip = floatArray( 16 ); +FrustumData::FrustumData() { + m_Frustum = new float*[16]; + for (int i = 0; i < 16; i++) m_Frustum[i] = new float[16]; + proj = floatArray(16); + modl = floatArray(16); + clip = floatArray(16); } -FrustumData::~FrustumData() -{ - delete[] proj.data; - delete[] modl.data; - delete[] clip.data; - for( int i = 0; i < 16; i++ ) delete[] m_Frustum[i]; - delete[] m_Frustum; +FrustumData::~FrustumData() { + delete[] proj.data; + delete[] modl.data; + delete[] clip.data; + for (int i = 0; i < 16; i++) delete[] m_Frustum[i]; + delete[] m_Frustum; } -bool FrustumData::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) - { +bool FrustumData::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 FrustumData::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 FrustumData::cubeFullyInFrustum(double x1, double y1, double z1, double x2, double y2, double 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; +bool FrustumData::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 FrustumData::cubeInFrustum(double x1, double y1, double z1, double x2, double y2, double 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; - +bool FrustumData::cubeFullyInFrustum(double x1, double y1, double z1, double x2, + double y2, double 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 FrustumData::cubeInFrustum(double x1, double y1, double z1, double x2, + double y2, double 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 FrustumData::isVisible(AABB *aabb) -{ - return cubeInFrustum(aabb->x0, aabb->y0, aabb->z0, aabb->x1, aabb->y1, aabb->z1); +bool FrustumData::isVisible(AABB* aabb) { + return cubeInFrustum(aabb->x0, aabb->y0, aabb->z0, aabb->x1, aabb->y1, + aabb->z1); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/FrustumData.h b/Minecraft.Client/Rendering/FrustumData.h index 314e0b111..1a61d4ae3 100644 --- a/Minecraft.Client/Rendering/FrustumData.h +++ b/Minecraft.Client/Rendering/FrustumData.h @@ -1,35 +1,36 @@ #pragma once #include "../../Minecraft.World/Util/AABB.h" -class FrustumData -{ +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 + // 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 + 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; floatArray proj; floatArray modl; floatArray clip; - FrustumData(); - ~FrustumData(); + FrustumData(); + ~FrustumData(); bool pointInFrustum(float x, float y, float z); bool sphereInFrustum(float x, float y, float z, float radius); - bool cubeFullyInFrustum(double x1, double y1, double z1, double x2, double y2, double z2); - bool cubeInFrustum(double x1, double y1, double z1, double x2, double y2, double z2); - bool isVisible(AABB *aabb); + bool cubeFullyInFrustum(double x1, double y1, double z1, double x2, + double y2, double z2); + bool cubeInFrustum(double x1, double y1, double z1, double x2, double y2, + double z2); + bool isVisible(AABB* aabb); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/GameRenderer.cpp b/Minecraft.Client/Rendering/GameRenderer.cpp index 9f45d145c..6b0d32724 100644 --- a/Minecraft.Client/Rendering/GameRenderer.cpp +++ b/Minecraft.Client/Rendering/GameRenderer.cpp @@ -53,664 +53,635 @@ bool GameRenderer::anaglyph3d = false; int GameRenderer::anaglyphPass = 0; #ifdef MULTITHREAD_ENABLE -C4JThread* GameRenderer::m_updateThread; +C4JThread* GameRenderer::m_updateThread; C4JThread::EventArray* GameRenderer::m_updateEvents; bool GameRenderer::nearThingsToDo = false; bool GameRenderer::updateRunning = false; -std::vector GameRenderer::m_deleteStackByte; -std::vector GameRenderer::m_deleteStackSparseLightStorage; -std::vector GameRenderer::m_deleteStackCompressedTileStorage; -std::vector GameRenderer::m_deleteStackSparseDataStorage; +std::vector GameRenderer::m_deleteStackByte; +std::vector GameRenderer::m_deleteStackSparseLightStorage; +std::vector + GameRenderer::m_deleteStackCompressedTileStorage; +std::vector GameRenderer::m_deleteStackSparseDataStorage; #endif CRITICAL_SECTION GameRenderer::m_csDeleteStack; -GameRenderer::GameRenderer(Minecraft *mc) -{ - // 4J - added this block of initialisers - renderDistance = 0; - _tick = 0; - hovered = nullptr; - thirdDistance = 4; - thirdDistanceO = 4; - thirdRotation = 0; - thirdRotationO = 0; - thirdTilt = 0; - thirdTiltO = 0; +GameRenderer::GameRenderer(Minecraft* mc) { + // 4J - added this block of initialisers + renderDistance = 0; + _tick = 0; + hovered = nullptr; + thirdDistance = 4; + thirdDistanceO = 4; + thirdRotation = 0; + thirdRotationO = 0; + thirdTilt = 0; + thirdTiltO = 0; accumulatedSmoothXO = 0; - accumulatedSmoothYO = 0; + accumulatedSmoothYO = 0; tickSmoothXO = 0; - tickSmoothYO = 0; - lastTickA = 0; + tickSmoothYO = 0; + lastTickA = 0; - cameraPos = Vec3::newPermanent(0.0f,0.0f,0.0f); + cameraPos = Vec3::newPermanent(0.0f, 0.0f, 0.0f); - fovOffset = 0; - fovOffsetO = 0; - cameraRoll = 0; - cameraRollO = 0; - for( int i = 0; i < 4; i++ ) - { - fov[i] = 0.0f; - oFov[i] = 0.0f; - tFov[i] = 0.0f; - } - isInClouds = false; - zoom = 1; - zoom_x = 0; - zoom_y = 0; - rainXa = NULL; - rainZa = NULL; - lastActiveTime = Minecraft::currentTimeMillis(); - lastNsTime = 0; - random = new Random(); - rainSoundTime = 0; - xMod = 0; - yMod = 0; - lb = MemoryTracker::createFloatBuffer(16); - fr = 0.0f; - fg = 0.0f; - fb = 0.0f; - fogBrO = 0.0f; - fogBr = 0.0f; - cameraFlip = 0; - _updateLightTexture = false; - blr = 0.0f; - blrt = 0.0f; - blg = 0.0f; - blgt = 0.0f; + fovOffset = 0; + fovOffsetO = 0; + cameraRoll = 0; + cameraRollO = 0; + for (int i = 0; i < 4; i++) { + fov[i] = 0.0f; + oFov[i] = 0.0f; + tFov[i] = 0.0f; + } + isInClouds = false; + zoom = 1; + zoom_x = 0; + zoom_y = 0; + rainXa = NULL; + rainZa = NULL; + lastActiveTime = Minecraft::currentTimeMillis(); + lastNsTime = 0; + random = new Random(); + rainSoundTime = 0; + xMod = 0; + yMod = 0; + lb = MemoryTracker::createFloatBuffer(16); + fr = 0.0f; + fg = 0.0f; + fb = 0.0f; + fogBrO = 0.0f; + fogBr = 0.0f; + cameraFlip = 0; + _updateLightTexture = false; + blr = 0.0f; + blrt = 0.0f; + blg = 0.0f; + blgt = 0.0f; + m_fov = 70.0f; - m_fov=70.0f; + // 4J Stu - Init these so they are setup before the tick + for (int i = 0; i < 4; i++) { + fov[i] = oFov[i] = 1.0f; + } - // 4J Stu - Init these so they are setup before the tick - for( int i = 0; i < 4; i++ ) - { - fov[i] = oFov[i] = 1.0f; - } + this->mc = mc; + itemInHandRenderer = NULL; - this->mc = mc; - itemInHandRenderer = NULL; + // 4J-PB - set up the local players iteminhand renderers here - needs to be + // done with lighting enabled so that the render geometry gets compiled + // correctly + glEnable(GL_LIGHTING); + mc->localitemInHandRenderers[0] = + new ItemInHandRenderer(mc); // itemInHandRenderer; + mc->localitemInHandRenderers[1] = new ItemInHandRenderer(mc); + mc->localitemInHandRenderers[2] = new ItemInHandRenderer(mc); + mc->localitemInHandRenderers[3] = new ItemInHandRenderer(mc); + glDisable(GL_LIGHTING); - // 4J-PB - set up the local players iteminhand renderers here - needs to be done with lighting enabled so that the render geometry gets compiled correctly - glEnable(GL_LIGHTING); - mc->localitemInHandRenderers[0] = new ItemInHandRenderer(mc);//itemInHandRenderer; - mc->localitemInHandRenderers[1] = new ItemInHandRenderer(mc); - mc->localitemInHandRenderers[2] = new ItemInHandRenderer(mc); - mc->localitemInHandRenderers[3] = new ItemInHandRenderer(mc); - glDisable(GL_LIGHTING); - - // 4J - changes brought forward from 1.8.2 - BufferedImage *img = new BufferedImage(16, 16, BufferedImage::TYPE_INT_RGB); - for( int i = 0; i < NUM_LIGHT_TEXTURES; i++ ) - { - lightTexture[i] = mc->textures->getTexture(img); // 4J - changed to one light texture per level to support split screen - } - delete img; + // 4J - changes brought forward from 1.8.2 + BufferedImage* img = new BufferedImage(16, 16, BufferedImage::TYPE_INT_RGB); + for (int i = 0; i < NUM_LIGHT_TEXTURES; i++) { + lightTexture[i] = + mc->textures->getTexture(img); // 4J - changed to one light texture + // per level to support split screen + } + delete img; #ifdef __PS3__ - // we're using the RSX now to upload textures to vram, so we need the main ram textures allocated from io space - for(int i=0;iSet(eUpdateEventIsFinished); + m_updateEvents = new C4JThread::EventArray( + eUpdateEventCount, C4JThread::EventArray::e_modeAutoClear); + m_updateEvents->Set(eUpdateEventIsFinished); - InitializeCriticalSection(&m_csDeleteStack); - m_updateThread = new C4JThread(runUpdate, NULL, "Chunk update"); + InitializeCriticalSection(&m_csDeleteStack); + m_updateThread = new C4JThread(runUpdate, NULL, "Chunk update"); #ifdef __PS3__ - m_updateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); -#endif// __PS3__ - m_updateThread->SetProcessor(CPU_CORE_CHUNK_UPDATE); - m_updateThread->Run(); + m_updateThread->SetPriority(THREAD_PRIORITY_ABOVE_NORMAL); +#endif // __PS3__ + m_updateThread->SetProcessor(CPU_CORE_CHUNK_UPDATE); + m_updateThread->Run(); #endif } // 4J Stu Added to go with 1.8.2 change -GameRenderer::~GameRenderer() -{ - if(rainXa != NULL) delete [] rainXa; - if(rainZa != NULL) delete [] rainZa; +GameRenderer::~GameRenderer() { + if (rainXa != NULL) delete[] rainXa; + if (rainZa != NULL) delete[] rainZa; } -void GameRenderer::tick(bool first) // 4J - add bFirst -{ - tickFov(); - tickLightTexture(); // 4J - change brought forward from 1.8.2 - fogBrO = fogBr; - thirdDistanceO = thirdDistance; - thirdRotationO = thirdRotation; - thirdTiltO = thirdTilt; - fovOffsetO = fovOffset; - cameraRollO = cameraRoll; +void GameRenderer::tick(bool first) // 4J - add bFirst +{ + tickFov(); + tickLightTexture(); // 4J - change brought forward from 1.8.2 + fogBrO = fogBr; + thirdDistanceO = thirdDistance; + thirdRotationO = thirdRotation; + thirdTiltO = thirdTilt; + fovOffsetO = fovOffset; + cameraRollO = cameraRoll; - if (ClientConstants::DEADMAU5_CAMERA_CHEATS) - { - if (mc->screen == NULL) - { - float distanceDelta = 0; - float rotationDelta = 0; - float tiltDelta = 0; - float rollDelta = 0; + if (ClientConstants::DEADMAU5_CAMERA_CHEATS) { + if (mc->screen == NULL) { + float distanceDelta = 0; + float rotationDelta = 0; + float tiltDelta = 0; + float rollDelta = 0; - if (Keyboard::isKeyDown(Keyboard::KEY_U)) - { - distanceDelta -= .3f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_O)) - { - distanceDelta += .3f * mc->options->cameraSpeed; - } - if (Keyboard::isKeyDown(Keyboard::KEY_J)) - { - rotationDelta += 8.0f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_L)) - { - rotationDelta -= 8.0f * mc->options->cameraSpeed; - } - if (Keyboard::isKeyDown(Keyboard::KEY_I)) - { - tiltDelta += 6.0f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_K)) - { - tiltDelta -= 6.0f * mc->options->cameraSpeed; - } - if (Keyboard::isKeyDown(Keyboard::KEY_Y) && Keyboard::isKeyDown(Keyboard::KEY_H)) - { - fovOffset = 0; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_Y)) - { - fovOffset -= 3.0f; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_H)) - { - fovOffset += 3.0f; - } - if (Keyboard::isKeyDown(Keyboard::KEY_N) && Keyboard::isKeyDown(Keyboard::KEY_M)) - { - cameraRoll = 0; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_N)) - { - rollDelta -= 8.0f * mc->options->cameraSpeed; - } - else if (Keyboard::isKeyDown(Keyboard::KEY_M)) - { - rollDelta += 8.0f * mc->options->cameraSpeed; - } + if (Keyboard::isKeyDown(Keyboard::KEY_U)) { + distanceDelta -= .3f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_O)) { + distanceDelta += .3f * mc->options->cameraSpeed; + } + if (Keyboard::isKeyDown(Keyboard::KEY_J)) { + rotationDelta += 8.0f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_L)) { + rotationDelta -= 8.0f * mc->options->cameraSpeed; + } + if (Keyboard::isKeyDown(Keyboard::KEY_I)) { + tiltDelta += 6.0f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_K)) { + tiltDelta -= 6.0f * mc->options->cameraSpeed; + } + if (Keyboard::isKeyDown(Keyboard::KEY_Y) && + Keyboard::isKeyDown(Keyboard::KEY_H)) { + fovOffset = 0; + } else if (Keyboard::isKeyDown(Keyboard::KEY_Y)) { + fovOffset -= 3.0f; + } else if (Keyboard::isKeyDown(Keyboard::KEY_H)) { + fovOffset += 3.0f; + } + if (Keyboard::isKeyDown(Keyboard::KEY_N) && + Keyboard::isKeyDown(Keyboard::KEY_M)) { + cameraRoll = 0; + } else if (Keyboard::isKeyDown(Keyboard::KEY_N)) { + rollDelta -= 8.0f * mc->options->cameraSpeed; + } else if (Keyboard::isKeyDown(Keyboard::KEY_M)) { + rollDelta += 8.0f * mc->options->cameraSpeed; + } - if (mc->options->smoothCamera) - { - distanceDelta = smoothDistance.getNewDeltaValue(distanceDelta, .5f * mc->options->sensitivity); - rotationDelta = smoothRotation.getNewDeltaValue(rotationDelta, .5f * mc->options->sensitivity); - tiltDelta = smoothTilt.getNewDeltaValue(tiltDelta, .5f * mc->options->sensitivity); - rollDelta = smoothRoll.getNewDeltaValue(rollDelta, .5f * mc->options->sensitivity); - } - thirdDistance += distanceDelta; - thirdRotation += rotationDelta; - thirdTilt += tiltDelta; - cameraRoll += rollDelta; - } - } + if (mc->options->smoothCamera) { + distanceDelta = smoothDistance.getNewDeltaValue( + distanceDelta, .5f * mc->options->sensitivity); + rotationDelta = smoothRotation.getNewDeltaValue( + rotationDelta, .5f * mc->options->sensitivity); + tiltDelta = smoothTilt.getNewDeltaValue( + tiltDelta, .5f * mc->options->sensitivity); + rollDelta = smoothRoll.getNewDeltaValue( + rollDelta, .5f * mc->options->sensitivity); + } + thirdDistance += distanceDelta; + thirdRotation += rotationDelta; + thirdTilt += tiltDelta; + cameraRoll += rollDelta; + } + } - if (mc->options->smoothCamera) - { + if (mc->options->smoothCamera) { // update player view in tick() instead of render() to maintain -// camera movement regardless of FPS + // camera movement regardless of FPS float ss = mc->options->sensitivity * 0.6f + 0.2f; float sens = (ss * ss * ss) * 8; - tickSmoothXO = smoothTurnX.getNewDeltaValue(accumulatedSmoothXO, 0.05f * sens); - tickSmoothYO = smoothTurnY.getNewDeltaValue(accumulatedSmoothYO, 0.05f * sens); + tickSmoothXO = + smoothTurnX.getNewDeltaValue(accumulatedSmoothXO, 0.05f * sens); + tickSmoothYO = + smoothTurnY.getNewDeltaValue(accumulatedSmoothYO, 0.05f * sens); lastTickA = 0; accumulatedSmoothXO = 0; accumulatedSmoothYO = 0; } - if (mc->cameraTargetPlayer == NULL) - { - mc->cameraTargetPlayer = std::dynamic_pointer_cast(mc->player); - } + if (mc->cameraTargetPlayer == NULL) { + mc->cameraTargetPlayer = std::dynamic_pointer_cast(mc->player); + } - float brr = mc->level->getBrightness(Mth::floor(mc->cameraTargetPlayer->x), Mth::floor(mc->cameraTargetPlayer->y), Mth::floor(mc->cameraTargetPlayer->z)); - float whiteness = (3 - mc->options->viewDistance) / 3.0f; - float fogBrT = brr * (1 - whiteness) + whiteness; - fogBr += (fogBrT - fogBr) * 0.1f; + float brr = mc->level->getBrightness(Mth::floor(mc->cameraTargetPlayer->x), + Mth::floor(mc->cameraTargetPlayer->y), + Mth::floor(mc->cameraTargetPlayer->z)); + float whiteness = (3 - mc->options->viewDistance) / 3.0f; + float fogBrT = brr * (1 - whiteness) + whiteness; + fogBr += (fogBrT - fogBr) * 0.1f; - itemInHandRenderer->tick(); + itemInHandRenderer->tick(); - PIXBeginNamedEvent(0,"Rain tick"); - tickRain(); - PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Rain tick"); + tickRain(); + PIXEndNamedEvent(); - if( mc->player != mc->localplayers[ProfileManager.GetPrimaryPad()] ) return; // 4J added for split screen - only do rest of processing for once per frame + if (mc->player != mc->localplayers[ProfileManager.GetPrimaryPad()]) + return; // 4J added for split screen - only do rest of processing for + // once per frame - _tick++; + _tick++; } -void GameRenderer::pick(float a) -{ - if (mc->cameraTargetPlayer == NULL) return; - if (mc->level == NULL) return; +void GameRenderer::pick(float a) { + if (mc->cameraTargetPlayer == NULL) return; + if (mc->level == NULL) return; - double range = mc->gameMode->getPickRange(); - delete mc->hitResult; - MemSect(31); - mc->hitResult = mc->cameraTargetPlayer->pick(range, a); - MemSect(0); + double range = mc->gameMode->getPickRange(); + delete mc->hitResult; + MemSect(31); + mc->hitResult = mc->cameraTargetPlayer->pick(range, a); + MemSect(0); - // 4J - added - stop blocks right at the edge of the world from being pickable so we shouldn't be able to directly destroy or create anything there - if( mc->hitResult ) - { - int maxxz = ( ( mc->level->chunkSource->m_XZSize / 2 ) * 16 ) - 2; - int minxz = ( -( mc->level->chunkSource->m_XZSize / 2 ) * 16 ) + 1; + // 4J - added - stop blocks right at the edge of the world from being + // pickable so we shouldn't be able to directly destroy or create anything + // there + if (mc->hitResult) { + int maxxz = ((mc->level->chunkSource->m_XZSize / 2) * 16) - 2; + int minxz = (-(mc->level->chunkSource->m_XZSize / 2) * 16) + 1; - // Don't select the tops of the very edge blocks, or the sides of the next blocks in - // 4J Stu - Only block the sides that are facing an outside block - int hitx = mc->hitResult->x; - int hitz = mc->hitResult->z; - int face = mc->hitResult->f; - if( face == Facing::WEST && hitx < 0 ) hitx -= 1; - if( face == Facing::EAST && hitx > 0 ) hitx += 1; - if( face == Facing::NORTH && hitz < 0 ) hitz -= 1; - if( face == Facing::SOUTH && hitz > 0 ) hitz += 1; + // Don't select the tops of the very edge blocks, or the sides of the + // next blocks in 4J Stu - Only block the sides that are facing an + // outside block + int hitx = mc->hitResult->x; + int hitz = mc->hitResult->z; + int face = mc->hitResult->f; + if (face == Facing::WEST && hitx < 0) hitx -= 1; + if (face == Facing::EAST && hitx > 0) hitx += 1; + if (face == Facing::NORTH && hitz < 0) hitz -= 1; + if (face == Facing::SOUTH && hitz > 0) hitz += 1; - if( ( hitx < minxz ) || ( hitx > maxxz) || - ( hitz < minxz ) || ( hitz > maxxz) ) - { - delete mc->hitResult; - mc->hitResult = NULL; - } - } + if ((hitx < minxz) || (hitx > maxxz) || (hitz < minxz) || + (hitz > maxxz)) { + delete mc->hitResult; + mc->hitResult = NULL; + } + } - double dist = range; - Vec3 *from = mc->cameraTargetPlayer->getPos(a); + double dist = range; + Vec3* from = mc->cameraTargetPlayer->getPos(a); - if (mc->gameMode->hasFarPickRange()) - { - dist = range = 6; - } - else - { - if (dist > 3) dist = 3; - range = dist; - } + if (mc->gameMode->hasFarPickRange()) { + dist = range = 6; + } else { + if (dist > 3) dist = 3; + range = dist; + } - if (mc->hitResult != NULL) - { - dist = mc->hitResult->pos->distanceTo(from); - } + if (mc->hitResult != NULL) { + dist = mc->hitResult->pos->distanceTo(from); + } - Vec3 *b = mc->cameraTargetPlayer->getViewVector(a); - Vec3 *to = from->add(b->x * range, b->y * range, b->z * range); + Vec3* b = mc->cameraTargetPlayer->getViewVector(a); + Vec3* to = from->add(b->x * range, b->y * range, b->z * range); hovered = nullptr; float overlap = 1; - std::vector > *objects = mc->level->getEntities(mc->cameraTargetPlayer, mc->cameraTargetPlayer->bb->expand(b->x * (range), b->y * (range), b->z * (range))->grow(overlap, overlap, overlap)); + std::vector >* objects = mc->level->getEntities( + mc->cameraTargetPlayer, + mc->cameraTargetPlayer->bb + ->expand(b->x * (range), b->y * (range), b->z * (range)) + ->grow(overlap, overlap, overlap)); double nearest = dist; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) - { - std::shared_ptr e = *it; //objects->at(i); + AUTO_VAR(itEnd, objects->end()); + for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) { + std::shared_ptr e = *it; // objects->at(i); if (!e->isPickable()) continue; - float rr = e->getPickRadius(); - AABB *bb = e->bb->grow(rr, rr, rr); - HitResult *p = bb->clip(from, to); - if (bb->contains(from)) - { - if (0 < nearest || nearest == 0) - { - hovered = e; - nearest = 0; - } - } - else if (p != NULL) - { - double dd = from->distanceTo(p->pos); - if (dd < nearest || nearest == 0) - { - hovered = e; - nearest = dd; - } - } - delete p; - } + float rr = e->getPickRadius(); + AABB* bb = e->bb->grow(rr, rr, rr); + HitResult* p = bb->clip(from, to); + if (bb->contains(from)) { + if (0 < nearest || nearest == 0) { + hovered = e; + nearest = 0; + } + } else if (p != NULL) { + double dd = from->distanceTo(p->pos); + if (dd < nearest || nearest == 0) { + hovered = e; + nearest = dd; + } + } + delete p; + } - if (hovered != NULL) - { - if (nearest < dist || (mc->hitResult == NULL)) - { - if( mc->hitResult != NULL ) - delete mc->hitResult; - mc->hitResult = new HitResult(hovered); - } - } + if (hovered != NULL) { + if (nearest < dist || (mc->hitResult == NULL)) { + if (mc->hitResult != NULL) delete mc->hitResult; + mc->hitResult = new HitResult(hovered); + } + } } -void GameRenderer::SetFovVal(float fov) -{ - m_fov=fov; -} +void GameRenderer::SetFovVal(float fov) { m_fov = fov; } -float GameRenderer::GetFovVal() -{ - return m_fov; -} +float GameRenderer::GetFovVal() { return m_fov; } -void GameRenderer::tickFov() -{ - std::shared_ptrplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); +void GameRenderer::tickFov() { + std::shared_ptr player = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); - int playerIdx = player ? player->GetXboxPad() : 0; + int playerIdx = player ? player->GetXboxPad() : 0; tFov[playerIdx] = player->getFieldOfViewModifier(); oFov[playerIdx] = fov[playerIdx]; fov[playerIdx] += (tFov[playerIdx] - fov[playerIdx]) * 0.5f; } -float GameRenderer::getFov(float a, bool applyEffects) -{ - if (cameraFlip > 0 ) return 90; +float GameRenderer::getFov(float a, bool applyEffects) { + if (cameraFlip > 0) return 90; - std::shared_ptr player = std::dynamic_pointer_cast(mc->cameraTargetPlayer); - int playerIdx = player ? player->GetXboxPad() : 0; - float fov = m_fov;//70; - if (applyEffects) - { + std::shared_ptr player = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); + int playerIdx = player ? player->GetXboxPad() : 0; + float fov = m_fov; // 70; + if (applyEffects) { fov += mc->options->fov * 40; - fov *= this->oFov[playerIdx] + (this->fov[playerIdx] - this->oFov[playerIdx]) * a; + fov *= this->oFov[playerIdx] + + (this->fov[playerIdx] - this->oFov[playerIdx]) * a; } - if (player->getHealth() <= 0) - { - float duration = player->deathTime + a; + if (player->getHealth() <= 0) { + float duration = player->deathTime + a; - fov /= ((1 - 500 / (duration + 500)) * 2.0f + 1); - } + fov /= ((1 - 500 / (duration + 500)) * 2.0f + 1); + } int t = Camera::getBlockAt(mc->level, player, a); - if (t != 0 && Tile::tiles[t]->material == Material::water) fov = fov * 60 / 70; - - return fov + fovOffsetO + (fovOffset - fovOffsetO) * a; + if (t != 0 && Tile::tiles[t]->material == Material::water) + fov = fov * 60 / 70; + return fov + fovOffsetO + (fovOffset - fovOffsetO) * a; } -void GameRenderer::bobHurt(float a) -{ - std::shared_ptr player = mc->cameraTargetPlayer; +void GameRenderer::bobHurt(float a) { + std::shared_ptr player = mc->cameraTargetPlayer; - float hurt = player->hurtTime - a; + float hurt = player->hurtTime - a; - if (player->getHealth() <= 0) - { - float duration = player->deathTime + a; + if (player->getHealth() <= 0) { + float duration = player->deathTime + a; - glRotatef(40 - (40 * 200) / (duration + 200), 0, 0, 1); - } + glRotatef(40 - (40 * 200) / (duration + 200), 0, 0, 1); + } - if (hurt < 0) return; - hurt /= player->hurtDuration; - hurt = (float) Mth::sin(hurt * hurt * hurt * hurt * PI); + if (hurt < 0) return; + hurt /= player->hurtDuration; + hurt = (float)Mth::sin(hurt * hurt * hurt * hurt * PI); - float rr = player->hurtDir; - - - glRotatef(-rr, 0, 1, 0); - glRotatef(-hurt * 14, 0, 0, 1); - glRotatef(+rr, 0, 1, 0); + float rr = player->hurtDir; + glRotatef(-rr, 0, 1, 0); + glRotatef(-hurt * 14, 0, 0, 1); + glRotatef(+rr, 0, 1, 0); } -void GameRenderer::bobView(float a) -{ - std::shared_ptr player = std::dynamic_pointer_cast(mc->cameraTargetPlayer); - if(player==NULL) - { - return; - } - //std::shared_ptr player = std::dynamic_pointer_cast(mc->cameraTargetPlayer); +void GameRenderer::bobView(float a) { + std::shared_ptr player = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); + if (player == NULL) { + return; + } + // std::shared_ptr player = + // std::dynamic_pointer_cast(mc->cameraTargetPlayer); - float wda = player->walkDist - player->walkDistO; - float b = -(player->walkDist + wda * a); - float bob = player->oBob + (player->bob - player->oBob) * a; - float tilt = player->oTilt + (player->tilt - player->oTilt) * a; - glTranslatef((float) Mth::sin(b * PI) * bob * 0.5f, -(float) abs(Mth::cos(b * PI) * bob), 0); - glRotatef((float) Mth::sin(b * PI) * bob * 3, 0, 0, 1); - glRotatef((float) abs(Mth::cos(b * PI - 0.2f) * bob) * 5, 1, 0, 0); - glRotatef((float) tilt, 1, 0, 0); + float wda = player->walkDist - player->walkDistO; + float b = -(player->walkDist + wda * a); + float bob = player->oBob + (player->bob - player->oBob) * a; + float tilt = player->oTilt + (player->tilt - player->oTilt) * a; + glTranslatef((float)Mth::sin(b * PI) * bob * 0.5f, + -(float)abs(Mth::cos(b * PI) * bob), 0); + glRotatef((float)Mth::sin(b * PI) * bob * 3, 0, 0, 1); + glRotatef((float)abs(Mth::cos(b * PI - 0.2f) * bob) * 5, 1, 0, 0); + glRotatef((float)tilt, 1, 0, 0); } -void GameRenderer::moveCameraToPlayer(float a) -{ - std::shared_ptr player = mc->cameraTargetPlayer; - std::shared_ptr localplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); - float heightOffset = player->heightOffset - 1.62f; +void GameRenderer::moveCameraToPlayer(float a) { + std::shared_ptr player = mc->cameraTargetPlayer; + std::shared_ptr localplayer = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); + float heightOffset = player->heightOffset - 1.62f; - double x = player->xo + (player->x - player->xo) * a; - double y = player->yo + (player->y - player->yo) * a - heightOffset; - double z = player->zo + (player->z - player->zo) * a; + double x = player->xo + (player->x - player->xo) * a; + double y = player->yo + (player->y - player->yo) * a - heightOffset; + double z = player->zo + (player->z - player->zo) * a; + glRotatef(cameraRollO + (cameraRoll - cameraRollO) * a, 0, 0, 1); - glRotatef(cameraRollO + (cameraRoll - cameraRollO) * a, 0, 0, 1); + if (player->isSleeping()) { + heightOffset += 1.0; + glTranslatef(0.0f, 0.3f, 0); + if (!mc->options->fixedCamera) { + int t = + mc->level->getTile(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + if (t == Tile::bed_Id) { + int data = mc->level->getData(Mth::floor(player->x), + Mth::floor(player->y), + Mth::floor(player->z)); - if (player->isSleeping()) - { - heightOffset += 1.0; - glTranslatef(0.0f, 0.3f, 0); - if (!mc->options->fixedCamera) - { - int t = mc->level->getTile(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - if (t == Tile::bed_Id) - { - int data = mc->level->getData(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); + int direction = data & 3; + glRotatef((float)direction * 90, 0.0f, 1.0f, 0.0f); + } + glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, + 0, -1, 0); + glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, -1, 0, + 0); + } + } + // 4J-PB - changing this to be per player + // else if (mc->options->thirdPersonView) + else if (localplayer->ThirdPersonView()) { + double cameraDist = + thirdDistanceO + (thirdDistance - thirdDistanceO) * a; - int direction = data & 3; - glRotatef((float)direction * 90,0.0f, 1.0f, 0.0f); - } - glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, 0, -1, 0); - glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, -1, 0, 0); - } - } - // 4J-PB - changing this to be per player - //else if (mc->options->thirdPersonView) - else if (localplayer->ThirdPersonView()) - { - double cameraDist = thirdDistanceO + (thirdDistance - thirdDistanceO) * a; + if (mc->options->fixedCamera) { + float rotationY = + thirdRotationO + (thirdRotation - thirdRotationO) * a; + float xRot = thirdTiltO + (thirdTilt - thirdTiltO) * a; - if (mc->options->fixedCamera) - { + glTranslatef(0, 0, (float)-cameraDist); + glRotatef(xRot, 1, 0, 0); + glRotatef(rotationY, 0, 1, 0); + } else { + // 4J - corrected bug where this used to just take player->xRot & + // yRot directly and so wasn't taking into account interpolation, + // allowing camera to go through walls + float yRot = player->yRotO + (player->yRot - player->yRotO) * a; + float xRot = player->xRotO + (player->xRot - player->xRotO) * a; - float rotationY = thirdRotationO + (thirdRotation - thirdRotationO) * a; - float xRot = thirdTiltO + (thirdTilt - thirdTiltO) * a; + // Thirdperson view values are now 0 for disabled, 1 for original + // mode, 2 for reversed. + if (localplayer->ThirdPersonView() == 2) { + // Reverse y rotation - note that this is only used in doing + // collision to calculate our view distance, the actual rotation + // itself is just below this else {} block + yRot += 180.0f; + } - glTranslatef(0, 0, (float) -cameraDist); - glRotatef(xRot, 1, 0, 0); - glRotatef(rotationY, 0, 1, 0); - } - else - { - // 4J - corrected bug where this used to just take player->xRot & yRot directly and so wasn't taking into account interpolation, allowing camera to go through walls - float yRot = player->yRotO + (player->yRot - player->yRotO) * a; - float xRot = player->xRotO + (player->xRot - player->xRotO) * a; + double xd = -Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * + cameraDist; + double zd = Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * + cameraDist; + double yd = -Mth::sin(xRot / 180 * PI) * cameraDist; - // Thirdperson view values are now 0 for disabled, 1 for original mode, 2 for reversed. - if( localplayer->ThirdPersonView() == 2 ) - { - // Reverse y rotation - note that this is only used in doing collision to calculate our view - // distance, the actual rotation itself is just below this else {} block - yRot += 180.0f; - } + for (int i = 0; i < 8; i++) { + float xo = (float)((i & 1) * 2 - 1); + float yo = (float)(((i >> 1) & 1) * 2 - 1); + float zo = (float)(((i >> 2) & 1) * 2 - 1); - double xd = -Mth::sin(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * cameraDist; - double zd = Mth::cos(yRot / 180 * PI) * Mth::cos(xRot / 180 * PI) * cameraDist; - double yd = -Mth::sin(xRot / 180 * PI) * cameraDist; + xo *= 0.1f; + yo *= 0.1f; + zo *= 0.1f; - for (int i = 0; i < 8; i++) - { - float xo = (float)((i & 1) * 2 - 1); - float yo = (float)(((i >> 1) & 1) * 2 - 1); - float zo = (float)(((i >> 2) & 1) * 2 - 1); + // 4J - corrected bug here where zo was also added to x + // component + HitResult* hr = mc->level->clip( + Vec3::newTemp(x + xo, y + yo, z + zo), + Vec3::newTemp(x - xd + xo, y - yd + yo, z - zd + zo)); + if (hr != NULL) { + double dist = hr->pos->distanceTo(Vec3::newTemp(x, y, z)); + if (dist < cameraDist) cameraDist = dist; + delete hr; + } + } - xo *= 0.1f; - yo *= 0.1f; - zo *= 0.1f; + // 4J - removed extra rotations here that aren't needed because our + // xRot/yRot don't ever deviate from the player's view direction + // glRotatef(player->xRot - xRot, 1, 0, 0); + // glRotatef(player->yRot - yRot, 0, 1, 0); + glTranslatef(0, 0, (float)-cameraDist); + // glRotatef(yRot - player->yRot, 0, 1, 0); + // glRotatef(xRot - player->xRot, 1, 0, 0); + } + } else { + glTranslatef(0, 0, -0.1f); + } - // 4J - corrected bug here where zo was also added to x component - HitResult *hr = mc->level->clip(Vec3::newTemp(x + xo, y + yo, z + zo), Vec3::newTemp(x - xd + xo, y - yd + yo, z - zd + zo)); - if (hr != NULL) - { - double dist = hr->pos->distanceTo(Vec3::newTemp(x, y, z)); - if (dist < cameraDist) cameraDist = dist; - delete hr; - } - } + if (!mc->options->fixedCamera) { + glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, 1, 0, 0); + if (localplayer->ThirdPersonView() == 2) { + // Third person view is now 0 for disabled, 1 for original, 2 for + // flipped + glRotatef(player->yRotO + (player->yRot - player->yRotO) * a, 0, 1, + 0); + } else { + glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, + 0, 1, 0); + } + } - // 4J - removed extra rotations here that aren't needed because our xRot/yRot don't ever - // deviate from the player's view direction -// glRotatef(player->xRot - xRot, 1, 0, 0); -// glRotatef(player->yRot - yRot, 0, 1, 0); - glTranslatef(0, 0, (float) -cameraDist); -// glRotatef(yRot - player->yRot, 0, 1, 0); -// glRotatef(xRot - player->xRot, 1, 0, 0); - } - } - else - { - glTranslatef(0, 0, -0.1f); - } + glTranslatef(0, heightOffset, 0); - if (!mc->options->fixedCamera) - { - glRotatef(player->xRotO + (player->xRot - player->xRotO) * a, 1, 0, 0); - if( localplayer->ThirdPersonView() == 2 ) - { - // Third person view is now 0 for disabled, 1 for original, 2 for flipped - glRotatef(player->yRotO + (player->yRot - player->yRotO) * a, 0, 1, 0); - } - else - { - glRotatef(player->yRotO + (player->yRot - player->yRotO) * a + 180, 0, 1, 0); - } - } - - glTranslatef(0, heightOffset, 0); - - x = player->xo + (player->x - player->xo) * a; - y = player->yo + (player->y - player->yo) * a - heightOffset; - z = player->zo + (player->z - player->zo) * a; - - isInClouds = mc->levelRenderer->isInCloud(x, y, z, a); + x = player->xo + (player->x - player->xo) * a; + y = player->yo + (player->y - player->yo) * a - heightOffset; + z = player->zo + (player->z - player->zo) * a; + isInClouds = mc->levelRenderer->isInCloud(x, y, z, a); } - -void GameRenderer::zoomRegion(double zoom, double xa, double ya) -{ - this->zoom = zoom; - this->zoom_x = xa; - this->zoom_y = ya; +void GameRenderer::zoomRegion(double zoom, double xa, double ya) { + this->zoom = zoom; + this->zoom_x = xa; + this->zoom_y = ya; } -void GameRenderer::unZoomRegion() -{ - zoom = 1; +void GameRenderer::unZoomRegion() { zoom = 1; } + +// 4J added as we have more complex adjustments to make for fov & aspect on +// account of viewports +void GameRenderer::getFovAndAspect(float& fov, float& aspect, float a, + bool applyEffects) { + // 4J - split out aspect ratio and fov here so we can adjust for viewports - + // we might need to revisit these as avoid pixel streching, its UGLEYYY + { + int fbw = mc->width; + int fbh = mc->height; + RenderManager.GetFramebufferSize(fbw, fbh); + aspect = fbw / (float)fbh; + } + fov = getFov(a, applyEffects); + + if ((mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_TOP) || + (mc->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM)) { + aspect *= 2.0f; + fov *= 0.7f; // Reduce FOV to make things less fish-eye, at the expense + // of reducing vertical FOV from single player mode + } else if ((mc->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_LEFT) || + (mc->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT)) { + // Ideally I'd like to make the fov bigger here, but if I do then you an + // see that the arm isn't very long... + aspect *= 0.5f; + } } -// 4J added as we have more complex adjustments to make for fov & aspect on account of viewports -void GameRenderer::getFovAndAspect(float& fov, float& aspect, float a, bool applyEffects) -{ - // 4J - split out aspect ratio and fov here so we can adjust for viewports - we might need to revisit these as - // avoid pixel streching, its UGLEYYY - { - int fbw = mc->width; - int fbh = mc->height; - RenderManager.GetFramebufferSize(fbw, fbh); - aspect = fbw / (float) fbh; - } - fov = getFov(a, applyEffects); +void GameRenderer::setupCamera(float a, int eye) { + renderDistance = (float)(16 * 16 >> (mc->options->viewDistance)); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); - if( ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_TOP ) || - ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM ) ) - { - aspect *= 2.0f; - fov *= 0.7f; // Reduce FOV to make things less fish-eye, at the expense of reducing vertical FOV from single player mode - } - else if( ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_LEFT ) || - ( mc->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT) ) - { - // Ideally I'd like to make the fov bigger here, but if I do then you an see that the arm isn't very long... - aspect *= 0.5f; - } -} + float stereoScale = 0.07f; + if (mc->options->anaglyph3d) + glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); -void GameRenderer::setupCamera(float a, int eye) -{ - renderDistance = (float)(16 * 16 >> (mc->options->viewDistance)); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); + // 4J - have split out fov & aspect calculation so we can take into account + // viewports + float aspect, fov; + getFovAndAspect(fov, aspect, a, true); - float stereoScale = 0.07f; - if (mc->options->anaglyph3d) glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); + if (zoom != 1) { + glTranslatef((float)zoom_x, (float)-zoom_y, 0); + glScaled(zoom, zoom, 1); + } + gluPerspective(fov, aspect, 0.05f, renderDistance * 2); - // 4J - have split out fov & aspect calculation so we can take into account viewports - float aspect, fov; - getFovAndAspect(fov, aspect, a, true); - - if (zoom != 1) - { - glTranslatef((float) zoom_x, (float) -zoom_y, 0); - glScaled(zoom, zoom, 1); - } - gluPerspective(fov, aspect, 0.05f, renderDistance * 2); - - if (mc->gameMode->isCutScene()) - { + if (mc->gameMode->isCutScene()) { float s = 1 / 1.5f; glScalef(1, s, 1); } - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); - bobHurt(a); + bobHurt(a); - // 4J-PB - this is a per-player option - //if (mc->options->bobView) bobView(a); - - bool bNoLegAnim =(mc->player->getAnimOverrideBitmask()&(1<player->getAnimOverrideBitmask()&(1<options->bobView) bobView(a); - if(app.GetGameSettings(mc->player->GetXboxPad(),eGameSetting_ViewBob) && !mc->player->abilities.flying && !bNoLegAnim && !bNoBobbingAnim) bobView(a); + bool bNoLegAnim = (mc->player->getAnimOverrideBitmask() & + (1 << HumanoidModel::eAnim_NoLegAnim)) != 0; + bool bNoBobbingAnim = (mc->player->getAnimOverrideBitmask() & + (1 << HumanoidModel::eAnim_NoBobbing)) != 0; - float pt = mc->player->oPortalTime + (mc->player->portalTime - mc->player->oPortalTime) * a; - if (pt > 0) - { + if (app.GetGameSettings(mc->player->GetXboxPad(), eGameSetting_ViewBob) && + !mc->player->abilities.flying && !bNoLegAnim && !bNoBobbingAnim) + bobView(a); + + float pt = mc->player->oPortalTime + + (mc->player->portalTime - mc->player->oPortalTime) * a; + if (pt > 0) { int multiplier = 20; - if (mc->player->hasEffect(MobEffect::confusion)) - { + if (mc->player->hasEffect(MobEffect::confusion)) { multiplier = 7; } - float skew = 5 / (pt * pt + 5) - pt * 0.04f; - skew *= skew; - glRotatef((_tick + a) * multiplier, 0, 1, 1); - glScalef(1 / skew, 1, 1); - glRotatef(-(_tick + a) * multiplier, 0, 1, 1); - } + float skew = 5 / (pt * pt + 5) - pt * 0.04f; + skew *= skew; + glRotatef((_tick + a) * multiplier, 0, 1, 1); + glScalef(1 / skew, 1, 1); + glRotatef(-(_tick + a) * multiplier, 0, 1, 1); + } + moveCameraToPlayer(a); - moveCameraToPlayer(a); - - if (cameraFlip > 0) - { + if (cameraFlip > 0) { int i = cameraFlip - 1; if (i == 1) glRotatef(90, 0, 1, 0); if (i == 2) glRotatef(180, 0, 1, 0); @@ -720,113 +691,124 @@ void GameRenderer::setupCamera(float a, int eye) } } -void GameRenderer::renderItemInHand(float a, int eye) -{ - if (cameraFlip > 0) return; +void GameRenderer::renderItemInHand(float a, int eye) { + if (cameraFlip > 0) return; - std::shared_ptr localplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); + std::shared_ptr localplayer = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); - // 4J-PB - to turn off the hand for screenshots, but not when the item held is a map - if ( localplayer!=NULL) - { - std::shared_ptr item = localplayer->inventory->getSelected(); - if(!(item && item->getItem()->id==Item::map_Id) && app.GetGameSettings(localplayer->GetXboxPad(),eGameSetting_DisplayHand)==0 ) return; - } - - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); + // 4J-PB - to turn off the hand for screenshots, but not when the item held + // is a map + if (localplayer != NULL) { + std::shared_ptr item = + localplayer->inventory->getSelected(); + if (!(item && item->getItem()->id == Item::map_Id) && + app.GetGameSettings(localplayer->GetXboxPad(), + eGameSetting_DisplayHand) == 0) + return; + } + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); float stereoScale = 0.07f; - if (mc->options->anaglyph3d) glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); + if (mc->options->anaglyph3d) + glTranslatef(-(eye * 2 - 1) * stereoScale, 0, 0); - // 4J - have split out fov & aspect calculation so we can take into account viewports - float fov, aspect; - getFovAndAspect(fov, aspect, a, false); + // 4J - have split out fov & aspect calculation so we can take into account + // viewports + float fov, aspect; + getFovAndAspect(fov, aspect, a, false); - if (zoom != 1) - { - glTranslatef((float) zoom_x, (float) -zoom_y, 0); + if (zoom != 1) { + glTranslatef((float)zoom_x, (float)-zoom_y, 0); glScaled(zoom, zoom, 1); } gluPerspective(fov, aspect, 0.05f, renderDistance * 2); - if (mc->gameMode->isCutScene()) - { + if (mc->gameMode->isCutScene()) { float s = 1 / 1.5f; glScalef(1, s, 1); } glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); + if (mc->options->anaglyph3d) glTranslatef((eye * 2 - 1) * 0.10f, 0, 0); - glPushMatrix(); - bobHurt(a); + glPushMatrix(); + bobHurt(a); - // 4J-PB - changing this to be per player - //if (mc->options->bobView) bobView(a); - bool bNoLegAnim =(localplayer->getAnimOverrideBitmask()&( (1<GetXboxPad(),eGameSetting_ViewBob) && !localplayer->abilities.flying && !bNoLegAnim) bobView(a); + // 4J-PB - changing this to be per player + // if (mc->options->bobView) bobView(a); + bool bNoLegAnim = (localplayer->getAnimOverrideBitmask() & + ((1 << HumanoidModel::eAnim_NoLegAnim) | + (1 << HumanoidModel::eAnim_NoBobbing))) != 0; + if (app.GetGameSettings(localplayer->GetXboxPad(), eGameSetting_ViewBob) && + !localplayer->abilities.flying && !bNoLegAnim) + bobView(a); - // 4J-PB - changing this to be per player - //if (!mc->options->thirdPersonView && !mc->cameraTargetPlayer->isSleeping()) - if (!localplayer->ThirdPersonView() && !mc->cameraTargetPlayer->isSleeping()) - { - if (!mc->options->hideGui && !mc->gameMode->isCutScene()) - { - turnOnLightLayer(a, true); - PIXBeginNamedEvent(0,"Item in hand render"); - // 4jcraft: add null pointer check to itemInHandRenderer to prevent a occasional seg fault - if (itemInHandRenderer != nullptr) { - itemInHandRenderer->render(a); - } - PIXEndNamedEvent(); - turnOffLightLayer(a); - } - } - glPopMatrix(); - // 4J-PB - changing this to be per player - //if (!mc->options->thirdPersonView && !mc->cameraTargetPlayer->isSleeping()) - if (!localplayer->ThirdPersonView() && !mc->cameraTargetPlayer->isSleeping()) - { - // 4jcraft: add null pointer check to itemInHandRenderer to prevent a occasional seg fault - if (itemInHandRenderer != nullptr) { - itemInHandRenderer->renderScreenEffect(a); - } - bobHurt(a); - } - // 4J-PB - changing this to be per player - //if (mc->options->bobView) bobView(a); - if(app.GetGameSettings(localplayer->GetXboxPad(),eGameSetting_ViewBob) && !localplayer->abilities.flying && !bNoLegAnim) bobView(a); + // 4J-PB - changing this to be per player + // if (!mc->options->thirdPersonView && + // !mc->cameraTargetPlayer->isSleeping()) + if (!localplayer->ThirdPersonView() && + !mc->cameraTargetPlayer->isSleeping()) { + if (!mc->options->hideGui && !mc->gameMode->isCutScene()) { + turnOnLightLayer(a, true); + PIXBeginNamedEvent(0, "Item in hand render"); + // 4jcraft: add null pointer check to itemInHandRenderer to prevent + // a occasional seg fault + if (itemInHandRenderer != nullptr) { + itemInHandRenderer->render(a); + } + PIXEndNamedEvent(); + turnOffLightLayer(a); + } + } + glPopMatrix(); + // 4J-PB - changing this to be per player + // if (!mc->options->thirdPersonView && + // !mc->cameraTargetPlayer->isSleeping()) + if (!localplayer->ThirdPersonView() && + !mc->cameraTargetPlayer->isSleeping()) { + // 4jcraft: add null pointer check to itemInHandRenderer to prevent a + // occasional seg fault + if (itemInHandRenderer != nullptr) { + itemInHandRenderer->renderScreenEffect(a); + } + bobHurt(a); + } + // 4J-PB - changing this to be per player + // if (mc->options->bobView) bobView(a); + if (app.GetGameSettings(localplayer->GetXboxPad(), eGameSetting_ViewBob) && + !localplayer->abilities.flying && !bNoLegAnim) + bobView(a); } // 4J - change brought forward from 1.8.2 -void GameRenderer::turnOffLightLayer(double alpha) -{ // 4J - TODO - // 4jcraft: manually handle this in order to ensure that the light layer is turned off correctly +void GameRenderer::turnOffLightLayer( + double alpha) { // 4J - TODO + // 4jcraft: manually handle this in order to ensure that + // the light layer is turned off correctly #if 1 - if (SharedConstants::TEXTURE_LIGHTING) - { + if (SharedConstants::TEXTURE_LIGHTING) { glClientActiveTexture(GL_TEXTURE1); glActiveTexture(GL_TEXTURE1); - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); glDisable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, 0); + glBindTexture(GL_TEXTURE_2D, 0); glClientActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE0); } #endif - //RenderManager.TextureBindVertex(-1); + // RenderManager.TextureBindVertex(-1); } // 4J - change brought forward from 1.8.2 -void GameRenderer::turnOnLightLayer(double alpha, bool scaleLight) -{ // 4J - TODO +void GameRenderer::turnOnLightLayer(double alpha, + bool scaleLight) { // 4J - TODO #if 0 if (SharedConstants::TEXTURE_LIGHTING) { @@ -854,9 +836,10 @@ void GameRenderer::turnOnLightLayer(double alpha, bool scaleLight) glActiveTexture(GL_TEXTURE0); } #endif - // update light texture - // todo: check implementation of getLightTexture. - RenderManager.TextureBindVertex(getLightTexture(mc->player->GetXboxPad(), mc->level), scaleLight); + // update light texture + // todo: check implementation of getLightTexture. + RenderManager.TextureBindVertex( + getLightTexture(mc->player->GetXboxPad(), mc->level), scaleLight); #if 0 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -866,10 +849,11 @@ void GameRenderer::turnOnLightLayer(double alpha, bool scaleLight) } // 4J - change brought forward from 1.8.2 -void GameRenderer::tickLightTexture() -{ - blrt += (float)((Math::random() - Math::random()) * Math::random() * Math::random()); - blgt += (float)((Math::random() - Math::random()) * Math::random() * Math::random()); +void GameRenderer::tickLightTexture() { + blrt += (float)((Math::random() - Math::random()) * Math::random() * + Math::random()); + blgt += (float)((Math::random() - Math::random()) * Math::random() * + Math::random()); blrt *= 0.9; blgt *= 0.9; blr += (blrt - blr) * 1; @@ -877,158 +861,147 @@ void GameRenderer::tickLightTexture() _updateLightTexture = true; } -void GameRenderer::updateLightTexture(float a) -{ - // 4J-JEV: Now doing light textures on PER PLAYER basis. - // 4J - we *had* added separate light textures for all dimensions, and this loop to update them all here - for(int j = 0; j < XUSER_MAX_COUNT; j++ ) - { - // Loop over all the players - std::shared_ptr player = Minecraft::GetInstance()->localplayers[j]; - if (player == NULL) continue; +void GameRenderer::updateLightTexture(float a) { + // 4J-JEV: Now doing light textures on PER PLAYER basis. + // 4J - we *had* added separate light textures for all dimensions, and this + // loop to update them all here + for (int j = 0; j < XUSER_MAX_COUNT; j++) { + // Loop over all the players + std::shared_ptr player = + Minecraft::GetInstance()->localplayers[j]; + if (player == NULL) continue; - Level *level = player->level; // 4J - was mc->level when it was just to update the one light texture - - float skyDarken1 = level->getSkyDarken((float) 1); - for (int i = 0; i < 256; i++) - { - float darken = skyDarken1 * 0.95f + 0.05f; - float sky = level->dimension->brightnessRamp[i / 16] * darken; - float block = level->dimension->brightnessRamp[i % 16] * (blr * 0.1f + 1.5f); + Level* level = player->level; // 4J - was mc->level when it was just to + // update the one light texture - if (level->lightningBoltTime > 0) - { - sky = level->dimension->brightnessRamp[i / 16]; - } + float skyDarken1 = level->getSkyDarken((float)1); + for (int i = 0; i < 256; i++) { + float darken = skyDarken1 * 0.95f + 0.05f; + float sky = level->dimension->brightnessRamp[i / 16] * darken; + float block = + level->dimension->brightnessRamp[i % 16] * (blr * 0.1f + 1.5f); - float rs = sky * (skyDarken1 * 0.65f + 0.35f); - float gs = sky * (skyDarken1 * 0.65f + 0.35f); - float bs = sky; + if (level->lightningBoltTime > 0) { + sky = level->dimension->brightnessRamp[i / 16]; + } - float rb = block; - float gb = block * ((block * 0.6f + 0.4f) * 0.6f + 0.4f); - float bb = block * ((block * block) * 0.6f + 0.4f); + float rs = sky * (skyDarken1 * 0.65f + 0.35f); + float gs = sky * (skyDarken1 * 0.65f + 0.35f); + float bs = sky; - float _r = (rs + rb); - float _g = (gs + gb); - float _b = (bs + bb); + float rb = block; + float gb = block * ((block * 0.6f + 0.4f) * 0.6f + 0.4f); + float bb = block * ((block * block) * 0.6f + 0.4f); - _r = _r * 0.96f + 0.03f; - _g = _g * 0.96f + 0.03f; - _b = _b * 0.96f + 0.03f; + float _r = (rs + rb); + float _g = (gs + gb); + float _b = (bs + bb); - if (level->dimension->id == 1) - { - _r = (0.22f + rb * 0.75f); - _g = (0.28f + gb * 0.75f); - _b = (0.25f + bb * 0.75f); - } + _r = _r * 0.96f + 0.03f; + _g = _g * 0.96f + 0.03f; + _b = _b * 0.96f + 0.03f; - if (player->hasEffect(MobEffect::nightVision)) - { - float scale = getNightVisionScale(player, a); - { - float dist = 1.0f / _r; - if (dist > (1.0f / _g)) - { - dist = (1.0f / _g); - } - if (dist > (1.0f / _b)) - { - dist = (1.0f / _b); - } - _r = _r * (1.0f - scale) + (_r * dist) * scale; - _g = _g * (1.0f - scale) + (_g * dist) * scale; - _b = _b * (1.0f - scale) + (_b * dist) * scale; - } - } + if (level->dimension->id == 1) { + _r = (0.22f + rb * 0.75f); + _g = (0.28f + gb * 0.75f); + _b = (0.25f + bb * 0.75f); + } - float brightness = 0.0f; // 4J - TODO - was mc->options->gamma; - if (_r > 1) _r = 1; - if (_g > 1) _g = 1; - if (_b > 1) _b = 1; + if (player->hasEffect(MobEffect::nightVision)) { + float scale = getNightVisionScale(player, a); + { + float dist = 1.0f / _r; + if (dist > (1.0f / _g)) { + dist = (1.0f / _g); + } + if (dist > (1.0f / _b)) { + dist = (1.0f / _b); + } + _r = _r * (1.0f - scale) + (_r * dist) * scale; + _g = _g * (1.0f - scale) + (_g * dist) * scale; + _b = _b * (1.0f - scale) + (_b * dist) * scale; + } + } - float ir = 1 - _r; - float ig = 1 - _g; - float ib = 1 - _b; - ir = 1 - (ir * ir * ir * ir); - ig = 1 - (ig * ig * ig * ig); - ib = 1 - (ib * ib * ib * ib); - _r = _r * (1 - brightness) + ir * brightness; - _g = _g * (1 - brightness) + ig * brightness; - _b = _b * (1 - brightness) + ib * brightness; + float brightness = 0.0f; // 4J - TODO - was mc->options->gamma; + if (_r > 1) _r = 1; + if (_g > 1) _g = 1; + if (_b > 1) _b = 1; + float ir = 1 - _r; + float ig = 1 - _g; + float ib = 1 - _b; + ir = 1 - (ir * ir * ir * ir); + ig = 1 - (ig * ig * ig * ig); + ib = 1 - (ib * ib * ib * ib); + _r = _r * (1 - brightness) + ir * brightness; + _g = _g * (1 - brightness) + ig * brightness; + _b = _b * (1 - brightness) + ib * brightness; - _r = _r * 0.96f + 0.03f; - _g = _g * 0.96f + 0.03f; - _b = _b * 0.96f + 0.03f; + _r = _r * 0.96f + 0.03f; + _g = _g * 0.96f + 0.03f; + _b = _b * 0.96f + 0.03f; + if (_r > 1) _r = 1; + if (_g > 1) _g = 1; + if (_b > 1) _b = 1; + if (_r < 0) _r = 0; + if (_g < 0) _g = 0; + if (_b < 0) _b = 0; - if (_r > 1) _r = 1; - if (_g > 1) _g = 1; - if (_b > 1) _b = 1; - if (_r < 0) _r = 0; - if (_g < 0) _g = 0; - if (_b < 0) _b = 0; + int a = 255; + int r = (int)(_r * 255); + int g = (int)(_g * 255); + int b = (int)(_b * 255); - int a = 255; - int r = (int) (_r * 255); - int g = (int) (_g * 255); - int b = (int) (_b * 255); - -#if ( defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__ ) - lightPixels[j][i] = a << 24 | b << 16 | g << 8 | r; -#elif ( defined _XBOX || defined __ORBIS__ ) - lightPixels[j][i] = a << 24 | r << 16 | g << 8 | b; +#if (defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__) + lightPixels[j][i] = a << 24 | b << 16 | g << 8 | r; +#elif (defined _XBOX || defined __ORBIS__) + lightPixels[j][i] = a << 24 | r << 16 | g << 8 | b; #else - lightPixels[j][i] = r << 24 | g << 16 | b << 8 | a; + lightPixels[j][i] = r << 24 | g << 16 | b << 8 | a; #endif - } + } - mc->textures->replaceTextureDirect( lightPixels[j], 16, 16, getLightTexture(j,level) ); - } + mc->textures->replaceTextureDirect(lightPixels[j], 16, 16, + getLightTexture(j, level)); + } } -float GameRenderer::getNightVisionScale(std::shared_ptr player, float a) -{ - int duration = player->getEffect(MobEffect::nightVision)->getDuration(); - if (duration > (SharedConstants::TICKS_PER_SECOND * 10)) - { - return 1.0f; - } - else - { - float flash = std::max(0.0f, (float)duration - a); - return .7f + Mth::sin(flash * PI * .05f) * .3f; // was: .7 + sin(flash*pi*0.2) * .3 - } +float GameRenderer::getNightVisionScale(std::shared_ptr player, + float a) { + int duration = player->getEffect(MobEffect::nightVision)->getDuration(); + if (duration > (SharedConstants::TICKS_PER_SECOND * 10)) { + return 1.0f; + } else { + float flash = std::max(0.0f, (float)duration - a); + return .7f + Mth::sin(flash * PI * .05f) * + .3f; // was: .7 + sin(flash*pi*0.2) * .3 + } } -// 4J added, so we can have a light texture for each player to support split screen -int GameRenderer::getLightTexture(int iPad, Level *level) -{ - // Turn the current dimenions id into an index from 0 to 2 - // int idx = level->dimension->id; - // if( idx == -1 ) idx = 2; +// 4J added, so we can have a light texture for each player to support split +// screen +int GameRenderer::getLightTexture(int iPad, Level* level) { + // Turn the current dimenions id into an index from 0 to 2 + // int idx = level->dimension->id; + // if( idx == -1 ) idx = 2; - return lightTexture[iPad]; // 4J-JEV: Changing to Per Player lighting textures. + return lightTexture[iPad]; // 4J-JEV: Changing to Per Player lighting + // textures. } -void GameRenderer::render(float a, bool bFirst) -{ - if( _updateLightTexture && bFirst) updateLightTexture(a); - if (Display::isActive()) - { - lastActiveTime = System::currentTimeMillis(); - } - else - { - if (System::currentTimeMillis() - lastActiveTime > 500) - { - mc->pauseGame(); - } - } +void GameRenderer::render(float a, bool bFirst) { + if (_updateLightTexture && bFirst) updateLightTexture(a); + if (Display::isActive()) { + lastActiveTime = System::currentTimeMillis(); + } else { + if (System::currentTimeMillis() - lastActiveTime > 500) { + mc->pauseGame(); + } + } -#if 0 // 4J - TODO +#if 0 // 4J - TODO if (mc->mouseGrabbed) { mc->mouseHandler.poll(); @@ -1066,579 +1039,585 @@ void GameRenderer::render(float a, bool bFirst) } #endif - if (mc->noRender) return; - GameRenderer::anaglyph3d = mc->options->anaglyph3d; + if (mc->noRender) return; + GameRenderer::anaglyph3d = mc->options->anaglyph3d; -{ - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - glViewport(0, 0, fbw, fbh); - ScreenSizeCalculator ssc(mc->options, mc->width, mc->height); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - int xMouse = Mouse::getX() * screenWidth / fbw; - int yMouse = screenHeight - Mouse::getY() * screenHeight / fbh - 1; + { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + glViewport(0, 0, fbw, fbh); + ScreenSizeCalculator ssc(mc->options, mc->width, mc->height); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + int xMouse = Mouse::getX() * screenWidth / fbw; + int yMouse = screenHeight - Mouse::getY() * screenHeight / fbh - 1; - int maxFps = getFpsCap(mc->options->framerateLimit); + int maxFps = getFpsCap(mc->options->framerateLimit); - if (mc->level != NULL) - { - if (maxFps == 0) - { - renderLevel(a, 0); - } - else - { - renderLevel(a, lastNsTime + 1000000000 / maxFps); - } + if (mc->level != NULL) { + if (maxFps == 0) { + renderLevel(a, 0); + } else { + renderLevel(a, lastNsTime + 1000000000 / maxFps); + } - lastNsTime = System::nanoTime(); + lastNsTime = System::nanoTime(); + if (!mc->options->hideGui || mc->screen != NULL) { + mc->gui->render(a, mc->screen != NULL, xMouse, yMouse); + } + } else { + { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + glViewport(0, 0, fbw, fbh); + } + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + setupGuiScreen(); - if (!mc->options->hideGui || mc->screen != NULL) - { - mc->gui->render(a, mc->screen != NULL, xMouse, yMouse); - } - } - else - { - { - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - glViewport(0, 0, fbw, fbh); - } - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - setupGuiScreen(); - - lastNsTime = System::nanoTime(); - } - - - if (mc->screen != NULL) - { - glClear(GL_DEPTH_BUFFER_BIT); - mc->screen->render(xMouse, yMouse, a); - if (mc->screen != NULL && mc->screen->particles != NULL) mc->screen->particles->render(a); - } + lastNsTime = System::nanoTime(); + } + if (mc->screen != NULL) { + glClear(GL_DEPTH_BUFFER_BIT); + mc->screen->render(xMouse, yMouse, a); + if (mc->screen != NULL && mc->screen->particles != NULL) + mc->screen->particles->render(a); + } + } } -} -void GameRenderer::renderLevel(float a) -{ - renderLevel(a, 0); -} +void GameRenderer::renderLevel(float a) { renderLevel(a, 0); } #ifdef MULTITHREAD_ENABLE // Request that an item be deleted, when it is safe to do so -void GameRenderer::AddForDelete(std::uint8_t *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackByte.push_back(deleteThis); +void GameRenderer::AddForDelete(std::uint8_t* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackByte.push_back(deleteThis); } -void GameRenderer::AddForDelete(SparseLightStorage *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackSparseLightStorage.push_back(deleteThis); +void GameRenderer::AddForDelete(SparseLightStorage* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackSparseLightStorage.push_back(deleteThis); } -void GameRenderer::AddForDelete(CompressedTileStorage *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackCompressedTileStorage.push_back(deleteThis); +void GameRenderer::AddForDelete(CompressedTileStorage* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackCompressedTileStorage.push_back(deleteThis); } -void GameRenderer::AddForDelete(SparseDataStorage *deleteThis) -{ - EnterCriticalSection(&m_csDeleteStack); - m_deleteStackSparseDataStorage.push_back(deleteThis); +void GameRenderer::AddForDelete(SparseDataStorage* deleteThis) { + EnterCriticalSection(&m_csDeleteStack); + m_deleteStackSparseDataStorage.push_back(deleteThis); } -void GameRenderer::FinishedReassigning() -{ - LeaveCriticalSection(&m_csDeleteStack); +void GameRenderer::FinishedReassigning() { + LeaveCriticalSection(&m_csDeleteStack); } -int GameRenderer::runUpdate(void *lpParam) -{ - Minecraft *minecraft = Minecraft::GetInstance(); - Vec3::CreateNewThreadStorage(); - AABB::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - Tesselator::CreateNewThreadStorage(1024*1024); - Compression::UseDefaultThreadStorage(); - RenderManager.InitialiseContext(); +int GameRenderer::runUpdate(void* lpParam) { + Minecraft* minecraft = Minecraft::GetInstance(); + Vec3::CreateNewThreadStorage(); + AABB::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Tesselator::CreateNewThreadStorage(1024 * 1024); + Compression::UseDefaultThreadStorage(); + RenderManager.InitialiseContext(); #ifdef _LARGE_WORLDS - Chunk::CreateNewThreadStorage(); + Chunk::CreateNewThreadStorage(); #endif - Tile::CreateNewThreadStorage(); + Tile::CreateNewThreadStorage(); - ShutdownManager::HasStarted(ShutdownManager::eRenderChunkUpdateThread,m_updateEvents); - while(ShutdownManager::ShouldRun(ShutdownManager::eRenderChunkUpdateThread)) - { - //m_updateEvents->Clear(eUpdateEventIsFinished); - //m_updateEvents->WaitForSingle(eUpdateCanRun,INFINITE); - // 4J Stu - We Need to have this happen atomically to avoid deadlocks - m_updateEvents->WaitForAll(INFINITE); + ShutdownManager::HasStarted(ShutdownManager::eRenderChunkUpdateThread, + m_updateEvents); + while ( + ShutdownManager::ShouldRun(ShutdownManager::eRenderChunkUpdateThread)) { + // m_updateEvents->Clear(eUpdateEventIsFinished); + // m_updateEvents->WaitForSingle(eUpdateCanRun,INFINITE); + // 4J Stu - We Need to have this happen atomically to avoid deadlocks + m_updateEvents->WaitForAll(INFINITE); - if( !ShutdownManager::ShouldRun(ShutdownManager::eRenderChunkUpdateThread) ) - { - break; - } + if (!ShutdownManager::ShouldRun( + ShutdownManager::eRenderChunkUpdateThread)) { + break; + } - m_updateEvents->Set(eUpdateCanRun); + m_updateEvents->Set(eUpdateCanRun); -// PIXBeginNamedEvent(0,"Updating dirty chunks %d",(count++)&7); + // PIXBeginNamedEvent(0,"Updating dirty chunks + //%d",(count++)&7); - // Update chunks atomically until there aren't any very near ones left - they will be deferred for rendering - // until the call to CBuffDeferredModeEnd if we have anything near to render here - // Now limiting maximum number of updates that can be deferred as have noticed that with redstone clock circuits, it is possible to create - // things that need constant updating, so if you stand near them, the render data Never gets updated and the game just keeps going until it runs out of render memory... - int count = 0; - static const int MAX_DEFERRED_UPDATES = 10; - bool shouldContinue = false; - do - { - shouldContinue = minecraft->levelRenderer->updateDirtyChunks(); - count++; - } while ( shouldContinue && count < MAX_DEFERRED_UPDATES ); + // Update chunks atomically until there aren't any very near ones left - + // they will be deferred for rendering until the call to + // CBuffDeferredModeEnd if we have anything near to render here Now + // limiting maximum number of updates that can be deferred as have + // noticed that with redstone clock circuits, it is possible to create + // things that need constant updating, so if you stand near them, the + // render data Never gets updated and the game just keeps going until it + // runs out of render memory... + int count = 0; + static const int MAX_DEFERRED_UPDATES = 10; + bool shouldContinue = false; + do { + shouldContinue = minecraft->levelRenderer->updateDirtyChunks(); + count++; + } while (shouldContinue && count < MAX_DEFERRED_UPDATES); -// while( minecraft->levelRenderer->updateDirtyChunks() ) -// ; - RenderManager.CBuffDeferredModeEnd(); + // while( minecraft->levelRenderer->updateDirtyChunks() ) + // ; + RenderManager.CBuffDeferredModeEnd(); - // If any renderable tile entities were flagged in this last block of chunk(s) that were udpated, then change their - // flags to say that this deferred chunk is over and they are actually safe to be removed now - minecraft->levelRenderer->fullyFlagRenderableTileEntitiesToBeRemoved(); + // If any renderable tile entities were flagged in this last block of + // chunk(s) that were udpated, then change their flags to say that this + // deferred chunk is over and they are actually safe to be removed now + minecraft->levelRenderer->fullyFlagRenderableTileEntitiesToBeRemoved(); - // We've got stacks for things that can only safely be deleted whilst this thread isn't updating things - delete those things now - EnterCriticalSection(&m_csDeleteStack); - for(unsigned int i = 0; i < m_deleteStackByte.size(); i++ ) - { - delete m_deleteStackByte[i]; - } - m_deleteStackByte.clear(); - for(unsigned int i = 0; i < m_deleteStackSparseLightStorage.size(); i++ ) - { - delete m_deleteStackSparseLightStorage[i]; - } - m_deleteStackSparseLightStorage.clear(); - for(unsigned int i = 0; i < m_deleteStackCompressedTileStorage.size(); i++ ) - { - delete m_deleteStackCompressedTileStorage[i]; - } - m_deleteStackCompressedTileStorage.clear(); - for(unsigned int i = 0; i < m_deleteStackSparseDataStorage.size(); i++ ) - { - delete m_deleteStackSparseDataStorage[i]; - } - m_deleteStackSparseDataStorage.clear(); - LeaveCriticalSection(&m_csDeleteStack); - -// PIXEndNamedEvent(); + // We've got stacks for things that can only safely be deleted whilst + // this thread isn't updating things - delete those things now + EnterCriticalSection(&m_csDeleteStack); + for (unsigned int i = 0; i < m_deleteStackByte.size(); i++) { + delete m_deleteStackByte[i]; + } + m_deleteStackByte.clear(); + for (unsigned int i = 0; i < m_deleteStackSparseLightStorage.size(); + i++) { + delete m_deleteStackSparseLightStorage[i]; + } + m_deleteStackSparseLightStorage.clear(); + for (unsigned int i = 0; i < m_deleteStackCompressedTileStorage.size(); + i++) { + delete m_deleteStackCompressedTileStorage[i]; + } + m_deleteStackCompressedTileStorage.clear(); + for (unsigned int i = 0; i < m_deleteStackSparseDataStorage.size(); + i++) { + delete m_deleteStackSparseDataStorage[i]; + } + m_deleteStackSparseDataStorage.clear(); + LeaveCriticalSection(&m_csDeleteStack); - AABB::resetPool(); - Vec3::resetPool(); - IntCache::Reset(); - m_updateEvents->Set(eUpdateEventIsFinished); - } + // PIXEndNamedEvent(); - ShutdownManager::HasFinished(ShutdownManager::eRenderChunkUpdateThread); - return 0; + AABB::resetPool(); + Vec3::resetPool(); + IntCache::Reset(); + m_updateEvents->Set(eUpdateEventIsFinished); + } + + ShutdownManager::HasFinished(ShutdownManager::eRenderChunkUpdateThread); + return 0; } #endif -void GameRenderer::EnableUpdateThread() -{ +void GameRenderer::EnableUpdateThread() { // #ifdef __PS3__ // MGH - disable the update on PS3 for now // return; // #endif #ifdef MULTITHREAD_ENABLE - if( updateRunning) return; - app.DebugPrintf("------------------EnableUpdateThread--------------------\n"); - updateRunning = true; - m_updateEvents->Set(eUpdateCanRun); - m_updateEvents->Set(eUpdateEventIsFinished); + if (updateRunning) return; + app.DebugPrintf( + "------------------EnableUpdateThread--------------------\n"); + updateRunning = true; + m_updateEvents->Set(eUpdateCanRun); + m_updateEvents->Set(eUpdateEventIsFinished); #endif } -void GameRenderer::DisableUpdateThread() -{ +void GameRenderer::DisableUpdateThread() { // #ifdef __PS3__ // MGH - disable the update on PS3 for now // return; // #endif #ifdef MULTITHREAD_ENABLE - if( !updateRunning) return; - app.DebugPrintf("------------------DisableUpdateThread--------------------\n"); - updateRunning = false; - m_updateEvents->Clear(eUpdateCanRun); - m_updateEvents->WaitForSingle(eUpdateEventIsFinished,INFINITE); + if (!updateRunning) return; + app.DebugPrintf( + "------------------DisableUpdateThread--------------------\n"); + updateRunning = false; + m_updateEvents->Clear(eUpdateCanRun); + m_updateEvents->WaitForSingle(eUpdateEventIsFinished, INFINITE); #endif } -void GameRenderer::renderLevel(float a, __int64 until) -{ -// if (updateLightTexture) updateLightTexture(); // 4J - TODO - Java 1.0.1 has this line enabled, should check why - don't want to put it in now in case it breaks split-screen +void GameRenderer::renderLevel(float a, __int64 until) { + // if (updateLightTexture) updateLightTexture(); // 4J - TODO - + //Java 1.0.1 has this line enabled, should check why - don't want to put it + //in now in case it breaks split-screen - glEnable(GL_CULL_FACE); - glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_DEPTH_TEST); - // Is this the primary player? Only do the updating of chunks if it is. This controls the creation of render data for each chunk - all of this we are only - // going to do for the primary player, and the other players can just view whatever they have loaded in - we're sharing render data between players. - bool updateChunks = ( mc->player == mc->localplayers[ProfileManager.GetPrimaryPad()] ); + // Is this the primary player? Only do the updating of chunks if it is. This + // controls the creation of render data for each chunk - all of this we are + // only going to do for the primary player, and the other players can just + // view whatever they have loaded in - we're sharing render data between + // players. + bool updateChunks = + (mc->player == mc->localplayers[ProfileManager.GetPrimaryPad()]); -// if (mc->cameraTargetPlayer == NULL) // 4J - removed condition as we want to update this is mc->player changes for different local players - { - mc->cameraTargetPlayer = mc->player; - } - pick(a); + // if (mc->cameraTargetPlayer == NULL) // 4J - removed condition as we + //want to update this is mc->player changes for different local players + { + mc->cameraTargetPlayer = mc->player; + } + pick(a); - std::shared_ptr cameraEntity = mc->cameraTargetPlayer; - LevelRenderer *levelRenderer = mc->levelRenderer; - ParticleEngine *particleEngine = mc->particleEngine; - double xOff = cameraEntity->xOld + (cameraEntity->x - cameraEntity->xOld) * a; - double yOff = cameraEntity->yOld + (cameraEntity->y - cameraEntity->yOld) * a; - double zOff = cameraEntity->zOld + (cameraEntity->z - cameraEntity->zOld) * a; + std::shared_ptr cameraEntity = mc->cameraTargetPlayer; + LevelRenderer* levelRenderer = mc->levelRenderer; + ParticleEngine* particleEngine = mc->particleEngine; + double xOff = + cameraEntity->xOld + (cameraEntity->x - cameraEntity->xOld) * a; + double yOff = + cameraEntity->yOld + (cameraEntity->y - cameraEntity->yOld) * a; + double zOff = + cameraEntity->zOld + (cameraEntity->z - cameraEntity->zOld) * a; - for (int i = 0; i < 2; i++) - { - if (mc->options->anaglyph3d) - { - GameRenderer::anaglyphPass = i; - if (GameRenderer::anaglyphPass == 0) glColorMask(false, true, true, false); - else glColorMask(true, false, false, false); - } + for (int i = 0; i < 2; i++) { + if (mc->options->anaglyph3d) { + GameRenderer::anaglyphPass = i; + if (GameRenderer::anaglyphPass == 0) + glColorMask(false, true, true, false); + else + glColorMask(true, false, false, false); + } + { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + glViewport(0, 0, fbw, fbh); + } + setupClearColor(a); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glEnable(GL_CULL_FACE); - { - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - glViewport(0, 0, fbw, fbh); - } - setupClearColor(a); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glEnable(GL_CULL_FACE); + setupCamera(a, i); + Camera::prepare(mc->player, mc->player->ThirdPersonView() == 2); - setupCamera(a, i); - Camera::prepare(mc->player, mc->player->ThirdPersonView() == 2); + Frustum::getFrustum(); + if (mc->options->viewDistance < 2) { + setupFog(-1, a); + levelRenderer->renderSky(a); + if (mc->skins->getSelected()->getId() == 1026) + levelRenderer->renderHaloRing(a); + } + // 4jcraft: needs to be enabled for proper transparent texturing on low + // render dists this was done in renderSky() for the far and normal + // dists but was missing here, UPDATE: Also needed for the nether, so + // just enable it unconditionally + glEnable(GL_ALPHA_TEST); + glEnable(GL_FOG); + setupFog(1, a); - Frustum::getFrustum(); - if (mc->options->viewDistance < 2) - { - setupFog(-1, a); - levelRenderer->renderSky(a); - if(mc->skins->getSelected()->getId() == 1026 ) levelRenderer->renderHaloRing(a); - } - // 4jcraft: needs to be enabled for proper transparent texturing on low render dists - // this was done in renderSky() for the far and normal dists but was missing here, - // UPDATE: Also needed for the nether, so just enable it unconditionally - glEnable(GL_ALPHA_TEST); - glEnable(GL_FOG); - setupFog(1, a); + if (mc->options->ambientOcclusion) { + GL11::glShadeModel(GL11::GL_SMOOTH); + } - if (mc->options->ambientOcclusion) - { - GL11::glShadeModel(GL11::GL_SMOOTH); - } + PIXBeginNamedEvent(0, "Culling"); + MemSect(31); + // Culler *frustum = new FrustumCuller(); + FrustumCuller frustObj; + Culler* frustum = &frustObj; + MemSect(0); + frustum->prepare(xOff, yOff, zOff); - PIXBeginNamedEvent(0,"Culling"); - MemSect(31); -// Culler *frustum = new FrustumCuller(); - FrustumCuller frustObj; - Culler *frustum = &frustObj; - MemSect(0); - frustum->prepare(xOff, yOff, zOff); - - mc->levelRenderer->cull(frustum, a); - PIXEndNamedEvent(); + mc->levelRenderer->cull(frustum, a); + PIXEndNamedEvent(); #ifndef MULTITHREAD_ENABLE - if ( (i == 0) && updateChunks ) // 4J - added updateChunks condition - { - int PIXPass = 0; - PIXBeginNamedEvent(0,"Updating dirty chunks"); - do - { - PIXBeginNamedEvent(0,"Updating dirty chunks pass %d",PIXPass++); - bool retval = mc->levelRenderer->updateDirtyChunks(cameraEntity, false); - PIXEndNamedEvent(); - if( retval ) break; + if ((i == 0) && updateChunks) // 4J - added updateChunks condition + { + int PIXPass = 0; + PIXBeginNamedEvent(0, "Updating dirty chunks"); + do { + PIXBeginNamedEvent(0, "Updating dirty chunks pass %d", + PIXPass++); + bool retval = + mc->levelRenderer->updateDirtyChunks(cameraEntity, false); + PIXEndNamedEvent(); + if (retval) break; + if (until == 0) break; - if (until == 0) break; - - __int64 diff = until - System::nanoTime(); - if (diff < 0) break; - if (diff > 1000000000) break; - } while (true); - PIXEndNamedEvent(); - } + __int64 diff = until - System::nanoTime(); + if (diff < 0) break; + if (diff > 1000000000) break; + } while (true); + PIXEndNamedEvent(); + } #endif - setupFog(0, a); - glEnable(GL_FOG); - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - Lighting::turnOff(); - PIXBeginNamedEvent(0,"Level render"); - levelRenderer->render(cameraEntity, 0, a, updateChunks); - PIXEndNamedEvent(); + setupFog(0, a); + glEnable(GL_FOG); + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + Lighting::turnOff(); + PIXBeginNamedEvent(0, "Level render"); + levelRenderer->render(cameraEntity, 0, a, updateChunks); + PIXEndNamedEvent(); - GL11::glShadeModel(GL11::GL_FLAT); + GL11::glShadeModel(GL11::GL_FLAT); - if (cameraFlip == 0 ) - { - Lighting::turnOn(); - PIXBeginNamedEvent(0,"Entity render"); - // 4J - for entities, don't include the "a" factor that interpolates from the old to new position, as the AABBs for the entities are already fully at the new position - // This fixes flickering minecarts, and pigs that you are riding on - frustum->prepare(cameraEntity->x,cameraEntity->y,cameraEntity->z); - // 4J Stu - When rendering entities, in the end if the dragon is hurt or we have a lot of entities we can end up wrapping - // our index into the temp Vec3 cache and overwrite the one that was storing the camera position - // Fix for #77745 - TU9: Content: Gameplay: Items and mobs not belonging to end world are disappearing when Enderdragon is damaged. - Vec3 *cameraPosTemp = cameraEntity->getPos(a); - cameraPos->x = cameraPosTemp->x; - cameraPos->y = cameraPosTemp->y; - cameraPos->z = cameraPosTemp->z; - levelRenderer->renderEntities(cameraPos, frustum, a); + if (cameraFlip == 0) { + Lighting::turnOn(); + PIXBeginNamedEvent(0, "Entity render"); + // 4J - for entities, don't include the "a" factor that interpolates + // from the old to new position, as the AABBs for the entities are + // already fully at the new position This fixes flickering + // minecarts, and pigs that you are riding on + frustum->prepare(cameraEntity->x, cameraEntity->y, cameraEntity->z); + // 4J Stu - When rendering entities, in the end if the dragon is + // hurt or we have a lot of entities we can end up wrapping our + // index into the temp Vec3 cache and overwrite the one that was + // storing the camera position Fix for #77745 - TU9: Content: + // Gameplay: Items and mobs not belonging to end world are + // disappearing when Enderdragon is damaged. + Vec3* cameraPosTemp = cameraEntity->getPos(a); + cameraPos->x = cameraPosTemp->x; + cameraPos->y = cameraPosTemp->y; + cameraPos->z = cameraPosTemp->z; + levelRenderer->renderEntities(cameraPos, frustum, a); #ifdef __PSVITA__ - // AP - make sure we're using the Alpha cut out effect for particles - glEnable(GL_ALPHA_TEST); + // AP - make sure we're using the Alpha cut out effect for particles + glEnable(GL_ALPHA_TEST); #endif - PIXEndNamedEvent(); - PIXBeginNamedEvent(0,"Particle render"); - turnOnLightLayer(a); // 4J - brought forward from 1.8.2 - particleEngine->renderLit(cameraEntity, a); - Lighting::turnOff(); - setupFog(0, a); - particleEngine->render(cameraEntity, a); - PIXEndNamedEvent(); - turnOffLightLayer(a); // 4J - brought forward from 1.8.2 + PIXEndNamedEvent(); + PIXBeginNamedEvent(0, "Particle render"); + turnOnLightLayer(a); // 4J - brought forward from 1.8.2 + particleEngine->renderLit(cameraEntity, a); + Lighting::turnOff(); + setupFog(0, a); + particleEngine->render(cameraEntity, a); + PIXEndNamedEvent(); + turnOffLightLayer(a); // 4J - brought forward from 1.8.2 - std::shared_ptr player = std::dynamic_pointer_cast(cameraEntity); - if (mc->hitResult != NULL && cameraEntity->isUnderLiquid(Material::water) && player!=NULL) //&& !mc->options.hideGui) - { - //std::shared_ptr player = std::dynamic_pointer_cast(cameraEntity); - glDisable(GL_ALPHA_TEST); - levelRenderer->renderHit(player, mc->hitResult, 0, player->inventory->getSelected(), a); - levelRenderer->renderHitOutline(player, mc->hitResult, 0, player->inventory->getSelected(), a); - glEnable(GL_ALPHA_TEST); - } - } + std::shared_ptr player = + std::dynamic_pointer_cast(cameraEntity); + if (mc->hitResult != NULL && + cameraEntity->isUnderLiquid(Material::water) && + player != NULL) //&& !mc->options.hideGui) + { + // std::shared_ptr player = + // std::dynamic_pointer_cast(cameraEntity); + glDisable(GL_ALPHA_TEST); + levelRenderer->renderHit(player, mc->hitResult, 0, + player->inventory->getSelected(), a); + levelRenderer->renderHitOutline( + player, mc->hitResult, 0, player->inventory->getSelected(), + a); + glEnable(GL_ALPHA_TEST); + } + } glDisable(GL_BLEND); glEnable(GL_CULL_FACE); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask(true); - setupFog(0, a); - glEnable(GL_BLEND); - glDisable(GL_CULL_FACE); - MemSect(31); - mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - MemSect(0); - // 4J - have changed this fancy rendering option to work with our command buffers. The original used to use frame buffer flags to disable - // writing to colour when doing the z-only pass, but that value gets obliterated by our command buffers. Using alpha blend function instead - // to achieve the same effect. - if (true) // (mc->options->fancyGraphics) - { - if (mc->options->ambientOcclusion) - { - GL11::glShadeModel(GL11::GL_SMOOTH); - } + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDepthMask(true); + setupFog(0, a); + glEnable(GL_BLEND); + glDisable(GL_CULL_FACE); + MemSect(31); + mc->textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + MemSect(0); + // 4J - have changed this fancy rendering option to work with our + // command buffers. The original used to use frame buffer flags to + // disable writing to colour when doing the z-only pass, but that value + // gets obliterated by our command buffers. Using alpha blend function + // instead to achieve the same effect. + if (true) // (mc->options->fancyGraphics) + { + if (mc->options->ambientOcclusion) { + GL11::glShadeModel(GL11::GL_SMOOTH); + } - glBlendFunc(GL_ZERO, GL_ONE); - PIXBeginNamedEvent(0,"Fancy second pass - writing z"); - int visibleWaterChunks = levelRenderer->render(cameraEntity, 1, a, updateChunks); - PIXEndNamedEvent(); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_ZERO, GL_ONE); + PIXBeginNamedEvent(0, "Fancy second pass - writing z"); + int visibleWaterChunks = + levelRenderer->render(cameraEntity, 1, a, updateChunks); + PIXEndNamedEvent(); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - if (visibleWaterChunks > 0) - { - PIXBeginNamedEvent(0,"Fancy second pass - actual rendering"); - levelRenderer->render(cameraEntity, 1, a, updateChunks); // 4J - chanaged, used to be renderSameAsLast but we don't support that anymore - PIXEndNamedEvent(); - } + if (visibleWaterChunks > 0) { + PIXBeginNamedEvent(0, "Fancy second pass - actual rendering"); + levelRenderer->render( + cameraEntity, 1, a, + updateChunks); // 4J - chanaged, used to be + // renderSameAsLast but we don't support + // that anymore + PIXEndNamedEvent(); + } - GL11::glShadeModel(GL11::GL_FLAT); - } - else - { - PIXBeginNamedEvent(0,"Second pass level render"); - levelRenderer->render(cameraEntity, 1, a, updateChunks); - PIXEndNamedEvent(); - } + GL11::glShadeModel(GL11::GL_FLAT); + } else { + PIXBeginNamedEvent(0, "Second pass level render"); + levelRenderer->render(cameraEntity, 1, a, updateChunks); + PIXEndNamedEvent(); + } + glDepthMask(true); + glEnable(GL_CULL_FACE); + glDisable(GL_BLEND); - glDepthMask(true); - glEnable(GL_CULL_FACE); - glDisable(GL_BLEND); + if (zoom == 1 && (std::dynamic_pointer_cast(cameraEntity) != + NULL)) //&& !mc->options.hideGui) + { + if (mc->hitResult != NULL && + !cameraEntity->isUnderLiquid(Material::water)) { + std::shared_ptr player = + std::dynamic_pointer_cast(cameraEntity); + glDisable(GL_ALPHA_TEST); + levelRenderer->renderHit(player, mc->hitResult, 0, + player->inventory->getSelected(), a); + levelRenderer->renderHitOutline( + player, mc->hitResult, 0, player->inventory->getSelected(), + a); + glEnable(GL_ALPHA_TEST); + } + } - if (zoom == 1 && (std::dynamic_pointer_cast(cameraEntity)!=NULL)) //&& !mc->options.hideGui) - { - if (mc->hitResult != NULL && !cameraEntity->isUnderLiquid(Material::water)) - { - std::shared_ptr player = std::dynamic_pointer_cast(cameraEntity); - glDisable(GL_ALPHA_TEST); - levelRenderer->renderHit(player, mc->hitResult, 0, player->inventory->getSelected(), a); - levelRenderer->renderHitOutline(player, mc->hitResult, 0, player->inventory->getSelected(), a); - glEnable(GL_ALPHA_TEST); - } - } + /* 4J - moved rain rendering to after clouds so that it alpha blends + onto them properly PIXBeginNamedEvent(0,"Rendering snow and rain"); + renderSnowAndRain(a); + PIXEndNamedEvent(); + glDisable(GL_FOG); + */ - /* 4J - moved rain rendering to after clouds so that it alpha blends onto them properly - PIXBeginNamedEvent(0,"Rendering snow and rain"); - renderSnowAndRain(a); - PIXEndNamedEvent(); - glDisable(GL_FOG); - */ + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + levelRenderer->renderDestroyAnimation( + Tesselator::getInstance(), + std::dynamic_pointer_cast(cameraEntity), a); + glDisable(GL_BLEND); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - levelRenderer->renderDestroyAnimation(Tesselator::getInstance(), std::dynamic_pointer_cast(cameraEntity), a); - glDisable(GL_BLEND); + if (mc->options->isCloudsOn()) { + glPushMatrix(); + setupFog(0, a); + glEnable(GL_FOG); + PIXBeginNamedEvent(0, "Rendering clouds"); + levelRenderer->renderClouds(a); + PIXEndNamedEvent(); + glDisable(GL_FOG); + setupFog(1, a); + glPopMatrix(); + } - if (mc->options->isCloudsOn()) - { - glPushMatrix(); - setupFog(0, a); - glEnable(GL_FOG); - PIXBeginNamedEvent(0,"Rendering clouds"); - levelRenderer->renderClouds(a); - PIXEndNamedEvent(); - glDisable(GL_FOG); - setupFog(1, a); - glPopMatrix(); - } + // 4J - rain rendering moved here so that it renders after clouds & can + // blend properly onto them + setupFog(0, a); + glEnable(GL_FOG); + PIXBeginNamedEvent(0, "Rendering snow and rain"); + renderSnowAndRain(a); + PIXEndNamedEvent(); + glDisable(GL_FOG); - // 4J - rain rendering moved here so that it renders after clouds & can blend properly onto them - setupFog(0, a); - glEnable(GL_FOG); - PIXBeginNamedEvent(0,"Rendering snow and rain"); - renderSnowAndRain(a); - PIXEndNamedEvent(); - glDisable(GL_FOG); + if (zoom == 1) { + glClear(GL_DEPTH_BUFFER_BIT); + renderItemInHand(a, i); + } - - if (zoom == 1) - { - glClear(GL_DEPTH_BUFFER_BIT); - renderItemInHand(a, i); - } - - - if (!mc->options->anaglyph3d) - { - return; - } - } - glColorMask(true, true, true, false); + if (!mc->options->anaglyph3d) { + return; + } + } + glColorMask(true, true, true, false); } -void GameRenderer::tickRain() -{ - float rainLevel = mc->level->getRainLevel(1); +void GameRenderer::tickRain() { + float rainLevel = mc->level->getRainLevel(1); - if (!mc->options->fancyGraphics) rainLevel /= 2; - if (rainLevel == 0) return; + if (!mc->options->fancyGraphics) rainLevel /= 2; + if (rainLevel == 0) return; - rainLevel /= ( mc->levelRenderer->activePlayers() + 1 ); + rainLevel /= (mc->levelRenderer->activePlayers() + 1); - random->setSeed(_tick * 312987231l); - std::shared_ptr player = mc->cameraTargetPlayer; - Level *level = mc->level; + random->setSeed(_tick * 312987231l); + std::shared_ptr player = mc->cameraTargetPlayer; + Level* level = mc->level; - int x0 = Mth::floor(player->x); - int y0 = Mth::floor(player->y); - int z0 = Mth::floor(player->z); + int x0 = Mth::floor(player->x); + int y0 = Mth::floor(player->y); + int z0 = Mth::floor(player->z); - int r = 10; + int r = 10; - double rainPosX = 0; - double rainPosY = 0; - double rainPosZ = 0; - int rainPosSamples = 0; + double rainPosX = 0; + double rainPosY = 0; + double rainPosZ = 0; + int rainPosSamples = 0; - int rainCount = (int) (100 * rainLevel * rainLevel); - if (mc->options->particles == 1) - { + int rainCount = (int)(100 * rainLevel * rainLevel); + if (mc->options->particles == 1) { rainCount >>= 1; - } else if (mc->options->particles == 2) - { + } else if (mc->options->particles == 2) { rainCount = 0; } - for (int i = 0; i < rainCount; i++) - { - int x = x0 + random->nextInt(r) - random->nextInt(r); - int z = z0 + random->nextInt(r) - random->nextInt(r); - int y = level->getTopRainBlock(x, z); - int t = level->getTile(x, y - 1, z); - Biome *biome = level->getBiome(x,z); - if (y <= y0 + r && y >= y0 - r && biome->hasRain() && biome->getTemperature() >= 0.2f) - { - float xa = random->nextFloat(); - float za = random->nextFloat(); - if (t > 0) - { - if (Tile::tiles[t]->material == Material::lava) - { - mc->particleEngine->add( std::shared_ptr( new SmokeParticle(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za, 0, 0, 0) ) ); - } - else - { - if (random->nextInt(++rainPosSamples) == 0) - { - rainPosX = x + xa; - rainPosY = y + 0.1f - Tile::tiles[t]->getShapeY0(); - rainPosZ = z + za; - } - mc->particleEngine->add( std::shared_ptr( new WaterDropParticle(level, x + xa, y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za) ) ); - } - } - } - } - - - if (rainPosSamples > 0 && random->nextInt(3) < rainSoundTime++) - { - rainSoundTime = 0; - MemSect(24); - if (rainPosY > player->y + 1 && level->getTopRainBlock(Mth::floor(player->x), Mth::floor(player->z)) > Mth::floor(player->y)) - { - mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, eSoundType_AMBIENT_WEATHER_RAIN, 0.1f, 0.5f); - } - else - { - mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, eSoundType_AMBIENT_WEATHER_RAIN, 0.2f, 1.0f); - } - MemSect(0); - } + for (int i = 0; i < rainCount; i++) { + int x = x0 + random->nextInt(r) - random->nextInt(r); + int z = z0 + random->nextInt(r) - random->nextInt(r); + int y = level->getTopRainBlock(x, z); + int t = level->getTile(x, y - 1, z); + Biome* biome = level->getBiome(x, z); + if (y <= y0 + r && y >= y0 - r && biome->hasRain() && + biome->getTemperature() >= 0.2f) { + float xa = random->nextFloat(); + float za = random->nextFloat(); + if (t > 0) { + if (Tile::tiles[t]->material == Material::lava) { + mc->particleEngine->add( + std::shared_ptr(new SmokeParticle( + level, x + xa, + y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za, 0, + 0, 0))); + } else { + if (random->nextInt(++rainPosSamples) == 0) { + rainPosX = x + xa; + rainPosY = y + 0.1f - Tile::tiles[t]->getShapeY0(); + rainPosZ = z + za; + } + mc->particleEngine->add(std::shared_ptr( + new WaterDropParticle( + level, x + xa, + y + 0.1f - Tile::tiles[t]->getShapeY0(), z + za))); + } + } + } + } + if (rainPosSamples > 0 && random->nextInt(3) < rainSoundTime++) { + rainSoundTime = 0; + MemSect(24); + if (rainPosY > player->y + 1 && + level->getTopRainBlock(Mth::floor(player->x), + Mth::floor(player->z)) > + Mth::floor(player->y)) { + mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, + eSoundType_AMBIENT_WEATHER_RAIN, 0.1f, + 0.5f); + } else { + mc->level->playLocalSound(rainPosX, rainPosY, rainPosZ, + eSoundType_AMBIENT_WEATHER_RAIN, 0.2f, + 1.0f); + } + MemSect(0); + } } // 4J - this whole function updated from 1.8.2 -void GameRenderer::renderSnowAndRain(float a) -{ - float rainLevel = mc->level->getRainLevel(a); - if (rainLevel <= 0) return; +void GameRenderer::renderSnowAndRain(float a) { + float rainLevel = mc->level->getRainLevel(a); + if (rainLevel <= 0) return; - // 4J - rain is relatively low poly, but high fill-rate - better to clip it - RenderManager.StateSetEnableViewportClipPlanes(true); + // 4J - rain is relatively low poly, but high fill-rate - better to clip it + RenderManager.StateSetEnableViewportClipPlanes(true); - this->turnOnLightLayer(a); + this->turnOnLightLayer(a); - if (rainXa == NULL) - { + if (rainXa == NULL) { rainXa = new float[32 * 32]; rainZa = new float[32 * 32]; - for (int z = 0; z < 32; z++) - { - for (int x = 0; x < 32; x++) - { + for (int z = 0; z < 32; z++) { + for (int x = 0; x < 32; x++) { float xa = x - 16; float za = z - 16; float d = Mth::sqrt(xa * xa + za * za); @@ -1648,218 +1627,236 @@ void GameRenderer::renderSnowAndRain(float a) } } - std::shared_ptr player = mc->cameraTargetPlayer; - Level *level = mc->level; + std::shared_ptr player = mc->cameraTargetPlayer; + Level* level = mc->level; - int x0 = Mth::floor(player->x); - int y0 = Mth::floor(player->y); - int z0 = Mth::floor(player->z); + int x0 = Mth::floor(player->x); + int y0 = Mth::floor(player->y); + int z0 = Mth::floor(player->z); - Tesselator *t = Tesselator::getInstance(); - glDisable(GL_CULL_FACE); - glNormal3f(0, 1, 0); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glAlphaFunc(GL_GREATER, 0.01f); + Tesselator* t = Tesselator::getInstance(); + glDisable(GL_CULL_FACE); + glNormal3f(0, 1, 0); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glAlphaFunc(GL_GREATER, 0.01f); - MemSect(31); - mc->textures->bindTexture(TN_ENVIRONMENT_SNOW); // 4J was L"/environment/snow.png" - MemSect(0); + MemSect(31); + mc->textures->bindTexture( + TN_ENVIRONMENT_SNOW); // 4J was L"/environment/snow.png" + MemSect(0); - double xo = player->xOld + (player->x - player->xOld) * a; - double yo = player->yOld + (player->y - player->yOld) * a; - double zo = player->zOld + (player->z - player->zOld) * a; + double xo = player->xOld + (player->x - player->xOld) * a; + double yo = player->yOld + (player->y - player->yOld) * a; + double zo = player->zOld + (player->z - player->zOld) * a; - int yMin = Mth::floor(yo); + int yMin = Mth::floor(yo); + int r = 5; + // 4J - was if(mc.options.fancyGraphics) r = 10; + switch (mc->levelRenderer->activePlayers()) { + case 1: + default: + r = 9; + break; + case 2: + r = 7; + break; + case 3: + r = 5; + break; + case 4: + r = 5; + break; + } - int r = 5; - // 4J - was if(mc.options.fancyGraphics) r = 10; - switch( mc->levelRenderer->activePlayers() ) - { - case 1: - default: - r = 9; - break; - case 2: - r = 7; - break; - case 3: - r = 5; - break; - case 4: - r = 5; - break; - } + // 4J - some changes made here to access biome through new interface that + // caches results in levelchunk flags, as an optimisation - // 4J - some changes made here to access biome through new interface that caches results in levelchunk flags, as an optimisation - int mode = -1; float time = _tick + a; glColor4f(1, 1, 1, 1); - for (int x = x0 - r; x <= x0 + r; x++) - for (int z = z0 - r; z <= z0 + r; z++) - { + for (int x = x0 - r; x <= x0 + r; x++) + for (int z = z0 - r; z <= z0 + r; z++) { int rainSlot = (z - z0 + 16) * 32 + (x - x0 + 16); float xa = rainXa[rainSlot] * 0.5f; float za = rainZa[rainSlot] * 0.5f; - - // 4J - changes here brought forward from 1.8.2 - Biome *b = level->getBiome(x, z); - if (!b->hasRain() && !b->hasSnow()) continue; - int floor = level->getTopRainBlock(x, z); + // 4J - changes here brought forward from 1.8.2 + Biome* b = level->getBiome(x, z); + if (!b->hasRain() && !b->hasSnow()) continue; - int yy0 = y0 - r; - int yy1 = y0 + r; + int floor = level->getTopRainBlock(x, z); - if (yy0 < floor) yy0 = floor; - if (yy1 < floor) yy1 = floor; - float s = 1; + int yy0 = y0 - r; + int yy1 = y0 + r; + + if (yy0 < floor) yy0 = floor; + if (yy1 < floor) yy1 = floor; + float s = 1; int yl = floor; if (yl < yMin) yl = yMin; - if (yy0 != yy1) - { - random->setSeed((x * x * 3121 + x * 45238971) ^ (z * z * 418711 + z * 13761)); + if (yy0 != yy1) { + random->setSeed((x * x * 3121 + x * 45238971) ^ + (z * z * 418711 + z * 13761)); - // 4J - changes here brought forward from 1.8.2 - float temp = b->getTemperature(); - if (level->getBiomeSource()->scaleTemp(temp, floor) >= 0.15f) - { - if (mode != 0) - { + // 4J - changes here brought forward from 1.8.2 + float temp = b->getTemperature(); + if (level->getBiomeSource()->scaleTemp(temp, floor) >= 0.15f) { + if (mode != 0) { if (mode >= 0) t->end(); mode = 0; mc->textures->bindTexture(TN_ENVIRONMENT_RAIN); t->begin(); } - float ra = (((_tick + x * x * 3121 + x * 45238971 + z * z * 418711 + z * 13761) & 31) + a) / 32.0f * (3 + random->nextFloat()); + float ra = (((_tick + x * x * 3121 + x * 45238971 + + z * z * 418711 + z * 13761) & + 31) + + a) / + 32.0f * (3 + random->nextFloat()); - double xd = (x + 0.5f) - player->x; - double zd = (z + 0.5f) - player->z; - float dd = (float) Mth::sqrt(xd * xd + zd * zd) / r; + double xd = (x + 0.5f) - player->x; + double zd = (z + 0.5f) - player->z; + float dd = (float)Mth::sqrt(xd * xd + zd * zd) / r; float br = 1; t->offset(-xo * 1, -yo * 1, -zo * 1); #ifdef __PSVITA__ - // AP - this will set up the 4 vertices in half the time - float Alpha = ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel; - int tex2 = (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; - t->tileRainQuad(x - xa + 0.5, yy0, z - za + 0.5, 0 * s, yy0 * s / 4.0f + ra * s, - x + xa + 0.5, yy0, z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s, - x + xa + 0.5, yy1, z + za + 0.5, 1 * s, yy1 * s / 4.0f + ra * s, - x - xa + 0.5, yy1, z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s, - br, br, br, Alpha, br, br, br, 0, tex2); + // AP - this will set up the 4 vertices in half the time + float Alpha = ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel; + int tex2 = + (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; + t->tileRainQuad( + x - xa + 0.5, yy0, z - za + 0.5, 0 * s, + yy0 * s / 4.0f + ra * s, x + xa + 0.5, yy0, + z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s, + x + xa + 0.5, yy1, z + za + 0.5, 1 * s, + yy1 * s / 4.0f + ra * s, x - xa + 0.5, yy1, + z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s, br, br, + br, Alpha, br, br, br, 0, tex2); #else t->tex2(level->getLightColor(x, yl, z, 0)); - t->color(br, br, br, ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel); - t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s, yy0 * s / 4.0f + ra * s); - t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s); - // 4jcraft: this color call made rain invisible - // t->color(br, br, br, 0.0f); // 4J - added to soften the top visible edge of the rain - t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s, yy1 * s / 4.0f + ra * s); - t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s); + t->color(br, br, br, + ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel); + t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s, + yy0 * s / 4.0f + ra * s); + t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s, + yy0 * s / 4.0f + ra * s); + // 4jcraft: this color call made rain invisible + // t->color(br, br, br, 0.0f); + // // 4J - added to soften the top visible edge of the rain + t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s, + yy1 * s / 4.0f + ra * s); + t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s, + yy1 * s / 4.0f + ra * s); #endif - t->offset(0, 0, 0); - t->end(); - } - else - { - if (mode != 1) - { + t->offset(0, 0, 0); + t->end(); + } else { + if (mode != 1) { if (mode >= 0) t->end(); mode = 1; mc->textures->bindTexture(TN_ENVIRONMENT_SNOW); t->begin(); } float ra = (((_tick) & 511) + a) / 512.0f; - float uo = random->nextFloat() + time * 0.01f * (float) random->nextGaussian(); - float vo = random->nextFloat() + time * (float) random->nextGaussian() * 0.001f; + float uo = random->nextFloat() + + time * 0.01f * (float)random->nextGaussian(); + float vo = random->nextFloat() + + time * (float)random->nextGaussian() * 0.001f; double xd = (x + 0.5f) - player->x; double zd = (z + 0.5f) - player->z; - float dd = (float) sqrt(xd * xd + zd * zd) / r; + float dd = (float)sqrt(xd * xd + zd * zd) / r; float br = 1; t->offset(-xo * 1, -yo * 1, -zo * 1); #ifdef __PSVITA__ - // AP - this will set up the 4 vertices in half the time - float Alpha = ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel; - int tex2 = (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; - t->tileRainQuad(x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, yy0 * s / 4.0f + ra * s + vo, - x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo, - x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, yy1 * s / 4.0f + ra * s + vo, - x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo, - br, br, br, Alpha, br, br, br, Alpha, tex2); + // AP - this will set up the 4 vertices in half the time + float Alpha = ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel; + int tex2 = + (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; + t->tileRainQuad( + x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, + yy0 * s / 4.0f + ra * s + vo, x + xa + 0.5, yy0, + z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo, + x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, + yy1 * s / 4.0f + ra * s + vo, x - xa + 0.5, yy1, + z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo, + br, br, br, Alpha, br, br, br, Alpha, tex2); #else - t->tex2((level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4); - t->color(br, br, br, ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel); - t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, yy0 * s / 4.0f + ra * s + vo); - t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo); - t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, yy1 * s / 4.0f + ra * s + vo); - t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo); + t->tex2((level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / + 4); + t->color(br, br, br, + ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel); + t->vertexUV(x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, + yy0 * s / 4.0f + ra * s + vo); + t->vertexUV(x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, + yy0 * s / 4.0f + ra * s + vo); + t->vertexUV(x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, + yy1 * s / 4.0f + ra * s + vo); + t->vertexUV(x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, + yy1 * s / 4.0f + ra * s + vo); #endif t->offset(0, 0, 0); } - } - } + } + } - if( mode >= 0 ) t->end(); - glEnable(GL_CULL_FACE); - glDisable(GL_BLEND); - glAlphaFunc(GL_GREATER, 0.1f); - this->turnOffLightLayer(a); + if (mode >= 0) t->end(); + glEnable(GL_CULL_FACE); + glDisable(GL_BLEND); + glAlphaFunc(GL_GREATER, 0.1f); + this->turnOffLightLayer(a); - RenderManager.StateSetEnableViewportClipPlanes(false); + RenderManager.StateSetEnableViewportClipPlanes(false); } // 4J - added forceScale parameter -void GameRenderer::setupGuiScreen(int forceScale /*=-1*/) -{ - int fbw, fbh; - RenderManager.GetFramebufferSize(fbw, fbh); - ScreenSizeCalculator ssc(mc->options, mc->width, mc->height, forceScale); +void GameRenderer::setupGuiScreen(int forceScale /*=-1*/) { + int fbw, fbh; + RenderManager.GetFramebufferSize(fbw, fbh); + ScreenSizeCalculator ssc(mc->options, mc->width, mc->height, forceScale); - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)ssc.rawWidth, (float)ssc.rawHeight, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); } -void GameRenderer::setupClearColor(float a) -{ - Level *level = mc->level; - std::shared_ptr player = mc->cameraTargetPlayer; +void GameRenderer::setupClearColor(float a) { + Level* level = mc->level; + std::shared_ptr player = mc->cameraTargetPlayer; - float whiteness = 1.0f / (4 - mc->options->viewDistance); - whiteness = 1 - (float) pow((double)whiteness, 0.25); + float whiteness = 1.0f / (4 - mc->options->viewDistance); + whiteness = 1 - (float)pow((double)whiteness, 0.25); - Vec3 *skyColor = level->getSkyColor(mc->cameraTargetPlayer, a); - float sr = (float) skyColor->x; - float sg = (float) skyColor->y; - float sb = (float) skyColor->z; + Vec3* skyColor = level->getSkyColor(mc->cameraTargetPlayer, a); + float sr = (float)skyColor->x; + float sg = (float)skyColor->y; + float sb = (float)skyColor->z; - Vec3 *fogColor = level->getFogColor(a); - fr = (float) fogColor->x; - fg = (float) fogColor->y; - fb = (float) fogColor->z; + Vec3* fogColor = level->getFogColor(a); + fr = (float)fogColor->x; + fg = (float)fogColor->y; + fb = (float)fogColor->z; - if (mc->options->viewDistance < 2) - { - Vec3 *sunAngle = Mth::sin(level->getSunAngle(a)) > 0 ? Vec3::newTemp(-1, 0, 0) : Vec3::newTemp(1, 0, 0); - float d = (float) player->getViewVector(a)->dot(sunAngle); + if (mc->options->viewDistance < 2) { + Vec3* sunAngle = Mth::sin(level->getSunAngle(a)) > 0 + ? Vec3::newTemp(-1, 0, 0) + : Vec3::newTemp(1, 0, 0); + float d = (float)player->getViewVector(a)->dot(sunAngle); if (d < 0) d = 0; - if (d > 0) - { - float *c = level->dimension->getSunriseColor(level->getTimeOfDay(a), a); - if (c != NULL) - { + if (d > 0) { + float* c = + level->dimension->getSunriseColor(level->getTimeOfDay(a), a); + if (c != NULL) { d *= c[3]; fr = fr * (1 - d) + c[0] * d; fg = fg * (1 - d) + c[1] * d; @@ -1868,83 +1865,76 @@ void GameRenderer::setupClearColor(float a) } } - fr += (sr - fr) * whiteness; - fg += (sg - fg) * whiteness; - fb += (sb - fb) * whiteness; + fr += (sr - fr) * whiteness; + fg += (sg - fg) * whiteness; + fb += (sb - fb) * whiteness; - float rainLevel = level->getRainLevel(a); - if (rainLevel > 0) - { - float ba = 1 - rainLevel * 0.5f; - float bb = 1 - rainLevel * 0.4f; - fr *= ba; - fg *= ba; - fb *= bb; - } - float thunderLevel = level->getThunderLevel(a); - if (thunderLevel > 0) - { - float ba = 1 - thunderLevel * 0.5f; - fr *= ba; - fg *= ba; - fb *= ba; - } + float rainLevel = level->getRainLevel(a); + if (rainLevel > 0) { + float ba = 1 - rainLevel * 0.5f; + float bb = 1 - rainLevel * 0.4f; + fr *= ba; + fg *= ba; + fb *= bb; + } + float thunderLevel = level->getThunderLevel(a); + if (thunderLevel > 0) { + float ba = 1 - thunderLevel * 0.5f; + fr *= ba; + fg *= ba; + fb *= ba; + } - int t = Camera::getBlockAt(mc->level, player, a); - if (isInClouds) - { - Vec3 *cc = level->getCloudColor(a); - fr = (float) cc->x; - fg = (float) cc->y; - fb = (float) cc->z; - } - else if (t != 0 && Tile::tiles[t]->material == Material::water) - { - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Water_Clear_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + int t = Camera::getBlockAt(mc->level, player, a); + if (isInClouds) { + Vec3* cc = level->getCloudColor(a); + fr = (float)cc->x; + fg = (float)cc->y; + fb = (float)cc->z; + } else if (t != 0 && Tile::tiles[t]->material == Material::water) { + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Water_Clear_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - fr = (float)redComponent/256;//0.02f; - fg = (float)greenComponent/256;//0.02f; - fb = (float)blueComponent/256;//0.2f; - } - else if (t != 0 && Tile::tiles[t]->material == Material::lava) - { - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Lava_Clear_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + fr = (float)redComponent / 256; // 0.02f; + fg = (float)greenComponent / 256; // 0.02f; + fb = (float)blueComponent / 256; // 0.2f; + } else if (t != 0 && Tile::tiles[t]->material == Material::lava) { + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Lava_Clear_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - fr = (float)redComponent/256;//0.6f; - fg = (float)greenComponent/256;//0.1f; - fb = (float)blueComponent/256;//0.00f; - } + fr = (float)redComponent / 256; // 0.6f; + fg = (float)greenComponent / 256; // 0.1f; + fb = (float)blueComponent / 256; // 0.00f; + } - float brr = fogBrO + (fogBr - fogBrO) * a; - fr *= brr; - fg *= brr; - fb *= brr; + float brr = fogBrO + (fogBr - fogBrO) * a; + fr *= brr; + fg *= brr; + fb *= brr; - double yy = (player->yOld + (player->y - player->yOld) * a) * level->dimension->getClearColorScale(); // 4J - getClearColorScale brought forward from 1.2.3 + double yy = + (player->yOld + (player->y - player->yOld) * a) * + level->dimension->getClearColorScale(); // 4J - getClearColorScale + // brought forward from 1.2.3 - if (player->hasEffect(MobEffect::blindness)) - { + if (player->hasEffect(MobEffect::blindness)) { int duration = player->getEffect(MobEffect::blindness)->getDuration(); - if (duration < 20) - { - yy = yy * (1.0f - (float) duration / 20.0f); - } - else - { + if (duration < 20) { + yy = yy * (1.0f - (float)duration / 20.0f); + } else { yy = 0; } } - if (yy < 1) - { + if (yy < 1) { if (yy < 0) yy = 0; yy = yy * yy; fr *= yy; @@ -1952,260 +1942,235 @@ void GameRenderer::setupClearColor(float a) fb *= yy; } - if (player->hasEffect(MobEffect::nightVision)) - { - float scale = getNightVisionScale(mc->player, a); - { - float dist = FLT_MAX; // MGH - changed this to avoid divide by zero - if ( (fr > 0) && (dist > (1.0f / fr)) ) - { - dist = (1.0f / fr); - } - if ( (fg > 0) && (dist > (1.0f / fg)) ) - { - dist = (1.0f / fg); - } - if ( (fb > 0) && (dist > (1.0f / fb)) ) - { - dist = (1.0f / fb); - } - fr = fr * (1.0f - scale) + (fr * dist) * scale; - fg = fg * (1.0f - scale) + (fg * dist) * scale; - fb = fb * (1.0f - scale) + (fb * dist) * scale; - } - } - - if (mc->options->anaglyph3d) - { - float frr = (fr * 30 + fg * 59 + fb * 11) / 100; - float fgg = (fr * 30 + fg * 70) / (100); - float fbb = (fr * 30 + fb * 70) / (100); - - fr = frr; - fg = fgg; - fb = fbb; - } - - glClearColor(fr, fg, fb, 0.0f); - -} - -void GameRenderer::setupFog(int i, float alpha) -{ - std::shared_ptr player = mc->cameraTargetPlayer; - - // 4J - check for creative mode brought forward from 1.2.3 - bool creative = false; - if (std::dynamic_pointer_cast(player) ) - { - creative = (std::dynamic_pointer_cast(player))->abilities.instabuild; + if (player->hasEffect(MobEffect::nightVision)) { + float scale = getNightVisionScale(mc->player, a); + { + float dist = FLT_MAX; // MGH - changed this to avoid divide by zero + if ((fr > 0) && (dist > (1.0f / fr))) { + dist = (1.0f / fr); + } + if ((fg > 0) && (dist > (1.0f / fg))) { + dist = (1.0f / fg); + } + if ((fb > 0) && (dist > (1.0f / fb))) { + dist = (1.0f / fb); + } + fr = fr * (1.0f - scale) + (fr * dist) * scale; + fg = fg * (1.0f - scale) + (fg * dist) * scale; + fb = fb * (1.0f - scale) + (fb * dist) * scale; + } } - if (i == 999) - { - __debugbreak(); - // 4J TODO - /* - glFog(GL_FOG_COLOR, getBuffer(0, 0, 0, 1)); - glFogi(GL_FOG_MODE, GL_LINEAR); - glFogf(GL_FOG_START, 0); - glFogf(GL_FOG_END, 8); + if (mc->options->anaglyph3d) { + float frr = (fr * 30 + fg * 59 + fb * 11) / 100; + float fgg = (fr * 30 + fg * 70) / (100); + float fbb = (fr * 30 + fb * 70) / (100); - if (GLContext.getCapabilities().GL_NV_fog_distance) { - glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV); - } + fr = frr; + fg = fgg; + fb = fbb; + } - glFogf(GL_FOG_START, 0); - */ + glClearColor(fr, fg, fb, 0.0f); +} + +void GameRenderer::setupFog(int i, float alpha) { + std::shared_ptr player = mc->cameraTargetPlayer; + + // 4J - check for creative mode brought forward from 1.2.3 + bool creative = false; + if (std::dynamic_pointer_cast(player)) { + creative = + (std::dynamic_pointer_cast(player))->abilities.instabuild; + } + + if (i == 999) { + __debugbreak(); + // 4J TODO + /* +glFog(GL_FOG_COLOR, getBuffer(0, 0, 0, 1)); +glFogi(GL_FOG_MODE, GL_LINEAR); +glFogf(GL_FOG_START, 0); +glFogf(GL_FOG_END, 8); + +if (GLContext.getCapabilities().GL_NV_fog_distance) { + glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, +NVFogDistance.GL_EYE_RADIAL_NV); +} + +glFogf(GL_FOG_START, 0); + */ return; } - glFog(GL_FOG_COLOR, getBuffer(fr, fg, fb, 1)); - glNormal3f(0, -1, 0); - glColor4f(1, 1, 1, 1); + glFog(GL_FOG_COLOR, getBuffer(fr, fg, fb, 1)); + glNormal3f(0, -1, 0); + glColor4f(1, 1, 1, 1); int t = Camera::getBlockAt(mc->level, player, alpha); - if (player->hasEffect(MobEffect::blindness)) - { + if (player->hasEffect(MobEffect::blindness)) { float distance = 5.0f; int duration = player->getEffect(MobEffect::blindness)->getDuration(); - if (duration < 20) - { - distance = 5.0f + (renderDistance - 5.0f) * (1.0f - (float) duration / 20.0f); + if (duration < 20) { + distance = 5.0f + (renderDistance - 5.0f) * + (1.0f - (float)duration / 20.0f); } glFogi(GL_FOG_MODE, GL_LINEAR); - if (i < 0) - { + if (i < 0) { glFogf(GL_FOG_START, 0); glFogf(GL_FOG_END, distance * 0.8f); - } - else - { + } else { glFogf(GL_FOG_START, distance * 0.25f); glFogf(GL_FOG_END, distance); } - // 4J - TODO investigate implementing this -// if (GLContext.getCapabilities().GL_NV_fog_distance) -// { -// glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV); -// } - } - else if (isInClouds) - { - glFogi(GL_FOG_MODE, GL_EXP); - glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_In_Cloud_Fog_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + // 4J - TODO investigate implementing this + // if (GLContext.getCapabilities().GL_NV_fog_distance) + // { + // glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, + // NVFogDistance.GL_EYE_RADIAL_NV); + // } + } else if (isInClouds) { + glFogi(GL_FOG_MODE, GL_EXP); + glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 - float rr = (float)redComponent/256;//1.0f; - float gg = (float)greenComponent/256;//1.0f; - float bb = (float)blueComponent/256;//1.0f; + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_In_Cloud_Fog_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - if (mc->options->anaglyph3d) - { - float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; - float ggg = (rr * 30 + gg * 70) / (100); - float bbb = (rr * 30 + bb * 70) / (100); + float rr = (float)redComponent / 256; // 1.0f; + float gg = (float)greenComponent / 256; // 1.0f; + float bb = (float)blueComponent / 256; // 1.0f; - rr = rrr; - gg = ggg; - bb = bbb; - } - } - else if (t > 0 && Tile::tiles[t]->material == Material::water) - { - glFogi(GL_FOG_MODE, GL_EXP); - if (player->hasEffect(MobEffect::waterBreathing)) - { - glFogf(GL_FOG_DENSITY, 0.05f); // was 0.06 - } - else - { - glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 - } - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Water_Fog_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + if (mc->options->anaglyph3d) { + float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; + float ggg = (rr * 30 + gg * 70) / (100); + float bbb = (rr * 30 + bb * 70) / (100); - float rr = (float)redComponent/256;//0.4f; - float gg = (float)greenComponent/256;//0.4f; - float bb = (float)blueComponent/256;//0.9f; + rr = rrr; + gg = ggg; + bb = bbb; + } + } else if (t > 0 && Tile::tiles[t]->material == Material::water) { + glFogi(GL_FOG_MODE, GL_EXP); + if (player->hasEffect(MobEffect::waterBreathing)) { + glFogf(GL_FOG_DENSITY, 0.05f); // was 0.06 + } else { + glFogf(GL_FOG_DENSITY, 0.1f); // was 0.06 + } - if (mc->options->anaglyph3d) - { - float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; - float ggg = (rr * 30 + gg * 70) / (100); - float bbb = (rr * 30 + bb * 70) / (100); + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Water_Fog_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); - rr = rrr; - gg = ggg; - bb = bbb; - } - } - else if (t > 0 && Tile::tiles[t]->material == Material::lava) - { - glFogi(GL_FOG_MODE, GL_EXP); - glFogf(GL_FOG_DENSITY, 2.0f); // was 0.06 - - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Under_Lava_Fog_Colour ); - std::uint8_t redComponent = ((colour>>16)&0xFF); - std::uint8_t greenComponent = ((colour>>8)&0xFF); - std::uint8_t blueComponent = ((colour)&0xFF); + float rr = (float)redComponent / 256; // 0.4f; + float gg = (float)greenComponent / 256; // 0.4f; + float bb = (float)blueComponent / 256; // 0.9f; - float rr = (float)redComponent/256;//0.4f; - float gg = (float)greenComponent/256;//0.3f; - float bb = (float)blueComponent/256;//0.3f; + if (mc->options->anaglyph3d) { + float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; + float ggg = (rr * 30 + gg * 70) / (100); + float bbb = (rr * 30 + bb * 70) / (100); - if (mc->options->anaglyph3d) - { - float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; - float ggg = (rr * 30 + gg * 70) / (100); - float bbb = (rr * 30 + bb * 70) / (100); + rr = rrr; + gg = ggg; + bb = bbb; + } + } else if (t > 0 && Tile::tiles[t]->material == Material::lava) { + glFogi(GL_FOG_MODE, GL_EXP); + glFogf(GL_FOG_DENSITY, 2.0f); // was 0.06 - rr = rrr; - gg = ggg; - bb = bbb; - } - } - else - { + unsigned int colour = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Under_Lava_Fog_Colour); + std::uint8_t redComponent = ((colour >> 16) & 0xFF); + std::uint8_t greenComponent = ((colour >> 8) & 0xFF); + std::uint8_t blueComponent = ((colour) & 0xFF); + + float rr = (float)redComponent / 256; // 0.4f; + float gg = (float)greenComponent / 256; // 0.3f; + float bb = (float)blueComponent / 256; // 0.3f; + + if (mc->options->anaglyph3d) { + float rrr = (rr * 30 + gg * 59 + bb * 11) / 100; + float ggg = (rr * 30 + gg * 70) / (100); + float bbb = (rr * 30 + bb * 70) / (100); + + rr = rrr; + gg = ggg; + bb = bbb; + } + } else { float distance = renderDistance; - if (!mc->level->dimension->hasCeiling) - { - // 4J - test for doing bedrockfog brought forward from 1.2.3 - if (mc->level->dimension->hasBedrockFog() && !creative) - { - double yy = ((player->getLightColor(alpha) & 0xf00000) >> 20) / 16.0 + (player->yOld + (player->y - player->yOld) * alpha + 4) / 32; - if (yy < 1) - { - if (yy < 0) yy = 0; - yy = yy * yy; - float dist = 100 * (float) yy; - if (dist < 5) dist = 5; - if (distance > dist) distance = dist; - } - } - } - - glFogi(GL_FOG_MODE, GL_LINEAR); - glFogf(GL_FOG_START, distance * 0.25f); - glFogf(GL_FOG_END, distance); - if (i < 0) - { - glFogf(GL_FOG_START, 0); - glFogf(GL_FOG_END, distance * 0.8f); + if (!mc->level->dimension->hasCeiling) { + // 4J - test for doing bedrockfog brought forward from 1.2.3 + if (mc->level->dimension->hasBedrockFog() && !creative) { + double yy = + ((player->getLightColor(alpha) & 0xf00000) >> 20) / 16.0 + + (player->yOld + (player->y - player->yOld) * alpha + 4) / + 32; + if (yy < 1) { + if (yy < 0) yy = 0; + yy = yy * yy; + float dist = 100 * (float)yy; + if (dist < 5) dist = 5; + if (distance > dist) distance = dist; + } + } } - else - { - glFogf(GL_FOG_START, distance * 0.25f); - glFogf(GL_FOG_END, distance); + + glFogi(GL_FOG_MODE, GL_LINEAR); + glFogf(GL_FOG_START, distance * 0.25f); + glFogf(GL_FOG_END, distance); + if (i < 0) { + glFogf(GL_FOG_START, 0); + glFogf(GL_FOG_END, distance * 0.8f); + } else { + glFogf(GL_FOG_START, distance * 0.25f); + glFogf(GL_FOG_END, distance); } - /* 4J - removed - TODO investigate - if (GLContext.getCapabilities().GL_NV_fog_distance) - { - glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV); - } - */ + /* 4J - removed - TODO investigate + if (GLContext.getCapabilities().GL_NV_fog_distance) + { + glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, + NVFogDistance.GL_EYE_RADIAL_NV); + } + */ - if (mc->level->dimension->isFoggyAt((int) player->x, (int) player->z)) - { - glFogf(GL_FOG_START, distance * 0.05f); - glFogf(GL_FOG_END, std::min(distance, 16 * 16 * .75f) * .5f); - } - } - - glEnable(GL_COLOR_MATERIAL); - glColorMaterial(GL_FRONT, GL_AMBIENT); + if (mc->level->dimension->isFoggyAt((int)player->x, (int)player->z)) { + glFogf(GL_FOG_START, distance * 0.05f); + glFogf(GL_FOG_END, std::min(distance, 16 * 16 * .75f) * .5f); + } + } + glEnable(GL_COLOR_MATERIAL); + glColorMaterial(GL_FRONT, GL_AMBIENT); } -FloatBuffer *GameRenderer::getBuffer(float a, float b, float c, float d) -{ - lb->clear(); - lb->put(a)->put(b)->put(c)->put(d); - lb->flip(); - return lb; +FloatBuffer* GameRenderer::getBuffer(float a, float b, float c, float d) { + lb->clear(); + lb->put(a)->put(b)->put(c)->put(d); + lb->flip(); + return lb; } -int GameRenderer::getFpsCap(int option) -{ - int maxFps = 200; - if (option == 1) maxFps = 120; - if (option == 2) maxFps = 35; - #ifndef ENABLE_VSYNC - if (option == 3) maxFps = 0; - #endif - return maxFps; +int GameRenderer::getFpsCap(int option) { + int maxFps = 200; + if (option == 1) maxFps = 120; + if (option == 2) maxFps = 35; +#ifndef ENABLE_VSYNC + if (option == 3) maxFps = 0; +#endif + return maxFps; } -void GameRenderer::updateAllChunks() -{ -// mc->levelRenderer->updateDirtyChunks(mc->cameraTargetPlayer, true); +void GameRenderer::updateAllChunks() { + // mc->levelRenderer->updateDirtyChunks(mc->cameraTargetPlayer, true); } diff --git a/Minecraft.Client/Rendering/GameRenderer.h b/Minecraft.Client/Rendering/GameRenderer.h index eec06278e..c6012c18a 100644 --- a/Minecraft.Client/Rendering/GameRenderer.h +++ b/Minecraft.Client/Rendering/GameRenderer.h @@ -12,19 +12,20 @@ class SparseDataStorage; #include "../../Minecraft.World/Util/SmoothFloat.h" #include "../../Minecraft.World/Util/C4JThread.h" -class GameRenderer -{ +class GameRenderer { public: - static bool anaglyph3d; + static bool anaglyph3d; static int anaglyphPass; private: - Minecraft *mc; + Minecraft* mc; float renderDistance; + public: - ItemInHandRenderer *itemInHandRenderer; + ItemInHandRenderer* itemInHandRenderer; + private: - int _tick; + int _tick; std::shared_ptr hovered; // smooth camera movement @@ -32,140 +33,158 @@ private: SmoothFloat smoothTurnY; // third-person distance etc - SmoothFloat smoothDistance; - SmoothFloat smoothRotation; - SmoothFloat smoothTilt; - SmoothFloat smoothRoll; - float thirdDistance; - float thirdDistanceO; - float thirdRotation; - float thirdRotationO; - float thirdTilt; - float thirdTiltO; + SmoothFloat smoothDistance; + SmoothFloat smoothRotation; + SmoothFloat smoothTilt; + SmoothFloat smoothRoll; + float thirdDistance; + float thirdDistanceO; + float thirdRotation; + float thirdRotationO; + float thirdTilt; + float thirdTiltO; float accumulatedSmoothXO, accumulatedSmoothYO; float tickSmoothXO, tickSmoothYO, lastTickA; - Vec3 *cameraPos; // 4J added + Vec3* cameraPos; // 4J added // fov modification - float fovOffset; - float fovOffsetO; + float fovOffset; + float fovOffsetO; // roll modification float cameraRoll; float cameraRollO; - // 4J - changes brought forward from 1.8.2 - static const int NUM_LIGHT_TEXTURES = 4;// * 3; - int lightTexture[NUM_LIGHT_TEXTURES]; // 4J - changed so that we have one lightTexture per level, to support split screen - int getLightTexture(int iPad, Level *level); // 4J added - intArray lightPixels[NUM_LIGHT_TEXTURES]; + // 4J - changes brought forward from 1.8.2 + static const int NUM_LIGHT_TEXTURES = 4; // * 3; + int lightTexture[NUM_LIGHT_TEXTURES]; // 4J - changed so that we have one + // lightTexture per level, to support + // split screen + int getLightTexture(int iPad, Level* level); // 4J added + intArray lightPixels[NUM_LIGHT_TEXTURES]; - float fov[4]; - float oFov[4]; - float tFov[4]; + float fov[4]; + float oFov[4]; + float tFov[4]; bool isInClouds; - float m_fov; -public: - GameRenderer(Minecraft *mc); - ~GameRenderer(); - void SetFovVal(float fov); - float GetFovVal(); + float m_fov; public: - void tick(bool bFirst); + GameRenderer(Minecraft* mc); + ~GameRenderer(); + void SetFovVal(float fov); + float GetFovVal(); + +public: + void tick(bool bFirst); void pick(float a); + private: - void tickFov(); - float getFov(float a, bool applyEffects); + void tickFov(); + float getFov(float a, bool applyEffects); void bobHurt(float a); void bobView(float a); void moveCameraToPlayer(float a); double zoom; double zoom_x; double zoom_y; + public: - void zoomRegion(double zoom, double xa, double ya); + void zoomRegion(double zoom, double xa, double ya); void unZoomRegion(); + private: - void getFovAndAspect(float& fov, float& aspect, float a, bool applyEffects); // 4J added + void getFovAndAspect(float& fov, float& aspect, float a, + bool applyEffects); // 4J added public: - void setupCamera(float a, int eye); + void setupCamera(float a, int eye); + private: void renderItemInHand(float a, int eye); __int64 lastActiveTime; __int64 lastNsTime; - // 4J - changes brought forward from 1.8.2 - bool _updateLightTexture; + // 4J - changes brought forward from 1.8.2 + bool _updateLightTexture; + public: - float blr; - float blrt; - float blg; - float blgt; - void turnOffLightLayer(double alpha); - void turnOnLightLayer(double alpha, bool scaleLight = false); + float blr; + float blrt; + float blg; + float blgt; + void turnOffLightLayer(double alpha); + void turnOnLightLayer(double alpha, bool scaleLight = false); + private: - void tickLightTexture(); - void updateLightTexture(float a); - float getNightVisionScale(std::shared_ptr player, float a); + void tickLightTexture(); + void updateLightTexture(float a); + float getNightVisionScale(std::shared_ptr player, float a); + public: - void render(float a, bool bFirst); // 4J added bFirst + void render(float a, bool bFirst); // 4J added bFirst void renderLevel(float a); void renderLevel(float a, __int64 until); + private: - Random *random; + Random* random; int rainSoundTime; void tickRain(); + private: - // 4J - brought forward from 1.8.2 - float *rainXa; - float *rainZa; + // 4J - brought forward from 1.8.2 + float* rainXa; + float* rainZa; + protected: - void renderSnowAndRain(float a); + void renderSnowAndRain(float a); volatile int xMod; volatile int yMod; -public: - void setupGuiScreen(int forceScale=-1); // 4J - added forceScale parameter - FloatBuffer *lb; +public: + void setupGuiScreen( + int forceScale = -1); // 4J - added forceScale parameter + + FloatBuffer* lb; float fr; float fg; float fb; + private: - void setupClearColor(float a); + void setupClearColor(float a); float fogBrO, fogBr; - int cameraFlip; + int cameraFlip; void setupFog(int i, float alpha); - FloatBuffer *getBuffer(float a, float b, float c, float d); - static int getFpsCap(int option); + FloatBuffer* getBuffer(float a, float b, float c, float d); + static int getFpsCap(int option); + public: - void updateAllChunks(); + void updateAllChunks(); #ifdef MULTITHREAD_ENABLE - static C4JThread* m_updateThread; - static int runUpdate(void *lpParam); - static C4JThread::EventArray* m_updateEvents; - enum EUpdateEvents - { - eUpdateCanRun, - eUpdateEventIsFinished, - eUpdateEventCount, - }; - static bool nearThingsToDo; - static bool updateRunning; + static C4JThread* m_updateThread; + static int runUpdate(void* lpParam); + static C4JThread::EventArray* m_updateEvents; + enum EUpdateEvents { + eUpdateCanRun, + eUpdateEventIsFinished, + eUpdateEventCount, + }; + static bool nearThingsToDo; + static bool updateRunning; #endif - static std::vector m_deleteStackByte; - static std::vector m_deleteStackSparseLightStorage; - static std::vector m_deleteStackCompressedTileStorage; - static std::vector m_deleteStackSparseDataStorage; - static CRITICAL_SECTION m_csDeleteStack; - static void AddForDelete(std::uint8_t *deleteThis); - static void AddForDelete(SparseLightStorage *deleteThis); - static void AddForDelete(CompressedTileStorage *deleteThis); - static void AddForDelete(SparseDataStorage *deleteThis); - static void FinishedReassigning(); - void EnableUpdateThread(); - void DisableUpdateThread(); + static std::vector m_deleteStackByte; + static std::vector m_deleteStackSparseLightStorage; + static std::vector + m_deleteStackCompressedTileStorage; + static std::vector m_deleteStackSparseDataStorage; + static CRITICAL_SECTION m_csDeleteStack; + static void AddForDelete(std::uint8_t* deleteThis); + static void AddForDelete(SparseLightStorage* deleteThis); + static void AddForDelete(CompressedTileStorage* deleteThis); + static void AddForDelete(SparseDataStorage* deleteThis); + static void FinishedReassigning(); + void EnableUpdateThread(); + void DisableUpdateThread(); }; diff --git a/Minecraft.Client/Rendering/LevelRenderer.cpp b/Minecraft.Client/Rendering/LevelRenderer.cpp index 1fb33a247..da691360b 100644 --- a/Minecraft.Client/Rendering/LevelRenderer.cpp +++ b/Minecraft.Client/Rendering/LevelRenderer.cpp @@ -65,1082 +65,1130 @@ #include "../Platform/PS3/SPU_Tasks/LevelRenderer_FindNearestChunk/LevelRenderer_FindNearestChunk.h" #include "../Platform/PS3/PS3Extras/C4JSpursJob.h" -static LevelRenderer_cull_DataIn g_cullDataIn[4] __attribute__((__aligned__(16))); -static LevelRenderer_FindNearestChunk_DataIn g_findNearestChunkDataIn __attribute__((__aligned__(16))); +static LevelRenderer_cull_DataIn g_cullDataIn[4] + __attribute__((__aligned__(16))); +static LevelRenderer_FindNearestChunk_DataIn g_findNearestChunkDataIn + __attribute__((__aligned__(16))); #endif const unsigned int HALO_RING_RADIUS = 100; #ifdef _LARGE_WORLDS Chunk LevelRenderer::permaChunk[MAX_CONCURRENT_CHUNK_REBUILDS]; -C4JThread *LevelRenderer::rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; -C4JThread::EventArray *LevelRenderer::s_rebuildCompleteEvents; -C4JThread::Event *LevelRenderer::s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; +C4JThread* LevelRenderer::rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; +C4JThread::EventArray* LevelRenderer::s_rebuildCompleteEvents; +C4JThread::Event* LevelRenderer::s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; -// This defines the maximum size of renderable level, must be big enough to cope with actual size of level + view distance at each side -// so that we can render the "infinite" sea at the edges. Currently defined as: -const int overworldSize = LEVEL_MAX_WIDTH + LevelRenderer::PLAYER_VIEW_DISTANCE + LevelRenderer::PLAYER_VIEW_DISTANCE; -const int netherSize = HELL_LEVEL_MAX_WIDTH + 2; // 4J Stu - The plus 2 is really just to make our total chunk count a multiple of 8 for the flags, we will never see these in the nether +// This defines the maximum size of renderable level, must be big enough to cope +// with actual size of level + view distance at each side so that we can render +// the "infinite" sea at the edges. Currently defined as: +const int overworldSize = LEVEL_MAX_WIDTH + + LevelRenderer::PLAYER_VIEW_DISTANCE + + LevelRenderer::PLAYER_VIEW_DISTANCE; +const int netherSize = + HELL_LEVEL_MAX_WIDTH + + 2; // 4J Stu - The plus 2 is really just to make our total chunk count a + // multiple of 8 for the flags, we will never see these in the nether const int endSize = END_LEVEL_MAX_WIDTH; -const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = { overworldSize, netherSize, endSize }; -const int LevelRenderer::DIMENSION_OFFSETS[3] = { 0, (overworldSize * overworldSize * CHUNK_Y_COUNT) , (overworldSize * overworldSize * CHUNK_Y_COUNT) + ( netherSize * netherSize * CHUNK_Y_COUNT ) }; +const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = {overworldSize, netherSize, + endSize}; +const int LevelRenderer::DIMENSION_OFFSETS[3] = { + 0, (overworldSize * overworldSize * CHUNK_Y_COUNT), + (overworldSize * overworldSize * CHUNK_Y_COUNT) + + (netherSize * netherSize * CHUNK_Y_COUNT)}; #else -// This defines the maximum size of renderable level, must be big enough to cope with actual size of level + view distance at each side -// so that we can render the "infinite" sea at the edges. Currently defined as: -// Dimension idx 0 (overworld) : 80 ( = 54 + 13 + 13 ) -// Dimension idx 1 (nether) : 44 ( = 18 + 13 + 13 ) -// Dimension idx 2 (the end) : 44 ( = 18 + 13 + 13 ) +// This defines the maximum size of renderable level, must be big enough to cope +// with actual size of level + view distance at each side so that we can render +// the "infinite" sea at the edges. Currently defined as: Dimension idx 0 +// (overworld) : 80 ( = 54 + 13 + 13 ) Dimension idx 1 (nether) : 44 ( = 18 + +// 13 + 13 ) Dimension idx 2 (the end) : 44 ( = 18 + 13 + 13 ) -const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = { 80, 44, 44 }; +const int LevelRenderer::MAX_LEVEL_RENDER_SIZE[3] = {80, 44, 44}; -// Linked directly to the sizes in the previous array, these next values dictate the start offset for each dimension index into the global array for these things. -// Each dimension uses MAX_LEVEL_RENDER_SIZE[i]^2 * 8 indices, as a MAX_LEVEL_RENDER_SIZE * MAX_LEVEL_RENDER_SIZE * 8 sized cube of references. +// Linked directly to the sizes in the previous array, these next values dictate +// the start offset for each dimension index into the global array for these +// things. Each dimension uses MAX_LEVEL_RENDER_SIZE[i]^2 * 8 indices, as a +// MAX_LEVEL_RENDER_SIZE * MAX_LEVEL_RENDER_SIZE * 8 sized cube of references. -const int LevelRenderer::DIMENSION_OFFSETS[3] = { 0, (80 * 80 * CHUNK_Y_COUNT) , (80 * 80 * CHUNK_Y_COUNT) + ( 44 * 44 * CHUNK_Y_COUNT ) }; +const int LevelRenderer::DIMENSION_OFFSETS[3] = { + 0, (80 * 80 * CHUNK_Y_COUNT), + (80 * 80 * CHUNK_Y_COUNT) + (44 * 44 * CHUNK_Y_COUNT)}; #endif -LevelRenderer::LevelRenderer(Minecraft *mc, Textures *textures) -{ - breakingTextures = NULL; +LevelRenderer::LevelRenderer(Minecraft* mc, Textures* textures) { + breakingTextures = NULL; - for( int i = 0; i < 4; i++ ) - { - level[i] = NULL; - tileRenderer[i] = NULL; - xOld[i] = -9999; - yOld[i] = -9999; - zOld[i] = -9999; - } - xChunks= yChunks= zChunks = 0; - chunkLists = 0; + for (int i = 0; i < 4; i++) { + level[i] = NULL; + tileRenderer[i] = NULL; + xOld[i] = -9999; + yOld[i] = -9999; + zOld[i] = -9999; + } + xChunks = yChunks = zChunks = 0; + chunkLists = 0; - ticks = 0; - starList= skyList= darkList = 0; - xMinChunk= yMinChunk= zMinChunk = 0; - xMaxChunk= yMaxChunk= zMaxChunk = 0; - lastViewDistance = -1; - noEntityRenderFrames = 2; - totalEntities = 0; - renderedEntities = 0; - culledEntities = 0; - chunkFixOffs = 0; - frame = 0; - repeatList = MemoryTracker::genLists(1); + ticks = 0; + starList = skyList = darkList = 0; + xMinChunk = yMinChunk = zMinChunk = 0; + xMaxChunk = yMaxChunk = zMaxChunk = 0; + lastViewDistance = -1; + noEntityRenderFrames = 2; + totalEntities = 0; + renderedEntities = 0; + culledEntities = 0; + chunkFixOffs = 0; + frame = 0; + repeatList = MemoryTracker::genLists(1); - destroyProgress = 0.0f; + destroyProgress = 0.0f; - totalChunks= offscreenChunks= occludedChunks= renderedChunks= emptyChunks = 0; - for( int i = 0; i < 4; i++ ) - { - // sortedChunks[i] = NULL; // 4J - removed - not sorting our chunks anymore - chunks[i] = ClipChunkArray(); - lastPlayerCount[i] = 0; - } + totalChunks = offscreenChunks = occludedChunks = renderedChunks = + emptyChunks = 0; + for (int i = 0; i < 4; i++) { + // sortedChunks[i] = NULL; // 4J - removed - not sorting + //our chunks anymore + chunks[i] = ClipChunkArray(); + lastPlayerCount[i] = 0; + } - InitializeCriticalSection(&m_csDirtyChunks); - InitializeCriticalSection(&m_csRenderableTileEntities); + InitializeCriticalSection(&m_csDirtyChunks); + InitializeCriticalSection(&m_csRenderableTileEntities); #ifdef _LARGE_WORLDS - InitializeCriticalSection(&m_csChunkFlags); + InitializeCriticalSection(&m_csChunkFlags); #endif - dirtyChunkPresent = false; - lastDirtyChunkFound = 0; + dirtyChunkPresent = false; + lastDirtyChunkFound = 0; - this->mc = mc; - this->textures = textures; + this->mc = mc; + this->textures = textures; - chunkLists = MemoryTracker::genLists(getGlobalChunkCount()*2); // *2 here is because there is one renderlist per chunk here for each of the opaque & transparent layers - globalChunkFlags = new unsigned char[getGlobalChunkCount()]; - memset(globalChunkFlags, 0, getGlobalChunkCount()); + chunkLists = MemoryTracker::genLists( + getGlobalChunkCount() * + 2); // *2 here is because there is one renderlist per chunk here for + // each of the opaque & transparent layers + globalChunkFlags = new unsigned char[getGlobalChunkCount()]; + memset(globalChunkFlags, 0, getGlobalChunkCount()); - starList = MemoryTracker::genLists(4); + starList = MemoryTracker::genLists(4); - glPushMatrix(); - glNewList(starList, GL_COMPILE); - renderStars(); - glEndList(); + glPushMatrix(); + glNewList(starList, GL_COMPILE); + renderStars(); + glEndList(); - // 4J added - create geometry for rendering clouds - createCloudMesh(); + // 4J added - create geometry for rendering clouds + createCloudMesh(); - glPopMatrix(); + glPopMatrix(); + Tesselator* t = Tesselator::getInstance(); + skyList = starList + 1; + glNewList(skyList, GL_COMPILE); + glDepthMask(false); // 4J - added to get depth mask disabled within the + // command buffer + float yy; + int s = 64; + int d = (256 / s) + 2; + yy = (float)(16); + for (int xx = -s * d; xx <= s * d; xx += s) { + for (int zz = -s * d; zz <= s * d; zz += s) { + t->begin(); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + s), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + s), (float)(yy), (float)(zz + s)); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + s)); + t->end(); + } + } + glEndList(); + darkList = starList + 2; + glNewList(darkList, GL_COMPILE); + yy = -(float)(16); + t->begin(); + for (int xx = -s * d; xx <= s * d; xx += s) { + for (int zz = -s * d; zz <= s * d; zz += s) { + t->vertex((float)(xx + s), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + 0)); + t->vertex((float)(xx + 0), (float)(yy), (float)(zz + s)); + t->vertex((float)(xx + s), (float)(yy), (float)(zz + s)); + } + } + t->end(); + glEndList(); - Tesselator *t = Tesselator::getInstance(); - skyList = starList + 1; - glNewList(skyList, GL_COMPILE); - glDepthMask(false); // 4J - added to get depth mask disabled within the command buffer - float yy; - int s = 64; - int d = (256 / s) + 2; - yy = (float) (16); - for (int xx = -s * d; xx <= s * d; xx += s) - { - for (int zz = -s * d; zz <= s * d; zz += s) - { - t->begin(); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + s)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + s)); - t->end(); - } - } - glEndList(); + // HALO ring for the texture pack + { + const unsigned int ARC_SEGMENTS = 50; + const float VERTICAL_OFFSET = + HALO_RING_RADIUS * 999 / + 1000; // How much we raise the circle origin to make the circle + // curve back towards us + const int WIDTH = 10; + const float ARC_RADIANS = 2.0f * PI / ARC_SEGMENTS; + const float HALF_ARC_SEG = ARC_SEGMENTS / 2; + const float WIDE_ARC_SEGS = ARC_SEGMENTS / 8; + const float WIDE_ARC_SEGS_SQR = WIDE_ARC_SEGS * WIDE_ARC_SEGS; - darkList = starList + 2; - glNewList(darkList, GL_COMPILE); - yy = -(float) (16); - t->begin(); - for (int xx = -s * d; xx <= s * d; xx += s) - { - for (int zz = -s * d; zz <= s * d; zz += s) - { - t->vertex((float)(xx + s), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + 0)); - t->vertex((float)(xx + 0), (float)( yy), (float)( zz + s)); - t->vertex((float)(xx + s), (float)( yy), (float)( zz + s)); - } - } - t->end(); - glEndList(); + float u = 0.0f; + float width = WIDTH; - // HALO ring for the texture pack - { - const unsigned int ARC_SEGMENTS = 50; - const float VERTICAL_OFFSET = HALO_RING_RADIUS * 999/1000; // How much we raise the circle origin to make the circle curve back towards us - const int WIDTH = 10; - const float ARC_RADIANS = 2.0f*PI/ARC_SEGMENTS; - const float HALF_ARC_SEG = ARC_SEGMENTS/2; - const float WIDE_ARC_SEGS = ARC_SEGMENTS/8; - const float WIDE_ARC_SEGS_SQR = WIDE_ARC_SEGS * WIDE_ARC_SEGS; + haloRingList = starList + 3; + glNewList(haloRingList, GL_COMPILE); + t->begin(GL_TRIANGLE_STRIP); + t->color(0xffffff); - float u = 0.0f; - float width = WIDTH; + for (unsigned int i = 0; i <= ARC_SEGMENTS; ++i) { + float DIFF = abs(i - HALF_ARC_SEG); + if (DIFF < (HALF_ARC_SEG - WIDE_ARC_SEGS)) + DIFF = 0; + else + DIFF -= (HALF_ARC_SEG - WIDE_ARC_SEGS); + width = 1 + ((DIFF * DIFF) / (WIDE_ARC_SEGS_SQR)) * WIDTH; + t->vertexUV( + (HALO_RING_RADIUS * cos(i * ARC_RADIANS)) - VERTICAL_OFFSET, + (HALO_RING_RADIUS * sin(i * ARC_RADIANS)), 0 - width, u, 0); + t->vertexUV( + (HALO_RING_RADIUS * cos(i * ARC_RADIANS)) - VERTICAL_OFFSET, + (HALO_RING_RADIUS * sin(i * ARC_RADIANS)), 0 + width, u, 1); + //--u; + u -= 0.25; + } + t->end(); + glEndList(); + } - haloRingList = starList + 3; - glNewList(haloRingList, GL_COMPILE); - t->begin(GL_TRIANGLE_STRIP); - t->color(0xffffff); + Chunk::levelRenderer = this; - for(unsigned int i = 0; i <= ARC_SEGMENTS; ++i) - { - float DIFF = abs(i - HALF_ARC_SEG); - if(DIFF<(HALF_ARC_SEG-WIDE_ARC_SEGS)) DIFF = 0; - else DIFF-=(HALF_ARC_SEG-WIDE_ARC_SEGS); - width = 1 + ( (DIFF * DIFF) / (WIDE_ARC_SEGS_SQR) ) * WIDTH; - t->vertexUV((HALO_RING_RADIUS * cos(i*ARC_RADIANS)) - VERTICAL_OFFSET, (HALO_RING_RADIUS * sin(i*ARC_RADIANS)), 0-width, u, 0); - t->vertexUV((HALO_RING_RADIUS * cos(i*ARC_RADIANS)) - VERTICAL_OFFSET, (HALO_RING_RADIUS * sin(i*ARC_RADIANS)), 0+width, u, 1); - //--u; - u -= 0.25; - } - t->end(); - glEndList(); - } + destroyedTileManager = new DestroyedTileManager(); - Chunk::levelRenderer = this; - - destroyedTileManager = new DestroyedTileManager(); - - dirtyChunksLockFreeStack.Initialize(); + dirtyChunksLockFreeStack.Initialize(); #ifdef __PS3__ - m_jobPort_CullSPU = new C4JSpursJobQueue::Port("C4JSpursJob_LevelRenderer_cull"); - m_jobPort_FindNearestChunk = new C4JSpursJobQueue::Port("C4JSpursJob_LevelRenderer_FindNearestChunk"); -#endif // __PS3__ + m_jobPort_CullSPU = + new C4JSpursJobQueue::Port("C4JSpursJob_LevelRenderer_cull"); + m_jobPort_FindNearestChunk = new C4JSpursJobQueue::Port( + "C4JSpursJob_LevelRenderer_FindNearestChunk"); +#endif // __PS3__ } -void LevelRenderer::renderStars() -{ - Random random = Random(10842); - Tesselator *t = Tesselator::getInstance(); - t->begin(); - for (int i = 0; i < 1500; i++) - { - double x = random.nextFloat() * 2 - 1; - double y = random.nextFloat() * 2 - 1; - double z = random.nextFloat() * 2 - 1; - double ss = 0.15f + random.nextFloat() * 0.10f; - double d = x * x + y * y + z * z; - if (d < 1 && d > 0.01) - { - d = 1 / sqrt(d); - x *= d; - y *= d; - z *= d; - double xp = x * 160; // 4J - moved further away (were 100) as they were cutting through far chunks - double yp = y * 160; - double zp = z * 160; +void LevelRenderer::renderStars() { + Random random = Random(10842); + Tesselator* t = Tesselator::getInstance(); + t->begin(); + for (int i = 0; i < 1500; i++) { + double x = random.nextFloat() * 2 - 1; + double y = random.nextFloat() * 2 - 1; + double z = random.nextFloat() * 2 - 1; + double ss = 0.15f + random.nextFloat() * 0.10f; + double d = x * x + y * y + z * z; + if (d < 1 && d > 0.01) { + d = 1 / sqrt(d); + x *= d; + y *= d; + z *= d; + double xp = x * 160; // 4J - moved further away (were 100) as they + // were cutting through far chunks + double yp = y * 160; + double zp = z * 160; - double yRot = atan2(x, z); - double ySin = sin(yRot); - double yCos = cos(yRot); + double yRot = atan2(x, z); + double ySin = sin(yRot); + double yCos = cos(yRot); - double xRot = atan2(sqrt(x * x + z * z), y); - double xSin = sin(xRot); - double xCos = cos(xRot); + double xRot = atan2(sqrt(x * x + z * z), y); + double xSin = sin(xRot); + double xCos = cos(xRot); - double zRot = random.nextDouble() * PI * 2; - double zSin = sin(zRot); - double zCos = cos(zRot); + double zRot = random.nextDouble() * PI * 2; + double zSin = sin(zRot); + double zCos = cos(zRot); - for (int c = 0; c < 4; c++) - { - double ___xo = 0; - double ___yo = ((c & 2) - 1) * ss; - double ___zo = (((c + 1) & 2) - 1) * ss; + for (int c = 0; c < 4; c++) { + double ___xo = 0; + double ___yo = ((c & 2) - 1) * ss; + double ___zo = (((c + 1) & 2) - 1) * ss; - double __xo = ___xo; - double __yo = ___yo * zCos - ___zo * zSin; - double __zo = ___zo * zCos + ___yo * zSin; + double __xo = ___xo; + double __yo = ___yo * zCos - ___zo * zSin; + double __zo = ___zo * zCos + ___yo * zSin; - double _zo = __zo; - double _yo = __yo * xSin + __xo * xCos; - double _xo = __xo * xSin - __yo * xCos; + double _zo = __zo; + double _yo = __yo * xSin + __xo * xCos; + double _xo = __xo * xSin - __yo * xCos; - double xo = _xo * ySin - _zo * yCos; - double yo = _yo; - double zo = _zo * ySin + _xo * yCos; - - t->vertex((float)(xp + xo), (float)( yp + yo), (float)( zp + zo)); - } - } - } - t->end(); + double xo = _xo * ySin - _zo * yCos; + double yo = _yo; + double zo = _zo * ySin + _xo * yCos; + t->vertex((float)(xp + xo), (float)(yp + yo), (float)(zp + zo)); + } + } + } + t->end(); } +void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel* level) { + if (this->level[playerIndex] != NULL) { + // Remove listener for this level if this is the last player referencing + // it + Level* prevLevel = this->level[playerIndex]; + int refCount = 0; + for (int i = 0; i < 4; i++) { + if (this->level[i] == prevLevel) refCount++; + } + if (refCount == 1) { + this->level[playerIndex]->removeListener(this); + } + } -void LevelRenderer::setLevel(int playerIndex, MultiPlayerLevel *level) -{ - if (this->level[playerIndex] != NULL) - { - // Remove listener for this level if this is the last player referencing it - Level *prevLevel = this->level[playerIndex]; - int refCount = 0; - for( int i = 0; i < 4; i++ ) - { - if( this->level[i] == prevLevel ) refCount++; - } - if( refCount == 1 ) - { - this->level[playerIndex]->removeListener(this); - } - } + xOld[playerIndex] = -9999; + yOld[playerIndex] = -9999; + zOld[playerIndex] = -9999; - xOld[playerIndex] = -9999; - yOld[playerIndex] = -9999; - zOld[playerIndex] = -9999; + this->level[playerIndex] = level; + if (tileRenderer[playerIndex] != NULL) { + delete tileRenderer[playerIndex]; + } + tileRenderer[playerIndex] = new TileRenderer(level); + if (level != NULL) { + // If we're the only player referencing this level, add a new listener + // for it + int refCount = 0; + for (int i = 0; i < 4; i++) { + if (this->level[i] == level) refCount++; + } + if (refCount == 1) { + level->addListener(this); + } - this->level[playerIndex] = level; - if( tileRenderer[playerIndex] != NULL ) - { - delete tileRenderer[playerIndex]; - } - tileRenderer[playerIndex] = new TileRenderer(level); - if (level != NULL) - { - // If we're the only player referencing this level, add a new listener for it - int refCount = 0; - for( int i = 0; i < 4; i++ ) - { - if( this->level[i] == level ) refCount++; - } - if( refCount == 1 ) - { - level->addListener(this); - } + allChanged(playerIndex); + } else { + // printf("NULLing player %d, chunks @ + //0x%x\n",playerIndex,chunks[playerIndex]); + if (chunks[playerIndex].data != NULL) { + for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { + chunks[playerIndex][i].chunk->_delete(); + delete chunks[playerIndex][i].chunk; + } + delete chunks[playerIndex].data; + chunks[playerIndex].data = NULL; + chunks[playerIndex].length = 0; + // delete sortedChunks[playerIndex]; // 4J - + //removed - not sorting our chunks anymore sortedChunks[playerIndex] + //= NULL; // 4J - removed - not sorting our chunks anymore + } - allChanged(playerIndex); - } - else - { - // printf("NULLing player %d, chunks @ 0x%x\n",playerIndex,chunks[playerIndex]); - if( chunks[playerIndex].data != NULL ) - { - for (unsigned int i = 0; i < chunks[playerIndex].length; i++) - { - chunks[playerIndex][i].chunk->_delete(); - delete chunks[playerIndex][i].chunk; - } - delete chunks[playerIndex].data; - chunks[playerIndex].data = NULL; - chunks[playerIndex].length = 0; - // delete sortedChunks[playerIndex]; // 4J - removed - not sorting our chunks anymore - // sortedChunks[playerIndex] = NULL; // 4J - removed - not sorting our chunks anymore - } - - // 4J Stu - If we do this for splitscreen players leaving, then all the tile entities in the world dissappear - // We should only do this when actually exiting the game, so only when the primary player sets there level to NULL - if(playerIndex == ProfileManager.GetPrimaryPad()) renderableTileEntities.clear(); - } + // 4J Stu - If we do this for splitscreen players leaving, then all the + // tile entities in the world dissappear We should only do this when + // actually exiting the game, so only when the primary player sets there + // level to NULL + if (playerIndex == ProfileManager.GetPrimaryPad()) + renderableTileEntities.clear(); + } } -void LevelRenderer::AddDLCSkinsToMemTextures() -{ - for(int i=0;iaddMemTexture(app.vSkinNames[i], new MobSkinMemTextureProcessor()); - } +void LevelRenderer::AddDLCSkinsToMemTextures() { + for (int i = 0; i < app.vSkinNames.size(); i++) { + textures->addMemTexture(app.vSkinNames[i], + new MobSkinMemTextureProcessor()); + } } -void LevelRenderer::allChanged() -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added - allChanged(playerIndex); +void LevelRenderer::allChanged() { + int playerIndex = mc->player->GetXboxPad(); // 4J added + allChanged(playerIndex); } -int LevelRenderer::activePlayers() -{ - int playerCount = 0; - for( int i = 0; i < 4; i++ ) - { - if( level[i] ) playerCount++; - } - return playerCount; +int LevelRenderer::activePlayers() { + int playerCount = 0; + for (int i = 0; i < 4; i++) { + if (level[i]) playerCount++; + } + return playerCount; } -void LevelRenderer::allChanged(int playerIndex) -{ - // 4J Stu - This was required by the threaded Minecraft::tick(). If we need to add it back then: - // If this CS is entered before DisableUpdateThread is called then (on 360 at least) we can get a - // deadlock when starting a game in splitscreen. - //EnterCriticalSection(&m_csDirtyChunks); - if( level[playerIndex] == NULL ) - { - return; - } +void LevelRenderer::allChanged(int playerIndex) { + // 4J Stu - This was required by the threaded Minecraft::tick(). If we need + // to add it back then: If this CS is entered before DisableUpdateThread is + // called then (on 360 at least) we can get a deadlock when starting a game + // in splitscreen. + // EnterCriticalSection(&m_csDirtyChunks); + if (level[playerIndex] == NULL) { + return; + } - Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); + Minecraft::GetInstance()->gameRenderer->DisableUpdateThread(); - Tile::leaves->setFancy(mc->options->fancyGraphics); - lastViewDistance = mc->options->viewDistance; + Tile::leaves->setFancy(mc->options->fancyGraphics); + lastViewDistance = mc->options->viewDistance; - // Calculate size of area we can render based on number of players we need to render for - int dist = (int)sqrtf( (float)PLAYER_RENDER_AREA / (float)activePlayers() ); + // Calculate size of area we can render based on number of players we need + // to render for + int dist = (int)sqrtf((float)PLAYER_RENDER_AREA / (float)activePlayers()); - // AP - poor little Vita just can't cope with such a big area + // AP - poor little Vita just can't cope with such a big area #ifdef __PSVITA__ - dist = 10; + dist = 10; #endif - lastPlayerCount[playerIndex] = activePlayers(); + lastPlayerCount[playerIndex] = activePlayers(); - xChunks = dist; - yChunks = Level::maxBuildHeight / CHUNK_SIZE; - zChunks = dist; + xChunks = dist; + yChunks = Level::maxBuildHeight / CHUNK_SIZE; + zChunks = dist; - if( chunks[playerIndex].data != NULL ) - { - for (unsigned int i = 0; i < chunks[playerIndex].length; i++) - { - chunks[playerIndex][i].chunk->_delete(); - delete chunks[playerIndex][i].chunk; - } - delete chunks[playerIndex].data; - // delete sortedChunks[playerIndex]; // 4J - removed - not sorting our chunks anymore - } + if (chunks[playerIndex].data != NULL) { + for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { + chunks[playerIndex][i].chunk->_delete(); + delete chunks[playerIndex][i].chunk; + } + delete chunks[playerIndex].data; + // delete sortedChunks[playerIndex]; // 4J - removed + //- not sorting our chunks anymore + } - chunks[playerIndex] = ClipChunkArray(xChunks * yChunks * zChunks); - // sortedChunks[playerIndex] = new std::vector(xChunks * yChunks * zChunks); // 4J - removed - not sorting our chunks anymore - int id = 0; - int count = 0; + chunks[playerIndex] = ClipChunkArray(xChunks * yChunks * zChunks); + // sortedChunks[playerIndex] = new std::vector(xChunks * yChunks * + //zChunks); // 4J - removed - not sorting our chunks anymore + int id = 0; + int count = 0; - xMinChunk = 0; - yMinChunk = 0; - zMinChunk = 0; - xMaxChunk = xChunks; - yMaxChunk = yChunks; - zMaxChunk = zChunks; + xMinChunk = 0; + yMinChunk = 0; + zMinChunk = 0; + xMaxChunk = xChunks; + yMaxChunk = yChunks; + zMaxChunk = zChunks; - // 4J removed - we now only fully clear this on exiting the game (setting level to NULL). Apart from that, the chunk rebuilding is responsible for maintaining this - // renderableTileEntities.clear(); + // 4J removed - we now only fully clear this on exiting the game (setting + // level to NULL). Apart from that, the chunk rebuilding is responsible for + // maintaining this + // renderableTileEntities.clear(); - for (int x = 0; x < xChunks; x++) - { - for (int y = 0; y < yChunks; y++) - { - for (int z = 0; z < zChunks; z++) - { - chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk = new Chunk(level[playerIndex], renderableTileEntities, m_csRenderableTileEntities, x * CHUNK_XZSIZE, y * CHUNK_SIZE, z * CHUNK_XZSIZE, &chunks[playerIndex][(z * yChunks + y) * xChunks + x]); - chunks[playerIndex][(z * yChunks + y) * xChunks + x].visible = true; - chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk->id = count++; - // sortedChunks[playerIndex]->at((z * yChunks + y) * xChunks + x) = chunks[playerIndex]->at((z * yChunks + y) * xChunks + x); // 4J - removed - not sorting our chunks anymore + for (int x = 0; x < xChunks; x++) { + for (int y = 0; y < yChunks; y++) { + for (int z = 0; z < zChunks; z++) { + chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk = + new Chunk( + level[playerIndex], renderableTileEntities, + m_csRenderableTileEntities, x * CHUNK_XZSIZE, + y * CHUNK_SIZE, z * CHUNK_XZSIZE, + &chunks[playerIndex][(z * yChunks + y) * xChunks + x]); + chunks[playerIndex][(z * yChunks + y) * xChunks + x].visible = + true; + chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk->id = + count++; + // sortedChunks[playerIndex]->at((z + //* yChunks + y) * xChunks + x) = chunks[playerIndex]->at((z * + //yChunks + y) * xChunks + x); // 4J - removed - not sorting + //our chunks anymore - id += 3; - } - } - } - nonStackDirtyChunksAdded(); + id += 3; + } + } + } + nonStackDirtyChunksAdded(); - if (level[playerIndex] != NULL) - { - std::shared_ptr player = mc->cameraTargetPlayer; - if (player != NULL) - { - this->resortChunks(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), DistanceChunkSorter(player)); // 4J - removed - not sorting our chunks anymore - } - } + if (level[playerIndex] != NULL) { + std::shared_ptr player = mc->cameraTargetPlayer; + if (player != NULL) { + this->resortChunks(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), + //DistanceChunkSorter(player)); // 4J - removed - not sorting + //our chunks anymore + } + } - noEntityRenderFrames = 2; + noEntityRenderFrames = 2; - Minecraft::GetInstance()->gameRenderer->EnableUpdateThread(); + Minecraft::GetInstance()->gameRenderer->EnableUpdateThread(); - // 4J Stu - Remove. See comment above. - //LeaveCriticalSection(&m_csDirtyChunks); + // 4J Stu - Remove. See comment above. + // LeaveCriticalSection(&m_csDirtyChunks); } -void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added +void LevelRenderer::renderEntities(Vec3* cam, Culler* culler, float a) { + int playerIndex = mc->player->GetXboxPad(); // 4J added - // 4J Stu - Set these up every time, even when not rendering as other things (like particle render) may depend on it for those frames. - TileEntityRenderDispatcher::instance->prepare(level[playerIndex], textures, mc->font, mc->cameraTargetPlayer, a); - EntityRenderDispatcher::instance->prepare(level[playerIndex], textures, mc->font, mc->cameraTargetPlayer, mc->options, a); + // 4J Stu - Set these up every time, even when not rendering as other things + // (like particle render) may depend on it for those frames. + TileEntityRenderDispatcher::instance->prepare( + level[playerIndex], textures, mc->font, mc->cameraTargetPlayer, a); + EntityRenderDispatcher::instance->prepare(level[playerIndex], textures, + mc->font, mc->cameraTargetPlayer, + mc->options, a); - if (noEntityRenderFrames > 0) - { - noEntityRenderFrames--; - return; - } + if (noEntityRenderFrames > 0) { + noEntityRenderFrames--; + return; + } - totalEntities = 0; - renderedEntities = 0; - culledEntities = 0; + totalEntities = 0; + renderedEntities = 0; + culledEntities = 0; - std::shared_ptr player = mc->cameraTargetPlayer; + std::shared_ptr player = mc->cameraTargetPlayer; - EntityRenderDispatcher::xOff = (player->xOld + (player->x - player->xOld) * a); - EntityRenderDispatcher::yOff = (player->yOld + (player->y - player->yOld) * a); - EntityRenderDispatcher::zOff = (player->zOld + (player->z - player->zOld) * a); - TileEntityRenderDispatcher::xOff = (player->xOld + (player->x - player->xOld) * a); - TileEntityRenderDispatcher::yOff = (player->yOld + (player->y - player->yOld) * a); - TileEntityRenderDispatcher::zOff = (player->zOld + (player->z - player->zOld) * a); + EntityRenderDispatcher::xOff = + (player->xOld + (player->x - player->xOld) * a); + EntityRenderDispatcher::yOff = + (player->yOld + (player->y - player->yOld) * a); + EntityRenderDispatcher::zOff = + (player->zOld + (player->z - player->zOld) * a); + TileEntityRenderDispatcher::xOff = + (player->xOld + (player->x - player->xOld) * a); + TileEntityRenderDispatcher::yOff = + (player->yOld + (player->y - player->yOld) * a); + TileEntityRenderDispatcher::zOff = + (player->zOld + (player->z - player->zOld) * a); - mc->gameRenderer->turnOnLightLayer(a, true); // 4J - brought forward from 1.8.2 + mc->gameRenderer->turnOnLightLayer( + a, true); // 4J - brought forward from 1.8.2 - std::vector > entities = level[playerIndex]->getAllEntities(); - totalEntities = (int)entities.size(); + std::vector > entities = + level[playerIndex]->getAllEntities(); + totalEntities = (int)entities.size(); - AUTO_VAR(itEndGE, level[playerIndex]->globalEntities.end()); - for (AUTO_VAR(it, level[playerIndex]->globalEntities.begin()); it != itEndGE; it++) - { - std::shared_ptr entity = *it; //level->globalEntities[i]; - renderedEntities++; - if (entity->shouldRender(cam)) EntityRenderDispatcher::instance->render(entity, a); - } + AUTO_VAR(itEndGE, level[playerIndex]->globalEntities.end()); + for (AUTO_VAR(it, level[playerIndex]->globalEntities.begin()); + it != itEndGE; it++) { + std::shared_ptr entity = *it; // level->globalEntities[i]; + renderedEntities++; + if (entity->shouldRender(cam)) + EntityRenderDispatcher::instance->render(entity, a); + } - AUTO_VAR(itEndEnts, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEndEnts; it++) - { - std::shared_ptr entity = *it; //entities[i]; + AUTO_VAR(itEndEnts, entities.end()); + for (AUTO_VAR(it, entities.begin()); it != itEndEnts; it++) { + std::shared_ptr entity = *it; // entities[i]; - if ((entity->shouldRender(cam) && (entity->noCulling || culler->isVisible(entity->bb)))) - { - // 4J-PB - changing this to be per player - //if (entity == mc->cameraTargetPlayer && !mc->options->thirdPersonView && !mc->cameraTargetPlayer->isSleeping()) continue; - std::shared_ptr localplayer = std::dynamic_pointer_cast(mc->cameraTargetPlayer); + if ((entity->shouldRender(cam) && + (entity->noCulling || culler->isVisible(entity->bb)))) { + // 4J-PB - changing this to be per player + // if (entity == mc->cameraTargetPlayer && + // !mc->options->thirdPersonView && + // !mc->cameraTargetPlayer->isSleeping()) continue; + std::shared_ptr localplayer = + std::dynamic_pointer_cast(mc->cameraTargetPlayer); - if (localplayer && entity == mc->cameraTargetPlayer && !localplayer->ThirdPersonView() && !mc->cameraTargetPlayer->isSleeping()) continue; + if (localplayer && entity == mc->cameraTargetPlayer && + !localplayer->ThirdPersonView() && + !mc->cameraTargetPlayer->isSleeping()) + continue; - if (!level[playerIndex]->hasChunkAt(Mth::floor(entity->x), 0, Mth::floor(entity->z))) - { - continue; - } - renderedEntities++; - EntityRenderDispatcher::instance->render(entity, a); - } - } + if (!level[playerIndex]->hasChunkAt(Mth::floor(entity->x), 0, + Mth::floor(entity->z))) { + continue; + } + renderedEntities++; + EntityRenderDispatcher::instance->render(entity, a); + } + } - Lighting::turnOn(); - // 4J - have restructed this so that the tile entities are stored within a hashmap by chunk/dimension index. The index - // is calculated in the same way as the global flags. - EnterCriticalSection(&m_csRenderableTileEntities); - for (AUTO_VAR(it, renderableTileEntities.begin()); it != renderableTileEntities.end(); it++) - { - int idx = it->first; - // Don't render if it isn't in the same dimension as this player - if( !isGlobalIndexInSameDimension(idx, level[playerIndex]) ) continue; + Lighting::turnOn(); + // 4J - have restructed this so that the tile entities are stored within a + // hashmap by chunk/dimension index. The index is calculated in the same way + // as the global flags. + EnterCriticalSection(&m_csRenderableTileEntities); + for (AUTO_VAR(it, renderableTileEntities.begin()); + it != renderableTileEntities.end(); it++) { + int idx = it->first; + // Don't render if it isn't in the same dimension as this player + if (!isGlobalIndexInSameDimension(idx, level[playerIndex])) continue; - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++) - { - TileEntityRenderDispatcher::instance->render(*it2, a); - } - } + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); + it2++) { + TileEntityRenderDispatcher::instance->render(*it2, a); + } + } - // Now consider if any of these renderable tile entities have been flagged for removal, and if so, remove - for (AUTO_VAR(it, renderableTileEntities.begin()); it != renderableTileEntities.end();) - { - int idx = it->first; + // Now consider if any of these renderable tile entities have been flagged + // for removal, and if so, remove + for (AUTO_VAR(it, renderableTileEntities.begin()); + it != renderableTileEntities.end();) { + int idx = it->first; - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); ) - { - // If it has been flagged for removal, remove - if((*it2)->shouldRemoveForRender()) - { - it2 = it->second.erase(it2); - } - else - { - it2++; - } - } + for (AUTO_VAR(it2, it->second.begin()); it2 != it->second.end();) { + // If it has been flagged for removal, remove + if ((*it2)->shouldRemoveForRender()) { + it2 = it->second.erase(it2); + } else { + it2++; + } + } - // If there aren't any entities left for this key, then delete the key - if( it->second.size() == 0 ) - { - it = renderableTileEntities.erase(it); - } - else - { - it++; - } - } + // If there aren't any entities left for this key, then delete the key + if (it->second.size() == 0) { + it = renderableTileEntities.erase(it); + } else { + it++; + } + } - LeaveCriticalSection(&m_csRenderableTileEntities); + LeaveCriticalSection(&m_csRenderableTileEntities); - mc->gameRenderer->turnOffLightLayer(a); // 4J - brought forward from 1.8.2 + mc->gameRenderer->turnOffLightLayer(a); // 4J - brought forward from 1.8.2 } -std::wstring LevelRenderer::gatherStats1() -{ - return L"C: " + _toString(renderedChunks) + L"/" + _toString(totalChunks) + L". F: " + _toString(offscreenChunks) + L", O: " + _toString(occludedChunks) + L", E: " + _toString(emptyChunks); +std::wstring LevelRenderer::gatherStats1() { + return L"C: " + _toString(renderedChunks) + L"/" + + _toString(totalChunks) + L". F: " + + _toString(offscreenChunks) + L", O: " + + _toString(occludedChunks) + L", E: " + + _toString(emptyChunks); } -std::wstring LevelRenderer::gatherStats2() -{ - return L"E: " + _toString(renderedEntities) + L"/" + _toString(totalEntities) + L". B: " + _toString(culledEntities) + L", I: " + _toString((totalEntities - culledEntities) - renderedEntities); +std::wstring LevelRenderer::gatherStats2() { + return L"E: " + _toString(renderedEntities) + L"/" + + _toString(totalEntities) + L". B: " + + _toString(culledEntities) + L", I: " + + _toString((totalEntities - culledEntities) - renderedEntities); } -void LevelRenderer::resortChunks(int xc, int yc, int zc) -{ - EnterCriticalSection(&m_csDirtyChunks); - xc -= CHUNK_XZSIZE / 2; - yc -= CHUNK_SIZE / 2; - zc -= CHUNK_XZSIZE / 2; - xMinChunk = INT_MAX; - yMinChunk = INT_MAX; - zMinChunk = INT_MAX; - xMaxChunk = INT_MIN; - yMaxChunk = INT_MIN; - zMaxChunk = INT_MIN; +void LevelRenderer::resortChunks(int xc, int yc, int zc) { + EnterCriticalSection(&m_csDirtyChunks); + xc -= CHUNK_XZSIZE / 2; + yc -= CHUNK_SIZE / 2; + zc -= CHUNK_XZSIZE / 2; + xMinChunk = INT_MAX; + yMinChunk = INT_MAX; + zMinChunk = INT_MAX; + xMaxChunk = INT_MIN; + yMaxChunk = INT_MIN; + zMaxChunk = INT_MIN; - int playerIndex = mc->player->GetXboxPad(); // 4J added + int playerIndex = mc->player->GetXboxPad(); // 4J added - int s2 = xChunks * CHUNK_XZSIZE; - int s1 = s2 / 2; + int s2 = xChunks * CHUNK_XZSIZE; + int s1 = s2 / 2; - for (int x = 0; x < xChunks; x++) - { - int xx = x * CHUNK_XZSIZE; + for (int x = 0; x < xChunks; x++) { + int xx = x * CHUNK_XZSIZE; - int xOff = (xx + s1 - xc); - if (xOff < 0) xOff -= (s2 - 1); - xOff /= s2; - xx -= xOff * s2; + int xOff = (xx + s1 - xc); + if (xOff < 0) xOff -= (s2 - 1); + xOff /= s2; + xx -= xOff * s2; - if (xx < xMinChunk) xMinChunk = xx; - if (xx > xMaxChunk) xMaxChunk = xx; + if (xx < xMinChunk) xMinChunk = xx; + if (xx > xMaxChunk) xMaxChunk = xx; - for (int z = 0; z < zChunks; z++) - { - int zz = z * CHUNK_XZSIZE; - int zOff = (zz + s1 - zc); - if (zOff < 0) zOff -= (s2 - 1); - zOff /= s2; - zz -= zOff * s2; + for (int z = 0; z < zChunks; z++) { + int zz = z * CHUNK_XZSIZE; + int zOff = (zz + s1 - zc); + if (zOff < 0) zOff -= (s2 - 1); + zOff /= s2; + zz -= zOff * s2; - if (zz < zMinChunk) zMinChunk = zz; - if (zz > zMaxChunk) zMaxChunk = zz; + if (zz < zMinChunk) zMinChunk = zz; + if (zz > zMaxChunk) zMaxChunk = zz; - for (int y = 0; y < yChunks; y++) - { - int yy = y * CHUNK_SIZE; - if (yy < yMinChunk) yMinChunk = yy; - if (yy > yMaxChunk) yMaxChunk = yy; + for (int y = 0; y < yChunks; y++) { + int yy = y * CHUNK_SIZE; + if (yy < yMinChunk) yMinChunk = yy; + if (yy > yMaxChunk) yMaxChunk = yy; - Chunk *chunk = chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk; - chunk->setPos(xx, yy, zz); - } - } - } - nonStackDirtyChunksAdded(); - LeaveCriticalSection(&m_csDirtyChunks); + Chunk* chunk = + chunks[playerIndex][(z * yChunks + y) * xChunks + x].chunk; + chunk->setPos(xx, yy, zz); + } + } + } + nonStackDirtyChunksAdded(); + LeaveCriticalSection(&m_csDirtyChunks); } -int LevelRenderer::render(std::shared_ptr player, int layer, double alpha, bool updateChunks) -{ - int playerIndex = mc->player->GetXboxPad(); +int LevelRenderer::render(std::shared_ptr player, int layer, double alpha, + bool updateChunks) { + int playerIndex = mc->player->GetXboxPad(); - // 4J - added - if the number of players has changed, we need to rebuild things for the new draw distance this will require - if( lastPlayerCount[playerIndex] != activePlayers() ) - { - allChanged(); - } - else if (mc->options->viewDistance != lastViewDistance) - { - allChanged(); - } + // 4J - added - if the number of players has changed, we need to rebuild + // things for the new draw distance this will require + if (lastPlayerCount[playerIndex] != activePlayers()) { + allChanged(); + } else if (mc->options->viewDistance != lastViewDistance) { + allChanged(); + } - if (layer == 0) - { - totalChunks = 0; - offscreenChunks = 0; - occludedChunks = 0; - renderedChunks = 0; - emptyChunks = 0; - } + if (layer == 0) { + totalChunks = 0; + offscreenChunks = 0; + occludedChunks = 0; + renderedChunks = 0; + emptyChunks = 0; + } - double xOff = player->xOld + (player->x - player->xOld) * alpha; - double yOff = player->yOld + (player->y - player->yOld) * alpha; - double zOff = player->zOld + (player->z - player->zOld) * alpha; + double xOff = player->xOld + (player->x - player->xOld) * alpha; + double yOff = player->yOld + (player->y - player->yOld) * alpha; + double zOff = player->zOld + (player->z - player->zOld) * alpha; - double xd = player->x - xOld[playerIndex]; - double yd = player->y - yOld[playerIndex]; - double zd = player->z - zOld[playerIndex]; + double xd = player->x - xOld[playerIndex]; + double yd = player->y - yOld[playerIndex]; + double zd = player->z - zOld[playerIndex]; - if (xd * xd + yd * yd + zd * zd > 4 * 4) - { - xOld[playerIndex] = player->x; - yOld[playerIndex] = player->y; - zOld[playerIndex] = player->z; + if (xd * xd + yd * yd + zd * zd > 4 * 4) { + xOld[playerIndex] = player->x; + yOld[playerIndex] = player->y; + zOld[playerIndex] = player->z; - resortChunks(Mth::floor(player->x), Mth::floor(player->y), Mth::floor(player->z)); - // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), DistanceChunkSorter(player)); // 4J - removed - not sorting our chunks anymore - } - Lighting::turnOff(); - glColor4f(1, 1, 1, 1); - glColor4f(1, 1, 1, 1); + resortChunks(Mth::floor(player->x), Mth::floor(player->y), + Mth::floor(player->z)); + // sort(sortedChunks[playerIndex]->begin(),sortedChunks[playerIndex]->end(), + //DistanceChunkSorter(player)); // 4J - removed - not sorting our chunks + //anymore + } + Lighting::turnOff(); + glColor4f(1, 1, 1, 1); + glColor4f(1, 1, 1, 1); - int count = renderChunks(0, (int)chunks[playerIndex].length, layer, alpha); - - return count; + int count = renderChunks(0, (int)chunks[playerIndex].length, layer, alpha); + return count; } #ifdef __PSVITA__ #include // this is need to sort the chunks by depth -typedef struct -{ - int Index; - float Depth; +typedef struct { + int Index; + float Depth; } SChunckSort; -int compare (const void * a, const void * b) -{ - return ( ((SChunckSort*)a)->Depth - ((SChunckSort*)b)->Depth ); +int compare(const void* a, const void* b) { + return (((SChunckSort*)a)->Depth - ((SChunckSort*)b)->Depth); } #endif -int LevelRenderer::renderChunks(int from, int to, int layer, double alpha) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added +int LevelRenderer::renderChunks(int from, int to, int layer, double alpha) { + int playerIndex = mc->player->GetXboxPad(); // 4J added #if 1 - // 4J - cut down version, we're not using offsetted render lists, or a sorted chunk list, anymore - mc->gameRenderer->turnOnLightLayer(alpha); // 4J - brought forward from 1.8.2 - std::shared_ptr player = mc->cameraTargetPlayer; - double xOff = player->xOld + (player->x - player->xOld) * alpha; - double yOff = player->yOld + (player->y - player->yOld) * alpha; - double zOff = player->zOld + (player->z - player->zOld) * alpha; + // 4J - cut down version, we're not using offsetted render lists, or a + // sorted chunk list, anymore + mc->gameRenderer->turnOnLightLayer( + alpha); // 4J - brought forward from 1.8.2 + std::shared_ptr player = mc->cameraTargetPlayer; + double xOff = player->xOld + (player->x - player->xOld) * alpha; + double yOff = player->yOld + (player->y - player->yOld) * alpha; + double zOff = player->zOld + (player->z - player->zOld) * alpha; - glPushMatrix(); - glTranslatef((float)-xOff, (float)-yOff, (float)-zOff); + glPushMatrix(); + glTranslatef((float)-xOff, (float)-yOff, (float)-zOff); #ifdef __PSVITA__ - // AP - also set the camera position so we can work out if a chunk is fogged or not - RenderManager.SetCameraPosition((float)-xOff, (float)-yOff, (float)-zOff); + // AP - also set the camera position so we can work out if a chunk is fogged + // or not + RenderManager.SetCameraPosition((float)-xOff, (float)-yOff, (float)-zOff); #endif #if defined __PS3__ && !defined DISABLE_SPU_CODE - // pre- calc'd on the SPU - int count = 0; - waitForCull_SPU(); - if(layer == 0) - { - count = g_cullDataIn[playerIndex].numToRender_layer0; - RenderManager.CBuffCallMultiple(g_cullDataIn[playerIndex].listArray_layer0, count); - } - else // layer == 1 - { - count = g_cullDataIn[playerIndex].numToRender_layer1; - RenderManager.CBuffCallMultiple(g_cullDataIn[playerIndex].listArray_layer1, count); - } + // pre- calc'd on the SPU + int count = 0; + waitForCull_SPU(); + if (layer == 0) { + count = g_cullDataIn[playerIndex].numToRender_layer0; + RenderManager.CBuffCallMultiple( + g_cullDataIn[playerIndex].listArray_layer0, count); + } else // layer == 1 + { + count = g_cullDataIn[playerIndex].numToRender_layer1; + RenderManager.CBuffCallMultiple( + g_cullDataIn[playerIndex].listArray_layer1, count); + } -#else // __PS3__ +#else // __PS3__ #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. First render all the non-alpha cut outs - glDisable(GL_ALPHA_TEST); + // AP - alpha cut out is expensive on vita. First render all the non-alpha + // cut outs + glDisable(GL_ALPHA_TEST); #endif - bool first = true; - int count = 0; - int dbgNotVisible = 0, dbgNoIdx = 0, dbgEmpty = 0, dbgCalled = 0, dbgCallOk = 0; - ClipChunk *pClipChunk = chunks[playerIndex].data; - unsigned char emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; - for( int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++ ) - { - if( !pClipChunk->visible ) { dbgNotVisible++; continue; } - if( pClipChunk->globalIdx == -1 ) { dbgNoIdx++; continue; } - if( ( globalChunkFlags[pClipChunk->globalIdx] & emptyFlag ) == emptyFlag ) { dbgEmpty++; continue; } + bool first = true; + int count = 0; + int dbgNotVisible = 0, dbgNoIdx = 0, dbgEmpty = 0, dbgCalled = 0, + dbgCallOk = 0; + ClipChunk* pClipChunk = chunks[playerIndex].data; + unsigned char emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; + for (int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++) { + if (!pClipChunk->visible) { + dbgNotVisible++; + continue; + } + if (pClipChunk->globalIdx == -1) { + dbgNoIdx++; + continue; + } + if ((globalChunkFlags[pClipChunk->globalIdx] & emptyFlag) == + emptyFlag) { + dbgEmpty++; + continue; + } - // List can be calculated directly from the chunk's global idex - int list = pClipChunk->globalIdx * 2 + layer; - list += chunkLists; + // List can be calculated directly from the chunk's global idex + int list = pClipChunk->globalIdx * 2 + layer; + list += chunkLists; - dbgCalled++; - if(RenderManager.CBuffCall(list, first)) - { - first = false; - dbgCallOk++; - } - count++; - } - static int _dbgRC = 0; - _dbgRC++; - if (_dbgRC <= 2 || (_dbgRC % 3000 == 0)) { - fprintf(stderr, "[RENDER] renderChunks frame=%d layer=%d total=%d notVis=%d noIdx=%d empty=%d called=%d callOk=%d chunkLists=%d\n", - _dbgRC, layer, chunks[playerIndex].length, dbgNotVisible, dbgNoIdx, dbgEmpty, dbgCalled, dbgCallOk, chunkLists); - fflush(stderr); - } + dbgCalled++; + if (RenderManager.CBuffCall(list, first)) { + first = false; + dbgCallOk++; + } + count++; + } + static int _dbgRC = 0; + _dbgRC++; + if (_dbgRC <= 2 || (_dbgRC % 3000 == 0)) { + fprintf(stderr, + "[RENDER] renderChunks frame=%d layer=%d total=%d notVis=%d " + "noIdx=%d empty=%d called=%d callOk=%d chunkLists=%d\n", + _dbgRC, layer, chunks[playerIndex].length, dbgNotVisible, + dbgNoIdx, dbgEmpty, dbgCalled, dbgCallOk, chunkLists); + fflush(stderr); + } #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Now we render all the alpha cut outs - glEnable(GL_ALPHA_TEST); - RenderManager.StateSetForceLOD(0); // AP - force mipmapping off for cut outs - first = true; - pClipChunk = chunks[playerIndex].data; - emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; - for( int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++ ) - { - if( !pClipChunk->visible ) continue; // This will be set if the chunk isn't visible, or isn't compiled, or has both empty flags set - if( pClipChunk->globalIdx == -1 ) continue; // Not sure if we should ever encounter this... TODO check - if( ( globalChunkFlags[pClipChunk->globalIdx] & emptyFlag ) == emptyFlag ) continue; // Check that this particular layer isn't empty - if( !(globalChunkFlags[pClipChunk->globalIdx] & LevelRenderer::CHUNK_FLAG_CUT_OUT) ) continue; // Does this chunk contain any cut out geometry + // AP - alpha cut out is expensive on vita. Now we render all the alpha cut + // outs + glEnable(GL_ALPHA_TEST); + RenderManager.StateSetForceLOD( + 0); // AP - force mipmapping off for cut outs + first = true; + pClipChunk = chunks[playerIndex].data; + emptyFlag = LevelRenderer::CHUNK_FLAG_EMPTY0 << layer; + for (int i = 0; i < chunks[playerIndex].length; i++, pClipChunk++) { + if (!pClipChunk->visible) + continue; // This will be set if the chunk isn't visible, or isn't + // compiled, or has both empty flags set + if (pClipChunk->globalIdx == -1) + continue; // Not sure if we should ever encounter this... TODO + // check + if ((globalChunkFlags[pClipChunk->globalIdx] & emptyFlag) == emptyFlag) + continue; // Check that this particular layer isn't empty + if (!(globalChunkFlags[pClipChunk->globalIdx] & + LevelRenderer::CHUNK_FLAG_CUT_OUT)) + continue; // Does this chunk contain any cut out geometry - // List can be calculated directly from the chunk's global idex - int list = pClipChunk->globalIdx * 2 + layer; - list += chunkLists; + // List can be calculated directly from the chunk's global idex + int list = pClipChunk->globalIdx * 2 + layer; + list += chunkLists; - if(RenderManager.CBuffCallCutOut(list, first)) - { - first = false; - } - } - RenderManager.StateSetForceLOD(-1); // AP - back to normal mipmapping + if (RenderManager.CBuffCallCutOut(list, first)) { + first = false; + } + } + RenderManager.StateSetForceLOD(-1); // AP - back to normal mipmapping #endif -#endif // __PS3__ +#endif // __PS3__ - glPopMatrix(); - mc->gameRenderer->turnOffLightLayer(alpha); // 4J - brought forward from 1.8.2 + glPopMatrix(); + mc->gameRenderer->turnOffLightLayer( + alpha); // 4J - brought forward from 1.8.2 #else - _renderChunks.clear(); - // int p = 0; - int count = 0; - for (int i = from; i < to; i++) - { - if (layer == 0) - { - totalChunks++; - if (sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer)) emptyChunks++; - else if (!sortedChunks[playerIndex]->at(i)->visible) offscreenChunks++; - else renderedChunks++; - } + _renderChunks.clear(); + // int p = 0; + int count = 0; + for (int i = from; i < to; i++) { + if (layer == 0) { + totalChunks++; + if (sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer)) + emptyChunks++; + else if (!sortedChunks[playerIndex]->at(i)->visible) + offscreenChunks++; + else + renderedChunks++; + } - // if (!sortedChunks[i].empty[layer] && sortedChunks[i].visible && (sortedChunks[i].occlusion_visible)) { - if (!(sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer) && sortedChunks[playerIndex]->at(i)->visible )) - { - int list = sortedChunks[playerIndex]->at(i)->getList(layer); - if (list >= 0) - { - _renderChunks.push_back(sortedChunks[playerIndex]->at(i)); - count++; - } - } - } + // if (!sortedChunks[i].empty[layer] && + // sortedChunks[i].visible && + // (sortedChunks[i].occlusion_visible)) { + if (!(sortedChunks[playerIndex]->at(i)->emptyFlagSet(layer) && + sortedChunks[playerIndex]->at(i)->visible)) { + int list = sortedChunks[playerIndex]->at(i)->getList(layer); + if (list >= 0) { + _renderChunks.push_back(sortedChunks[playerIndex]->at(i)); + count++; + } + } + } - std::shared_ptr player = mc->cameraTargetPlayer; - double xOff = player->xOld + (player->x - player->xOld) * alpha; - double yOff = player->yOld + (player->y - player->yOld) * alpha; - double zOff = player->zOld + (player->z - player->zOld) * alpha; + std::shared_ptr player = mc->cameraTargetPlayer; + double xOff = player->xOld + (player->x - player->xOld) * alpha; + double yOff = player->yOld + (player->y - player->yOld) * alpha; + double zOff = player->zOld + (player->z - player->zOld) * alpha; - int lists = 0; - for (int l = 0; l < RENDERLISTS_LENGTH; l++) - { - renderLists[l].clear(); - } + int lists = 0; + for (int l = 0; l < RENDERLISTS_LENGTH; l++) { + renderLists[l].clear(); + } - AUTO_VAR(itEnd, _renderChunks.end()); - for (AUTO_VAR(it, _renderChunks.begin()); it != itEnd; it++) - { - Chunk *chunk = *it; //_renderChunks[i]; + AUTO_VAR(itEnd, _renderChunks.end()); + for (AUTO_VAR(it, _renderChunks.begin()); it != itEnd; it++) { + Chunk* chunk = *it; //_renderChunks[i]; - int list = -1; - for (int l = 0; l < lists; l++) - { - if (renderLists[l].isAt(chunk->xRender, chunk->yRender, chunk->zRender)) - { - list = l; - } - } - if (list < 0) - { - list = lists++; - renderLists[list].init(chunk->xRender, chunk->yRender, chunk->zRender, xOff, yOff, zOff); - } + int list = -1; + for (int l = 0; l < lists; l++) { + if (renderLists[l].isAt(chunk->xRender, chunk->yRender, + chunk->zRender)) { + list = l; + } + } + if (list < 0) { + list = lists++; + renderLists[list].init(chunk->xRender, chunk->yRender, + chunk->zRender, xOff, yOff, zOff); + } - renderLists[list].add(chunk->getList(layer)); - } + renderLists[list].add(chunk->getList(layer)); + } - renderSameAsLast(layer, alpha); + renderSameAsLast(layer, alpha); #endif - return count; - + return count; } - -void LevelRenderer::renderSameAsLast(int layer, double alpha) -{ - for (int i = 0; i < RENDERLISTS_LENGTH; i++) - { - renderLists[i].render(); - } +void LevelRenderer::renderSameAsLast(int layer, double alpha) { + for (int i = 0; i < RENDERLISTS_LENGTH; i++) { + renderLists[i].render(); + } } -void LevelRenderer::tick() -{ - ticks++; +void LevelRenderer::tick() { + ticks++; - if ((ticks % SharedConstants::TICKS_PER_SECOND) == 0) - { - AUTO_VAR(it , destroyingBlocks.begin()); - while (it != destroyingBlocks.end()) - { - BlockDestructionProgress *block = it->second; + if ((ticks % SharedConstants::TICKS_PER_SECOND) == 0) { + AUTO_VAR(it, destroyingBlocks.begin()); + while (it != destroyingBlocks.end()) { + BlockDestructionProgress* block = it->second; - int updatedRenderTick = block->getUpdatedRenderTick(); + int updatedRenderTick = block->getUpdatedRenderTick(); - if (ticks - updatedRenderTick > (SharedConstants::TICKS_PER_SECOND * 20)) - { - delete it->second; - it = destroyingBlocks.erase(it); - } - else - { - ++it; - } - } - } + if (ticks - updatedRenderTick > + (SharedConstants::TICKS_PER_SECOND * 20)) { + delete it->second; + it = destroyingBlocks.erase(it); + } else { + ++it; + } + } + } } -void LevelRenderer::renderSky(float alpha) -{ - if (mc->level->dimension->id == 1) - { - glDisable(GL_FOG); - glDisable(GL_ALPHA_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Lighting::turnOff(); - glColor4f(1, 1, 1, 1); +void LevelRenderer::renderSky(float alpha) { + if (mc->level->dimension->id == 1) { + glDisable(GL_FOG); + glDisable(GL_ALPHA_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Lighting::turnOff(); + glColor4f(1, 1, 1, 1); + glDepthMask(false); + textures->bind(textures->loadTexture( + TN_MISC_TUNNEL)); // 4J was L"/1_2_2/misc/tunnel.png" + Tesselator* t = Tesselator::getInstance(); + t->setMipmapEnable(false); + for (int i = 0; i < 6; i++) { + glPushMatrix(); + if (i == 1) glRotatef(90, 1, 0, 0); + if (i == 2) glRotatef(-90, 1, 0, 0); + if (i == 3) glRotatef(180, 1, 0, 0); + if (i == 4) glRotatef(90, 0, 0, 1); + if (i == 5) glRotatef(-90, 0, 0, 1); + t->begin(); + t->color(0x282828); + t->vertexUV(-100, -100, -100, 0, 0); + t->vertexUV(-100, -100, +100, 0, 16); + t->vertexUV(+100, -100, +100, 16, 16); + t->vertexUV(+100, -100, -100, 16, 0); + t->end(); + glPopMatrix(); + } + t->setMipmapEnable(true); + glDepthMask(true); + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); - glDepthMask(false); - textures->bind(textures->loadTexture(TN_MISC_TUNNEL)); // 4J was L"/1_2_2/misc/tunnel.png" - Tesselator *t = Tesselator::getInstance(); - t->setMipmapEnable(false); - for (int i = 0; i < 6; i++) - { - glPushMatrix(); - if (i == 1) glRotatef(90, 1, 0, 0); - if (i == 2) glRotatef(-90, 1, 0, 0); - if (i == 3) glRotatef(180, 1, 0, 0); - if (i == 4) glRotatef(90, 0, 0, 1); - if (i == 5) glRotatef(-90, 0, 0, 1); - t->begin(); - t->color(0x282828); - t->vertexUV(-100, -100, -100, 0, 0); - t->vertexUV(-100, -100, +100, 0, 16); - t->vertexUV(+100, -100, +100, 16, 16); - t->vertexUV(+100, -100, -100, 16, 0); - t->end(); - glPopMatrix(); - } - t->setMipmapEnable(true); - glDepthMask(true); - glEnable(GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); + return; + } - return; - } + if (!mc->level->dimension->isNaturalDimension()) return; - if (!mc->level->dimension->isNaturalDimension()) return; + glDisable(GL_TEXTURE_2D); - glDisable(GL_TEXTURE_2D); + int playerIndex = mc->player->GetXboxPad(); + Vec3* sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); + float sr = (float)sc->x; + float sg = (float)sc->y; + float sb = (float)sc->z; - int playerIndex = mc->player->GetXboxPad(); - Vec3 *sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); - float sr = (float) sc->x; - float sg = (float) sc->y; - float sb = (float) sc->z; + if (mc->options->anaglyph3d) { + float srr = (sr * 30 + sg * 59 + sb * 11) / 100; + float sgg = (sr * 30 + sg * 70) / (100); + float sbb = (sr * 30 + sb * 70) / (100); - if (mc->options->anaglyph3d) - { - float srr = (sr * 30 + sg * 59 + sb * 11) / 100; - float sgg = (sr * 30 + sg * 70) / (100); - float sbb = (sr * 30 + sb * 70) / (100); + sr = srr; + sg = sgg; + sb = sbb; + } - sr = srr; - sg = sgg; - sb = sbb; - } + glColor3f(sr, sg, sb); - glColor3f(sr, sg, sb); + Tesselator* t = Tesselator::getInstance(); - Tesselator *t = Tesselator::getInstance(); - - glDepthMask(false); + glDepthMask(false); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. - glDisable(GL_ALPHA_TEST); + // AP - alpha cut out is expensive on vita. + glDisable(GL_ALPHA_TEST); #endif - glEnable(GL_FOG); - glColor3f(sr, sg, sb); - glCallList(skyList); + glEnable(GL_FOG); + glColor3f(sr, sg, sb); + glCallList(skyList); - glDisable(GL_FOG); - glDisable(GL_ALPHA_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Lighting::turnOff(); - glColor4f(1, 1, 1, 1); + glDisable(GL_FOG); + glDisable(GL_ALPHA_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Lighting::turnOff(); + glColor4f(1, 1, 1, 1); - float *c = level[playerIndex]->dimension->getSunriseColor(level[playerIndex]->getTimeOfDay(alpha), alpha); - if (c != NULL) - { - glDisable(GL_TEXTURE_2D); - glShadeModel(GL_SMOOTH); + float* c = level[playerIndex]->dimension->getSunriseColor( + level[playerIndex]->getTimeOfDay(alpha), alpha); + if (c != NULL) { + glDisable(GL_TEXTURE_2D); + glShadeModel(GL_SMOOTH); - glPushMatrix(); - { - glRotatef(90, 1, 0, 0); - glRotatef(Mth::sin(level[playerIndex]->getSunAngle(alpha)) < 0 ? 180 : 0, 0, 0, 1); - glRotatef(90, 0, 0, 1); + glPushMatrix(); + { + glRotatef(90, 1, 0, 0); + glRotatef( + Mth::sin(level[playerIndex]->getSunAngle(alpha)) < 0 ? 180 : 0, + 0, 0, 1); + glRotatef(90, 0, 0, 1); - float r = c[0]; - float g = c[1]; - float b = c[2]; - if (mc->options->anaglyph3d) - { - float srr = (r * 30 + g * 59 + b * 11) / 100; - float sgg = (r * 30 + g * 70) / (100); - float sbb = (r * 30 + b * 70) / (100); + float r = c[0]; + float g = c[1]; + float b = c[2]; + if (mc->options->anaglyph3d) { + float srr = (r * 30 + g * 59 + b * 11) / 100; + float sgg = (r * 30 + g * 70) / (100); + float sbb = (r * 30 + b * 70) / (100); - r = srr; - g = sgg; - b = sbb; - } + r = srr; + g = sgg; + b = sbb; + } - t->begin(GL_TRIANGLE_FAN); - t->color(r, g, b, c[3]); + t->begin(GL_TRIANGLE_FAN); + t->color(r, g, b, c[3]); - t->vertex((float)(0), (float)( 100), (float)( 0)); - int steps = 16; - t->color(c[0], c[1], c[2], 0.0f); - for (int i = 0; i <= steps; i++) - { - float a = i * PI * 2 / steps; - float _sin = Mth::sin(a); - float _cos = Mth::cos(a); - t->vertex((float)(_sin * 120), (float)( _cos * 120), (float)( -_cos * 40 * c[3])); - } - t->end(); - } - glPopMatrix(); - glShadeModel(GL_FLAT); - } + t->vertex((float)(0), (float)(100), (float)(0)); + int steps = 16; + t->color(c[0], c[1], c[2], 0.0f); + for (int i = 0; i <= steps; i++) { + float a = i * PI * 2 / steps; + float _sin = Mth::sin(a); + float _cos = Mth::cos(a); + t->vertex((float)(_sin * 120), (float)(_cos * 120), + (float)(-_cos * 40 * c[3])); + } + t->end(); + } + glPopMatrix(); + glShadeModel(GL_FLAT); + } - glEnable(GL_TEXTURE_2D); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glPushMatrix(); - { - float rainBrightness = 1 - level[playerIndex]->getRainLevel(alpha); - float xp = 0; - float yp = 0; - float zp = 0; - glColor4f(1, 1, 1, rainBrightness); - glTranslatef(xp, yp, zp); - glRotatef(-90, 0, 1, 0); - glRotatef(level[playerIndex]->getTimeOfDay(alpha) * 360, 1, 0, 0); - float ss = 30; + glEnable(GL_TEXTURE_2D); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glPushMatrix(); + { + float rainBrightness = 1 - level[playerIndex]->getRainLevel(alpha); + float xp = 0; + float yp = 0; + float zp = 0; + glColor4f(1, 1, 1, rainBrightness); + glTranslatef(xp, yp, zp); + glRotatef(-90, 0, 1, 0); + glRotatef(level[playerIndex]->getTimeOfDay(alpha) * 360, 1, 0, 0); + float ss = 30; - MemSect(31); - textures->bindTexture(TN_TERRAIN_SUN); // 4J was L"/terrain/sun.png" - MemSect(0); - t->begin(); - t->vertexUV((float)(-ss), (float)( 100), (float)( -ss), (float)( 0), (float)( 0)); - t->vertexUV((float)(+ss), (float)( 100), (float)( -ss), (float)( 1), (float)( 0)); - t->vertexUV((float)(+ss), (float)( 100), (float)( +ss), (float)( 1), (float)( 1)); - t->vertexUV((float)(-ss), (float)( 100), (float)( +ss), (float)( 0), (float)( 1)); - t->end(); + MemSect(31); + textures->bindTexture(TN_TERRAIN_SUN); // 4J was L"/terrain/sun.png" + MemSect(0); + t->begin(); + t->vertexUV((float)(-ss), (float)(100), (float)(-ss), (float)(0), + (float)(0)); + t->vertexUV((float)(+ss), (float)(100), (float)(-ss), (float)(1), + (float)(0)); + t->vertexUV((float)(+ss), (float)(100), (float)(+ss), (float)(1), + (float)(1)); + t->vertexUV((float)(-ss), (float)(100), (float)(+ss), (float)(0), + (float)(1)); + t->end(); - ss = 20; - textures->bindTexture(TN_TERRAIN_MOON_PHASES); // 4J was L"/1_2_2/terrain/moon_phases.png" - int phase = level[playerIndex]->getMoonPhase(alpha); - int u = phase % 4; - int v = phase / 4 % 2; - float u0 = (u + 0) / 4.0f; - float v0 = (v + 0) / 2.0f; - float u1 = (u + 1) / 4.0f; - float v1 = (v + 1) / 2.0f; - t->begin(); - t->vertexUV(-ss, -100, +ss, u1, v1); - t->vertexUV(+ss, -100, +ss, u0, v1); - t->vertexUV(+ss, -100, -ss, u0, v0); - t->vertexUV(-ss, -100, -ss, u1, v0); - t->end(); + ss = 20; + textures->bindTexture( + TN_TERRAIN_MOON_PHASES); // 4J was + // L"/1_2_2/terrain/moon_phases.png" + int phase = level[playerIndex]->getMoonPhase(alpha); + int u = phase % 4; + int v = phase / 4 % 2; + float u0 = (u + 0) / 4.0f; + float v0 = (v + 0) / 2.0f; + float u1 = (u + 1) / 4.0f; + float v1 = (v + 1) / 2.0f; + t->begin(); + t->vertexUV(-ss, -100, +ss, u1, v1); + t->vertexUV(+ss, -100, +ss, u0, v1); + t->vertexUV(+ss, -100, -ss, u0, v0); + t->vertexUV(-ss, -100, -ss, u1, v0); + t->end(); - glDisable(GL_TEXTURE_2D); - float br = level[playerIndex]->getStarBrightness(alpha) * rainBrightness; - if (br > 0) - { - glColor4f(br, br, br, br); - glCallList(starList); - } - glColor4f(1, 1, 1, 1); - } - glDisable(GL_BLEND); - glEnable(GL_ALPHA_TEST); - glEnable(GL_FOG); + glDisable(GL_TEXTURE_2D); + float br = + level[playerIndex]->getStarBrightness(alpha) * rainBrightness; + if (br > 0) { + glColor4f(br, br, br, br); + glCallList(starList); + } + glColor4f(1, 1, 1, 1); + } + glDisable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glEnable(GL_FOG); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. - glDisable(GL_ALPHA_TEST); + // AP - alpha cut out is expensive on vita. + glDisable(GL_ALPHA_TEST); #endif - glPopMatrix(); - glDisable(GL_TEXTURE_2D); - glColor3f(0, 0, 0); + glPopMatrix(); + glDisable(GL_TEXTURE_2D); + glColor3f(0, 0, 0); - double yy = mc->player->getPos(alpha)->y - level[playerIndex]->getHorizonHeight(); // 4J - getHorizonHeight moved forward from 1.2.3 - if (yy < 0) - { - glPushMatrix(); - glTranslatef(0, -(float) (-12), 0); - glCallList(darkList); - glPopMatrix(); + double yy = + mc->player->getPos(alpha)->y - + level[playerIndex]->getHorizonHeight(); // 4J - getHorizonHeight moved + // forward from 1.2.3 + if (yy < 0) { + glPushMatrix(); + glTranslatef(0, -(float)(-12), 0); + glCallList(darkList); + glPopMatrix(); - // 4J - can't work out what this big black box is for. Taking it out until someone misses it... it causes a big black box to visible appear in 3rd person mode whilst under the ground. + // 4J - can't work out what this big black box is for. Taking it out + // until someone misses it... it causes a big black box to visible + // appear in 3rd person mode whilst under the ground. #if 0 float ss = 1; float yo = -(float) (yy + 65); @@ -1176,465 +1224,472 @@ void LevelRenderer::renderSky(float alpha) t->vertex(+ss, y0, -ss); t->end(); #endif - } + } - if (level[playerIndex]->dimension->hasGround()) - { - glColor3f(sr * 0.2f + 0.04f, sg * 0.2f + 0.04f, sb * 0.6f + 0.1f); - } - else - { - glColor3f(sr, sg, sb); - } - glPushMatrix(); - glTranslatef(0, -(float) (yy - 16), 0); - glCallList(darkList); - glPopMatrix(); - glEnable(GL_TEXTURE_2D); + if (level[playerIndex]->dimension->hasGround()) { + glColor3f(sr * 0.2f + 0.04f, sg * 0.2f + 0.04f, sb * 0.6f + 0.1f); + } else { + glColor3f(sr, sg, sb); + } + glPushMatrix(); + glTranslatef(0, -(float)(yy - 16), 0); + glCallList(darkList); + glPopMatrix(); + glEnable(GL_TEXTURE_2D); - glDepthMask(true); + glDepthMask(true); } -void LevelRenderer::renderHaloRing(float alpha) -{ +void LevelRenderer::renderHaloRing(float alpha) { #if !defined(__PS3__) && !defined(__ORBIS__) && !defined(__PSVITA__) - if (!mc->level->dimension->isNaturalDimension()) return; + if (!mc->level->dimension->isNaturalDimension()) return; - glDisable(GL_ALPHA_TEST); - glDisable(GL_TEXTURE_2D); - glDepthMask(false); - glEnable(GL_FOG); + glDisable(GL_ALPHA_TEST); + glDisable(GL_TEXTURE_2D); + glDepthMask(false); + glEnable(GL_FOG); - int playerIndex = mc->player->GetXboxPad(); + int playerIndex = mc->player->GetXboxPad(); - Vec3 *sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); - float sr = (float) sc->x; - float sg = (float) sc->y; - float sb = (float) sc->z; + Vec3* sc = level[playerIndex]->getSkyColor(mc->cameraTargetPlayer, alpha); + float sr = (float)sc->x; + float sg = (float)sc->y; + float sb = (float)sc->z; - // Rough lumninance calculation - float Y = (sr+sr+sb+sg+sg+sg)/6; - float br = 0.6f + (Y*0.4f); - //app.DebugPrintf("Luminance = %f, brightness = %f\n", Y, br); - glColor3f(br,br,br); + // Rough lumninance calculation + float Y = (sr + sr + sb + sg + sg + sg) / 6; + float br = 0.6f + (Y * 0.4f); + // app.DebugPrintf("Luminance = %f, brightness = %f\n", Y, br); + glColor3f(br, br, br); - // Fog at the base near the world - glFogi(GL_FOG_MODE, GL_LINEAR); - glFogf(GL_FOG_START, HALO_RING_RADIUS); - glFogf(GL_FOG_END, HALO_RING_RADIUS * 0.20f); + // Fog at the base near the world + glFogi(GL_FOG_MODE, GL_LINEAR); + glFogf(GL_FOG_START, HALO_RING_RADIUS); + glFogf(GL_FOG_END, HALO_RING_RADIUS * 0.20f); - Lighting::turnOn(); + Lighting::turnOn(); - glDepthMask(false); - textures->bindTexture(L"misc/haloRing.png"); // 4J was L"/1_2_2/misc/tunnel.png" - Tesselator *t = Tesselator::getInstance(); - bool prev = t->setMipmapEnable(true); + glDepthMask(false); + textures->bindTexture( + L"misc/haloRing.png"); // 4J was L"/1_2_2/misc/tunnel.png" + Tesselator* t = Tesselator::getInstance(); + bool prev = t->setMipmapEnable(true); - glPushMatrix(); - glRotatef(-90, 1, 0, 0); - glRotatef(90, 0, 1, 0); - glCallList(haloRingList); - glPopMatrix(); - t->setMipmapEnable(prev); + glPushMatrix(); + glRotatef(-90, 1, 0, 0); + glRotatef(90, 0, 1, 0); + glCallList(haloRingList); + glPopMatrix(); + t->setMipmapEnable(prev); - glDepthMask(true); - glEnable(GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); + glDepthMask(true); + glEnable(GL_TEXTURE_2D); + glEnable(GL_ALPHA_TEST); - glDisable(GL_FOG); + glDisable(GL_FOG); #endif } -void LevelRenderer::renderClouds(float alpha) -{ - int iTicks=ticks; - int playerIndex = mc->player->GetXboxPad(); +void LevelRenderer::renderClouds(float alpha) { + int iTicks = ticks; + int playerIndex = mc->player->GetXboxPad(); - // if the primary player has clouds off, so do all players on this machine - if(app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_Clouds)==0) - { - return; - } + // if the primary player has clouds off, so do all players on this machine + if (app.GetGameSettings(ProfileManager.GetPrimaryPad(), + eGameSetting_Clouds) == 0) { + return; + } - // debug setting added to keep it at day time - if (!mc->level->dimension->isNaturalDimension()) return; + // debug setting added to keep it at day time + if (!mc->level->dimension->isNaturalDimension()) return; - if (mc->options->fancyGraphics) - { - renderAdvancedClouds(alpha); - return; - } + if (mc->options->fancyGraphics) { + renderAdvancedClouds(alpha); + return; + } - if(app.DebugSettingsOn()) - { - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); - int s = 32; - int d = 256 / s; - Tesselator *t = Tesselator::getInstance(); + if (app.DebugSettingsOn()) { + if (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_FreezeTime)) { + iTicks = m_freezeticks; + } + } + glDisable(GL_CULL_FACE); + float yOffs = + (float)(mc->cameraTargetPlayer->yOld + + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * + alpha); + int s = 32; + int d = 256 / s; + Tesselator* t = Tesselator::getInstance(); - textures->bindTexture(TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + textures->bindTexture( + TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - Vec3 *cc = level[playerIndex]->getCloudColor(alpha); - float cr = (float) cc->x; - float cg = (float) cc->y; - float cb = (float) cc->z; + Vec3* cc = level[playerIndex]->getCloudColor(alpha); + float cr = (float)cc->x; + float cg = (float)cc->y; + float cb = (float)cc->z; - if (mc->options->anaglyph3d) - { - float crr = (cr * 30 + cg * 59 + cb * 11) / 100; - float cgg = (cr * 30 + cg * 70) / (100); - float cbb = (cr * 30 + cb * 70) / (100); + if (mc->options->anaglyph3d) { + float crr = (cr * 30 + cg * 59 + cb * 11) / 100; + float cgg = (cr * 30 + cg * 70) / (100); + float cbb = (cr * 30 + cb * 70) / (100); - cr = crr; - cg = cgg; - cb = cbb; - } + cr = crr; + cg = cgg; + cb = cbb; + } + float scale = 1 / 2048.0f; + double time = (ticks + alpha); + double xo = + mc->cameraTargetPlayer->xo + + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + + time * 0.03f; + double zo = + mc->cameraTargetPlayer->zo + + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha; + int xOffs = Mth::floor(xo / 2048); + int zOffs = Mth::floor(zo / 2048); + xo -= xOffs * 2048; + zo -= zOffs * 2048; - float scale = 1 / 2048.0f; + float yy = (float)(level[playerIndex]->dimension->getCloudHeight() - yOffs + + 0.33f); + float uo = (float)(xo * scale); + float vo = (float)(zo * scale); + t->begin(); - double time = (ticks + alpha); - double xo = mc->cameraTargetPlayer->xo + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + time * 0.03f; - double zo = mc->cameraTargetPlayer->zo + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha; - int xOffs = Mth::floor(xo / 2048); - int zOffs = Mth::floor(zo / 2048); - xo -= xOffs * 2048; - zo -= zOffs * 2048; + t->color(cr, cg, cb, 0.8f); + for (int xx = -s * d; xx < +s * d; xx += s) { + for (int zz = -s * d; zz < +s * d; zz += s) { + t->vertexUV((float)(xx + 0), (float)(yy), (float)(zz + s), + (float)((xx + 0) * scale + uo), + (float)((zz + s) * scale + vo)); + t->vertexUV((float)(xx + s), (float)(yy), (float)(zz + s), + (float)((xx + s) * scale + uo), + (float)((zz + s) * scale + vo)); + t->vertexUV((float)(xx + s), (float)(yy), (float)(zz + 0), + (float)((xx + s) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xx + 0), (float)(yy), (float)(zz + 0), + (float)((xx + 0) * scale + uo), + (float)((zz + 0) * scale + vo)); + } + } + t->end(); - float yy = (float) (level[playerIndex]->dimension->getCloudHeight() - yOffs + 0.33f); - float uo = (float) (xo * scale); - float vo = (float) (zo * scale); - t->begin(); + glColor4f(1, 1, 1, 1.0f); + glDisable(GL_BLEND); + glEnable(GL_CULL_FACE); - t->color(cr, cg, cb, 0.8f); - for (int xx = -s * d; xx < +s * d; xx += s) - { - for (int zz = -s * d; zz < +s * d; zz += s) - { - t->vertexUV((float)(xx + 0), (float)( yy), (float)( zz + s), (float)( (xx + 0) * scale + uo), (float)( (zz + s) * scale + vo)); - t->vertexUV((float)(xx + s), (float)( yy), (float)( zz + s), (float)( (xx + s) * scale + uo), (float)( (zz + s) * scale + vo)); - t->vertexUV((float)(xx + s), (float)( yy), (float)( zz + 0), (float)( (xx + s) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xx + 0), (float)( yy), (float)( zz + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); - } - } - t->end(); - - glColor4f(1, 1, 1, 1.0f); - glDisable(GL_BLEND); - glEnable(GL_CULL_FACE); - - if(app.DebugSettingsOn()) - { - - if(!(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.7f, 0.7f, 0.7f, 0.8f); - t->normal(0, -1, 0); - t->vertexUV(x0, y0, z0, u, v ); - t->vertexUV(x1, y0, z0, u, v ); - t->vertexUV(x1, y0, z1, u, v ); - t->vertexUV(x0, y0, z1, u, v ); - } - } - t->end(); - } - if( ( i == 1 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(1.0f, 1.0f, 1.0f, 0.8f); - t->normal(0, 1, 0); - t->vertexUV(x0, y1, z1, u, v ); - t->vertexUV(x1, y1, z1, u, v ); - t->vertexUV(x1, y1, z0, u, v ); - t->vertexUV(x0, y1, z0, u, v ); - } - } - t->end(); - } - if( ( i == 2 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.9f, 0.9f, 0.9f, 0.8f); - t->normal(-1, 0, 0); - t->vertexUV(x0, y0, z1, u, v ); - t->vertexUV(x0, y1, z1, u, v ); - t->vertexUV(x0, y1, z0, u, v ); - t->vertexUV(x0, y0, z0, u, v ); - } - } - t->end(); - } - if( ( i == 3 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.9f, 0.9f, 0.9f, 0.8f); - t->normal(1, 0, 0); - t->vertexUV(x1, y0, z0, u, v ); - t->vertexUV(x1, y1, z0, u, v ); - t->vertexUV(x1, y1, z1, u, v ); - t->vertexUV(x1, y0, z1, u, v ); - } - } - t->end(); - } - if( ( i == 4 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.8f, 0.8f, 0.8f, 0.8f); - t->normal(-1, 0, 0); - t->vertexUV(x0, y1, z0, u, v ); - t->vertexUV(x1, y1, z0, u, v ); - t->vertexUV(x1, y0, z0, u, v ); - t->vertexUV(x0, y0, z0, u, v ); - } - } - t->end(); - } - if( ( i == 5 ) || ( i == 6 ) ) - { - t->begin(); - for( int zt = 0; zt < D; zt++ ) - { - for( int xt = 0; xt < D; xt++ ) - { - float u = (((float) xt ) + 0.5f ) / 256.0f; - float v = (((float) zt ) + 0.5f ) / 256.0f; - float x0 = (float)xt; - float x1 = x0 + 1.0f; - float y0 = 0; - float y1 = h; - float z0 = (float)zt; - float z1 = z0 + 1.0f; - t->color(0.8f, 0.8f, 0.8f, 0.8f); - t->normal(1, 0, 0); - t->vertexUV(x0, y0, z1, u, v ); - t->vertexUV(x1, y0, z1, u, v ); - t->vertexUV(x1, y1, z1, u, v ); - t->vertexUV(x0, y1, z1, u, v ); - } - } - t->end(); - } - glEndList(); - } + if ((i == 0) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.7f, 0.7f, 0.7f, 0.8f); + t->normal(0, -1, 0); + t->vertexUV(x0, y0, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->vertexUV(x0, y0, z1, u, v); + } + } + t->end(); + } + if ((i == 1) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(1.0f, 1.0f, 1.0f, 0.8f); + t->normal(0, 1, 0); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x0, y1, z0, u, v); + } + } + t->end(); + } + if ((i == 2) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.9f, 0.9f, 0.9f, 0.8f); + t->normal(-1, 0, 0); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x0, y1, z1, u, v); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x0, y0, z0, u, v); + } + } + t->end(); + } + if ((i == 3) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.9f, 0.9f, 0.9f, 0.8f); + t->normal(1, 0, 0); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + } + } + t->end(); + } + if ((i == 4) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.8f, 0.8f, 0.8f, 0.8f); + t->normal(-1, 0, 0); + t->vertexUV(x0, y1, z0, u, v); + t->vertexUV(x1, y1, z0, u, v); + t->vertexUV(x1, y0, z0, u, v); + t->vertexUV(x0, y0, z0, u, v); + } + } + t->end(); + } + if ((i == 5) || (i == 6)) { + t->begin(); + for (int zt = 0; zt < D; zt++) { + for (int xt = 0; xt < D; xt++) { + float u = (((float)xt) + 0.5f) / 256.0f; + float v = (((float)zt) + 0.5f) / 256.0f; + float x0 = (float)xt; + float x1 = x0 + 1.0f; + float y0 = 0; + float y1 = h; + float z0 = (float)zt; + float z1 = z0 + 1.0f; + t->color(0.8f, 0.8f, 0.8f, 0.8f); + t->normal(1, 0, 0); + t->vertexUV(x0, y0, z1, u, v); + t->vertexUV(x1, y0, z1, u, v); + t->vertexUV(x1, y1, z1, u, v); + t->vertexUV(x0, y1, z1, u, v); + } + } + t->end(); + } + glEndList(); + } } -void LevelRenderer::renderAdvancedClouds(float alpha) -{ - // MGH - added, we were getting dark clouds sometimes on PS3, with this being setup incorrectly - glMultiTexCoord2f(GL_TEXTURE1, 0, 0); +void LevelRenderer::renderAdvancedClouds(float alpha) { + // MGH - added, we were getting dark clouds sometimes on PS3, with this + // being setup incorrectly + glMultiTexCoord2f(GL_TEXTURE1, 0, 0); + // 4J - most of our viewports are now rendered with no clip planes but using + // stencilling to limit the area drawn to. Clouds have a relatively large + // fill area compared to the number of vertices that they have, and so + // enabling clipping here to try and reduce fill rate cost. + RenderManager.StateSetEnableViewportClipPlanes(true); + float yOffs = + (float)(mc->cameraTargetPlayer->yOld + + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * + alpha); + Tesselator* t = Tesselator::getInstance(); + int playerIndex = mc->player->GetXboxPad(); - // 4J - most of our viewports are now rendered with no clip planes but using stencilling to limit the area drawn to. Clouds have a relatively large fill area compared to - // the number of vertices that they have, and so enabling clipping here to try and reduce fill rate cost. - RenderManager.StateSetEnableViewportClipPlanes(true); - float yOffs = (float) (mc->cameraTargetPlayer->yOld + (mc->cameraTargetPlayer->y - mc->cameraTargetPlayer->yOld) * alpha); - Tesselator *t = Tesselator::getInstance(); - int playerIndex = mc->player->GetXboxPad(); + int iTicks = ticks; - int iTicks=ticks; + if (app.DebugSettingsOn()) { + if (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) & + (1L << eDebugSetting_FreezeTime)) { + iTicks = m_freezeticks; + } + } - if(app.DebugSettingsOn()) - { - if(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<cameraTargetPlayer->xo + + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + + time * 0.03f) / + ss; + double zo = + (mc->cameraTargetPlayer->zo + + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha) / + ss + + 0.33f; + float yy = (float)(level[playerIndex]->dimension->getCloudHeight() - yOffs + + 0.33f); + int xOffs = Mth::floor(xo / 2048); + int zOffs = Mth::floor(zo / 2048); + xo -= xOffs * 2048; + zo -= zOffs * 2048; - double time = (ticks + alpha); - double xo = (mc->cameraTargetPlayer->xo + (mc->cameraTargetPlayer->x - mc->cameraTargetPlayer->xo) * alpha + time * 0.03f) / ss; - double zo = (mc->cameraTargetPlayer->zo + (mc->cameraTargetPlayer->z - mc->cameraTargetPlayer->zo) * alpha) / ss + 0.33f; - float yy = (float) (level[playerIndex]->dimension->getCloudHeight() - yOffs + 0.33f); - int xOffs = Mth::floor(xo / 2048); - int zOffs = Mth::floor(zo / 2048); - xo -= xOffs * 2048; - zo -= zOffs * 2048; + // 4J - we are now conditionally rendering the clouds in two ways + // (1) if we are (by our y height) in the clouds, then we render in a mode + // quite like the original, with no backface culling, and decisions on which + // sides of the clouds to render based on the positions of the 8x8 blocks of + // cloud texels (2) if we aren't in the clouds, then we do a simpler form of + // rendering with backface culling on This is because the complex sort of + // rendering is really there so that the clouds seem more solid when you + // might be in them, but it has more risk of artifacts so we don't want to + // do it when not necessary - // 4J - we are now conditionally rendering the clouds in two ways - // (1) if we are (by our y height) in the clouds, then we render in a mode quite like the original, with no backface culling, and - // decisions on which sides of the clouds to render based on the positions of the 8x8 blocks of cloud texels - // (2) if we aren't in the clouds, then we do a simpler form of rendering with backface culling on - // This is because the complex sort of rendering is really there so that the clouds seem more solid when you might be in them, but it has more risk of artifacts so - // we don't want to do it when not necessary + // 4jcraft: not needed for the tesselator-based implementation + // bool noBFCMode = ( (yy > -h - 1) && (yy <= h + 1) ); + // if( noBFCMode ) + // { + // glDisable(GL_CULL_FACE); + // } + // else + // { + // glEnable(GL_CULL_FACE); + // } - // 4jcraft: not needed for the tesselator-based implementation - // bool noBFCMode = ( (yy > -h - 1) && (yy <= h + 1) ); - // if( noBFCMode ) - // { - // glDisable(GL_CULL_FACE); - // } - // else - // { - // glEnable(GL_CULL_FACE); - // } + MemSect(31); + textures->bindTexture( + TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" + MemSect(0); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - MemSect(31); - textures->bindTexture(TN_ENVIRONMENT_CLOUDS); // 4J was L"/environment/clouds.png" - MemSect(0); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + Vec3* cc = level[playerIndex]->getCloudColor(alpha); + float cr = (float)cc->x; + float cg = (float)cc->y; + float cb = (float)cc->z; - Vec3 *cc = level[playerIndex]->getCloudColor(alpha); - float cr = (float) cc->x; - float cg = (float) cc->y; - float cb = (float) cc->z; + if (mc->options->anaglyph3d) { + float crr = (cr * 30 + cg * 59 + cb * 11) / 100; + float cgg = (cr * 30 + cg * 70) / (100); + float cbb = (cr * 30 + cb * 70) / (100); - if (mc->options->anaglyph3d) - { - float crr = (cr * 30 + cg * 59 + cb * 11) / 100; - float cgg = (cr * 30 + cg * 70) / (100); - float cbb = (cr * 30 + cb * 70) / (100); + cr = crr; + cg = cgg; + cb = cbb; + } - cr = crr; - cg = cgg; - cb = cbb; - } + float uo = (float)(xo * 0); + float vo = (float)(zo * 0); - float uo = (float) (xo * 0); - float vo = (float) (zo * 0); + float scale = 1 / 256.0f; - float scale = 1 / 256.0f; + uo = (float)(Mth::floor(xo)) * scale; + vo = (float)(Mth::floor(zo)) * scale; + // 4J - keep our UVs +ve - there's a small bug in the xbox GPU that + // incorrectly rounds small -ve UVs (between -1/(64*size) and 0) up to 0, + // which leaves gaps in our clouds... + while (uo < 1.0f) uo += 1.0f; + while (vo < 1.0f) vo += 1.0f; - uo = (float) (Mth::floor(xo)) * scale; - vo = (float) (Mth::floor(zo)) * scale; - // 4J - keep our UVs +ve - there's a small bug in the xbox GPU that incorrectly rounds small -ve UVs (between -1/(64*size) and 0) up to 0, which leaves gaps in our clouds... - while( uo < 1.0f ) uo += 1.0f; - while( vo < 1.0f ) vo += 1.0f; + float xoffs = (float)(xo - Mth::floor(xo)); + float zoffs = (float)(zo - Mth::floor(zo)); - float xoffs = (float) (xo - Mth::floor(xo)); - float zoffs = (float) (zo - Mth::floor(zo)); + int D = 8; - int D = 8; + int radius = 3; + if (activePlayers() > 2) + radius = 2; // 4J - reduce the cloud render distance a bit for 3 & 4 + // player split screen + float e = 1 / 1024.0f; + glScalef(ss, 1, ss); + FrustumData* pFrustumData = Frustum::getFrustum(); + for (int pass = 0; pass < 2; pass++) { + if (pass == 0) { + // 4J - changed to use blend rather than color mask to avoid writing + // to frame buffer, to work with our command buffers + glBlendFunc(GL_ZERO, GL_ONE); + // glColorMask(false, false, false, false); + } else { + // 4J - changed to use blend rather than color mask to avoid writing + // to frame buffer, to work with our command buffers + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + // glColorMask(true, true, true, true); + } + for (int xPos = -radius + 1; xPos <= radius; xPos++) { + for (int zPos = -radius + 1; zPos <= radius; zPos++) { + // 4J - reimplemented the clouds with full cube-per-texel + // geometry to get rid of seams. This is a huge amount more + // quads to render, so now using command buffers to render each + // section to cut CPU hit. - int radius = 3; - if( activePlayers() > 2 ) radius = 2; // 4J - reduce the cloud render distance a bit for 3 & 4 player split screen - float e = 1 / 1024.0f; - glScalef(ss, 1, ss); - FrustumData* pFrustumData = Frustum::getFrustum(); - for (int pass = 0; pass < 2; pass++) - { - if (pass == 0) - { - // 4J - changed to use blend rather than color mask to avoid writing to frame buffer, to work with our command buffers - glBlendFunc(GL_ZERO, GL_ONE); - // glColorMask(false, false, false, false); - } - else - { - // 4J - changed to use blend rather than color mask to avoid writing to frame buffer, to work with our command buffers - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - // glColorMask(true, true, true, true); - } - for (int xPos = -radius + 1; xPos <= radius; xPos++) - { - for (int zPos = -radius + 1; zPos <= radius; zPos++) - { - // 4J - reimplemented the clouds with full cube-per-texel geometry to get rid of seams. This is a huge amount more quads to render, so - // now using command buffers to render each section to cut CPU hit. - - // 4jcraft: switch back to the tesselator-based implementation of cloud renders + // 4jcraft: switch back to the tesselator-based implementation + // of cloud renders #if 0 float xx = (float)(xPos * D); float zz = (float)(zPos * D); @@ -1710,909 +1765,1096 @@ void LevelRenderer::renderAdvancedClouds(float alpha) glLoadIdentity(); glMatrixMode(GL_MODELVIEW); #else - glDisable(GL_CULL_FACE); - t->begin(); - float xx = (float)(xPos * D); - float zz = (float)(zPos * D); - float xp = xx - xoffs; - float zp = zz - zoffs; + glDisable(GL_CULL_FACE); + t->begin(); + float xx = (float)(xPos * D); + float zz = (float)(zPos * D); + float xp = xx - xoffs; + float zp = zz - zoffs; + if (yy > -h - 1) { + t->color(cr * 0.7f, cg * 0.7f, cb * 0.7f, 0.8f); + t->normal(0, -1, 0); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + D), (float)((xx + 0) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + D), (float)((xx + D) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + 0), (float)((xx + D) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + 0), (float)((xx + 0) * scale + uo), + (float)((zz + 0) * scale + vo)); + } - if (yy > -h - 1) - { - t->color(cr * 0.7f, cg * 0.7f, cb * 0.7f, 0.8f); - t->normal(0, -1, 0); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + D), (float)( (xx + 0) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + D), (float)( (xx + D) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + 0), (float)( (xx + D) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); - } + if (yy <= h + 1) { + t->color(cr, cg, cb, 0.8f); + t->normal(0, 1, 0); + t->vertexUV((float)(xp + 0), (float)(yy + h - e), + (float)(zp + D), (float)((xx + 0) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h - e), + (float)(zp + D), (float)((xx + D) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h - e), + (float)(zp + 0), (float)((xx + D) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + h - e), + (float)(zp + 0), (float)((xx + 0) * scale + uo), + (float)((zz + 0) * scale + vo)); + } - if (yy <= h + 1) - { - t->color(cr, cg, cb, 0.8f); - t->normal(0, 1, 0); - t->vertexUV((float)(xp + 0), (float)( yy + h - e), (float)( zp + D), (float)( (xx + 0) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h - e), (float)( zp + D), (float)( (xx + D) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h - e), (float)( zp + 0), (float)( (xx + D) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + h - e), (float)( zp + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + 0) * scale + vo)); - } + t->color(cr * 0.9f, cg * 0.9f, cb * 0.9f, 0.8f); + if (xPos > -1) { + t->normal(-1, 0, 0); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + i + 0), (float)(yy + 0), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 0), (float)(yy + h), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 0), (float)(yy + h), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + i + 0), (float)(yy + 0), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + } + } - t->color(cr * 0.9f, cg * 0.9f, cb * 0.9f, 0.8f); - if (xPos > -1) - { - t->normal(-1, 0, 0); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + i + 0), (float)( yy + 0), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 0), (float)( yy + h), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 0), (float)( yy + h), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + i + 0), (float)( yy + 0), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - } - } + if (xPos <= 1) { + t->normal(+1, 0, 0); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + 0), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + h), + (float)(zp + D), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + D) * scale + vo)); + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + h), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + t->vertexUV((float)(xp + i + 1 - e), (float)(yy + 0), + (float)(zp + 0), + (float)((xx + i + 0.5f) * scale + uo), + (float)((zz + 0) * scale + vo)); + } + } - if (xPos <= 1) - { - t->normal(+1, 0, 0); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + 0), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + h), (float)( zp + D), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + D) * scale + vo)); - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + h), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - t->vertexUV((float)(xp + i + 1 - e), (float)( yy + 0), (float)( zp + 0), (float)( (xx + i + 0.5f) * scale + uo), (float)( (zz + 0) * scale + vo)); - } - } + t->color(cr * 0.8f, cg * 0.8f, cb * 0.8f, 0.8f); + if (zPos > -1) { + t->normal(0, 0, -1); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + 0), (float)(yy + h), + (float)(zp + i + 0), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h), + (float)(zp + i + 0), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + i + 0), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + i + 0), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + } + } - t->color(cr * 0.8f, cg * 0.8f, cb * 0.8f, 0.8f); - if (zPos > -1) - { - t->normal(0, 0, -1); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + 0), (float)( yy + h), (float)( zp + i + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h), (float)( zp + i + 0), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + i + 0), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + i + 0), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - } - } - - if (zPos <= 1) - { - t->normal(0, 0, 1); - for (int i = 0; i < D; i++) - { - t->vertexUV((float)(xp + 0), (float)( yy + h), (float)( zp + i + 1 - e), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + h), (float)( zp + i + 1 - e), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + D), (float)( yy + 0), (float)( zp + i + 1 - e), (float)( (xx + D) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - t->vertexUV((float)(xp + 0), (float)( yy + 0), (float)( zp + i + 1 - e), (float)( (xx + 0) * scale + uo), (float)( (zz + i + 0.5f) * scale + vo)); - } - } - t->end(); + if (zPos <= 1) { + t->normal(0, 0, 1); + for (int i = 0; i < D; i++) { + t->vertexUV((float)(xp + 0), (float)(yy + h), + (float)(zp + i + 1 - e), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + h), + (float)(zp + i + 1 - e), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + D), (float)(yy + 0), + (float)(zp + i + 1 - e), + (float)((xx + D) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + t->vertexUV((float)(xp + 0), (float)(yy + 0), + (float)(zp + i + 1 - e), + (float)((xx + 0) * scale + uo), + (float)((zz + i + 0.5f) * scale + vo)); + } + } + t->end(); #endif - } - } - } + } + } + } - glColor4f(1, 1, 1, 1.0f); - glDisable(GL_BLEND); - glEnable(GL_CULL_FACE); + glColor4f(1, 1, 1, 1.0f); + glDisable(GL_BLEND); + glEnable(GL_CULL_FACE); - - if(app.DebugSettingsOn()) - { - if(!(app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L< > nearestClipChunks; + std::list > nearestClipChunks; #endif - ClipChunk *nearChunk = NULL; // Nearest chunk that is dirty - int veryNearCount = 0; - int minDistSq = 0x7fffffff; // Distances to this chunk + ClipChunk* nearChunk = NULL; // Nearest chunk that is dirty + int veryNearCount = 0; + int minDistSq = 0x7fffffff; // Distances to this chunk + // Set a flag if we should only rebuild existing chunks, not create anything + // new + unsigned int memAlloc = RenderManager.CBuffSize(-1); + /* + static int throttle = 0; + if( ( throttle % 100 ) == 0 ) + { + app.DebugPrintf("CBuffSize: %d\n",memAlloc/(1024*1024)); + } + throttle++; + */ + PIXAddNamedCounter(((float)memAlloc) / (1024.0f * 1024.0f), + "Command buffer allocations"); + bool onlyRebuild = (memAlloc >= MAX_COMMANDBUFFER_ALLOCATIONS); + EnterCriticalSection(&m_csDirtyChunks); - // Set a flag if we should only rebuild existing chunks, not create anything new - unsigned int memAlloc = RenderManager.CBuffSize(-1); - /* - static int throttle = 0; - if( ( throttle % 100 ) == 0 ) - { - app.DebugPrintf("CBuffSize: %d\n",memAlloc/(1024*1024)); - } - throttle++; - */ - PIXAddNamedCounter(((float)memAlloc)/(1024.0f*1024.0f),"Command buffer allocations"); - bool onlyRebuild = ( memAlloc >= MAX_COMMANDBUFFER_ALLOCATIONS ); - EnterCriticalSection(&m_csDirtyChunks); + // Move any dirty chunks stored in the lock free stack into global flags + int index = 0; - // Move any dirty chunks stored in the lock free stack into global flags - int index = 0; - - do - { - // See comment on dirtyChunksLockFreeStack.Push() regarding details of this casting/subtracting -2. - index = (size_t)dirtyChunksLockFreeStack.Pop(); + do { + // See comment on dirtyChunksLockFreeStack.Push() regarding details of + // this casting/subtracting -2. + index = (size_t)dirtyChunksLockFreeStack.Pop(); #ifdef _CRITICAL_CHUNKS - int oldIndex = index; - index &= 0x0fffffff; // remove the top bit that marked the chunk as non-critical + int oldIndex = index; + index &= 0x0fffffff; // remove the top bit that marked the chunk as + // non-critical #endif - if( index == 1 ) dirtyChunkPresent = true; // 1 is a special value passed to let this thread know that a chunk which isn't on this stack has been set to dirty - else if( index > 1 ) - { - int i2 = index - 2; - if( i2 >= DIMENSION_OFFSETS[2] ) - { - i2 -= DIMENSION_OFFSETS[2]; - int y2 = i2 & (CHUNK_Y_COUNT-1); - i2 /= CHUNK_Y_COUNT; - int z2 = i2 / MAX_LEVEL_RENDER_SIZE[2]; - int x2 = i2 - z2 * MAX_LEVEL_RENDER_SIZE[2]; - x2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; - z2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; - } - setGlobalChunkFlag(index - 2, CHUNK_FLAG_DIRTY); + if (index == 1) + dirtyChunkPresent = + true; // 1 is a special value passed to let this thread know + // that a chunk which isn't on this stack has been set to + // dirty + else if (index > 1) { + int i2 = index - 2; + if (i2 >= DIMENSION_OFFSETS[2]) { + i2 -= DIMENSION_OFFSETS[2]; + int y2 = i2 & (CHUNK_Y_COUNT - 1); + i2 /= CHUNK_Y_COUNT; + int z2 = i2 / MAX_LEVEL_RENDER_SIZE[2]; + int x2 = i2 - z2 * MAX_LEVEL_RENDER_SIZE[2]; + x2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; + z2 -= MAX_LEVEL_RENDER_SIZE[2] / 2; + } + setGlobalChunkFlag(index - 2, CHUNK_FLAG_DIRTY); #ifdef _CRITICAL_CHUNKS - if( !(oldIndex & 0x10000000) ) // was this chunk not marked as non-critical. Ugh double negatives - { - setGlobalChunkFlag(index - 2, CHUNK_FLAG_CRITICAL); - } + if (!(oldIndex & 0x10000000)) // was this chunk not marked as + // non-critical. Ugh double negatives + { + setGlobalChunkFlag(index - 2, CHUNK_FLAG_CRITICAL); + } #endif - dirtyChunkPresent = true; - } - } while( index ); + dirtyChunkPresent = true; + } + } while (index); - // Only bother searching round all the chunks if we have some dirty chunk(s) - if( dirtyChunkPresent ) - { - lastDirtyChunkFound = System::currentTimeMillis(); - PIXBeginNamedEvent(0,"Finding nearest chunk\n"); + // Only bother searching round all the chunks if we have some dirty chunk(s) + if (dirtyChunkPresent) { + lastDirtyChunkFound = System::currentTimeMillis(); + PIXBeginNamedEvent(0, "Finding nearest chunk\n"); #if defined __PS3__ && !defined DISABLE_SPU_CODE - // find the nearest chunk with a spu task, copy all the data over here for uploading to SPU - g_findNearestChunkDataIn.numGlobalChunks = getGlobalChunkCount(); - g_findNearestChunkDataIn.pGlobalChunkFlags = globalChunkFlags; - g_findNearestChunkDataIn.onlyRebuild = onlyRebuild; - g_findNearestChunkDataIn.lowerOffset = (int)&((LevelChunk*)0)->lowerBlocks; // dodgy bit of class structure poking, as we don't want to try and get the whole of LevelChunk copmpiling on SPU - g_findNearestChunkDataIn.upperOffset = (int)&((LevelChunk*)0)->upperBlocks; - g_findNearestChunkDataIn.xChunks = xChunks; - g_findNearestChunkDataIn.yChunks = yChunks; - g_findNearestChunkDataIn.zChunks = zChunks; + // find the nearest chunk with a spu task, copy all the data over here + // for uploading to SPU + g_findNearestChunkDataIn.numGlobalChunks = getGlobalChunkCount(); + g_findNearestChunkDataIn.pGlobalChunkFlags = globalChunkFlags; + g_findNearestChunkDataIn.onlyRebuild = onlyRebuild; + g_findNearestChunkDataIn.lowerOffset = + (int)&((LevelChunk*)0) + ->lowerBlocks; // dodgy bit of class structure poking, as we + // don't want to try and get the whole of + // LevelChunk copmpiling on SPU + g_findNearestChunkDataIn.upperOffset = + (int)&((LevelChunk*)0)->upperBlocks; + g_findNearestChunkDataIn.xChunks = xChunks; + g_findNearestChunkDataIn.yChunks = yChunks; + g_findNearestChunkDataIn.zChunks = zChunks; - for(int i=0;i<4;i++) - { - g_findNearestChunkDataIn.chunks[i] = (LevelRenderer_FindNearestChunk_DataIn::ClipChunk*)chunks[i].data; - g_findNearestChunkDataIn.chunkLengths[i] = chunks[i].length; - g_findNearestChunkDataIn.level[i] = level[i]; - g_findNearestChunkDataIn.playerData[i].bValid = mc->localplayers[i] != NULL; - if(mc->localplayers[i] != NULL) - { - g_findNearestChunkDataIn.playerData[i].x = mc->localplayers[i]->x; - g_findNearestChunkDataIn.playerData[i].y = mc->localplayers[i]->y; - g_findNearestChunkDataIn.playerData[i].z = mc->localplayers[i]->z; + for (int i = 0; i < 4; i++) { + g_findNearestChunkDataIn.chunks[i] = + (LevelRenderer_FindNearestChunk_DataIn::ClipChunk*)chunks[i] + .data; + g_findNearestChunkDataIn.chunkLengths[i] = chunks[i].length; + g_findNearestChunkDataIn.level[i] = level[i]; + g_findNearestChunkDataIn.playerData[i].bValid = + mc->localplayers[i] != NULL; + if (mc->localplayers[i] != NULL) { + g_findNearestChunkDataIn.playerData[i].x = + mc->localplayers[i]->x; + g_findNearestChunkDataIn.playerData[i].y = + mc->localplayers[i]->y; + g_findNearestChunkDataIn.playerData[i].z = + mc->localplayers[i]->z; + } + if (level[i] != NULL) { + g_findNearestChunkDataIn.multiplayerChunkCache[i].XZOFFSET = + ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZOFFSET; + g_findNearestChunkDataIn.multiplayerChunkCache[i].XZSIZE = + ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZSIZE; + g_findNearestChunkDataIn.multiplayerChunkCache[i].cache = + (void**)((MultiPlayerChunkCache*)(level[i]->chunkSource)) + ->cache; + } + } - } - if(level[i] != NULL) - { - g_findNearestChunkDataIn.multiplayerChunkCache[i].XZOFFSET = ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZOFFSET; - g_findNearestChunkDataIn.multiplayerChunkCache[i].XZSIZE = ((MultiPlayerChunkCache*)(level[i]->chunkSource))->XZSIZE; - g_findNearestChunkDataIn.multiplayerChunkCache[i].cache = (void**)((MultiPlayerChunkCache*)(level[i]->chunkSource))->cache; - } - - } - - // assert(sizeof(LevelRenderer_FindNearestChunk_DataIn::Chunk) == sizeof(Chunk)); - C4JSpursJob_LevelRenderer_FindNearestChunk findJob(&g_findNearestChunkDataIn); - m_jobPort_FindNearestChunk->submitJob(&findJob); - m_jobPort_FindNearestChunk->waitForCompletion(); - nearChunk = (ClipChunk*)g_findNearestChunkDataIn.nearChunk; - veryNearCount = g_findNearestChunkDataIn.veryNearCount; -#else // __PS3__ + // assert(sizeof(LevelRenderer_FindNearestChunk_DataIn::Chunk) + // == sizeof(Chunk)); + C4JSpursJob_LevelRenderer_FindNearestChunk findJob( + &g_findNearestChunkDataIn); + m_jobPort_FindNearestChunk->submitJob(&findJob); + m_jobPort_FindNearestChunk->waitForCompletion(); + nearChunk = (ClipChunk*)g_findNearestChunkDataIn.nearChunk; + veryNearCount = g_findNearestChunkDataIn.veryNearCount; +#else // __PS3__ #ifdef _LARGE_WORLDS - int maxNearestChunks = MAX_CONCURRENT_CHUNK_REBUILDS; - // 4J Stu - On XboxOne we should cut this down if in a constrained state so the saving threads get more time + int maxNearestChunks = MAX_CONCURRENT_CHUNK_REBUILDS; + // 4J Stu - On XboxOne we should cut this down if in a constrained state + // so the saving threads get more time #endif - // Find nearest chunk that is dirty - for( int p = 0; p < XUSER_MAX_COUNT; p++ ) - { - // It's possible that the localplayers member can be set to NULL on the main thread when a player chooses to exit the game - // So take a reference to the player object now. As it is a std::shared_ptr it should live as long as we need it - std::shared_ptr player = mc->localplayers[p]; - if( player == NULL ) continue; - if( chunks[p].data == NULL ) continue; - if( level[p] == NULL ) continue; - if( chunks[p].length != xChunks * zChunks * CHUNK_Y_COUNT ) continue; - int px = (int)player->x; - int py = (int)player->y; - int pz = (int)player->z; + // Find nearest chunk that is dirty + for (int p = 0; p < XUSER_MAX_COUNT; p++) { + // It's possible that the localplayers member can be set to NULL on + // the main thread when a player chooses to exit the game So take a + // reference to the player object now. As it is a std::shared_ptr it + // should live as long as we need it + std::shared_ptr player = mc->localplayers[p]; + if (player == NULL) continue; + if (chunks[p].data == NULL) continue; + if (level[p] == NULL) continue; + if (chunks[p].length != xChunks * zChunks * CHUNK_Y_COUNT) continue; + int px = (int)player->x; + int py = (int)player->y; + int pz = (int)player->z; -// app.DebugPrintf("!! %d %d %d, %d %d %d {%d,%d} ",px,py,pz,stackChunkDirty,nonStackChunkDirty,onlyRebuild, xChunks, zChunks); + // app.DebugPrintf("!! %d %d %d, %d %d %d {%d,%d} + //",px,py,pz,stackChunkDirty,nonStackChunkDirty,onlyRebuild, + //xChunks, zChunks); - int considered = 0; - int wouldBeNearButEmpty = 0; - for( int x = 0; x < xChunks; x++ ) - { - for( int z = 0; z < zChunks; z++ ) - { - for( int y = 0; y < CHUNK_Y_COUNT; y++ ) - { - ClipChunk *pClipChunk = &chunks[p][(z * yChunks + y) * xChunks + x]; - // Get distance to this chunk - deliberately not calling the chunk's method of doing this to avoid overheads (passing entitie, type conversion etc.) that this involves - int xd = pClipChunk->xm - px; - int yd = pClipChunk->ym - py; - int zd = pClipChunk->zm - pz; - int distSq = xd * xd + yd * yd + zd * zd; - int distSqWeighted = xd * xd + yd * yd * 4 + zd * zd; // Weighting against y to prioritise things in same x/z plane as player first + int considered = 0; + int wouldBeNearButEmpty = 0; + for (int x = 0; x < xChunks; x++) { + for (int z = 0; z < zChunks; z++) { + for (int y = 0; y < CHUNK_Y_COUNT; y++) { + ClipChunk* pClipChunk = + &chunks[p][(z * yChunks + y) * xChunks + x]; + // Get distance to this chunk - deliberately not calling + // the chunk's method of doing this to avoid overheads + // (passing entitie, type conversion etc.) that this + // involves + int xd = pClipChunk->xm - px; + int yd = pClipChunk->ym - py; + int zd = pClipChunk->zm - pz; + int distSq = xd * xd + yd * yd + zd * zd; + int distSqWeighted = + xd * xd + yd * yd * 4 + + zd * + zd; // Weighting against y to prioritise things + // in same x/z plane as player first - if( globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_DIRTY ) - { - if( (!onlyRebuild) || - globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_COMPILED || - ( distSq < 20 * 20 ) ) // Always rebuild really near things or else building (say) at tower up into empty blocks when we are low on memory will not create render data - { - considered++; - // Is this chunk nearer than our nearest? + if (globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_DIRTY) { + if ((!onlyRebuild) || + globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_COMPILED || + (distSq < + 20 * 20)) // Always rebuild really near things + // or else building (say) at tower + // up into empty blocks when we are + // low on memory will not create + // render data + { + considered++; + // Is this chunk nearer than our nearest? #ifdef _LARGE_WORLDS - bool isNearer = nearestClipChunks.empty(); - AUTO_VAR(itNearest, nearestClipChunks.begin()); - for(; itNearest != nearestClipChunks.end(); ++itNearest) - { - isNearer = distSqWeighted < itNearest->second; - if(isNearer) break; - } - isNearer = isNearer || (nearestClipChunks.size() < maxNearestChunks); + bool isNearer = nearestClipChunks.empty(); + AUTO_VAR(itNearest, nearestClipChunks.begin()); + for (; itNearest != nearestClipChunks.end(); + ++itNearest) { + isNearer = + distSqWeighted < itNearest->second; + if (isNearer) break; + } + isNearer = + isNearer || (nearestClipChunks.size() < + maxNearestChunks); #else - bool isNearer = distSqWeighted < minDistSq; + bool isNearer = distSqWeighted < minDistSq; #endif #ifdef _CRITICAL_CHUNKS - // AP - this will make sure that if a deferred grouping has started, only critical chunks go into that - // grouping, even if a non-critical chunk is closer. - if( (!veryNearCount && isNearer) || - (distSq < 20 * 20 && (globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_CRITICAL)) ) + // AP - this will make sure that if a deferred + // grouping has started, only critical chunks go + // into that grouping, even if a non-critical + // chunk is closer. + if ((!veryNearCount && isNearer) || + (distSq < 20 * 20 && + (globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_CRITICAL))) #else - if( isNearer ) + if (isNearer) #endif - { - // At this point we've got a chunk that we would like to consider for rendering, at least based on its proximity to the player(s). - // Its *quite* quick to generate empty render data for render chunks, but if we let the rebuilding do that then the after rebuilding we will have - // to start searching for the next nearest chunk from scratch again. Instead, its better to detect empty chunks at this stage, flag them up as not dirty - // (and empty), and carry on. The levelchunk's isRenderChunkEmpty method can be quite optimal as it can make use of the chunk's data compression to detect - // emptiness without actually testing as many data items as uncompressed data would. - Chunk *chunk = pClipChunk->chunk; - LevelChunk *lc = level[p]->getChunkAt(chunk->x,chunk->z); - if( !lc->isRenderChunkEmpty(y * 16) ) - { - nearChunk = pClipChunk; - minDistSq = distSqWeighted; + { + // At this point we've got a chunk that we + // would like to consider for rendering, at + // least based on its proximity to the + // player(s). Its *quite* quick to generate + // empty render data for render chunks, but + // if we let the rebuilding do that then the + // after rebuilding we will have to start + // searching for the next nearest chunk from + // scratch again. Instead, its better to + // detect empty chunks at this stage, flag + // them up as not dirty (and empty), and + // carry on. The levelchunk's + // isRenderChunkEmpty method can be quite + // optimal as it can make use of the chunk's + // data compression to detect emptiness + // without actually testing as many data + // items as uncompressed data would. + Chunk* chunk = pClipChunk->chunk; + LevelChunk* lc = level[p]->getChunkAt( + chunk->x, chunk->z); + if (!lc->isRenderChunkEmpty(y * 16)) { + nearChunk = pClipChunk; + minDistSq = distSqWeighted; #ifdef _LARGE_WORLDS - nearestClipChunks.insert(itNearest, std::pair(nearChunk, minDistSq) ); - if(nearestClipChunks.size() > maxNearestChunks) - { - nearestClipChunks.pop_back(); - } + nearestClipChunks.insert( + itNearest, + std::pair( + nearChunk, minDistSq)); + if (nearestClipChunks.size() > + maxNearestChunks) { + nearestClipChunks.pop_back(); + } #endif - } - else - { - chunk->clearDirty(); - globalChunkFlags[ pClipChunk->globalIdx ] |= CHUNK_FLAG_EMPTYBOTH; - wouldBeNearButEmpty++; - } - } + } else { + chunk->clearDirty(); + globalChunkFlags[pClipChunk + ->globalIdx] |= + CHUNK_FLAG_EMPTYBOTH; + wouldBeNearButEmpty++; + } + } #ifdef _CRITICAL_CHUNKS - // AP - is the chunk near and also critical - if( distSq < 20 * 20 && ((globalChunkFlags[ pClipChunk->globalIdx ] & CHUNK_FLAG_CRITICAL)) ) + // AP - is the chunk near and also critical + if (distSq < 20 * 20 && + ((globalChunkFlags[pClipChunk->globalIdx] & + CHUNK_FLAG_CRITICAL))) #else - if( distSq < 20 * 20 ) + if (distSq < 20 * 20) #endif - { - veryNearCount++; - } - } - } - } - } - } -// app.DebugPrintf("[%d,%d,%d]\n",nearestClipChunks.empty(),considered,wouldBeNearButEmpty); - } -#endif // __PS3__ - PIXEndNamedEvent(); - } + { + veryNearCount++; + } + } + } + } + } + } + // app.DebugPrintf("[%d,%d,%d]\n",nearestClipChunks.empty(),considered,wouldBeNearButEmpty); + } +#endif // __PS3__ + PIXEndNamedEvent(); + } - - - Chunk *chunk = NULL; + Chunk* chunk = NULL; #ifdef _LARGE_WORLDS - if(!nearestClipChunks.empty()) - { - int index = 0; - for(AUTO_VAR(it, nearestClipChunks.begin()); it != nearestClipChunks.end(); ++it) - { - chunk = it->first->chunk; - // If this chunk is very near, then move the renderer into a deferred mode. This won't commit any command buffers - // for rendering until we call CBuffDeferredModeEnd(), allowing us to group any near changes into an atomic unit. This - // is essential so we don't temporarily create any holes in the environment whilst updating one chunk and not the neighbours. - // The "ver near" aspect of this is just a cosmetic nicety - exactly the same thing would happen further away, but we just don't - // care about it so much from terms of visual impact. - if( veryNearCount > 0 ) - { - RenderManager.CBuffDeferredModeStart(); - } - // Build this chunk & return false to continue processing - chunk->clearDirty(); - // Take a copy of the details that are required for chunk rebuilding, and rebuild That instead of the original chunk data. This is done within - // the m_csDirtyChunks critical section, which means that any chunks can't be repositioned whilst we are doing this copy. The copy will then - // be guaranteed to be consistent whilst rebuilding takes place outside of that critical section. - permaChunk[index].makeCopyForRebuild(chunk); - ++index; - } - LeaveCriticalSection(&m_csDirtyChunks); + if (!nearestClipChunks.empty()) { + int index = 0; + for (AUTO_VAR(it, nearestClipChunks.begin()); + it != nearestClipChunks.end(); ++it) { + chunk = it->first->chunk; + // If this chunk is very near, then move the renderer into a + // deferred mode. This won't commit any command buffers for + // rendering until we call CBuffDeferredModeEnd(), allowing us to + // group any near changes into an atomic unit. This is essential so + // we don't temporarily create any holes in the environment whilst + // updating one chunk and not the neighbours. The "ver near" aspect + // of this is just a cosmetic nicety - exactly the same thing would + // happen further away, but we just don't care about it so much from + // terms of visual impact. + if (veryNearCount > 0) { + RenderManager.CBuffDeferredModeStart(); + } + // Build this chunk & return false to continue processing + chunk->clearDirty(); + // Take a copy of the details that are required for chunk + // rebuilding, and rebuild That instead of the original chunk data. + // This is done within the m_csDirtyChunks critical section, which + // means that any chunks can't be repositioned whilst we are doing + // this copy. The copy will then be guaranteed to be consistent + // whilst rebuilding takes place outside of that critical section. + permaChunk[index].makeCopyForRebuild(chunk); + ++index; + } + LeaveCriticalSection(&m_csDirtyChunks); - --index; // Bring it back into 0 counted range + --index; // Bring it back into 0 counted range - for(int i = MAX_CHUNK_REBUILD_THREADS - 1; i >= 0; --i) - { - // Set the events that won't run - if( (i+1) > index) s_rebuildCompleteEvents->Set(i); - else break; - } + for (int i = MAX_CHUNK_REBUILD_THREADS - 1; i >= 0; --i) { + // Set the events that won't run + if ((i + 1) > index) + s_rebuildCompleteEvents->Set(i); + else + break; + } - for(; index >=0; --index) - { - bool bAtomic = false; - if((veryNearCount > 0)) - bAtomic = true; //MGH - if veryNearCount, then we're trying to rebuild atomically, so do it all on the main thread + for (; index >= 0; --index) { + bool bAtomic = false; + if ((veryNearCount > 0)) + bAtomic = true; // MGH - if veryNearCount, then we're trying + // to rebuild atomically, so do it all on the + // main thread - if( bAtomic || (index == 0) ) - { - //PIXBeginNamedEvent(0,"Rebuilding near chunk %d %d %d",chunk->x, chunk->y, chunk->z); - // static __int64 totalTime = 0; - // static __int64 countTime = 0; - // __int64 startTime = System::currentTimeMillis(); + if (bAtomic || (index == 0)) { + // PIXBeginNamedEvent(0,"Rebuilding near chunk %d %d + // %d",chunk->x, chunk->y, chunk->z); static __int64 totalTime = + //0; static __int64 countTime = 0; + // __int64 startTime = System::currentTimeMillis(); - //app.DebugPrintf("Rebuilding permaChunk %d\n", index); + // app.DebugPrintf("Rebuilding permaChunk %d\n", index); - permaChunk[index].rebuild(); + permaChunk[index].rebuild(); - if(index !=0) - s_rebuildCompleteEvents->Set(index-1); // MGH - this rebuild happening on the main thread instead, mark the thread it should have been running on as complete + if (index != 0) + s_rebuildCompleteEvents->Set( + index - 1); // MGH - this rebuild happening on the main + // thread instead, mark the thread it + // should have been running on as complete - // __int64 endTime = System::currentTimeMillis(); - // totalTime += (endTime - startTime); - // countTime++; - // printf("%d : %f\n", countTime, (float)totalTime / (float)countTime); - //PIXEndNamedEvent(); - } - // 4J Stu - Ignore this path when in constrained mode on Xbox One - else - { - // Activate thread to rebuild this chunk - s_activationEventA[index - 1]->Set(); - } - } + // __int64 endTime = System::currentTimeMillis(); + // totalTime += (endTime - startTime); + // countTime++; + // printf("%d : %f\n", countTime, (float)totalTime + /// (float)countTime); PIXEndNamedEvent(); + } + // 4J Stu - Ignore this path when in constrained mode on Xbox One + else { + // Activate thread to rebuild this chunk + s_activationEventA[index - 1]->Set(); + } + } - // Wait for the other threads to be done as well - s_rebuildCompleteEvents->WaitForAll(INFINITE); - } + // Wait for the other threads to be done as well + s_rebuildCompleteEvents->WaitForAll(INFINITE); + } #else - if( nearChunk ) - { - chunk = nearChunk->chunk; - PIXBeginNamedEvent(0,"Rebuilding near chunk %d %d %d",chunk->x, chunk->y, chunk->z); - // If this chunk is very near, then move the renderer into a deferred mode. This won't commit any command buffers - // for rendering until we call CBuffDeferredModeEnd(), allowing us to group any near changes into an atomic unit. This - // is essential so we don't temporarily create any holes in the environment whilst updating one chunk and not the neighbours. - // The "ver near" aspect of this is just a cosmetic nicety - exactly the same thing would happen further away, but we just don't - // care about it so much from terms of visual impact. - if( veryNearCount > 0 ) - { - RenderManager.CBuffDeferredModeStart(); - } - // Build this chunk & return false to continue processing - chunk->clearDirty(); - // Take a copy of the details that are required for chunk rebuilding, and rebuild That instead of the original chunk data. This is done within - // the m_csDirtyChunks critical section, which means that any chunks can't be repositioned whilst we are doing this copy. The copy will then - // be guaranteed to be consistent whilst rebuilding takes place outside of that critical section. - static Chunk permaChunk; - permaChunk.makeCopyForRebuild(chunk); - LeaveCriticalSection(&m_csDirtyChunks); - // static __int64 totalTime = 0; - // static __int64 countTime = 0; - // __int64 startTime = System::currentTimeMillis(); - permaChunk.rebuild(); - // __int64 endTime = System::currentTimeMillis(); - // totalTime += (endTime - startTime); - // countTime++; - // printf("%d : %f\n", countTime, (float)totalTime / (float)countTime); - PIXEndNamedEvent(); - } + if (nearChunk) { + chunk = nearChunk->chunk; + PIXBeginNamedEvent(0, "Rebuilding near chunk %d %d %d", chunk->x, + chunk->y, chunk->z); + // If this chunk is very near, then move the renderer into a deferred + // mode. This won't commit any command buffers for rendering until we + // call CBuffDeferredModeEnd(), allowing us to group any near changes + // into an atomic unit. This is essential so we don't temporarily create + // any holes in the environment whilst updating one chunk and not the + // neighbours. The "ver near" aspect of this is just a cosmetic nicety - + // exactly the same thing would happen further away, but we just don't + // care about it so much from terms of visual impact. + if (veryNearCount > 0) { + RenderManager.CBuffDeferredModeStart(); + } + // Build this chunk & return false to continue processing + chunk->clearDirty(); + // Take a copy of the details that are required for chunk rebuilding, + // and rebuild That instead of the original chunk data. This is done + // within the m_csDirtyChunks critical section, which means that any + // chunks can't be repositioned whilst we are doing this copy. The copy + // will then be guaranteed to be consistent whilst rebuilding takes + // place outside of that critical section. + static Chunk permaChunk; + permaChunk.makeCopyForRebuild(chunk); + LeaveCriticalSection(&m_csDirtyChunks); + // static __int64 totalTime = 0; + // static __int64 countTime = 0; + // __int64 startTime = System::currentTimeMillis(); + permaChunk.rebuild(); + // __int64 endTime = System::currentTimeMillis(); + // totalTime += (endTime - startTime); + // countTime++; + // printf("%d : %f\n", countTime, (float)totalTime / + //(float)countTime); + PIXEndNamedEvent(); + } #endif - else - { - // Nothing to do - clear flags that there are things to process, unless it's been a while since we found any dirty chunks in which case force a check next time through - if( ( System::currentTimeMillis() - lastDirtyChunkFound ) > FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS ) - { - dirtyChunkPresent = true; - } - else - { - dirtyChunkPresent = false; - } - LeaveCriticalSection(&m_csDirtyChunks); + else { + // Nothing to do - clear flags that there are things to process, unless + // it's been a while since we found any dirty chunks in which case force + // a check next time through + if ((System::currentTimeMillis() - lastDirtyChunkFound) > + FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS) { + dirtyChunkPresent = true; + } else { + dirtyChunkPresent = false; + } + LeaveCriticalSection(&m_csDirtyChunks); #ifdef __PS3__ - Sleep(5); -#endif // __PS3__ - return false; - } + Sleep(5); +#endif // __PS3__ + return false; + } - // If there was more than one very near thing found in our initial assessment, then return true so that we will keep doing the other one(s) - // in an atomic unit - if( veryNearCount > 1 ) - { - destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, chunk->z, veryNearCount ); - return true; - } - // If the chunk we've just built was near, and it has been marked dirty at some point while we are rebuilding, also return true so - // we can rebuild the same thing atomically - if its data was changed during creating render data, it may well be invalid - if( ( veryNearCount == 1 ) && getGlobalChunkFlag(chunk->x, chunk->y, chunk->z, chunk->level, CHUNK_FLAG_DIRTY ) ) - { - destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, chunk->z, veryNearCount + 1); - return true; - } + // If there was more than one very near thing found in our initial + // assessment, then return true so that we will keep doing the other one(s) + // in an atomic unit + if (veryNearCount > 1) { + destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, + chunk->z, veryNearCount); + return true; + } + // If the chunk we've just built was near, and it has been marked dirty at + // some point while we are rebuilding, also return true so we can rebuild + // the same thing atomically - if its data was changed during creating + // render data, it may well be invalid + if ((veryNearCount == 1) && + getGlobalChunkFlag(chunk->x, chunk->y, chunk->z, chunk->level, + CHUNK_FLAG_DIRTY)) { + destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, + chunk->z, veryNearCount + 1); + return true; + } - if( nearChunk ) destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, chunk->z, veryNearCount ); + if (nearChunk) + destroyedTileManager->updatedChunkAt(chunk->level, chunk->x, chunk->y, + chunk->z, veryNearCount); - return false; + return false; } +void LevelRenderer::renderHit(std::shared_ptr player, HitResult* h, + int mode, + std::shared_ptr inventoryItem, + float a) { + Tesselator* t = Tesselator::getInstance(); + glEnable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glColor4f( + 1, 1, 1, + ((float)(Mth::sin(Minecraft::currentTimeMillis() / 100.0f)) * 0.2f + + 0.4f) * + 0.5f); + if (mode != 0 && inventoryItem != NULL) { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + float br = + (Mth::sin(Minecraft::currentTimeMillis() / 100.0f) * 0.2f + 0.8f); + glColor4f( + br, br, br, + (Mth::sin(Minecraft::currentTimeMillis() / 200.0f) * 0.2f + 0.5f)); -void LevelRenderer::renderHit(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a) -{ - Tesselator *t = Tesselator::getInstance(); - glEnable(GL_BLEND); - glEnable(GL_ALPHA_TEST); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glColor4f(1, 1, 1, ((float) (Mth::sin(Minecraft::currentTimeMillis() / 100.0f)) * 0.2f + 0.4f) * 0.5f); - if (mode != 0 && inventoryItem != NULL) - { - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - float br = (Mth::sin(Minecraft::currentTimeMillis() / 100.0f) * 0.2f + 0.8f); - glColor4f(br, br, br, (Mth::sin(Minecraft::currentTimeMillis() / 200.0f) * 0.2f + 0.5f)); - - textures->bindTexture(TN_TERRAIN); //L"/terrain.png"); - } - glDisable(GL_BLEND); - glDisable(GL_ALPHA_TEST); + textures->bindTexture(TN_TERRAIN); // L"/terrain.png"); + } + glDisable(GL_BLEND); + glDisable(GL_ALPHA_TEST); } -void LevelRenderer::renderDestroyAnimation(Tesselator *t, std::shared_ptr player, float a) -{ - double xo = player->xOld + (player->x - player->xOld) * a; - double yo = player->yOld + (player->y - player->yOld) * a; - double zo = player->zOld + (player->z - player->zOld) * a; +void LevelRenderer::renderDestroyAnimation(Tesselator* t, + std::shared_ptr player, + float a) { + double xo = player->xOld + (player->x - player->xOld) * a; + double yo = player->yOld + (player->y - player->yOld) * a; + double zo = player->zOld + (player->z - player->zOld) * a; - int playerIndex = mc->player->GetXboxPad(); - if (!destroyingBlocks.empty()) - { - glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); + int playerIndex = mc->player->GetXboxPad(); + if (!destroyingBlocks.empty()) { + glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR); - textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - glColor4f(1, 1, 1, 0.5f); - glPushMatrix(); + textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + glColor4f(1, 1, 1, 0.5f); + glPushMatrix(); - glDisable(GL_ALPHA_TEST); + glDisable(GL_ALPHA_TEST); - glPolygonOffset(-3.0f, -3.0f); - glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(-3.0f, -3.0f); + glEnable(GL_POLYGON_OFFSET_FILL); - glEnable(GL_ALPHA_TEST); - t->begin(); + glEnable(GL_ALPHA_TEST); + t->begin(); #ifdef __PSVITA__ - // AP : fix for bug 4952. No amount of polygon offset will push this close enough to be seen above the second tile layer when looking straight down - // so just add on a little bit of y to fix this. hacky hacky - t->offset((float)-xo, (float)-yo + 0.01f,(float) -zo); + // AP : fix for bug 4952. No amount of polygon offset will push this + // close enough to be seen above the second tile layer when looking + // straight down so just add on a little bit of y to fix this. hacky + // hacky + t->offset((float)-xo, (float)-yo + 0.01f, (float)-zo); #else - t->offset((float)-xo, (float)-yo,(float) -zo); + t->offset((float)-xo, (float)-yo, (float)-zo); #endif - t->noColor(); + t->noColor(); - AUTO_VAR(it, destroyingBlocks.begin()); - while (it != destroyingBlocks.end()) - { - BlockDestructionProgress *block = it->second; - double xd = block->getX() - xo; - double yd = block->getY() - yo; - double zd = block->getZ() - zo; + AUTO_VAR(it, destroyingBlocks.begin()); + while (it != destroyingBlocks.end()) { + BlockDestructionProgress* block = it->second; + double xd = block->getX() - xo; + double yd = block->getY() - yo; + double zd = block->getZ() - zo; - if (xd * xd + yd * yd + zd * zd < 32 * 32) // 4J MGH - now only culling instead of removing, as the list is shared in split screen - { - int iPad = mc->player->GetXboxPad(); // 4J added - int tileId = level[iPad]->getTile(block->getX(), block->getY(), block->getZ()); - Tile *tile = tileId > 0 ? Tile::tiles[tileId] : NULL; - if (tile == NULL) tile = Tile::rock; - tileRenderer[iPad]->tesselateInWorldFixedTexture(tile, block->getX(), block->getY(), block->getZ(), breakingTextures[block->getProgress()]); // 4J renamed to differentiate from tesselateInWorld - } - ++it; - } + if (xd * xd + yd * yd + zd * zd < + 32 * 32) // 4J MGH - now only culling instead of removing, as + // the list is shared in split screen + { + int iPad = mc->player->GetXboxPad(); // 4J added + int tileId = level[iPad]->getTile(block->getX(), block->getY(), + block->getZ()); + Tile* tile = tileId > 0 ? Tile::tiles[tileId] : NULL; + if (tile == NULL) tile = Tile::rock; + tileRenderer[iPad]->tesselateInWorldFixedTexture( + tile, block->getX(), block->getY(), block->getZ(), + breakingTextures + [block->getProgress()]); // 4J renamed to differentiate + // from tesselateInWorld + } + ++it; + } - t->end(); - t->offset(0, 0, 0); - glDisable(GL_ALPHA_TEST); - /* - * for (int i = 0; i < 6; i++) { tile.renderFace(t, h.x, h.y, - * h.z, i, 15 * 16 + (int) (destroyProgress * 10)); } - */ - glPolygonOffset(0.0f, 0.0f); - glDisable(GL_POLYGON_OFFSET_FILL); - glEnable(GL_ALPHA_TEST); + t->end(); + t->offset(0, 0, 0); + glDisable(GL_ALPHA_TEST); + /* + * for (int i = 0; i < 6; i++) { tile.renderFace(t, h.x, h.y, + * h.z, i, 15 * 16 + (int) (destroyProgress * 10)); } + */ + glPolygonOffset(0.0f, 0.0f); + glDisable(GL_POLYGON_OFFSET_FILL); + glEnable(GL_ALPHA_TEST); - glDepthMask(true); - glPopMatrix(); - } + glDepthMask(true); + glPopMatrix(); + } } -void LevelRenderer::renderHitOutline(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a) -{ +void LevelRenderer::renderHitOutline( + std::shared_ptr player, HitResult* h, int mode, + std::shared_ptr inventoryItem, float a) { + if (mode == 0 && h->type == HitResult::TILE) { + int iPad = mc->player->GetXboxPad(); // 4J added - if (mode == 0 && h->type == HitResult::TILE) - { - int iPad = mc->player->GetXboxPad(); // 4J added + // 4J-PB - If Display HUD is false, don't render the hit outline + if (app.GetGameSettings(iPad, eGameSetting_DisplayHUD) == 0) return; - // 4J-PB - If Display HUD is false, don't render the hit outline - if ( app.GetGameSettings(iPad,eGameSetting_DisplayHUD)==0 ) return; + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(0, 0, 0, 0.4f); + glLineWidth(2.0f); + glDisable(GL_TEXTURE_2D); + glDepthMask(false); + float ss = 0.002f; + int tileId = level[iPad]->getTile(h->x, h->y, h->z); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(0, 0, 0, 0.4f); - glLineWidth(2.0f); - glDisable(GL_TEXTURE_2D); - glDepthMask(false); - float ss = 0.002f; - int tileId = level[iPad]->getTile(h->x, h->y, h->z); - - if (tileId > 0) - { - Tile::tiles[tileId]->updateShape(level[iPad], h->x, h->y, h->z); - double xo = player->xOld + (player->x - player->xOld) * a; - double yo = player->yOld + (player->y - player->yOld) * a; - double zo = player->zOld + (player->z - player->zOld) * a; - render(Tile::tiles[tileId]->getTileAABB(level[iPad], h->x, h->y, h->z)->grow(ss, ss, ss)->cloneMove(-xo, -yo, -zo)); - } - glDepthMask(true); - glEnable(GL_TEXTURE_2D); - glDisable(GL_BLEND); - } + if (tileId > 0) { + Tile::tiles[tileId]->updateShape(level[iPad], h->x, h->y, h->z); + double xo = player->xOld + (player->x - player->xOld) * a; + double yo = player->yOld + (player->y - player->yOld) * a; + double zo = player->zOld + (player->z - player->zOld) * a; + render(Tile::tiles[tileId] + ->getTileAABB(level[iPad], h->x, h->y, h->z) + ->grow(ss, ss, ss) + ->cloneMove(-xo, -yo, -zo)); + } + glDepthMask(true); + glEnable(GL_TEXTURE_2D); + glDisable(GL_BLEND); + } } -void LevelRenderer::render(AABB *b) -{ - Tesselator *t = Tesselator::getInstance(); +void LevelRenderer::render(AABB* b) { + Tesselator* t = Tesselator::getInstance(); - t->begin(GL_LINE_STRIP); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->end(); + t->begin(GL_LINE_STRIP); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z0)); + t->end(); - t->begin(GL_LINE_STRIP); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->end(); + t->begin(GL_LINE_STRIP); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z0)); + t->end(); - t->begin(GL_LINES); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z0)); - t->vertex((float)(b->x1), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x1), (float)( b->y1), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y0), (float)( b->z1)); - t->vertex((float)(b->x0), (float)( b->y1), (float)( b->z1)); - t->end(); + t->begin(GL_LINES); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z0)); + t->vertex((float)(b->x1), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x1), (float)(b->y1), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y0), (float)(b->z1)); + t->vertex((float)(b->x0), (float)(b->y1), (float)(b->z1)); + t->end(); } -void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) // 4J - added level param +void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level) // 4J - added level param { - // 4J - level is passed if this is coming from setTilesDirty, which could come from when connection is being ticked outside of normal level tick, and player won't - // be set up - if( level == NULL ) level = this->level[mc->player->GetXboxPad()]; - // EnterCriticalSection(&m_csDirtyChunks); - int _x0 = Mth::intFloorDiv(x0, CHUNK_XZSIZE); - int _y0 = Mth::intFloorDiv(y0, CHUNK_SIZE); - int _z0 = Mth::intFloorDiv(z0, CHUNK_XZSIZE); - int _x1 = Mth::intFloorDiv(x1, CHUNK_XZSIZE); - int _y1 = Mth::intFloorDiv(y1, CHUNK_SIZE); - int _z1 = Mth::intFloorDiv(z1, CHUNK_XZSIZE); + // 4J - level is passed if this is coming from setTilesDirty, which could + // come from when connection is being ticked outside of normal level tick, + // and player won't be set up + if (level == NULL) level = this->level[mc->player->GetXboxPad()]; + // EnterCriticalSection(&m_csDirtyChunks); + int _x0 = Mth::intFloorDiv(x0, CHUNK_XZSIZE); + int _y0 = Mth::intFloorDiv(y0, CHUNK_SIZE); + int _z0 = Mth::intFloorDiv(z0, CHUNK_XZSIZE); + int _x1 = Mth::intFloorDiv(x1, CHUNK_XZSIZE); + int _y1 = Mth::intFloorDiv(y1, CHUNK_SIZE); + int _z1 = Mth::intFloorDiv(z1, CHUNK_XZSIZE); - for (int x = _x0; x <= _x1; x++) - { - for (int y = _y0; y <= _y1; y++) - { - for (int z = _z0; z <= _z1; z++) - { - // printf("Setting %d %d %d dirty\n",x,y,z); - int index = getGlobalIndexForChunk(x * 16, y * 16, z * 16, level); - // Rather than setting the flags directly, add any dirty chunks into a lock free stack - this avoids having to lock m_csDirtyChunks . - // These chunks are then added to the global flags in the render update thread. - // An XLockFreeQueue actually implements a queue of pointers to its templated type, and I don't want to have to go allocating ints here just to store the - // pointer to them in a queue. Hence actually pretending that the int Is a pointer here. Our Index has a a valid range from 0 to something quite big, - // but including zero. The lock free queue, since it thinks it is dealing with pointers, uses a NULL pointer to signify that a Pop hasn't succeeded. - // We also want to reserve one special value (of 1 ) for use when multiple chunks not individually listed are made dirty. Therefore adding 2 to our - // index value here to move our valid range from 1 to something quite big + 2 - if( index > -1 ) - { + for (int x = _x0; x <= _x1; x++) { + for (int y = _y0; y <= _y1; y++) { + for (int z = _z0; z <= _z1; z++) { + // printf("Setting %d %d %d + //dirty\n",x,y,z); + int index = + getGlobalIndexForChunk(x * 16, y * 16, z * 16, level); + // Rather than setting the flags directly, add any dirty chunks + // into a lock free stack - this avoids having to lock + // m_csDirtyChunks . These chunks are then added to the global + // flags in the render update thread. An XLockFreeQueue actually + // implements a queue of pointers to its templated type, and I + // don't want to have to go allocating ints here just to store + // the pointer to them in a queue. Hence actually pretending + // that the int Is a pointer here. Our Index has a a valid range + // from 0 to something quite big, but including zero. The lock + // free queue, since it thinks it is dealing with pointers, uses + // a NULL pointer to signify that a Pop hasn't succeeded. We + // also want to reserve one special value (of 1 ) for use when + // multiple chunks not individually listed are made dirty. + // Therefore adding 2 to our index value here to move our valid + // range from 1 to something quite big + 2 + if (index > -1) { #ifdef _CRITICAL_CHUNKS - index += 2; + index += 2; - // AP - by the time we reach this function the area passed in has a 1 block border added to it to make sure geometry and lighting is updated correctly. - // Some of those blocks will only need lighting updated so it is acceptable to not have those blocks grouped in the deferral system as the mismatch - // will hardly be noticable. The blocks that need geometry updated will be adjacent to the original, non-bordered area. - // This bit of code will mark a chunk as 'non-critical' if all of the blocks inside it are NOT adjacent to the original area. This has the greatest effect - // when digging a single block. Only 6 of the blocks out of the possible 26 are actually adjacent to the original block. The other 20 only need lighting updated. - // Note I have noticed a new side effect of this system where it's possible to see into the sides of water but this is acceptable compared to seeing through - // the entire landscape. - // is the left or right most block just inside this chunk - if( ((x0 & 15) == 15 && x == _x0) || ((x1 & 15) == 0 && x == _x1) ) - { - // is the front, back, top or bottom most block just inside this chunk - if( ((z0 & 15) == 15 && z == _z0) || ((z1 & 15) == 0 && z == _z1) || - ((y0 & 15) == 15 && y == _y0) || ((y1 & 15) == 0 && y == _y1)) - { - index |= 0x10000000; - } - } - else - { - // is the front or back most block just inside this chunk - if( ((z0 & 15) == 15 && z == _z0) || ((z1 & 15) == 0 && z == _z1) ) - { - // is the top or bottom most block just inside this chunk - if( ((y0 & 15) == 15 && y == _y0) || ((y1 & 15) == 0 && y == _y1)) - { - index |= 0x10000000; - } - } - } + // AP - by the time we reach this function the area passed + // in has a 1 block border added to it to make sure geometry + // and lighting is updated correctly. Some of those blocks + // will only need lighting updated so it is acceptable to + // not have those blocks grouped in the deferral system as + // the mismatch will hardly be noticable. The blocks that + // need geometry updated will be adjacent to the original, + // non-bordered area. This bit of code will mark a chunk as + // 'non-critical' if all of the blocks inside it are NOT + // adjacent to the original area. This has the greatest + // effect when digging a single block. Only 6 of the blocks + // out of the possible 26 are actually adjacent to the + // original block. The other 20 only need lighting updated. + // Note I have noticed a new side effect of this system + // where it's possible to see into the sides of water but + // this is acceptable compared to seeing through the entire + // landscape. is the left or right most block just inside + // this chunk + if (((x0 & 15) == 15 && x == _x0) || + ((x1 & 15) == 0 && x == _x1)) { + // is the front, back, top or bottom most block just + // inside this chunk + if (((z0 & 15) == 15 && z == _z0) || + ((z1 & 15) == 0 && z == _z1) || + ((y0 & 15) == 15 && y == _y0) || + ((y1 & 15) == 0 && y == _y1)) { + index |= 0x10000000; + } + } else { + // is the front or back most block just inside this + // chunk + if (((z0 & 15) == 15 && z == _z0) || + ((z1 & 15) == 0 && z == _z1)) { + // is the top or bottom most block just inside this + // chunk + if (((y0 & 15) == 15 && y == _y0) || + ((y1 & 15) == 0 && y == _y1)) { + index |= 0x10000000; + } + } + } - dirtyChunksLockFreeStack.Push((int *)(index)); + dirtyChunksLockFreeStack.Push((int*)(index)); #else - dirtyChunksLockFreeStack.Push((int *)(intptr_t)(uintptr_t)(index + 2)); + dirtyChunksLockFreeStack.Push( + (int*)(intptr_t)(uintptr_t)(index + 2)); #endif #ifdef _XBOX - PIXSetMarker(0,"Setting chunk %d %d %d dirty",x * 16,y * 16,z * 16); + PIXSetMarker(0, "Setting chunk %d %d %d dirty", x * 16, + y * 16, z * 16); #else - PIXSetMarkerDeprecated(0,"Setting chunk %d %d %d dirty",x * 16,y * 16,z * 16); + PIXSetMarkerDeprecated(0, "Setting chunk %d %d %d dirty", + x * 16, y * 16, z * 16); #endif - } - // setGlobalChunkFlag(x * 16, y * 16, z * 16, level, CHUNK_FLAG_DIRTY); - } - } - } - // LeaveCriticalSection(&m_csDirtyChunks); + } + // setGlobalChunkFlag(x * 16, y * + //16, z * 16, level, CHUNK_FLAG_DIRTY); + } + } + } + // LeaveCriticalSection(&m_csDirtyChunks); } -void LevelRenderer::tileChanged(int x, int y, int z) -{ - setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); +void LevelRenderer::tileChanged(int x, int y, int z) { + setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); } -void LevelRenderer::tileLightChanged(int x, int y, int z) -{ - setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); +void LevelRenderer::tileLightChanged(int x, int y, int z) { + setDirty(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, NULL); } -void LevelRenderer::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) // 4J - added level param +void LevelRenderer::setTilesDirty(int x0, int y0, int z0, int x1, int y1, + int z1, + Level* level) // 4J - added level param { - setDirty(x0 - 1, y0 - 1, z0 - 1, x1 + 1, y1 + 1, z1 + 1, level); + setDirty(x0 - 1, y0 - 1, z0 - 1, x1 + 1, y1 + 1, z1 + 1, level); } -bool inline clip(float *bb, float *frustum) -{ - for (int i = 0; i < 6; ++i, frustum += 4) - { - if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; - if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + frustum[3] > 0) continue; +bool inline clip(float* bb, float* frustum) { + for (int i = 0; i < 6; ++i, frustum += 4) { + if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[2]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[0]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[1]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[0]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; + if (frustum[0] * (bb[3]) + frustum[1] * (bb[4]) + frustum[2] * (bb[5]) + + frustum[3] > + 0) + continue; - return false; - } + return false; + } - return true; + return true; } #ifdef __PS3__ -int g_listArray_layer0[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); // 8000 -int g_listArray_layer1[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); -float g_zDepth_layer0[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); // 8000 -float g_zDepth_layer1[4][LevelRenderer_cull_DataIn::sc_listSize]__attribute__((__aligned__(16))); +int g_listArray_layer0[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); // 8000 +int g_listArray_layer1[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); +float g_zDepth_layer0[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); // 8000 +float g_zDepth_layer1[4][LevelRenderer_cull_DataIn::sc_listSize] + __attribute__((__aligned__(16))); volatile bool g_useIdent = false; volatile float g_maxDepthRender = 1000; volatile float g_maxHeightRender = -1000; volatile float g_offMulVal = 1; -void LevelRenderer::cull_SPU(int playerIndex, Culler *culler, float a) -{ - if(m_bSPUCullStarted[playerIndex]) - { - return; // running already - } +void LevelRenderer::cull_SPU(int playerIndex, Culler* culler, float a) { + if (m_bSPUCullStarted[playerIndex]) { + return; // running already + } - FrustumCuller *fc = (FrustumCuller *)culler; - FrustumData *fd = fc->frustum; - float fdraw[6 * 4]; - for( int i = 0; i < 6; i++ ) - { - double fx = fd->m_Frustum[i][0]; - double fy = fd->m_Frustum[i][1]; - double fz = fd->m_Frustum[i][2]; - fdraw[i * 4 + 0] = (float)fx; - fdraw[i * 4 + 1] = (float)fy; - fdraw[i * 4 + 2] = (float)fz; - fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + ( fx * -fc->xOff ) + ( fy * - fc->yOff ) + ( fz * -fc->zOff )); - } + FrustumCuller* fc = (FrustumCuller*)culler; + FrustumData* fd = fc->frustum; + float fdraw[6 * 4]; + for (int i = 0; i < 6; i++) { + double fx = fd->m_Frustum[i][0]; + double fy = fd->m_Frustum[i][1]; + double fz = fd->m_Frustum[i][2]; + fdraw[i * 4 + 0] = (float)fx; + fdraw[i * 4 + 1] = (float)fy; + fdraw[i * 4 + 2] = (float)fz; + fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + (fx * -fc->xOff) + + (fy * -fc->yOff) + (fz * -fc->zOff)); + } - memcpy(&g_cullDataIn[playerIndex].fdraw, fdraw, sizeof(fdraw)); - g_cullDataIn[playerIndex].numClipChunks = chunks[playerIndex].length; - g_cullDataIn[playerIndex].pClipChunks = (ClipChunk_SPU*)chunks[playerIndex].data; - g_cullDataIn[playerIndex].numGlobalChunks = getGlobalChunkCount(); - g_cullDataIn[playerIndex].pGlobalChunkFlags = globalChunkFlags; - g_cullDataIn[playerIndex].chunkLists = chunkLists; - g_cullDataIn[playerIndex].listArray_layer0 = g_listArray_layer0[playerIndex]; - g_cullDataIn[playerIndex].listArray_layer1 = g_listArray_layer1[playerIndex]; - g_cullDataIn[playerIndex].zDepth_layer0 = g_zDepth_layer0[playerIndex]; - g_cullDataIn[playerIndex].zDepth_layer1 = g_zDepth_layer1[playerIndex]; - g_cullDataIn[playerIndex].maxDepthRender = g_maxDepthRender; - g_cullDataIn[playerIndex].maxHeightRender = g_maxHeightRender; + memcpy(&g_cullDataIn[playerIndex].fdraw, fdraw, sizeof(fdraw)); + g_cullDataIn[playerIndex].numClipChunks = chunks[playerIndex].length; + g_cullDataIn[playerIndex].pClipChunks = + (ClipChunk_SPU*)chunks[playerIndex].data; + g_cullDataIn[playerIndex].numGlobalChunks = getGlobalChunkCount(); + g_cullDataIn[playerIndex].pGlobalChunkFlags = globalChunkFlags; + g_cullDataIn[playerIndex].chunkLists = chunkLists; + g_cullDataIn[playerIndex].listArray_layer0 = + g_listArray_layer0[playerIndex]; + g_cullDataIn[playerIndex].listArray_layer1 = + g_listArray_layer1[playerIndex]; + g_cullDataIn[playerIndex].zDepth_layer0 = g_zDepth_layer0[playerIndex]; + g_cullDataIn[playerIndex].zDepth_layer1 = g_zDepth_layer1[playerIndex]; + g_cullDataIn[playerIndex].maxDepthRender = g_maxDepthRender; + g_cullDataIn[playerIndex].maxHeightRender = g_maxHeightRender; - if(g_useIdent) - g_cullDataIn[playerIndex].clipMat = Vectormath::Aos::Matrix4::identity(); - else - { - memcpy(&g_cullDataIn[playerIndex].clipMat, &fc->frustum->modl[0], sizeof(float) * 16); - g_cullDataIn[playerIndex].clipMat[3][0] = -fc->xOff; - g_cullDataIn[playerIndex].clipMat[3][1] = -fc->yOff; - g_cullDataIn[playerIndex].clipMat[3][2] = -fc->zOff; - } + if (g_useIdent) + g_cullDataIn[playerIndex].clipMat = + Vectormath::Aos::Matrix4::identity(); + else { + memcpy(&g_cullDataIn[playerIndex].clipMat, &fc->frustum->modl[0], + sizeof(float) * 16); + g_cullDataIn[playerIndex].clipMat[3][0] = -fc->xOff; + g_cullDataIn[playerIndex].clipMat[3][1] = -fc->yOff; + g_cullDataIn[playerIndex].clipMat[3][2] = -fc->zOff; + } + C4JSpursJob_LevelRenderer_cull cullJob(&g_cullDataIn[playerIndex]); + C4JSpursJob_LevelRenderer_zSort sortJob(&g_cullDataIn[playerIndex]); - C4JSpursJob_LevelRenderer_cull cullJob(&g_cullDataIn[playerIndex]); - C4JSpursJob_LevelRenderer_zSort sortJob(&g_cullDataIn[playerIndex]); - - m_jobPort_CullSPU->submitJob(&cullJob); - m_jobPort_CullSPU->submitSync(); - // static int doSort = false; - // if(doSort) - { - m_jobPort_CullSPU->submitJob(&sortJob); - } - // doSort ^= 1; - m_bSPUCullStarted[playerIndex] = true; + m_jobPort_CullSPU->submitJob(&cullJob); + m_jobPort_CullSPU->submitSync(); + // static int doSort = false; + // if(doSort) + { + m_jobPort_CullSPU->submitJob(&sortJob); + } + // doSort ^= 1; + m_bSPUCullStarted[playerIndex] = true; } -void LevelRenderer::waitForCull_SPU() -{ - m_jobPort_CullSPU->waitForCompletion(); - int playerIndex = mc->player->GetXboxPad(); // 4J added - m_bSPUCullStarted[playerIndex] = false; +void LevelRenderer::waitForCull_SPU() { + m_jobPort_CullSPU->waitForCompletion(); + int playerIndex = mc->player->GetXboxPad(); // 4J added + m_bSPUCullStarted[playerIndex] = false; } -#endif // __PS3__ +#endif // __PS3__ -void LevelRenderer::cull(Culler *culler, float a) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added +void LevelRenderer::cull(Culler* culler, float a) { + int playerIndex = mc->player->GetXboxPad(); // 4J added #if defined __PS3__ && !defined DISABLE_SPU_CODE - cull_SPU(playerIndex, culler, a); - return; -#endif // __PS3__ + cull_SPU(playerIndex, culler, a); + return; +#endif // __PS3__ + FrustumCuller* fc = (FrustumCuller*)culler; + FrustumData* fd = fc->frustum; + float fdraw[6 * 4]; + for (int i = 0; i < 6; i++) { + double fx = fd->m_Frustum[i][0]; + double fy = fd->m_Frustum[i][1]; + double fz = fd->m_Frustum[i][2]; + fdraw[i * 4 + 0] = (float)fx; + fdraw[i * 4 + 1] = (float)fy; + fdraw[i * 4 + 2] = (float)fz; + fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + (fx * -fc->xOff) + + (fy * -fc->yOff) + (fz * -fc->zOff)); + } - FrustumCuller *fc = (FrustumCuller *)culler; - FrustumData *fd = fc->frustum; - float fdraw[6 * 4]; - for( int i = 0; i < 6; i++ ) - { - double fx = fd->m_Frustum[i][0]; - double fy = fd->m_Frustum[i][1]; - double fz = fd->m_Frustum[i][2]; - fdraw[i * 4 + 0] = (float)fx; - fdraw[i * 4 + 1] = (float)fy; - fdraw[i * 4 + 2] = (float)fz; - fdraw[i * 4 + 3] = (float)(fd->m_Frustum[i][3] + ( fx * -fc->xOff ) + ( fy * - fc->yOff ) + ( fz * -fc->zOff )); - } + ClipChunk* pClipChunk = chunks[playerIndex].data; + int vis = 0; + int total = 0; + int numWrong = 0; + for (unsigned int i = 0; i < chunks[playerIndex].length; i++) { + unsigned char flags = pClipChunk->globalIdx == -1 + ? 0 + : globalChunkFlags[pClipChunk->globalIdx]; - ClipChunk *pClipChunk = chunks[playerIndex].data; - int vis = 0; - int total = 0; - int numWrong = 0; - for (unsigned int i = 0; i < chunks[playerIndex].length; i++) - { - unsigned char flags = pClipChunk->globalIdx == -1 ? 0 : globalChunkFlags[ pClipChunk->globalIdx ]; - - if ( (flags & CHUNK_FLAG_COMPILED ) && ( ( flags & CHUNK_FLAG_EMPTYBOTH ) != CHUNK_FLAG_EMPTYBOTH ) ) - { - bool clipres = clip(pClipChunk->aabb, fdraw); - pClipChunk->visible = clipres; - if( pClipChunk->visible ) vis++; - total++; - } - else - { - pClipChunk->visible = false; - } - pClipChunk++; - } + if ((flags & CHUNK_FLAG_COMPILED) && + ((flags & CHUNK_FLAG_EMPTYBOTH) != CHUNK_FLAG_EMPTYBOTH)) { + bool clipres = clip(pClipChunk->aabb, fdraw); + pClipChunk->visible = clipres; + if (pClipChunk->visible) vis++; + total++; + } else { + pClipChunk->visible = false; + } + pClipChunk++; + } } -void LevelRenderer::playStreamingMusic(const std::wstring& name, int x, int y, int z) -{ - if (name != L"") - { - mc->gui->setNowPlaying(L"C418 - " + name); - } - mc->soundEngine->playStreaming(name, (float) x, (float) y, (float) z, 1, 1); +void LevelRenderer::playStreamingMusic(const std::wstring& name, int x, int y, + int z) { + if (name != L"") { + mc->gui->setNowPlaying(L"C418 - " + name); + } + mc->soundEngine->playStreaming(name, (float)x, (float)y, (float)z, 1, 1); } -void LevelRenderer::playSound(int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist) -{ - // 4J-PB - removed in 1.4 +void LevelRenderer::playSound(int iSound, double x, double y, double z, + float volume, float pitch, float fSoundClipDist) { + // 4J-PB - removed in 1.4 - //float dd = 16; - /*if (volume > 1) fSoundClipDist *= volume; + // float dd = 16; + /*if (volume > 1) fSoundClipDist *= volume; - // 4J - find min distance to any players rather than just the current one - float minDistSq = FLT_MAX; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - if( mc->localplayers[i] ) - { - float distSq = mc->localplayers[i]->distanceToSqr(x, y, z ); - if( distSq < minDistSq ) - { - minDistSq = distSq; - } - } - } + // 4J - find min distance to any players rather than just the current one + float minDistSq = FLT_MAX; + for( int i = 0; i < XUSER_MAX_COUNT; i++ ) + { + if( mc->localplayers[i] ) + { + float distSq = mc->localplayers[i]->distanceToSqr(x, y, z ); + if( distSq < minDistSq ) + { + minDistSq = distSq; + } + } + } - if (minDistSq < fSoundClipDist * fSoundClipDist) - { - mc->soundEngine->play(iSound, (float) x, (float) y, (float) z, volume, pitch); - } */ + if (minDistSq < fSoundClipDist * fSoundClipDist) + { + mc->soundEngine->play(iSound, (float) x, (float) y, (float) z, volume, + pitch); + } */ } -void LevelRenderer::playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist) -{ -} +void LevelRenderer::playSound(std::shared_ptr entity, int iSound, + double x, double y, double z, float volume, + float pitch, float fSoundClipDist) {} // 4J-PB - original function. I've changed to an enum instead of string compares -// 4J removed - +// 4J removed - /* -void LevelRenderer::addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za) +void LevelRenderer::addParticle(const std::wstring& name, double x, double y, +double z, double xa, double ya, double za) { -if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) return; +if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) +return; double xd = mc->cameraTargetPlayer->x - x; double yd = mc->cameraTargetPlayer->y - y; @@ -2623,318 +2865,384 @@ if (xd * xd + yd * yd + zd * zd > particleDistance * particleDistance) return; int playerIndex = mc->player->GetXboxPad(); // 4J added -if (name== L"bubble") mc->particleEngine->add(std::shared_ptr( new BubbleParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"smoke") mc->particleEngine->add(std::shared_ptr( new SmokeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"note") mc->particleEngine->add(std::shared_ptr( new NoteParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"portal") mc->particleEngine->add(std::shared_ptr( new PortalParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"explode") mc->particleEngine->add(std::shared_ptr( new ExplodeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"flame") mc->particleEngine->add(std::shared_ptr( new FlameParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"lava") mc->particleEngine->add(std::shared_ptr( new LavaParticle(level[playerIndex], x, y, z) ) ); -else if (name== L"footstep") mc->particleEngine->add(std::shared_ptr( new FootstepParticle(textures, level[playerIndex], x, y, z) ) ); -else if (name== L"splash") mc->particleEngine->add(std::shared_ptr( new SplashParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"largesmoke") mc->particleEngine->add(std::shared_ptr( new SmokeParticle(level[playerIndex], x, y, z, xa, ya, za, 2.5f) ) ); -else if (name== L"reddust") mc->particleEngine->add(std::shared_ptr( new RedDustParticle(level[playerIndex], x, y, z, (float) xa, (float) ya, (float) za) ) ); -else if (name== L"snowballpoof") mc->particleEngine->add(std::shared_ptr( new BreakingItemParticle(level[playerIndex], x, y, z, Item::snowBall) ) ); -else if (name== L"snowshovel") mc->particleEngine->add(std::shared_ptr( new SnowShovelParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); -else if (name== L"slime") mc->particleEngine->add(std::shared_ptr( new BreakingItemParticle(level[playerIndex], x, y, z, Item::slimeBall)) ) ; -else if (name== L"heart") mc->particleEngine->add(std::shared_ptr( new HeartParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); +if (name== L"bubble") mc->particleEngine->add(std::shared_ptr( +new BubbleParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"smoke") mc->particleEngine->add(std::shared_ptr( new +SmokeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"note") mc->particleEngine->add(std::shared_ptr( new +NoteParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"portal") mc->particleEngine->add(std::shared_ptr( new +PortalParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"explode") mc->particleEngine->add(std::shared_ptr( new +ExplodeParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"flame") mc->particleEngine->add(std::shared_ptr( new +FlameParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"lava") mc->particleEngine->add(std::shared_ptr( new +LavaParticle(level[playerIndex], x, y, z) ) ); else if (name== L"footstep") +mc->particleEngine->add(std::shared_ptr( new +FootstepParticle(textures, level[playerIndex], x, y, z) ) ); else if (name== +L"splash") mc->particleEngine->add(std::shared_ptr( new +SplashParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"largesmoke") mc->particleEngine->add(std::shared_ptr( new +SmokeParticle(level[playerIndex], x, y, z, xa, ya, za, 2.5f) ) ); else if +(name== L"reddust") mc->particleEngine->add(std::shared_ptr( +new RedDustParticle(level[playerIndex], x, y, z, (float) xa, (float) ya, (float) +za) ) ); else if (name== L"snowballpoof") +mc->particleEngine->add(std::shared_ptr( new +BreakingItemParticle(level[playerIndex], x, y, z, Item::snowBall) ) ); else if +(name== L"snowshovel") +mc->particleEngine->add(std::shared_ptr( new +SnowShovelParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); else if (name== +L"slime") mc->particleEngine->add(std::shared_ptr( new +BreakingItemParticle(level[playerIndex], x, y, z, Item::slimeBall)) ) ; else if +(name== L"heart") mc->particleEngine->add(std::shared_ptr( new +HeartParticle(level[playerIndex], x, y, z, xa, ya, za) ) ); } */ -void LevelRenderer::addParticle(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za) -{ - addParticleInternal( eParticleType, x, y, z, xa, ya, za ); +void LevelRenderer::addParticle(ePARTICLE_TYPE eParticleType, double x, + double y, double z, double xa, double ya, + double za) { + addParticleInternal(eParticleType, x, y, z, xa, ya, za); } -std::shared_ptr LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za) -{ - if (mc == NULL || mc->cameraTargetPlayer == NULL || mc->particleEngine == NULL) - { - return nullptr; - } +std::shared_ptr LevelRenderer::addParticleInternal( + ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, + double ya, double za) { + if (mc == NULL || mc->cameraTargetPlayer == NULL || + mc->particleEngine == NULL) { + return nullptr; + } - // 4J added - do some explicit checking for NaN. The normal depth clipping seems to generally work for NaN (ie they get rejected), except on optimised PS3 code which - // reverses the logic on the comparison with particleDistanceSquared and gets the opposite result to what you might expect. - if( Double::isNaN(x) ) return nullptr; - if( Double::isNaN(y) ) return nullptr; - if( Double::isNaN(z) ) return nullptr; + // 4J added - do some explicit checking for NaN. The normal depth clipping + // seems to generally work for NaN (ie they get rejected), except on + // optimised PS3 code which reverses the logic on the comparison with + // particleDistanceSquared and gets the opposite result to what you might + // expect. + if (Double::isNaN(x)) return nullptr; + if (Double::isNaN(y)) return nullptr; + if (Double::isNaN(z)) return nullptr; - int particleLevel = mc->options->particles; + int particleLevel = mc->options->particles; - Level *lev; - int playerIndex = mc->player->GetXboxPad(); // 4J added - lev = level[playerIndex]; + Level* lev; + int playerIndex = mc->player->GetXboxPad(); // 4J added + lev = level[playerIndex]; - if (particleLevel == 1) - { - // when playing at "decreased" particle level, randomly filter - // particles by setting the level to "minimal" - if (level[playerIndex]->random->nextInt(3) == 0) - { - particleLevel = 2; - } - } + if (particleLevel == 1) { + // when playing at "decreased" particle level, randomly filter + // particles by setting the level to "minimal" + if (level[playerIndex]->random->nextInt(3) == 0) { + particleLevel = 2; + } + } - // 4J - the java code doesn't distance cull these two particle types, we need to implement this behaviour differently as our distance check is - // mixed up with other things - bool distCull = true; - if ( (eParticleType == eParticleType_hugeexplosion) || (eParticleType == eParticleType_largeexplode) || (eParticleType == eParticleType_dragonbreath) ) - { - distCull = false; - } + // 4J - the java code doesn't distance cull these two particle types, we + // need to implement this behaviour differently as our distance check is + // mixed up with other things + bool distCull = true; + if ((eParticleType == eParticleType_hugeexplosion) || + (eParticleType == eParticleType_largeexplode) || + (eParticleType == eParticleType_dragonbreath)) { + distCull = false; + } - // 4J - this is a bit of hack to get communication through from the level itself, but if Minecraft::animateTickLevel is NULL then - // we are to behave as normal, and if it is set, then we should use that as a pointer to the level the particle is to be created with - // rather than try to work it out from the current player. This is because in this state we are calling from a loop that is trying - // to amalgamate particle creation between all players for a particular level. Also don't do distance clipping as it isn't for a particular - // player, and distance is already taken into account before we get here anyway by the code in Level::animateTickDoWork - if( mc->animateTickLevel == NULL ) - { - double particleDistanceSquared = 16 * 16; - double xd = 0.0f; - double yd = 0.0f; - double zd = 0.0f; + // 4J - this is a bit of hack to get communication through from the level + // itself, but if Minecraft::animateTickLevel is NULL then we are to behave + // as normal, and if it is set, then we should use that as a pointer to the + // level the particle is to be created with rather than try to work it out + // from the current player. This is because in this state we are calling + // from a loop that is trying to amalgamate particle creation between all + // players for a particular level. Also don't do distance clipping as it + // isn't for a particular player, and distance is already taken into account + // before we get here anyway by the code in Level::animateTickDoWork + if (mc->animateTickLevel == NULL) { + double particleDistanceSquared = 16 * 16; + double xd = 0.0f; + double yd = 0.0f; + double zd = 0.0f; - // 4J Stu - Changed this as we need to check all local players in case one of them is in range of this particle - // Fix for #13454 - art : note blocks do not show notes - bool inRange = false; - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - std::shared_ptr thisPlayer = mc->localplayers[i]; - if(thisPlayer != NULL && level[i] == lev) - { - xd = thisPlayer->x - x; - yd = thisPlayer->y - y; - zd = thisPlayer->z - z; - if (xd * xd + yd * yd + zd * zd <= particleDistanceSquared) inRange = true; - } - } - if( (!inRange) && distCull ) return nullptr; - } - else - { - lev = mc->animateTickLevel; - } + // 4J Stu - Changed this as we need to check all local players in case + // one of them is in range of this particle Fix for #13454 - art : note + // blocks do not show notes + bool inRange = false; + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + std::shared_ptr thisPlayer = mc->localplayers[i]; + if (thisPlayer != NULL && level[i] == lev) { + xd = thisPlayer->x - x; + yd = thisPlayer->y - y; + zd = thisPlayer->z - z; + if (xd * xd + yd * yd + zd * zd <= particleDistanceSquared) + inRange = true; + } + } + if ((!inRange) && distCull) return nullptr; + } else { + lev = mc->animateTickLevel; + } - if (particleLevel > 1) - { - // TODO: If any of the particles below are necessary even if - // particles are turned off, then modify this if statement - return nullptr; - } + if (particleLevel > 1) { + // TODO: If any of the particles below are necessary even if + // particles are turned off, then modify this if statement + return nullptr; + } - std::shared_ptr particle; + std::shared_ptr particle; - switch(eParticleType) - { - case eParticleType_hugeexplosion: - particle = std::shared_ptr(new HugeExplosionSeedParticle(lev, x, y, z, xa, ya, za)); - break; - case eParticleType_largeexplode: - particle = std::shared_ptr(new HugeExplosionParticle(textures, lev, x, y, z, xa, ya, za)); - break; + switch (eParticleType) { + case eParticleType_hugeexplosion: + particle = std::shared_ptr( + new HugeExplosionSeedParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_largeexplode: + particle = std::shared_ptr( + new HugeExplosionParticle(textures, lev, x, y, z, xa, ya, za)); + break; - case eParticleType_bubble: - particle = std::shared_ptr( new BubbleParticle(lev, x, y, z, xa, ya, za) ); - break; + case eParticleType_bubble: + particle = std::shared_ptr( + new BubbleParticle(lev, x, y, z, xa, ya, za)); + break; - case eParticleType_suspended: - particle = std::shared_ptr( new SuspendedParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_depthsuspend: - particle = std::shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_townaura: - particle = std::shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_crit: - { - std::shared_ptr critParticle2 = std::shared_ptr(new CritParticle2(lev, x, y, z, xa, ya, za)); - critParticle2->CritParticle2PostConstructor(); - particle = std::shared_ptr( critParticle2 ); - // request from 343 to set pink for the needler in the Halo Texture Pack - // Set particle colour from colour-table. - unsigned int cStart = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_CritStart ); - unsigned int cEnd = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_CritEnd ); + case eParticleType_suspended: + particle = std::shared_ptr( + new SuspendedParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_depthsuspend: + particle = std::shared_ptr( + new SuspendedTownParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_townaura: + particle = std::shared_ptr( + new SuspendedTownParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_crit: { + std::shared_ptr critParticle2 = + std::shared_ptr( + new CritParticle2(lev, x, y, z, xa, ya, za)); + critParticle2->CritParticle2PostConstructor(); + particle = std::shared_ptr(critParticle2); + // request from 343 to set pink for the needler in the Halo Texture + // Pack Set particle colour from colour-table. + unsigned int cStart = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_CritStart); + unsigned int cEnd = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_CritEnd); - // If the start and end colours are the same, just set that colour, otherwise random between them - if(cStart==cEnd) - { - critParticle2->SetAgeUniformly(); - particle->setColor( ( (cStart>>16)&0xFF )/255.0f, ( (cStart>>8)&0xFF )/255.0, ( cStart&0xFF )/255.0 ); - } - else - { - float fStart=((float)(cStart&0xFF)); - float fDiff=(float)((cEnd-cStart)&0xFF); + // If the start and end colours are the same, just set that colour, + // otherwise random between them + if (cStart == cEnd) { + critParticle2->SetAgeUniformly(); + particle->setColor(((cStart >> 16) & 0xFF) / 255.0f, + ((cStart >> 8) & 0xFF) / 255.0, + (cStart & 0xFF) / 255.0); + } else { + float fStart = ((float)(cStart & 0xFF)); + float fDiff = (float)((cEnd - cStart) & 0xFF); - float fCol = (fStart + (Math::random() * fDiff))/255.0f; - particle->setColor( fCol, fCol, fCol ); - } - } - break; - case eParticleType_magicCrit: - { - std::shared_ptr critParticle2 = std::shared_ptr(new CritParticle2(lev, x, y, z, xa, ya, za)); - critParticle2->CritParticle2PostConstructor(); - particle = std::shared_ptr(critParticle2); - particle->setColor(particle->getRedCol() * 0.3f, particle->getGreenCol() * 0.8f, particle->getBlueCol()); - particle->setNextMiscAnimTex(); - } - break; - case eParticleType_smoke: - particle = std::shared_ptr( new SmokeParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_endportal: // 4J - Added. - { - SmokeParticle *tmp = new SmokeParticle(lev, x, y, z, xa, ya, za); + float fCol = (fStart + (Math::random() * fDiff)) / 255.0f; + particle->setColor(fCol, fCol, fCol); + } + } break; + case eParticleType_magicCrit: { + std::shared_ptr critParticle2 = + std::shared_ptr( + new CritParticle2(lev, x, y, z, xa, ya, za)); + critParticle2->CritParticle2PostConstructor(); + particle = std::shared_ptr(critParticle2); + particle->setColor(particle->getRedCol() * 0.3f, + particle->getGreenCol() * 0.8f, + particle->getBlueCol()); + particle->setNextMiscAnimTex(); + } break; + case eParticleType_smoke: + particle = std::shared_ptr( + new SmokeParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_endportal: // 4J - Added. + { + SmokeParticle* tmp = new SmokeParticle(lev, x, y, z, xa, ya, za); - // 4J-JEV: Set particle colour from colour-table. - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_EnderPortal ); - tmp->setColor( ( (col>>16)&0xFF )/255.0f, ( (col>>8)&0xFF )/255.0, ( col&0xFF )/255.0 ); + // 4J-JEV: Set particle colour from colour-table. + unsigned int col = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_EnderPortal); + tmp->setColor(((col >> 16) & 0xFF) / 255.0f, + ((col >> 8) & 0xFF) / 255.0, (col & 0xFF) / 255.0); - particle = std::shared_ptr(tmp); - } - break; - case eParticleType_mobSpell: - particle = std::shared_ptr(new SpellParticle(lev, x, y, z, 0, 0, 0)); - particle->setColor((float) xa, (float) ya, (float) za); - break; - case eParticleType_spell: - particle = std::shared_ptr( new SpellParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_instantSpell: - particle = std::shared_ptr(new SpellParticle(lev, x, y, z, xa, ya, za)); - std::dynamic_pointer_cast(particle)->setBaseTex(9 * 16); - break; - case eParticleType_note: - particle = std::shared_ptr( new NoteParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_netherportal: - particle = std::shared_ptr( new NetherPortalParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_ender: - particle = std::shared_ptr( new EnderParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_enchantmenttable: - particle = std::shared_ptr(new EchantmentTableParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_explode: - particle = std::shared_ptr( new ExplodeParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_flame: - particle = std::shared_ptr( new FlameParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_lava: - particle = std::shared_ptr( new LavaParticle(lev, x, y, z) ); - break; - case eParticleType_footstep: - particle = std::shared_ptr( new FootstepParticle(textures, lev, x, y, z) ); - break; - case eParticleType_splash: - particle = std::shared_ptr( new SplashParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_largesmoke: - particle = std::shared_ptr( new SmokeParticle(lev, x, y, z, xa, ya, za, 2.5f) ); - break; - case eParticleType_reddust: - particle = std::shared_ptr( new RedDustParticle(lev, x, y, z, (float) xa, (float) ya, (float) za) ); - break; - case eParticleType_snowballpoof: - particle = std::shared_ptr( new BreakingItemParticle(lev, x, y, z, Item::snowBall, textures) ); - break; - case eParticleType_dripWater: - particle = std::shared_ptr( new DripParticle(lev, x, y, z, Material::water) ); - break; - case eParticleType_dripLava: - particle = std::shared_ptr( new DripParticle(lev, x, y, z, Material::lava) ); - break; - case eParticleType_snowshovel: - particle = std::shared_ptr( new SnowShovelParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_slime: - particle = std::shared_ptr( new BreakingItemParticle(lev, x, y, z, Item::slimeBall, textures)); - break; - case eParticleType_heart: - particle = std::shared_ptr( new HeartParticle(lev, x, y, z, xa, ya, za) ); - break; - case eParticleType_angryVillager: - particle = std::shared_ptr( new HeartParticle(lev, x, y + 0.5f, z, xa, ya, za) ); - particle->setMiscTex(1 + 16 * 5); - particle->setColor(1, 1, 1); - break; - case eParticleType_happyVillager: - particle = std::shared_ptr( new SuspendedTownParticle(lev, x, y, z, xa, ya, za) ); - particle->setMiscTex(2 + 16 * 5); - particle->setColor(1, 1, 1); - break; - case eParticleType_dragonbreath: - particle = std::shared_ptr( new DragonBreathParticle(lev, x, y, z, xa, ya, za) ); - break; - default: - if( ( eParticleType >= eParticleType_iconcrack_base ) && ( eParticleType <= eParticleType_iconcrack_last ) ) - { - int id = PARTICLE_CRACK_ID(eParticleType), data = PARTICLE_CRACK_DATA(eParticleType); - particle = std::shared_ptr(new BreakingItemParticle(lev, x, y, z, xa, ya, za, Item::items[id], textures, data)); - } - else if( ( eParticleType >= eParticleType_tilecrack_base ) && ( eParticleType <= eParticleType_tilecrack_last ) ) - { - int id = PARTICLE_CRACK_ID(eParticleType), data = PARTICLE_CRACK_DATA(eParticleType); - particle = std::dynamic_pointer_cast( std::shared_ptr(new TerrainParticle(lev, x, y, z, xa, ya, za, Tile::tiles[id], 0, data, textures))->init(data) ); - } - } + particle = std::shared_ptr(tmp); + } break; + case eParticleType_mobSpell: + particle = std::shared_ptr( + new SpellParticle(lev, x, y, z, 0, 0, 0)); + particle->setColor((float)xa, (float)ya, (float)za); + break; + case eParticleType_spell: + particle = std::shared_ptr( + new SpellParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_instantSpell: + particle = std::shared_ptr( + new SpellParticle(lev, x, y, z, xa, ya, za)); + std::dynamic_pointer_cast(particle)->setBaseTex(9 * + 16); + break; + case eParticleType_note: + particle = std::shared_ptr( + new NoteParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_netherportal: + particle = std::shared_ptr( + new NetherPortalParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_ender: + particle = std::shared_ptr( + new EnderParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_enchantmenttable: + particle = std::shared_ptr( + new EchantmentTableParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_explode: + particle = std::shared_ptr( + new ExplodeParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_flame: + particle = std::shared_ptr( + new FlameParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_lava: + particle = + std::shared_ptr(new LavaParticle(lev, x, y, z)); + break; + case eParticleType_footstep: + particle = std::shared_ptr( + new FootstepParticle(textures, lev, x, y, z)); + break; + case eParticleType_splash: + particle = std::shared_ptr( + new SplashParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_largesmoke: + particle = std::shared_ptr( + new SmokeParticle(lev, x, y, z, xa, ya, za, 2.5f)); + break; + case eParticleType_reddust: + particle = std::shared_ptr(new RedDustParticle( + lev, x, y, z, (float)xa, (float)ya, (float)za)); + break; + case eParticleType_snowballpoof: + particle = std::shared_ptr(new BreakingItemParticle( + lev, x, y, z, Item::snowBall, textures)); + break; + case eParticleType_dripWater: + particle = std::shared_ptr( + new DripParticle(lev, x, y, z, Material::water)); + break; + case eParticleType_dripLava: + particle = std::shared_ptr( + new DripParticle(lev, x, y, z, Material::lava)); + break; + case eParticleType_snowshovel: + particle = std::shared_ptr( + new SnowShovelParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_slime: + particle = std::shared_ptr(new BreakingItemParticle( + lev, x, y, z, Item::slimeBall, textures)); + break; + case eParticleType_heart: + particle = std::shared_ptr( + new HeartParticle(lev, x, y, z, xa, ya, za)); + break; + case eParticleType_angryVillager: + particle = std::shared_ptr( + new HeartParticle(lev, x, y + 0.5f, z, xa, ya, za)); + particle->setMiscTex(1 + 16 * 5); + particle->setColor(1, 1, 1); + break; + case eParticleType_happyVillager: + particle = std::shared_ptr( + new SuspendedTownParticle(lev, x, y, z, xa, ya, za)); + particle->setMiscTex(2 + 16 * 5); + particle->setColor(1, 1, 1); + break; + case eParticleType_dragonbreath: + particle = std::shared_ptr( + new DragonBreathParticle(lev, x, y, z, xa, ya, za)); + break; + default: + if ((eParticleType >= eParticleType_iconcrack_base) && + (eParticleType <= eParticleType_iconcrack_last)) { + int id = PARTICLE_CRACK_ID(eParticleType), + data = PARTICLE_CRACK_DATA(eParticleType); + particle = std::shared_ptr(new BreakingItemParticle( + lev, x, y, z, xa, ya, za, Item::items[id], textures, data)); + } else if ((eParticleType >= eParticleType_tilecrack_base) && + (eParticleType <= eParticleType_tilecrack_last)) { + int id = PARTICLE_CRACK_ID(eParticleType), + data = PARTICLE_CRACK_DATA(eParticleType); + particle = std::dynamic_pointer_cast( + std::shared_ptr( + new TerrainParticle(lev, x, y, z, xa, ya, za, + Tile::tiles[id], 0, data, textures)) + ->init(data)); + } + } - if (particle != NULL) - { - mc->particleEngine->add(particle); - } + if (particle != NULL) { + mc->particleEngine->add(particle); + } - return particle; + return particle; } -void LevelRenderer::entityAdded(std::shared_ptr entity) -{ - entity->prepareCustomTextures(); - // 4J - these empty string comparisons used to check for NULL references, but we don't have string pointers (currently) in entities, - // hopefully this should be equivalent - /* 4J - removed temp */ - //if (entity->customTextureUrl != L"") textures->addHttpTexture(entity->customTextureUrl, new MobSkinTextureProcessor()); - //if (entity->customTextureUrl2 != L"") textures->addHttpTexture(entity->customTextureUrl2, new MobSkinTextureProcessor()); - - // 4J-PB - adding these from global title storage - if (entity->customTextureUrl != L"") - { - textures->addMemTexture(entity->customTextureUrl, new MobSkinMemTextureProcessor()); - } - if (entity->customTextureUrl2 != L"") - { - textures->addMemTexture(entity->customTextureUrl2, new MobSkinMemTextureProcessor()); - } - - // if (entity->customTextureUrl2 != L"") textures->addHttpTexture(entity->customTextureUrl2, new MobSkinTextureProcessor()); +void LevelRenderer::entityAdded(std::shared_ptr entity) { + entity->prepareCustomTextures(); + // 4J - these empty string comparisons used to check for NULL references, + // but we don't have string pointers (currently) in entities, hopefully this + // should be equivalent + /* 4J - removed temp */ + // if (entity->customTextureUrl != L"") + // textures->addHttpTexture(entity->customTextureUrl, new + // MobSkinTextureProcessor()); if (entity->customTextureUrl2 != L"") + // textures->addHttpTexture(entity->customTextureUrl2, new + // MobSkinTextureProcessor()); + // 4J-PB - adding these from global title storage + if (entity->customTextureUrl != L"") { + textures->addMemTexture(entity->customTextureUrl, + new MobSkinMemTextureProcessor()); + } + if (entity->customTextureUrl2 != L"") { + textures->addMemTexture(entity->customTextureUrl2, + new MobSkinMemTextureProcessor()); + } + // if (entity->customTextureUrl2 != L"") + // textures->addHttpTexture(entity->customTextureUrl2, new + // MobSkinTextureProcessor()); } -void LevelRenderer::entityRemoved(std::shared_ptr entity) -{ - /* 4J - removed temp - if (entity->customTextureUrl != L"") textures->removeHttpTexture(entity->customTextureUrl); - if (entity->customTextureUrl2 != L"") textures->removeHttpTexture(entity->customTextureUrl2); - */ - if (entity->customTextureUrl != L"") - { - textures->removeMemTexture(entity->customTextureUrl); - } - if (entity->customTextureUrl2 != L"") - { - textures->removeMemTexture(entity->customTextureUrl2); - } +void LevelRenderer::entityRemoved(std::shared_ptr entity) { + /* 4J - removed temp + if (entity->customTextureUrl != L"") + textures->removeHttpTexture(entity->customTextureUrl); if + (entity->customTextureUrl2 != L"") + textures->removeHttpTexture(entity->customTextureUrl2); + */ + if (entity->customTextureUrl != L"") { + textures->removeMemTexture(entity->customTextureUrl); + } + if (entity->customTextureUrl2 != L"") { + textures->removeMemTexture(entity->customTextureUrl2); + } } -void LevelRenderer::skyColorChanged() -{ - // 4J - no longer used +void LevelRenderer::skyColorChanged() { + // 4J - no longer used #if 0 EnterCriticalSection(&m_csDirtyChunks); for( int i = 0; i < getGlobalChunkCountForOverworld(); i++ ) @@ -2948,718 +3256,743 @@ void LevelRenderer::skyColorChanged() #endif } -void LevelRenderer::clear() -{ - MemoryTracker::releaseLists(chunkLists); +void LevelRenderer::clear() { MemoryTracker::releaseLists(chunkLists); } + +void LevelRenderer::levelEvent(std::shared_ptr source, int type, int x, + int y, int z, int data) { + int playerIndex = mc->player->GetXboxPad(); // 4J added + Random* random = level[playerIndex]->random; + switch (type) { + // case LevelEvent::SOUND_WITHER_BOSS_SPAWN: + case LevelEvent::SOUND_DRAGON_DEATH: + if (mc->cameraTargetPlayer != NULL) { + // play the sound at an offset from the player + double dx = x - mc->cameraTargetPlayer->x; + double dy = y - mc->cameraTargetPlayer->y; + double dz = z - mc->cameraTargetPlayer->z; + + double len = sqrt(dx * dx + dy * dy + dz * dz); + double sx = mc->cameraTargetPlayer->x; + double sy = mc->cameraTargetPlayer->y; + double sz = mc->cameraTargetPlayer->z; + + if (len > 0) { + sx += (dx / len) * 2; + sy += (dy / len) * 2; + sz += (dz / len) * 2; + } + + level[playerIndex]->playLocalSound( + sx, sy, sz, eSoundType_MOB_ENDERDRAGON_END, 5.0f, 1.0f); + } + break; + case LevelEvent::SOUND_CLICK_FAIL: + // level[playerIndex]->playSound(x, y, z, + // L"random.click", 1.0f, 1.2f); + level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, + 1.0f, 1.2f); + break; + case LevelEvent::SOUND_CLICK: + level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, + 1.0f, 1.0f); + break; + case LevelEvent::SOUND_LAUNCH: + level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_BOW, + 1.0f, 1.2f); + break; + case LevelEvent::PARTICLES_SHOOT: { + int xd = (data % 3) - 1; + int zd = (data / 3 % 3) - 1; + double xp = x + xd * 0.6 + 0.5; + double yp = y + 0.5; + double zp = z + zd * 0.6 + 0.5; + for (int i = 0; i < 10; i++) { + double pow = random->nextDouble() * 0.2 + 0.01; + double xs = + xp + xd * 0.01 + (random->nextDouble() - 0.5) * zd * 0.5; + double ys = yp + (random->nextDouble() - 0.5) * 0.5; + double zs = + zp + zd * 0.01 + (random->nextDouble() - 0.5) * xd * 0.5; + double xsa = xd * pow + random->nextGaussian() * 0.01; + double ysa = -0.03 + random->nextGaussian() * 0.01; + double zsa = zd * pow + random->nextGaussian() * 0.01; + addParticle(eParticleType_smoke, xs, ys, zs, xsa, ysa, zsa); + } + break; + } + case LevelEvent::PARTICLES_EYE_OF_ENDER_DEATH: { + double xp = x + 0.5; + double yp = y; + double zp = z + 0.5; + + ePARTICLE_TYPE particle = + PARTICLE_ICONCRACK(Item::eyeOfEnder->id, 0); + for (int i = 0; i < 8; i++) { + addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, + random->nextDouble() * 0.2, + random->nextGaussian() * .15); + } + for (double a = 0; a < PI * 2.0; a += PI * 0.05) { + addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, + zp + sin(a) * 5, cos(a) * -5, 0, sin(a) * -5); + addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, + zp + sin(a) * 5, cos(a) * -7, 0, sin(a) * -7); + } + + } break; + case LevelEvent::PARTICLES_POTION_SPLASH: { + double xp = x; + double yp = y; + double zp = z; + + ePARTICLE_TYPE particle = PARTICLE_ICONCRACK(Item::potion->id, 0); + for (int i = 0; i < 8; i++) { + addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, + random->nextDouble() * 0.2, + random->nextGaussian() * 0.15); + } + + int colorValue = Item::potion->getColor(data); + + float red = (float)((colorValue >> 16) & 0xff) / 255.0f; + float green = (float)((colorValue >> 8) & 0xff) / 255.0f; + float blue = (float)((colorValue >> 0) & 0xff) / 255.0f; + + ePARTICLE_TYPE particleName = eParticleType_spell; + if (Item::potion->hasInstantenousEffects(data)) { + particleName = eParticleType_instantSpell; + } + + for (int i = 0; i < 100; i++) { + double dist = random->nextDouble() * ThrownPotion::SPLASH_RANGE; + double angle = random->nextDouble() * PI * 2; + double xs = cos(angle) * dist; + double ys = 0.01 + random->nextDouble() * 0.5; + double zs = sin(angle) * dist; + + std::shared_ptr spellParticle = + addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, + zp + zs * 0.1, xs, ys, zs); + if (spellParticle != NULL) { + float randBrightness = 0.75f + random->nextFloat() * 0.25f; + spellParticle->setColor(red * randBrightness, + green * randBrightness, + blue * randBrightness); + spellParticle->setPower((float)dist); + } + } + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_GLASS, 1, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } break; + case LevelEvent::ENDERDRAGON_FIREBALL_SPLASH: { + double xp = x; + double yp = y; + double zp = z; + + ePARTICLE_TYPE particleName = eParticleType_dragonbreath; + + for (int i = 0; i < 200; i++) { + double dist = + random->nextDouble() * DragonFireball::SPLASH_RANGE; + double angle = random->nextDouble() * PI * 2; + double xs = cos(angle) * dist; + double ys = 0.01 + random->nextDouble() * 0.5; + double zs = sin(angle) * dist; + + std::shared_ptr acidParticle = + addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, + zp + zs * 0.1, xs, ys, zs); + if (acidParticle != NULL) { + float randBrightness = 0.75f + random->nextFloat() * 0.25f; + acidParticle->setPower((float)dist); + } + } + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_EXPLODE, 1, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } break; + case LevelEvent::PARTICLES_DESTROY_BLOCK: { + int t = data & Tile::TILE_NUM_MASK; + if (t > 0) { + Tile* oldTile = Tile::tiles[t]; + mc->soundEngine->play(oldTile->soundType->getBreakSound(), + x + 0.5f, y + 0.5f, z + 0.5f, + (oldTile->soundType->getVolume() + 1) / 2, + oldTile->soundType->getPitch() * 0.8f); + } + + mc->particleEngine->destroy(x, y, z, data & Tile::TILE_NUM_MASK, + (data >> Tile::TILE_NUM_SHIFT) & 0xff); + break; + } + case LevelEvent::PARTICLES_MOBTILE_SPAWN: { + for (int i = 0; i < 20; i++) { + double xP = x + 0.5 + + (level[playerIndex]->random->nextFloat() - 0.5) * 2; + double yP = y + 0.5 + + (level[playerIndex]->random->nextFloat() - 0.5) * 2; + double zP = z + 0.5 + + (level[playerIndex]->random->nextFloat() - 0.5) * 2; + + level[playerIndex]->addParticle(eParticleType_smoke, xP, yP, zP, + 0, 0, 0); + level[playerIndex]->addParticle(eParticleType_flame, xP, yP, zP, + 0, 0, 0); + } + break; + } + case LevelEvent::SOUND_OPEN_DOOR: + if (Math::random() < 0.5) { + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_OPEN, + 1.0f, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } else { + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_CLOSE, + 1.0f, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + } + break; + case LevelEvent::SOUND_FIZZ: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, + 2.6f + (random->nextFloat() - random->nextFloat()) * 0.8f); + break; + case LevelEvent::SOUND_ANVIL_BROKEN: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_BREAK, + 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + break; + case LevelEvent::SOUND_ANVIL_USED: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_USE, 1.0f, + level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + break; + case LevelEvent::SOUND_ANVIL_LAND: + level[playerIndex]->playLocalSound( + x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_LAND, + 0.3f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); + break; + case LevelEvent::SOUND_PLAY_RECORDING: { + RecordingItem* rci = + dynamic_cast(Item::items[data]); + if (rci != NULL) { + level[playerIndex]->playStreamingMusic(rci->recording, x, y, z); + } else { + // 4J-PB - only play streaming music if there isn't already some + // playing - the CD playing may have finished, and game music + // started playing already + if (!mc->soundEngine->GetIsPlayingStreamingGameMusic()) { + level[playerIndex]->playStreamingMusic( + L"", x, y, z); // 4J - used to pass NULL, but using + // empty string here now instead + } + } + mc->localplayers[playerIndex]->updateRichPresence(); + } break; + // 4J - new level event sounds brought forward from 1.2.3 + case LevelEvent::SOUND_GHAST_WARNING: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_CHARGE, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, + 80.0f); + break; + case LevelEvent::SOUND_GHAST_FIREBALL: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_FIREBALL, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, + 80.0f); + break; + case LevelEvent::SOUND_ZOMBIE_WOODEN_DOOR: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + break; + case LevelEvent::SOUND_ZOMBIE_DOOR_CRASH: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD_BREAK, + 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + break; + case LevelEvent::SOUND_ZOMBIE_IRON_DOOR: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_METAL, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); + break; + case LevelEvent::SOUND_ZOMBIE_INFECTED: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_INFECT, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + + 1.0f); //, false); + break; + case LevelEvent::SOUND_ZOMBIE_CONVERTED: + level[playerIndex]->playLocalSound( + x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_UNFECT, 2.0f, + (random->nextFloat() - random->nextFloat()) * 0.2f + + 1.0f); //, false); + break; + // 4J Added TU9 to fix #77475 - TU9: Content: Art: Dragon egg + // teleport particle effect isn't present. + case LevelEvent::END_EGG_TELEPORT: + // 4J Added to show the paricles when the End egg teleports after + // being attacked + EggTile::generateTeleportParticles(level[playerIndex], x, y, z, + data); + break; + } } -void LevelRenderer::levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data) -{ - int playerIndex = mc->player->GetXboxPad(); // 4J added - Random *random = level[playerIndex]->random; - switch (type) - { - //case LevelEvent::SOUND_WITHER_BOSS_SPAWN: - case LevelEvent::SOUND_DRAGON_DEATH: - if (mc->cameraTargetPlayer != NULL) - { - // play the sound at an offset from the player - double dx = x - mc->cameraTargetPlayer->x; - double dy = y - mc->cameraTargetPlayer->y; - double dz = z - mc->cameraTargetPlayer->z; +void LevelRenderer::destroyTileProgress(int id, int x, int y, int z, + int progress) { + if (progress < 0 || progress >= 10) { + AUTO_VAR(it, destroyingBlocks.find(id)); + if (it != destroyingBlocks.end()) { + delete it->second; + destroyingBlocks.erase(it); + } + // destroyingBlocks.remove(id); + } else { + BlockDestructionProgress* entry = NULL; - double len = sqrt(dx * dx + dy * dy + dz * dz); - double sx = mc->cameraTargetPlayer->x; - double sy = mc->cameraTargetPlayer->y; - double sz = mc->cameraTargetPlayer->z; + AUTO_VAR(it, destroyingBlocks.find(id)); + if (it != destroyingBlocks.end()) entry = it->second; - if (len > 0) - { - sx += (dx / len) * 2; - sy += (dy / len) * 2; - sz += (dz / len) * 2; - } - - level[playerIndex]->playLocalSound(sx, sy, sz, eSoundType_MOB_ENDERDRAGON_END, 5.0f, 1.0f); - } - break; - case LevelEvent::SOUND_CLICK_FAIL: - //level[playerIndex]->playSound(x, y, z, L"random.click", 1.0f, 1.2f); - level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, 1.0f, 1.2f); - break; - case LevelEvent::SOUND_CLICK: - level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_CLICK, 1.0f, 1.0f); - break; - case LevelEvent::SOUND_LAUNCH: - level[playerIndex]->playLocalSound(x, y, z, eSoundType_RANDOM_BOW, 1.0f, 1.2f); - break; - case LevelEvent::PARTICLES_SHOOT: - { - int xd = (data % 3) - 1; - int zd = (data / 3 % 3) - 1; - double xp = x + xd * 0.6 + 0.5; - double yp = y + 0.5; - double zp = z + zd * 0.6 + 0.5; - for (int i = 0; i < 10; i++) - { - double pow = random->nextDouble() * 0.2 + 0.01; - double xs = xp + xd * 0.01 + (random->nextDouble() - 0.5) * zd * 0.5; - double ys = yp + (random->nextDouble() - 0.5) * 0.5; - double zs = zp + zd * 0.01 + (random->nextDouble() - 0.5) * xd * 0.5; - double xsa = xd * pow + random->nextGaussian() * 0.01; - double ysa = -0.03 + random->nextGaussian() * 0.01; - double zsa = zd * pow + random->nextGaussian() * 0.01; - addParticle(eParticleType_smoke, xs, ys, zs, xsa, ysa, zsa); - } - break; - } - case LevelEvent::PARTICLES_EYE_OF_ENDER_DEATH: - { - double xp = x + 0.5; - double yp = y; - double zp = z + 0.5; - - ePARTICLE_TYPE particle = PARTICLE_ICONCRACK(Item::eyeOfEnder->id,0); - for (int i = 0; i < 8; i++) - { - addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, random->nextDouble() * 0.2, random->nextGaussian() * .15); - } - for (double a = 0; a < PI * 2.0; a += PI * 0.05) - { - addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, zp + sin(a) * 5, cos(a) * -5, 0, sin(a) * -5); - addParticle(eParticleType_ender, xp + cos(a) * 5, yp - .4, zp + sin(a) * 5, cos(a) * -7, 0, sin(a) * -7); - } - - } - break; - case LevelEvent::PARTICLES_POTION_SPLASH: - { - double xp = x; - double yp = y; - double zp = z; - - ePARTICLE_TYPE particle = PARTICLE_ICONCRACK(Item::potion->id,0); - for (int i = 0; i < 8; i++) - { - addParticle(particle, xp, yp, zp, random->nextGaussian() * 0.15, random->nextDouble() * 0.2, random->nextGaussian() * 0.15); - } - - - int colorValue = Item::potion->getColor(data); - - float red = (float) ((colorValue >> 16) & 0xff) / 255.0f; - float green = (float) ((colorValue >> 8) & 0xff) / 255.0f; - float blue = (float) ((colorValue >> 0) & 0xff) / 255.0f; - - ePARTICLE_TYPE particleName = eParticleType_spell; - if (Item::potion->hasInstantenousEffects(data)) - { - particleName = eParticleType_instantSpell; - } - - for (int i = 0; i < 100; i++) - { - double dist = random->nextDouble() * ThrownPotion::SPLASH_RANGE; - double angle = random->nextDouble() * PI * 2; - double xs = cos(angle) * dist; - double ys = 0.01 + random->nextDouble() * 0.5; - double zs = sin(angle) * dist; - - std::shared_ptr spellParticle = addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, zp + zs * 0.1, xs, ys, zs); - if (spellParticle != NULL) - { - float randBrightness = 0.75f + random->nextFloat() * 0.25f; - spellParticle->setColor(red * randBrightness, green * randBrightness, blue * randBrightness); - spellParticle->setPower((float) dist); - } - } - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_GLASS, 1, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } - break; - case LevelEvent::ENDERDRAGON_FIREBALL_SPLASH: - { - double xp = x; - double yp = y; - double zp = z; - - ePARTICLE_TYPE particleName = eParticleType_dragonbreath; - - for (int i = 0; i < 200; i++) - { - double dist = random->nextDouble() * DragonFireball::SPLASH_RANGE; - double angle = random->nextDouble() * PI * 2; - double xs = cos(angle) * dist; - double ys = 0.01 + random->nextDouble() * 0.5; - double zs = sin(angle) * dist; - - std::shared_ptr acidParticle = addParticleInternal(particleName, xp + xs * 0.1, yp + 0.3, zp + zs * 0.1, xs, ys, zs); - if (acidParticle != NULL) - { - float randBrightness = 0.75f + random->nextFloat() * 0.25f; - acidParticle->setPower((float) dist); - } - } - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_EXPLODE, 1, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } - break; - case LevelEvent::PARTICLES_DESTROY_BLOCK: - { - int t = data & Tile::TILE_NUM_MASK; - if (t > 0) - { - Tile *oldTile = Tile::tiles[t]; - mc->soundEngine->play(oldTile->soundType->getBreakSound(), x + 0.5f, y + 0.5f, z + 0.5f, (oldTile->soundType->getVolume() + 1) / 2, oldTile->soundType->getPitch() * 0.8f); - } - - mc->particleEngine->destroy(x, y, z, data & Tile::TILE_NUM_MASK, (data >> Tile::TILE_NUM_SHIFT) & 0xff); - break; - } - case LevelEvent::PARTICLES_MOBTILE_SPAWN: - { - for (int i = 0; i < 20; i++) - { - - double xP = x + 0.5 + (level[playerIndex]->random->nextFloat() - 0.5) * 2; - double yP = y + 0.5 + (level[playerIndex]->random->nextFloat() - 0.5) * 2; - double zP = z + 0.5 + (level[playerIndex]->random->nextFloat() - 0.5) * 2; - - level[playerIndex]->addParticle(eParticleType_smoke, xP, yP, zP, 0, 0, 0); - level[playerIndex]->addParticle(eParticleType_flame, xP, yP, zP, 0, 0, 0); - } - break; - } - case LevelEvent::SOUND_OPEN_DOOR: - if (Math::random() < 0.5) - { - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_OPEN, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } else { - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_RANDOM_DOOR_CLOSE, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - } - break; - case LevelEvent::SOUND_FIZZ: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_FIZZ, 0.5f, 2.6f + (random->nextFloat() - random->nextFloat()) * 0.8f); - break; - case LevelEvent::SOUND_ANVIL_BROKEN: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_BREAK, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - break; - case LevelEvent::SOUND_ANVIL_USED: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_USE, 1.0f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - break; - case LevelEvent::SOUND_ANVIL_LAND: - level[playerIndex]->playLocalSound(x + 0.5f, y + 0.5f, z + 0.5f, eSoundType_RANDOM_ANVIL_LAND, 0.3f, level[playerIndex]->random->nextFloat() * 0.1f + 0.9f); - break; - case LevelEvent::SOUND_PLAY_RECORDING: - { - RecordingItem *rci = dynamic_cast(Item::items[data]); - if (rci != NULL) - { - level[playerIndex]->playStreamingMusic(rci->recording, x, y, z); - } - else - { - // 4J-PB - only play streaming music if there isn't already some playing - the CD playing may have finished, and game music started playing already - if(!mc->soundEngine->GetIsPlayingStreamingGameMusic()) - { - level[playerIndex]->playStreamingMusic(L"", x, y, z); // 4J - used to pass NULL, but using empty string here now instead - } - } - mc->localplayers[playerIndex]->updateRichPresence(); - } - break; - // 4J - new level event sounds brought forward from 1.2.3 - case LevelEvent::SOUND_GHAST_WARNING: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_CHARGE, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, 80.0f); - break; - case LevelEvent::SOUND_GHAST_FIREBALL: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_GHAST_FIREBALL, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f, 80.0f); - break; - case LevelEvent::SOUND_ZOMBIE_WOODEN_DOOR: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - break; - case LevelEvent::SOUND_ZOMBIE_DOOR_CRASH: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_WOOD_BREAK, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - break; - case LevelEvent::SOUND_ZOMBIE_IRON_DOOR: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_METAL, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); - break; - case LevelEvent::SOUND_ZOMBIE_INFECTED: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_INFECT, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f);//, false); - break; - case LevelEvent::SOUND_ZOMBIE_CONVERTED: - level[playerIndex]->playLocalSound(x + 0.5, y + 0.5, z + 0.5, eSoundType_MOB_ZOMBIE_UNFECT, 2.0f, (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f);//, false); - break; - // 4J Added TU9 to fix #77475 - TU9: Content: Art: Dragon egg teleport particle effect isn't present. - case LevelEvent::END_EGG_TELEPORT: - // 4J Added to show the paricles when the End egg teleports after being attacked - EggTile::generateTeleportParticles(level[playerIndex],x,y,z,data); - break; - } + if (entry == NULL || entry->getX() != x || entry->getY() != y || + entry->getZ() != z) { + entry = new BlockDestructionProgress(id, x, y, z); + destroyingBlocks.insert( + std::unordered_map::value_type( + id, entry)); + } + entry->setProgress(progress); + entry->updateTick(ticks); + } } -void LevelRenderer::destroyTileProgress(int id, int x, int y, int z, int progress) -{ - if (progress < 0 || progress >= 10) - { - AUTO_VAR(it, destroyingBlocks.find(id)); - if(it != destroyingBlocks.end()) - { - delete it->second; - destroyingBlocks.erase(it); - } - //destroyingBlocks.remove(id); - } - else - { - BlockDestructionProgress *entry = NULL; +void LevelRenderer::registerTextures(IconRegister* iconRegister) { + breakingTextures = new Icon*[10]; - AUTO_VAR(it, destroyingBlocks.find(id)); - if(it != destroyingBlocks.end()) entry = it->second; - - if (entry == NULL || entry->getX() != x || entry->getY() != y || entry->getZ() != z) - { - entry = new BlockDestructionProgress(id, x, y, z); - destroyingBlocks.insert( std::unordered_map::value_type(id, entry) ); - } - - entry->setProgress(progress); - entry->updateTick(ticks); - } -} - -void LevelRenderer::registerTextures(IconRegister *iconRegister) -{ - breakingTextures = new Icon*[10]; - - for (int i = 0; i < 10; i++) - { - breakingTextures[i] = iconRegister->registerIcon(L"destroy_" + _toString(i) ); - } + for (int i = 0; i < 10; i++) { + breakingTextures[i] = + iconRegister->registerIcon(L"destroy_" + _toString(i)); + } } // Gets a dimension index (0, 1, or 2) from an id ( 0, -1, 1) -int LevelRenderer::getDimensionIndexFromId(int id) -{ - return ( 3 - id ) % 3; +int LevelRenderer::getDimensionIndexFromId(int id) { return (3 - id) % 3; } + +// 4J - added for new render list handling. Render lists used to be allocated +// per chunk, but these are now allocated per fixed chunk position in our (now +// finite) maps. +int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, Level* level) { + return getGlobalIndexForChunk(x, y, z, level->dimension->id); } -// 4J - added for new render list handling. Render lists used to be allocated per chunk, but these are now allocated per fixed chunk position -// in our (now finite) maps. -int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, Level *level) -{ - return getGlobalIndexForChunk(x,y,z,level->dimension->id); +int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, + int dimensionId) { + int dimIdx = getDimensionIndexFromId(dimensionId); + // int xx = ( x / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); + // int yy = y / CHUNK_SIZE; + // int zz = ( z / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); + int xx = (Mth::intFloorDiv(x, CHUNK_XZSIZE)) + + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); + int yy = Mth::intFloorDiv(y, CHUNK_SIZE); + int zz = (Mth::intFloorDiv(z, CHUNK_XZSIZE)) + + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); + + if ((xx < 0) || (xx >= MAX_LEVEL_RENDER_SIZE[dimIdx])) return -1; + if ((zz < 0) || (zz >= MAX_LEVEL_RENDER_SIZE[dimIdx])) return -1; + if ((yy < 0) || (yy >= CHUNK_Y_COUNT)) return -1; + + int dimOffset = DIMENSION_OFFSETS[dimIdx]; + + int offset = dimOffset; // Offset caused by current dimension + offset += (zz * MAX_LEVEL_RENDER_SIZE[dimIdx] + xx) * + CHUNK_Y_COUNT; // Offset by x/z pos + offset += yy; // Offset by y pos + + return offset; } -int LevelRenderer::getGlobalIndexForChunk(int x, int y, int z, int dimensionId) -{ - int dimIdx = getDimensionIndexFromId(dimensionId); - //int xx = ( x / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); - //int yy = y / CHUNK_SIZE; - //int zz = ( z / CHUNK_XZSIZE ) + ( MAX_LEVEL_RENDER_SIZE[dimIdx] / 2 ); - int xx = ( Mth::intFloorDiv(x, CHUNK_XZSIZE)) + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); - int yy = Mth::intFloorDiv(y, CHUNK_SIZE); - int zz = ( Mth::intFloorDiv(z, CHUNK_XZSIZE)) + (MAX_LEVEL_RENDER_SIZE[dimIdx] / 2); - - if( ( xx < 0 ) || ( xx >= MAX_LEVEL_RENDER_SIZE[dimIdx] ) ) return -1; - if( ( zz < 0 ) || ( zz >= MAX_LEVEL_RENDER_SIZE[dimIdx] ) ) return -1; - if( ( yy < 0 ) || ( yy >= CHUNK_Y_COUNT ) ) return -1; - - int dimOffset = DIMENSION_OFFSETS[dimIdx]; - - int offset = dimOffset; // Offset caused by current dimension - offset += ( zz * MAX_LEVEL_RENDER_SIZE[dimIdx] + xx ) * CHUNK_Y_COUNT; // Offset by x/z pos - offset += yy; // Offset by y pos - - return offset; +bool LevelRenderer::isGlobalIndexInSameDimension(int idx, Level* level) { + int dim = getDimensionIndexFromId(level->dimension->id); + int idxDim = 0; + if (idx >= DIMENSION_OFFSETS[2]) + idxDim = 2; + else if (idx >= DIMENSION_OFFSETS[1]) + idxDim = 1; + return (dim == idxDim); } -bool LevelRenderer::isGlobalIndexInSameDimension( int idx, Level *level) -{ - int dim = getDimensionIndexFromId(level->dimension->id); - int idxDim = 0; - if( idx >= DIMENSION_OFFSETS[2] ) idxDim = 2; - else if ( idx >= DIMENSION_OFFSETS[1] ) idxDim = 1; - return (dim == idxDim); +int LevelRenderer::getGlobalChunkCount() { + return (MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * + CHUNK_Y_COUNT) + + (MAX_LEVEL_RENDER_SIZE[1] * MAX_LEVEL_RENDER_SIZE[1] * + CHUNK_Y_COUNT) + + (MAX_LEVEL_RENDER_SIZE[2] * MAX_LEVEL_RENDER_SIZE[2] * + CHUNK_Y_COUNT); } -int LevelRenderer::getGlobalChunkCount() -{ - return ( MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * CHUNK_Y_COUNT ) + - ( MAX_LEVEL_RENDER_SIZE[1] * MAX_LEVEL_RENDER_SIZE[1] * CHUNK_Y_COUNT ) + - ( MAX_LEVEL_RENDER_SIZE[2] * MAX_LEVEL_RENDER_SIZE[2] * CHUNK_Y_COUNT ); +int LevelRenderer::getGlobalChunkCountForOverworld() { + return (MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * + CHUNK_Y_COUNT); } -int LevelRenderer::getGlobalChunkCountForOverworld() -{ - return ( MAX_LEVEL_RENDER_SIZE[0] * MAX_LEVEL_RENDER_SIZE[0] * CHUNK_Y_COUNT ); +unsigned char LevelRenderer::getGlobalChunkFlags(int x, int y, int z, + Level* level) { + int index = getGlobalIndexForChunk(x, y, z, level); + if (index == -1) { + return 0; + } else { + return globalChunkFlags[index]; + } } -unsigned char LevelRenderer::getGlobalChunkFlags(int x, int y, int z, Level *level) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index == -1 ) - { - return 0; - } - else - { - return globalChunkFlags[ index ]; - } -} - -void LevelRenderer::setGlobalChunkFlags(int x, int y, int z, Level *level, unsigned char flags) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { +void LevelRenderer::setGlobalChunkFlags(int x, int y, int z, Level* level, + unsigned char flags) { + int index = getGlobalIndexForChunk(x, y, z, level); + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] = flags; + globalChunkFlags[index] = flags; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -void LevelRenderer::setGlobalChunkFlag(int index, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; +void LevelRenderer::setGlobalChunkFlag(int index, unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; - if( index != -1 ) - { + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] |= sflag; + globalChunkFlags[index] |= sflag; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -void LevelRenderer::setGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { +void LevelRenderer::setGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; + int index = getGlobalIndexForChunk(x, y, z, level); + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] |= sflag; + globalChunkFlags[index] |= sflag; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -void LevelRenderer::clearGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { +void LevelRenderer::clearGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; + int index = getGlobalIndexForChunk(x, y, z, level); + if (index != -1) { #ifdef _LARGE_WORLDS - EnterCriticalSection(&m_csChunkFlags); + EnterCriticalSection(&m_csChunkFlags); #endif - globalChunkFlags[ index ] &= ~sflag; + globalChunkFlags[index] &= ~sflag; #ifdef _LARGE_WORLDS - LeaveCriticalSection(&m_csChunkFlags); + LeaveCriticalSection(&m_csChunkFlags); #endif - } + } } -bool LevelRenderer::getGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift) -{ - unsigned char sflag = flag << shift; - int index = getGlobalIndexForChunk(x, y, z, level); - if( index == -1 ) - { - return false; - } - else - { - return ( globalChunkFlags[ index ] & sflag ) == sflag; - } +bool LevelRenderer::getGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, + unsigned char shift) { + unsigned char sflag = flag << shift; + int index = getGlobalIndexForChunk(x, y, z, level); + if (index == -1) { + return false; + } else { + return (globalChunkFlags[index] & sflag) == sflag; + } } -unsigned char LevelRenderer::incGlobalChunkRefCount(int x, int y, int z, Level *level) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { - unsigned char flags = globalChunkFlags[ index ]; - unsigned char refCount = (flags >> CHUNK_FLAG_REF_SHIFT ) & CHUNK_FLAG_REF_MASK; - refCount++; - flags &= ~(CHUNK_FLAG_REF_MASK<> CHUNK_FLAG_REF_SHIFT) & CHUNK_FLAG_REF_MASK; + refCount++; + flags &= ~(CHUNK_FLAG_REF_MASK << CHUNK_FLAG_REF_SHIFT); + flags |= refCount << CHUNK_FLAG_REF_SHIFT; + globalChunkFlags[index] = flags; + return refCount; + } else { + return 0; + } } -unsigned char LevelRenderer::decGlobalChunkRefCount(int x, int y, int z, Level *level) -{ - int index = getGlobalIndexForChunk(x, y, z, level); - if( index != -1 ) - { - unsigned char flags = globalChunkFlags[ index ]; - unsigned char refCount = (flags >> CHUNK_FLAG_REF_SHIFT ) & CHUNK_FLAG_REF_MASK; - refCount--; - flags &= ~(CHUNK_FLAG_REF_MASK<> CHUNK_FLAG_REF_SHIFT) & CHUNK_FLAG_REF_MASK; + refCount--; + flags &= ~(CHUNK_FLAG_REF_MASK << CHUNK_FLAG_REF_SHIFT); + flags |= refCount << CHUNK_FLAG_REF_SHIFT; + globalChunkFlags[index] = flags; - return refCount; - } - else - { - return 0; - } + return refCount; + } else { + return 0; + } } // 4J added -void LevelRenderer::fullyFlagRenderableTileEntitiesToBeRemoved() -{ - EnterCriticalSection(&m_csRenderableTileEntities); - AUTO_VAR(itChunkEnd, renderableTileEntities.end()); - for (AUTO_VAR(it, renderableTileEntities.begin()); it != itChunkEnd; it++) - { - AUTO_VAR(itTEEnd, it->second.end()); - for( AUTO_VAR(it2, it->second.begin()); it2 != itTEEnd; it2++ ) - { - (*it2)->upgradeRenderRemoveStage(); - } - } - LeaveCriticalSection(&m_csRenderableTileEntities); +void LevelRenderer::fullyFlagRenderableTileEntitiesToBeRemoved() { + EnterCriticalSection(&m_csRenderableTileEntities); + AUTO_VAR(itChunkEnd, renderableTileEntities.end()); + for (AUTO_VAR(it, renderableTileEntities.begin()); it != itChunkEnd; it++) { + AUTO_VAR(itTEEnd, it->second.end()); + for (AUTO_VAR(it2, it->second.begin()); it2 != itTEEnd; it2++) { + (*it2)->upgradeRenderRemoveStage(); + } + } + LeaveCriticalSection(&m_csRenderableTileEntities); } -LevelRenderer::DestroyedTileManager::RecentTile::RecentTile(int x, int y, int z, Level *level) : x(x), y(y), z(z), level(level) -{ - timeout_ticks = 20; - rebuilt = false; +LevelRenderer::DestroyedTileManager::RecentTile::RecentTile(int x, int y, int z, + Level* level) + : x(x), y(y), z(z), level(level) { + timeout_ticks = 20; + rebuilt = false; } -LevelRenderer::DestroyedTileManager::RecentTile::~RecentTile() -{ - for( AUTO_VAR(it, boxes.begin()); it!= boxes.end(); it++ ) - { - delete *it; - } +LevelRenderer::DestroyedTileManager::RecentTile::~RecentTile() { + for (AUTO_VAR(it, boxes.begin()); it != boxes.end(); it++) { + delete *it; + } } -LevelRenderer::DestroyedTileManager::DestroyedTileManager() -{ - InitializeCriticalSection(&m_csDestroyedTiles); +LevelRenderer::DestroyedTileManager::DestroyedTileManager() { + InitializeCriticalSection(&m_csDestroyedTiles); } -LevelRenderer::DestroyedTileManager::~DestroyedTileManager() -{ - DeleteCriticalSection(&m_csDestroyedTiles); - for( unsigned int i = 0; i < m_destroyedTiles.size(); i++ ) - { - delete m_destroyedTiles[i]; - } +LevelRenderer::DestroyedTileManager::~DestroyedTileManager() { + DeleteCriticalSection(&m_csDestroyedTiles); + for (unsigned int i = 0; i < m_destroyedTiles.size(); i++) { + delete m_destroyedTiles[i]; + } } +// For game to let this manager know that a tile is about to be destroyed (must +// be called before it actually is) +void LevelRenderer::DestroyedTileManager::destroyingTileAt(Level* level, int x, + int y, int z) { + EnterCriticalSection(&m_csDestroyedTiles); -// For game to let this manager know that a tile is about to be destroyed (must be called before it actually is) -void LevelRenderer::DestroyedTileManager::destroyingTileAt( Level *level, int x, int y, int z ) -{ - EnterCriticalSection(&m_csDestroyedTiles); + // Store a list of AABBs that the tile to be destroyed would have made, + // before we go and destroy it. This is made slightly more complicated as + // the addAABBs method for tiles adds temporary AABBs and we need permanent + // ones, so make a temporary list and then copy over - // Store a list of AABBs that the tile to be destroyed would have made, before we go and destroy it. This - // is made slightly more complicated as the addAABBs method for tiles adds temporary AABBs and we need permanent - // ones, so make a temporary list and then copy over + RecentTile* recentTile = new RecentTile(x, y, z, level); + AABB* box = AABB::newTemp((float)x, (float)y, (float)z, (float)(x + 1), + (float)(y + 1), (float)(z + 1)); + Tile* tile = Tile::tiles[level->getTile(x, y, z)]; - RecentTile *recentTile = new RecentTile(x, y, z, level); - AABB *box = AABB::newTemp((float)x, (float)y, (float)z, (float)(x+1), (float)(y+1), (float)(z+1)); - Tile *tile = Tile::tiles[level->getTile(x, y, z)]; + if (tile != NULL) { + tile->addAABBs(level, x, y, z, box, &recentTile->boxes, nullptr); + } - if (tile != NULL) - { - tile->addAABBs(level, x, y, z, box, &recentTile->boxes, nullptr); - } + // Make these temporary AABBs into permanently allocated AABBs + for (unsigned int i = 0; i < recentTile->boxes.size(); i++) { + recentTile->boxes[i] = AABB::newPermanent( + recentTile->boxes[i]->x0, recentTile->boxes[i]->y0, + recentTile->boxes[i]->z0, recentTile->boxes[i]->x1, + recentTile->boxes[i]->y1, recentTile->boxes[i]->z1); + } - // Make these temporary AABBs into permanently allocated AABBs - for( unsigned int i = 0; i < recentTile->boxes.size(); i++ ) - { - recentTile->boxes[i] = AABB::newPermanent(recentTile->boxes[i]->x0, - recentTile->boxes[i]->y0, - recentTile->boxes[i]->z0, - recentTile->boxes[i]->x1, - recentTile->boxes[i]->y1, - recentTile->boxes[i]->z1); - } + m_destroyedTiles.push_back(recentTile); - m_destroyedTiles.push_back( recentTile ); - - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } -// For chunk rebuilding to inform the manager that a chunk (a 16x16x16 tile render chunk) has been updated -void LevelRenderer::DestroyedTileManager::updatedChunkAt(Level *level, int x, int y, int z, int veryNearCount) -{ - EnterCriticalSection(&m_csDestroyedTiles); +// For chunk rebuilding to inform the manager that a chunk (a 16x16x16 tile +// render chunk) has been updated +void LevelRenderer::DestroyedTileManager::updatedChunkAt(Level* level, int x, + int y, int z, + int veryNearCount) { + EnterCriticalSection(&m_csDestroyedTiles); - // There's 2 stages to this. This function is called when a renderer chunk has been rebuilt, but that chunk's render data might be grouped atomically with - // changes to other very near chunks. Therefore, we don't want to consider the render data to be fully updated until the chunk that it is in has been - // rebuilt, AND there aren't any very near things waiting to be rebuilt. + // There's 2 stages to this. This function is called when a renderer chunk + // has been rebuilt, but that chunk's render data might be grouped + // atomically with changes to other very near chunks. Therefore, we don't + // want to consider the render data to be fully updated until the chunk that + // it is in has been rebuilt, AND there aren't any very near things waiting + // to be rebuilt. - // First pass through - see if any tiles are within the chunk which is being rebuilt, and mark up by setting their rebuilt flag - bool printed = false; - for( unsigned int i = 0; i < m_destroyedTiles.size(); i++) - { - if( ( m_destroyedTiles[i]->level == level ) && - ( m_destroyedTiles[i]->x >= x ) && ( m_destroyedTiles[i]->x < ( x + 16 ) ) && - ( m_destroyedTiles[i]->y >= y ) && ( m_destroyedTiles[i]->y < ( y + 16 ) ) && - ( m_destroyedTiles[i]->z >= z ) && ( m_destroyedTiles[i]->z < ( z + 16 ) ) ) - { - printed = true; - m_destroyedTiles[i]->rebuilt = true; - } - } + // First pass through - see if any tiles are within the chunk which is being + // rebuilt, and mark up by setting their rebuilt flag + bool printed = false; + for (unsigned int i = 0; i < m_destroyedTiles.size(); i++) { + if ((m_destroyedTiles[i]->level == level) && + (m_destroyedTiles[i]->x >= x) && + (m_destroyedTiles[i]->x < (x + 16)) && + (m_destroyedTiles[i]->y >= y) && + (m_destroyedTiles[i]->y < (y + 16)) && + (m_destroyedTiles[i]->z >= z) && + (m_destroyedTiles[i]->z < (z + 16))) { + printed = true; + m_destroyedTiles[i]->rebuilt = true; + } + } - // Now go through every tile that has been marked up as already being rebuilt, and fully remove it once there aren't going to be any more - // very near chunks. This might not happen on the same call to this function that rebuilt the chunk with the tile in. - if( veryNearCount <= 1 ) - { - for( unsigned int i = 0; i < m_destroyedTiles.size(); ) - { - if( m_destroyedTiles[i]->rebuilt ) - { - printed = true; - delete m_destroyedTiles[i]; - m_destroyedTiles[i] = m_destroyedTiles[m_destroyedTiles.size() - 1]; - m_destroyedTiles.pop_back(); - } - else - { - i++; - } - } - } + // Now go through every tile that has been marked up as already being + // rebuilt, and fully remove it once there aren't going to be any more very + // near chunks. This might not happen on the same call to this function that + // rebuilt the chunk with the tile in. + if (veryNearCount <= 1) { + for (unsigned int i = 0; i < m_destroyedTiles.size();) { + if (m_destroyedTiles[i]->rebuilt) { + printed = true; + delete m_destroyedTiles[i]; + m_destroyedTiles[i] = + m_destroyedTiles[m_destroyedTiles.size() - 1]; + m_destroyedTiles.pop_back(); + } else { + i++; + } + } + } - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } -// For game to get any AABBs that the user should be colliding with as render data has not yet been updated -void LevelRenderer::DestroyedTileManager::addAABBs( Level *level, AABB *box, AABBList *boxes ) -{ - EnterCriticalSection(&m_csDestroyedTiles); +// For game to get any AABBs that the user should be colliding with as render +// data has not yet been updated +void LevelRenderer::DestroyedTileManager::addAABBs(Level* level, AABB* box, + AABBList* boxes) { + EnterCriticalSection(&m_csDestroyedTiles); - for( unsigned int i = 0; i < m_destroyedTiles.size(); i++ ) - { - if( m_destroyedTiles[i]->level == level ) - { - for( unsigned int j = 0; j < m_destroyedTiles[i]->boxes.size(); j++ ) - { - // If we find any AABBs intersecting the region we are interested in, add them to the output list, making a temp AABB copy so that we can destroy our own copy - // without worrying about the lifespan of the copy we've passed out - if( m_destroyedTiles[i]->boxes[j]->intersects( box ) ) - { - boxes->push_back(AABB::newTemp( m_destroyedTiles[i]->boxes[j]->x0, - m_destroyedTiles[i]->boxes[j]->y0, - m_destroyedTiles[i]->boxes[j]->z0, - m_destroyedTiles[i]->boxes[j]->x1, - m_destroyedTiles[i]->boxes[j]->y1, - m_destroyedTiles[i]->boxes[j]->z1 ) ); - } - } - } - } + for (unsigned int i = 0; i < m_destroyedTiles.size(); i++) { + if (m_destroyedTiles[i]->level == level) { + for (unsigned int j = 0; j < m_destroyedTiles[i]->boxes.size(); + j++) { + // If we find any AABBs intersecting the region we are + // interested in, add them to the output list, making a temp + // AABB copy so that we can destroy our own copy without + // worrying about the lifespan of the copy we've passed out + if (m_destroyedTiles[i]->boxes[j]->intersects(box)) { + boxes->push_back( + AABB::newTemp(m_destroyedTiles[i]->boxes[j]->x0, + m_destroyedTiles[i]->boxes[j]->y0, + m_destroyedTiles[i]->boxes[j]->z0, + m_destroyedTiles[i]->boxes[j]->x1, + m_destroyedTiles[i]->boxes[j]->y1, + m_destroyedTiles[i]->boxes[j]->z1)); + } + } + } + } - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } -void LevelRenderer::DestroyedTileManager::tick() -{ - EnterCriticalSection(&m_csDestroyedTiles); +void LevelRenderer::DestroyedTileManager::tick() { + EnterCriticalSection(&m_csDestroyedTiles); - // Remove any tiles that have timed out - for( unsigned int i = 0; i < m_destroyedTiles.size(); ) - { - if( --m_destroyedTiles[i]->timeout_ticks == 0 ) - { - delete m_destroyedTiles[i]; - m_destroyedTiles[i] = m_destroyedTiles[m_destroyedTiles.size() - 1]; - m_destroyedTiles.pop_back(); - } - else - { - i++; - } - } + // Remove any tiles that have timed out + for (unsigned int i = 0; i < m_destroyedTiles.size();) { + if (--m_destroyedTiles[i]->timeout_ticks == 0) { + delete m_destroyedTiles[i]; + m_destroyedTiles[i] = m_destroyedTiles[m_destroyedTiles.size() - 1]; + m_destroyedTiles.pop_back(); + } else { + i++; + } + } - LeaveCriticalSection(&m_csDestroyedTiles); + LeaveCriticalSection(&m_csDestroyedTiles); } #ifdef _LARGE_WORLDS -void LevelRenderer::staticCtor() -{ - s_rebuildCompleteEvents = new C4JThread::EventArray(MAX_CHUNK_REBUILD_THREADS); - char threadName[256]; - for(unsigned int i = 0; i < MAX_CHUNK_REBUILD_THREADS; ++i) - { - sprintf(threadName,"Rebuild Chunk Thread %d\n",i); - rebuildThreads[i] = new C4JThread(rebuildChunkThreadProc,(void *)(intptr_t)i,threadName); +void LevelRenderer::staticCtor() { + s_rebuildCompleteEvents = + new C4JThread::EventArray(MAX_CHUNK_REBUILD_THREADS); + char threadName[256]; + for (unsigned int i = 0; i < MAX_CHUNK_REBUILD_THREADS; ++i) { + sprintf(threadName, "Rebuild Chunk Thread %d\n", i); + rebuildThreads[i] = new C4JThread(rebuildChunkThreadProc, + (void*)(intptr_t)i, threadName); - s_activationEventA[i] = new C4JThread::Event(); + s_activationEventA[i] = new C4JThread::Event(); - // Threads 1,3 and 5 are generally idle so use them - if((i%3) == 0) rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_A); - else if((i%3) == 1) - { - rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_B); + // Threads 1,3 and 5 are generally idle so use them + if ((i % 3) == 0) + rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_A); + else if ((i % 3) == 1) { + rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_B); #ifdef __ORBIS__ - rebuildThreads[i]->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2. + rebuildThreads[i]->SetPriority( + THREAD_PRIORITY_BELOW_NORMAL); // On Orbis, this core is also + // used for Matching 2, and that + // priority of that seems to be + // always at default no matter + // what we set it to. Prioritise + // this below Matching 2. #endif - } - else if((i%3) == 2) rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_C); + } else if ((i % 3) == 2) + rebuildThreads[i]->SetProcessor(CPU_CORE_CHUNK_REBUILD_C); - //ResumeThread( saveThreads[j] ); - rebuildThreads[i]->Run(); - } + // ResumeThread( saveThreads[j] ); + rebuildThreads[i]->Run(); + } } -int LevelRenderer::rebuildChunkThreadProc(void *lpParam) -{ - Vec3::CreateNewThreadStorage(); - AABB::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - Tesselator::CreateNewThreadStorage(1024*1024); - RenderManager.InitialiseContext(); - Chunk::CreateNewThreadStorage(); - Tile::CreateNewThreadStorage(); - - int index = (int)(uintptr_t)lpParam; - - while(true) - - { - s_activationEventA[index]->WaitForSignal(INFINITE); +int LevelRenderer::rebuildChunkThreadProc(void* lpParam) { + Vec3::CreateNewThreadStorage(); + AABB::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Tesselator::CreateNewThreadStorage(1024 * 1024); + RenderManager.InitialiseContext(); + Chunk::CreateNewThreadStorage(); + Tile::CreateNewThreadStorage(); - //app.DebugPrintf("Rebuilding permaChunk %d\n", index + 1); - permaChunk[index + 1].rebuild(); + int index = (int)(uintptr_t)lpParam; - // Inform the producer thread that we are done with this chunk - s_rebuildCompleteEvents->Set(index); - } + while (true) - return 0; + { + s_activationEventA[index]->WaitForSignal(INFINITE); + + // app.DebugPrintf("Rebuilding permaChunk %d\n", index + 1); + permaChunk[index + 1].rebuild(); + + // Inform the producer thread that we are done with this chunk + s_rebuildCompleteEvents->Set(index); + } + + return 0; } #endif -// This is called when chunks require rebuilding, but they haven't been added individually to the dirtyChunksLockFreeStack. Once in this -// state, the rebuilding thread will keep assuming there are dirty chunks until it has had a full pass through the chunks and found no dirty ones -void LevelRenderer::nonStackDirtyChunksAdded() -{ - dirtyChunksLockFreeStack.Push((int *)1); +// This is called when chunks require rebuilding, but they haven't been added +// individually to the dirtyChunksLockFreeStack. Once in this state, the +// rebuilding thread will keep assuming there are dirty chunks until it has had +// a full pass through the chunks and found no dirty ones +void LevelRenderer::nonStackDirtyChunksAdded() { + dirtyChunksLockFreeStack.Push((int*)1); } diff --git a/Minecraft.Client/Rendering/LevelRenderer.h b/Minecraft.Client/Rendering/LevelRenderer.h index 65a82d4be..da75e8345 100644 --- a/Minecraft.Client/Rendering/LevelRenderer.h +++ b/Minecraft.Client/Rendering/LevelRenderer.h @@ -6,7 +6,7 @@ #include "../../Minecraft.World/Level/Level.h" #ifndef __linux__ #include -#endif // __linux__ +#endif // __linux__ #ifdef __PS3__ #include "../Platform/PS3/PS3Extras/C4JSpursJob.h" #endif @@ -25,255 +25,313 @@ class BlockDestructionProgress; class IconRegister; class Tesselator; - -// AP - this is a system that works out which chunks actually need to be grouped together via the deferral system when doing chunk::rebuild. Doing this will reduce the number -// of chunks built in a single group and reduce the chance of seeing through the landscape when digging near the edges/corners of a chunk. -// I've added another chunk flag to mark a chunk critical so it swipes a bit from the reference count value (goes to 3 bits to 2). This works on Vita because it doesn't have -// split screen reference counting. +// AP - this is a system that works out which chunks actually need to be grouped +// together via the deferral system when doing chunk::rebuild. Doing this will +// reduce the number of chunks built in a single group and reduce the chance of +// seeing through the landscape when digging near the edges/corners of a chunk. +// I've added another chunk flag to mark a chunk critical so it swipes a bit +// from the reference count value (goes to 3 bits to 2). This works on Vita +// because it doesn't have split screen reference counting. #ifdef __PSVITA__ #define _CRITICAL_CHUNKS #endif -class LevelRenderer : public LevelListener -{ - friend class Chunk; +class LevelRenderer : public LevelListener { + friend class Chunk; + public: - static const int CHUNK_XZSIZE = 16; + static const int CHUNK_XZSIZE = 16; #ifdef _LARGE_WORLDS - static const int CHUNK_SIZE = 16; + static const int CHUNK_SIZE = 16; #else - static const int CHUNK_SIZE = 16; + static const int CHUNK_SIZE = 16; #endif - static const int CHUNK_Y_COUNT = Level::maxBuildHeight / CHUNK_SIZE; + static const int CHUNK_Y_COUNT = Level::maxBuildHeight / CHUNK_SIZE; #if defined _XBOX_ONE - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 512 * 1024 * 1024; // 4J - added + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 512 * 1024 * 1024; // 4J - added #elif defined __ORBIS__ - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 448 * 1024 * 1024; // 4J - added - hard limit is 512 so giving a lot of headroom here for fragmentation (have seen 16MB lost to fragmentation in multiplayer crash dump before) + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 448 * 1024 * + 1024; // 4J - added - hard limit is 512 so giving a lot of headroom + // here for fragmentation (have seen 16MB lost to fragmentation + // in multiplayer crash dump before) #elif defined __PS3__ - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 110 * 1024 * 1024; // 4J - added + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 110 * 1024 * 1024; // 4J - added #else - static const int MAX_COMMANDBUFFER_ALLOCATIONS = 55 * 1024 * 1024; // 4J - added + static const int MAX_COMMANDBUFFER_ALLOCATIONS = + 55 * 1024 * 1024; // 4J - added #endif public: - LevelRenderer(Minecraft *mc, Textures *textures); -private: - void renderStars(); - void createCloudMesh(); // 4J added -public: - void setLevel(int playerIndex, MultiPlayerLevel *level); - void allChanged(); - void allChanged(int playerIndex); + LevelRenderer(Minecraft* mc, Textures* textures); - // 4J-PB added - void AddDLCSkinsToMemTextures(); -public: - void renderEntities(Vec3 *cam, Culler *culler, float a); - std::wstring gatherStats1(); - std::wstring gatherStats2(); private: - void resortChunks(int xc, int yc, int zc); + void renderStars(); + void createCloudMesh(); // 4J added public: - int render(std::shared_ptr player, int layer, double alpha, bool updateChunks); -private: - int renderChunks(int from, int to, int layer, double alpha); -public: - int activePlayers(); // 4J - added -public: - void renderSameAsLast(int layer, double alpha); - void tick(); - void renderSky(float alpha); - void renderHaloRing(float alpha); - void renderClouds(float alpha); - bool isInCloud(double x, double y, double z, float alpha); - void renderAdvancedClouds(float alpha); - bool updateDirtyChunks(); + void setLevel(int playerIndex, MultiPlayerLevel* level); + void allChanged(); + void allChanged(int playerIndex); + + // 4J-PB added + void AddDLCSkinsToMemTextures(); public: - void renderHit(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a); - void renderDestroyAnimation(Tesselator *t, std::shared_ptr player, float a); - void renderHitOutline(std::shared_ptr player, HitResult *h, int mode, std::shared_ptr inventoryItem, float a); - void render(AABB *b); - void setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level); // 4J - added level param - void tileChanged(int x, int y, int z); - void tileLightChanged(int x, int y, int z); - void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level); // 4J - added level param + void renderEntities(Vec3* cam, Culler* culler, float a); + std::wstring gatherStats1(); + std::wstring gatherStats2(); + +private: + void resortChunks(int xc, int yc, int zc); + +public: + int render(std::shared_ptr player, int layer, double alpha, + bool updateChunks); + +private: + int renderChunks(int from, int to, int layer, double alpha); + +public: + int activePlayers(); // 4J - added +public: + void renderSameAsLast(int layer, double alpha); + void tick(); + void renderSky(float alpha); + void renderHaloRing(float alpha); + void renderClouds(float alpha); + bool isInCloud(double x, double y, double z, float alpha); + void renderAdvancedClouds(float alpha); + bool updateDirtyChunks(); + +public: + void renderHit(std::shared_ptr player, HitResult* h, int mode, + std::shared_ptr inventoryItem, float a); + void renderDestroyAnimation(Tesselator* t, std::shared_ptr player, + float a); + void renderHitOutline(std::shared_ptr player, HitResult* h, + int mode, std::shared_ptr inventoryItem, + float a); + void render(AABB* b); + void setDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level); // 4J - added level param + void tileChanged(int x, int y, int z); + void tileLightChanged(int x, int y, int z); + void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, + Level* level); // 4J - added level param #ifdef __PS3__ - void cull_SPU(int playerIndex, Culler *culler, float a); - void waitForCull_SPU(); - C4JSpursJobQueue::Port* m_jobPort_CullSPU; - C4JSpursJobQueue::Port* m_jobPort_FindNearestChunk; - bool m_bSPUCullStarted[4]; -#endif // __PS3__ - void cull(Culler *culler, float a); - void playStreamingMusic(const std::wstring& name, int x, int y, int z); - void playSound(int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist=16.0f); - void playSound(std::shared_ptr entity,int iSound, double x, double y, double z, float volume, float pitch, float fSoundClipDist=16.0f); - void addParticle(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za); // 4J added - std::shared_ptr addParticleInternal(ePARTICLE_TYPE eParticleType, double x, double y, double z, double xa, double ya, double za); // 4J added - void entityAdded(std::shared_ptr entity); - void entityRemoved(std::shared_ptr entity); - void playerRemoved(std::shared_ptr entity) {} // 4J added - for when a player is removed from the level's player array, not just the entity storage - void skyColorChanged(); - void clear(); - void levelEvent(std::shared_ptr source, int type, int x, int y, int z, int data); - void destroyTileProgress(int id, int x, int y, int z, int progress); - void registerTextures(IconRegister *iconRegister); + void cull_SPU(int playerIndex, Culler* culler, float a); + void waitForCull_SPU(); + C4JSpursJobQueue::Port* m_jobPort_CullSPU; + C4JSpursJobQueue::Port* m_jobPort_FindNearestChunk; + bool m_bSPUCullStarted[4]; +#endif // __PS3__ + void cull(Culler* culler, float a); + void playStreamingMusic(const std::wstring& name, int x, int y, int z); + void playSound(int iSound, double x, double y, double z, float volume, + float pitch, float fSoundClipDist = 16.0f); + void playSound(std::shared_ptr entity, int iSound, double x, + double y, double z, float volume, float pitch, + float fSoundClipDist = 16.0f); + void addParticle(ePARTICLE_TYPE eParticleType, double x, double y, double z, + double xa, double ya, double za); // 4J added + std::shared_ptr addParticleInternal(ePARTICLE_TYPE eParticleType, + double x, double y, double z, + double xa, double ya, + double za); // 4J added + void entityAdded(std::shared_ptr entity); + void entityRemoved(std::shared_ptr entity); + void playerRemoved(std::shared_ptr entity) { + } // 4J added - for when a player is removed from the level's player array, + // not just the entity storage + void skyColorChanged(); + void clear(); + void levelEvent(std::shared_ptr source, int type, int x, int y, + int z, int data); + void destroyTileProgress(int id, int x, int y, int z, int progress); + void registerTextures(IconRegister* iconRegister); + + typedef std::unordered_map >, + IntKeyHash, IntKeyEq> + rteMap; - typedef std::unordered_map >, IntKeyHash, IntKeyEq> rteMap; private: + // debug + int m_freezeticks; // used to freeze the clouds - // debug - int m_freezeticks; // used to freeze the clouds + // 4J - this block of declarations was scattered round the code but have + // gathered everything into one place + rteMap renderableTileEntities; // 4J - changed - was + // std::vector, + // now hashed by chunk so we can find them + CRITICAL_SECTION m_csRenderableTileEntities; + MultiPlayerLevel* level[4]; // 4J - now one per player + Textures* textures; + // std::vector *sortedChunks[4]; // 4J - removed - not + // sorting our chunks anymore + ClipChunkArray chunks[4]; // 4J - now one per player + int lastPlayerCount[4]; // 4J - added + int xChunks, yChunks, zChunks; + int chunkLists; + Minecraft* mc; + TileRenderer* tileRenderer[4]; // 4J - now one per player + int ticks; + int starList, skyList, darkList, haloRingList; + int cloudList; // 4J added + int xMinChunk, yMinChunk, zMinChunk; + int xMaxChunk, yMaxChunk, zMaxChunk; + int lastViewDistance; + int noEntityRenderFrames; + int totalEntities; + int renderedEntities; + int culledEntities; + int chunkFixOffs; + std::vector _renderChunks; + int frame; + int repeatList; + double xOld[4]; // 4J - now one per player + double yOld[4]; // 4J - now one per player + double zOld[4]; // 4J - now one per player - // 4J - this block of declarations was scattered round the code but have gathered everything into one place - rteMap renderableTileEntities; // 4J - changed - was std::vector, now hashed by chunk so we can find them - CRITICAL_SECTION m_csRenderableTileEntities; - MultiPlayerLevel *level[4]; // 4J - now one per player - Textures *textures; - // std::vector *sortedChunks[4]; // 4J - removed - not sorting our chunks anymore - ClipChunkArray chunks[4]; // 4J - now one per player - int lastPlayerCount[4]; // 4J - added - int xChunks, yChunks, zChunks; - int chunkLists; - Minecraft *mc; - TileRenderer *tileRenderer[4]; // 4J - now one per player - int ticks; - int starList, skyList, darkList, haloRingList; - int cloudList; // 4J added - int xMinChunk, yMinChunk, zMinChunk; - int xMaxChunk, yMaxChunk, zMaxChunk; - int lastViewDistance; - int noEntityRenderFrames; - int totalEntities; - int renderedEntities; - int culledEntities; - int chunkFixOffs; - std::vector _renderChunks; - int frame; - int repeatList; - double xOld[4]; // 4J - now one per player - double yOld[4]; // 4J - now one per player - double zOld[4]; // 4J - now one per player + int totalChunks, offscreenChunks, occludedChunks, renderedChunks, + emptyChunks; + static const int RENDERLISTS_LENGTH = 4; // 4J - added + OffsettedRenderList renderLists[RENDERLISTS_LENGTH]; - int totalChunks, offscreenChunks, occludedChunks, renderedChunks, emptyChunks; - static const int RENDERLISTS_LENGTH = 4; // 4J - added - OffsettedRenderList renderLists[RENDERLISTS_LENGTH]; - - std::unordered_map destroyingBlocks; - Icon **breakingTextures; + std::unordered_map destroyingBlocks; + Icon** breakingTextures; public: - void fullyFlagRenderableTileEntitiesToBeRemoved(); // 4J added + void fullyFlagRenderableTileEntitiesToBeRemoved(); // 4J added - CRITICAL_SECTION m_csDirtyChunks; - bool m_nearDirtyChunk; + CRITICAL_SECTION m_csDirtyChunks; + bool m_nearDirtyChunk; + // 4J - Destroyed Tile Management - these things added so we can track tiles + // which have been recently destroyed, and provide temporary collision for + // them until the render data has been updated to reflect this change + class DestroyedTileManager { + private: + class RecentTile { + public: + int x; + int y; + int z; + Level* level; + AABBList boxes; + int timeout_ticks; + bool rebuilt; + RecentTile(int x, int y, int z, Level* level); + ~RecentTile(); + }; + CRITICAL_SECTION m_csDestroyedTiles; + std::vector m_destroyedTiles; - // 4J - Destroyed Tile Management - these things added so we can track tiles which have been recently destroyed, and - // provide temporary collision for them until the render data has been updated to reflect this change - class DestroyedTileManager - { - private: - class RecentTile - { - public: - int x; - int y; - int z; - Level *level; - AABBList boxes; - int timeout_ticks; - bool rebuilt; - RecentTile(int x, int y, int z, Level *level); - ~RecentTile(); - }; - CRITICAL_SECTION m_csDestroyedTiles; - std::vector m_destroyedTiles; - public: - void destroyingTileAt( Level *level, int x, int y, int z ); // For game to let this manager know that a tile is about to be destroyed (must be called before it actually is) - void updatedChunkAt( Level * level, int x, int y, int z, int veryNearCount ); // For chunk rebuilding to inform the manager that a chunk (a 16x16x16 tile render chunk) has been updated - void addAABBs( Level *level, AABB *box, AABBList *boxes ); // For game to get any AABBs that the user should be colliding with as render data has not yet been updated - void tick(); - DestroyedTileManager(); - ~DestroyedTileManager(); - }; - DestroyedTileManager *destroyedTileManager; + public: + void destroyingTileAt( + Level* level, int x, int y, + int z); // For game to let this manager know that a tile is about + // to be destroyed (must be called before it actually is) + void updatedChunkAt( + Level* level, int x, int y, int z, + int veryNearCount); // For chunk rebuilding to inform the manager + // that a chunk (a 16x16x16 tile render chunk) + // has been updated + void addAABBs(Level* level, AABB* box, + AABBList* boxes); // For game to get any AABBs that the + // user should be colliding with as + // render data has not yet been updated + void tick(); + DestroyedTileManager(); + ~DestroyedTileManager(); + }; + DestroyedTileManager* destroyedTileManager; - float destroyProgress; + float destroyProgress; - // 4J - added for new render list handling - // This defines the maximum size of renderable level, must be big enough to cope with actual size of level + view distance at each side - // so that we can render the "infinite" sea at the edges - static const int MAX_LEVEL_RENDER_SIZE[3]; - static const int DIMENSION_OFFSETS[3]; - // This is the TOTAL area of columns of chunks to be allocated for render round the players. So for one player, it would be a region of - // sqrt(PLAYER_RENDER_AREA) x sqrt(PLAYER_RENDER_AREA) + // 4J - added for new render list handling + // This defines the maximum size of renderable level, must be big enough to + // cope with actual size of level + view distance at each side so that we + // can render the "infinite" sea at the edges + static const int MAX_LEVEL_RENDER_SIZE[3]; + static const int DIMENSION_OFFSETS[3]; + // This is the TOTAL area of columns of chunks to be allocated for render + // round the players. So for one player, it would be a region of + // sqrt(PLAYER_RENDER_AREA) x sqrt(PLAYER_RENDER_AREA) #ifdef _LARGE_WORLDS - static const int PLAYER_VIEW_DISTANCE = 18; // Straight line distance from centre to extent of visible world - static const int PLAYER_RENDER_AREA = (PLAYER_VIEW_DISTANCE * PLAYER_VIEW_DISTANCE * 4); + static const int PLAYER_VIEW_DISTANCE = + 18; // Straight line distance from centre to extent of visible world + static const int PLAYER_RENDER_AREA = + (PLAYER_VIEW_DISTANCE * PLAYER_VIEW_DISTANCE * 4); #else - static const int PLAYER_RENDER_AREA = 400; + static const int PLAYER_RENDER_AREA = 400; #endif - static int getDimensionIndexFromId(int id); - static int getGlobalIndexForChunk(int x, int y, int z, Level *level); - static int getGlobalIndexForChunk(int x, int y, int z, int dimensionId); - static bool isGlobalIndexInSameDimension( int idx, Level *level); - static int getGlobalChunkCount(); - static int getGlobalChunkCountForOverworld(); + static int getDimensionIndexFromId(int id); + static int getGlobalIndexForChunk(int x, int y, int z, Level* level); + static int getGlobalIndexForChunk(int x, int y, int z, int dimensionId); + static bool isGlobalIndexInSameDimension(int idx, Level* level); + static int getGlobalChunkCount(); + static int getGlobalChunkCountForOverworld(); - // Get/set/clear individual flags - bool getGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift = 0); - void setGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift = 0); - void setGlobalChunkFlag(int index, unsigned char flag, unsigned char shift = 0); - void clearGlobalChunkFlag(int x, int y, int z, Level *level, unsigned char flag, unsigned char shift = 0); + // Get/set/clear individual flags + bool getGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, unsigned char shift = 0); + void setGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, unsigned char shift = 0); + void setGlobalChunkFlag(int index, unsigned char flag, + unsigned char shift = 0); + void clearGlobalChunkFlag(int x, int y, int z, Level* level, + unsigned char flag, unsigned char shift = 0); - // Get/set whole byte of flags - unsigned char getGlobalChunkFlags(int x, int y, int z, Level *level); - void setGlobalChunkFlags(int x, int y, int z, Level *level, unsigned char flags); + // Get/set whole byte of flags + unsigned char getGlobalChunkFlags(int x, int y, int z, Level* level); + void setGlobalChunkFlags(int x, int y, int z, Level* level, + unsigned char flags); - // Reference counting - unsigned char incGlobalChunkRefCount(int x, int y, int z, Level *level); - unsigned char decGlobalChunkRefCount(int x, int y, int z, Level *level); + // Reference counting + unsigned char incGlobalChunkRefCount(int x, int y, int z, Level* level); + unsigned char decGlobalChunkRefCount(int x, int y, int z, Level* level); - // Actual storage for flags - unsigned char *globalChunkFlags; + // Actual storage for flags + unsigned char* globalChunkFlags; - // The flag definitions - static const int CHUNK_FLAG_COMPILED = 0x01; - static const int CHUNK_FLAG_DIRTY = 0x02; - static const int CHUNK_FLAG_EMPTY0 = 0x04; - static const int CHUNK_FLAG_EMPTY1 = 0x08; - static const int CHUNK_FLAG_EMPTYBOTH = 0x0c; - static const int CHUNK_FLAG_NOTSKYLIT = 0x10; + // The flag definitions + static const int CHUNK_FLAG_COMPILED = 0x01; + static const int CHUNK_FLAG_DIRTY = 0x02; + static const int CHUNK_FLAG_EMPTY0 = 0x04; + static const int CHUNK_FLAG_EMPTY1 = 0x08; + static const int CHUNK_FLAG_EMPTYBOTH = 0x0c; + static const int CHUNK_FLAG_NOTSKYLIT = 0x10; #ifdef _CRITICAL_CHUNKS - static const int CHUNK_FLAG_CRITICAL = 0x20; - static const int CHUNK_FLAG_CUT_OUT = 0x40; - static const int CHUNK_FLAG_REF_MASK = 0x01; - static const int CHUNK_FLAG_REF_SHIFT = 7; + static const int CHUNK_FLAG_CRITICAL = 0x20; + static const int CHUNK_FLAG_CUT_OUT = 0x40; + static const int CHUNK_FLAG_REF_MASK = 0x01; + static const int CHUNK_FLAG_REF_SHIFT = 7; #else - static const int CHUNK_FLAG_REF_MASK = 0x07; - static const int CHUNK_FLAG_REF_SHIFT = 5; + static const int CHUNK_FLAG_REF_MASK = 0x07; + static const int CHUNK_FLAG_REF_SHIFT = 5; #endif - XLockFreeStack dirtyChunksLockFreeStack; + XLockFreeStack dirtyChunksLockFreeStack; - bool dirtyChunkPresent; - __int64 lastDirtyChunkFound; - static const int FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS = 250; + bool dirtyChunkPresent; + __int64 lastDirtyChunkFound; + static const int FORCE_DIRTY_CHUNK_CHECK_PERIOD_MS = 250; #ifdef _LARGE_WORLDS - static const int MAX_CONCURRENT_CHUNK_REBUILDS = 4; - static const int MAX_CHUNK_REBUILD_THREADS = MAX_CONCURRENT_CHUNK_REBUILDS - 1; - static Chunk permaChunk[MAX_CONCURRENT_CHUNK_REBUILDS]; - static C4JThread *rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; - static C4JThread::EventArray *s_rebuildCompleteEvents; - static C4JThread::Event *s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; - static void staticCtor(); - static int rebuildChunkThreadProc(void *lpParam); + static const int MAX_CONCURRENT_CHUNK_REBUILDS = 4; + static const int MAX_CHUNK_REBUILD_THREADS = + MAX_CONCURRENT_CHUNK_REBUILDS - 1; + static Chunk permaChunk[MAX_CONCURRENT_CHUNK_REBUILDS]; + static C4JThread* rebuildThreads[MAX_CHUNK_REBUILD_THREADS]; + static C4JThread::EventArray* s_rebuildCompleteEvents; + static C4JThread::Event* s_activationEventA[MAX_CHUNK_REBUILD_THREADS]; + static void staticCtor(); + static int rebuildChunkThreadProc(void* lpParam); - CRITICAL_SECTION m_csChunkFlags; + CRITICAL_SECTION m_csChunkFlags; #endif - void nonStackDirtyChunksAdded(); + void nonStackDirtyChunksAdded(); }; diff --git a/Minecraft.Client/Rendering/Lighting.cpp b/Minecraft.Client/Rendering/Lighting.cpp index eafba1dfd..c0eb8e562 100644 --- a/Minecraft.Client/Rendering/Lighting.cpp +++ b/Minecraft.Client/Rendering/Lighting.cpp @@ -3,19 +3,16 @@ #include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "../../Minecraft.World/Util/Vec3.h" -FloatBuffer *Lighting::lb = new FloatBuffer(16); +FloatBuffer* Lighting::lb = new FloatBuffer(16); - -void Lighting::turnOff() -{ +void Lighting::turnOff() { glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_LIGHT1); glDisable(GL_COLOR_MATERIAL); } -void Lighting::turnOn() -{ +void Lighting::turnOn() { glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); @@ -25,7 +22,7 @@ void Lighting::turnOn() float d = 0.6f; float s = 0.0f; - Vec3 *l = Vec3::newTemp(0.2f, 1.0f, -0.7f)->normalize(); + Vec3* l = Vec3::newTemp(0.2f, 1.0f, -0.7f)->normalize(); glLight(GL_LIGHT0, GL_POSITION, getBuffer(l->x, l->y, l->z, 0)); glLight(GL_LIGHT0, GL_DIFFUSE, getBuffer(d, d, d, 1)); glLight(GL_LIGHT0, GL_AMBIENT, getBuffer(0.0f, 0.0f, 0.0f, 1.0f)); @@ -39,27 +36,23 @@ void Lighting::turnOn() glShadeModel(GL_FLAT); glLightModel(GL_LIGHT_MODEL_AMBIENT, getBuffer(a, a, a, 1)); - } -FloatBuffer *Lighting::getBuffer(double a, double b, double c, double d) -{ - return getBuffer((float) a, (float) b, (float) c, (float) d); +FloatBuffer* Lighting::getBuffer(double a, double b, double c, double d) { + return getBuffer((float)a, (float)b, (float)c, (float)d); } -FloatBuffer *Lighting::getBuffer(float a, float b, float c, float d) -{ +FloatBuffer* Lighting::getBuffer(float a, float b, float c, float d) { lb->clear(); lb->put(a)->put(b)->put(c)->put(d); lb->flip(); return lb; } -void Lighting::turnOnGui() -{ - glPushMatrix(); - glRotatef(-30, 0, 1, 0); - glRotatef(165, 1, 0, 0); - turnOn(); - glPopMatrix(); +void Lighting::turnOnGui() { + glPushMatrix(); + glRotatef(-30, 0, 1, 0); + glRotatef(165, 1, 0, 0); + turnOn(); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Lighting.h b/Minecraft.Client/Rendering/Lighting.h index c06fd5399..561406c79 100644 --- a/Minecraft.Client/Rendering/Lighting.h +++ b/Minecraft.Client/Rendering/Lighting.h @@ -1,16 +1,16 @@ #pragma once class FloatBuffer; -class Lighting -{ +class Lighting { private: - static FloatBuffer *lb; + static FloatBuffer* lb; public: - static void turnOff(); + static void turnOff(); static void turnOn(); - static void turnOnGui(); + static void turnOnGui(); + private: - static FloatBuffer *getBuffer(double a, double b, double c, double d); - static FloatBuffer *getBuffer(float a, float b, float c, float d); + static FloatBuffer* getBuffer(double a, double b, double c, double d); + static FloatBuffer* getBuffer(float a, float b, float c, float d); }; diff --git a/Minecraft.Client/Rendering/Minimap.cpp b/Minecraft.Client/Rendering/Minimap.cpp index 51126a522..bf8c61b2a 100644 --- a/Minecraft.Client/Rendering/Minimap.cpp +++ b/Minecraft.Client/Rendering/Minimap.cpp @@ -9,173 +9,192 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.material.h" #ifdef __ORBIS__ -short Minimap::LUT[256]; // 4J added +short Minimap::LUT[256]; // 4J added #else -int Minimap::LUT[256]; // 4J added +int Minimap::LUT[256]; // 4J added #endif -bool Minimap::genLUT = true; // 4J added +bool Minimap::genLUT = true; // 4J added -Minimap::Minimap(Font *font, Options *options, Textures *textures, bool optimised) -{ +Minimap::Minimap(Font* font, Options* options, Textures* textures, + bool optimised) { #ifdef __PS3__ - // we're using the RSX now to upload textures to vram, so we need the main ram textures allocated from io space - this->pixels = intArray((int*)RenderManager.allocIOMem(w*h*sizeof(int)), 16*16); + // we're using the RSX now to upload textures to vram, so we need the main + // ram textures allocated from io space + this->pixels = + intArray((int*)RenderManager.allocIOMem(w * h * sizeof(int)), 16 * 16); #elif defined __ORBIS__ - this->pixels = shortArray(w*h); + this->pixels = shortArray(w * h); #else - this->pixels = intArray(w*h); + this->pixels = intArray(w * h); #endif this->options = options; this->font = font; - BufferedImage *img = new BufferedImage(w, h, BufferedImage::TYPE_INT_ARGB); + BufferedImage* img = new BufferedImage(w, h, BufferedImage::TYPE_INT_ARGB); #ifdef __ORBIS__ - mapTexture = textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw5551, false ); // 4J - make sure we aren't mipmapping as we never set the data for mipmaps + mapTexture = + textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw5551, + false); // 4J - make sure we aren't mipmapping as + // we never set the data for mipmaps #else - mapTexture = textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw, false ); // 4J - make sure we aren't mipmapping as we never set the data for mipmaps + mapTexture = + textures->getTexture(img, C4JRender::TEXTURE_FORMAT_RxGyBzAw, + false); // 4J - make sure we aren't mipmapping as + // we never set the data for mipmaps #endif - delete img; - for (int i = 0; i < w * h; i++) - { + delete img; + for (int i = 0; i < w * h; i++) { pixels[i] = 0x00000000; - } + } - // 4J added - generate the colour mapping that we'll be needing as a LUT to minimise processing we actually need to do during normal rendering - if( genLUT ) - { - reloadColours(); - } - renderCount = 0; // 4J added - m_optimised = optimised; + // 4J added - generate the colour mapping that we'll be needing as a LUT to + // minimise processing we actually need to do during normal rendering + if (genLUT) { + reloadColours(); + } + renderCount = 0; // 4J added + m_optimised = optimised; } -void Minimap::reloadColours() -{ - ColourTable *colourTable = Minecraft::GetInstance()->getColourTable(); - // 4J note that this code has been extracted pretty much as it was in Minimap::render, although with some byte order changes - for( int i = 0; i < (14 * 4); i++ ) // 14 material colours currently, 4 brightnesses of each - { - if (i / 4 == 0) - { - // 4J - changed byte order to save having to reorder later +void Minimap::reloadColours() { + ColourTable* colourTable = Minecraft::GetInstance()->getColourTable(); + // 4J note that this code has been extracted pretty much as it was in + // Minimap::render, although with some byte order changes + for (int i = 0; i < (14 * 4); + i++) // 14 material colours currently, 4 brightnesses of each + { + if (i / 4 == 0) { + // 4J - changed byte order to save having to reorder later #ifdef __ORBIS__ - LUT[i] = 0; + LUT[i] = 0; #else - LUT[i] = (((i + i / w) & 1) * 8 + 16); + LUT[i] = (((i + i / w) & 1) * 8 + 16); #endif - //pixels[i] = (((i + i / w) & 1) * 8 + 16) << 24; - } - else - { - int color = colourTable->getColor( MaterialColor::colors[i / 4]->col ); - int brightness = i & 3; + // pixels[i] = (((i + i / w) & 1) * 8 + 16) << 24; + } else { + int color = + colourTable->getColor(MaterialColor::colors[i / 4]->col); + int brightness = i & 3; - int br = 220; - if (brightness == 2) br = 255; - if (brightness == 0) br = 180; + int br = 220; + if (brightness == 2) br = 255; + if (brightness == 0) br = 180; - int r = ((color >> 16) & 0xff) * br / 255; - int g = ((color >> 8) & 0xff) * br / 255; - int b = ((color) & 0xff) * br / 255; + int r = ((color >> 16) & 0xff) * br / 255; + int g = ((color >> 8) & 0xff) * br / 255; + int b = ((color) & 0xff) * br / 255; - // 4J - changed byte order to save having to reorder later -#if ( defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__ ) - LUT[i] = 255 << 24 | b << 16 | g << 8 | r; + // 4J - changed byte order to save having to reorder later +#if (defined _DURANGO || defined _WIN64 || __PSVITA__ || __linux__) + LUT[i] = 255 << 24 | b << 16 | g << 8 | r; #elif defined _XBOX - LUT[i] = 255 << 24 | r << 16 | g << 8 | b; + LUT[i] = 255 << 24 | r << 16 | g << 8 | b; #elif defined __ORBIS__ - r >>= 3; g >>= 3; b >>= 3; - LUT[i] = 1 << 15 | ( r << 10 ) | ( g << 5 ) | b; + r >>= 3; + g >>= 3; + b >>= 3; + LUT[i] = 1 << 15 | (r << 10) | (g << 5) | b; #else - LUT[i] = r << 24 | g << 16 | b << 8 | 255; + LUT[i] = r << 24 | g << 16 | b << 8 | 255; #endif - //pixels[i] = (255) << 24 | r << 16 | g << 8 | b; - } - - } - genLUT = false; + // pixels[i] = (255) << 24 | r << 16 | g << 8 | b; + } + } + genLUT = false; } // 4J added entityId -void Minimap::render(std::shared_ptr player, Textures *textures, std::shared_ptr data, int entityId) -{ - // 4J - only update every 8 renders, as an optimisation - // We don't want to use this for ItemFrame renders of maps, as then we can't have different maps together - if( !m_optimised || ( renderCount & 7 ) == 0 ) - { - for (int i = 0; i < w * h; i++) - { - int val = data->colors[i]; - // 4J - moved the code that used to run here into a LUT that is generated once in the ctor above - pixels[i] = LUT[val]; - } - } - renderCount++; +void Minimap::render(std::shared_ptr player, Textures* textures, + std::shared_ptr data, int entityId) { + // 4J - only update every 8 renders, as an optimisation + // We don't want to use this for ItemFrame renders of maps, as then we can't + // have different maps together + if (!m_optimised || (renderCount & 7) == 0) { + for (int i = 0; i < w * h; i++) { + int val = data->colors[i]; + // 4J - moved the code that used to run here into a LUT that is + // generated once in the ctor above + pixels[i] = LUT[val]; + } + } + renderCount++; - // 4J - changed - have changed texture generation here to put the bytes in the right order already, so we don't have to do any copying round etc. in the texture replacement itself + // 4J - changed - have changed texture generation here to put the bytes in + // the right order already, so we don't have to do any copying round etc. in + // the texture replacement itself textures->replaceTextureDirect(pixels, w, h, mapTexture); int x = 0; int y = 0; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); float vo = 0; glBindTexture(GL_TEXTURE_2D, mapTexture); glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_ALPHA_TEST); t->begin(); - // 4J - moved to -0.02 to stop z fighting ( was -0.01) - // AP - Vita still has issues so push it a bit more - float Offset = -0.02f; + // 4J - moved to -0.02 to stop z fighting ( was -0.01) + // AP - Vita still has issues so push it a bit more + float Offset = -0.02f; #ifdef __PSVITA__ - Offset = -0.03f; + Offset = -0.03f; #endif - t->vertexUV((float)(x + 0 + vo), (float)( y + h - vo), (float)( Offset), (float)( 0), (float)( 1)); - t->vertexUV((float)(x + w - vo), (float)( y + h - vo), (float)( Offset), (float)( 1), (float)( 1)); - t->vertexUV((float)(x + w - vo), (float)( y + 0 + vo), (float)( Offset), (float)( 1), (float)( 0)); - t->vertexUV((float)(x + 0 + vo), (float)( y + 0 + vo), (float)( Offset), (float)( 0), (float)( 0)); + t->vertexUV((float)(x + 0 + vo), (float)(y + h - vo), (float)(Offset), + (float)(0), (float)(1)); + t->vertexUV((float)(x + w - vo), (float)(y + h - vo), (float)(Offset), + (float)(1), (float)(1)); + t->vertexUV((float)(x + w - vo), (float)(y + 0 + vo), (float)(Offset), + (float)(1), (float)(0)); + t->vertexUV((float)(x + 0 + vo), (float)(y + 0 + vo), (float)(Offset), + (float)(0), (float)(0)); t->end(); glEnable(GL_ALPHA_TEST); glDisable(GL_BLEND); + textures->bind( + textures->loadTexture(TN_MISC_MAPICONS)); // L"/misc/mapicons.png")); - textures->bind(textures->loadTexture(TN_MISC_MAPICONS));//L"/misc/mapicons.png")); - - AUTO_VAR(itEnd, data->decorations.end()); + AUTO_VAR(itEnd, data->decorations.end()); #ifdef _LARGE_WORLDS - std::vector m_edgeIcons; + std::vector m_edgeIcons; #endif - // 4J-PB - stack the map icons - float fIconZ=-0.04f;// 4J - moved to -0.04 (was -0.02) to stop z fighting - for( std::vector::iterator it = data->decorations.begin(); it != itEnd; it++ ) - { - MapItemSavedData::MapDecoration *dec = *it; + // 4J-PB - stack the map icons + float fIconZ = + -0.04f; // 4J - moved to -0.04 (was -0.02) to stop z fighting + for (std::vector::iterator it = + data->decorations.begin(); + it != itEnd; it++) { + MapItemSavedData::MapDecoration* dec = *it; - if(!dec->visible) continue; + if (!dec->visible) continue; - char imgIndex = dec->img; + char imgIndex = dec->img; #ifdef _LARGE_WORLDS - // For edge icons, use a different texture - if(imgIndex >= 16) - { - m_edgeIcons.push_back(dec); - continue; - } + // For edge icons, use a different texture + if (imgIndex >= 16) { + m_edgeIcons.push_back(dec); + continue; + } #endif - // 4J Stu - For item frame renders, the player is NULL. We do not want to show player icons on the frames. - if(player == NULL && (imgIndex != 12)) continue; - else if (player != NULL && imgIndex == 12) continue; - else if( imgIndex == 12 && dec->entityId != entityId) continue; + // 4J Stu - For item frame renders, the player is NULL. We do not want + // to show player icons on the frames. + if (player == NULL && (imgIndex != 12)) + continue; + else if (player != NULL && imgIndex == 12) + continue; + else if (imgIndex == 12 && dec->entityId != entityId) + continue; glPushMatrix(); - glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, fIconZ); + glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, + fIconZ); glRotatef(dec->rot * 360 / 16.0f, 0, 0, 1); glScalef(4, 4, 3); glTranslatef(-1.0f / 8.0f, +1.0f / 8.0f, 0); @@ -186,34 +205,42 @@ void Minimap::render(std::shared_ptr player, Textures *textures, std::sh float v1 = (imgIndex / 4 + 1) / 4.0f; t->begin(); - t->vertexUV((float)(-1), (float)( +1), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+1), (float)( +1), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+1), (float)( -1), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-1), (float)( -1), (float)( 0), (float)( u0), (float)( v1)); + t->vertexUV((float)(-1), (float)(+1), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(+1), (float)(+1), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(+1), (float)(-1), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-1), (float)(-1), (float)(0), (float)(u0), + (float)(v1)); t->end(); glPopMatrix(); - fIconZ-=0.01f; + fIconZ -= 0.01f; } #ifdef _LARGE_WORLDS - // For players on the edge of the world - textures->bind(textures->loadTexture(TN_MISC_ADDITIONALMAPICONS)); + // For players on the edge of the world + textures->bind(textures->loadTexture(TN_MISC_ADDITIONALMAPICONS)); - fIconZ=-0.04f;// 4J - moved to -0.04 (was -0.02) to stop z fighting - for( AUTO_VAR(it,m_edgeIcons.begin()); it != m_edgeIcons.end(); it++ ) - { - MapItemSavedData::MapDecoration *dec = *it; - - char imgIndex = dec->img; - imgIndex -= 16; + fIconZ = -0.04f; // 4J - moved to -0.04 (was -0.02) to stop z fighting + for (AUTO_VAR(it, m_edgeIcons.begin()); it != m_edgeIcons.end(); it++) { + MapItemSavedData::MapDecoration* dec = *it; - // 4J Stu - For item frame renders, the player is NULL. We do not want to show player icons on the frames. - if(player == NULL && (imgIndex != 12)) continue; - else if (player != NULL && imgIndex == 12) continue; - else if( imgIndex == 12 && dec->entityId != entityId) continue; + char imgIndex = dec->img; + imgIndex -= 16; + + // 4J Stu - For item frame renders, the player is NULL. We do not want + // to show player icons on the frames. + if (player == NULL && (imgIndex != 12)) + continue; + else if (player != NULL && imgIndex == 12) + continue; + else if (imgIndex == 12 && dec->entityId != entityId) + continue; glPushMatrix(); - glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, fIconZ); + glTranslatef(x + dec->x / 2.0f + w / 2, y + dec->y / 2.0f + h / 2, + fIconZ); glRotatef(dec->rot * 360 / 16.0f, 0, 0, 1); glScalef(4, 4, 3); glTranslatef(-1.0f / 8.0f, +1.0f / 8.0f, 0); @@ -224,39 +251,43 @@ void Minimap::render(std::shared_ptr player, Textures *textures, std::sh float v1 = (imgIndex / 4 + 1) / 4.0f; t->begin(); - t->vertexUV((float)(-1), (float)( +1), (float)( 0), (float)( u0), (float)( v0)); - t->vertexUV((float)(+1), (float)( +1), (float)( 0), (float)( u1), (float)( v0)); - t->vertexUV((float)(+1), (float)( -1), (float)( 0), (float)( u1), (float)( v1)); - t->vertexUV((float)(-1), (float)( -1), (float)( 0), (float)( u0), (float)( v1)); + t->vertexUV((float)(-1), (float)(+1), (float)(0), (float)(u0), + (float)(v0)); + t->vertexUV((float)(+1), (float)(+1), (float)(0), (float)(u1), + (float)(v0)); + t->vertexUV((float)(+1), (float)(-1), (float)(0), (float)(u1), + (float)(v1)); + t->vertexUV((float)(-1), (float)(-1), (float)(0), (float)(u0), + (float)(v1)); t->end(); glPopMatrix(); - fIconZ-=0.01f; + fIconZ -= 0.01f; } #endif glPushMatrix(); -// glRotatef(0, 1, 0, 0); + // glRotatef(0, 1, 0, 0); glTranslatef(0, 0, -0.06f); glScalef(1, 1, 1); -// 4J Stu - Don't render the text name, except in debug -//#if 1 -//#ifdef _DEBUG -// font->draw(data->id, x, y, 0xff000000); -//#else - // 4J Stu - TU-1 hotfix - // DCR: Render the players current position here instead - if(player != NULL) - { - wchar_t playerPosText[32]; - ZeroMemory(&playerPosText, sizeof(wchar_t) * 32); - int posx = floor(player->x); - int posy = floor(player->y); - int posz = floor(player->z); - swprintf(playerPosText, 32, L"X: %d, Y: %d, Z: %d", posx, posy, posz); - - font->draw(playerPosText, x, y, Minecraft::GetInstance()->getColourTable()->getColour(eMinecraftColour_Map_Text)); - } -//#endif - glPopMatrix(); + // 4J Stu - Don't render the text name, except in debug + // #if 1 + // #ifdef _DEBUG + // font->draw(data->id, x, y, 0xff000000); + // #else + // 4J Stu - TU-1 hotfix + // DCR: Render the players current position here instead + if (player != NULL) { + wchar_t playerPosText[32]; + ZeroMemory(&playerPosText, sizeof(wchar_t) * 32); + int posx = floor(player->x); + int posy = floor(player->y); + int posz = floor(player->z); + swprintf(playerPosText, 32, L"X: %d, Y: %d, Z: %d", posx, posy, posz); + font->draw(playerPosText, x, y, + Minecraft::GetInstance()->getColourTable()->getColour( + eMinecraftColour_Map_Text)); + } + // #endif + glPopMatrix(); } diff --git a/Minecraft.Client/Rendering/Minimap.h b/Minecraft.Client/Rendering/Minimap.h index 2743f03d5..5ff83c5aa 100644 --- a/Minecraft.Client/Rendering/Minimap.h +++ b/Minecraft.Client/Rendering/Minimap.h @@ -6,30 +6,32 @@ class Textures; class Player; class MapItemSavedData; -class Minimap -{ +class Minimap { private: - static const int w = MapItem::IMAGE_WIDTH; + static const int w = MapItem::IMAGE_WIDTH; static const int h = MapItem::IMAGE_HEIGHT; #ifdef __ORBIS__ - static short LUT[256]; // 4J added + static short LUT[256]; // 4J added #else - static int LUT[256]; // 4J added + static int LUT[256]; // 4J added #endif - static bool genLUT; // 4J added - int renderCount; // 4J added - bool m_optimised; // 4J Added + static bool genLUT; // 4J added + int renderCount; // 4J added + bool m_optimised; // 4J Added #ifdef __ORBIS__ - shortArray pixels; + shortArray pixels; #else intArray pixels; #endif int mapTexture; - Options *options; - Font *font; + Options* options; + Font* font; public: - Minimap(Font *font, Options *options, Textures *textures, bool optimised = true); // 4J Added optimised param - static void reloadColours(); - void render(std::shared_ptr player, Textures *textures, std::shared_ptr data, int entityId); // 4J added entityId param + Minimap(Font* font, Options* options, Textures* textures, + bool optimised = true); // 4J Added optimised param + static void reloadColours(); + void render(std::shared_ptr player, Textures* textures, + std::shared_ptr data, + int entityId); // 4J added entityId param }; diff --git a/Minecraft.Client/Rendering/Models/BlazeModel.cpp b/Minecraft.Client/Rendering/Models/BlazeModel.cpp index f1a805957..8fbb67e04 100644 --- a/Minecraft.Client/Rendering/Models/BlazeModel.cpp +++ b/Minecraft.Client/Rendering/Models/BlazeModel.cpp @@ -3,12 +3,10 @@ #include "BlazeModel.h" #include "ModelPart.h" -BlazeModel::BlazeModel() : Model() -{ +BlazeModel::BlazeModel() : Model() { upperBodyParts = ModelPartArray(12); - for (unsigned int i = 0; i < upperBodyParts.length; i++) - { + for (unsigned int i = 0; i < upperBodyParts.length; i++) { upperBodyParts[i] = new ModelPart(this, 0, 16); upperBodyParts[i]->addBox(0, 0, 0, 2, 8, 2); } @@ -16,61 +14,54 @@ BlazeModel::BlazeModel() : Model() head = new ModelPart(this, 0, 0); head->addBox(-4, -4, -4, 8, 8, 8); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - for (unsigned int i = 0; i < upperBodyParts.length; i++) - { - upperBodyParts[i]->compile(1.0f/16.0f); - } - head->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here + for (unsigned int i = 0; i < upperBodyParts.length; i++) { + upperBodyParts[i]->compile(1.0f / 16.0f); + } + head->compile(1.0f / 16.0f); } -int BlazeModel::modelVersion() -{ - return 8; -} +int BlazeModel::modelVersion() { return 8; } -void BlazeModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void BlazeModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale,usecompiled); - for (unsigned int i = 0; i < upperBodyParts.length; i++) - { + head->render(scale, usecompiled); + for (unsigned int i = 0; i < upperBodyParts.length; i++) { upperBodyParts[i]->render(scale, usecompiled); } } -void BlazeModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - +void BlazeModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { float angle = bob * PI * -.1f; - for (int i = 0; i < 4; i++) - { - upperBodyParts[i]->y = -2 + Mth::cos((i * 2 + bob) * .25f); - upperBodyParts[i]->x = Mth::cos(angle) * 9.0f; - upperBodyParts[i]->z = Mth::sin(angle) * 9.0f; + for (int i = 0; i < 4; i++) { + upperBodyParts[i]->y = -2 + Mth::cos((i * 2 + bob) * .25f); + upperBodyParts[i]->x = Mth::cos(angle) * 9.0f; + upperBodyParts[i]->z = Mth::sin(angle) * 9.0f; angle += PI * 0.5f; } angle = .25f * PI + bob * PI * .03f; - for (int i = 4; i < 8; i++) - { - upperBodyParts[i]->y = 2 + Mth::cos((i * 2 + bob) * .25f); - upperBodyParts[i]->x = Mth::cos(angle) * 7.0f; - upperBodyParts[i]->z = Mth::sin(angle) * 7.0f; + for (int i = 4; i < 8; i++) { + upperBodyParts[i]->y = 2 + Mth::cos((i * 2 + bob) * .25f); + upperBodyParts[i]->x = Mth::cos(angle) * 7.0f; + upperBodyParts[i]->z = Mth::sin(angle) * 7.0f; angle += PI * 0.5f; } angle = .15f * PI + bob * PI * -.05f; - for (int i = 8; i < 12; i++) - { - upperBodyParts[i]->y = 11 + Mth::cos((i * 1.5f + bob) * .5f); - upperBodyParts[i]->x = Mth::cos(angle) * 5.0f; - upperBodyParts[i]->z = Mth::sin(angle) * 5.0f; + for (int i = 8; i < 12; i++) { + upperBodyParts[i]->y = 11 + Mth::cos((i * 1.5f + bob) * .5f); + upperBodyParts[i]->x = Mth::cos(angle) * 5.0f; + upperBodyParts[i]->z = Mth::sin(angle) * 5.0f; angle += PI * 0.5f; } - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); } - diff --git a/Minecraft.Client/Rendering/Models/BlazeModel.h b/Minecraft.Client/Rendering/Models/BlazeModel.h index 9e702ecb4..3abf74199 100644 --- a/Minecraft.Client/Rendering/Models/BlazeModel.h +++ b/Minecraft.Client/Rendering/Models/BlazeModel.h @@ -1,16 +1,18 @@ #pragma once #include "Model.h" -class BlazeModel : public Model -{ - +class BlazeModel : public Model { private: - ModelPartArray upperBodyParts; - ModelPart *head; + ModelPartArray upperBodyParts; + ModelPart* head; public: - BlazeModel(); - int modelVersion(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + BlazeModel(); + int modelVersion(); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/BoatModel.cpp b/Minecraft.Client/Rendering/Models/BoatModel.cpp index 90a9752d5..e0b5da365 100644 --- a/Minecraft.Client/Rendering/Models/BoatModel.cpp +++ b/Minecraft.Client/Rendering/Models/BoatModel.cpp @@ -1,51 +1,51 @@ #include "../../Platform/stdafx.h" #include "BoatModel.h" -BoatModel::BoatModel() : Model() -{ - cubes[0] = new ModelPart(this, 0, 8); - cubes[1] = new ModelPart(this, 0, 0); - cubes[2] = new ModelPart(this, 0, 0); - cubes[3] = new ModelPart(this, 0, 0); - cubes[4] = new ModelPart(this, 0, 0); +BoatModel::BoatModel() : Model() { + cubes[0] = new ModelPart(this, 0, 8); + cubes[1] = new ModelPart(this, 0, 0); + cubes[2] = new ModelPart(this, 0, 0); + cubes[3] = new ModelPart(this, 0, 0); + cubes[4] = new ModelPart(this, 0, 0); - int w = 24; - int d = 6; - int h = 20; - int yOff = 4; + int w = 24; + int d = 6; + int h = 20; + int yOff = 4; - cubes[0]->addBox((float)(-w / 2), (float)(-h / 2 + 2), -3, w, h - 4, 4, 0); - cubes[0]->setPos(0, (float)(0 + yOff), 0); - - cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); - - cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); - - cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); - - cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); - cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); - - cubes[0]->xRot = PI / 2; - cubes[1]->yRot = PI / 2 * 3; - cubes[2]->yRot = PI / 2 * 1; - cubes[3]->yRot = PI / 2 * 2; + cubes[0]->addBox((float)(-w / 2), (float)(-h / 2 + 2), -3, w, h - 4, 4, 0); + cubes[0]->setPos(0, (float)(0 + yOff), 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - cubes[0]->compile(1.0f/16.0f); - cubes[1]->compile(1.0f/16.0f); - cubes[2]->compile(1.0f/16.0f); - cubes[3]->compile(1.0f/16.0f); - cubes[4]->compile(1.0f/16.0f); + cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); + + cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); + + cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); + + cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); + cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); + + cubes[0]->xRot = PI / 2; + cubes[1]->yRot = PI / 2 * 3; + cubes[2]->yRot = PI / 2 * 1; + cubes[3]->yRot = PI / 2 * 2; + + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + cubes[0]->compile(1.0f / 16.0f); + cubes[1]->compile(1.0f / 16.0f); + cubes[2]->compile(1.0f / 16.0f); + cubes[3]->compile(1.0f / 16.0f); + cubes[4]->compile(1.0f / 16.0f); } -void BoatModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - for (int i = 0; i < 5; i++) - { - cubes[i]->render(scale, usecompiled); - } +void BoatModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + for (int i = 0; i < 5; i++) { + cubes[i]->render(scale, usecompiled); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/BoatModel.h b/Minecraft.Client/Rendering/Models/BoatModel.h index 192e140f3..d96fdef06 100644 --- a/Minecraft.Client/Rendering/Models/BoatModel.h +++ b/Minecraft.Client/Rendering/Models/BoatModel.h @@ -2,10 +2,11 @@ #include "Model.h" #include "ModelPart.h" -class BoatModel : public Model -{ +class BoatModel : public Model { public: - ModelPart *cubes[5]; + ModelPart* cubes[5]; BoatModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/BookModel.cpp b/Minecraft.Client/Rendering/Models/BookModel.cpp index 04237d2be..b5b522eef 100644 --- a/Minecraft.Client/Rendering/Models/BookModel.cpp +++ b/Minecraft.Client/Rendering/Models/BookModel.cpp @@ -3,66 +3,77 @@ #include "BookModel.h" #include "ModelPart.h" -BookModel::BookModel() -{ - leftLid = (new ModelPart(this))->texOffs(0, 0)->addBox(-6, -5, 0, 6, 10, 0); - rightLid = (new ModelPart(this))->texOffs(16, 0)->addBox(0, -5, 0, 6, 10, 0); +BookModel::BookModel() { + leftLid = (new ModelPart(this))->texOffs(0, 0)->addBox(-6, -5, 0, 6, 10, 0); + rightLid = + (new ModelPart(this))->texOffs(16, 0)->addBox(0, -5, 0, 6, 10, 0); - seam = (new ModelPart(this))->texOffs(12, 0)->addBox(-1, -5, 0, 2, 10, 0); + seam = (new ModelPart(this))->texOffs(12, 0)->addBox(-1, -5, 0, 2, 10, 0); - // 4J - added faceMasks here to remove sides of these page boxes which end up being nearly coplanar to the cover of the book and flickering when rendering at a distance - leftPages = (new ModelPart(this))->texOffs(0, 10)->addBoxWithMask(0, -4, -1 + 0.01f, 5, 8, 1, 47); // 4J - faceMask is binary 101111 - rightPages = (new ModelPart(this))->texOffs(12, 10)->addBoxWithMask(0, -4, -0.01f, 5, 8, 1, 31); // 4J - faceMask is binary 011111 + // 4J - added faceMasks here to remove sides of these page boxes which end + // up being nearly coplanar to the cover of the book and flickering when + // rendering at a distance + leftPages = (new ModelPart(this)) + ->texOffs(0, 10) + ->addBoxWithMask(0, -4, -1 + 0.01f, 5, 8, 1, + 47); // 4J - faceMask is binary 101111 + rightPages = (new ModelPart(this)) + ->texOffs(12, 10) + ->addBoxWithMask(0, -4, -0.01f, 5, 8, 1, + 31); // 4J - faceMask is binary 011111 - flipPage1 = (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); - flipPage2 = (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); + flipPage1 = + (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); + flipPage2 = + (new ModelPart(this))->texOffs(24, 10)->addBox(0, -4, 0, 5, 8, 0); - leftLid->setPos(0, 0, -1); - rightLid->setPos(0, 0, 1); + leftLid->setPos(0, 0, -1); + rightLid->setPos(0, 0, 1); - seam->yRot = PI / 2; - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - leftLid->compile(1.0f/16.0f); - rightLid->compile(1.0f/16.0f); - seam->compile(1.0f/16.0f); - leftPages->compile(1.0f/16.0f); - rightPages->compile(1.0f/16.0f); - flipPage1->compile(1.0f/16.0f); - flipPage2->compile(1.0f/16.0f); + seam->yRot = PI / 2; + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + leftLid->compile(1.0f / 16.0f); + rightLid->compile(1.0f / 16.0f); + seam->compile(1.0f / 16.0f); + leftPages->compile(1.0f / 16.0f); + rightPages->compile(1.0f / 16.0f); + flipPage1->compile(1.0f / 16.0f); + flipPage2->compile(1.0f / 16.0f); } -void BookModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void BookModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); - leftLid->render(scale,usecompiled); - rightLid->render(scale,usecompiled); - seam->render(scale,usecompiled); + leftLid->render(scale, usecompiled); + rightLid->render(scale, usecompiled); + seam->render(scale, usecompiled); - leftPages->render(scale,usecompiled); - rightPages->render(scale,usecompiled); + leftPages->render(scale, usecompiled); + rightPages->render(scale, usecompiled); - flipPage1->render(scale,usecompiled); - flipPage2->render(scale,usecompiled); + flipPage1->render(scale, usecompiled); + flipPage2->render(scale, usecompiled); } -void BookModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - float openness = (Mth::sin(time * 0.02f) * 0.10f + 1.25f) * yRot; +void BookModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + float openness = (Mth::sin(time * 0.02f) * 0.10f + 1.25f) * yRot; - leftLid->yRot = PI + openness; - rightLid->yRot = -openness; - leftPages->yRot = +openness; - rightPages->yRot = -openness; + leftLid->yRot = PI + openness; + rightLid->yRot = -openness; + leftPages->yRot = +openness; + rightPages->yRot = -openness; - flipPage1->yRot = +openness - openness * 2 * r; - flipPage2->yRot = +openness - openness * 2 * bob; + flipPage1->yRot = +openness - openness * 2 * r; + flipPage2->yRot = +openness - openness * 2 * bob; - leftPages->x = Mth::sin(openness); - rightPages->x = Mth::sin(openness); - flipPage1->x = Mth::sin(openness); - flipPage2->x = Mth::sin(openness); + leftPages->x = Mth::sin(openness); + rightPages->x = Mth::sin(openness); + flipPage1->x = Mth::sin(openness); + flipPage2->x = Mth::sin(openness); } - diff --git a/Minecraft.Client/Rendering/Models/BookModel.h b/Minecraft.Client/Rendering/Models/BookModel.h index 411d2df55..152c9fec8 100644 --- a/Minecraft.Client/Rendering/Models/BookModel.h +++ b/Minecraft.Client/Rendering/Models/BookModel.h @@ -2,15 +2,18 @@ #pragma once #include "Model.h" -class BookModel : public Model -{ +class BookModel : public Model { public: - ModelPart *leftLid, *rightLid; - ModelPart *leftPages, *rightPages; - ModelPart *flipPage1, *flipPage2; - ModelPart *seam; + ModelPart *leftLid, *rightLid; + ModelPart *leftPages, *rightPages; + ModelPart *flipPage1, *flipPage2; + ModelPart* seam; - BookModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + BookModel(); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/ChestModel.cpp b/Minecraft.Client/Rendering/Models/ChestModel.cpp index 51e5cf0bc..918c44620 100644 --- a/Minecraft.Client/Rendering/Models/ChestModel.cpp +++ b/Minecraft.Client/Rendering/Models/ChestModel.cpp @@ -2,42 +2,42 @@ #include "ChestModel.h" #include "ModelPart.h" -ChestModel::ChestModel() -{ - lid = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); - lid->addBox(0.0f, -5.0f, -14.0f, 14, 5, 14, 0.0f); - lid->x = 1; - lid->y = 7; - lid->z = 15; +ChestModel::ChestModel() { + lid = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); + lid->addBox(0.0f, -5.0f, -14.0f, 14, 5, 14, 0.0f); + lid->x = 1; + lid->y = 7; + lid->z = 15; - lock = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); - lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); - lock->x = 8; - lock->y = 7; - lock->z = 15; + lock = ((new ModelPart(this, 0, 0)))->setTexSize(64, 64); + lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); + lock->x = 8; + lock->y = 7; + lock->z = 15; - bottom = ((new ModelPart(this, 0, 19)))->setTexSize(64, 64); - bottom->addBox(0.0f, 0.0f, 0.0f, 14, 10, 14, 0.0f); - bottom->x = 1; - bottom->y = 6; - bottom->z = 1; + bottom = ((new ModelPart(this, 0, 19)))->setTexSize(64, 64); + bottom->addBox(0.0f, 0.0f, 0.0f, 14, 10, 14, 0.0f); + bottom->x = 1; + bottom->y = 6; + bottom->z = 1; - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - lid->compile(1.0f/16.0f); - lock->compile(1.0f/16.0f); - bottom->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + lid->compile(1.0f / 16.0f); + lock->compile(1.0f / 16.0f); + bottom->compile(1.0f / 16.0f); } -void ChestModel::render(bool usecompiled) -{ - lock->xRot = lid->xRot; +void ChestModel::render(bool usecompiled) { + lock->xRot = lid->xRot; - lock->render(1 / 16.0f, usecompiled); - bottom->render(1 / 16.0f, usecompiled); + lock->render(1 / 16.0f, usecompiled); + bottom->render(1 / 16.0f, usecompiled); - // 4J - moved lid to last and added z-bias to avoid glitching caused by z-fighting between the area of overlap between the lid & bottom of the chest - glPolygonOffset(-0.3f, -0.3f); - lid->render(1 / 16.0f, usecompiled); - glPolygonOffset(0.0f, 0.0f); + // 4J - moved lid to last and added z-bias to avoid glitching caused by + // z-fighting between the area of overlap between the lid & bottom of the + // chest + glPolygonOffset(-0.3f, -0.3f); + lid->render(1 / 16.0f, usecompiled); + glPolygonOffset(0.0f, 0.0f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/ChestModel.h b/Minecraft.Client/Rendering/Models/ChestModel.h index 416ccf753..3b3cfd8b2 100644 --- a/Minecraft.Client/Rendering/Models/ChestModel.h +++ b/Minecraft.Client/Rendering/Models/ChestModel.h @@ -4,15 +4,14 @@ class Cube; -class ChestModel : public Model -{ +class ChestModel : public Model { public: - using Model::render; + using Model::render; - ModelPart *lid; - ModelPart *bottom; - ModelPart *lock; + ModelPart* lid; + ModelPart* bottom; + ModelPart* lock; - ChestModel(); - void render(bool usecompiled); + ChestModel(); + void render(bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/ChickenModel.cpp b/Minecraft.Client/Rendering/Models/ChickenModel.cpp index 642954c9f..b75d80319 100644 --- a/Minecraft.Client/Rendering/Models/ChickenModel.cpp +++ b/Minecraft.Client/Rendering/Models/ChickenModel.cpp @@ -3,102 +3,101 @@ #include "ChickenModel.h" #include "ModelPart.h" -ChickenModel::ChickenModel() : Model() -{ +ChickenModel::ChickenModel() : Model() { int yo = 16; head = new ModelPart(this, 0, 0); - head->addBox(-2.0f, -6.0f, -2.0f, 4, 6, 3, 0.0f); // Head + head->addBox(-2.0f, -6.0f, -2.0f, 4, 6, 3, 0.0f); // Head head->setPos(0, (float)(-1 + yo), -4); beak = new ModelPart(this, 14, 0); - beak->addBox(-2.0f, -4.0f, -4.0f, 4, 2, 2, 0.0f); // Beak + beak->addBox(-2.0f, -4.0f, -4.0f, 4, 2, 2, 0.0f); // Beak beak->setPos(0, (float)(-1 + yo), -4); redThing = new ModelPart(this, 14, 4); - redThing->addBox(-1.0f, -2.0f, -3.0f, 2, 2, 2, 0.0f); // Beak + redThing->addBox(-1.0f, -2.0f, -3.0f, 2, 2, 2, 0.0f); // Beak redThing->setPos(0, (float)(-1 + yo), -4); body = new ModelPart(this, 0, 9); - body->addBox(-3.0f, -4.0f, -3.0f, 6, 8, 6, 0.0f); // Body + body->addBox(-3.0f, -4.0f, -3.0f, 6, 8, 6, 0.0f); // Body body->setPos(0, (float)(0 + yo), 0); leg0 = new ModelPart(this, 26, 0); - leg0->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg0 + leg0->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg0 leg0->setPos(-2, (float)(3 + yo), 1); leg1 = new ModelPart(this, 26, 0); - leg1->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg1 + leg1->addBox(-1.0f, 0.0f, -3.0f, 3, 5, 3); // Leg1 leg1->setPos(1, (float)(3 + yo), 1); wing0 = new ModelPart(this, 24, 13); - wing0->addBox(0.0f, 0.0f, -3.0f, 1, 4, 6); // Wing0 + wing0->addBox(0.0f, 0.0f, -3.0f, 1, 4, 6); // Wing0 wing0->setPos(-4, (float)(-3 + yo), 0); wing1 = new ModelPart(this, 24, 13); - wing1->addBox(-1.0f, 0.0f, -3.0f, 1, 4, 6); // Wing1 + wing1->addBox(-1.0f, 0.0f, -3.0f, 1, 4, 6); // Wing1 wing1->setPos(4, (float)(-3 + yo), 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - beak->compile(1.0f/16.0f); - redThing->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - wing0->compile(1.0f/16.0f); - wing1->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + beak->compile(1.0f / 16.0f); + redThing->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + wing0->compile(1.0f / 16.0f); + wing1->compile(1.0f / 16.0f); } -void ChickenModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void ChickenModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2; - glPushMatrix(); - glTranslatef(0, 5 * scale, 2 * scale); - head->render(scale,usecompiled); - beak->render(scale,usecompiled); - redThing->render(scale,usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - wing0->render(scale,usecompiled); - wing1->render(scale,usecompiled); - glPopMatrix(); - } - else - { - head->render(scale,usecompiled); - beak->render(scale,usecompiled); - redThing->render(scale,usecompiled); - body->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - wing0->render(scale,usecompiled); - wing1->render(scale,usecompiled); - } + if (young) { + float ss = 2; + glPushMatrix(); + glTranslatef(0, 5 * scale, 2 * scale); + head->render(scale, usecompiled); + beak->render(scale, usecompiled); + redThing->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + wing0->render(scale, usecompiled); + wing1->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + beak->render(scale, usecompiled); + redThing->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + wing0->render(scale, usecompiled); + wing1->render(scale, usecompiled); + } } -void ChickenModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->xRot = xRot / (float) (180 / PI); - head->yRot = yRot / (float) (180 / PI); - - beak->xRot = head->xRot; - beak->yRot = head->yRot; - - redThing->xRot = head->xRot; - redThing->yRot = head->yRot; - - body->xRot = 90 / (float) (180 / PI); +void ChickenModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->xRot = xRot / (float)(180 / PI); + head->yRot = yRot / (float)(180 / PI); - leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; - leg1->xRot = ( Mth::cos(time * 0.6662f + PI) * 1.4f) * r; - wing0->zRot = bob; - wing1->zRot = -bob; + beak->xRot = head->xRot; + beak->yRot = head->yRot; + + redThing->xRot = head->xRot; + redThing->yRot = head->yRot; + + body->xRot = 90 / (float)(180 / PI); + + leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; + wing0->zRot = bob; + wing1->zRot = -bob; } diff --git a/Minecraft.Client/Rendering/Models/ChickenModel.h b/Minecraft.Client/Rendering/Models/ChickenModel.h index 7ef7e99b4..5b21368e6 100644 --- a/Minecraft.Client/Rendering/Models/ChickenModel.h +++ b/Minecraft.Client/Rendering/Models/ChickenModel.h @@ -1,12 +1,16 @@ #pragma once #include "Model.h" -class ChickenModel : public Model -{ +class ChickenModel : public Model { public: - ModelPart *head, *hair, *body, *leg0, *leg1, *wing0,* wing1, *beak, *redThing; + ModelPart *head, *hair, *body, *leg0, *leg1, *wing0, *wing1, *beak, + *redThing; ChickenModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/CowModel.cpp b/Minecraft.Client/Rendering/Models/CowModel.cpp index 698cbfc6a..78efcd2a6 100644 --- a/Minecraft.Client/Rendering/Models/CowModel.cpp +++ b/Minecraft.Client/Rendering/Models/CowModel.cpp @@ -2,18 +2,17 @@ #include "CowModel.h" #include "ModelPart.h" -CowModel::CowModel() : QuadrupedModel(12,0) -{ +CowModel::CowModel() : QuadrupedModel(12, 0) { head = new ModelPart(this, 0, 0); - head->addBox(-4, -4, -6, 8, 8, 6, 0); // Head + head->addBox(-4, -4, -6, 8, 8, 6, 0); // Head head->setPos(0, 12 - 6 - 2, -8); - head->texOffs(22, 0)->addBox(-5, -5, -4, 1, 3, 1, 0); // Horn1 - head->texOffs(22, 0)->addBox(+4, -5, -4, 1, 3, 1, 0); // Horn1 + head->texOffs(22, 0)->addBox(-5, -5, -4, 1, 3, 1, 0); // Horn1 + head->texOffs(22, 0)->addBox(+4, -5, -4, 1, 3, 1, 0); // Horn1 body = new ModelPart(this, 18, 4); - body->addBox(-6, -10, -7, 12, 18, 10, 0); // Body + body->addBox(-6, -10, -7, 12, 18, 10, 0); // Body body->setPos(0, 11 + 6 - 12, 2); - body->texOffs(52, 0)->addBox(-2, 2, -8, 4, 6, 1); + body->texOffs(52, 0)->addBox(-2, 2, -8, 4, 6, 1); leg0->x -= 1; leg1->x += 1; @@ -24,9 +23,10 @@ CowModel::CowModel() : QuadrupedModel(12,0) leg2->z -= 1; leg3->z -= 1; - this->zHeadOffs += 2; + this->zHeadOffs += 2; - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); } diff --git a/Minecraft.Client/Rendering/Models/CowModel.h b/Minecraft.Client/Rendering/Models/CowModel.h index dcd7671c6..125da558c 100644 --- a/Minecraft.Client/Rendering/Models/CowModel.h +++ b/Minecraft.Client/Rendering/Models/CowModel.h @@ -1,10 +1,11 @@ #pragma once #include "QuadrupedModel.h" -class CowModel : public QuadrupedModel -{ +class CowModel : public QuadrupedModel { public: CowModel(); -// virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); -// virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); + // virtual void render(std::shared_ptr entity, float time, float + // r, float bob, float yRot, float xRot, float scale, bool usecompiled); + // virtual void setupAnim(float time, float r, float bob, float yRot, + // float xRot, float scale); }; diff --git a/Minecraft.Client/Rendering/Models/CreeperModel.cpp b/Minecraft.Client/Rendering/Models/CreeperModel.cpp index 8a2d2e498..a92685595 100644 --- a/Minecraft.Client/Rendering/Models/CreeperModel.cpp +++ b/Minecraft.Client/Rendering/Models/CreeperModel.cpp @@ -4,60 +4,55 @@ #include "ModelPart.h" // 4J - added -void CreeperModel::_init(float g) -{ +void CreeperModel::_init(float g) { int yo = 4; head = new ModelPart(this, 0, 0); - head->addBox(-4, - 8, -4, 8, 8, 8, g); // Head + head->addBox(-4, -8, -4, 8, 8, 8, g); // Head head->setPos(0, (float)(yo), 0); hair = new ModelPart(this, 32, 0); - hair->addBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head + hair->addBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head hair->setPos(0, (float)(yo), 0); body = new ModelPart(this, 16, 16); - body->addBox(-4, 0, -2, 8, 12, 4, g); // Body + body->addBox(-4, 0, -2, 8, 12, 4, g); // Body body->setPos(0, (float)(yo), 0); leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 + leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 leg0->setPos(-2, (float)(12 + yo), 4); leg1 = new ModelPart(this, 0, 16); - leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 + leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 leg1->setPos(2, (float)(12 + yo), 4); leg2 = new ModelPart(this, 0, 16); - leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 + leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 leg2->setPos(-2, (float)(12 + yo), -4); leg3 = new ModelPart(this, 0, 16); - leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 + leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 leg3->setPos(2, (float)(12 + yo), -4); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - hair->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + hair->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); } -CreeperModel::CreeperModel() : Model() -{ - _init(0); -} +CreeperModel::CreeperModel() : Model() { _init(0); } -CreeperModel::CreeperModel(float g) : Model() -{ - _init(g); -} +CreeperModel::CreeperModel(float g) : Model() { _init(g); } -void CreeperModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void CreeperModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); head->render(scale, usecompiled); @@ -68,10 +63,11 @@ void CreeperModel::render(std::shared_ptr entity, float time, float r, f leg3->render(scale, usecompiled); } -void CreeperModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); +void CreeperModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; diff --git a/Minecraft.Client/Rendering/Models/CreeperModel.h b/Minecraft.Client/Rendering/Models/CreeperModel.h index 0c4e9448e..cb5843522 100644 --- a/Minecraft.Client/Rendering/Models/CreeperModel.h +++ b/Minecraft.Client/Rendering/Models/CreeperModel.h @@ -1,14 +1,17 @@ #pragma once #include "Model.h" -class CreeperModel : public Model -{ +class CreeperModel : public Model { public: - ModelPart *head, *hair, *body, *leg0, *leg1, *leg2, *leg3; + ModelPart *head, *hair, *body, *leg0, *leg1, *leg2, *leg3; - void _init(float g); // 4J added + void _init(float g); // 4J added CreeperModel(); CreeperModel(float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/DragonModel.cpp b/Minecraft.Client/Rendering/Models/DragonModel.cpp index 9f85bed2e..59ec47a5d 100644 --- a/Minecraft.Client/Rendering/Models/DragonModel.cpp +++ b/Minecraft.Client/Rendering/Models/DragonModel.cpp @@ -3,246 +3,248 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Entities/Mobs/EnderDragon.h" -DragonModel::DragonModel(float g) : Model() -{ - // 4J-PB - texWidth = 256; - texHeight = 256; +DragonModel::DragonModel(float g) : Model() { + // 4J-PB + texWidth = 256; + texHeight = 256; - setMapTex(L"body.body", 0, 0); - setMapTex(L"wing.skin", -56, 88); - setMapTex(L"wingtip.skin", -56, 144); - setMapTex(L"rearleg.main", 0, 0); - setMapTex(L"rearfoot.main", 112, 0); - setMapTex(L"rearlegtip.main", 196, 0); - setMapTex(L"head.upperhead", 112, 30); - setMapTex(L"wing.bone", 112, 88); - setMapTex(L"head.upperlip", 176, 44); - setMapTex(L"jaw.jaw", 176, 65); - setMapTex(L"frontleg.main", 112, 104); - setMapTex(L"wingtip.bone", 112, 136); - setMapTex(L"frontfoot.main", 144, 104); - setMapTex(L"neck.box", 192, 104); - setMapTex(L"frontlegtip.main", 226, 138); - setMapTex(L"body.scale", 220, 53); - setMapTex(L"head.scale", 0, 0); - setMapTex(L"neck.scale", 48, 0); - setMapTex(L"head.nostril", 112, 0); + setMapTex(L"body.body", 0, 0); + setMapTex(L"wing.skin", -56, 88); + setMapTex(L"wingtip.skin", -56, 144); + setMapTex(L"rearleg.main", 0, 0); + setMapTex(L"rearfoot.main", 112, 0); + setMapTex(L"rearlegtip.main", 196, 0); + setMapTex(L"head.upperhead", 112, 30); + setMapTex(L"wing.bone", 112, 88); + setMapTex(L"head.upperlip", 176, 44); + setMapTex(L"jaw.jaw", 176, 65); + setMapTex(L"frontleg.main", 112, 104); + setMapTex(L"wingtip.bone", 112, 136); + setMapTex(L"frontfoot.main", 144, 104); + setMapTex(L"neck.box", 192, 104); + setMapTex(L"frontlegtip.main", 226, 138); + setMapTex(L"body.scale", 220, 53); + setMapTex(L"head.scale", 0, 0); + setMapTex(L"neck.scale", 48, 0); + setMapTex(L"head.nostril", 112, 0); - float zo = -16; - head = new ModelPart(this, L"head"); - head->addBox(L"upperlip", -6, -1, -8 + zo, 12, 5, 16); - head->addBox(L"upperhead", -8, -8, 6 + zo, 16, 16, 16); - head->bMirror = true; - head->addBox(L"scale", -1 - 4, -12, 12 + zo, 2, 4, 6); - head->addBox(L"nostril", -1 - 4, -3, -6 + zo, 2, 2, 4); - head->bMirror = false; - head->addBox(L"scale", -1 + 4, -12, 12 + zo, 2, 4, 6); - head->addBox(L"nostril", -1 + 4, -3, -6 + zo, 2, 2, 4); + float zo = -16; + head = new ModelPart(this, L"head"); + head->addBox(L"upperlip", -6, -1, -8 + zo, 12, 5, 16); + head->addBox(L"upperhead", -8, -8, 6 + zo, 16, 16, 16); + head->bMirror = true; + head->addBox(L"scale", -1 - 4, -12, 12 + zo, 2, 4, 6); + head->addBox(L"nostril", -1 - 4, -3, -6 + zo, 2, 2, 4); + head->bMirror = false; + head->addBox(L"scale", -1 + 4, -12, 12 + zo, 2, 4, 6); + head->addBox(L"nostril", -1 + 4, -3, -6 + zo, 2, 2, 4); - jaw = new ModelPart(this, L"jaw"); - jaw->setPos(0, 4, 8 + zo); - jaw->addBox(L"jaw", -6, 0, -16, 12, 4, 16); - head->addChild(jaw); + jaw = new ModelPart(this, L"jaw"); + jaw->setPos(0, 4, 8 + zo); + jaw->addBox(L"jaw", -6, 0, -16, 12, 4, 16); + head->addChild(jaw); - neck = new ModelPart(this, L"neck"); - neck->addBox(L"box", -5, -5, -5, 10, 10, 10); - neck->addBox(L"scale", -1, -9, -5 + 2, 2, 4, 6); + neck = new ModelPart(this, L"neck"); + neck->addBox(L"box", -5, -5, -5, 10, 10, 10); + neck->addBox(L"scale", -1, -9, -5 + 2, 2, 4, 6); - body = new ModelPart(this, L"body"); - body->setPos(0, 4, 8); - body->addBox(L"body", -12, 0, -16, 24, 24, 64); - body->addBox(L"scale", -1, -6, -10 + 20 * 0, 2, 6, 12); - body->addBox(L"scale", -1, -6, -10 + 20 * 1, 2, 6, 12); - body->addBox(L"scale", -1, -6, -10 + 20 * 2, 2, 6, 12); + body = new ModelPart(this, L"body"); + body->setPos(0, 4, 8); + body->addBox(L"body", -12, 0, -16, 24, 24, 64); + body->addBox(L"scale", -1, -6, -10 + 20 * 0, 2, 6, 12); + body->addBox(L"scale", -1, -6, -10 + 20 * 1, 2, 6, 12); + body->addBox(L"scale", -1, -6, -10 + 20 * 2, 2, 6, 12); - wing = new ModelPart(this, L"wing"); - wing->setPos(-12, 5, 2); - wing->addBox(L"bone", -56, -4, -4, 56, 8, 8); - wing->addBox(L"skin", -56, 0, +2, 56, 0, 56); - wingTip = new ModelPart(this, L"wingtip"); - wingTip->setPos(-56, 0, 0); - wingTip->addBox(L"bone", -56, -2, -2, 56, 4, 4); - wingTip->addBox(L"skin", -56, 0, +2, 56, 0, 56); - wing->addChild(wingTip); + wing = new ModelPart(this, L"wing"); + wing->setPos(-12, 5, 2); + wing->addBox(L"bone", -56, -4, -4, 56, 8, 8); + wing->addBox(L"skin", -56, 0, +2, 56, 0, 56); + wingTip = new ModelPart(this, L"wingtip"); + wingTip->setPos(-56, 0, 0); + wingTip->addBox(L"bone", -56, -2, -2, 56, 4, 4); + wingTip->addBox(L"skin", -56, 0, +2, 56, 0, 56); + wing->addChild(wingTip); - frontLeg = new ModelPart(this, L"frontleg"); - frontLeg->setPos(-12, 20, 2); - frontLeg->addBox(L"main", -4, -4, -4, 8, 24, 8); - frontLegTip = new ModelPart(this, L"frontlegtip"); - frontLegTip->setPos(0, 20, -1); - frontLegTip->addBox(L"main", -3, -1, -3, 6, 24, 6); - frontLeg->addChild(frontLegTip); - frontFoot = new ModelPart(this, L"frontfoot"); - frontFoot->setPos(0, 23, 0); - frontFoot->addBox(L"main", -4, 0, -12, 8, 4, 16); - frontLegTip->addChild(frontFoot); + frontLeg = new ModelPart(this, L"frontleg"); + frontLeg->setPos(-12, 20, 2); + frontLeg->addBox(L"main", -4, -4, -4, 8, 24, 8); + frontLegTip = new ModelPart(this, L"frontlegtip"); + frontLegTip->setPos(0, 20, -1); + frontLegTip->addBox(L"main", -3, -1, -3, 6, 24, 6); + frontLeg->addChild(frontLegTip); + frontFoot = new ModelPart(this, L"frontfoot"); + frontFoot->setPos(0, 23, 0); + frontFoot->addBox(L"main", -4, 0, -12, 8, 4, 16); + frontLegTip->addChild(frontFoot); - rearLeg = new ModelPart(this, L"rearleg"); - rearLeg->setPos(-12 - 4, 16, 2 + 40); - rearLeg->addBox(L"main", -8, -4, -8, 16, 32, 16); - rearLegTip = new ModelPart(this, L"rearlegtip"); - rearLegTip->setPos(0, 32, -4); - rearLegTip->addBox(L"main", -6, -2, 0, 12, 32, 12); - rearLeg->addChild(rearLegTip); - rearFoot = new ModelPart(this, L"rearfoot"); - rearFoot->setPos(0, 31, 4); - rearFoot->addBox(L"main", -9, 0, -20, 18, 6, 24); - rearLegTip->addChild(rearFoot); + rearLeg = new ModelPart(this, L"rearleg"); + rearLeg->setPos(-12 - 4, 16, 2 + 40); + rearLeg->addBox(L"main", -8, -4, -8, 16, 32, 16); + rearLegTip = new ModelPart(this, L"rearlegtip"); + rearLegTip->setPos(0, 32, -4); + rearLegTip->addBox(L"main", -6, -2, 0, 12, 32, 12); + rearLeg->addChild(rearLegTip); + rearFoot = new ModelPart(this, L"rearfoot"); + rearFoot->setPos(0, 31, 4); + rearFoot->addBox(L"main", -9, 0, -20, 18, 6, 24); + rearLegTip->addChild(rearFoot); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - head->compile(1.0f/16.0f); - jaw->compile(1.0f/16.0f); - neck->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - wing->compile(1.0f/16.0f); - wingTip->compile(1.0f/16.0f); - frontLeg->compile(1.0f/16.0f); - frontLegTip->compile(1.0f/16.0f); - frontFoot->compile(1.0f/16.0f); - rearLeg->compile(1.0f/16.0f); - rearLegTip->compile(1.0f/16.0f); - rearFoot->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here + head->compile(1.0f / 16.0f); + jaw->compile(1.0f / 16.0f); + neck->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + wing->compile(1.0f / 16.0f); + wingTip->compile(1.0f / 16.0f); + frontLeg->compile(1.0f / 16.0f); + frontLegTip->compile(1.0f / 16.0f); + frontFoot->compile(1.0f / 16.0f); + rearLeg->compile(1.0f / 16.0f); + rearLegTip->compile(1.0f / 16.0f); + rearFoot->compile(1.0f / 16.0f); } -void DragonModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - this->a = a; +void DragonModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { + this->a = a; } -void DragonModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - glPushMatrix(); - std::shared_ptr dragon = std::dynamic_pointer_cast(entity); +void DragonModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + glPushMatrix(); + std::shared_ptr dragon = + std::dynamic_pointer_cast(entity); - float ttt = dragon->oFlapTime + (dragon->flapTime - dragon->oFlapTime) * a; - jaw->xRot = (float) (Mth::sin(ttt * PI * 2) + 1) * 0.2f; + float ttt = dragon->oFlapTime + (dragon->flapTime - dragon->oFlapTime) * a; + jaw->xRot = (float)(Mth::sin(ttt * PI * 2) + 1) * 0.2f; - float yo = (float) (Mth::sin(ttt * PI * 2 - 1) + 1); - yo = (yo * yo * 1 + yo * 2) * 0.05f; + float yo = (float)(Mth::sin(ttt * PI * 2 - 1) + 1); + yo = (yo * yo * 1 + yo * 2) * 0.05f; - glTranslatef(0, yo - 2.0f, -3); - glRotatef(yo * 2, 1, 0, 0); + glTranslatef(0, yo - 2.0f, -3); + glRotatef(yo * 2, 1, 0, 0); - float yy = -30.0f; - float zz = 22.0f; - float xx = 0.0f; + float yy = -30.0f; + float zz = 22.0f; + float xx = 0.0f; - float rotScale = 1.5f; + float rotScale = 1.5f; + double startComponents[3]; + doubleArray start = doubleArray(startComponents, 3); + dragon->getLatencyPos(start, 6, a); - double startComponents[3]; - doubleArray start = doubleArray(startComponents,3); - dragon->getLatencyPos(start, 6, a); + double latencyPosAComponents[3], latencyPosBComponents[3]; + doubleArray latencyPosA = doubleArray(latencyPosAComponents, 3); + doubleArray latencyPosB = doubleArray(latencyPosBComponents, 3); + dragon->getLatencyPos(latencyPosA, 5, a); + dragon->getLatencyPos(latencyPosB, 10, a); + float rot2 = rotWrap(latencyPosA[0] - latencyPosB[0]); + float rot = rotWrap(latencyPosA[0] + rot2 / 2); - double latencyPosAComponents[3], latencyPosBComponents[3]; - doubleArray latencyPosA = doubleArray( latencyPosAComponents, 3 ); - doubleArray latencyPosB = doubleArray( latencyPosBComponents, 3 ); - dragon->getLatencyPos(latencyPosA, 5, a); - dragon->getLatencyPos(latencyPosB, 10, a); - float rot2 = rotWrap(latencyPosA[0] - latencyPosB[0]); - float rot = rotWrap(latencyPosA[0] + rot2 / 2); + yy += 2.0f; - yy += 2.0f; + float rr = 0; + float roff = ttt * PI * 2.0f; + yy = 20.0f; + zz = -12.0f; + double pComponents[3]; + doubleArray p = doubleArray(pComponents, 3); - float rr = 0; - float roff = ttt * PI * 2.0f; - yy = 20.0f; - zz = -12.0f; - double pComponents[3]; - doubleArray p = doubleArray(pComponents,3); + for (int i = 0; i < 5; i++) { + dragon->getLatencyPos(p, 5 - i, a); - for (int i = 0; i < 5; i++) - { - dragon->getLatencyPos(p, 5 - i, a); + rr = (float)Mth::cos(i * 0.45f + roff) * 0.15f; + neck->yRot = rotWrap(dragon->getHeadPartYRotDiff(i, start, p)) * PI / + 180.0f * rotScale; // 4J replaced "p[0] - start[0] with + // call to getHeadPartYRotDiff + neck->xRot = rr + (float)(dragon->getHeadPartYOffset(i, start, p)) * + PI / 180.0f * rotScale * + 5.0f; // 4J replaced "p[1] - start[1]" with call + // to getHeadPartYOffset + neck->zRot = -rotWrap(p[0] - rot) * PI / 180.0f * rotScale; - rr = (float) Mth::cos(i * 0.45f + roff) * 0.15f; - neck->yRot = rotWrap(dragon->getHeadPartYRotDiff(i, start, p)) * PI / 180.0f * rotScale; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff - neck->xRot = rr + (float) (dragon->getHeadPartYOffset(i, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J replaced "p[1] - start[1]" with call to getHeadPartYOffset - neck->zRot = -rotWrap(p[0] - rot) * PI / 180.0f * rotScale; + neck->y = yy; + neck->z = zz; + neck->x = xx; + yy += Mth::sin(neck->xRot) * 10.0f; + zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; + xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; + neck->render(scale, usecompiled); + } - neck->y = yy; - neck->z = zz; - neck->x = xx; - yy += Mth::sin(neck->xRot) * 10.0f; - zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; - xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10.0f; - neck->render(scale,usecompiled); - } + head->y = yy; + head->z = zz; + head->x = xx; + dragon->getLatencyPos(p, 0, a); + head->yRot = + rotWrap(dragon->getHeadPartYRotDiff(6, start, p)) * PI / 180.0f * + 1; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff + head->xRot = (float)(dragon->getHeadPartYOffset(6, start, p)) * PI / + 180.0f * rotScale * 5.0f; // 4J Added + head->zRot = -rotWrap(p[0] - rot) * PI / 180 * 1; + head->render(scale, usecompiled); + glPushMatrix(); + glTranslatef(0, 1, 0); + glRotatef(-(float)(rot2)*rotScale * 1, 0, 0, 1); + glTranslatef(0, -1, 0); + body->zRot = 0; + body->render(scale, usecompiled); - head->y = yy; - head->z = zz; - head->x = xx; - dragon->getLatencyPos(p, 0, a); - head->yRot = rotWrap(dragon->getHeadPartYRotDiff(6, start, p)) * PI / 180.0f * 1; // 4J replaced "p[0] - start[0] with call to getHeadPartYRotDiff - head->xRot = (float) (dragon->getHeadPartYOffset(6, start, p)) * PI / 180.0f * rotScale * 5.0f; // 4J Added - head->zRot = -rotWrap(p[0] - rot) * PI / 180 * 1; - head->render(scale,usecompiled); - glPushMatrix(); - glTranslatef(0, 1, 0); - glRotatef(-(float) (rot2) * rotScale * 1, 0, 0, 1); - glTranslatef(0, -1, 0); - body->zRot = 0; - body->render(scale,usecompiled); - - glEnable(GL_CULL_FACE); - for (int i = 0; i < 2; i++) - { - float flapTime = ttt * PI * 2; - wing->xRot = 0.125f - (float) (Mth::cos(flapTime)) * 0.2f; - wing->yRot = 0.25f; - wing->zRot = (float) (Mth::sin(flapTime) + 0.125f) * 0.8f; - wingTip->zRot = -(float) (Mth::sin(flapTime + 2.0f) + 0.5f) * 0.75f; + glEnable(GL_CULL_FACE); + for (int i = 0; i < 2; i++) { + float flapTime = ttt * PI * 2; + wing->xRot = 0.125f - (float)(Mth::cos(flapTime)) * 0.2f; + wing->yRot = 0.25f; + wing->zRot = (float)(Mth::sin(flapTime) + 0.125f) * 0.8f; + wingTip->zRot = -(float)(Mth::sin(flapTime + 2.0f) + 0.5f) * 0.75f; - rearLeg->xRot = 1.0f + yo * 0.1f; - rearLegTip->xRot = 0.5f + yo * 0.1f; - rearFoot->xRot = 0.75f + yo * 0.1f; + rearLeg->xRot = 1.0f + yo * 0.1f; + rearLegTip->xRot = 0.5f + yo * 0.1f; + rearFoot->xRot = 0.75f + yo * 0.1f; - frontLeg->xRot = 1.3f + yo * 0.1f; - frontLegTip->xRot = -0.5f - yo * 0.1f; - frontFoot->xRot = 0.75f + yo * 0.1f; - wing->render(scale,usecompiled); - frontLeg->render(scale,usecompiled); - rearLeg->render(scale,usecompiled); - glScalef(-1, 1, 1); - if (i == 0) - { - glCullFace(GL_FRONT); - } - } - glPopMatrix(); - glCullFace(GL_BACK); - glDisable(GL_CULL_FACE); + frontLeg->xRot = 1.3f + yo * 0.1f; + frontLegTip->xRot = -0.5f - yo * 0.1f; + frontFoot->xRot = 0.75f + yo * 0.1f; + wing->render(scale, usecompiled); + frontLeg->render(scale, usecompiled); + rearLeg->render(scale, usecompiled); + glScalef(-1, 1, 1); + if (i == 0) { + glCullFace(GL_FRONT); + } + } + glPopMatrix(); + glCullFace(GL_BACK); + glDisable(GL_CULL_FACE); - rr = -(float) Mth::sin(ttt * PI * 2) * 0.0f; - roff = ttt * PI * 2; - yy = 10; - zz = 60; - xx = 0; - dragon->getLatencyPos(start, 11, a); - for (int i = 0; i < 12; i++) - { - dragon->getLatencyPos(p, 12 + i, a); - rr += Mth::sin(i * 0.45f + roff) * 0.05f; - neck->yRot = (rotWrap(p[0] - start[0]) * rotScale + 180) * PI / 180; - neck->xRot = rr + (float) (p[1] - start[1]) * PI / 180 * rotScale * 5; - neck->zRot = rotWrap(p[0] - rot) * PI / 180 * rotScale; - neck->y = yy; - neck->z = zz; - neck->x = xx; - yy += Mth::sin(neck->xRot) * 10; - zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10; - xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10; - neck->render(scale,usecompiled); - } - glPopMatrix(); + rr = -(float)Mth::sin(ttt * PI * 2) * 0.0f; + roff = ttt * PI * 2; + yy = 10; + zz = 60; + xx = 0; + dragon->getLatencyPos(start, 11, a); + for (int i = 0; i < 12; i++) { + dragon->getLatencyPos(p, 12 + i, a); + rr += Mth::sin(i * 0.45f + roff) * 0.05f; + neck->yRot = (rotWrap(p[0] - start[0]) * rotScale + 180) * PI / 180; + neck->xRot = rr + (float)(p[1] - start[1]) * PI / 180 * rotScale * 5; + neck->zRot = rotWrap(p[0] - rot) * PI / 180 * rotScale; + neck->y = yy; + neck->z = zz; + neck->x = xx; + yy += Mth::sin(neck->xRot) * 10; + zz -= Mth::cos(neck->yRot) * Mth::cos(neck->xRot) * 10; + xx -= Mth::sin(neck->yRot) * Mth::cos(neck->xRot) * 10; + neck->render(scale, usecompiled); + } + glPopMatrix(); } -float DragonModel::rotWrap(double d) -{ - while (d >= 180) - d -= 360; - while (d < -180) - d += 360; - return (float) d; +float DragonModel::rotWrap(double d) { + while (d >= 180) d -= 360; + while (d < -180) d += 360; + return (float)d; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/DragonModel.h b/Minecraft.Client/Rendering/Models/DragonModel.h index baee83dec..e52112e80 100644 --- a/Minecraft.Client/Rendering/Models/DragonModel.h +++ b/Minecraft.Client/Rendering/Models/DragonModel.h @@ -2,34 +2,34 @@ #include "Model.h" #include "ModelPart.h" -class DragonModel : public Model -{ +class DragonModel : public Model { public: - static const int MODEL_ID = 4; + static const int MODEL_ID = 4; private: - ModelPart *head; - ModelPart *neck; - ModelPart *jaw; - ModelPart *body; - ModelPart *rearLeg; - ModelPart *frontLeg; - ModelPart *rearLegTip; - ModelPart *frontLegTip; - ModelPart *rearFoot; - ModelPart *frontFoot; - ModelPart *wing; - ModelPart *wingTip; - float a; + ModelPart* head; + ModelPart* neck; + ModelPart* jaw; + ModelPart* body; + ModelPart* rearLeg; + ModelPart* frontLeg; + ModelPart* rearLegTip; + ModelPart* frontLegTip; + ModelPart* rearFoot; + ModelPart* frontFoot; + ModelPart* wing; + ModelPart* wingTip; + float a; public: - - ModelPart *cubes[5]; + ModelPart* cubes[5]; DragonModel(float g); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); private: - float rotWrap(double d); - + float rotWrap(double d); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp b/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp index 05cb52e2c..3d6cf075b 100644 --- a/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp +++ b/Minecraft.Client/Rendering/Models/EnderCrystalModel.cpp @@ -1,44 +1,42 @@ #include "../../Platform/stdafx.h" #include "EnderCrystalModel.h" +EnderCrystalModel::EnderCrystalModel(float g) { + glass = new ModelPart(this, L"glass"); + glass->texOffs(0, 0)->addBox(-4, -4, -4, 8, 8, 8); + cube = new ModelPart(this, L"cube"); + cube->texOffs(32, 0)->addBox(-4, -4, -4, 8, 8, 8); -EnderCrystalModel::EnderCrystalModel(float g) -{ - glass = new ModelPart(this, L"glass"); - glass->texOffs(0, 0)->addBox(-4, -4, -4, 8, 8, 8); + base = new ModelPart(this, L"base"); + base->texOffs(0, 16)->addBox(-6, 0, -6, 12, 4, 12); - cube = new ModelPart(this, L"cube"); - cube->texOffs(32, 0)->addBox(-4, -4, -4, 8, 8, 8); - - base = new ModelPart(this, L"base"); - base->texOffs(0, 16)->addBox(-6, 0, -6, 12, 4, 12); - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - glass->compile(1.0f/16.0f); - cube->compile(1.0f/16.0f); - base->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + glass->compile(1.0f / 16.0f); + cube->compile(1.0f / 16.0f); + base->compile(1.0f / 16.0f); } - -void EnderCrystalModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - glPushMatrix(); - glScalef(2, 2, 2); - glTranslatef(0, -0.5f, 0); - base->render(scale,usecompiled); - glRotatef(r, 0, 1, 0); - glTranslatef(0, 0.8f + bob, 0); - glRotatef(60, 0.7071f, 0, 0.7071f); - glass->render(scale,usecompiled); - float ss = 14 / 16.0f; - glScalef(ss, ss, ss); - glRotatef(60, 0.7071f, 0, 0.7071f); - glRotatef(r, 0, 1, 0); - glass->render(scale,usecompiled); - glScalef(ss, ss, ss); - glRotatef(60, 0.7071f, 0, 0.7071f); - glRotatef(r, 0, 1, 0); - cube->render(scale,usecompiled); - glPopMatrix(); +void EnderCrystalModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + glPushMatrix(); + glScalef(2, 2, 2); + glTranslatef(0, -0.5f, 0); + base->render(scale, usecompiled); + glRotatef(r, 0, 1, 0); + glTranslatef(0, 0.8f + bob, 0); + glRotatef(60, 0.7071f, 0, 0.7071f); + glass->render(scale, usecompiled); + float ss = 14 / 16.0f; + glScalef(ss, ss, ss); + glRotatef(60, 0.7071f, 0, 0.7071f); + glRotatef(r, 0, 1, 0); + glass->render(scale, usecompiled); + glScalef(ss, ss, ss); + glRotatef(60, 0.7071f, 0, 0.7071f); + glRotatef(r, 0, 1, 0); + cube->render(scale, usecompiled); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderCrystalModel.h b/Minecraft.Client/Rendering/Models/EnderCrystalModel.h index 42ae1b3d1..ead865977 100644 --- a/Minecraft.Client/Rendering/Models/EnderCrystalModel.h +++ b/Minecraft.Client/Rendering/Models/EnderCrystalModel.h @@ -2,17 +2,18 @@ #include "Model.h" #include "ModelPart.h" -class EnderCrystalModel : public Model -{ +class EnderCrystalModel : public Model { public: - static const int MODEL_ID = 1; + static const int MODEL_ID = 1; private: - ModelPart *cube; - ModelPart *glass; - ModelPart *base; + ModelPart* cube; + ModelPart* glass; + ModelPart* base; public: - EnderCrystalModel(float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + EnderCrystalModel(float g); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderManModel.cpp b/Minecraft.Client/Rendering/Models/EnderManModel.cpp index 81816d05b..377f0a874 100644 --- a/Minecraft.Client/Rendering/Models/EnderManModel.cpp +++ b/Minecraft.Client/Rendering/Models/EnderManModel.cpp @@ -2,120 +2,116 @@ #include "EnderManModel.h" #include "ModelPart.h" -EndermanModel::EndermanModel() : HumanoidModel(0, -14, 64, 32) -{ - carrying = false; - creepy = false; +EndermanModel::EndermanModel() : HumanoidModel(0, -14, 64, 32) { + carrying = false; + creepy = false; - float yOffset = -14.0f; - float g = 0; + float yOffset = -14.0f; + float g = 0; - delete hair; - hair = new ModelPart(this, 0, 16); - hair->addBox(-4.0f, -8.0f, -4.0f, 8, 8, 8, g - 0.5f); // Head - hair->setPos(0.0f, 0.0f + yOffset, 0.0f); + delete hair; + hair = new ModelPart(this, 0, 16); + hair->addBox(-4.0f, -8.0f, -4.0f, 8, 8, 8, g - 0.5f); // Head + hair->setPos(0.0f, 0.0f + yOffset, 0.0f); - delete body; - body = new ModelPart(this, 32, 16); - body->addBox(-4.0f, 0.0f, -2.0f, 8, 12, 4, g); // Body - body->setPos(0.0f, 0.0f + yOffset, 0.0f); + delete body; + body = new ModelPart(this, 32, 16); + body->addBox(-4.0f, 0.0f, -2.0f, 8, 12, 4, g); // Body + body->setPos(0.0f, 0.0f + yOffset, 0.0f); + delete arm0; + arm0 = new ModelPart(this, 56, 0); + arm0->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm0 + arm0->setPos(-3.0f, 2.0f + yOffset, 0.0f); - delete arm0; - arm0 = new ModelPart(this, 56, 0); - arm0->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm0 - arm0->setPos(-3.0f, 2.0f + yOffset, 0.0f); + delete arm1; + arm1 = new ModelPart(this, 56, 0); + arm1->bMirror = true; + arm1->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm1 + arm1->setPos(5.0f, 2.0f + yOffset, 0.0f); + delete leg0; + leg0 = new ModelPart(this, 56, 0); + leg0->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg0 + leg0->setPos(-2.0f, 12.0f + yOffset, 0.0f); - delete arm1; - arm1 = new ModelPart(this, 56, 0); - arm1->bMirror = true; - arm1->addBox(-1.0f, -2.0f, -1.0f, 2, 30, 2, g); // Arm1 - arm1->setPos(5.0f, 2.0f + yOffset, 0.0f); - - delete leg0; - leg0 = new ModelPart(this, 56, 0); - leg0->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg0 - leg0->setPos(-2.0f, 12.0f + yOffset, 0.0f); - - delete leg1; - leg1 = new ModelPart(this, 56, 0); - leg1->bMirror = true; - leg1->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg1 - leg1->setPos(2.0f, 12.0f + yOffset, 0.0f); - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - body->compile(1.0f/16.0f); - arm0->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - hair->compile(1.0f/16.0f); + delete leg1; + leg1 = new ModelPart(this, 56, 0); + leg1->bMirror = true; + leg1->addBox(-1.0f, 0.0f, -1.0f, 2, 30, 2, g); // Leg1 + leg1->setPos(2.0f, 12.0f + yOffset, 0.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + body->compile(1.0f / 16.0f); + arm0->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + hair->compile(1.0f / 16.0f); } -void EndermanModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); +void EndermanModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); - head->visible = true; + head->visible = true; - float yOffs = -14.0f; - body->xRot = 0.0f; - body->y = yOffs; - body->z = -0.0f; + float yOffs = -14.0f; + body->xRot = 0.0f; + body->y = yOffs; + body->z = -0.0f; - leg0->xRot -= 0.0f; - leg1->xRot -= 0.0f; + leg0->xRot -= 0.0f; + leg1->xRot -= 0.0f; - arm0->xRot *= 0.5f; - arm1->xRot *= 0.5f; - leg0->xRot *= 0.5f; - leg1->xRot *= 0.5f; + arm0->xRot *= 0.5f; + arm1->xRot *= 0.5f; + leg0->xRot *= 0.5f; + leg1->xRot *= 0.5f; - float max = 0.4f; - if (arm0->xRot > +max) arm0->xRot = +max; - if (arm1->xRot > +max) arm1->xRot = +max; - if (arm0->xRot < -max) arm0->xRot = -max; - if (arm1->xRot < -max) arm1->xRot = -max; - if (leg0->xRot > +max) leg0->xRot = +max; - if (leg1->xRot > +max) leg1->xRot = +max; - if (leg0->xRot < -max) leg0->xRot = -max; - if (leg1->xRot < -max) leg1->xRot = -max; + float max = 0.4f; + if (arm0->xRot > +max) arm0->xRot = +max; + if (arm1->xRot > +max) arm1->xRot = +max; + if (arm0->xRot < -max) arm0->xRot = -max; + if (arm1->xRot < -max) arm1->xRot = -max; + if (leg0->xRot > +max) leg0->xRot = +max; + if (leg1->xRot > +max) leg1->xRot = +max; + if (leg0->xRot < -max) leg0->xRot = -max; + if (leg1->xRot < -max) leg1->xRot = -max; + if (carrying) { + arm0->xRot = -0.5f; + arm1->xRot = -0.5f; + arm0->zRot = 0.05f; + arm1->zRot = -0.05f; + } - if (carrying) - { - arm0->xRot = -0.5f; - arm1->xRot = -0.5f; - arm0->zRot = 0.05f; - arm1->zRot = -0.05f; - } + arm0->z = -0.0f; + arm1->z = -0.0f; + leg0->z = -0.0f; + leg1->z = -0.0f; - arm0->z = -0.0f; - arm1->z = -0.0f; - leg0->z = -0.0f; - leg1->z = -0.0f; + arm0->y = 2.0f + yOffs; + arm1->y = 2.0f + yOffs; - arm0->y = 2.0f + yOffs; - arm1->y = 2.0f + yOffs; + leg0->y = +9.0f + yOffs; + leg1->y = +9.0f + yOffs; - leg0->y = +9.0f + yOffs; - leg1->y = +9.0f + yOffs; + head->z = -0.0f; + head->y = +yOffs + 1; - head->z = -0.0f; - head->y = +yOffs + 1; + hair->x = head->x; + hair->y = head->y; + hair->z = head->z; + hair->xRot = head->xRot; + hair->yRot = head->yRot; + hair->zRot = head->zRot; - hair->x = head->x; - hair->y = head->y; - hair->z = head->z; - hair->xRot = head->xRot; - hair->yRot = head->yRot; - hair->zRot = head->zRot; - - if (creepy) - { - float amt = 1; - head->y -= (float) (amt * 5); - } + if (creepy) { + float amt = 1; + head->y -= (float)(amt * 5); + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/EnderManModel.h b/Minecraft.Client/Rendering/Models/EnderManModel.h index 3760e7968..a1a8ebce6 100644 --- a/Minecraft.Client/Rendering/Models/EnderManModel.h +++ b/Minecraft.Client/Rendering/Models/EnderManModel.h @@ -2,12 +2,13 @@ #include "HumanoidModel.h" -class EndermanModel : public HumanoidModel -{ +class EndermanModel : public HumanoidModel { public: - bool carrying; - bool creepy; + bool carrying; + bool creepy; - EndermanModel(); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + EndermanModel(); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/GhastModel.cpp b/Minecraft.Client/Rendering/Models/GhastModel.cpp index b5f64fd21..5f8f70153 100644 --- a/Minecraft.Client/Rendering/Models/GhastModel.cpp +++ b/Minecraft.Client/Rendering/Models/GhastModel.cpp @@ -4,16 +4,15 @@ #include "GhastModel.h" #include "ModelPart.h" -GhastModel::GhastModel() : Model() -{ +GhastModel::GhastModel() : Model() { int yoffs = -16; body = new ModelPart(this, 0, 0); body->addBox(-8, -8, -8, 16, 16, 16); body->y += (8 + 16) + yoffs; - Random *random = new Random(1660); - for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length - { + Random* random = new Random(1660); + for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length + { tentacles[i] = new ModelPart(this, 0, 0); float xo = (((i % 3 - (i / 3 % 2) * 0.5f + 0.25f) / 2.0f * 2 - 1) * 5); @@ -26,34 +25,36 @@ GhastModel::GhastModel() : Model() tentacles[i]->y = (float)(31 + yoffs); } - // 4J added - compile now to avoid random performance hit first time cubes are rendered - body->compile(1.0f/16.0f); - for( int i = 0; i < TENTACLESLENGTH; i++ ) - { - tentacles[i]->compile(1.0f/16.0f); - } + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + body->compile(1.0f / 16.0f); + for (int i = 0; i < TENTACLESLENGTH; i++) { + tentacles[i]->compile(1.0f / 16.0f); + } } -void GhastModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length - { +void GhastModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length + { tentacles[i]->xRot = 0.2f * Mth::sin(bob * 0.3f + i) + 0.4f; } } -void GhastModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void GhastModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - glPushMatrix(); - glTranslatef(0, .6f, 0); + glPushMatrix(); + glTranslatef(0, .6f, 0); body->render(scale, usecompiled); - for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length - { + for (int i = 0; i < TENTACLESLENGTH; i++) // 4J - 9 was tentacles.length + { tentacles[i]->render(scale, usecompiled); } - glPopMatrix(); + glPopMatrix(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/GhastModel.h b/Minecraft.Client/Rendering/Models/GhastModel.h index 59ce7b7df..610152766 100644 --- a/Minecraft.Client/Rendering/Models/GhastModel.h +++ b/Minecraft.Client/Rendering/Models/GhastModel.h @@ -1,14 +1,17 @@ #pragma once #include "Model.h" -class GhastModel : public Model -{ +class GhastModel : public Model { public: - static const int TENTACLESLENGTH=9; - ModelPart *body; - ModelPart *tentacles[TENTACLESLENGTH]; + static const int TENTACLESLENGTH = 9; + ModelPart* body; + ModelPart* tentacles[TENTACLESLENGTH]; GhastModel(); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/HumanoidModel.cpp b/Minecraft.Client/Rendering/Models/HumanoidModel.cpp index a548edf8c..ef4d78f95 100644 --- a/Minecraft.Client/Rendering/Models/HumanoidModel.cpp +++ b/Minecraft.Client/Rendering/Models/HumanoidModel.cpp @@ -4,438 +4,419 @@ #include "../../../Minecraft.World/Entities/Entity.h" #include "ModelPart.h" -// 4J added +// 4J added -ModelPart * HumanoidModel::AddOrRetrievePart(SKIN_BOX *pBox) -{ - ModelPart *pAttachTo=NULL; +ModelPart* HumanoidModel::AddOrRetrievePart(SKIN_BOX* pBox) { + ModelPart* pAttachTo = NULL; - switch(pBox->ePart) - { - case eBodyPart_Head: - pAttachTo=head; - break; - case eBodyPart_Body: - pAttachTo=body; - break; - case eBodyPart_Arm0: - pAttachTo=arm0; - break; - case eBodyPart_Arm1: - pAttachTo=arm1; - break; - case eBodyPart_Leg0: - pAttachTo=leg0; - break; - case eBodyPart_Leg1: - pAttachTo=leg1; - break; - case eBodyPart_Unknown: - default: - return NULL; - } + switch (pBox->ePart) { + case eBodyPart_Head: + pAttachTo = head; + break; + case eBodyPart_Body: + pAttachTo = body; + break; + case eBodyPart_Arm0: + pAttachTo = arm0; + break; + case eBodyPart_Arm1: + pAttachTo = arm1; + break; + case eBodyPart_Leg0: + pAttachTo = leg0; + break; + case eBodyPart_Leg1: + pAttachTo = leg1; + break; + case eBodyPart_Unknown: + default: + return NULL; + } - // first check this box doesn't already exist - ModelPart *pNewBox = pAttachTo->retrieveChild(pBox); + // first check this box doesn't already exist + ModelPart* pNewBox = pAttachTo->retrieveChild(pBox); - if(pNewBox) - { - if((pNewBox->getfU()!=(int)pBox->fU) || (pNewBox->getfV()!=(int)pBox->fV)) - { - app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Box geometry was found, but with different uvs\n"); - pNewBox=NULL; - } - } - if(pNewBox==NULL) - { - //app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Adding box to model part\n"); + if (pNewBox) { + if ((pNewBox->getfU() != (int)pBox->fU) || + (pNewBox->getfV() != (int)pBox->fV)) { + app.DebugPrintf( + "HumanoidModel::AddOrRetrievePart - Box geometry was found, " + "but with different uvs\n"); + pNewBox = NULL; + } + } + if (pNewBox == NULL) { + // app.DebugPrintf("HumanoidModel::AddOrRetrievePart - Adding box to + // model part\n"); - pNewBox = new ModelPart(this, (int)pBox->fU, (int)pBox->fV); - pNewBox->visible=false; - pNewBox->addHumanoidBox(pBox->fX, pBox->fY, pBox->fZ, pBox->fW, pBox->fH, pBox->fD, 0); - // 4J-PB - don't compile here, since the lighting isn't set up. It'll be compiled on first use. - //pNewBox->compile(1.0f/16.0f); - pAttachTo->addChild(pNewBox); - } + pNewBox = new ModelPart(this, (int)pBox->fU, (int)pBox->fV); + pNewBox->visible = false; + pNewBox->addHumanoidBox(pBox->fX, pBox->fY, pBox->fZ, pBox->fW, + pBox->fH, pBox->fD, 0); + // 4J-PB - don't compile here, since the lighting isn't set up. It'll be + // compiled on first use. + // pNewBox->compile(1.0f/16.0f); + pAttachTo->addChild(pNewBox); + } - return pNewBox; + return pNewBox; } -void HumanoidModel::_init(float g, float yOffset, int texWidth, int texHeight) -{ - this->texWidth = texWidth; - this->texHeight = texHeight; +void HumanoidModel::_init(float g, float yOffset, int texWidth, int texHeight) { + this->texWidth = texWidth; + this->texHeight = texHeight; - m_fYOffset=yOffset; + m_fYOffset = yOffset; cloak = new ModelPart(this, 0, 0); - cloak->addHumanoidBox(-5, -0, -1, 10, 16, 1, g); // Cloak + cloak->addHumanoidBox(-5, -0, -1, 10, 16, 1, g); // Cloak ear = new ModelPart(this, 24, 0); - ear->addHumanoidBox(-3, -6, -1, 6, 6, 1, g); // Ear - + ear->addHumanoidBox(-3, -6, -1, 6, 6, 1, g); // Ear + head = new ModelPart(this, 0, 0); - head->addHumanoidBox(-4, -8, -4, 8, 8, 8, g); // Head + head->addHumanoidBox(-4, -8, -4, 8, 8, 8, g); // Head head->setPos(0, 0 + yOffset, 0); hair = new ModelPart(this, 32, 0); - hair->addHumanoidBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head + hair->addHumanoidBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head hair->setPos(0, 0 + yOffset, 0); body = new ModelPart(this, 16, 16); - body->addHumanoidBox(-4, 0, -2, 8, 12, 4, g); // Body + body->addHumanoidBox(-4, 0, -2, 8, 12, 4, g); // Body body->setPos(0, 0 + yOffset, 0); arm0 = new ModelPart(this, 24 + 16, 16); - arm0->addHumanoidBox(-3, -2, -2, 4, 12, 4, g); // Arm0 + arm0->addHumanoidBox(-3, -2, -2, 4, 12, 4, g); // Arm0 arm0->setPos(-5, 2 + yOffset, 0); arm1 = new ModelPart(this, 24 + 16, 16); arm1->bMirror = true; - arm1->addHumanoidBox(-1, -2, -2, 4, 12, 4, g); // Arm1 + arm1->addHumanoidBox(-1, -2, -2, 4, 12, 4, g); // Arm1 arm1->setPos(5, 2 + yOffset, 0); leg0 = new ModelPart(this, 0, 16); - leg0->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg0 + leg0->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg0 leg0->setPos(-1.9, 12 + yOffset, 0); leg1 = new ModelPart(this, 0, 16); leg1->bMirror = true; - leg1->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg1 + leg1->addHumanoidBox(-2, 0, -2, 4, 12, 4, g); // Leg1 leg1->setPos(1.9, 12 + yOffset, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - cloak->compile(1.0f/16.0f); - ear->compile(1.0f/16.0f); - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - arm0->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - hair->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here + cloak->compile(1.0f / 16.0f); + ear->compile(1.0f / 16.0f); + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + arm0->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + hair->compile(1.0f / 16.0f); - holdingLeftHand=0; - holdingRightHand=0; - sneaking=false; - idle=false; - bowAndArrow=false; + holdingLeftHand = 0; + holdingRightHand = 0; + sneaking = false; + idle = false; + bowAndArrow = false; - // 4J added - eating = false; - eating_t = 0.0f; - eating_swing = 0.0f; - m_uiAnimOverrideBitmask = 0L; + // 4J added + eating = false; + eating_t = 0.0f; + eating_swing = 0.0f; + m_uiAnimOverrideBitmask = 0L; } -HumanoidModel::HumanoidModel() : Model() -{ - _init(0, 0, 64, 32); +HumanoidModel::HumanoidModel() : Model() { _init(0, 0, 64, 32); } + +HumanoidModel::HumanoidModel(float g) : Model() { _init(g, 0, 64, 32); } + +HumanoidModel::HumanoidModel(float g, float yOffset, int texWidth, + int texHeight) + : Model() { + _init(g, yOffset, texWidth, texHeight); } -HumanoidModel::HumanoidModel(float g) : Model() -{ - _init(g, 0, 64, 32); +void HumanoidModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + if (entity != NULL) { + m_uiAnimOverrideBitmask = entity->getAnimOverrideBitmask(); + } + + setupAnim(time, r, bob, yRot, xRot, scale, m_uiAnimOverrideBitmask); + + if (young) { + float ss = 2.0f; + glPushMatrix(); + glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); + glTranslatef(0, 16 * scale, 0); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + arm0->render(scale, usecompiled); + arm1->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + hair->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHead)) > 0); + body->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderTorso)) > 0); + arm0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm0)) > 0); + arm1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm1)) > 0); + leg0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg0)) > 0); + leg1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg1)) > 0); + hair->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHair)) > 0); + } } -HumanoidModel::HumanoidModel(float g, float yOffset, int texWidth, int texHeight) : Model() -{ - _init(g,yOffset,texWidth,texHeight); +void HumanoidModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + // bool bIsAttacking = (attackTime > -9990.0f); + + { + head->yRot = yRot / (float)(180.0f / PI); + head->xRot = xRot / (float)(180.0f / PI); + hair->yRot = head->yRot; + hair->xRot = head->xRot; + + // Does the skin have an override for anim? + + if (uiBitmaskOverrideAnim & (1 << eAnim_ArmsDown)) { + arm0->xRot = 0.0f; + arm1->xRot = 0.0f; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + + } else if (uiBitmaskOverrideAnim & (1 << eAnim_ArmsOutFront)) { + arm0->xRot = -HALF_PI; + arm1->xRot = -HALF_PI; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + } else if (uiBitmaskOverrideAnim & (1 << eAnim_SingleArms)) { + arm0->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; + arm1->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + } + // 4J-PB - Weeping Angel - does't look good holding something in the arm + // that's up + else if ((uiBitmaskOverrideAnim & (1 << eAnim_StatueOfLiberty)) && + (holdingRightHand == 0) && (attackTime == 0.0f)) { + arm0->xRot = -PI; + arm0->zRot = -0.3f; + arm1->xRot = (Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; + arm1->zRot = 0.0f; + } else { + arm0->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; + arm1->xRot = (Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + } + // arm0.zRot = ((float) (util.Mth.cos(time * 0.2312f) + 1) * 1) * + // r; + + // arm1.zRot = ((float) (util.Mth.cos(time * 0.2812f) - 1) * 1) * + // r; + + leg0->yRot = 0.0f; + leg1->yRot = 0.0f; + + if (riding) { + arm0->xRot += -HALF_PI * 0.4f; + arm1->xRot += -HALF_PI * 0.4f; + leg0->xRot = -HALF_PI * 0.8f; + leg1->xRot = -HALF_PI * 0.8f; + leg0->yRot = HALF_PI * 0.2f; + leg1->yRot = -HALF_PI * 0.2f; + } else if (idle && !sneaking) { + leg0->xRot = -HALF_PI; + leg1->xRot = -HALF_PI; + leg0->yRot = HALF_PI * 0.2f; + leg1->yRot = -HALF_PI * 0.2f; + } else if (uiBitmaskOverrideAnim & (1 << eAnim_NoLegAnim)) { + leg0->xRot = 0.0f; + leg0->zRot = 0.0f; + leg1->xRot = 0.0f; + leg1->zRot = 0.0f; + leg0->yRot = 0.0f; + leg1->yRot = 0.0f; + } else if (uiBitmaskOverrideAnim & (1 << eAnim_SingleLegs)) { + leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + leg1->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + } else { + leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; + leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; + } + + if (holdingLeftHand != 0) { + arm1->xRot = arm1->xRot * 0.5f - HALF_PI * 0.2f * holdingLeftHand; + } + if (holdingRightHand != 0) { + arm0->xRot = arm0->xRot * 0.5f - HALF_PI * 0.2f * holdingRightHand; + } + + arm0->yRot = 0.0f; + arm1->yRot = 0.0f; + if (attackTime > -9990.0f) { + float swing = attackTime; + body->yRot = Mth::sin(sqrt(swing) * PI * 2.0f) * 0.2f; + arm0->z = Mth::sin(body->yRot) * 5.0f; + arm0->x = -Mth::cos(body->yRot) * 5.0f; + arm1->z = -Mth::sin(body->yRot) * 5.0f; + arm1->x = Mth::cos(body->yRot) * 5.0f; + arm0->yRot += body->yRot; + arm1->yRot += body->yRot; + arm1->xRot += body->yRot; + + swing = 1.0f - attackTime; + swing *= swing; + swing *= swing; + swing = 1.0f - swing; + float aa = Mth::sin(swing * PI); + float bb = Mth::sin(attackTime * PI) * -(head->xRot - 0.7f) * 0.75f; + arm0->xRot -= aa * 1.2f + bb; // 4J - changed 1.2 -> 1.2f + arm0->yRot += body->yRot * 2.0f; + + if ((uiBitmaskOverrideAnim & (1 << eAnim_StatueOfLiberty)) && + (holdingRightHand == 0) && (attackTime == 0.0f)) { + arm0->zRot -= Mth::sin(attackTime * PI) * -0.4f; + } else { + arm0->zRot = Mth::sin(attackTime * PI) * -0.4f; + } + } + + // 4J added + if (eating) { + // These factors are largely lifted from ItemInHandRenderer to try + // and keep the 3rd person eating animation as similar as possible + float is = 1 - eating_swing; + is = is * is * is; + is = is * is * is; + is = is * is * is; + float iss = 1 - is; + arm0->xRot = -Mth::abs(Mth::cos(eating_t / 4.0f * PI) * 0.1f) * + (eating_swing > 0.2 ? 1.0f : 0.0f) * + 2.0f; // This factor is the chomping bit (conditional + // factor is so that he doesn't eat whilst the + // food is being pulled away at the end) + arm0->yRot -= + iss * 0.5f; // This factor and the following to the general arm + // movement through the life of the swing + arm0->xRot -= iss * 1.2f; + } + + if (sneaking) { + body->xRot = 0.5f; + leg0->xRot -= 0.0f; + leg1->xRot -= 0.0f; + arm0->xRot += 0.4f; + arm1->xRot += 0.4f; + leg0->z = +4.0f; + leg1->z = +4.0f; + body->y = 0.0f; + arm0->y = 2.0f; + arm1->y = 2.0f; + leg0->y = +9.0f; + leg1->y = +9.0f; + head->y = +1.0f; + hair->y = +1.0f; + ear->y = +1.0f; + cloak->y = 0.0f; + } else { + body->xRot = 0.0f; + leg0->z = 0.1f; + leg1->z = 0.1f; + + if (!riding && idle) { + leg0->y = 22.0f; + leg1->y = 22.0f; + body->y = 10.0f; + arm0->y = 12.0f; + arm1->y = 12.0f; + head->y = 10.0f; + hair->y = 10.0f; + ear->y = 11.0f; + cloak->y = 10.0f; + } else { + leg0->y = 12.0f; + leg1->y = 12.0f; + body->y = 0.0f; + arm0->y = 2.0f; + arm1->y = 2.0f; + head->y = 0.0f; + hair->y = 0.0f; + ear->y = 1.0f; + cloak->y = 0.0f; + } + } + + arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm0->xRot += ((Mth::sin(bob * 0.067f)) * 0.05f); + arm1->xRot -= ((Mth::sin(bob * 0.067f)) * 0.05f); + + if (bowAndArrow) { + float attack2 = 0.0f; + float attack = 0.0f; + + arm0->zRot = 0.0f; + arm1->zRot = 0.0f; + arm0->yRot = -(0.1f - attack2 * 0.6f) + head->yRot; + arm1->yRot = +(0.1f - attack2 * 0.6f) + head->yRot + 0.4f; + arm0->xRot = -HALF_PI + head->xRot; + arm1->xRot = -HALF_PI + head->xRot; + arm0->xRot -= attack2 * 1.2f - attack * 0.4f; + arm1->xRot -= attack2 * 1.2f - attack * 0.4f; + arm0->zRot += ((float)(Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm1->zRot -= ((float)(Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm0->xRot += ((float)(Mth::sin(bob * 0.067f)) * 0.05f); + arm1->xRot -= ((float)(Mth::sin(bob * 0.067f)) * 0.05f); + } + } } -void HumanoidModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - if(entity!=NULL) - { - m_uiAnimOverrideBitmask=entity->getAnimOverrideBitmask(); - } - - setupAnim(time, r, bob, yRot, xRot, scale, m_uiAnimOverrideBitmask); - - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); - glTranslatef(0, 16 * scale, 0); - head->render(scale, usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - arm0->render(scale, usecompiled); - arm1->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - hair->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - body->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - hair->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - } -} - -void HumanoidModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - //bool bIsAttacking = (attackTime > -9990.0f); - - { - head->yRot = yRot / (float) (180.0f / PI); - head->xRot = xRot / (float) (180.0f / PI); - hair->yRot = head->yRot; - hair->xRot = head->xRot; - - // Does the skin have an override for anim? - - if(uiBitmaskOverrideAnim&(1<xRot=0.0f; - arm1->xRot=0.0f; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - - } - else if(uiBitmaskOverrideAnim&(1<xRot=-HALF_PI; - arm1->xRot=-HALF_PI; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - } - else if(uiBitmaskOverrideAnim&(1<xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; - arm1->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - } - // 4J-PB - Weeping Angel - does't look good holding something in the arm that's up - else if((uiBitmaskOverrideAnim&(1<xRot = -PI; - arm0->zRot = -0.3f; - arm1->xRot = ( Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; - arm1->zRot = 0.0f; - } - else - { - arm0->xRot = (Mth::cos(time * 0.6662f + PI) * 2.0f) * r * 0.5f; - arm1->xRot = ( Mth::cos(time * 0.6662f) * 2.0f) * r * 0.5f; - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - } - // arm0.zRot = ((float) (util.Mth.cos(time * 0.2312f) + 1) * 1) * r; - - - // arm1.zRot = ((float) (util.Mth.cos(time * 0.2812f) - 1) * 1) * r; - - - leg0->yRot = 0.0f; - leg1->yRot = 0.0f; - - if (riding) - { - arm0->xRot += -HALF_PI * 0.4f; - arm1->xRot += -HALF_PI * 0.4f; - leg0->xRot = -HALF_PI * 0.8f; - leg1->xRot = -HALF_PI * 0.8f; - leg0->yRot = HALF_PI * 0.2f; - leg1->yRot = -HALF_PI * 0.2f; - } - else if(idle && !sneaking ) - { - leg0->xRot = -HALF_PI; - leg1->xRot = -HALF_PI; - leg0->yRot = HALF_PI * 0.2f; - leg1->yRot = -HALF_PI * 0.2f; - } - else if(uiBitmaskOverrideAnim&(1<xRot=0.0f; - leg0->zRot=0.0f; - leg1->xRot=0.0f; - leg1->zRot=0.0f; - leg0->yRot = 0.0f; - leg1->yRot = 0.0f; - } - else if(uiBitmaskOverrideAnim&(1<xRot = ( Mth::cos(time * 0.6662f) * 1.4f) * r; - leg1->xRot = ( Mth::cos(time * 0.6662f) * 1.4f) * r; - } - else - { - leg0->xRot = ( Mth::cos(time * 0.6662f) * 1.4f) * r; - leg1->xRot = ( Mth::cos(time * 0.6662f + PI) * 1.4f) * r; - } - - - if (holdingLeftHand != 0) - { - arm1->xRot = arm1->xRot * 0.5f - HALF_PI * 0.2f * holdingLeftHand; - } - if (holdingRightHand != 0) - { - arm0->xRot = arm0->xRot * 0.5f - HALF_PI * 0.2f * holdingRightHand; - } - - arm0->yRot = 0.0f; - arm1->yRot = 0.0f; - if (attackTime > -9990.0f) - { - float swing = attackTime; - body->yRot = Mth::sin(sqrt(swing) * PI * 2.0f) * 0.2f; - arm0->z = Mth::sin(body->yRot) * 5.0f; - arm0->x = -Mth::cos(body->yRot) * 5.0f; - arm1->z = -Mth::sin(body->yRot) * 5.0f; - arm1->x = Mth::cos(body->yRot) * 5.0f; - arm0->yRot += body->yRot; - arm1->yRot += body->yRot; - arm1->xRot += body->yRot; - - swing = 1.0f - attackTime; - swing *= swing; - swing *= swing; - swing = 1.0f - swing; - float aa = Mth::sin(swing * PI); - float bb = Mth::sin(attackTime * PI) * -(head->xRot - 0.7f) * 0.75f; - arm0->xRot -= aa * 1.2f + bb; // 4J - changed 1.2 -> 1.2f - arm0->yRot += body->yRot * 2.0f; - - if((uiBitmaskOverrideAnim&(1<zRot -= Mth::sin(attackTime * PI) * -0.4f; - } - else - { - arm0->zRot = Mth::sin(attackTime * PI) * -0.4f; - } - } - - // 4J added - if( eating ) - { - // These factors are largely lifted from ItemInHandRenderer to try and keep the 3rd person eating animation as similar as possible - float is = 1 - eating_swing; - is = is * is * is; - is = is * is * is; - is = is * is * is; - float iss = 1 - is; - arm0->xRot = - Mth::abs(Mth::cos(eating_t / 4.0f * PI) * 0.1f) * (eating_swing > 0.2 ? 1.0f : 0.0f) * 2.0f; // This factor is the chomping bit (conditional factor is so that he doesn't eat whilst the food is being pulled away at the end) - arm0->yRot -= iss * 0.5f; // This factor and the following to the general arm movement through the life of the swing - arm0->xRot -= iss * 1.2f; - - } - - if (sneaking) - { - body->xRot = 0.5f; - leg0->xRot -= 0.0f; - leg1->xRot -= 0.0f; - arm0->xRot += 0.4f; - arm1->xRot += 0.4f; - leg0->z = +4.0f; - leg1->z = +4.0f; - body->y = 0.0f; - arm0->y = 2.0f; - arm1->y = 2.0f; - leg0->y = +9.0f; - leg1->y = +9.0f; - head->y = +1.0f; - hair->y = +1.0f; - ear->y = +1.0f; - cloak->y = 0.0f; - } - else - { - body->xRot = 0.0f; - leg0->z = 0.1f; - leg1->z = 0.1f; - - if(!riding && idle) - { - leg0->y = 22.0f; - leg1->y = 22.0f; - body->y = 10.0f; - arm0->y = 12.0f; - arm1->y = 12.0f; - head->y = 10.0f; - hair->y = 10.0f; - ear->y = 11.0f; - cloak->y = 10.0f; - } - else - { - leg0->y = 12.0f; - leg1->y = 12.0f; - body->y = 0.0f; - arm0->y = 2.0f; - arm1->y = 2.0f; - head->y = 0.0f; - hair->y = 0.0f; - ear->y = 1.0f; - cloak->y = 0.0f; - } - } - - - arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm0->xRot += ((Mth::sin(bob * 0.067f)) * 0.05f); - arm1->xRot -= ((Mth::sin(bob * 0.067f)) * 0.05f); - - if (bowAndArrow) - { - float attack2 = 0.0f; - float attack = 0.0f; - - arm0->zRot = 0.0f; - arm1->zRot = 0.0f; - arm0->yRot = -(0.1f - attack2 * 0.6f) + head->yRot; - arm1->yRot = +(0.1f - attack2 * 0.6f) + head->yRot + 0.4f; - arm0->xRot = -HALF_PI + head->xRot; - arm1->xRot = -HALF_PI + head->xRot; - arm0->xRot -= attack2 * 1.2f - attack * 0.4f; - arm1->xRot -= attack2 * 1.2f - attack * 0.4f; - arm0->zRot += ((float) (Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm1->zRot -= ((float) (Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); - arm0->xRot += ((float) (Mth::sin(bob * 0.067f)) * 0.05f); - arm1->xRot -= ((float) (Mth::sin(bob * 0.067f)) * 0.05f); - } - } -} - -void HumanoidModel::renderHair(float scale,bool usecompiled) -{ +void HumanoidModel::renderHair(float scale, bool usecompiled) { hair->yRot = head->yRot; hair->xRot = head->xRot; - hair->render(scale,usecompiled); + hair->render(scale, usecompiled); } -void HumanoidModel::renderEars(float scale,bool usecompiled) -{ +void HumanoidModel::renderEars(float scale, bool usecompiled) { ear->yRot = head->yRot; ear->xRot = head->xRot; - ear->x=0; - ear->y=0; - ear->render(scale,usecompiled); + ear->x = 0; + ear->y = 0; + ear->render(scale, usecompiled); } -void HumanoidModel::renderCloak(float scale,bool usecompiled) -{ - cloak->render(scale,usecompiled); +void HumanoidModel::renderCloak(float scale, bool usecompiled) { + cloak->render(scale, usecompiled); } -void HumanoidModel::render(HumanoidModel *model, float scale, bool usecompiled) -{ +void HumanoidModel::render(HumanoidModel* model, float scale, + bool usecompiled) { head->yRot = model->head->yRot; head->y = model->head->y; head->xRot = model->head->xRot; @@ -444,23 +425,37 @@ void HumanoidModel::render(HumanoidModel *model, float scale, bool usecompiled) hair->xRot = head->xRot; body->yRot = model->body->yRot; - + arm0->xRot = model->arm0->xRot; arm0->yRot = model->arm0->yRot; arm0->zRot = model->arm0->zRot; - + arm1->xRot = model->arm1->xRot; arm1->yRot = model->arm1->yRot; arm1->zRot = model->arm1->zRot; - + leg0->xRot = model->leg0->xRot; leg1->xRot = model->leg1->xRot; - head->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - body->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - arm1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg0->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - leg1->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); - hair->render(scale, usecompiled,(m_uiAnimOverrideBitmask&(1<0); + head->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHead)) > 0); + body->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderTorso)) > 0); + arm0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm0)) > 0); + arm1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderArm1)) > 0); + leg0->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg0)) > 0); + leg1->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderLeg1)) > 0); + hair->render( + scale, usecompiled, + (m_uiAnimOverrideBitmask & (1 << eAnim_DisableRenderHair)) > 0); } diff --git a/Minecraft.Client/Rendering/Models/HumanoidModel.h b/Minecraft.Client/Rendering/Models/HumanoidModel.h index 2f9fcff57..3eb256b77 100644 --- a/Minecraft.Client/Rendering/Models/HumanoidModel.h +++ b/Minecraft.Client/Rendering/Models/HumanoidModel.h @@ -1,65 +1,69 @@ #pragma once #include "Model.h" -class HumanoidModel : public Model -{ +class HumanoidModel : public Model { public: - ModelPart *head, *hair, *body, *arm0, *arm1, *leg0, *leg1, *ear, *cloak; - //ModelPart *hat; + ModelPart *head, *hair, *body, *arm0, *arm1, *leg0, *leg1, *ear, *cloak; + // ModelPart *hat; - int holdingLeftHand; + int holdingLeftHand; int holdingRightHand; - bool idle; - bool sneaking; - bool bowAndArrow; - bool eating; // 4J added - float eating_t; // 4J added - float eating_swing; // 4J added - unsigned int m_uiAnimOverrideBitmask; // 4J added - float m_fYOffset; // 4J added - enum animbits - { - eAnim_ArmsDown =0, - eAnim_ArmsOutFront, - eAnim_NoLegAnim, - eAnim_HasIdle, - eAnim_ForceAnim, // Claptrap looks bad if the user turns off custom skin anim - // 4J-PB - DaveK wants Fish characters to move both legs in the same way - eAnim_SingleLegs, - eAnim_SingleArms, - eAnim_StatueOfLiberty, // Dr Who Weeping Angel - eAnim_DontRenderArmour, // Dr Who Daleks - eAnim_NoBobbing, // Dr Who Daleks - eAnim_DisableRenderHead, - eAnim_DisableRenderArm0, - eAnim_DisableRenderArm1, - eAnim_DisableRenderTorso, - eAnim_DisableRenderLeg0, - eAnim_DisableRenderLeg1, - eAnim_DisableRenderHair + bool idle; + bool sneaking; + bool bowAndArrow; + bool eating; // 4J added + float eating_t; // 4J added + float eating_swing; // 4J added + unsigned int m_uiAnimOverrideBitmask; // 4J added + float m_fYOffset; // 4J added + enum animbits { + eAnim_ArmsDown = 0, + eAnim_ArmsOutFront, + eAnim_NoLegAnim, + eAnim_HasIdle, + eAnim_ForceAnim, // Claptrap looks bad if the user turns off custom + // skin anim + // 4J-PB - DaveK wants Fish characters to move both legs in the same way + eAnim_SingleLegs, + eAnim_SingleArms, + eAnim_StatueOfLiberty, // Dr Who Weeping Angel + eAnim_DontRenderArmour, // Dr Who Daleks + eAnim_NoBobbing, // Dr Who Daleks + eAnim_DisableRenderHead, + eAnim_DisableRenderArm0, + eAnim_DisableRenderArm1, + eAnim_DisableRenderTorso, + eAnim_DisableRenderLeg0, + eAnim_DisableRenderLeg1, + eAnim_DisableRenderHair - }; + }; - static const unsigned int m_staticBitmaskIgnorePlayerCustomAnimSetting= (1< entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); void renderHair(float scale, bool usecompiled); void renderEars(float scale, bool usecompiled); - void renderCloak(float scale, bool usecompiled); - void render(HumanoidModel *model, float scale, bool usecompiled); + void renderCloak(float scale, bool usecompiled); + void render(HumanoidModel* model, float scale, bool usecompiled); -// Add new bits to models - ModelPart * AddOrRetrievePart(SKIN_BOX *pBox); + // Add new bits to models + ModelPart* AddOrRetrievePart(SKIN_BOX* pBox); }; diff --git a/Minecraft.Client/Rendering/Models/LargeChestModel.cpp b/Minecraft.Client/Rendering/Models/LargeChestModel.cpp index 65a708509..f9a11082a 100644 --- a/Minecraft.Client/Rendering/Models/LargeChestModel.cpp +++ b/Minecraft.Client/Rendering/Models/LargeChestModel.cpp @@ -2,28 +2,28 @@ #include "LargeChestModel.h" #include "ModelPart.h" -LargeChestModel::LargeChestModel() -{ - lid = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); - lid->addBox(0.0f, -5.0f, -14.0f, 14+16, 5, 14, 0.0f); - lid->x = 1; - lid->y = 7; - lid->z = 15; +LargeChestModel::LargeChestModel() { + lid = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); + lid->addBox(0.0f, -5.0f, -14.0f, 14 + 16, 5, 14, 0.0f); + lid->x = 1; + lid->y = 7; + lid->z = 15; - lock = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); - lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); - lock->x = 8+8; - lock->y = 7; - lock->z = 15; + lock = ((new ModelPart(this, 0, 0)))->setTexSize(128, 64); + lock->addBox(-1.0f, -2.0f, -15.0f, 2, 4, 1, 0.0f); + lock->x = 8 + 8; + lock->y = 7; + lock->z = 15; - bottom = ((new ModelPart(this, 0, 19)))->setTexSize(128, 64); - bottom->addBox(0.0f, 0.0f, 0.0f, 14+16, 10, 14, 0.0f); - bottom->x = 1; - bottom->y = 6; - bottom->z = 1; + bottom = ((new ModelPart(this, 0, 19)))->setTexSize(128, 64); + bottom->addBox(0.0f, 0.0f, 0.0f, 14 + 16, 10, 14, 0.0f); + bottom->x = 1; + bottom->y = 6; + bottom->z = 1; - // 4J added - compile now to avoid random performance hit first time cubes are rendered - lid->compile(1.0f/16.0f); - lock->compile(1.0f/16.0f); - bottom->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + lid->compile(1.0f / 16.0f); + lock->compile(1.0f / 16.0f); + bottom->compile(1.0f / 16.0f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/LargeChestModel.h b/Minecraft.Client/Rendering/Models/LargeChestModel.h index a2dcb991c..ebe4724c8 100644 --- a/Minecraft.Client/Rendering/Models/LargeChestModel.h +++ b/Minecraft.Client/Rendering/Models/LargeChestModel.h @@ -2,8 +2,7 @@ #include "ChestModel.h" -class LargeChestModel : public ChestModel -{ +class LargeChestModel : public ChestModel { public: - LargeChestModel(); + LargeChestModel(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp b/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp index 3bb1e9d35..67d423b62 100644 --- a/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp +++ b/Minecraft.Client/Rendering/Models/LavaSlimeModel.cpp @@ -4,20 +4,14 @@ #include "ModelPart.h" #include "../../../Minecraft.World/Entities/Mobs/LavaSlime.h" - -LavaSlimeModel::LavaSlimeModel() -{ - for (int i = 0; i < BODYCUBESLENGTH; i++) - { +LavaSlimeModel::LavaSlimeModel() { + for (int i = 0; i < BODYCUBESLENGTH; i++) { int u = 0; int v = i; - if (i == 2) - { + if (i == 2) { u = 24; v = 10; - } - else if (i == 3) - { + } else if (i == 3) { u = 24; v = 19; } @@ -28,44 +22,39 @@ LavaSlimeModel::LavaSlimeModel() insideCube = new ModelPart(this, 0, 16); insideCube->addBox(-2, 16 + 2, -2, 4, 4, 4); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - insideCube->compile(1.0f/16.0f); - for( int i = 0; i < BODYCUBESLENGTH; i++ ) - { - bodyCubes[i]->compile(1.0f/16.0f); - } + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + insideCube->compile(1.0f / 16.0f); + for (int i = 0; i < BODYCUBESLENGTH; i++) { + bodyCubes[i]->compile(1.0f / 16.0f); + } } -int LavaSlimeModel::getModelVersion() -{ - return 5; -} +int LavaSlimeModel::getModelVersion() { return 5; } -void LavaSlimeModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - std::shared_ptr lavaSlime = std::dynamic_pointer_cast(mob); +void LavaSlimeModel::prepareMobModel(std::shared_ptr mob, float time, + float r, float a) { + std::shared_ptr lavaSlime = + std::dynamic_pointer_cast(mob); - float slimeSquish = (lavaSlime->oSquish + (lavaSlime->squish - lavaSlime->oSquish) * a); - if (slimeSquish < 0) - { + float slimeSquish = + (lavaSlime->oSquish + (lavaSlime->squish - lavaSlime->oSquish) * a); + if (slimeSquish < 0) { slimeSquish = 0.0f; } - for (int i = 0; i < BODYCUBESLENGTH; i++) - { + for (int i = 0; i < BODYCUBESLENGTH; i++) { bodyCubes[i]->y = -(4 - i) * slimeSquish * 1.7f; } } -void LavaSlimeModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); - - insideCube->render(scale, usecompiled); - for (int i = 0; i < BODYCUBESLENGTH; i++) - { - bodyCubes[i]->render(scale, usecompiled); - } +void LavaSlimeModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + insideCube->render(scale, usecompiled); + for (int i = 0; i < BODYCUBESLENGTH; i++) { + bodyCubes[i]->render(scale, usecompiled); + } } - diff --git a/Minecraft.Client/Rendering/Models/LavaSlimeModel.h b/Minecraft.Client/Rendering/Models/LavaSlimeModel.h index 4fcce75de..4f9f8ef07 100644 --- a/Minecraft.Client/Rendering/Models/LavaSlimeModel.h +++ b/Minecraft.Client/Rendering/Models/LavaSlimeModel.h @@ -1,15 +1,17 @@ #pragma once #include "Model.h" -class LavaSlimeModel : public Model -{ - static const int BODYCUBESLENGTH=8; - ModelPart *bodyCubes[BODYCUBESLENGTH]; - ModelPart *insideCube; +class LavaSlimeModel : public Model { + static const int BODYCUBESLENGTH = 8; + ModelPart* bodyCubes[BODYCUBESLENGTH]; + ModelPart* insideCube; public: - LavaSlimeModel(); - int getModelVersion(); - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + LavaSlimeModel(); + int getModelVersion(); + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/MinecartModel.cpp b/Minecraft.Client/Rendering/Models/MinecartModel.cpp index e7e659362..1feb9ab3b 100644 --- a/Minecraft.Client/Rendering/Models/MinecartModel.cpp +++ b/Minecraft.Client/Rendering/Models/MinecartModel.cpp @@ -2,8 +2,7 @@ #include "MinecartModel.h" #include "ModelPart.h" -MinecartModel::MinecartModel() : Model() -{ +MinecartModel::MinecartModel() : Model() { cubes[0] = new ModelPart(this, 0, 10); cubes[1] = new ModelPart(this, 0, 0); cubes[2] = new ModelPart(this, 0, 0); @@ -18,40 +17,41 @@ MinecartModel::MinecartModel() : Model() cubes[0]->addBox((float)(-w / 2), (float)(-h / 2), -1, w, h, 2, 0); cubes[0]->setPos(0, (float)(0 + yOff), 0); - - cubes[5]->addBox((float)(-w / 2 + 1), (float)(-h / 2 + 1), -1, w - 2, h - 2, 1, 0); + + cubes[5]->addBox((float)(-w / 2 + 1), (float)(-h / 2 + 1), -1, w - 2, h - 2, + 1, 0); cubes[5]->setPos(0, (float)(0 + yOff), 0); - + cubes[1]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[1]->setPos((float)(-w / 2 + 1), (float)(0 + yOff), 0); - + cubes[2]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[2]->setPos((float)(+w / 2 - 1), (float)(0 + yOff), 0); - + cubes[3]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[3]->setPos(0, (float)(0 + yOff), (float)(-h / 2 + 1)); - + cubes[4]->addBox((float)(-w / 2 + 2), (float)(-d - 1), -1, w - 4, d, 2, 0); cubes[4]->setPos(0, (float)(0 + yOff), (float)(+h / 2 - 1)); - + cubes[0]->xRot = PI / 2; cubes[1]->yRot = PI / 2 * 3; cubes[2]->yRot = PI / 2 * 1; cubes[3]->yRot = PI / 2 * 2; cubes[5]->xRot = -PI / 2; - // 4J added - compile now to avoid random performance hit first time cubes are rendered - for (int i = 0; i < MINECART_LENGTH; i++) - { - cubes[i]->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + for (int i = 0; i < MINECART_LENGTH; i++) { + cubes[i]->compile(1.0f / 16.0f); } } -void MinecartModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void MinecartModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { cubes[5]->y = 4 - bob; - for (int i = 0; i < MINECART_LENGTH; i++) - { + for (int i = 0; i < MINECART_LENGTH; i++) { cubes[i]->render(scale, usecompiled); } } diff --git a/Minecraft.Client/Rendering/Models/MinecartModel.h b/Minecraft.Client/Rendering/Models/MinecartModel.h index 2cf6d0efb..13b7cf69e 100644 --- a/Minecraft.Client/Rendering/Models/MinecartModel.h +++ b/Minecraft.Client/Rendering/Models/MinecartModel.h @@ -1,13 +1,14 @@ #pragma once #include "Model.h" -class MinecartModel : public Model -{ +class MinecartModel : public Model { public: - static const int MINECART_LENGTH=6; + static const int MINECART_LENGTH = 6; - ModelPart *cubes[MINECART_LENGTH]; + ModelPart* cubes[MINECART_LENGTH]; MinecartModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/Model.cpp b/Minecraft.Client/Rendering/Models/Model.cpp index e4f278cbc..788738bd5 100644 --- a/Minecraft.Client/Rendering/Models/Model.cpp +++ b/Minecraft.Client/Rendering/Models/Model.cpp @@ -2,22 +2,18 @@ #include "../TexOffs.h" #include "Model.h" - -Model::Model() -{ - riding = false; - young=true; - texWidth=64; - texHeight=32; -} - -void Model::setMapTex(std::wstring id, int x, int y) -{ - mappedTexOffs[id]=new TexOffs(x, y); +Model::Model() { + riding = false; + young = true; + texWidth = 64; + texHeight = 32; } -TexOffs *Model::getMapTex(std::wstring id) -{ - // 4J-PB - assuming there will always be this one - return mappedTexOffs[id]; +void Model::setMapTex(std::wstring id, int x, int y) { + mappedTexOffs[id] = new TexOffs(x, y); +} + +TexOffs* Model::getMapTex(std::wstring id) { + // 4J-PB - assuming there will always be this one + return mappedTexOffs[id]; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/Model.h b/Minecraft.Client/Rendering/Models/Model.h index c80f9e8f6..f1cfc5f74 100644 --- a/Minecraft.Client/Rendering/Models/Model.h +++ b/Minecraft.Client/Rendering/Models/Model.h @@ -6,30 +6,35 @@ class Mob; class ModelPart; class TexOffs; - -class Model -{ +class Model { public: - float attackTime; + float attackTime; bool riding; - std::vector cubes; - bool young; - std::unordered_map mappedTexOffs; - int texWidth; - int texHeight; + std::vector cubes; + bool young; + std::unordered_map mappedTexOffs; + int texWidth; + int texHeight; - Model(); // 4J added - virtual ~Model(){} - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) {} - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0) {} - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a) {} - virtual ModelPart *getRandomCube(Random random) {return cubes.at(random.nextInt((int)cubes.size()));} - virtual ModelPart * AddOrRetrievePart(SKIN_BOX *pBox) { return NULL;} + Model(); // 4J added + virtual ~Model() {} + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) {} + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0) {} + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a) {} + virtual ModelPart* getRandomCube(Random random) { + return cubes.at(random.nextInt((int)cubes.size())); + } + virtual ModelPart* AddOrRetrievePart(SKIN_BOX* pBox) { return NULL; } - void setMapTex(std::wstring id, int x, int y); - TexOffs *getMapTex(std::wstring id); + void setMapTex(std::wstring id, int x, int y); + TexOffs* getMapTex(std::wstring id); protected: - float yHeadOffs; - float zHeadOffs; + float yHeadOffs; + float zHeadOffs; }; diff --git a/Minecraft.Client/Rendering/Models/ModelPart.cpp b/Minecraft.Client/Rendering/Models/ModelPart.cpp index 341a0cb57..833746e3b 100644 --- a/Minecraft.Client/Rendering/Models/ModelPart.cpp +++ b/Minecraft.Client/Rendering/Models/ModelPart.cpp @@ -5,318 +5,263 @@ const float ModelPart::RAD = (180.0f / PI); -void ModelPart::_init() -{ - xTexSize = 64.0f; - yTexSize = 32.0f; - list = 0; - compiled=false; - bMirror = false; - visible = true; - neverRender = false; - x=y=z = 0.0f; - xRot=yRot=zRot = 0.0f; +void ModelPart::_init() { + xTexSize = 64.0f; + yTexSize = 32.0f; + list = 0; + compiled = false; + bMirror = false; + visible = true; + neverRender = false; + x = y = z = 0.0f; + xRot = yRot = zRot = 0.0f; } -ModelPart::ModelPart() -{ - _init(); +ModelPart::ModelPart() { _init(); } + +ModelPart::ModelPart(Model* model, const std::wstring& id) { + construct(model, id); } -ModelPart::ModelPart(Model *model, const std::wstring& id) -{ - construct(model, id); +ModelPart::ModelPart(Model* model) { construct(model); } + +ModelPart::ModelPart(Model* model, int xTexOffs, int yTexOffs) { + construct(model, xTexOffs, yTexOffs); } -ModelPart::ModelPart(Model *model) -{ - construct(model); +void ModelPart::construct(Model* model, const std::wstring& id) { + _init(); + this->model = model; + model->cubes.push_back(this); + this->id = id; + setTexSize(model->texWidth, model->texHeight); } -ModelPart::ModelPart(Model *model, int xTexOffs, int yTexOffs) -{ - construct(model, xTexOffs, yTexOffs); +void ModelPart::construct(Model* model) { + _init(); + construct(model, L""); } - -void ModelPart::construct(Model *model, const std::wstring& id) -{ - _init(); - this->model = model; - model->cubes.push_back(this); - this->id = id; - setTexSize(model->texWidth, model->texHeight); +void ModelPart::construct(Model* model, int xTexOffs, int yTexOffs) { + _init(); + construct(model); + texOffs(xTexOffs, yTexOffs); } -void ModelPart::construct(Model *model) -{ - _init(); - construct(model, L""); +void ModelPart::addChild(ModelPart* child) { + // if (children == NULL) children = new ModelPartArray; + children.push_back(child); } -void ModelPart::construct(Model *model, int xTexOffs, int yTexOffs) -{ - _init(); - construct(model); - texOffs(xTexOffs, yTexOffs); +ModelPart* ModelPart::retrieveChild(SKIN_BOX* pBox) { + for (AUTO_VAR(it, children.begin()); it != children.end(); ++it) { + ModelPart* child = *it; + + for (AUTO_VAR(itcube, child->cubes.begin()); + itcube != child->cubes.end(); ++itcube) { + Cube* pCube = *itcube; + + if ((pCube->x0 == pBox->fX) && (pCube->y0 == pBox->fY) && + (pCube->z0 == pBox->fZ) && + (pCube->x1 == (pBox->fX + pBox->fW)) && + (pCube->y1 == (pBox->fY + pBox->fH)) && + (pCube->z1 == (pBox->fZ + pBox->fD))) { + return child; + break; + } + } + } + + return NULL; } - -void ModelPart::addChild(ModelPart *child) -{ - //if (children == NULL) children = new ModelPartArray; - children.push_back(child); +ModelPart* ModelPart::mirror() { + bMirror = !bMirror; + return this; } -ModelPart * ModelPart::retrieveChild(SKIN_BOX *pBox) -{ - for(AUTO_VAR(it, children.begin()); it != children.end(); ++it) - { - ModelPart *child=*it; - - for(AUTO_VAR(itcube, child->cubes.begin()); itcube != child->cubes.end(); ++itcube) - { - Cube *pCube=*itcube; - - if((pCube->x0==pBox->fX) && - (pCube->y0==pBox->fY) && - (pCube->z0==pBox->fZ) && - (pCube->x1==(pBox->fX + pBox->fW)) && - (pCube->y1==(pBox->fY + pBox->fH)) && - (pCube->z1==(pBox->fZ + pBox->fD)) - ) - { - return child; - break; - } - } - } - - return NULL; +ModelPart* ModelPart::texOffs(int xTexOffs, int yTexOffs) { + this->xTexOffs = xTexOffs; + this->yTexOffs = yTexOffs; + return this; } -ModelPart *ModelPart::mirror() -{ - bMirror = !bMirror; - return this; +ModelPart* ModelPart::addBox(std::wstring id, float x0, float y0, float z0, + int w, int h, int d) { + id = this->id + L"." + id; + TexOffs* offs = model->getMapTex(id); + texOffs(offs->x, offs->y); + cubes.push_back((new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0)) + ->setId(id)); + return this; } -ModelPart *ModelPart::texOffs(int xTexOffs, int yTexOffs) -{ - this->xTexOffs = xTexOffs; - this->yTexOffs = yTexOffs; - return this; +ModelPart* ModelPart::addBox(float x0, float y0, float z0, int w, int h, + int d) { + cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0)); + return this; } -ModelPart *ModelPart::addBox(std::wstring id, float x0, float y0, float z0, int w, int h, int d) -{ - id = this->id + L"." + id; - TexOffs *offs = model->getMapTex(id); - texOffs(offs->x, offs->y); - cubes.push_back((new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0))->setId(id)); - return this; +void ModelPart::addHumanoidBox(float x0, float y0, float z0, int w, int h, + int d, float g) { + cubes.push_back( + new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g, 63, true)); } -ModelPart *ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0)); - return this; +ModelPart* ModelPart::addBoxWithMask(float x0, float y0, float z0, int w, int h, + int d, int faceMask) { + cubes.push_back( + new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0, faceMask)); + return this; } -void ModelPart::addHumanoidBox(float x0, float y0, float z0, int w, int h, int d, float g) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g, 63, true)); +void ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d, + float g) { + cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g)); } -ModelPart *ModelPart::addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, int faceMask) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0, faceMask)); - return this; +void ModelPart::addTexBox(float x0, float y0, float z0, int w, int h, int d, + int tex) { + cubes.push_back( + new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, (float)tex)); } -void ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d, float g) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g)); +void ModelPart::setPos(float x, float y, float z) { + this->x = x; + this->y = y; + this->z = z; } +void ModelPart::render(float scale, bool usecompiled, + bool bHideParentBodyPart) { + if (neverRender) return; + if (!visible) return; + if (!compiled) compile(scale); -void ModelPart::addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex) -{ - cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, (float)tex)); + if (xRot != 0 || yRot != 0 || zRot != 0) { + glPushMatrix(); + glTranslatef(x * scale, y * scale, z * scale); + if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); + if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); + if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); + + if (!bHideParentBodyPart) { + if (usecompiled) { + glCallList(list); + } else { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes[i]->render(t, scale); + } + } + } + // if (children != NULL) + { + for (unsigned int i = 0; i < children.size(); i++) { + children.at(i)->render(scale, usecompiled); + } + } + + glPopMatrix(); + } else if (x != 0 || y != 0 || z != 0) { + glTranslatef(x * scale, y * scale, z * scale); + if (!bHideParentBodyPart) { + if (usecompiled) { + glCallList(list); + } else { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes[i]->render(t, scale); + } + } + } + // if (children != NULL) + { + for (unsigned int i = 0; i < children.size(); i++) { + children.at(i)->render(scale, usecompiled); + } + } + glTranslatef(-x * scale, -y * scale, -z * scale); + } else { + if (!bHideParentBodyPart) { + if (usecompiled) { + glCallList(list); + } else { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes[i]->render(t, scale); + } + } + } + // if (children != NULL) + { + for (unsigned int i = 0; i < children.size(); i++) { + children.at(i)->render(scale, usecompiled); + } + } + } } -void ModelPart::setPos(float x, float y, float z) -{ - this->x = x; - this->y = y; - this->z = z; +void ModelPart::renderRollable(float scale, bool usecompiled) { + if (neverRender) return; + if (!visible) return; + if (!compiled) compile(scale); + + glPushMatrix(); + glTranslatef(x * scale, y * scale, z * scale); + if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); + if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); + if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); + glCallList(list); + glPopMatrix(); } -void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) -{ - if (neverRender) return; - if (!visible) return; - if (!compiled) compile(scale); +void ModelPart::translateTo(float scale) { + if (neverRender) return; + if (!visible) return; + if (!compiled) compile(scale); - if (xRot != 0 || yRot != 0 || zRot != 0) - { - glPushMatrix(); - glTranslatef(x * scale, y * scale, z * scale); - if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); - if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); - if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); - - if(!bHideParentBodyPart) - { - if( usecompiled ) - { - glCallList(list); - } - else - { - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes[i]->render(t, scale); - } - } - } - //if (children != NULL) - { - for (unsigned int i = 0; i < children.size(); i++) - { - children.at(i)->render(scale,usecompiled); - } - } - - glPopMatrix(); - } - else if (x != 0 || y != 0 || z != 0) - { - glTranslatef(x * scale, y * scale, z * scale); - if(!bHideParentBodyPart) - { - if( usecompiled ) - { - glCallList(list); - } - else - { - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes[i]->render(t, scale); - } - } - } - //if (children != NULL) - { - for (unsigned int i = 0; i < children.size(); i++) - { - children.at(i)->render(scale,usecompiled); - } - } - glTranslatef(-x * scale, -y * scale, -z * scale); - } - else - { - if(!bHideParentBodyPart) - { - if( usecompiled ) - { - glCallList(list); - } - else - { - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes[i]->render(t, scale); - } - } - } - //if (children != NULL) - { - for (unsigned int i = 0; i < children.size(); i++) - { - children.at(i)->render(scale,usecompiled); - } - } - } + if (xRot != 0 || yRot != 0 || zRot != 0) { + glTranslatef(x * scale, y * scale, z * scale); + if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); + if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); + if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); + } else if (x != 0 || y != 0 || z != 0) { + glTranslatef(x * scale, y * scale, z * scale); + } else { + } } -void ModelPart::renderRollable(float scale, bool usecompiled) -{ - if (neverRender) return; - if (!visible) return; - if (!compiled) compile(scale); +void ModelPart::compile(float scale) { + list = MemoryTracker::genLists(1); - glPushMatrix(); - glTranslatef(x * scale, y * scale, z * scale); - if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); - if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); - if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); - glCallList(list); - glPopMatrix(); + glNewList(list, GL_COMPILE); + // Set a few render states that aren't configured by default + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + glDepthMask(true); + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { + cubes.at(i)->render(t, scale); + } + + glEndList(); + + compiled = true; } -void ModelPart::translateTo(float scale) -{ - if (neverRender) return; - if (!visible) return; - if (!compiled) compile(scale); - - if (xRot != 0 || yRot != 0 || zRot != 0) - { - glTranslatef(x * scale, y * scale, z * scale); - if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); - if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); - if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); - } - else if (x != 0 || y != 0 || z != 0) - { - glTranslatef(x * scale, y * scale, z * scale); - } - else - { - } +ModelPart* ModelPart::setTexSize(int xs, int ys) { + this->xTexSize = (float)xs; + this->yTexSize = (float)ys; + return this; } -void ModelPart::compile(float scale) -{ - list = MemoryTracker::genLists(1); - - glNewList(list, GL_COMPILE); - // Set a few render states that aren't configured by default - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); - glDepthMask(true); - Tesselator *t = Tesselator::getInstance(); - - for (unsigned int i = 0; i < cubes.size(); i++) - { - cubes.at(i)->render(t, scale); - } - - glEndList(); - - compiled = true; -} - -ModelPart *ModelPart::setTexSize(int xs, int ys) -{ - this->xTexSize = (float)xs; - this->yTexSize = (float)ys; - return this; -} - -void ModelPart::mimic(ModelPart *o) -{ - x = o->x; - y = o->y; - z = o->z; - xRot = o->xRot; - yRot = o->yRot; - zRot = o->zRot; +void ModelPart::mimic(ModelPart* o) { + x = o->x; + y = o->y; + z = o->z; + xRot = o->xRot; + yRot = o->yRot; + zRot = o->zRot; } diff --git a/Minecraft.Client/Rendering/Models/ModelPart.h b/Minecraft.Client/Rendering/Models/ModelPart.h index 822ed1025..f412fc244 100644 --- a/Minecraft.Client/Rendering/Models/ModelPart.h +++ b/Minecraft.Client/Rendering/Models/ModelPart.h @@ -7,56 +7,62 @@ class Cube; -class ModelPart -{ +class ModelPart { public: float xTexSize; float yTexSize; - float x, y, z; - float xRot, yRot, zRot; - bool bMirror; - bool visible; - bool neverRender; - std::vector cubes; - std::vector children; + float x, y, z; + float xRot, yRot, zRot; + bool bMirror; + bool visible; + bool neverRender; + std::vector cubes; + std::vector children; static const float RAD; private: std::wstring id; - int xTexOffs, yTexOffs; + int xTexOffs, yTexOffs; boolean compiled; int list; - Model *model; - + Model* model; + public: - void _init(); // 4J added - ModelPart(); - ModelPart(Model *model, const std::wstring &id); - ModelPart(Model *model); - ModelPart(Model *model, int xTexOffs, int yTexOffs); + void _init(); // 4J added + ModelPart(); + ModelPart(Model* model, const std::wstring& id); + ModelPart(Model* model); + ModelPart(Model* model, int xTexOffs, int yTexOffs); - // MGH - had to add these for PS3, as calling constructors from others was only introduced in c++11 - https://en.wikipedia.org/wiki/C++11#Object_construction_improvement - void construct(Model *model, const std::wstring &id); - void construct(Model *model); - void construct(Model *model, int xTexOffs, int yTexOffs); + // MGH - had to add these for PS3, as calling constructors from others was + // only introduced in c++11 - + // https://en.wikipedia.org/wiki/C++11#Object_construction_improvement + void construct(Model* model, const std::wstring& id); + void construct(Model* model); + void construct(Model* model, int xTexOffs, int yTexOffs); - void addChild(ModelPart *child); - ModelPart * retrieveChild(SKIN_BOX *pBox); - ModelPart *mirror(); - ModelPart *texOffs(int xTexOffs, int yTexOffs); - ModelPart *addBox(std::wstring 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); - ModelPart *addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, int faceMask); // 4J added + void addChild(ModelPart* child); + ModelPart* retrieveChild(SKIN_BOX* pBox); + ModelPart* mirror(); + ModelPart* texOffs(int xTexOffs, int yTexOffs); + ModelPart* addBox(std::wstring 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); + ModelPart* addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, + int faceMask); // 4J added void addBox(float x0, float y0, float z0, int w, int h, int d, float g); - void addHumanoidBox(float x0, float y0, float z0, int w, int h, int d, float g); // 4J - to flip the poly 3 uvs so the skin maps correctly + void addHumanoidBox( + float x0, float y0, float z0, int w, int h, int d, + float g); // 4J - to flip the poly 3 uvs so the skin maps correctly void addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex); void setPos(float x, float y, float z); - void render(float scale, bool usecompiled,bool bHideParentBodyPart=false); + void render(float scale, bool usecompiled, + bool bHideParentBodyPart = false); void renderRollable(float scale, bool usecompiled); void translateTo(float scale); - ModelPart *setTexSize(int xs, int ys); - void mimic(ModelPart *o); - void compile(float scale); - int getfU() {return xTexOffs;} - int getfV() {return yTexOffs;} - }; + ModelPart* setTexSize(int xs, int ys); + void mimic(ModelPart* o); + void compile(float scale); + int getfU() { return xTexOffs; } + int getfV() { return yTexOffs; } +}; diff --git a/Minecraft.Client/Rendering/Models/OcelotModel.cpp b/Minecraft.Client/Rendering/Models/OcelotModel.cpp index 03e0e5dac..ba239b4cc 100644 --- a/Minecraft.Client/Rendering/Models/OcelotModel.cpp +++ b/Minecraft.Client/Rendering/Models/OcelotModel.cpp @@ -21,228 +21,214 @@ const float OzelotModel::backLegZ = 14 + zo; const float OzelotModel::frontLegY = -2.2f + yo; const float OzelotModel::frontLegZ = 4.f + zo; -OzelotModel::OzelotModel() -{ - state = WALK_STATE; +OzelotModel::OzelotModel() { + state = WALK_STATE; - setMapTex(L"head.main", 0, 0); - setMapTex(L"head.nose", 0, 24); - setMapTex(L"head.ear1", 0, 10); - setMapTex(L"head.ear2", 6, 10); + setMapTex(L"head.main", 0, 0); + setMapTex(L"head.nose", 0, 24); + setMapTex(L"head.ear1", 0, 10); + setMapTex(L"head.ear2", 6, 10); - head = new ModelPart(this, L"head"); - head->addBox(L"main", -2.5f, -2, -3, 5, 4, 5); - head->addBox(L"nose", -1.5f, 0, -4, 3, 2, 2); - head->addBox(L"ear1", -2, -3, 0, 1, 1, 2); - head->addBox(L"ear2", 1, -3, 0, 1, 1, 2); - head->setPos(0 + xo, headWalkY, headWalkZ); + head = new ModelPart(this, L"head"); + head->addBox(L"main", -2.5f, -2, -3, 5, 4, 5); + head->addBox(L"nose", -1.5f, 0, -4, 3, 2, 2); + head->addBox(L"ear1", -2, -3, 0, 1, 1, 2); + head->addBox(L"ear2", 1, -3, 0, 1, 1, 2); + head->setPos(0 + xo, headWalkY, headWalkZ); - body = new ModelPart(this, 20, 0); - body->addBox(-2, 3, -8, 4, 16, 6, 0); - body->setPos(0 + xo, bodyWalkY, bodyWalkZ); + body = new ModelPart(this, 20, 0); + body->addBox(-2, 3, -8, 4, 16, 6, 0); + body->setPos(0 + xo, bodyWalkY, bodyWalkZ); - tail1 = new ModelPart(this, 0, 15); - tail1->addBox(-0.5f, 0, 0, 1, 8, 1); - tail1->xRot = 0.9f; - tail1->setPos(0 + xo, tail1WalkY, tail1WalkZ); + tail1 = new ModelPart(this, 0, 15); + tail1->addBox(-0.5f, 0, 0, 1, 8, 1); + tail1->xRot = 0.9f; + tail1->setPos(0 + xo, tail1WalkY, tail1WalkZ); - tail2 = new ModelPart(this, 4, 15); - tail2->addBox(-0.5f, 0, 0, 1, 8, 1); - tail2->setPos(0 + xo, tail2WalkY, tail2WalkZ); + tail2 = new ModelPart(this, 4, 15); + tail2->addBox(-0.5f, 0, 0, 1, 8, 1); + tail2->setPos(0 + xo, tail2WalkY, tail2WalkZ); - backLegL = new ModelPart(this, 8, 13); - backLegL->addBox(-1, 0, 1, 2, 6, 2); - backLegL->setPos(1.1f + xo, backLegY, backLegZ); + backLegL = new ModelPart(this, 8, 13); + backLegL->addBox(-1, 0, 1, 2, 6, 2); + backLegL->setPos(1.1f + xo, backLegY, backLegZ); - backLegR = new ModelPart(this, 8, 13); - backLegR->addBox(-1, 0, 1, 2, 6, 2); - backLegR->setPos(-1.1f + xo, backLegY, backLegZ); + backLegR = new ModelPart(this, 8, 13); + backLegR->addBox(-1, 0, 1, 2, 6, 2); + backLegR->setPos(-1.1f + xo, backLegY, backLegZ); - frontLegL = new ModelPart(this, 40, 0); - frontLegL->addBox(-1, 0, 0, 2, 10, 2); - frontLegL->setPos(1.2f + xo, frontLegY, frontLegZ); + frontLegL = new ModelPart(this, 40, 0); + frontLegL->addBox(-1, 0, 0, 2, 10, 2); + frontLegL->setPos(1.2f + xo, frontLegY, frontLegZ); - frontLegR = new ModelPart(this, 40, 0); - frontLegR->addBox(-1, 0, 0, 2, 10, 2); - frontLegR->setPos(-1.2f + xo, frontLegY, frontLegZ); + frontLegR = new ModelPart(this, 40, 0); + frontLegR->addBox(-1, 0, 0, 2, 10, 2); + frontLegR->setPos(-1.2f + xo, frontLegY, frontLegZ); - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - tail1->compile(1.0f/16.0f); - tail2->compile(1.0f/16.0f); - backLegL->compile(1.0f/16.0f); - backLegR->compile(1.0f/16.0f); - backLegL->compile(1.0f/16.0f); - backLegR->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + tail1->compile(1.0f / 16.0f); + tail2->compile(1.0f / 16.0f); + backLegL->compile(1.0f / 16.0f); + backLegR->compile(1.0f / 16.0f); + backLegL->compile(1.0f / 16.0f); + backLegR->compile(1.0f / 16.0f); } -void OzelotModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); - glTranslatef(0, 10 * scale, 4 * scale); - head->render(scale, usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - backLegL->render(scale, usecompiled); - backLegR->render(scale, usecompiled); - frontLegL->render(scale, usecompiled); - frontLegR->render(scale, usecompiled); - tail1->render(scale, usecompiled); - tail2->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled); - body->render(scale, usecompiled); - tail1->render(scale, usecompiled); - tail2->render(scale, usecompiled); - backLegL->render(scale, usecompiled); - backLegR->render(scale, usecompiled); - frontLegL->render(scale, usecompiled); - frontLegR->render(scale, usecompiled); - } +void OzelotModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + if (young) { + float ss = 2.0f; + glPushMatrix(); + glScalef(1.5f / ss, 1.5f / ss, 1.5f / ss); + glTranslatef(0, 10 * scale, 4 * scale); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + backLegL->render(scale, usecompiled); + backLegR->render(scale, usecompiled); + frontLegL->render(scale, usecompiled); + frontLegR->render(scale, usecompiled); + tail1->render(scale, usecompiled); + tail2->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + body->render(scale, usecompiled); + tail1->render(scale, usecompiled); + tail2->render(scale, usecompiled); + backLegL->render(scale, usecompiled); + backLegR->render(scale, usecompiled); + frontLegL->render(scale, usecompiled); + frontLegR->render(scale, usecompiled); + } } -void OzelotModel::render(OzelotModel *model, float scale, bool usecompiled) -{ - head->yRot = model->head->yRot; - head->xRot = model->head->xRot; - head->y = model->head->y; - head->x = model->head->x; - body->yRot = model->body->yRot; - body->xRot = model->body->xRot; +void OzelotModel::render(OzelotModel* model, float scale, bool usecompiled) { + head->yRot = model->head->yRot; + head->xRot = model->head->xRot; + head->y = model->head->y; + head->x = model->head->x; + body->yRot = model->body->yRot; + body->xRot = model->body->xRot; - tail1->yRot = model->body->yRot; - tail1->y = model->body->y; - tail1->x = model->body->x; - tail1->render(scale, usecompiled); + tail1->yRot = model->body->yRot; + tail1->y = model->body->y; + tail1->x = model->body->x; + tail1->render(scale, usecompiled); - tail2->yRot = model->body->yRot; - tail2->y = model->body->y; - tail2->x = model->body->x; - tail2->render(scale, usecompiled); + tail2->yRot = model->body->yRot; + tail2->y = model->body->y; + tail2->x = model->body->x; + tail2->render(scale, usecompiled); - backLegL->xRot = model->backLegL->xRot; - backLegR->xRot = model->backLegR->xRot; - backLegL->render(scale, usecompiled); - backLegR->render(scale, usecompiled); + backLegL->xRot = model->backLegL->xRot; + backLegR->xRot = model->backLegR->xRot; + backLegL->render(scale, usecompiled); + backLegR->render(scale, usecompiled); - frontLegL->xRot = model->frontLegL->xRot; - frontLegR->xRot = model->frontLegR->xRot; - frontLegL->render(scale, usecompiled); - frontLegR->render(scale, usecompiled); + frontLegL->xRot = model->frontLegL->xRot; + frontLegR->xRot = model->frontLegR->xRot; + frontLegL->render(scale, usecompiled); + frontLegR->render(scale, usecompiled); - head->render(scale, usecompiled); - body->render(scale, usecompiled); + head->render(scale, usecompiled); + body->render(scale, usecompiled); } -void OzelotModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->xRot = xRot / (float) (180 / PI); - head->yRot = yRot / (float) (180 / PI); +void OzelotModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->xRot = xRot / (float)(180 / PI); + head->yRot = yRot / (float)(180 / PI); - if (state == SITTING_STATE) - { + if (state == SITTING_STATE) { + } else { + body->xRot = 90 / (float)(180 / PI); + if (state == SPRINT_STATE) { + backLegL->xRot = ((float)Mth::cos(time * 0.6662f) * 1.f) * r; + backLegR->xRot = ((float)Mth::cos(time * 0.6662f + 0.3f) * 1.f) * r; + frontLegL->xRot = + ((float)Mth::cos(time * 0.6662f + PI + 0.3f) * 1.f) * r; + frontLegR->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.f) * r; + tail2->xRot = 0.55f * PI + 0.1f * PI * Mth::cos(time) * r; + } else { + backLegL->xRot = ((float)Mth::cos(time * 0.6662f) * 1.f) * r; + backLegR->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.f) * r; + frontLegL->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.f) * r; + frontLegR->xRot = ((float)Mth::cos(time * 0.6662f) * 1.f) * r; - } - else - { - body->xRot = 90 / (float) (180 / PI); - if (state == SPRINT_STATE) - { - backLegL->xRot = ((float) Mth::cos(time * 0.6662f) * 1.f) * r; - backLegR->xRot = ((float) Mth::cos(time * 0.6662f + 0.3f) * 1.f) * r; - frontLegL->xRot = ((float) Mth::cos(time * 0.6662f + PI + 0.3f) * 1.f) * r; - frontLegR->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.f) * r; - tail2->xRot = 0.55f * PI + 0.1f * PI * Mth::cos(time) * r; - } - else - { - backLegL->xRot = ((float) Mth::cos(time * 0.6662f) * 1.f) * r; - backLegR->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.f) * r; - frontLegL->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.f) * r; - frontLegR->xRot = ((float) Mth::cos(time * 0.6662f) * 1.f) * r; - - if (state == WALK_STATE) tail2->xRot = 0.55f * PI + 0.25f * PI * Mth::cos(time) * r; - else tail2->xRot = 0.55f * PI + 0.15f * PI * Mth::cos(time) * r; - } - } + if (state == WALK_STATE) + tail2->xRot = 0.55f * PI + 0.25f * PI * Mth::cos(time) * r; + else + tail2->xRot = 0.55f * PI + 0.15f * PI * Mth::cos(time) * r; + } + } } -void OzelotModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - std::shared_ptr ozelot = std::dynamic_pointer_cast(mob); +void OzelotModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { + std::shared_ptr ozelot = std::dynamic_pointer_cast(mob); - body->y = bodyWalkY; - body->z = bodyWalkZ; - head->y = headWalkY; - head->z = headWalkZ; - tail1->y = tail1WalkY; - tail1->z = tail1WalkZ; - tail2->y = tail2WalkY; - tail2->z = tail2WalkZ; - frontLegL->y = frontLegR->y = frontLegY; - frontLegL->z = frontLegR->z = frontLegZ; - backLegL->y = backLegR->y = backLegY; - backLegL->z = backLegR->z = backLegZ; - tail1->xRot = 0.9f; + body->y = bodyWalkY; + body->z = bodyWalkZ; + head->y = headWalkY; + head->z = headWalkZ; + tail1->y = tail1WalkY; + tail1->z = tail1WalkZ; + tail2->y = tail2WalkY; + tail2->z = tail2WalkZ; + frontLegL->y = frontLegR->y = frontLegY; + frontLegL->z = frontLegR->z = frontLegZ; + backLegL->y = backLegR->y = backLegY; + backLegL->z = backLegR->z = backLegZ; + tail1->xRot = 0.9f; - if (ozelot->isSneaking()) - { - body->y += 1; - head->y += 2; - tail1->y += 1; - tail2->y += -4; - tail2->z += 2; - tail1->xRot = 0.5f * PI; - tail2->xRot = 0.5f * PI; - state = SNEAK_STATE; - } - else if (ozelot->isSprinting()) - { - tail2->y = tail1->y; - tail2->z += 2; - tail1->xRot = 0.5f * PI; - tail2->xRot = 0.5f * PI; - state = SPRINT_STATE; - } - else if (ozelot->isSitting()) - { - body->xRot = 45 / (float) (180 / PI); - body->y += -4; - body->z += 5; - head->y += -3.3f; - head->z += 1; + if (ozelot->isSneaking()) { + body->y += 1; + head->y += 2; + tail1->y += 1; + tail2->y += -4; + tail2->z += 2; + tail1->xRot = 0.5f * PI; + tail2->xRot = 0.5f * PI; + state = SNEAK_STATE; + } else if (ozelot->isSprinting()) { + tail2->y = tail1->y; + tail2->z += 2; + tail1->xRot = 0.5f * PI; + tail2->xRot = 0.5f * PI; + state = SPRINT_STATE; + } else if (ozelot->isSitting()) { + body->xRot = 45 / (float)(180 / PI); + body->y += -4; + body->z += 5; + head->y += -3.3f; + head->z += 1; - tail1->y += 8; - tail1->z += -2; - tail2->y += 2; - tail2->z += -0.8f; - tail1->xRot = PI * 0.55f; - tail2->xRot = PI * 0.85f; + tail1->y += 8; + tail1->z += -2; + tail2->y += 2; + tail2->z += -0.8f; + tail1->xRot = PI * 0.55f; + tail2->xRot = PI * 0.85f; - frontLegL->xRot = frontLegR->xRot = -PI * 0.05f; - frontLegL->y = frontLegR->y = frontLegY + 2; - frontLegL->z = frontLegR->z = -7; + frontLegL->xRot = frontLegR->xRot = -PI * 0.05f; + frontLegL->y = frontLegR->y = frontLegY + 2; + frontLegL->z = frontLegR->z = -7; - backLegL->xRot = backLegR->xRot = -PI * 0.5f; - backLegL->y = backLegR->y = backLegY + 3; - backLegL->z = backLegR->z = backLegZ - 4; - state = SITTING_STATE; - } - else - { - state = WALK_STATE; - } + backLegL->xRot = backLegR->xRot = -PI * 0.5f; + backLegL->y = backLegR->y = backLegY + 3; + backLegL->z = backLegR->z = backLegZ - 4; + state = SITTING_STATE; + } else { + state = WALK_STATE; + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/OcelotModel.h b/Minecraft.Client/Rendering/Models/OcelotModel.h index cdccc8fe8..c34b8e0d6 100644 --- a/Minecraft.Client/Rendering/Models/OcelotModel.h +++ b/Minecraft.Client/Rendering/Models/OcelotModel.h @@ -2,42 +2,44 @@ #include "Model.h" -class OzelotModel : public Model -{ +class OzelotModel : public Model { private: - ModelPart *backLegL, *backLegR; - ModelPart *frontLegL, *frontLegR; - ModelPart *tail1, *tail2, *head, *body; + ModelPart *backLegL, *backLegR; + ModelPart *frontLegL, *frontLegR; + ModelPart *tail1, *tail2, *head, *body; - static const int SNEAK_STATE = 0; - static const int WALK_STATE = 1; - static const int SPRINT_STATE = 2; - static const int SITTING_STATE = 3; + static const int SNEAK_STATE = 0; + static const int WALK_STATE = 1; + static const int SPRINT_STATE = 2; + static const int SITTING_STATE = 3; - int state; + int state; - static const float xo; - static const float yo; - static const float zo; + static const float xo; + static const float yo; + static const float zo; - static const float headWalkY; - static const float headWalkZ; - static const float bodyWalkY; - static const float bodyWalkZ; - static const float tail1WalkY; - static const float tail1WalkZ; - static const float tail2WalkY; - static const float tail2WalkZ; - static const float backLegY; - static const float backLegZ; - static const float frontLegY; - static const float frontLegZ ; + static const float headWalkY; + static const float headWalkZ; + static const float bodyWalkY; + static const float bodyWalkZ; + static const float tail1WalkY; + static const float tail1WalkZ; + static const float tail2WalkY; + static const float tail2WalkZ; + static const float backLegY; + static const float backLegZ; + static const float frontLegY; + static const float frontLegZ; public: - OzelotModel(); + OzelotModel(); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void render(OzelotModel *model, float scale, bool usecompiled); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + void render(OzelotModel* model, float scale, bool usecompiled); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/PigModel.cpp b/Minecraft.Client/Rendering/Models/PigModel.cpp index f5facc2f6..eb5308133 100644 --- a/Minecraft.Client/Rendering/Models/PigModel.cpp +++ b/Minecraft.Client/Rendering/Models/PigModel.cpp @@ -2,19 +2,16 @@ #include "PigModel.h" #include "ModelPart.h" -PigModel::PigModel() : QuadrupedModel(6, 0) -{ - head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, 0.0f); - yHeadOffs = 4; +PigModel::PigModel() : QuadrupedModel(6, 0) { + head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, 0.0f); + yHeadOffs = 4; - head->compile(1.0f/16.0f); + head->compile(1.0f / 16.0f); } -PigModel::PigModel(float grow) : QuadrupedModel(6, grow) -{ - head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, grow); - yHeadOffs = 4; +PigModel::PigModel(float grow) : QuadrupedModel(6, grow) { + head->texOffs(16, 16)->addBox(-2.0f, 0.0f, -9.0f, 4, 3, 1, grow); + yHeadOffs = 4; - head->compile(1.0f/16.0f); + head->compile(1.0f / 16.0f); } - diff --git a/Minecraft.Client/Rendering/Models/PigModel.h b/Minecraft.Client/Rendering/Models/PigModel.h index c443115d9..1f5998a52 100644 --- a/Minecraft.Client/Rendering/Models/PigModel.h +++ b/Minecraft.Client/Rendering/Models/PigModel.h @@ -1,10 +1,8 @@ #pragma once #include "QuadrupedModel.h" -class PigModel : public QuadrupedModel -{ +class PigModel : public QuadrupedModel { public: - - PigModel(); - PigModel(float grow); + PigModel(); + PigModel(float grow); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp b/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp index ff9354681..f5685c209 100644 --- a/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp +++ b/Minecraft.Client/Rendering/Models/QuadrupedModel.cpp @@ -3,79 +3,78 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -QuadrupedModel::QuadrupedModel(int legSize, float g) : Model() -{ - yHeadOffs = 8; - zHeadOffs = 4; +QuadrupedModel::QuadrupedModel(int legSize, float g) : Model() { + yHeadOffs = 8; + zHeadOffs = 4; - head = new ModelPart(this, 0, 0); - head->addBox(-4, -4, -8, 8, 8, 8, g); // Head - head->setPos(0, (float)(12 + 6 - legSize), -6); + head = new ModelPart(this, 0, 0); + head->addBox(-4, -4, -8, 8, 8, 8, g); // Head + head->setPos(0, (float)(12 + 6 - legSize), -6); - body = new ModelPart(this, 28, 8); - body->addBox(-5, -10, -7, 10, 16, 8, g); // Body - body->setPos(0, (float)(11 + 6 - legSize), 2); + body = new ModelPart(this, 28, 8); + body->addBox(-5, -10, -7, 10, 16, 8, g); // Body + body->setPos(0, (float)(11 + 6 - legSize), 2); - leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg0 - leg0->setPos(-3, (float)(18 + 6 - legSize), 7); + leg0 = new ModelPart(this, 0, 16); + leg0->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg0 + leg0->setPos(-3, (float)(18 + 6 - legSize), 7); - leg1 = new ModelPart(this, 0, 16); - leg1->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg1 - leg1->setPos(3, (float)(18 + 6 - legSize), 7); + leg1 = new ModelPart(this, 0, 16); + leg1->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg1 + leg1->setPos(3, (float)(18 + 6 - legSize), 7); - leg2 = new ModelPart(this, 0, 16); - leg2->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg2 - leg2->setPos(-3, (float)(18 + 6 - legSize), -5); + leg2 = new ModelPart(this, 0, 16); + leg2->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg2 + leg2->setPos(-3, (float)(18 + 6 - legSize), -5); - leg3 = new ModelPart(this, 0, 16); - leg3->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg3 - leg3->setPos(3, (float)(18 + 6 - legSize), -5); + leg3 = new ModelPart(this, 0, 16); + leg3->addBox(-2, 0, -2, 4, legSize, 4, g); // Leg3 + leg3->setPos(3, (float)(18 + 6 - legSize), -5); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); } -void QuadrupedModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void QuadrupedModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glTranslatef(0, yHeadOffs * scale, zHeadOffs * scale); - head->render(scale,usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - } + if (young) { + float ss = 2.0f; + glPushMatrix(); + glTranslatef(0, yHeadOffs * scale, zHeadOffs * scale); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + } } -void QuadrupedModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - float rad = (float) (180 / PI); +void QuadrupedModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + float rad = (float)(180 / PI); head->xRot = xRot / rad; head->yRot = yRot / rad; body->xRot = 90 / rad; @@ -86,8 +85,8 @@ void QuadrupedModel::setupAnim(float time, float r, float bob, float yRot, float leg3->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; } -void QuadrupedModel::render(QuadrupedModel *model, float scale, bool usecompiled) -{ +void QuadrupedModel::render(QuadrupedModel* model, float scale, + bool usecompiled) { head->yRot = model->head->yRot; head->xRot = model->head->xRot; @@ -102,30 +101,27 @@ void QuadrupedModel::render(QuadrupedModel *model, float scale, bool usecompiled leg2->xRot = model->leg2->xRot; leg3->xRot = model->leg3->xRot; - if (young) - { - float ss = 2.0f; - glPushMatrix(); - glTranslatef(0, 8 * scale, 4 * scale); - head->render(scale,usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->render(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - } + if (young) { + float ss = 2.0f; + glPushMatrix(); + glTranslatef(0, 8 * scale, 4 * scale); + head->render(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + glPopMatrix(); + } else { + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + } } diff --git a/Minecraft.Client/Rendering/Models/QuadrupedModel.h b/Minecraft.Client/Rendering/Models/QuadrupedModel.h index d1c24de78..f7dcdc0d9 100644 --- a/Minecraft.Client/Rendering/Models/QuadrupedModel.h +++ b/Minecraft.Client/Rendering/Models/QuadrupedModel.h @@ -1,13 +1,16 @@ #pragma once #include "Model.h" -class QuadrupedModel : public Model -{ +class QuadrupedModel : public Model { public: - ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; + ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; - QuadrupedModel(int legSize, float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void render(QuadrupedModel *model, float scale, bool usecompiled); + QuadrupedModel(int legSize, float g); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + void render(QuadrupedModel* model, float scale, bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepFurModel.cpp b/Minecraft.Client/Rendering/Models/SheepFurModel.cpp index c12ad5fdc..de078c74e 100644 --- a/Minecraft.Client/Rendering/Models/SheepFurModel.cpp +++ b/Minecraft.Client/Rendering/Models/SheepFurModel.cpp @@ -3,55 +3,56 @@ #include "SheepFurModel.h" #include "ModelPart.h" -SheepFurModel::SheepFurModel() : QuadrupedModel(12, 0) -{ - headXRot = 0.0f; +SheepFurModel::SheepFurModel() : QuadrupedModel(12, 0) { + headXRot = 0.0f; head = new ModelPart(this, 0, 0); - head->addBox(-3, -4, -4, 6, 6, 6, 0.6f); // Head + head->addBox(-3, -4, -4, 6, 6, 6, 0.6f); // Head head->setPos(0, 12 - 6, -8); body = new ModelPart(this, 28, 8); - body->addBox(-4, -10, -7, 8, 16, 6, 1.75f); // Body + body->addBox(-4, -10, -7, 8, 16, 6, 1.75f); // Body body->setPos(0, 11 + 6 - 12, 2); float g = 0.5f; leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 + leg0->addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 leg0->setPos(-3, 18 + 6 - 12, 7); leg1 = new ModelPart(this, 0, 16); - leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 + leg1->addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 leg1->setPos(3, 18 + 6 - 12, 7); leg2 = new ModelPart(this, 0, 16); - leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 + leg2->addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 leg2->setPos(-3, 18 + 6 - 12, -5); leg3 = new ModelPart(this, 0, 16); - leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 + leg3->addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 leg3->setPos(3, 18 + 6 - 12, -5); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); } -void SheepFurModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - QuadrupedModel::prepareMobModel(mob, time, r, a); +void SheepFurModel::prepareMobModel(std::shared_ptr mob, float time, + float r, float a) { + QuadrupedModel::prepareMobModel(mob, time, r, a); - std::shared_ptr sheep = std::dynamic_pointer_cast(mob); - head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; - headXRot = sheep->getHeadEatAngleScale(a); + std::shared_ptr sheep = std::dynamic_pointer_cast(mob); + head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; + headXRot = sheep->getHeadEatAngleScale(a); } -void SheepFurModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); - head->xRot = headXRot; +void SheepFurModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); + head->xRot = headXRot; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepFurModel.h b/Minecraft.Client/Rendering/Models/SheepFurModel.h index 65bb913ed..3b43feafb 100644 --- a/Minecraft.Client/Rendering/Models/SheepFurModel.h +++ b/Minecraft.Client/Rendering/Models/SheepFurModel.h @@ -1,13 +1,16 @@ #pragma once #include "QuadrupedModel.h" -class SheepFurModel : public QuadrupedModel -{ +class SheepFurModel : public QuadrupedModel { private: - float headXRot; -public: - SheepFurModel(); + float headXRot; - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); +public: + SheepFurModel(); + + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepModel.cpp b/Minecraft.Client/Rendering/Models/SheepModel.cpp index 40ded26ff..8599efe9c 100644 --- a/Minecraft.Client/Rendering/Models/SheepModel.cpp +++ b/Minecraft.Client/Rendering/Models/SheepModel.cpp @@ -3,35 +3,36 @@ #include "SheepModel.h" #include "ModelPart.h" -SheepModel::SheepModel() : QuadrupedModel(12, 0) -{ - headXRot = 0.0f; +SheepModel::SheepModel() : QuadrupedModel(12, 0) { + headXRot = 0.0f; head = new ModelPart(this, 0, 0); - head->addBox(-3, -4, -6, 6, 6, 8, 0); // Head - head->setPos(0, 12-6, -8); - + head->addBox(-3, -4, -6, 6, 6, 8, 0); // Head + head->setPos(0, 12 - 6, -8); + body = new ModelPart(this, 28, 8); - body->addBox(-4, -10, -7, 8, 16, 6, 0); // Body - body->setPos(0, 11+6-12, 2); + body->addBox(-4, -10, -7, 8, 16, 6, 0); // Body + body->setPos(0, 11 + 6 - 12, 2); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); } -void SheepModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - QuadrupedModel::prepareMobModel(mob, time, r, a); +void SheepModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { + QuadrupedModel::prepareMobModel(mob, time, r, a); - std::shared_ptr sheep = std::dynamic_pointer_cast(mob); - head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; - headXRot = sheep->getHeadEatAngleScale(a); + std::shared_ptr sheep = std::dynamic_pointer_cast(mob); + head->y = 6 + sheep->getHeadEatPositionScale(a) * 9.0f; + headXRot = sheep->getHeadEatAngleScale(a); } -void SheepModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); +void SheepModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + QuadrupedModel::setupAnim(time, r, bob, yRot, xRot, scale); - head->xRot = headXRot; + head->xRot = headXRot; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SheepModel.h b/Minecraft.Client/Rendering/Models/SheepModel.h index 78c3b7c8b..6fbfcebc2 100644 --- a/Minecraft.Client/Rendering/Models/SheepModel.h +++ b/Minecraft.Client/Rendering/Models/SheepModel.h @@ -1,13 +1,16 @@ #pragma once #include "QuadrupedModel.h" -class SheepModel : public QuadrupedModel -{ +class SheepModel : public QuadrupedModel { private: - float headXRot; -public: - SheepModel(); + float headXRot; - virtual void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); +public: + SheepModel(); + + virtual void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SignModel.cpp b/Minecraft.Client/Rendering/Models/SignModel.cpp index 1035d32fd..4b72bbbd0 100644 --- a/Minecraft.Client/Rendering/Models/SignModel.cpp +++ b/Minecraft.Client/Rendering/Models/SignModel.cpp @@ -2,21 +2,20 @@ #include "SignModel.h" #include "ModelPart.h" -SignModel::SignModel() -{ +SignModel::SignModel() { cube = new ModelPart(this, 0, 0); cube->addBox(-12, -14, -1, 24, 12, 2, 0); - + cube2 = new ModelPart(this, 0, 14); cube2->addBox(-1, -2, -1, 2, 14, 2, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - cube->compile(1.0f/16.0f); - cube2->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + cube->compile(1.0f / 16.0f); + cube2->compile(1.0f / 16.0f); } -void SignModel::render(bool usecompiled) -{ - cube->render(1/16.0f,usecompiled); - cube2->render(1/16.0f,usecompiled); +void SignModel::render(bool usecompiled) { + cube->render(1 / 16.0f, usecompiled); + cube2->render(1 / 16.0f, usecompiled); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SignModel.h b/Minecraft.Client/Rendering/Models/SignModel.h index 6de4ce131..3c2d26d22 100644 --- a/Minecraft.Client/Rendering/Models/SignModel.h +++ b/Minecraft.Client/Rendering/Models/SignModel.h @@ -4,13 +4,12 @@ class Cube; -class SignModel : public Model -{ +class SignModel : public Model { public: - using Model::render; - ModelPart *cube; - ModelPart *cube2; - + using Model::render; + ModelPart* cube; + ModelPart* cube2; + SignModel(); void render(bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/SilverfishModel.cpp b/Minecraft.Client/Rendering/Models/SilverfishModel.cpp index 6e03ee6dd..6ddc1187d 100644 --- a/Minecraft.Client/Rendering/Models/SilverfishModel.cpp +++ b/Minecraft.Client/Rendering/Models/SilverfishModel.cpp @@ -5,108 +5,79 @@ #include "ModelPart.h" const int SilverfishModel::BODY_SIZES[BODY_COUNT][3] = { - { - 3, 2, 2 - }, { - 4, 3, 2 - }, { - 6, 4, 3 - }, { - 3, 3, 3 - }, { - 2, 2, 3 - }, { - 2, 1, 2 - }, { - 1, 1, 2 - }, + {3, 2, 2}, {4, 3, 2}, {6, 4, 3}, {3, 3, 3}, {2, 2, 3}, {2, 1, 2}, {1, 1, 2}, }; const int SilverfishModel::BODY_TEXS[BODY_COUNT][2] = { - { - 0, 0 - }, { - 0, 4 - }, { - 0, 9 - }, { - 0, 16 - }, { - 0, 22 - }, { - 11, 0 - }, { - 13, 4 - }, + {0, 0}, {0, 4}, {0, 9}, {0, 16}, {0, 22}, {11, 0}, {13, 4}, }; -SilverfishModel::SilverfishModel() -{ - bodyParts = ModelPartArray(BODY_COUNT); - float placement = -3.5f; - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i] = new ModelPart(this, BODY_TEXS[i][0], BODY_TEXS[i][1]); - bodyParts[i]->addBox(BODY_SIZES[i][0] * -0.5f, 0, BODY_SIZES[i][2] * -0.5f, BODY_SIZES[i][0], BODY_SIZES[i][1], BODY_SIZES[i][2]); - bodyParts[i]->setPos(0.0f, 24.0f - (float)BODY_SIZES[i][1], placement); - zPlacement[i] = placement; - if (i < bodyParts.length - 1) - { - placement += (BODY_SIZES[i][2] + BODY_SIZES[i + 1][2]) * .5f; - } - } +SilverfishModel::SilverfishModel() { + bodyParts = ModelPartArray(BODY_COUNT); + float placement = -3.5f; + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i] = new ModelPart(this, BODY_TEXS[i][0], BODY_TEXS[i][1]); + bodyParts[i]->addBox(BODY_SIZES[i][0] * -0.5f, 0, + BODY_SIZES[i][2] * -0.5f, BODY_SIZES[i][0], + BODY_SIZES[i][1], BODY_SIZES[i][2]); + bodyParts[i]->setPos(0.0f, 24.0f - (float)BODY_SIZES[i][1], placement); + zPlacement[i] = placement; + if (i < bodyParts.length - 1) { + placement += (BODY_SIZES[i][2] + BODY_SIZES[i + 1][2]) * .5f; + } + } - bodyLayers = ModelPartArray(3); - bodyLayers[0] = new ModelPart(this, 20, 0); - bodyLayers[0]->addBox(-5, 0, BODY_SIZES[2][2] * -0.5f, 10, 8, BODY_SIZES[2][2]); - bodyLayers[0]->setPos(0, 24 - 8, zPlacement[2]); - bodyLayers[1] = new ModelPart(this, 20, 11); - bodyLayers[1]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 4, BODY_SIZES[4][2]); - bodyLayers[1]->setPos(0, 24 - 4, zPlacement[4]); - bodyLayers[2] = new ModelPart(this, 20, 18); - bodyLayers[2]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 5, BODY_SIZES[1][2]); - bodyLayers[2]->setPos(0, 24 - 5, zPlacement[1]); + bodyLayers = ModelPartArray(3); + bodyLayers[0] = new ModelPart(this, 20, 0); + bodyLayers[0]->addBox(-5, 0, BODY_SIZES[2][2] * -0.5f, 10, 8, + BODY_SIZES[2][2]); + bodyLayers[0]->setPos(0, 24 - 8, zPlacement[2]); + bodyLayers[1] = new ModelPart(this, 20, 11); + bodyLayers[1]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 4, + BODY_SIZES[4][2]); + bodyLayers[1]->setPos(0, 24 - 4, zPlacement[4]); + bodyLayers[2] = new ModelPart(this, 20, 18); + bodyLayers[2]->addBox(-3, 0, BODY_SIZES[4][2] * -0.5f, 6, 5, + BODY_SIZES[1][2]); + bodyLayers[2]->setPos(0, 24 - 5, zPlacement[1]); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i]->compile(1.0f/16.0f); - } - bodyLayers[0]->compile(1.0f/16.0f); - bodyLayers[1]->compile(1.0f/16.0f); - bodyLayers[2]->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i]->compile(1.0f / 16.0f); + } + bodyLayers[0]->compile(1.0f / 16.0f); + bodyLayers[1]->compile(1.0f / 16.0f); + bodyLayers[2]->compile(1.0f / 16.0f); } -int SilverfishModel::modelVersion() -{ - return 38; +int SilverfishModel::modelVersion() { return 38; } + +void SilverfishModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i]->render(scale, usecompiled); + } + for (unsigned int i = 0; i < bodyLayers.length; i++) { + bodyLayers[i]->render(scale, usecompiled); + } } -void SilverfishModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); - - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i]->render(scale, usecompiled); - } - for (unsigned int i = 0; i < bodyLayers.length; i++) - { - bodyLayers[i]->render(scale, usecompiled); - } -} - -void SilverfishModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - - for (unsigned int i = 0; i < bodyParts.length; i++) - { - bodyParts[i]->yRot = Mth::cos(bob * .9f + i * .15f * PI) * PI * .05f * (1 + abs((int)i - 2)); - bodyParts[i]->x = Mth::sin(bob * .9f + i * .15f * PI) * PI * .2f * abs((int)i - 2); - } - bodyLayers[0]->yRot = bodyParts[2]->yRot; - bodyLayers[1]->yRot = bodyParts[4]->yRot; - bodyLayers[1]->x = bodyParts[4]->x; - bodyLayers[2]->yRot = bodyParts[1]->yRot; - bodyLayers[2]->x = bodyParts[1]->x; +void SilverfishModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + for (unsigned int i = 0; i < bodyParts.length; i++) { + bodyParts[i]->yRot = Mth::cos(bob * .9f + i * .15f * PI) * PI * .05f * + (1 + abs((int)i - 2)); + bodyParts[i]->x = + Mth::sin(bob * .9f + i * .15f * PI) * PI * .2f * abs((int)i - 2); + } + bodyLayers[0]->yRot = bodyParts[2]->yRot; + bodyLayers[1]->yRot = bodyParts[4]->yRot; + bodyLayers[1]->x = bodyParts[4]->x; + bodyLayers[2]->yRot = bodyParts[1]->yRot; + bodyLayers[2]->x = bodyParts[1]->x; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SilverfishModel.h b/Minecraft.Client/Rendering/Models/SilverfishModel.h index 4ce0e16ee..9db32edd5 100644 --- a/Minecraft.Client/Rendering/Models/SilverfishModel.h +++ b/Minecraft.Client/Rendering/Models/SilverfishModel.h @@ -2,25 +2,26 @@ #include "Model.h" -class SilverfishModel : public Model -{ +class SilverfishModel : public Model { +private: + static const int BODY_COUNT = 7; private: - static const int BODY_COUNT = 7; + ModelPartArray bodyParts; + ModelPartArray bodyLayers; + float zPlacement[BODY_COUNT]; -private: - ModelPartArray bodyParts; - ModelPartArray bodyLayers; - float zPlacement[BODY_COUNT]; + static const int BODY_SIZES[BODY_COUNT][3]; - static const int BODY_SIZES[BODY_COUNT][3]; - - static const int BODY_TEXS[BODY_COUNT][2]; + static const int BODY_TEXS[BODY_COUNT][2]; public: - SilverfishModel(); + SilverfishModel(); - int modelVersion(); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + int modelVersion(); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp index 6f472a0c2..4b84b1e88 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp +++ b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.cpp @@ -2,42 +2,42 @@ #include "ModelPart.h" #include "SkeletonHeadModel.h" -void SkeletonHeadModel::_init(int u, int v, int tw, int th) -{ - texWidth = tw; - texHeight = th; - head = new ModelPart(this, u, v); +void SkeletonHeadModel::_init(int u, int v, int tw, int th) { + texWidth = tw; + texHeight = th; + head = new ModelPart(this, u, v); - // 4J Stu - Set "g" param to 0.1 to fix z-fighting issues (hair has this set to 0.5, so need to be less that that) - // Fix for #101501 - TU12: Content: Art: Z-Fighting occurs on the bottom side of a character's head when a Mob Head is equipped. - head->addBox(-4, -8, -4, 8, 8, 8, 0.1); // Head - head->setPos(0, 0, 0); + // 4J Stu - Set "g" param to 0.1 to fix z-fighting issues (hair has this set + // to 0.5, so need to be less that that) Fix for #101501 - TU12: Content: + // Art: Z-Fighting occurs on the bottom side of a character's head when a + // Mob Head is equipped. + head->addBox(-4, -8, -4, 8, 8, 8, 0.1); // Head + head->setPos(0, 0, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); } -SkeletonHeadModel::SkeletonHeadModel() -{ - _init(0, 35, 64, 64); +SkeletonHeadModel::SkeletonHeadModel() { _init(0, 35, 64, 64); } + +SkeletonHeadModel::SkeletonHeadModel(int u, int v, int tw, int th) { + _init(u, v, tw, th); } -SkeletonHeadModel::SkeletonHeadModel(int u, int v, int tw, int th) -{ - _init(u,v,tw,th); +void SkeletonHeadModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); + + head->render(scale, usecompiled); } -void SkeletonHeadModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void SkeletonHeadModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + Model::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); - head->render(scale,usecompiled); -} - -void SkeletonHeadModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - Model::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); - - head->yRot = yRot / (180 / PI); - head->xRot = xRot / (180 / PI); + head->yRot = yRot / (180 / PI); + head->xRot = xRot / (180 / PI); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h index aa045571e..b276c0ce5 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h +++ b/Minecraft.Client/Rendering/Models/SkeletonHeadModel.h @@ -2,18 +2,19 @@ #include "Model.h" -class SkeletonHeadModel : public Model -{ +class SkeletonHeadModel : public Model { public: - ModelPart *head; + ModelPart* head; private: - void _init(int u, int v, int tw, int th); + void _init(int u, int v, int tw, int th); public: - SkeletonHeadModel(); - SkeletonHeadModel(int u, int v, int tw, int th); + SkeletonHeadModel(); + SkeletonHeadModel(int u, int v, int tw, int th); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonModel.cpp b/Minecraft.Client/Rendering/Models/SkeletonModel.cpp index 0239e4c44..d6d363257 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonModel.cpp +++ b/Minecraft.Client/Rendering/Models/SkeletonModel.cpp @@ -3,45 +3,41 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -void SkeletonModel::_init(float g) -{ +void SkeletonModel::_init(float g) { arm0 = new ModelPart(this, 24 + 16, 16); - arm0->addBox(-1, -2, -1, 2, 12, 2, g); // Arm0 + arm0->addBox(-1, -2, -1, 2, 12, 2, g); // Arm0 arm0->setPos(-5, 2, 0); arm1 = new ModelPart(this, 24 + 16, 16); arm1->bMirror = true; - arm1->addBox(-1, -2, -1, 2, 12, 2, g); // Arm1 + arm1->addBox(-1, -2, -1, 2, 12, 2, g); // Arm1 arm1->setPos(5, 2, 0); leg0 = new ModelPart(this, 0, 16); - leg0->addBox(-1, 0, -1, 2, 12, 2, g); // Leg0 + leg0->addBox(-1, 0, -1, 2, 12, 2, g); // Leg0 leg0->setPos(-2, 12, 0); leg1 = new ModelPart(this, 0, 16); leg1->bMirror = true; - leg1->addBox(-1, 0, -1, 2, 12, 2, g); // Leg1 + leg1->addBox(-1, 0, -1, 2, 12, 2, g); // Leg1 leg1->setPos(2, 12, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - arm0->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + arm0->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); } -SkeletonModel::SkeletonModel() : ZombieModel(0, 0, 64, 32) -{ - _init(0); -} +SkeletonModel::SkeletonModel() : ZombieModel(0, 0, 64, 32) { _init(0); } -SkeletonModel::SkeletonModel(float g) : ZombieModel(g, 0, 64, 32) -{ - _init(g); -} +SkeletonModel::SkeletonModel(float g) : ZombieModel(g, 0, 64, 32) { _init(g); } -void SkeletonModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - bowAndArrow=true; - ZombieModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); +void SkeletonModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + bowAndArrow = true; + ZombieModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkeletonModel.h b/Minecraft.Client/Rendering/Models/SkeletonModel.h index ba5f9449d..db0d093ac 100644 --- a/Minecraft.Client/Rendering/Models/SkeletonModel.h +++ b/Minecraft.Client/Rendering/Models/SkeletonModel.h @@ -1,13 +1,14 @@ #pragma once #include "ZombieModel.h" -class SkeletonModel : public ZombieModel -{ +class SkeletonModel : public ZombieModel { private: - void _init(float g); + void _init(float g); public: - SkeletonModel(); - SkeletonModel(float g); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + SkeletonModel(); + SkeletonModel(float g); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SkinBox.h b/Minecraft.Client/Rendering/Models/SkinBox.h index 827e4447c..eaa39143c 100644 --- a/Minecraft.Client/Rendering/Models/SkinBox.h +++ b/Minecraft.Client/Rendering/Models/SkinBox.h @@ -1,19 +1,16 @@ #pragma once -enum eBodyPart -{ - eBodyPart_Unknown=0, - eBodyPart_Head, - eBodyPart_Body, - eBodyPart_Arm0, - eBodyPart_Arm1, - eBodyPart_Leg0, - eBodyPart_Leg1, +enum eBodyPart { + eBodyPart_Unknown = 0, + eBodyPart_Head, + eBodyPart_Body, + eBodyPart_Arm0, + eBodyPart_Arm1, + eBodyPart_Leg0, + eBodyPart_Leg1, }; -typedef struct -{ - eBodyPart ePart; - float fX,fY,fZ,fW,fH,fD,fU,fV; -} -SKIN_BOX; +typedef struct { + eBodyPart ePart; + float fX, fY, fZ, fW, fH, fD, fU, fV; +} SKIN_BOX; diff --git a/Minecraft.Client/Rendering/Models/SlimeModel.cpp b/Minecraft.Client/Rendering/Models/SlimeModel.cpp index b8244ebbd..029d7a1c4 100644 --- a/Minecraft.Client/Rendering/Models/SlimeModel.cpp +++ b/Minecraft.Client/Rendering/Models/SlimeModel.cpp @@ -2,47 +2,44 @@ #include "SlimeModel.h" #include "ModelPart.h" -SlimeModel::SlimeModel(int vOffs) -{ +SlimeModel::SlimeModel(int vOffs) { cube = new ModelPart(this, 0, vOffs); cube->addBox(-4, 16, -4, 8, 8, 8); - if (vOffs > 0) - { + if (vOffs > 0) { cube = new ModelPart(this, 0, vOffs); - cube->addBox(-3, 16+1, -3, 6, 6, 6); + cube->addBox(-3, 16 + 1, -3, 6, 6, 6); eye0 = new ModelPart(this, 32, 0); - eye0->addBox(-3-0.25f, 16+2, -3.5f, 2, 2, 2); + eye0->addBox(-3 - 0.25f, 16 + 2, -3.5f, 2, 2, 2); eye1 = new ModelPart(this, 32, 4); - eye1->addBox(+1+0.25f, 16+2, -3.5f, 2, 2, 2); + eye1->addBox(+1 + 0.25f, 16 + 2, -3.5f, 2, 2, 2); mouth = new ModelPart(this, 32, 8); - mouth->addBox(0, 16+5, -3.5f, 1, 1, 1); + mouth->addBox(0, 16 + 5, -3.5f, 1, 1, 1); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - eye0->compile(1.0f/16.0f); - eye1->compile(1.0f/16.0f); - mouth->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time + // cubes are rendered + eye0->compile(1.0f / 16.0f); + eye1->compile(1.0f / 16.0f); + mouth->compile(1.0f / 16.0f); + } else { + eye0 = NULL; + eye1 = NULL; + mouth = NULL; } - else - { - eye0 = NULL; - eye1 = NULL; - mouth = NULL; - } - cube->compile(1.0f/16.0f); + cube->compile(1.0f / 16.0f); } -void SlimeModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void SlimeModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - cube->render(scale,usecompiled); - if (eye0!=NULL) - { - eye0->render(scale,usecompiled); - eye1->render(scale,usecompiled); - mouth->render(scale,usecompiled); + cube->render(scale, usecompiled); + if (eye0 != NULL) { + eye0->render(scale, usecompiled); + eye1->render(scale, usecompiled); + mouth->render(scale, usecompiled); } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SlimeModel.h b/Minecraft.Client/Rendering/Models/SlimeModel.h index fe2a4fc2b..c9c8cadcb 100644 --- a/Minecraft.Client/Rendering/Models/SlimeModel.h +++ b/Minecraft.Client/Rendering/Models/SlimeModel.h @@ -1,13 +1,14 @@ #pragma once #include "Model.h" -class SlimeModel : public Model -{ +class SlimeModel : public Model { public: - ModelPart *cube; - ModelPart *eye0, *eye1,* mouth; + ModelPart* cube; + ModelPart *eye0, *eye1, *mouth; SlimeModel(int vOffs); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SnowManModel.cpp b/Minecraft.Client/Rendering/Models/SnowManModel.cpp index ba1053e1b..5d9daa888 100644 --- a/Minecraft.Client/Rendering/Models/SnowManModel.cpp +++ b/Minecraft.Client/Rendering/Models/SnowManModel.cpp @@ -3,70 +3,70 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -SnowManModel::SnowManModel() : Model() -{ +SnowManModel::SnowManModel() : Model() { float yOffset = 4; float g = 0; head = (new ModelPart(this, 0, 0))->setTexSize(64, 64); - head->addBox(-4, -8, -4, 8, 8, 8, g - 0.5f); // head + head->addBox(-4, -8, -4, 8, 8, 8, g - 0.5f); // head head->setPos(0, 0 + yOffset, 0); arm1 = (new ModelPart(this, 32, 0))->setTexSize(64, 64); - arm1->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm + arm1->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm arm1->setPos(0, 0 + yOffset + 9 - 7, 0); arm2 = (new ModelPart(this, 32, 0))->setTexSize(64, 64); - arm2->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm + arm2->addBox(-1, 0, -1, 12, 2, 2, g - 0.5f); // arm arm2->setPos(0, 0 + yOffset + 9 - 7, 0); piece1 = (new ModelPart(this, 0, 16))->setTexSize(64, 64); - piece1->addBox(-5, -10, -5, 10, 10, 10, g - 0.5f); // upper body + piece1->addBox(-5, -10, -5, 10, 10, 10, g - 0.5f); // upper body piece1->setPos(0, 0 + yOffset + 9, 0); piece2 = (new ModelPart(this, 0, 36))->setTexSize(64, 64); - piece2->addBox(-6, -12, -6, 12, 12, 12, g - 0.5f); // lower body - piece2->setPos(0, 0 + yOffset + 20, 0); + piece2->addBox(-6, -12, -6, 12, 12, 12, g - 0.5f); // lower body + piece2->setPos(0, 0 + yOffset + 20, 0); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - arm1->compile(1.0f/16.0f); - arm2->compile(1.0f/16.0f); - piece1->compile(1.0f/16.0f); - piece2->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + arm1->compile(1.0f / 16.0f); + arm2->compile(1.0f / 16.0f); + piece1->compile(1.0f / 16.0f); + piece2->compile(1.0f / 16.0f); } -void SnowManModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ +void SnowManModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { Model::setupAnim(time, r, bob, yRot, xRot, scale); - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); - piece1->yRot = (yRot / (float) (180 / PI)) * 0.25f; + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); + piece1->yRot = (yRot / (float)(180 / PI)) * 0.25f; - float s = Mth::sin(piece1->yRot); - float c = Mth::cos(piece1->yRot); + float s = Mth::sin(piece1->yRot); + float c = Mth::cos(piece1->yRot); - arm1->zRot = 1; - arm2->zRot = -1; - arm1->yRot = 0 + piece1->yRot; - arm2->yRot = PI + piece1->yRot; + arm1->zRot = 1; + arm2->zRot = -1; + arm1->yRot = 0 + piece1->yRot; + arm2->yRot = PI + piece1->yRot; - arm1->x = (c) * 5; - arm1->z = (-s) * 5; - - arm2->x = (-c) * 5; - arm2->z = (s) * 5; + arm1->x = (c) * 5; + arm1->z = (-s) * 5; + + arm2->x = (-c) * 5; + arm2->z = (s) * 5; } -void SnowManModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void SnowManModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); - piece1->render(scale,usecompiled); - piece2->render(scale,usecompiled); - head->render(scale,usecompiled); - arm1->render(scale,usecompiled); - arm2->render(scale,usecompiled); + piece1->render(scale, usecompiled); + piece2->render(scale, usecompiled); + head->render(scale, usecompiled); + arm1->render(scale, usecompiled); + arm2->render(scale, usecompiled); } - - diff --git a/Minecraft.Client/Rendering/Models/SnowManModel.h b/Minecraft.Client/Rendering/Models/SnowManModel.h index b2d8229ac..971172a22 100644 --- a/Minecraft.Client/Rendering/Models/SnowManModel.h +++ b/Minecraft.Client/Rendering/Models/SnowManModel.h @@ -1,13 +1,15 @@ #pragma once #include "Model.h" -class SnowManModel : public Model -{ +class SnowManModel : public Model { public: - ModelPart *piece1, *piece2, *head; - ModelPart *arm1, *arm2; + ModelPart *piece1, *piece2, *head; + ModelPart *arm1, *arm2; - SnowManModel() ; - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + SnowManModel(); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); }; diff --git a/Minecraft.Client/Rendering/Models/SpiderModel.cpp b/Minecraft.Client/Rendering/Models/SpiderModel.cpp index ff1a79b1d..da0dff534 100644 --- a/Minecraft.Client/Rendering/Models/SpiderModel.cpp +++ b/Minecraft.Client/Rendering/Models/SpiderModel.cpp @@ -3,108 +3,109 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -SpiderModel::SpiderModel() : Model() -{ +SpiderModel::SpiderModel() : Model() { float g = 0; - - int yo = 18+6-9; + + int yo = 18 + 6 - 9; head = new ModelPart(this, 32, 4); - head->addBox(-4, -4, -8, 8, 8, 8, g); // Head - head->setPos(0, (float)(0+yo), -3); + head->addBox(-4, -4, -8, 8, 8, 8, g); // Head + head->setPos(0, (float)(0 + yo), -3); body0 = new ModelPart(this, 0, 0); - body0->addBox(-3, -3, -3, 6, 6, 6, g); // Body - body0->setPos(0,(float)(yo), 0); + body0->addBox(-3, -3, -3, 6, 6, 6, g); // Body + body0->setPos(0, (float)(yo), 0); body1 = new ModelPart(this, 0, 12); - body1->addBox(-5, -4, -6, 10, 8, 12, g); // Body - body1->setPos(0, (float)(0+yo), 3 + 6); - + body1->addBox(-5, -4, -6, 10, 8, 12, g); // Body + body1->setPos(0, (float)(0 + yo), 3 + 6); leg0 = new ModelPart(this, 18, 0); - leg0->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg0->setPos(-4, (float)(0+yo), 2); + leg0->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 + leg0->setPos(-4, (float)(0 + yo), 2); leg1 = new ModelPart(this, 18, 0); - leg1->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg1->setPos(4, (float)(0+yo), 2); + leg1->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 + leg1->setPos(4, (float)(0 + yo), 2); leg2 = new ModelPart(this, 18, 0); - leg2->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg2->setPos(-4, (float)(0+yo), 1); + leg2->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 + leg2->setPos(-4, (float)(0 + yo), 1); leg3 = new ModelPart(this, 18, 0); - leg3->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg3->setPos(4, (float)(0+yo), 1); + leg3->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 + leg3->setPos(4, (float)(0 + yo), 1); leg4 = new ModelPart(this, 18, 0); - leg4->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg4->setPos(-4, (float)(0+yo), 0); + leg4->addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 + leg4->setPos(-4, (float)(0 + yo), 0); leg5 = new ModelPart(this, 18, 0); - leg5->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg5->setPos(4, (float)(0+yo), 0); + leg5->addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 + leg5->setPos(4, (float)(0 + yo), 0); leg6 = new ModelPart(this, 18, 0); - leg6->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg6->setPos(-4, (float)(0+yo), -1); + leg6->addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 + leg6->setPos(-4, (float)(0 + yo), -1); leg7 = new ModelPart(this, 18, 0); - leg7->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg7->setPos(4, (float)(0+yo), -1); + leg7->addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 + leg7->setPos(4, (float)(0 + yo), -1); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body0->compile(1.0f/16.0f); - body1->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); - leg4->compile(1.0f/16.0f); - leg5->compile(1.0f/16.0f); - leg6->compile(1.0f/16.0f); - leg7->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body0->compile(1.0f / 16.0f); + body1->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); + leg4->compile(1.0f / 16.0f); + leg5->compile(1.0f / 16.0f); + leg6->compile(1.0f / 16.0f); + leg7->compile(1.0f / 16.0f); } -void SpiderModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void SpiderModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale,usecompiled); - body0->render(scale,usecompiled); - body1->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - leg2->render(scale,usecompiled); - leg3->render(scale,usecompiled); - leg4->render(scale,usecompiled); - leg5->render(scale,usecompiled); - leg6->render(scale,usecompiled); - leg7->render(scale,usecompiled); + head->render(scale, usecompiled); + body0->render(scale, usecompiled); + body1->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + leg4->render(scale, usecompiled); + leg5->render(scale, usecompiled); + leg6->render(scale, usecompiled); + leg7->render(scale, usecompiled); } -void SpiderModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); +void SpiderModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); - float sr = (float) PI / 4.0f; + float sr = (float)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) PI / 2.0f * 0; - float ur = (float) PI / 8.0f; + float ro = -(float)PI / 2.0f * 0; + float ur = (float)PI / 8.0f; leg0->yRot = +ur * 2.0f + ro; leg1->yRot = -ur * 2.0f - ro; leg2->yRot = +ur * 1.0f + ro; @@ -114,16 +115,23 @@ void SpiderModel::setupAnim(float time, float r, float bob, float yRot, float xR leg6->yRot = -ur * 2.0f + ro; leg7->yRot = +ur * 2.0f - ro; + float c0 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 0 / 4.0f) * 0.4f) * r; + float c1 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 2 / 4.0f) * 0.4f) * r; + float c2 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 1 / 4.0f) * 0.4f) * r; + float c3 = + -((float)Mth::cos(time * 0.6662f * 2 + PI * 2 * 3 / 4.0f) * 0.4f) * r; - float c0 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 0 / 4.0f) * 0.4f) * r; - float c1 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 2 / 4.0f) * 0.4f) * r; - float c2 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 1 / 4.0f) * 0.4f) * r; - float c3 = -((float) Mth::cos(time * 0.6662f * 2 + PI * 2 * 3 / 4.0f) * 0.4f) * r; - - float s0 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 0 / 4.0f) * 0.4f) * r; - float s1 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 2 / 4.0f) * 0.4f) * r; - float s2 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 1 / 4.0f) * 0.4f) * r; - float s3 = abs((float)Mth::sin(time * 0.6662f + PI * 2 * 3 / 4.0f) * 0.4f) * r; + float s0 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 0 / 4.0f) * 0.4f) * r; + float s1 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 2 / 4.0f) * 0.4f) * r; + float s2 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 1 / 4.0f) * 0.4f) * r; + float s3 = + abs((float)Mth::sin(time * 0.6662f + PI * 2 * 3 / 4.0f) * 0.4f) * r; leg0->yRot += +c0; leg1->yRot += -c0; diff --git a/Minecraft.Client/Rendering/Models/SpiderModel.h b/Minecraft.Client/Rendering/Models/SpiderModel.h index 2d9d15273..ea2624647 100644 --- a/Minecraft.Client/Rendering/Models/SpiderModel.h +++ b/Minecraft.Client/Rendering/Models/SpiderModel.h @@ -1,12 +1,16 @@ #pragma once #include "Model.h" - class SpiderModel : public Model -{ +class SpiderModel : public Model { public: - ModelPart *head, *body0, *body1, *leg0, *leg1, *leg2, *leg3, *leg4, *leg5, *leg6, *leg7; + ModelPart *head, *body0, *body1, *leg0, *leg1, *leg2, *leg3, *leg4, *leg5, + *leg6, *leg7; SpiderModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SquidModel.cpp b/Minecraft.Client/Rendering/Models/SquidModel.cpp index baeb6ea19..bf0541d19 100644 --- a/Minecraft.Client/Rendering/Models/SquidModel.cpp +++ b/Minecraft.Client/Rendering/Models/SquidModel.cpp @@ -3,18 +3,18 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -SquidModel::SquidModel() : Model() -{ +SquidModel::SquidModel() : Model() { int yoffs = -16; body = new ModelPart(this, 0, 0); body->addBox(-6, -8, -6, 12, 16, 12); body->y += (8 + 16) + yoffs; - for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length - { + for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length + { tentacles[i] = new ModelPart(this, 48, 0); - double angle = i * PI * 2.0 / (double) TENTACLES_LENGTH; // 4J - 8 was tentacles.length + double angle = i * PI * 2.0 / + (double)TENTACLES_LENGTH; // 4J - 8 was tentacles.length float xo = Mth::cos((float)angle) * 5; float yo = Mth::sin((float)angle) * 5; tentacles[i]->addBox(-1, 0, -1, 2, 18, 2); @@ -23,33 +23,37 @@ SquidModel::SquidModel() : Model() tentacles[i]->z = yo; tentacles[i]->y = (float)(31 + yoffs); - angle = i * PI * -2.0 / (double) TENTACLES_LENGTH + PI * .5; // 4J - 8 was tentacles.length - tentacles[i]->yRot = (float) angle; - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - tentacles[i]->compile(1.0f/16.0f); - } - body->compile(1.0f/16.0f); + angle = i * PI * -2.0 / (double)TENTACLES_LENGTH + + PI * .5; // 4J - 8 was tentacles.length + tentacles[i]->yRot = (float)angle; + // 4J added - compile now to avoid random performance hit first time + // cubes are rendered + tentacles[i]->compile(1.0f / 16.0f); + } + body->compile(1.0f / 16.0f); } -void SquidModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length - { - +void SquidModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length + { // tentacle angle is calculated in SquidRenderer tentacles[i]->xRot = bob; } } -void SquidModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void SquidModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); body->render(scale, usecompiled); - for (int i = 0; i < TENTACLES_LENGTH; i++) // 4J - 8 was tentacles.length // 4J Stu - Was 9 but I made it 8 as the array is [0,8) - { + for (int i = 0; i < TENTACLES_LENGTH; + i++) // 4J - 8 was tentacles.length // 4J Stu - Was 9 but I made it 8 + // as the array is [0,8) + { tentacles[i]->render(scale, usecompiled); } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/SquidModel.h b/Minecraft.Client/Rendering/Models/SquidModel.h index 0b7948a80..28bc025a7 100644 --- a/Minecraft.Client/Rendering/Models/SquidModel.h +++ b/Minecraft.Client/Rendering/Models/SquidModel.h @@ -1,14 +1,17 @@ #pragma once #include "Model.h" -class SquidModel : public Model -{ +class SquidModel : public Model { public: - static const int TENTACLES_LENGTH=8; - ModelPart *body; - ModelPart *tentacles[TENTACLES_LENGTH]; + static const int TENTACLES_LENGTH = 8; + ModelPart* body; + ModelPart* tentacles[TENTACLES_LENGTH]; SquidModel(); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp b/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp index ec83b39c8..4e55acee3 100644 --- a/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp +++ b/Minecraft.Client/Rendering/Models/VillagerGolemModel.cpp @@ -3,88 +3,84 @@ #include "ModelPart.h" #include "VillagerGolemModel.h" -VillagerGolemModel::VillagerGolemModel(float g, float yOffset) -{ - int xTexSize = 128; - int yTexSize = 128; +VillagerGolemModel::VillagerGolemModel(float g, float yOffset) { + int xTexSize = 128; + int yTexSize = 128; - head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - head->setPos(0, 0 + yOffset, -2); - head->texOffs(0, 0)->addBox(-4, -12, -5.5f, 8, 10, 8, g); - head->texOffs(24, 0)->addBox(-1, -5.0f, -7.5f, 2, 4, 2, g); + head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + head->setPos(0, 0 + yOffset, -2); + head->texOffs(0, 0)->addBox(-4, -12, -5.5f, 8, 10, 8, g); + head->texOffs(24, 0)->addBox(-1, -5.0f, -7.5f, 2, 4, 2, g); - body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - body->setPos(0, 0 + yOffset, 0); - body->texOffs(0, 40)->addBox(-9, -2, -6, 18, 12, 11, g); - body->texOffs(0, 70)->addBox(-4.5f, 10, -3, 9, 5, 6, g + 0.5f); + body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + body->setPos(0, 0 + yOffset, 0); + body->texOffs(0, 40)->addBox(-9, -2, -6, 18, 12, 11, g); + body->texOffs(0, 70)->addBox(-4.5f, 10, -3, 9, 5, 6, g + 0.5f); - arm0 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - arm0->setPos(0, -7, 0); - arm0->texOffs(60, 21)->addBox(-13, -2.5f, -3, 4, 30, 6, g); + arm0 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + arm0->setPos(0, -7, 0); + arm0->texOffs(60, 21)->addBox(-13, -2.5f, -3, 4, 30, 6, g); - arm1 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - arm1->setPos(0, -7, 0); - arm1->texOffs(60, 58)->addBox(9, -2.5f, -3, 4, 30, 6, g); + arm1 = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + arm1->setPos(0, -7, 0); + arm1->texOffs(60, 58)->addBox(9, -2.5f, -3, 4, 30, 6, g); - leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg0->setPos(-4.0f, 18 + yOffset, 0); - leg0->texOffs(37, 0)->addBox(-3.5f, -3, -3, 6, 16, 5, g); + leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg0->setPos(-4.0f, 18 + yOffset, 0); + leg0->texOffs(37, 0)->addBox(-3.5f, -3, -3, 6, 16, 5, g); - leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg1->bMirror = true; - leg1->texOffs(60, 0)->setPos(5.0f, 18 + yOffset, 0); - leg1->addBox(-3.5f, -3, -3, 6, 16, 5, g); + leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg1->bMirror = true; + leg1->texOffs(60, 0)->setPos(5.0f, 18 + yOffset, 0); + leg1->addBox(-3.5f, -3, -3, 6, 16, 5, g); } -void VillagerGolemModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ - setupAnim(time, r, bob, yRot, xRot, scale); +void VillagerGolemModel::render(std::shared_ptr entity, float time, + float r, float bob, float yRot, float xRot, + float scale, bool usecompiled) { + setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - arm0->render(scale, usecompiled); - arm1->render(scale, usecompiled); + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + arm0->render(scale, usecompiled); + arm1->render(scale, usecompiled); } -void VillagerGolemModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); +void VillagerGolemModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); - leg0->xRot = (-1.5f * triangleWave(time, 13)) * r; - leg1->xRot = (1.5f * triangleWave(time, 13)) * r; - leg0->yRot = 0; - leg1->yRot = 0; + leg0->xRot = (-1.5f * triangleWave(time, 13)) * r; + leg1->xRot = (1.5f * triangleWave(time, 13)) * r; + leg0->yRot = 0; + leg1->yRot = 0; } -void VillagerGolemModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ - std::shared_ptr vg = std::dynamic_pointer_cast(mob); - int attackTick = vg->getAttackAnimationTick(); - if (attackTick > 0) - { - arm0->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); - arm1->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); - } - else - { - int offerFlowerTick = vg->getOfferFlowerTick(); - if (offerFlowerTick > 0) - { - arm0->xRot = -0.8f + 0.025f * triangleWave(offerFlowerTick, 70); - arm1->xRot = 0; - } - else - { - arm0->xRot = (-0.2f + 1.5f * triangleWave(time, 13)) * r; - arm1->xRot = (-0.2f - 1.5f * triangleWave(time, 13)) * r; - } - } +void VillagerGolemModel::prepareMobModel(std::shared_ptr mob, float time, + float r, float a) { + std::shared_ptr vg = + std::dynamic_pointer_cast(mob); + int attackTick = vg->getAttackAnimationTick(); + if (attackTick > 0) { + arm0->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); + arm1->xRot = (-2.0f + 1.5f * triangleWave(attackTick - a, 10)); + } else { + int offerFlowerTick = vg->getOfferFlowerTick(); + if (offerFlowerTick > 0) { + arm0->xRot = -0.8f + 0.025f * triangleWave(offerFlowerTick, 70); + arm1->xRot = 0; + } else { + arm0->xRot = (-0.2f + 1.5f * triangleWave(time, 13)) * r; + arm1->xRot = (-0.2f - 1.5f * triangleWave(time, 13)) * r; + } + } } -float VillagerGolemModel::triangleWave(float bob, float period) -{ - return (abs(fmod(bob, period) - period * 0.5f) - period * 0.25f) / (period * 0.25f); +float VillagerGolemModel::triangleWave(float bob, float period) { + return (abs(fmod(bob, period) - period * 0.5f) - period * 0.25f) / + (period * 0.25f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerGolemModel.h b/Minecraft.Client/Rendering/Models/VillagerGolemModel.h index 80c822d5c..9dba11416 100644 --- a/Minecraft.Client/Rendering/Models/VillagerGolemModel.h +++ b/Minecraft.Client/Rendering/Models/VillagerGolemModel.h @@ -4,27 +4,29 @@ class ModelPart; -class VillagerGolemModel : public Model -{ +class VillagerGolemModel : public Model { public: - ModelPart *head, *body, *arm0, *arm1, *leg0, *leg1; + ModelPart *head, *body, *arm0, *arm1, *leg0, *leg1; - //VillagerGolemModel() - //{ - // this(0); - //} + // VillagerGolemModel() + //{ + // this(0); + // } - //VillagerGolemModel(float g) - //{ - // this(g, -7); - //} + // VillagerGolemModel(float g) + //{ + // this(g, -7); + // } - VillagerGolemModel(float g = 0.0f, float yOffset = -7.0f); + VillagerGolemModel(float g = 0.0f, float yOffset = -7.0f); - void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); + void render(std::shared_ptr entity, float time, float r, float bob, + float yRot, float xRot, float scale, bool usecompiled); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); private: - float triangleWave(float bob, float period); + float triangleWave(float bob, float period); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerModel.cpp b/Minecraft.Client/Rendering/Models/VillagerModel.cpp index 3f7242175..42990ef1e 100644 --- a/Minecraft.Client/Rendering/Models/VillagerModel.cpp +++ b/Minecraft.Client/Rendering/Models/VillagerModel.cpp @@ -3,81 +3,77 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" +void VillagerModel::_init(float g, float yOffset) { + int xTexSize = 64; + int yTexSize = 64; -void VillagerModel::_init(float g, float yOffset) -{ - int xTexSize = 64; - int yTexSize = 64; + head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + head->setPos(0, 0 + yOffset, 0); + head->texOffs(0, 0)->addBox(-4, -10, -4, 8, 10, 8, g); + // head.texOffs(32, 0).addBox(-4, -10, -4, 8, 12, 8, g + 0.5f); + head->texOffs(24, 0)->addBox(-1, -3, -6, 2, 4, 2, g); - head = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - head->setPos(0, 0 + yOffset, 0); - head->texOffs(0, 0)->addBox(-4, -10, -4, 8, 10, 8, g); - // head.texOffs(32, 0).addBox(-4, -10, -4, 8, 12, 8, g + 0.5f); - head->texOffs(24, 0)->addBox(-1, -3, -6, 2, 4, 2, g); + body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + body->setPos(0, 0 + yOffset, 0); + body->texOffs(16, 20)->addBox(-4, 0, -3, 8, 12, 6, g); + body->texOffs(0, 38)->addBox(-4, 0, -3, 8, 18, 6, g + 0.5f); - body = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - body->setPos(0, 0 + yOffset, 0); - body->texOffs(16, 20)->addBox(-4, 0, -3, 8, 12, 6, g); - body->texOffs(0, 38)->addBox(-4, 0, -3, 8, 18, 6, g + 0.5f); + arms = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); + arms->setPos(0, 0 + yOffset + 2, 0); + arms->texOffs(44, 22)->addBox(-6 - 2, -2, -2, 4, 8, 4, g); + arms->texOffs(44, 22)->addBox(6 - 2, -2, -2, 4, 8, 4, g); + arms->texOffs(40, 38)->addBox(-4, 2, -2, 8, 4, 4, g); - arms = (new ModelPart(this))->setTexSize(xTexSize, yTexSize); - arms->setPos(0, 0 + yOffset + 2, 0); - arms->texOffs(44, 22)->addBox(-6 - 2, -2, -2, 4, 8, 4, g); - arms->texOffs(44, 22)->addBox(6 - 2, -2, -2, 4, 8, 4, g); - arms->texOffs(40, 38)->addBox(-4, 2, -2, 8, 4, 4, g); + leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg0->setPos(-2, 12 + yOffset, 0); + leg0->addBox(-2, 0, -2, 4, 12, 4, g); // Leg0 - leg0 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg0->setPos(-2, 12 + yOffset, 0); - leg0->addBox(-2, 0, -2, 4, 12, 4, g); // Leg0 + leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); + leg1->bMirror = true; + leg1->setPos(2, 12 + yOffset, 0); + leg1->addBox(-2, 0, -2, 4, 12, 4, g); // Leg1 - leg1 = (new ModelPart(this, 0, 22))->setTexSize(xTexSize, yTexSize); - leg1->bMirror = true; - leg1->setPos(2, 12 + yOffset, 0); - leg1->addBox(-2, 0, -2, 4, 12, 4, g); // Leg1 + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered 4J Stu - Not just performance, but alpha+depth tests don't + // work right unless we compile here - // 4J added - compile now to avoid random performance hit first time cubes are rendered - // 4J Stu - Not just performance, but alpha+depth tests don't work right unless we compile here - - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - arms->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + arms->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); } -VillagerModel::VillagerModel(float g) : Model() -{ - _init(g, 0); +VillagerModel::VillagerModel(float g) : Model() { _init(g, 0); } + +VillagerModel::VillagerModel(float g, float yOffset) : Model() { + _init(g, yOffset); } -VillagerModel::VillagerModel(float g, float yOffset) : Model() -{ - _init(g,yOffset); -} - -void VillagerModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void VillagerModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { setupAnim(time, r, bob, yRot, xRot, scale); - head->render(scale,usecompiled); - body->render(scale,usecompiled); - leg0->render(scale,usecompiled); - leg1->render(scale,usecompiled); - arms->render(scale,usecompiled); + head->render(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + arms->render(scale, usecompiled); } -void VillagerModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - head->yRot = yRot / (float) (180 / PI); - head->xRot = xRot / (float) (180 / PI); - +void VillagerModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + head->yRot = yRot / (float)(180 / PI); + head->xRot = xRot / (float)(180 / PI); + arms->y = 3; arms->z = -1; arms->xRot = -0.75f; - - leg0->xRot = ((float) Mth::cos(time * 0.6662f) * 1.4f) * r * 0.5f; - leg1->xRot = ((float) Mth::cos(time * 0.6662f + PI) * 1.4f) * r * 0.5f; + + leg0->xRot = ((float)Mth::cos(time * 0.6662f) * 1.4f) * r * 0.5f; + leg1->xRot = ((float)Mth::cos(time * 0.6662f + PI) * 1.4f) * r * 0.5f; leg0->yRot = 0; leg1->yRot = 0; } - diff --git a/Minecraft.Client/Rendering/Models/VillagerModel.h b/Minecraft.Client/Rendering/Models/VillagerModel.h index cfb4b1d9f..59f3b18de 100644 --- a/Minecraft.Client/Rendering/Models/VillagerModel.h +++ b/Minecraft.Client/Rendering/Models/VillagerModel.h @@ -2,14 +2,17 @@ #pragma once #include "Model.h" -class VillagerModel : public Model -{ +class VillagerModel : public Model { public: - ModelPart *head, *body, *arms, *leg0, *leg1; + ModelPart *head, *body, *arms, *leg0, *leg1; - void _init(float g, float yOffset); // 4J added + void _init(float g, float yOffset); // 4J added VillagerModel(float g, float yOffset); VillagerModel(float g); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) ; - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp b/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp index 891f98faf..152e991cc 100644 --- a/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp +++ b/Minecraft.Client/Rendering/Models/VillagerZombieModel.cpp @@ -3,60 +3,54 @@ #include "VillagerZombieModel.h" #include "../../../Minecraft.World/Util/Mth.h" -void VillagerZombieModel::_init(float g, float yOffset, bool isArmor) -{ - delete head; - if (isArmor) - { - head = new ModelPart(this, 0, 0); - head->addBox(-4, -10, -4, 8, 6, 8, g); // Head - head->setPos(0, 0 + yOffset, 0); - } - else - { - head = new ModelPart(this); - head->setPos(0, 0 + yOffset, 0); - head->texOffs(0, 32)->addBox(-4, -10, -4, 8, 10, 8, g); - head->texOffs(24, 32)->addBox(-1, -3, -6, 2, 4, 2, g); - } +void VillagerZombieModel::_init(float g, float yOffset, bool isArmor) { + delete head; + if (isArmor) { + head = new ModelPart(this, 0, 0); + head->addBox(-4, -10, -4, 8, 6, 8, g); // Head + head->setPos(0, 0 + yOffset, 0); + } else { + head = new ModelPart(this); + head->setPos(0, 0 + yOffset, 0); + head->texOffs(0, 32)->addBox(-4, -10, -4, 8, 10, 8, g); + head->texOffs(24, 32)->addBox(-1, -3, -6, 2, 4, 2, g); + } - - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); } -VillagerZombieModel::VillagerZombieModel() : HumanoidModel(0, 0, 64, 64) -{ - _init(0, 0, false); +VillagerZombieModel::VillagerZombieModel() : HumanoidModel(0, 0, 64, 64) { + _init(0, 0, false); } -VillagerZombieModel::VillagerZombieModel(float g, float yOffset, bool isArmor) : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) -{ - _init(g, yOffset, isArmor); +VillagerZombieModel::VillagerZombieModel(float g, float yOffset, bool isArmor) + : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) { + _init(g, yOffset, isArmor); } -int VillagerZombieModel::version() -{ - return 10; -} +int VillagerZombieModel::version() { return 10; } -void VillagerZombieModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); +void VillagerZombieModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); - float attack2 = Mth::sin(attackTime * PI); - float attack = Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * PI); - arm0->zRot = 0; - arm1->zRot = 0; - arm0->yRot = -(0.1f - attack2 * 0.6f); - arm1->yRot = +(0.1f - attack2 * 0.6f); - arm0->xRot = -PI / 2.0f; - arm1->xRot = -PI / 2.0f; - arm0->xRot -= attack2 * 1.2f - attack * 0.4f; - arm1->xRot -= attack2 * 1.2f - attack * 0.4f; + float attack2 = Mth::sin(attackTime * PI); + float attack = Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * PI); + arm0->zRot = 0; + arm1->zRot = 0; + arm0->yRot = -(0.1f - attack2 * 0.6f); + arm1->yRot = +(0.1f - attack2 * 0.6f); + arm0->xRot = -PI / 2.0f; + arm1->xRot = -PI / 2.0f; + arm0->xRot -= attack2 * 1.2f - attack * 0.4f; + arm1->xRot -= attack2 * 1.2f - attack * 0.4f; - arm0->zRot += (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); - arm1->zRot -= (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); - arm0->xRot += (Mth::sin(bob * 0.067f) * 0.05f); - arm1->xRot -= (Mth::sin(bob * 0.067f) * 0.05f); + arm0->zRot += (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); + arm1->zRot -= (Mth::cos(bob * 0.09f) * 0.05f + 0.05f); + arm0->xRot += (Mth::sin(bob * 0.067f) * 0.05f); + arm1->xRot -= (Mth::sin(bob * 0.067f) * 0.05f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/VillagerZombieModel.h b/Minecraft.Client/Rendering/Models/VillagerZombieModel.h index b4400b354..201664a68 100644 --- a/Minecraft.Client/Rendering/Models/VillagerZombieModel.h +++ b/Minecraft.Client/Rendering/Models/VillagerZombieModel.h @@ -2,15 +2,15 @@ #include "HumanoidModel.h" -class VillagerZombieModel : public HumanoidModel -{ +class VillagerZombieModel : public HumanoidModel { private: - void _init(float g, float yOffset, bool isArmor); + void _init(float g, float yOffset, bool isArmor); public: - VillagerZombieModel(); - VillagerZombieModel(float g, float yOffset, bool isArmor); + VillagerZombieModel(); + VillagerZombieModel(float g, float yOffset, bool isArmor); - int version(); - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + int version(); + void setupAnim(float time, float r, float bob, float yRot, float xRot, + float scale, unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/WolfModel.cpp b/Minecraft.Client/Rendering/Models/WolfModel.cpp index 101f3a58e..ebacdb74f 100644 --- a/Minecraft.Client/Rendering/Models/WolfModel.cpp +++ b/Minecraft.Client/Rendering/Models/WolfModel.cpp @@ -4,111 +4,105 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -WolfModel::WolfModel() -{ +WolfModel::WolfModel() { float g = 0; float headHeight = 12 + 9.5f - legSize; head = new ModelPart(this, 0, 0); - head->addBox(-3, -3, -2, 6, 6, 4, g); // Head + head->addBox(-3, -3, -2, 6, 6, 4, g); // Head head->setPos(-1, headHeight, -7); body = new ModelPart(this, 18, 14); - body->addBox(-4, -2, -3, 6, 9, 6, g); // Body + body->addBox(-4, -2, -3, 6, 9, 6, g); // Body body->setPos(0, 11 + 11 - legSize, 2); upperBody = new ModelPart(this, 21, 0); - upperBody->addBox(-4, -3, -3, 8, 6, 7, g); // Body + upperBody->addBox(-4, -3, -3, 8, 6, 7, g); // Body upperBody->setPos(-1.0f, 11 + 11.0f - legSize, 2); leg0 = new ModelPart(this, 0, 18); - leg0->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg0 + leg0->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg0 leg0->setPos(-2.5f, 18 + 6 - legSize, 7); leg1 = new ModelPart(this, 0, 18); - leg1->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg1 + leg1->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg1 leg1->setPos(.5f, 18 + 6 - legSize, 7); leg2 = new ModelPart(this, 0, 18); - leg2->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg2 + leg2->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg2 leg2->setPos(-2.5f, 18 + 6 - legSize, -4); leg3 = new ModelPart(this, 0, 18); - leg3->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg3 + leg3->addBox(-1, 0, -1, 2, legSize, 2, g); // Leg3 leg3->setPos(.5f, 18 + 6 - legSize, -4); tail = new ModelPart(this, 9, 18); tail->addBox(-1, 0, -1, 2, 8, 2, g); tail->setPos(-1, 2 + 18 - legSize, 8); - head->texOffs(16, 14)->addBox(-3, -5, 0, 2, 2, 1, g); - head->texOffs(16, 14)->addBox(1, -5, 0, 2, 2, 1, g); - head->texOffs(0, 10)->addBox(-1.5f, 0, -5, 3, 3, 4, g); + head->texOffs(16, 14)->addBox(-3, -5, 0, 2, 2, 1, g); + head->texOffs(16, 14)->addBox(1, -5, 0, 2, 2, 1, g); + head->texOffs(0, 10)->addBox(-1.5f, 0, -5, 3, 3, 4, g); - // 4J added - compile now to avoid random performance hit first time cubes are rendered - head->compile(1.0f/16.0f); - body->compile(1.0f/16.0f); - upperBody->compile(1.0f/16.0f); - leg0->compile(1.0f/16.0f); - leg1->compile(1.0f/16.0f); - leg2->compile(1.0f/16.0f); - leg3->compile(1.0f/16.0f); - tail->compile(1.0f/16.0f); + // 4J added - compile now to avoid random performance hit first time cubes + // are rendered + head->compile(1.0f / 16.0f); + body->compile(1.0f / 16.0f); + upperBody->compile(1.0f / 16.0f); + leg0->compile(1.0f / 16.0f); + leg1->compile(1.0f / 16.0f); + leg2->compile(1.0f / 16.0f); + leg3->compile(1.0f / 16.0f); + tail->compile(1.0f / 16.0f); } -void WolfModel::render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled) -{ +void WolfModel::render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled) { Model::render(entity, time, r, bob, yRot, xRot, scale, usecompiled); setupAnim(time, r, bob, yRot, xRot, scale); - if (young) - { - float ss = 2; - glPushMatrix(); - glTranslatef(0, 5 * scale, 2 * scale); - head->renderRollable(scale, usecompiled); - glPopMatrix(); - glPushMatrix(); - glScalef(1 / ss, 1 / ss, 1 / ss); - glTranslatef(0, 24 * scale, 0); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - tail->renderRollable(scale, usecompiled); - upperBody->render(scale, usecompiled); - glPopMatrix(); - } - else - { - head->renderRollable(scale, usecompiled); - body->render(scale, usecompiled); - leg0->render(scale, usecompiled); - leg1->render(scale, usecompiled); - leg2->render(scale, usecompiled); - leg3->render(scale, usecompiled); - tail->renderRollable(scale, usecompiled); - upperBody->render(scale, usecompiled); - } + if (young) { + float ss = 2; + glPushMatrix(); + glTranslatef(0, 5 * scale, 2 * scale); + head->renderRollable(scale, usecompiled); + glPopMatrix(); + glPushMatrix(); + glScalef(1 / ss, 1 / ss, 1 / ss); + glTranslatef(0, 24 * scale, 0); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + tail->renderRollable(scale, usecompiled); + upperBody->render(scale, usecompiled); + glPopMatrix(); + } else { + head->renderRollable(scale, usecompiled); + body->render(scale, usecompiled); + leg0->render(scale, usecompiled); + leg1->render(scale, usecompiled); + leg2->render(scale, usecompiled); + leg3->render(scale, usecompiled); + tail->renderRollable(scale, usecompiled); + upperBody->render(scale, usecompiled); + } } -void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, float a) -{ +void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, + float a) { std::shared_ptr wolf = std::dynamic_pointer_cast(mob); - if (wolf->isAngry()) - { + if (wolf->isAngry()) { tail->yRot = 0; - } - else - { + } else { tail->yRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; } - if (wolf->isSitting()) - { + if (wolf->isSitting()) { upperBody->setPos(-1.0f, 11 + 13.0f - 8, -3); upperBody->xRot = .40f * PI; upperBody->yRot = .0f * PI; @@ -127,11 +121,9 @@ void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, f leg2->setPos(-2.49f, 18 + 7.0f - legSize, -4); leg3->xRot = 1.85f * PI; leg3->setPos(.51f, 18 + 7.0f - legSize, -4); - } - else - { + } else { body->setPos(0, 11 + 11 - legSize, 2); - body->xRot = 90 / (float) (180 / PI); + body->xRot = 90 / (float)(180 / PI); upperBody->setPos(-1.0f, 11 + 11.0f - legSize, -3); upperBody->xRot = body->xRot; @@ -143,7 +135,6 @@ void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, f leg2->setPos(-2.5f, 18 + 6 - legSize, -4); leg3->setPos(.5f, 18 + 6 - legSize, -4); - leg0->xRot = (Mth::cos(time * 0.6662f) * 1.4f) * r; leg1->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; leg2->xRot = (Mth::cos(time * 0.6662f + PI) * 1.4f) * r; @@ -158,10 +149,11 @@ void WolfModel::prepareMobModel(std::shared_ptr mob, float time, float r, f tail->zRot = wolf->getBodyRollAngle(a, -.2f); } -void WolfModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ +void WolfModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { Model::setupAnim(time, r, bob, yRot, xRot, scale); - head->xRot = xRot / (float) (180 / PI); - head->yRot = yRot / (float) (180 / PI); + head->xRot = xRot / (float)(180 / PI); + head->yRot = yRot / (float)(180 / PI); tail->xRot = bob; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/WolfModel.h b/Minecraft.Client/Rendering/Models/WolfModel.h index 809259906..efdddbc58 100644 --- a/Minecraft.Client/Rendering/Models/WolfModel.h +++ b/Minecraft.Client/Rendering/Models/WolfModel.h @@ -2,20 +2,26 @@ #include "Model.h" #include "../../../Minecraft.World/Entities/Mob.h" -class WolfModel : public Model -{ +class WolfModel : public Model { public: - ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; -// Cube *ear1; -// Cube *ear2; -// Cube *mouth; - ModelPart *tail; - ModelPart *upperBody; + ModelPart *head, *body, *leg0, *leg1, *leg2, *leg3; + // Cube *ear1; + // Cube *ear2; + // Cube *mouth; + ModelPart* tail; + ModelPart* upperBody; + private: - static const int legSize = 8; + static const int legSize = 8; + public: - WolfModel(); - virtual void render(std::shared_ptr entity, float time, float r, float bob, float yRot, float xRot, float scale, bool usecompiled); - void prepareMobModel(std::shared_ptr mob, float time, float r, float a); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + WolfModel(); + virtual void render(std::shared_ptr entity, float time, float r, + float bob, float yRot, float xRot, float scale, + bool usecompiled); + void prepareMobModel(std::shared_ptr mob, float time, float r, + float a); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/ZombieModel.cpp b/Minecraft.Client/Rendering/Models/ZombieModel.cpp index 918f751fc..b159f6019 100644 --- a/Minecraft.Client/Rendering/Models/ZombieModel.cpp +++ b/Minecraft.Client/Rendering/Models/ZombieModel.cpp @@ -3,34 +3,32 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "ModelPart.h" -ZombieModel::ZombieModel() : HumanoidModel(0, 0, 64, 32) -{ -} +ZombieModel::ZombieModel() : HumanoidModel(0, 0, 64, 32) {} -ZombieModel::ZombieModel(float g, float yOffset, int texWidth, int texHeight) : HumanoidModel(g, yOffset, texWidth, texHeight) -{ -} +ZombieModel::ZombieModel(float g, float yOffset, int texWidth, int texHeight) + : HumanoidModel(g, yOffset, texWidth, texHeight) {} -ZombieModel::ZombieModel(float g, bool isArmor) : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) -{ -} +ZombieModel::ZombieModel(float g, bool isArmor) + : HumanoidModel(g, 0, 64, isArmor ? 32 : 64) {} -void ZombieModel::setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim) -{ - HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, uiBitmaskOverrideAnim); - - float attack2 = Mth::sin(attackTime*PI); - float attack = Mth::sin((1-(1-attackTime)*(1-attackTime))*PI); +void ZombieModel::setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim) { + HumanoidModel::setupAnim(time, r, bob, yRot, xRot, scale, + uiBitmaskOverrideAnim); + + float attack2 = Mth::sin(attackTime * PI); + float attack = Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * PI); arm0->zRot = 0; arm1->zRot = 0; - arm0->yRot = -(0.1f-attack2*0.6f); - arm1->yRot = +(0.1f-attack2*0.6f); - arm0->xRot = -(float)PI/2.0f; - arm1->xRot = -(float)PI/2.0f; - arm0->xRot -= attack2*1.2f-attack*0.4f; - arm1->xRot -= attack2*1.2f-attack*0.4f; - arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f+0.05f); - arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f+0.05f); + arm0->yRot = -(0.1f - attack2 * 0.6f); + arm1->yRot = +(0.1f - attack2 * 0.6f); + arm0->xRot = -(float)PI / 2.0f; + arm1->xRot = -(float)PI / 2.0f; + arm0->xRot -= attack2 * 1.2f - attack * 0.4f; + arm1->xRot -= attack2 * 1.2f - attack * 0.4f; + arm0->zRot += ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); + arm1->zRot -= ((Mth::cos(bob * 0.09f)) * 0.05f + 0.05f); arm0->xRot += ((Mth::sin(bob * 0.067f)) * 0.05f); arm1->xRot -= ((Mth::sin(bob * 0.067f)) * 0.05f); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Models/ZombieModel.h b/Minecraft.Client/Rendering/Models/ZombieModel.h index 1971db097..90351967b 100644 --- a/Minecraft.Client/Rendering/Models/ZombieModel.h +++ b/Minecraft.Client/Rendering/Models/ZombieModel.h @@ -1,16 +1,17 @@ #pragma once #include "HumanoidModel.h" -class ZombieModel : public HumanoidModel -{ +class ZombieModel : public HumanoidModel { public: - ZombieModel(); + ZombieModel(); protected: - ZombieModel(float g, float yOffset, int texWidth, int texHeight); + ZombieModel(float g, float yOffset, int texWidth, int texHeight); public: - ZombieModel(float g, bool isArmor); + ZombieModel(float g, bool isArmor); - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale, unsigned int uiBitmaskOverrideAnim=0); + virtual void setupAnim(float time, float r, float bob, float yRot, + float xRot, float scale, + unsigned int uiBitmaskOverrideAnim = 0); }; diff --git a/Minecraft.Client/Rendering/OffsettedRenderList.cpp b/Minecraft.Client/Rendering/OffsettedRenderList.cpp index 2c2dfd92d..685da0524 100644 --- a/Minecraft.Client/Rendering/OffsettedRenderList.cpp +++ b/Minecraft.Client/Rendering/OffsettedRenderList.cpp @@ -3,54 +3,48 @@ #include "OffsettedRenderList.h" // 4J added -OffsettedRenderList::OffsettedRenderList() -{ - x = y = z = 0; - xOff = yOff = zOff = 0; - lists = MemoryTracker::createIntBuffer(1024 * 64); - inited = false; - rendered = false; +OffsettedRenderList::OffsettedRenderList() { + x = y = z = 0; + xOff = yOff = zOff = 0; + lists = MemoryTracker::createIntBuffer(1024 * 64); + inited = false; + rendered = false; } -void OffsettedRenderList::init(int x, int y, int z, double xOff, double yOff, double zOff) -{ +void OffsettedRenderList::init(int x, int y, int z, double xOff, double yOff, + double zOff) { inited = true; lists->clear(); this->x = x; this->y = y; this->z = z; - this->xOff = (float) xOff; - this->yOff = (float) yOff; - this->zOff = (float) zOff; + this->xOff = (float)xOff; + this->yOff = (float)yOff; + this->zOff = (float)zOff; } -bool OffsettedRenderList::isAt(int x, int y, int z) -{ +bool OffsettedRenderList::isAt(int x, int y, int z) { if (!inited) return false; return x == this->x && y == this->y && z == this->z; } -void OffsettedRenderList::add(int list) -{ - // 4J - added - chunkList::getList returns -1 when chunks aren't visible, we really don't want to end up sending that to glCallLists - if( list >= 0 ) - { - lists->put(list); - } +void OffsettedRenderList::add(int list) { + // 4J - added - chunkList::getList returns -1 when chunks aren't visible, we + // really don't want to end up sending that to glCallLists + if (list >= 0) { + lists->put(list); + } if (lists->remaining() == 0) render(); } -void OffsettedRenderList::render() -{ +void OffsettedRenderList::render() { if (!inited) return; - if (!rendered) - { + if (!rendered) { lists->flip(); rendered = true; } - if (lists->remaining() > 0) - { + if (lists->remaining() > 0) { glPushMatrix(); glTranslatef(x - xOff, y - yOff, z - zOff); glCallLists(lists); @@ -58,8 +52,7 @@ void OffsettedRenderList::render() } } -void OffsettedRenderList::clear() -{ +void OffsettedRenderList::clear() { inited = false; rendered = false; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/OffsettedRenderList.h b/Minecraft.Client/Rendering/OffsettedRenderList.h index c989da31b..cc529edee 100644 --- a/Minecraft.Client/Rendering/OffsettedRenderList.h +++ b/Minecraft.Client/Rendering/OffsettedRenderList.h @@ -2,17 +2,16 @@ class IntBuffer; -class OffsettedRenderList -{ +class OffsettedRenderList { private: - int x, y, z; + int x, y, z; float xOff, yOff, zOff; - IntBuffer *lists; + IntBuffer* lists; bool inited; - bool rendered ; + bool rendered; public: - OffsettedRenderList(); // 4J added + OffsettedRenderList(); // 4J added void init(int x, int y, int z, double xOff, double yOff, double zOff); bool isAt(int x, int y, int z); void add(int list); diff --git a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp index b20aaa6e5..c7655ec0c 100644 --- a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.cpp @@ -5,60 +5,68 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -void BreakingItemParticle::_init(Item *item, Textures *textures, int data) -{ +void BreakingItemParticle::_init(Item* item, Textures* textures, int data) { this->setTex(textures, item->getIcon(data)); rCol = gCol = bCol = 1.0f; gravity = Tile::snow->gravity; size /= 2; } -BreakingItemParticle::BreakingItemParticle(Level *level, double x, double y, double z, Item *item, Textures *textures, int data) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(item, textures, data); +BreakingItemParticle::BreakingItemParticle(Level* level, double x, double y, + double z, Item* item, + Textures* textures, int data) + : Particle(level, x, y, z, 0, 0, 0) { + _init(item, textures, data); } -BreakingItemParticle::BreakingItemParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Item *item, Textures *textures, int data) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(item, textures, data); - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa; - yd += ya; - zd += za; +BreakingItemParticle::BreakingItemParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za, Item* item, + Textures* textures, int data) + : Particle(level, x, y, z, 0, 0, 0) { + _init(item, textures, data); + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa; + yd += ya; + zd += za; } -int BreakingItemParticle::getParticleTexture() -{ - return ParticleEngine::ITEM_TEXTURE; +int BreakingItemParticle::getParticleTexture() { + return ParticleEngine::ITEM_TEXTURE; } -void BreakingItemParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void BreakingItemParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float u0 = (texX + uo / 4.0f) / 16.0f; float u1 = u0 + 0.999f / 16.0f / 4; float v0 = (texY + vo / 4.0f) / 16.0f; float v1 = v0 + 0.999f / 16.0f / 4; float r = 0.1f * size; - if (tex != NULL) - { - u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - } + if (tex != NULL) { + u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + } - 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 = SharedConstants::TEXTURE_LIGHTING ? 1 : getBrightness(a); // 4J - change brought forward from 1.8.2 + 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 = + SharedConstants::TEXTURE_LIGHTING + ? 1 + : getBrightness(a); // 4J - change brought forward from 1.8.2 t->color(br * rCol, br * gCol, br * bCol); - t->vertexUV((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u0), (float)( v1)); - t->vertexUV((float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u0), (float)( v0)); - t->vertexUV((float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u1), (float)( v0)); - t->vertexUV((float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u1), (float)( v1)); - + t->vertexUV((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u0), (float)(v1)); + t->vertexUV((float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u1), (float)(v1)); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h index 390426d41..7fd7e5aab 100644 --- a/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h +++ b/Minecraft.Client/Rendering/Particles/BreakingItemParticle.h @@ -1,15 +1,18 @@ #pragma once #include "Particle.h" -class BreakingItemParticle : public Particle -{ - // virtual eINSTANCEOF GetType(); // 4J-IB/JEV TODO needs implementation +class BreakingItemParticle : public Particle { + // virtual eINSTANCEOF GetType(); // 4J-IB/JEV TODO needs implementation public: - virtual eINSTANCEOF GetType() { return eType_BREAKINGITEMPARTICLE; } - void _init(Item *item, Textures *textures, int data); - BreakingItemParticle(Level *level, double x, double y, double z, Item *item, Textures *textures, int data = 0); - BreakingItemParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Item *item, Textures *textures, int data = 0); + virtual eINSTANCEOF GetType() { return eType_BREAKINGITEMPARTICLE; } + void _init(Item* item, Textures* textures, int data); + BreakingItemParticle(Level* level, double x, double y, double z, Item* item, + Textures* textures, int data = 0); + BreakingItemParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, Item* item, Textures* textures, + int data = 0); virtual int getParticleTexture(); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); }; diff --git a/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp b/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp index 54011b215..79008ef54 100644 --- a/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/BubbleParticle.cpp @@ -6,25 +6,25 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.material.h" -BubbleParticle::BubbleParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) - { - rCol = 1.0f; - gCol = 1.0f; - bCol = 1.0f; - setMiscTex(32); - this->setSize(0.02f, 0.02f); - - size = size*(random->nextFloat()*0.6f+0.2f); - - xd = xa*0.2f+(float)(Math::random()*2-1)*0.02f; - yd = ya*0.2f+(float)(Math::random()*2-1)*0.02f; - zd = za*0.2f+(float)(Math::random()*2-1)*0.02f; +BubbleParticle::BubbleParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, xa, ya, za) { + rCol = 1.0f; + gCol = 1.0f; + bCol = 1.0f; + setMiscTex(32); + this->setSize(0.02f, 0.02f); - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + size = size * (random->nextFloat() * 0.6f + 0.2f); + + xd = xa * 0.2f + (float)(Math::random() * 2 - 1) * 0.02f; + yd = ya * 0.2f + (float)(Math::random() * 2 - 1) * 0.02f; + zd = za * 0.2f + (float)(Math::random() * 2 - 1) * 0.02f; + + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); } -void BubbleParticle::tick() -{ +void BubbleParticle::tick() { xo = x; yo = y; zo = z; @@ -35,7 +35,9 @@ void BubbleParticle::tick() yd *= 0.85f; zd *= 0.85f; - if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != Material::water) remove(); + if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != + Material::water) + remove(); if (lifetime-- <= 0) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/BubbleParticle.h b/Minecraft.Client/Rendering/Particles/BubbleParticle.h index 0e786d9de..18ad2f785 100644 --- a/Minecraft.Client/Rendering/Particles/BubbleParticle.h +++ b/Minecraft.Client/Rendering/Particles/BubbleParticle.h @@ -1,10 +1,10 @@ #pragma once #include "Particle.h" -class BubbleParticle : public Particle -{ +class BubbleParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_BUBBLEPARTICLE; } - BubbleParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - virtual void tick(); + virtual eINSTANCEOF GetType() { return eType_BUBBLEPARTICLE; } + BubbleParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/CritParticle.cpp b/Minecraft.Client/Rendering/Particles/CritParticle.cpp index 8f142f2e6..11457da37 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/CritParticle.cpp @@ -5,57 +5,54 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.phys.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -void CritParticle::_init(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type) -{ - life = 0; - this->entity = entity; - lifeTime = 3; - particleName = type; - // 4J-PB - can't use a shared_from_this in the constructor - //tick(); +void CritParticle::_init(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type) { + life = 0; + this->entity = entity; + lifeTime = 3; + particleName = type; + // 4J-PB - can't use a shared_from_this in the constructor + // tick(); } -CritParticle::CritParticle(Level *level, std::shared_ptr entity) : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, entity->z, entity->xd, entity->yd, entity->zd) -{ - _init(level,entity,eParticleType_crit); +CritParticle::CritParticle(Level* level, std::shared_ptr entity) + : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, + entity->z, entity->xd, entity->yd, entity->zd) { + _init(level, entity, eParticleType_crit); } -CritParticle::CritParticle(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type) : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, entity->z, entity->xd, entity->yd, entity->zd) -{ - _init(level, entity, type); +CritParticle::CritParticle(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type) + : Particle(level, entity->x, entity->bb->y0 + entity->bbHeight / 2, + entity->z, entity->xd, entity->yd, entity->zd) { + _init(level, entity, type); } -// 4J - Added this so that we can use some std::shared_ptr functions that were needed in the ctor -void CritParticle::CritParticlePostConstructor(void) -{ - tick(); +// 4J - Added this so that we can use some std::shared_ptr functions that were +// needed in the ctor +void CritParticle::CritParticlePostConstructor(void) { tick(); } + +void CritParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) {} + +void CritParticle::tick() { + for (int i = 0; i < 16; i++) { + double xa = random->nextFloat() * 2 - 1; + double ya = random->nextFloat() * 2 - 1; + double za = random->nextFloat() * 2 - 1; + if (xa * xa + ya * ya + za * za > 1) continue; + double x = entity->x + xa * entity->bbWidth / 4; + double y = + entity->bb->y0 + entity->bbHeight / 2 + ya * entity->bbHeight / 4; + double z = entity->z + za * entity->bbWidth / 4; + level->addParticle(particleName, x, y, z, xa, ya + 0.2, za); + } + life++; + if (life >= lifeTime) { + remove(); + } } -void CritParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ -} - -void CritParticle::tick() -{ - for (int i=0; i<16; i++) - { - double xa = random->nextFloat()*2-1; - double ya = random->nextFloat()*2-1; - double za = random->nextFloat()*2-1; - if (xa*xa+ya*ya+za*za>1) continue; - double x = entity->x+xa*entity->bbWidth/4; - double y = entity->bb->y0+entity->bbHeight/2+ya*entity->bbHeight/4; - double z = entity->z+za*entity->bbWidth/4; - level->addParticle(particleName, x, y, z, xa, ya+0.2, za); - } - life++; - if (life >= lifeTime) - { - remove(); - } -} - -int CritParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int CritParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/CritParticle.h b/Minecraft.Client/Rendering/Particles/CritParticle.h index 5bad1c251..22ae938dd 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle.h +++ b/Minecraft.Client/Rendering/Particles/CritParticle.h @@ -4,22 +4,24 @@ class Entity; -class CritParticle : public Particle -{ +class CritParticle : public Particle { private: - std::shared_ptr entity; - int life; - int lifeTime; - ePARTICLE_TYPE particleName; + std::shared_ptr entity; + int life; + int lifeTime; + ePARTICLE_TYPE particleName; - void _init(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type); + void _init(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type); public: - virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE; } - CritParticle(Level *level, std::shared_ptr entity); - CritParticle(Level *level, std::shared_ptr entity, ePARTICLE_TYPE type); - void CritParticlePostConstructor(void); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); - int getParticleTexture(); + virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE; } + CritParticle(Level* level, std::shared_ptr entity); + CritParticle(Level* level, std::shared_ptr entity, + ePARTICLE_TYPE type); + void CritParticlePostConstructor(void); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); + int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/CritParticle2.cpp b/Minecraft.Client/Rendering/Particles/CritParticle2.cpp index 2c01bd48f..cd9f40d32 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle2.cpp +++ b/Minecraft.Client/Rendering/Particles/CritParticle2.cpp @@ -2,92 +2,82 @@ #include "CritParticle2.h" #include "../../../Minecraft.World/Util/JavaMath.h" -void CritParticle2::_init(double xa, double ya, double za, float scale) -{ - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa * 0.4; - yd += ya * 0.4; - zd += za * 0.4; +void CritParticle2::_init(double xa, double ya, double za, float scale) { + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa * 0.4; + yd += ya * 0.4; + zd += za * 0.4; - rCol = gCol = bCol = (float) (Math::random() * 0.3f + 0.6f); - size *= 0.75f; - size *= scale; - oSize = size; + rCol = gCol = bCol = (float)(Math::random() * 0.3f + 0.6f); + size *= 0.75f; + size *= scale; + oSize = size; - lifetime = (int) (6 / (Math::random() * 0.8 + 0.6)); - lifetime *= scale; - noPhysics = false; + lifetime = (int)(6 / (Math::random() * 0.8 + 0.6)); + lifetime *= scale; + noPhysics = false; - setMiscTex(16 * 4 + 1); - // 4J-PB - can't use a shared_from_this in the constructor - //tick(); - m_bAgeUniformly=false; // 4J added + setMiscTex(16 * 4 + 1); + // 4J-PB - can't use a shared_from_this in the constructor + // tick(); + m_bAgeUniformly = false; // 4J added } -CritParticle2::CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(xa,ya,za,1); +CritParticle2::CritParticle2(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + _init(xa, ya, za, 1); } -CritParticle2::CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - _init(xa,ya,za,scale); +CritParticle2::CritParticle2(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + _init(xa, ya, za, scale); } -void CritParticle2::CritParticle2PostConstructor(void) -{ - tick(); +void CritParticle2::CritParticle2PostConstructor(void) { tick(); } + +void CritParticle2::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; + Particle::render(t, a, xa, ya, za, xa2, za2); } -void CritParticle2::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; +void CritParticle2::SetAgeUniformly() { m_bAgeUniformly = true; } - size = oSize * l; - Particle::render(t, a, xa, ya, za, xa2, za2); -} - -void CritParticle2::SetAgeUniformly() -{ - m_bAgeUniformly=true; -} - -void CritParticle2::tick() -{ - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - - move(xd, yd, zd); - gCol *= 0.96; - bCol *= 0.9; - - if(m_bAgeUniformly) - { - rCol *= 0.99; - gCol *= 0.99; - bCol *= 0.99; - } - else - { - gCol *= 0.96; - bCol *= 0.9; - } - - xd *= 0.70f; - yd *= 0.70f; - zd *= 0.70f; - yd-=0.02f; - - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - } +void CritParticle2::tick() { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + + move(xd, yd, zd); + gCol *= 0.96; + bCol *= 0.9; + + if (m_bAgeUniformly) { + rCol *= 0.99; + gCol *= 0.99; + bCol *= 0.99; + } else { + gCol *= 0.96; + bCol *= 0.9; + } + + xd *= 0.70f; + yd *= 0.70f; + zd *= 0.70f; + yd -= 0.02f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } } diff --git a/Minecraft.Client/Rendering/Particles/CritParticle2.h b/Minecraft.Client/Rendering/Particles/CritParticle2.h index 3febb0ffe..10fdffcb1 100644 --- a/Minecraft.Client/Rendering/Particles/CritParticle2.h +++ b/Minecraft.Client/Rendering/Particles/CritParticle2.h @@ -2,18 +2,20 @@ #include "Particle.h" -class CritParticle2 : public Particle -{ -public: - float oSize; - bool m_bAgeUniformly; // 4J added for Halo texture pack +class CritParticle2 : public Particle { +public: + float oSize; + bool m_bAgeUniformly; // 4J added for Halo texture pack - virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE2; } - void _init(double xa, double ya, double za, float scale); - CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za); - CritParticle2(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - void CritParticle2PostConstructor(void); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); - void SetAgeUniformly(); + virtual eINSTANCEOF GetType() { return eType_CRITPARTICLE2; } + void _init(double xa, double ya, double za, float scale); + CritParticle2(Level* level, double x, double y, double z, double xa, + double ya, double za); + CritParticle2(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + void CritParticle2PostConstructor(void); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); + void SetAgeUniformly(); }; diff --git a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp index 53f9bd3e2..ca58a3250 100644 --- a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.cpp @@ -2,47 +2,55 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "DragonBreathParticle.h" -void DragonBreathParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void DragonBreathParticle::init(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; - xd = xa; //+= xa; - yd = ya; //+= ya; - zd = za; //+= za; + xd = xa; //+= xa; + yd = ya; //+= ya; + zd = za; //+= za; - unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DragonBreathMin ); //0xb700d2 - unsigned int cMax = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DragonBreathMax ); //0xdf00f9 - double rMin = ( (cMin>>16)&0xFF )/255.0f, gMin = ( (cMin>>8)&0xFF )/255.0, bMin = ( cMin&0xFF )/255.0; - double rMax = ( (cMax>>16)&0xFF )/255.0f, gMax = ( (cMax>>8)&0xFF )/255.0, bMax = ( cMax&0xFF )/255.0; + unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DragonBreathMin); // 0xb700d2 + unsigned int cMax = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DragonBreathMax); // 0xdf00f9 + double rMin = ((cMin >> 16) & 0xFF) / 255.0f, + gMin = ((cMin >> 8) & 0xFF) / 255.0, bMin = (cMin & 0xFF) / 255.0; + double rMax = ((cMax >> 16) & 0xFF) / 255.0f, + gMax = ((cMax >> 8) & 0xFF) / 255.0, bMax = (cMax & 0xFF) / 255.0; - rCol = (rMax - rMin) * Math::random() + rMin; // 184/255 -- 224/255 - gCol = (gMax - gMin) * Math::random() + gMin; // 0,0 - bCol = (bMax - bMin) * Math::random() + bMin; // 210/255 -- 250/255 + rCol = (rMax - rMin) * Math::random() + rMin; // 184/255 -- 224/255 + gCol = (gMax - gMin) * Math::random() + gMin; // 0,0 + bCol = (bMax - bMin) * Math::random() + bMin; // 210/255 -- 250/255 size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (20 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) (lifetime * scale); + lifetime = (int)(20 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(lifetime * scale); noPhysics = false; - m_bHasHitGround = false; + m_bHasHitGround = false; } -DragonBreathParticle::DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 1); +DragonBreathParticle::DragonBreathParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 1); } -DragonBreathParticle::DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, scale); +DragonBreathParticle::DragonBreathParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void DragonBreathParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void DragonBreathParticle::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; @@ -51,54 +59,49 @@ void DragonBreathParticle::render(Tesselator *t, float a, float xa, float ya, fl Particle::render(t, a, xa, ya, za, xa2, za2); } -void DragonBreathParticle::tick() -{ +void DragonBreathParticle::tick() { xo = x; yo = y; zo = z; if (age++ >= lifetime) remove(); - setMiscTex( ( 3 * age / lifetime) + 5 ); + setMiscTex((3 * age / lifetime) + 5); - if(onGround) - { - yd = 0; - m_bHasHitGround = true; - } + if (onGround) { + yd = 0; + m_bHasHitGround = true; + } - if(m_bHasHitGround) yd += 0.002; //0.004; + if (m_bHasHitGround) yd += 0.002; // 0.004; move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } xd *= 0.96f; zd *= 0.96f; - if(m_bHasHitGround) yd *= 0.96f; + if (m_bHasHitGround) yd *= 0.96f; - // if (onGround) - //{ - // xd *= 0.7f; - // zd *= 0.7f; - // } + // if (onGround) + //{ + // xd *= 0.7f; + // zd *= 0.7f; + // } } -int DragonBreathParticle::getParticleTexture() -{ - return ParticleEngine::DRAGON_BREATH_TEXTURE; +int DragonBreathParticle::getParticleTexture() { + return ParticleEngine::DRAGON_BREATH_TEXTURE; } -float DragonBreathParticle::getBrightness(float a) -{ - float l = ((age + a) / lifetime) * 32; +float DragonBreathParticle::getBrightness(float a) { + float l = ((age + a) / lifetime) * 32; if (l < 0) l = 0; if (l > 1) l = 1; - float brightness = (0.5f / l) + 0.5f; + float brightness = (0.5f / l) + 0.5f; - return brightness; + return brightness; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h index e9199d7c1..dfb9cf2f2 100644 --- a/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h +++ b/Minecraft.Client/Rendering/Particles/DragonBreathParticle.h @@ -1,20 +1,24 @@ #pragma once #include "Particle.h" -class DragonBreathParticle : public Particle -{ +class DragonBreathParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eTYPE_DRAGONBREATHPARTICLE; } + virtual eINSTANCEOF GetType() { return eTYPE_DRAGONBREATHPARTICLE; } + private: - bool m_bHasHitGround; - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + bool m_bHasHitGround; + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + DragonBreathParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - DragonBreathParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + DragonBreathParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); - virtual int getParticleTexture(); - virtual float getBrightness(float a); + virtual int getParticleTexture(); + virtual float getBrightness(float a); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/DripParticle.cpp b/Minecraft.Client/Rendering/Particles/DripParticle.cpp index a66e38fdd..be5e8f889 100644 --- a/Minecraft.Client/Rendering/Particles/DripParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/DripParticle.cpp @@ -6,127 +6,126 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "DripParticle.h" -DripParticle::DripParticle(Level *level, double x, double y, double z, Material *material) : Particle(level, x, y, z, 0, 0, 0) -{ - xd = yd = zd = 0; +DripParticle::DripParticle(Level* level, double x, double y, double z, + Material* material) + : Particle(level, x, y, z, 0, 0, 0) { + xd = yd = zd = 0; - unsigned int clr; - if (material == Material::water) - { - clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripWater); - } - else - { - clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripLavaStart ); - } + unsigned int clr; + if (material == Material::water) { + clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripWater); + } else { + clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripLavaStart); + } - rCol = ( (clr>>16)&0xFF )/255.0f; - gCol = ( (clr>>8)&0xFF )/255.0; - bCol = ( clr&0xFF )/255.0; + rCol = ((clr >> 16) & 0xFF) / 255.0f; + gCol = ((clr >> 8) & 0xFF) / 255.0; + bCol = (clr & 0xFF) / 255.0; - setMiscTex(16 * 7 + 1); - this->setSize(0.01f, 0.01f); - gravity = 0.06f; - this->material = material; - stuckTime = 40; + setMiscTex(16 * 7 + 1); + this->setSize(0.01f, 0.01f); + gravity = 0.06f; + this->material = material; + stuckTime = 40; - lifetime = (int) (64 / (Math::random() * 0.8 + 0.2)); - xd = yd = zd = 0; + lifetime = (int)(64 / (Math::random() * 0.8 + 0.2)); + xd = yd = zd = 0; } -int DripParticle::getLightColor(float a) -{ - if (material == Material::water) return Particle::getLightColor(a); - - // 4J-JEV: Looks like this value was never used on the java version, - // but it is on ours, so I've changed this to be bright manualy. - int s = 0x0f; - int b = 0x0f; - return s << 20 | b << 4; // MGH changed this to a proper value as PS3 wasn't clamping the values. +int DripParticle::getLightColor(float a) { + if (material == Material::water) return Particle::getLightColor(a); + + // 4J-JEV: Looks like this value was never used on the java version, + // but it is on ours, so I've changed this to be bright manualy. + int s = 0x0f; + int b = 0x0f; + return s << 20 | b << 4; // MGH changed this to a proper value as PS3 + // wasn't clamping the values. } -float DripParticle::getBrightness(float a) -{ - if (material == Material::water) return Particle::getBrightness(a); - else return 1.0f; +float DripParticle::getBrightness(float a) { + if (material == Material::water) + return Particle::getBrightness(a); + else + return 1.0f; } -void DripParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void DripParticle::tick() { + xo = x; + yo = y; + zo = z; - if (material == Material::water) - { - //rCol = 0.2f; - //gCol = 0.3f; - //bCol = 1.0f; + if (material == Material::water) { + // rCol = 0.2f; + // gCol = 0.3f; + // bCol = 1.0f; - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripWater); - rCol = ( (clr>>16)&0xFF )/255.0f; - gCol = ( (clr>>8)&0xFF )/255.0; - bCol = ( clr&0xFF )/255.0; - } - else - { - //rCol = 1.0f; - //gCol = 16.0f / (40 - stuckTime + 16); - //bCol = 4.0f / (40 - stuckTime + 8); + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripWater); + rCol = ((clr >> 16) & 0xFF) / 255.0f; + gCol = ((clr >> 8) & 0xFF) / 255.0; + bCol = (clr & 0xFF) / 255.0; + } else { + // rCol = 1.0f; + // gCol = 16.0f / (40 - stuckTime + 16); + // bCol = 4.0f / (40 - stuckTime + 8); - unsigned int cStart = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripLavaStart ); - unsigned int cEnd = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_DripLavaEnd ); - double rStart = ( (cStart>>16)&0xFF )/255.0f, gStart = ( (cStart>>8)&0xFF )/255.0, bStart = ( cStart&0xFF )/255.0; - double rEnd = ( (cEnd>>16)&0xFF )/255.0f, gEnd = ( (cEnd>>8)&0xFF )/255.0, bEnd = ( cEnd&0xFF )/255.0; + unsigned int cStart = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripLavaStart); + unsigned int cEnd = + Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_DripLavaEnd); + double rStart = ((cStart >> 16) & 0xFF) / 255.0f, + gStart = ((cStart >> 8) & 0xFF) / 255.0, + bStart = (cStart & 0xFF) / 255.0; + double rEnd = ((cEnd >> 16) & 0xFF) / 255.0f, + gEnd = ((cEnd >> 8) & 0xFF) / 255.0, + bEnd = (cEnd & 0xFF) / 255.0; - float variance = (40 - stuckTime); - rCol = rStart - ((rStart - rEnd)/40) * variance; - gCol = gStart - ((gStart - gEnd)/40) * variance; - bCol = bStart - ((bStart - bEnd)/40) * variance; - } + float variance = (40 - stuckTime); + rCol = rStart - ((rStart - rEnd) / 40) * variance; + gCol = gStart - ((gStart - gEnd) / 40) * variance; + bCol = bStart - ((bStart - bEnd) / 40) * variance; + } - yd -= gravity; - if (stuckTime-- > 0) - { - xd *= 0.02; - yd *= 0.02; - zd *= 0.02; - setMiscTex(16 * 7 + 1); - } - else - { - setMiscTex(16 * 7 + 0); - } - move(xd, yd, zd); - xd *= 0.98f; - yd *= 0.98f; - zd *= 0.98f; + yd -= gravity; + if (stuckTime-- > 0) { + xd *= 0.02; + yd *= 0.02; + zd *= 0.02; + setMiscTex(16 * 7 + 1); + } else { + setMiscTex(16 * 7 + 0); + } + move(xd, yd, zd); + xd *= 0.98f; + yd *= 0.98f; + zd *= 0.98f; - if (lifetime-- <= 0) remove(); + if (lifetime-- <= 0) remove(); - if (onGround) - { - if (material == Material::water) - { - remove(); - level->addParticle(eParticleType_splash, x, y, z, 0, 0, 0); - } - else - { - setMiscTex(16 * 7 + 2); + if (onGround) { + if (material == Material::water) { + remove(); + level->addParticle(eParticleType_splash, x, y, z, 0, 0, 0); + } else { + setMiscTex(16 * 7 + 2); + } + xd *= 0.7f; + zd *= 0.7f; + } - } - xd *= 0.7f; - zd *= 0.7f; - } - - Material *m = level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - if (m->isLiquid() || m->isSolid()) - { - double y0 = Mth::floor(y) + 1 - LiquidTile::getHeight(level->getData(Mth::floor(x), Mth::floor(y), Mth::floor(z))); - if (y < y0) - { - remove(); - } - } + Material* m = + level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + if (m->isLiquid() || m->isSolid()) { + double y0 = Mth::floor(y) + 1 - + LiquidTile::getHeight(level->getData( + Mth::floor(x), Mth::floor(y), Mth::floor(z))); + if (y < y0) { + remove(); + } + } } diff --git a/Minecraft.Client/Rendering/Particles/DripParticle.h b/Minecraft.Client/Rendering/Particles/DripParticle.h index 1549c3384..7c0b62364 100644 --- a/Minecraft.Client/Rendering/Particles/DripParticle.h +++ b/Minecraft.Client/Rendering/Particles/DripParticle.h @@ -5,18 +5,18 @@ class Level; class Material; -class DripParticle : public Particle -{ +class DripParticle : public Particle { private: - Material *material; - int stuckTime; + Material* material; + int stuckTime; -public: - virtual eINSTANCEOF GetType() { return eTYPE_DRIPPARTICLE; } +public: + virtual eINSTANCEOF GetType() { return eTYPE_DRIPPARTICLE; } - DripParticle(Level *level, double x, double y, double z, Material *material); + DripParticle(Level* level, double x, double y, double z, + Material* material); - virtual int getLightColor(float a); - virtual float getBrightness(float a); - virtual void tick(); + virtual int getLightColor(float a); + virtual float getBrightness(float a); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp index 113edbff2..ff20c175f 100644 --- a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.cpp @@ -2,70 +2,71 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "EnchantmentTableParticle.h" -EchantmentTableParticle::EchantmentTableParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ - this->xd = xd; - this->yd = yd; - this->zd = zd; - this->xStart = this->x = x; - this->yStart = this->y = y; - this->zStart = this->z = z; +EchantmentTableParticle::EchantmentTableParticle(Level* level, double x, + double y, double z, double xd, + double yd, double zd) + : Particle(level, x, y, z, xd, yd, zd) { + this->xd = xd; + this->yd = yd; + this->zd = zd; + this->xStart = this->x = x; + this->yStart = this->y = y; + this->zStart = this->z = z; - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_EnchantmentTable ); //0xE5E5FF - double r = ( (clr>>16)&0xFF )/255.0f, g = ( (clr>>8)&0xFF )/255.0, b = ( clr&0xFF )/255.0; + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_EnchantmentTable); // 0xE5E5FF + double r = ((clr >> 16) & 0xFF) / 255.0f, g = ((clr >> 8) & 0xFF) / 255.0, + b = (clr & 0xFF) / 255.0; - float br = random->nextFloat() * 0.6f + 0.4f; - rCol = r * br; - gCol = g * br; - bCol = b * br; + float br = random->nextFloat() * 0.6f + 0.4f; + rCol = r * br; + gCol = g * br; + bCol = b * br; - oSize = size = random->nextFloat() * 0.5f + 0.2f; + oSize = size = random->nextFloat() * 0.5f + 0.2f; - lifetime = (int) (Math::random() * 10) + 30; - noPhysics = true; - setMiscTex( (int) (Math::random() * 26 + 1 + 14 * 16) ); + lifetime = (int)(Math::random() * 10) + 30; + noPhysics = true; + setMiscTex((int)(Math::random() * 26 + 1 + 14 * 16)); } -int EchantmentTableParticle::getLightColor(float a) -{ - int br = Particle::getLightColor(a); +int EchantmentTableParticle::getLightColor(float a) { + int br = Particle::getLightColor(a); - float pos = age / (float) lifetime; - pos = pos * pos; - pos = pos * pos; + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; - int br1 = (br) & 0xff; - int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); - if (br2 > 15 * 16) br2 = 15 * 16; - return br1 | br2 << 16; + int br1 = (br) & 0xff; + int br2 = (br >> 16) & 0xff; + br2 += (int)(pos * 15 * 16); + if (br2 > 15 * 16) br2 = 15 * 16; + return br1 | br2 << 16; } -float EchantmentTableParticle::getBrightness(float a) -{ - float br = Particle::getBrightness(a); - float pos = age / (float) lifetime; - pos = pos * pos; - pos = pos * pos; - return br * (1 - pos) + pos; +float EchantmentTableParticle::getBrightness(float a) { + float br = Particle::getBrightness(a); + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + return br * (1 - pos) + pos; } -void EchantmentTableParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void EchantmentTableParticle::tick() { + xo = x; + yo = y; + zo = z; - float pos = age / (float) lifetime; + float pos = age / (float)lifetime; - pos = 1 - pos; + pos = 1 - pos; - float pp = 1 - pos; - pp = pp * pp; - pp = pp * pp; - x = xStart + xd * pos; - y = yStart + yd * pos - pp * 1.2f; - z = zStart + zd * pos; + float pp = 1 - pos; + pp = pp * pp; + pp = pp * pp; + x = xStart + xd * pos; + y = yStart + yd * pos - pp * 1.2f; + z = zStart + zd * pos; - if (age++ >= lifetime) remove(); + if (age++ >= lifetime) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h index 98b027c60..334655d5f 100644 --- a/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h +++ b/Minecraft.Client/Rendering/Particles/EnchantmentTableParticle.h @@ -4,18 +4,18 @@ class Level; -class EchantmentTableParticle : public Particle -{ +class EchantmentTableParticle : public Particle { private: - float oSize; - double xStart, yStart, zStart; + float oSize; + double xStart, yStart, zStart; public: - virtual eINSTANCEOF GetType() { return eTYPE_ENCHANTMENTTABLEPARTICLE; } + virtual eINSTANCEOF GetType() { return eTYPE_ENCHANTMENTTABLEPARTICLE; } - EchantmentTableParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); + EchantmentTableParticle(Level* level, double x, double y, double z, + double xd, double yd, double zd); - virtual int getLightColor(float a); - virtual float getBrightness(float a); - virtual void tick(); + virtual int getLightColor(float a); + virtual float getBrightness(float a); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/EnderParticle.cpp b/Minecraft.Client/Rendering/Particles/EnderParticle.cpp index 9b786d009..5e9458e32 100644 --- a/Minecraft.Client/Rendering/Particles/EnderParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/EnderParticle.cpp @@ -3,11 +3,13 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "../../../Minecraft.World/Util/Random.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use +// this particle -EnderParticle::EnderParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ +EnderParticle::EnderParticle(Level* level, double x, double y, double z, + double xd, double yd, double zd) + : Particle(level, x, y, z, xd, yd, zd) { this->xd = xd; this->yd = yd; this->zd = zd; @@ -15,80 +17,80 @@ EnderParticle::EnderParticle(Level *level, double x, double y, double z, double this->yStart = this->y = y; this->zStart = this->z = z; - // 4J-JEV: Set particle colour from colour-table. - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Ender ); //0xE54CFF - rCol = ( (col>>16)&0xFF )/255.0f, gCol = ( (col>>8)&0xFF )/255.0, bCol = ( col&0xFF )/255.0; + // 4J-JEV: Set particle colour from colour-table. + unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Ender); // 0xE54CFF + rCol = ((col >> 16) & 0xFF) / 255.0f, gCol = ((col >> 8) & 0xFF) / 255.0, + bCol = (col & 0xFF) / 255.0; float br = random->nextFloat() * 0.6f + 0.4f; - rCol *= br; gCol *= br; bCol *= br; + rCol *= br; + gCol *= br; + bCol *= br; - //rCol = gCol = bCol = 1.0f*br; - //gCol *= 0.3f; - //rCol *= 0.9f; + // rCol = gCol = bCol = 1.0f*br; + // gCol *= 0.3f; + // rCol *= 0.9f; - oSize = size = random->nextFloat()*0.2f+0.5f; + oSize = size = random->nextFloat() * 0.2f + 0.5f; - lifetime = (int) (Math::random()*10) + 40; + lifetime = (int)(Math::random() * 10) + 40; noPhysics = true; - setMiscTex((int)(Math::random()*8)); + setMiscTex((int)(Math::random() * 8)); } -void EnderParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float s = (age + a) / (float) lifetime; - s = 1-s; - s = s*s; - s = 1-s; +void EnderParticle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { + float s = (age + a) / (float)lifetime; + s = 1 - s; + s = s * s; + s = 1 - s; size = oSize * (s); Particle::render(t, a, xa, ya, za, xa2, za2); } // 4J - brought forward from 1.8.2 -int EnderParticle::getLightColor(float a) -{ +int EnderParticle::getLightColor(float a) { int br = Particle::getLightColor(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); + br2 += (int)(pos * 15 * 16); if (br2 > 15 * 16) br2 = 15 * 16; return br1 | br2 << 16; } -float EnderParticle::getBrightness(float a) -{ +float EnderParticle::getBrightness(float a) { float br = Particle::getBrightness(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - return br*(1-pos)+pos; + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + return br * (1 - pos) + pos; } -void EnderParticle::tick() -{ +void EnderParticle::tick() { xo = x; yo = y; zo = z; - - float pos = age/(float)lifetime; + + float pos = age / (float)lifetime; float a = pos; - pos = -pos+pos*pos*2; -// pos = pos*pos; -// pos = pos*pos; - pos = 1-pos; - - x = xStart+xd*pos; - y = yStart+yd*pos+(1-a); - z = zStart+zd*pos; - - -// spd+=0.002/lifetime*age; + pos = -pos + pos * pos * 2; + // pos = pos*pos; + // pos = pos*pos; + pos = 1 - pos; + + x = xStart + xd * pos; + y = yStart + yd * pos + (1 - a); + z = zStart + zd * pos; + + // spd+=0.002/lifetime*age; if (age++ >= lifetime) remove(); -// move(xd*spd, yd*spd, zd*spd); + // move(xd*spd, yd*spd, zd*spd); } diff --git a/Minecraft.Client/Rendering/Particles/EnderParticle.h b/Minecraft.Client/Rendering/Particles/EnderParticle.h index 56b75b61e..5da1cf44d 100644 --- a/Minecraft.Client/Rendering/Particles/EnderParticle.h +++ b/Minecraft.Client/Rendering/Particles/EnderParticle.h @@ -1,21 +1,24 @@ #pragma once #include "Particle.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle End creatures/items (e.g. EnderMan, EyeOfEnder, etc) use +// this particle -class EnderParticle : public Particle -{ +class EnderParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_ENDERPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_ENDERPARTICLE; } + private: - float oSize; - double xStart, yStart, zStart; + float oSize; + double xStart, yStart, zStart; public: - EnderParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + EnderParticle(Level* level, double x, double y, double z, double xd, + double yd, double zd); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp b/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp index 11d9e257e..586428892 100644 --- a/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/ExplodeParticle.cpp @@ -3,50 +3,54 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "../../../Minecraft.World/Util/Random.h" -ExplodeParticle::ExplodeParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - xd = xa+(float)(Math::random()*2-1)*0.05f; - yd = ya+(float)(Math::random()*2-1)*0.05f; - zd = za+(float)(Math::random()*2-1)*0.05f; - - //rCol = gCol = bCol = random->nextFloat()*.3f+.7; - - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Explode ); //0xFFFFFF - double r = ( (clr>>16)&0xFF )/255.0f, g = ( (clr>>8)&0xFF )/255.0, b = ( clr&0xFF )/255.0; +ExplodeParticle::ExplodeParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, xa, ya, za) { + xd = xa + (float)(Math::random() * 2 - 1) * 0.05f; + yd = ya + (float)(Math::random() * 2 - 1) * 0.05f; + zd = za + (float)(Math::random() * 2 - 1) * 0.05f; - float br = random->nextFloat() * 0.3f + 0.7f; - rCol = r * br; - gCol = g * br; - bCol = b * br; + // rCol = gCol = bCol = random->nextFloat()*.3f+.7; - size = random->nextFloat()*random->nextFloat()*6+1; - - lifetime = (int)(16/(random->nextFloat()*0.8+0.2))+2; -// noPhysics = true; + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Explode); // 0xFFFFFF + double r = ((clr >> 16) & 0xFF) / 255.0f, g = ((clr >> 8) & 0xFF) / 255.0, + b = (clr & 0xFF) / 255.0; + + float br = random->nextFloat() * 0.3f + 0.7f; + rCol = r * br; + gCol = g * br; + bCol = b * br; + + size = random->nextFloat() * random->nextFloat() * 6 + 1; + + lifetime = (int)(16 / (random->nextFloat() * 0.8 + 0.2)) + 2; + // noPhysics = true; } -void ExplodeParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - // 4J - don't render explosion particles that are less than 3 metres away, to try and avoid large particles that are causing us problems with photosensitivity testing - 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); +void ExplodeParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { + // 4J - don't render explosion particles that are less than 3 metres away, + // to try and avoid large particles that are causing us problems with + // photosensitivity testing + 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 distSq = (x*x + y*y + z*z); - if( distSq < (3.0f * 3.0f) ) return; + float distSq = (x * x + y * y + z * z); + if (distSq < (3.0f * 3.0f)) return; - Particle::render(t, a, xa, ya, za, xa2, za2); + Particle::render(t, a, xa, ya, za, xa2, za2); } -void ExplodeParticle::tick() -{ +void ExplodeParticle::tick() { xo = x; yo = y; zo = z; if (age++ >= lifetime) remove(); - - setMiscTex(7-age*8/lifetime); + + setMiscTex(7 - age * 8 / lifetime); yd += 0.004; move(xd, yd, zd); @@ -54,8 +58,7 @@ void ExplodeParticle::tick() yd *= 0.90f; zd *= 0.90f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/ExplodeParticle.h b/Minecraft.Client/Rendering/Particles/ExplodeParticle.h index e25243d60..6bace3ea0 100644 --- a/Minecraft.Client/Rendering/Particles/ExplodeParticle.h +++ b/Minecraft.Client/Rendering/Particles/ExplodeParticle.h @@ -1,11 +1,12 @@ #pragma once #include "Particle.h" -class ExplodeParticle : public Particle -{ +class ExplodeParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_EXPLODEPARTICLE; } - ExplodeParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual void tick(); + virtual eINSTANCEOF GetType() { return eType_EXPLODEPARTICLE; } + ExplodeParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/FlameParticle.cpp b/Minecraft.Client/Rendering/Particles/FlameParticle.cpp index 4ef80a2e1..89106e8e4 100644 --- a/Minecraft.Client/Rendering/Particles/FlameParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/FlameParticle.cpp @@ -3,33 +3,33 @@ #include "../../../Minecraft.World/Util/Random.h" #include "FlameParticle.h" -FlameParticle::FlameParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ - this->xd=this->xd*0.01f+xd; - this->yd=this->yd*0.01f+yd; - this->zd=this->zd*0.01f+zd; - x+=(random->nextFloat()-random->nextFloat())*0.05f; - y+=(random->nextFloat()-random->nextFloat())*0.05f; - z+=(random->nextFloat()-random->nextFloat())*0.05f; - +FlameParticle::FlameParticle(Level* level, double x, double y, double z, + double xd, double yd, double zd) + : Particle(level, x, y, z, xd, yd, zd) { + this->xd = this->xd * 0.01f + xd; + this->yd = this->yd * 0.01f + yd; + this->zd = this->zd * 0.01f + zd; + x += (random->nextFloat() - random->nextFloat()) * 0.05f; + y += (random->nextFloat() - random->nextFloat()) * 0.05f; + z += (random->nextFloat() - random->nextFloat()) * 0.05f; + oSize = size; rCol = gCol = bCol = 1.0f; - - lifetime = (int)(8/(Math::random()*0.8+0.2))+4; + + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)) + 4; noPhysics = true; setMiscTex(48); } -void FlameParticle::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); +void FlameParticle::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); Particle::render(t, a, xa, ya, za, xa2, za2); } // 4J - brought forward from 1.8.2 -int FlameParticle::getLightColor(float a) -{ +int FlameParticle::getLightColor(float a) { float l = (age + a) / lifetime; if (l < 0) l = 0; if (l > 1) l = 1; @@ -37,23 +37,21 @@ int FlameParticle::getLightColor(float a) int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br1 += (int) (l * 15 * 16); + br1 += (int)(l * 15 * 16); if (br1 > 15 * 16) br1 = 15 * 16; return br1 | br2 << 16; } -float FlameParticle::getBrightness(float a) -{ - float l = (age+a)/lifetime; - if (l<0) l = 0; - if (l>1) l = 1; - float br = Particle::getBrightness(a); - - return br*l+(1-l); +float FlameParticle::getBrightness(float a) { + float l = (age + a) / lifetime; + if (l < 0) l = 0; + if (l > 1) l = 1; + float br = Particle::getBrightness(a); + + return br * l + (1 - l); } -void FlameParticle::tick() -{ +void FlameParticle::tick() { xo = x; yo = y; zo = z; @@ -65,8 +63,7 @@ void FlameParticle::tick() yd *= 0.96f; zd *= 0.96f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/FlameParticle.h b/Minecraft.Client/Rendering/Particles/FlameParticle.h index 7097d9dc4..a0fb9f691 100644 --- a/Minecraft.Client/Rendering/Particles/FlameParticle.h +++ b/Minecraft.Client/Rendering/Particles/FlameParticle.h @@ -1,17 +1,19 @@ #pragma once #include "Particle.h" -class FlameParticle : public Particle -{ +class FlameParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_FLAMEPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_FLAMEPARTICLE; } + private: - float oSize; - + float oSize; + public: - FlameParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + FlameParticle(Level* level, double x, double y, double z, double xd, + double yd, double zd); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp b/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp index 8d4e9d86c..40961989c 100644 --- a/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/FootstepParticle.cpp @@ -5,19 +5,20 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -FootstepParticle::FootstepParticle(Textures *textures, Level *level, double x, double y, double z) : Particle(level, x, y, z, 0, 0, 0) -{ - // 4J added initialisers - life = 0; - lifeTime = 0; +FootstepParticle::FootstepParticle(Textures* textures, Level* level, double x, + double y, double z) + : Particle(level, x, y, z, 0, 0, 0) { + // 4J added initialisers + life = 0; + lifeTime = 0; - this->textures = textures; - xd = yd = zd = 0; - lifeTime = 200; + this->textures = textures; + xd = yd = zd = 0; + lifeTime = 200; } -void FootstepParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void FootstepParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float time = (life + a) / lifeTime; time = time * time; @@ -28,36 +29,38 @@ void FootstepParticle::render(Tesselator *t, float a, float xa, float ya, float glDisable(GL_LIGHTING); float r = 2 / 16.0f; - float xx = (float) (x - xOff); - float yy = (float) (y - yOff); - float zz = (float) (z - zOff); + float xx = (float)(x - xOff); + float yy = (float)(y - yOff); + float zz = (float)(z - zOff); - float br = level->getBrightness(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + float br = + level->getBrightness(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - textures->bindTexture(TN_MISC_FOOTSTEP);//L"/misc/footprint.png")); + textures->bindTexture(TN_MISC_FOOTSTEP); // L"/misc/footprint.png")); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); t->begin(); t->color(br, br, br, alpha); - t->vertexUV((float)(xx - r), (float)( yy), (float)( zz + r), (float)( 0), (float)( 1)); - t->vertexUV((float)(xx + r), (float)( yy), (float)( zz + r), (float)( 1), (float)( 1)); - t->vertexUV((float)(xx + r), (float)( yy), (float)( zz - r), (float)( 1), (float)( 0)); - t->vertexUV((float)(xx - r), (float)( yy), (float)( zz - r), (float)( 0), (float)( 0)); + t->vertexUV((float)(xx - r), (float)(yy), (float)(zz + r), (float)(0), + (float)(1)); + t->vertexUV((float)(xx + r), (float)(yy), (float)(zz + r), (float)(1), + (float)(1)); + t->vertexUV((float)(xx + r), (float)(yy), (float)(zz - r), (float)(1), + (float)(0)); + t->vertexUV((float)(xx - r), (float)(yy), (float)(zz - r), (float)(0), + (float)(0)); t->end(); glDisable(GL_BLEND); glEnable(GL_LIGHTING); - } -void FootstepParticle::tick() -{ +void FootstepParticle::tick() { life++; if (life == lifeTime) remove(); } -int FootstepParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int FootstepParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/FootstepParticle.h b/Minecraft.Client/Rendering/Particles/FootstepParticle.h index 50e5e36d1..398b6addd 100644 --- a/Minecraft.Client/Rendering/Particles/FootstepParticle.h +++ b/Minecraft.Client/Rendering/Particles/FootstepParticle.h @@ -2,18 +2,20 @@ #include "Particle.h" class Textures; -class FootstepParticle : public Particle -{ +class FootstepParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_FOOTSTEPPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_FOOTSTEPPARTICLE; } + private: - int life; + int life; int lifeTime; - Textures *textures; + Textures* textures; public: - FootstepParticle(Textures *textures, Level *level, double x, double y, double z); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + FootstepParticle(Textures* textures, Level* level, double x, double y, + double z); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); virtual int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/GuiParticle.cpp b/Minecraft.Client/Rendering/Particles/GuiParticle.cpp index 27c828da9..85497e989 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/GuiParticle.cpp @@ -2,17 +2,16 @@ #include "GuiParticle.h" #include "../../../Minecraft.World/Util/Random.h" -Random *GuiParticle::random = new Random(); +Random* GuiParticle::random = new Random(); -GuiParticle::GuiParticle(double x, double y, double xa, double ya) -{ - // 4J - added initialisation block +GuiParticle::GuiParticle(double x, double y, double xa, double ya) { + // 4J - added initialisation block removed = false; life = 0; a = 1; oR = oG = oB = oA = 0; - - this->xo = this->x = x; + + this->xo = this->x = x; this->yo = this->y = y; this->xa = xa; this->ya = ya; @@ -24,11 +23,10 @@ GuiParticle::GuiParticle(double x, double y, double xa, double ya) friction = 1.0 / (random->nextDouble() * 0.05 + 1.01); - lifeTime = (int) (10.0 / (random->nextDouble() * 2 + 0.1)); + lifeTime = (int)(10.0 / (random->nextDouble() * 2 + 0.1)); } -void GuiParticle::tick(GuiParticles *guiParticles) -{ +void GuiParticle::tick(GuiParticles* guiParticles) { x += xa; y += ya; @@ -37,14 +35,13 @@ void GuiParticle::tick(GuiParticles *guiParticles) ya += 0.1; if (++life > lifeTime) remove(); - a = 2 - (life / (double) lifeTime) * 2; + a = 2 - (life / (double)lifeTime) * 2; if (a > 1) a = 1; a = a * a; a *= 0.5; } -void GuiParticle::preTick() -{ +void GuiParticle::preTick() { oR = r; oG = g; oB = b; @@ -54,7 +51,4 @@ void GuiParticle::preTick() yo = y; } -void GuiParticle::remove() -{ - removed = true; -} \ No newline at end of file +void GuiParticle::remove() { removed = true; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/GuiParticle.h b/Minecraft.Client/Rendering/Particles/GuiParticle.h index 27b14a69e..60434a1e3 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticle.h +++ b/Minecraft.Client/Rendering/Particles/GuiParticle.h @@ -2,13 +2,12 @@ class GuiParticles; class Random; -class GuiParticle -{ +class GuiParticle { private: - static Random *random; + static Random* random; public: - double x, y; + double x, y; double xo, yo; double xa, ya; double friction; @@ -16,10 +15,11 @@ public: int life, lifeTime; double r, g, b, a; - double oR, oG, oB, oA; // MGH - remaned these, as PS3 complained about "or" var name + double oR, oG, oB, + oA; // MGH - remaned these, as PS3 complained about "or" var name GuiParticle(double x, double y, double xa, double ya); - void tick(GuiParticles *guiParticles); + void tick(GuiParticles* guiParticles); void preTick(); void remove(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/GuiParticles.cpp b/Minecraft.Client/Rendering/Particles/GuiParticles.cpp index 3311854f5..c60ffcd81 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticles.cpp +++ b/Minecraft.Client/Rendering/Particles/GuiParticles.cpp @@ -3,37 +3,29 @@ #include "GuiParticle.h" #include "../../Textures/Textures.h" -GuiParticles::GuiParticles(Minecraft *mc) -{ - this->mc = mc; -} +GuiParticles::GuiParticles(Minecraft* mc) { this->mc = mc; } -void GuiParticles::tick() -{ - for (unsigned int i = 0; i < particles.size(); i++) - { - GuiParticle *gp = particles[i]; +void GuiParticles::tick() { + for (unsigned int i = 0; i < particles.size(); i++) { + GuiParticle* gp = particles[i]; gp->preTick(); gp->tick(this); - if (gp->removed) - { - particles.erase(particles.begin()+i); - i--; + if (gp->removed) { + particles.erase(particles.begin() + i); + i--; } } } -void GuiParticles::add(GuiParticle *guiParticle) -{ +void GuiParticles::add(GuiParticle* guiParticle) { particles.push_back(guiParticle); guiParticle->preTick(); } -void GuiParticles::render(float a) -{ - // 4J Stu - Never used +void GuiParticles::render(float a) { + // 4J Stu - Never used #if 0 mc->textures->bindTexture(L"/gui/particles.png"); diff --git a/Minecraft.Client/Rendering/Particles/GuiParticles.h b/Minecraft.Client/Rendering/Particles/GuiParticles.h index 82be7ec60..4c277f4f7 100644 --- a/Minecraft.Client/Rendering/Particles/GuiParticles.h +++ b/Minecraft.Client/Rendering/Particles/GuiParticles.h @@ -4,16 +4,14 @@ class GuiParticle; class Minecraft; - -class GuiParticles : public GuiComponent -{ +class GuiParticles : public GuiComponent { private: - std::vector particles; - Minecraft *mc; + std::vector particles; + Minecraft* mc; public: - GuiParticles(Minecraft *mc); + GuiParticles(Minecraft* mc); void tick(); - void add(GuiParticle *guiParticle); + void add(GuiParticle* guiParticle); void render(float a); }; diff --git a/Minecraft.Client/Rendering/Particles/HeartParticle.cpp b/Minecraft.Client/Rendering/Particles/HeartParticle.cpp index 7109c688a..cb77054ce 100644 --- a/Minecraft.Client/Rendering/Particles/HeartParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/HeartParticle.cpp @@ -2,8 +2,8 @@ #include "HeartParticle.h" // 4J - added -void HeartParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void HeartParticle::init(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale) { xd *= 0.01f; yd *= 0.01f; zd *= 0.01f; @@ -16,22 +16,23 @@ void HeartParticle::init(Level *level, double x, double y, double z, double xa, lifetime = 16; noPhysics = false; - setMiscTex(16 * 5); } -HeartParticle::HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 2); +HeartParticle::HeartParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 2); } -HeartParticle::HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level,x,y,z,xa,ya,za,scale); +HeartParticle::HeartParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void HeartParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void HeartParticle::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; @@ -40,8 +41,7 @@ void HeartParticle::render(Tesselator *t, float a, float xa, float ya, float za, Particle::render(t, a, xa, ya, za, xa2, za2); } -void HeartParticle::tick() -{ +void HeartParticle::tick() { xo = x; yo = y; zo = z; @@ -49,8 +49,7 @@ void HeartParticle::tick() if (age++ >= lifetime) remove(); move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -58,8 +57,7 @@ void HeartParticle::tick() yd *= 0.86f; zd *= 0.86f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/HeartParticle.h b/Minecraft.Client/Rendering/Particles/HeartParticle.h index f249325ef..9c9ef358f 100644 --- a/Minecraft.Client/Rendering/Particles/HeartParticle.h +++ b/Minecraft.Client/Rendering/Particles/HeartParticle.h @@ -1,19 +1,23 @@ #pragma once #include "Particle.h" -class HeartParticle : public Particle -{ +class HeartParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_HEARTPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_HEARTPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J added public: - HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + HeartParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - HeartParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); + HeartParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp index e57961054..eefda7f41 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.cpp @@ -5,78 +5,79 @@ #include "../Tesselator.h" #include "../Lighting.h" -HugeExplosionParticle::HugeExplosionParticle(Textures *textures, Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x,y,z,0,0,0) -{ - life = 0; +HugeExplosionParticle::HugeExplosionParticle(Textures* textures, Level* level, + double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + life = 0; - this->textures = textures; - lifeTime = 6 + random->nextInt(4); + this->textures = textures; + lifeTime = 6 + random->nextInt(4); - // rCol = gCol = bCol = random->nextFloat() * 0.6f + 0.4f; + // rCol = gCol = bCol = random->nextFloat() * 0.6f + 0.4f; - unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_HugeExplosion ); //0x999999 - double r = ( (clr>>16)&0xFF )/255.0f, g = ( (clr>>8)&0xFF )/255.0, b = ( clr&0xFF )/255.0; + unsigned int clr = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_HugeExplosion); // 0x999999 + double r = ((clr >> 16) & 0xFF) / 255.0f, g = ((clr >> 8) & 0xFF) / 255.0, + b = (clr & 0xFF) / 255.0; - double br = random->nextFloat() * 0.6 + 0.4; - rCol = r * br; - gCol = g * br; - bCol = b * br; - - size = 1 - (float) xa * 0.5f; + double br = random->nextFloat() * 0.6 + 0.4; + rCol = r * br; + gCol = g * br; + bCol = b * br; + + size = 1 - (float)xa * 0.5f; } -void HugeExplosionParticle::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->bindTexture(TN_MISC_EXPLOSION); // 4J was "/misc/explosion.png" +void HugeExplosionParticle::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->bindTexture(TN_MISC_EXPLOSION); // 4J was "/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; + 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; - float r = 2.0f * size; + float r = 2.0f * 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 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); - // 4J - don't render explosion particles that are less than 3 metres away, to try and avoid large particles that are causing us problems with photosensitivity testing - float distSq = (x*x + y*y + z*z); - if( distSq < ( 3.0f * 3.0f )) return; + // 4J - don't render explosion particles that are less than 3 metres away, + // to try and avoid large particles that are causing us problems with + // photosensitivity testing + float distSq = (x * x + y * y + z * z); + if (distSq < (3.0f * 3.0f)) return; - glColor4f(1, 1, 1, 1); - glDisable(GL_LIGHTING); - Lighting::turnOff(); - t->begin(); - t->color(rCol, gCol, bCol, 1.0f); - t->normal(0, 1, 0); - t->tex2(0x00f0); - t->vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u1, v1); - 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, u0, v0); - t->vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u0, v1); - t->end(); - glPolygonOffset(0, 0.0f); - glEnable(GL_LIGHTING); + glColor4f(1, 1, 1, 1); + glDisable(GL_LIGHTING); + Lighting::turnOff(); + t->begin(); + t->color(rCol, gCol, bCol, 1.0f); + t->normal(0, 1, 0); + t->tex2(0x00f0); + t->vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u1, v1); + 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, u0, v0); + t->vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u0, v1); + t->end(); + glPolygonOffset(0, 0.0f); + glEnable(GL_LIGHTING); } -int HugeExplosionParticle::getLightColor(float a) -{ - return 0xf0f0; +int HugeExplosionParticle::getLightColor(float a) { return 0xf0f0; } + +void HugeExplosionParticle::tick() { + xo = x; + yo = y; + zo = z; + life++; + if (life == lifeTime) remove(); } -void HugeExplosionParticle::tick() -{ - xo = x; - yo = y; - zo = z; - life++; - if (life == lifeTime) remove(); -} - -int HugeExplosionParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int HugeExplosionParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h index 0f02d1227..2c44d2148 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionParticle.h @@ -2,19 +2,20 @@ #include "Particle.h" -class HugeExplosionParticle : public Particle -{ +class HugeExplosionParticle : public Particle { private: - int life; - int lifeTime; - Textures *textures; - float size; + int life; + int lifeTime; + Textures* textures; + float size; public: - virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONPARTICLE; } - HugeExplosionParticle(Textures *textures, Level *level, double x, double y, double z, double xa, double ya, double za); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - int getLightColor(float a); - void tick(); - int getParticleTexture(); + virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONPARTICLE; } + HugeExplosionParticle(Textures* textures, Level* level, double x, double y, + double z, double xa, double ya, double za); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + int getLightColor(float a); + void tick(); + int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp index cdbc6e157..2bfc541be 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.cpp @@ -3,35 +3,39 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -HugeExplosionSeedParticle::HugeExplosionSeedParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x,y,z,0,0,0) -{ - life = 0; +HugeExplosionSeedParticle::HugeExplosionSeedParticle(Level* level, double x, + double y, double z, + double xa, double ya, + double za) + : Particle(level, x, y, z, 0, 0, 0) { + life = 0; - lifeTime = 8; + lifeTime = 8; } -void HugeExplosionSeedParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void HugeExplosionSeedParticle::render(Tesselator* t, float a, float xa, + float ya, float za, float xa2, + float za2) {} + +void HugeExplosionSeedParticle::tick() { + // Horrible hack to communicate with the level renderer, which is just + // attached as a listener to this level. This let's the particle rendering + // know to use this level (rather than try to work it out from the current + // player), and to not bother distance clipping particles which would again + // be based on the current player. + Minecraft::GetInstance()->animateTickLevel = level; + for (int i = 0; i < 6; i++) { + double xx = x + (random->nextDouble() - random->nextDouble()) * 4; + double yy = y + (random->nextDouble() - random->nextDouble()) * 4; + double zz = z + (random->nextDouble() - random->nextDouble()) * 4; + level->addParticle(eParticleType_largeexplode, xx, yy, zz, + life / (float)lifeTime, 0, 0); + } + Minecraft::GetInstance()->animateTickLevel = NULL; + life++; + if (life == lifeTime) remove(); } -void HugeExplosionSeedParticle::tick() -{ - // Horrible hack to communicate with the level renderer, which is just attached as a listener to this level. This let's the particle - // rendering know to use this level (rather than try to work it out from the current player), and to not bother distance clipping particles - // which would again be based on the current player. - Minecraft::GetInstance()->animateTickLevel = level; - for (int i = 0; i < 6; i++) { - double xx = x + (random->nextDouble() - random->nextDouble()) * 4; - double yy = y + (random->nextDouble() - random->nextDouble()) * 4; - double zz = z + (random->nextDouble() - random->nextDouble()) * 4; - level->addParticle(eParticleType_largeexplode, xx, yy, zz, life / (float) lifeTime, 0, 0); - } - Minecraft::GetInstance()->animateTickLevel = NULL; - life++; - if (life == lifeTime) remove(); -} - -int HugeExplosionSeedParticle::getParticleTexture() -{ - return ParticleEngine::TERRAIN_TEXTURE; +int HugeExplosionSeedParticle::getParticleTexture() { + return ParticleEngine::TERRAIN_TEXTURE; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h index 445c8a347..0ed0b9e33 100644 --- a/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h +++ b/Minecraft.Client/Rendering/Particles/HugeExplosionSeedParticle.h @@ -2,16 +2,17 @@ #include "Particle.h" -class HugeExplosionSeedParticle : public Particle -{ +class HugeExplosionSeedParticle : public Particle { private: - int life; - int lifeTime; + int life; + int lifeTime; public: - virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONSEEDPARTICLE; } - HugeExplosionSeedParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); - int getParticleTexture(); + virtual eINSTANCEOF GetType() { return eType_HUGEEXPLOSIONSEEDPARTICLE; } + HugeExplosionSeedParticle(Level* level, double x, double y, double z, + double xa, double ya, double za); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); + int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/LavaParticle.cpp b/Minecraft.Client/Rendering/Particles/LavaParticle.cpp index 9eb825357..b3cb03c18 100644 --- a/Minecraft.Client/Rendering/Particles/LavaParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/LavaParticle.cpp @@ -4,8 +4,8 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" -LavaParticle::LavaParticle(Level *level, double x, double y, double z) : Particle(level, x, y, z, 0, 0, 0) -{ +LavaParticle::LavaParticle(Level* level, double x, double y, double z) + : Particle(level, x, y, z, 0, 0, 0) { xd *= 0.8f; yd *= 0.8f; zd *= 0.8f; @@ -15,14 +15,13 @@ LavaParticle::LavaParticle(Level *level, double x, double y, double z) : Particl size *= (random->nextFloat() * 2 + 0.2f); oSize = size; - lifetime = (int) (16 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(16 / (Math::random() * 0.8 + 0.2)); noPhysics = false; setMiscTex(49); } // 4J - brought forward from 1.8.2 -int LavaParticle::getLightColor(float a) -{ +int LavaParticle::getLightColor(float a) { float l = (age + a) / lifetime; if (l < 0) l = 0; if (l > 1) l = 1; @@ -33,27 +32,24 @@ int LavaParticle::getLightColor(float a) return br1 | br2 << 16; } -float LavaParticle::getBrightness(float a) -{ - return 1; -} +float LavaParticle::getBrightness(float a) { return 1; } -void LavaParticle::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); +void LavaParticle::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); Particle::render(t, a, xa, ya, za, xa2, za2); } -void LavaParticle::tick() -{ +void LavaParticle::tick() { xo = x; yo = y; zo = z; if (age++ >= lifetime) remove(); - float odds = age / (float) lifetime; - if (random->nextFloat() > odds) level->addParticle(eParticleType_smoke, x, y, z, xd, yd, zd); + float odds = age / (float)lifetime; + if (random->nextFloat() > odds) + level->addParticle(eParticleType_smoke, x, y, z, xd, yd, zd); yd -= 0.03; move(xd, yd, zd); @@ -61,8 +57,7 @@ void LavaParticle::tick() yd *= 0.999f; zd *= 0.999f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/LavaParticle.h b/Minecraft.Client/Rendering/Particles/LavaParticle.h index 235edcf41..de5f4f4b5 100644 --- a/Minecraft.Client/Rendering/Particles/LavaParticle.h +++ b/Minecraft.Client/Rendering/Particles/LavaParticle.h @@ -1,16 +1,18 @@ #pragma once #include "Particle.h" -class LavaParticle : public Particle -{ +class LavaParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_LAVAPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_LAVAPARTICLE; } + private: - float oSize; + float oSize; + public: - LavaParticle(Level *level, double x, double y, double z); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + LavaParticle(Level* level, double x, double y, double z); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; diff --git a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp index 5667515eb..315adc071 100644 --- a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.cpp @@ -4,11 +4,13 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../Minecraft.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// Only the nether portal uses this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle Only the nether portal uses this particle -NetherPortalParticle::NetherPortalParticle(Level *level, double x, double y, double z, double xd, double yd, double zd) : Particle(level, x, y, z, xd, yd, zd) -{ +NetherPortalParticle::NetherPortalParticle(Level* level, double x, double y, + double z, double xd, double yd, + double zd) + : Particle(level, x, y, z, xd, yd, zd) { this->xd = xd; this->yd = yd; this->zd = zd; @@ -16,84 +18,81 @@ NetherPortalParticle::NetherPortalParticle(Level *level, double x, double y, dou this->yStart = this->y = y; this->zStart = this->z = z; - float br = random->nextFloat()*0.6f+0.4f; - oSize = size = random->nextFloat()*0.2f+0.5f; - //rCol = gCol = bCol = 1.0f*br; - //gCol *= 0.3f; - //rCol *= 0.9f; + float br = random->nextFloat() * 0.6f + 0.4f; + oSize = size = random->nextFloat() * 0.2f + 0.5f; + // rCol = gCol = bCol = 1.0f*br; + // gCol *= 0.3f; + // rCol *= 0.9f; - // Default colour (0.9f, 0.3f, 1.0f) - // 0xE64DFF + // Default colour (0.9f, 0.3f, 1.0f) + // 0xE64DFF - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_NetherPortal ); - int r = (colour>>16)&0xFF; - int g = (colour>>8)&0xFF; - int b = colour&0xFF; - rCol = (r/255.0f)*br; - gCol = (g/255.0f)*br; - bCol = (b/255.0f)*br; + unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_NetherPortal); + int r = (colour >> 16) & 0xFF; + int g = (colour >> 8) & 0xFF; + int b = colour & 0xFF; + rCol = (r / 255.0f) * br; + gCol = (g / 255.0f) * br; + bCol = (b / 255.0f) * br; - lifetime = (int) (Math::random()*10) + 40; + lifetime = (int)(Math::random() * 10) + 40; noPhysics = true; - setMiscTex((int)(Math::random()*8)); + setMiscTex((int)(Math::random() * 8)); } -void NetherPortalParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ - float s = (age + a) / (float) lifetime; - s = 1-s; - s = s*s; - s = 1-s; +void NetherPortalParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { + float s = (age + a) / (float)lifetime; + s = 1 - s; + s = s * s; + s = 1 - s; size = oSize * (s); Particle::render(t, a, xa, ya, za, xa2, za2); } // 4J - brought forward from 1.8.2 -int NetherPortalParticle::getLightColor(float a) -{ +int NetherPortalParticle::getLightColor(float a) { int br = Particle::getLightColor(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + int br1 = (br) & 0xff; int br2 = (br >> 16) & 0xff; - br2 += (int) (pos * 15 * 16); + br2 += (int)(pos * 15 * 16); if (br2 > 15 * 16) br2 = 15 * 16; return br1 | br2 << 16; } -float NetherPortalParticle::getBrightness(float a) -{ +float NetherPortalParticle::getBrightness(float a) { float br = Particle::getBrightness(a); - float pos = age/(float)lifetime; - pos = pos*pos; - pos = pos*pos; - return br*(1-pos)+pos; + float pos = age / (float)lifetime; + pos = pos * pos; + pos = pos * pos; + return br * (1 - pos) + pos; } -void NetherPortalParticle::tick() -{ +void NetherPortalParticle::tick() { xo = x; yo = y; zo = z; - - float pos = age/(float)lifetime; + + float pos = age / (float)lifetime; float a = pos; - pos = -pos+pos*pos*2; -// pos = pos*pos; -// pos = pos*pos; - pos = 1-pos; - - x = xStart+xd*pos; - y = yStart+yd*pos+(1-a); - z = zStart+zd*pos; - - -// spd+=0.002/lifetime*age; + pos = -pos + pos * pos * 2; + // pos = pos*pos; + // pos = pos*pos; + pos = 1 - pos; + + x = xStart + xd * pos; + y = yStart + yd * pos + (1 - a); + z = zStart + zd * pos; + + // spd+=0.002/lifetime*age; if (age++ >= lifetime) remove(); -// move(xd*spd, yd*spd, zd*spd); + // move(xd*spd, yd*spd, zd*spd); } diff --git a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h index 85aa8c669..a053d356e 100644 --- a/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h +++ b/Minecraft.Client/Rendering/Particles/NetherPortalParticle.h @@ -1,21 +1,23 @@ #pragma once #include "Particle.h" -// 4J Stu - This class was originally "PortalParticle" but I have split the two uses of the particle -// Only the nether portal uses this particle +// 4J Stu - This class was originally "PortalParticle" but I have split the two +// uses of the particle Only the nether portal uses this particle -class NetherPortalParticle : public Particle -{ +class NetherPortalParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_NETHERPORTALPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_NETHERPORTALPARTICLE; } + private: - float oSize; - double xStart, yStart, zStart; + float oSize; + double xStart, yStart, zStart; public: - NetherPortalParticle(Level *level, double x, double y, double z, double xd, double yd, double zd); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 + NetherPortalParticle(Level* level, double x, double y, double z, double xd, + double yd, double zd); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual int getLightColor(float a); // 4J - brought forward from 1.8.2 virtual float getBrightness(float a); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/NoteParticle.cpp b/Minecraft.Client/Rendering/Particles/NoteParticle.cpp index d4f50d182..db6bb47b5 100644 --- a/Minecraft.Client/Rendering/Particles/NoteParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/NoteParticle.cpp @@ -2,32 +2,38 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "NoteParticle.h" -void NoteParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void NoteParticle::init(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale) { xd *= 0.01f; yd *= 0.01f; zd *= 0.01f; yd += 0.2; - /* - unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_NoteMin ); - unsigned int cMax = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_NoteMax ); - double rMin = ( (cMin>>16)&0xFF )/255.0f, gMin = ( (cMin>>8)&0xFF )/255.0, bMin = ( cMin&0xFF )/255.0; - double rMax = ( (cMax>>16)&0xFF )/255.0f, gMax = ( (cMax>>8)&0xFF )/255.0, bMax = ( cMax&0xFF )/255.0; + /* + unsigned int cMin = Minecraft::GetInstance()->getColourTable()->getColor( +eMinecraftColour_Particle_NoteMin ); unsigned int cMax = +Minecraft::GetInstance()->getColourTable()->getColor( +eMinecraftColour_Particle_NoteMax ); double rMin = ( (cMin>>16)&0xFF )/255.0f, +gMin = ( (cMin>>8)&0xFF )/255.0, bMin = ( cMin&0xFF )/255.0; double rMax = ( +(cMax>>16)&0xFF )/255.0f, gMax = ( (cMax>>8)&0xFF )/255.0, bMax = ( cMax&0xFF +)/255.0; - rCol = Mth::sin(((float) xa + 0.0f / 3) * PI * 2) * (rMax - rMin) + rMin; - gCol = Mth::sin(((float) xa + 1.0f / 3) * PI * 2) * (gMax - gMin) + gMin; - bCol = Mth::sin(((float) xa + 2.0f / 3) * PI * 2) * (bMax - bMin) + bMin; - */ +rCol = Mth::sin(((float) xa + 0.0f / 3) * PI * 2) * (rMax - rMin) + rMin; +gCol = Mth::sin(((float) xa + 1.0f / 3) * PI * 2) * (gMax - gMin) + gMin; +bCol = Mth::sin(((float) xa + 2.0f / 3) * PI * 2) * (bMax - bMin) + bMin; + */ - // 4J-JEV: Added, - // There are 24 valid colours for this particle input through the 'xa' field (0.0-1.0). - int note = (int) floor(0.5 + (xa*24.0)) + (int) eMinecraftColour_Particle_Note_00; - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( (eMinecraftColour) note ); - - rCol = ( (col>>16)&0xFF )/255.0; - gCol = ( (col>>8)&0xFF )/255.0; - bCol = ( col&0xFF )/255.0; + // 4J-JEV: Added, + // There are 24 valid colours for this particle input through the 'xa' field + // (0.0-1.0). + int note = + (int)floor(0.5 + (xa * 24.0)) + (int)eMinecraftColour_Particle_Note_00; + unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( + (eMinecraftColour)note); + + rCol = ((col >> 16) & 0xFF) / 255.0; + gCol = ((col >> 8) & 0xFF) / 255.0; + bCol = (col & 0xFF) / 255.0; size *= 0.75f; size *= scale; @@ -36,22 +42,23 @@ void NoteParticle::init(Level *level, double x, double y, double z, double xa, d lifetime = 6; noPhysics = false; - setMiscTex(16 * 4); } -NoteParticle::NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 2); +NoteParticle::NoteParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 2); } -NoteParticle::NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, scale); +NoteParticle::NoteParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void NoteParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void NoteParticle::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; @@ -60,8 +67,7 @@ void NoteParticle::render(Tesselator *t, float a, float xa, float ya, float za, Particle::render(t, a, xa, ya, za, xa2, za2); } -void NoteParticle::tick() -{ +void NoteParticle::tick() { xo = x; yo = y; zo = z; @@ -69,8 +75,7 @@ void NoteParticle::tick() if (age++ >= lifetime) remove(); move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -78,10 +83,8 @@ void NoteParticle::tick() yd *= 0.66f; zd *= 0.66f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } - } diff --git a/Minecraft.Client/Rendering/Particles/NoteParticle.h b/Minecraft.Client/Rendering/Particles/NoteParticle.h index b53910b8d..75af522d5 100644 --- a/Minecraft.Client/Rendering/Particles/NoteParticle.h +++ b/Minecraft.Client/Rendering/Particles/NoteParticle.h @@ -1,16 +1,20 @@ #pragma once #include "Particle.h" -class NoteParticle : public Particle -{ +class NoteParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_NOTEPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_NOTEPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + NoteParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - NoteParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + NoteParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; diff --git a/Minecraft.Client/Rendering/Particles/Particle.cpp b/Minecraft.Client/Rendering/Particles/Particle.cpp index 422f9ca6d..8fea088a5 100644 --- a/Minecraft.Client/Rendering/Particles/Particle.cpp +++ b/Minecraft.Client/Rendering/Particles/Particle.cpp @@ -9,116 +9,93 @@ /* protected int tex; protected float gravity; - */ + */ double Particle::xOff = 0; double Particle::yOff = 0; double Particle::zOff = 0; -void Particle::_init(Level *level, double x, double y, double z) -{ - // 4J - added these initialisers - alpha = 1.0f; +void Particle::_init(Level* level, double x, double y, double z) { + // 4J - added these initialisers + alpha = 1.0f; tex = NULL; - gravity = 0.0f; + gravity = 0.0f; - setSize(0.2f, 0.2f); - heightOffset = bbHeight / 2.0f; - setPos(x, y, z); - xo = xOld = x; - yo = yOld = y; - zo = zOld = z; - rCol = gCol = bCol = 1.0f; + setSize(0.2f, 0.2f); + heightOffset = bbHeight / 2.0f; + setPos(x, y, z); + xo = xOld = x; + yo = yOld = y; + zo = zOld = z; + rCol = gCol = bCol = 1.0f; - uo = random->nextFloat() * 3; - vo = random->nextFloat() * 3; + uo = random->nextFloat() * 3; + vo = random->nextFloat() * 3; - size = (random->nextFloat() * 0.5f + 0.5f) * 2; + size = (random->nextFloat() * 0.5f + 0.5f) * 2; - lifetime = (int) (4 / (random->nextFloat() * 0.9f + 0.1f)); - age = 0; + lifetime = (int)(4 / (random->nextFloat() * 0.9f + 0.1f)); + age = 0; - texX = 0; - texY = 0; + texX = 0; + texY = 0; } -Particle::Particle(Level *level, double x, double y, double z) : Entity(level, false) -{ - _init(level,x,y,z); +Particle::Particle(Level* level, double x, double y, double z) + : Entity(level, false) { + _init(level, x, y, z); } -Particle::Particle(Level *level, double x, double y, double z, double xa, double ya, double za) : Entity(level, false) -{ - _init(level,x,y,z); +Particle::Particle(Level* level, double x, double y, double z, double xa, + double ya, double za) + : Entity(level, false) { + _init(level, x, y, z); - xd = xa + (float) (Math::random() * 2 - 1) * 0.4f; - yd = ya + (float) (Math::random() * 2 - 1) * 0.4f; - zd = za + (float) (Math::random() * 2 - 1) * 0.4f; - float speed = (float) (Math::random() + Math::random() + 1) * 0.15f; + xd = xa + (float)(Math::random() * 2 - 1) * 0.4f; + yd = ya + (float)(Math::random() * 2 - 1) * 0.4f; + zd = za + (float)(Math::random() * 2 - 1) * 0.4f; + float speed = (float)(Math::random() + Math::random() + 1) * 0.15f; - float dd = (float) (Mth::sqrt(xd * xd + yd * yd + zd * zd)); + float dd = (float)(Mth::sqrt(xd * xd + yd * yd + zd * zd)); xd = xd / dd * speed * 0.4f; yd = yd / dd * speed * 0.4f + 0.1f; - zd = zd / dd * speed * 0.4f;} + zd = zd / dd * speed * 0.4f; +} -std::shared_ptr Particle::setPower(float power) -{ +std::shared_ptr Particle::setPower(float power) { xd *= power; yd = (yd - 0.1f) * power + 0.1f; zd *= power; - return std::dynamic_pointer_cast( shared_from_this() ); + return std::dynamic_pointer_cast(shared_from_this()); } -std::shared_ptr Particle::scale(float scale) -{ +std::shared_ptr Particle::scale(float scale) { setSize(0.2f * scale, 0.2f * scale); size *= scale; - return std::dynamic_pointer_cast( shared_from_this() ); + return std::dynamic_pointer_cast(shared_from_this()); } -void Particle::setColor(float r, float g, float b) -{ - this->rCol = r; - this->gCol = g; - this->bCol = b; +void Particle::setColor(float r, float g, float b) { + this->rCol = r; + this->gCol = g; + this->bCol = b; } -void Particle::setAlpha(float alpha) -{ - this->alpha = alpha; -} +void Particle::setAlpha(float alpha) { this->alpha = alpha; } -float Particle::getRedCol() -{ - return rCol; -} +float Particle::getRedCol() { return rCol; } -float Particle::getGreenCol() -{ - return gCol; -} +float Particle::getGreenCol() { return gCol; } -float Particle::getBlueCol() -{ - return bCol; -} +float Particle::getBlueCol() { return bCol; } -float Particle::getAlpha() -{ - return alpha; -} +float Particle::getAlpha() { return alpha; } -bool Particle::makeStepSound() -{ - return false; -} +bool Particle::makeStepSound() { return false; } -void Particle::defineSynchedData() -{ -} +void Particle::defineSynchedData() {} -void Particle::tick() -{ +void Particle::tick() { xo = x; yo = y; zo = z; @@ -131,116 +108,102 @@ void Particle::tick() yd *= 0.98f; zd *= 0.98f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } - } -void Particle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void Particle::render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2) { float u0 = texX / 16.0f; float u1 = u0 + 0.999f / 16.0f; float v0 = texY / 16.0f; float v1 = v0 + 0.999f / 16.0f; float r = 0.1f * size; - if (tex != NULL) - { - u0 = tex->getU0(); - u1 = tex->getU1(); - v0 = tex->getV0(); - v1 = tex->getV1(); - } + if (tex != NULL) { + u0 = tex->getU0(); + u1 = tex->getU1(); + v0 = tex->getV0(); + v1 = tex->getV1(); + } - 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 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 = 1.0f; // 4J - change brought forward from 1.8.2 - if( !SharedConstants::TEXTURE_LIGHTING ) - { - br = getBrightness(a); - } + float br = 1.0f; // 4J - change brought forward from 1.8.2 + if (!SharedConstants::TEXTURE_LIGHTING) { + br = getBrightness(a); + } #ifdef __PSVITA__ - // AP - this will set up the 4 vertices in half the time. - t->tileParticleQuad((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u1), (float)( v1), - (float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u1), (float)( v0), - (float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u0), (float)( v0), - (float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u0), (float)( v1), - rCol * br, gCol * br, bCol * br, alpha); + // AP - this will set up the 4 vertices in half the time. + t->tileParticleQuad((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u1), (float)(v1), + (float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u1), (float)(v0), + (float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u0), (float)(v0), + (float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u0), (float)(v1), + rCol * br, gCol * br, bCol * br, alpha); #else t->color(rCol * br, gCol * br, bCol * br, alpha); - t->vertexUV((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u1), (float)( v1)); - t->vertexUV((float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u1), (float)( v0)); - t->vertexUV((float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u0), (float)( v0)); - t->vertexUV((float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u0), (float)( v1)); + t->vertexUV((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u1), (float)(v1)); + t->vertexUV((float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u0), (float)(v1)); #endif } -int Particle::getParticleTexture() -{ - return ParticleEngine::MISC_TEXTURE; -} +int Particle::getParticleTexture() { return ParticleEngine::MISC_TEXTURE; } -void Particle::addAdditonalSaveData(CompoundTag *entityTag) -{ -} +void Particle::addAdditonalSaveData(CompoundTag* entityTag) {} -void Particle::readAdditionalSaveData(CompoundTag *tag) -{ -} +void Particle::readAdditionalSaveData(CompoundTag* tag) {} -void Particle::setTex(Textures *textures, Icon *icon) -{ - if (getParticleTexture() == ParticleEngine::TERRAIN_TEXTURE) - { - tex = icon; - } - else if (getParticleTexture() == ParticleEngine::ITEM_TEXTURE) - { - tex = icon; - } - else - { +void Particle::setTex(Textures* textures, Icon* icon) { + if (getParticleTexture() == ParticleEngine::TERRAIN_TEXTURE) { + tex = icon; + } else if (getParticleTexture() == ParticleEngine::ITEM_TEXTURE) { + tex = icon; + } else { #ifndef _CONTENT_PACKAGE - printf("Invalid call to Particle.setTex, use coordinate methods\n"); - __debugbreak(); + printf("Invalid call to Particle.setTex, use coordinate methods\n"); + __debugbreak(); #endif - //throw new RuntimeException("Invalid call to Particle.setTex, use coordinate methods"); - } + // throw new RuntimeException("Invalid call to Particle.setTex, use + // coordinate methods"); + } } -void Particle::setMiscTex(int slotIndex) -{ - if (getParticleTexture() != ParticleEngine::MISC_TEXTURE && getParticleTexture() != ParticleEngine::DRAGON_BREATH_TEXTURE) - { +void Particle::setMiscTex(int slotIndex) { + if (getParticleTexture() != ParticleEngine::MISC_TEXTURE && + getParticleTexture() != ParticleEngine::DRAGON_BREATH_TEXTURE) { #ifndef _CONTENT_PACKAGE - printf("Invalid call to Particle.setMixTex\n"); - __debugbreak(); - //throw new RuntimeException("Invalid call to Particle.setMiscTex"); + printf("Invalid call to Particle.setMixTex\n"); + __debugbreak(); + // throw new RuntimeException("Invalid call to Particle.setMiscTex"); #endif - } - texX = slotIndex % 16; - texY = slotIndex / 16; + } + texX = slotIndex % 16; + texY = slotIndex / 16; } -void Particle::setNextMiscAnimTex() -{ - texX++; -} +void Particle::setNextMiscAnimTex() { texX++; } -bool Particle::isAttackable() -{ - return false; -} +bool Particle::isAttackable() { return false; } //@Override -std::wstring Particle::toString() -{ - return L"A particle"; //getClass()->getSimpleName() + ", Pos (" + x + "," + y + "," + z + "), RGBA (" + rCol + "," + gCol + "," + bCol + "," + alpha + "), Age " + age; +std::wstring Particle::toString() { + return L"A particle"; // getClass()->getSimpleName() + ", Pos (" + x + "," + // + y + "," + z + "), RGBA (" + rCol + "," + gCol + + // "," + bCol + "," + alpha + "), Age " + age; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/Particle.h b/Minecraft.Client/Rendering/Particles/Particle.h index e2202c14c..f8b99761f 100644 --- a/Minecraft.Client/Rendering/Particles/Particle.h +++ b/Minecraft.Client/Rendering/Particles/Particle.h @@ -1,6 +1,5 @@ #pragma once - #include "../../../Minecraft.World/Entities/Entity.h" #include "../../../Minecraft.World/Util/ParticleTypes.h" #include "ParticleEngine.h" @@ -8,46 +7,53 @@ class Tesselator; class CompoundTag; class Icon; -class Particle : public Entity -{ +class Particle : public Entity { protected: - int texX, texY; + int texX, texY; float uo, vo; int age; int lifetime; float size; float gravity; float rCol, gCol, bCol; - float alpha; - Icon *tex; + float alpha; + Icon* tex; + public: - static double xOff, yOff, zOff; + static double xOff, yOff, zOff; + private: - void _init(Level *level, double x, double y, double z); + void _init(Level* level, double x, double y, double z); + protected: - Particle(Level *level, double x, double y, double z); + Particle(Level* level, double x, double y, double z); + public: - Particle(Level *level, double x, double y, double z, double xa, double ya, double za); + Particle(Level* level, double x, double y, double z, double xa, double ya, + double za); virtual std::shared_ptr setPower(float power); virtual std::shared_ptr scale(float scale); - void setColor(float r, float g, float b); - void setAlpha(float alpha); - float getRedCol(); - float getGreenCol(); - float getBlueCol(); - float getAlpha(); + void setColor(float r, float g, float b); + void setAlpha(float alpha); + float getRedCol(); + float getGreenCol(); + float getBlueCol(); + float getAlpha(); + protected: - virtual bool makeStepSound(); + virtual bool makeStepSound(); virtual void defineSynchedData(); + public: - 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 void setTex(Textures *textures, Icon *icon); - virtual void setMiscTex(int slotIndex); - virtual void setNextMiscAnimTex(); - virtual bool isAttackable(); - virtual std::wstring toString(); + 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 void setTex(Textures* textures, Icon* icon); + virtual void setMiscTex(int slotIndex); + virtual void setNextMiscAnimTex(); + virtual bool isAttackable(); + virtual std::wstring toString(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp b/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp index 978ac1ea0..2eb3e59cb 100644 --- a/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp +++ b/Minecraft.Client/Rendering/Particles/ParticleEngine.cpp @@ -11,54 +11,50 @@ #include "../../../Minecraft.World/Util/StringHelpers.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.dimension.h" -ParticleEngine::ParticleEngine(Level *level, Textures *textures) -{ -// if (level != NULL) // 4J - removed - we want level to be initialised to *something* - { +ParticleEngine::ParticleEngine(Level* level, Textures* textures) { + // if (level != NULL) // 4J - removed - we want level to be + // initialised to *something* + { this->level = level; } this->textures = textures; - - this->random = new Random(); + + this->random = new Random(); } -ParticleEngine::~ParticleEngine() -{ - delete random; -} +ParticleEngine::~ParticleEngine() { delete random; } -void ParticleEngine::add(std::shared_ptr p) -{ +void ParticleEngine::add(std::shared_ptr p) { int t = p->getParticleTexture(); - int l = p->level->dimension->id == 0 ? 0 : ( p->level->dimension->id == -1 ? 1 : 2); - if ( (t != DRAGON_BREATH_TEXTURE && particles[l][t].size() >= MAX_PARTICLES_PER_LAYER) || particles[l][t].size() >= MAX_DRAGON_BREATH_PARTICLES) particles[l][t].pop_front();//particles[l][t].erase(particles[l][t].begin()); + int l = p->level->dimension->id == 0 + ? 0 + : (p->level->dimension->id == -1 ? 1 : 2); + if ((t != DRAGON_BREATH_TEXTURE && + particles[l][t].size() >= MAX_PARTICLES_PER_LAYER) || + particles[l][t].size() >= MAX_DRAGON_BREATH_PARTICLES) + particles[l][t] + .pop_front(); // particles[l][t].erase(particles[l][t].begin()); particles[l][t].push_back(p); } -void ParticleEngine::tick() -{ - for( int l = 0; l < 3; l++ ) - { - for (int tt = 0; tt < TEXTURE_COUNT; tt++) - { - for (unsigned int i = 0; i < particles[l][tt].size(); i++) - { - std::shared_ptr p = particles[l][tt][i]; - p->tick(); - if (p->removed) - { - particles[l][tt][i] = particles[l][tt].back(); - particles[l][tt].pop_back(); - i--; - } - } - } - } +void ParticleEngine::tick() { + for (int l = 0; l < 3; l++) { + for (int tt = 0; tt < TEXTURE_COUNT; tt++) { + for (unsigned int i = 0; i < particles[l][tt].size(); i++) { + std::shared_ptr p = particles[l][tt][i]; + p->tick(); + if (p->removed) { + particles[l][tt][i] = particles[l][tt].back(); + particles[l][tt].pop_back(); + i--; + } + } + } + } } -void ParticleEngine::render(std::shared_ptr player, float a) -{ - // 4J - change brought forward from 1.2.3 +void ParticleEngine::render(std::shared_ptr player, float a) { + // 4J - change brought forward from 1.2.3 float xa = Camera::xa; float za = Camera::za; @@ -69,19 +65,22 @@ void ParticleEngine::render(std::shared_ptr player, float a) Particle::xOff = (player->xOld + (player->x - player->xOld) * a); Particle::yOff = (player->yOld + (player->y - player->yOld) * a); Particle::zOff = (player->zOld + (player->z - player->zOld) * a); - int l = level->dimension->id == 0 ? 0 : ( level->dimension->id == -1 ? 1 : 2 ); - for (int tt = 0; tt < TEXTURE_COUNT; tt++) - { - if(tt == ENTITY_PARTICLE_TEXTURE) continue; + int l = + level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2); + for (int tt = 0; tt < TEXTURE_COUNT; tt++) { + if (tt == ENTITY_PARTICLE_TEXTURE) continue; if (particles[l][tt].empty()) continue; - MemSect(31); - if (tt == MISC_TEXTURE || tt == DRAGON_BREATH_TEXTURE) textures->bindTexture(TN_PARTICLES); // 4J was L"/particles.png" - if (tt == TERRAIN_TEXTURE) textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" - if (tt == ITEM_TEXTURE) textures->bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + if (tt == MISC_TEXTURE || tt == DRAGON_BREATH_TEXTURE) + textures->bindTexture(TN_PARTICLES); // 4J was L"/particles.png" + if (tt == TERRAIN_TEXTURE) + textures->bindTexture(TN_TERRAIN); // 4J was L"/terrain.png" + if (tt == ITEM_TEXTURE) + textures->bindTexture(TN_GUI_ITEMS); // 4J was L"/gui/items.png" + MemSect(0); + Tesselator* t = Tesselator::getInstance(); glColor4f(1.0f, 1.0f, 1.0f, 1); #if 0 // Note that these changes were brought in from java (1.5ish), but as with the java version, break rendering of the particles @@ -92,17 +91,16 @@ void ParticleEngine::render(std::shared_ptr player, float a) glAlphaFunc(GL_GREATER, 1.0f / 255.0f); #endif t->begin(); - for (unsigned int i = 0; i < particles[l][tt].size(); i++) - { - if(t->hasMaxVertices()) - { - t->end(); - t->begin(); - } + for (unsigned int i = 0; i < particles[l][tt].size(); i++) { + if (t->hasMaxVertices()) { + t->end(); + t->begin(); + } std::shared_ptr p = particles[l][tt][i]; - if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward from 1.8.2 - { + if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought + // forward from 1.8.2 + { t->tex2(p->getLightColor(a)); } p->render(t, a, xa, ya, za, xa2, za2); @@ -115,98 +113,110 @@ void ParticleEngine::render(std::shared_ptr player, float a) glAlphaFunc(GL_GREATER, .1f); #endif } - } -void ParticleEngine::renderLit(std::shared_ptr player, float a) -{ - // 4J - added. We call this before ParticleEngine::render in the general render per player, so if we - // don't set this here then the offsets will be from the previous player - a single frame lag for the - // java game, or totally incorrect placement of things for split screen. +void ParticleEngine::renderLit(std::shared_ptr player, float a) { + // 4J - added. We call this before ParticleEngine::render in the general + // render per player, so if we don't set this here then the offsets will be + // from the previous player - a single frame lag for the java game, or + // totally incorrect placement of things for split screen. Particle::xOff = (player->xOld + (player->x - player->xOld) * a); Particle::yOff = (player->yOld + (player->y - player->yOld) * a); Particle::zOff = (player->zOld + (player->z - player->zOld) * a); - float RAD = PI / 180; - float xa = (float) Mth::cos(player->yRot * RAD); - float za = (float) Mth::sin(player->yRot * RAD); + float RAD = PI / 180; + float xa = (float)Mth::cos(player->yRot * RAD); + float za = (float)Mth::sin(player->yRot * RAD); - float xa2 = -za * (float) Mth::sin(player->xRot * RAD); - float za2 = xa * (float) Mth::sin(player->xRot * RAD); - float ya = (float) Mth::cos(player->xRot * RAD); + float xa2 = -za * (float)Mth::sin(player->xRot * RAD); + float za2 = xa * (float)Mth::sin(player->xRot * RAD); + float ya = (float)Mth::cos(player->xRot * RAD); - int l = level->dimension->id == 0 ? 0 : ( level->dimension->id == -1 ? 1 : 2 ); + int l = + level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2); int tt = ENTITY_PARTICLE_TEXTURE; if (particles[l][tt].empty()) return; - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < particles[l][tt].size(); i++) - { + Tesselator* t = Tesselator::getInstance(); + for (unsigned int i = 0; i < particles[l][tt].size(); i++) { std::shared_ptr p = particles[l][tt][i]; - if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward from 1.8.2 - { + if (SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward + // from 1.8.2 + { t->tex2(p->getLightColor(a)); } p->render(t, a, xa, ya, za, xa2, za2); } } -void ParticleEngine::setLevel(Level *level) -{ +void ParticleEngine::setLevel(Level* level) { this->level = level; - // 4J - we've now got a set of particle vectors for each dimension, and only clearing them when its game over & the level is set to NULL - if( level == NULL ) - { - for( int l = 0; l < 3; l++ ) - { - for (int tt = 0; tt < TEXTURE_COUNT; tt++) - { - particles[l][tt].clear(); - } - } - } + // 4J - we've now got a set of particle vectors for each dimension, and only + // clearing them when its game over & the level is set to NULL + if (level == NULL) { + for (int l = 0; l < 3; l++) { + for (int tt = 0; tt < TEXTURE_COUNT; tt++) { + particles[l][tt].clear(); + } + } + } } -void ParticleEngine::destroy(int x, int y, int z, int tid, int data) -{ +void ParticleEngine::destroy(int x, int y, int z, int tid, int data) { if (tid == 0) return; - Tile *tile = Tile::tiles[tid]; + Tile* tile = Tile::tiles[tid]; int SD = 4; for (int xx = 0; xx < SD; xx++) for (int yy = 0; yy < SD; yy++) - for (int zz = 0; zz < SD; zz++) - { + for (int zz = 0; zz < SD; zz++) { double xp = x + (xx + 0.5) / SD; double yp = y + (yy + 0.5) / SD; double zp = z + (zz + 0.5) / SD; - int face = random->nextInt(6); - add(( std::shared_ptr(new TerrainParticle(level, xp, yp, zp, xp - x - 0.5f, yp - y - 0.5f, zp - z - 0.5f, tile, face, data, textures) ) )->init(x, y, z, data)); + int face = random->nextInt(6); + add((std::shared_ptr(new TerrainParticle( + level, xp, yp, zp, xp - x - 0.5f, yp - y - 0.5f, + zp - z - 0.5f, tile, face, data, textures))) + ->init(x, y, z, data)); } } -void ParticleEngine::crack(int x, int y, int z, int face) -{ +void ParticleEngine::crack(int x, int y, int z, int face) { int tid = level->getTile(x, y, z); if (tid == 0) return; - Tile *tile = Tile::tiles[tid]; + Tile* tile = Tile::tiles[tid]; float r = 0.10f; - double xp = x + random->nextDouble() * ((tile->getShapeX1() - tile->getShapeX0()) - r * 2) + r + tile->getShapeX0(); - double yp = y + random->nextDouble() * ((tile->getShapeY1() - tile->getShapeY0()) - r * 2) + r + tile->getShapeY0(); - double zp = z + random->nextDouble() * ((tile->getShapeZ1() - tile->getShapeZ0()) - r * 2) + r + tile->getShapeZ0(); + double xp = x + + random->nextDouble() * + ((tile->getShapeX1() - tile->getShapeX0()) - r * 2) + + r + tile->getShapeX0(); + double yp = y + + random->nextDouble() * + ((tile->getShapeY1() - tile->getShapeY0()) - r * 2) + + r + tile->getShapeY0(); + double zp = z + + random->nextDouble() * + ((tile->getShapeZ1() - tile->getShapeZ0()) - r * 2) + + r + tile->getShapeZ0(); if (face == 0) yp = y + tile->getShapeY0() - r; if (face == 1) yp = y + tile->getShapeY1() + r; if (face == 2) zp = z + tile->getShapeZ0() - r; if (face == 3) zp = z + tile->getShapeZ1() + r; if (face == 4) xp = x + tile->getShapeX0() - r; if (face == 5) xp = x + tile->getShapeX1() + r; - add(( std::shared_ptr(new TerrainParticle(level, xp, yp, zp, 0, 0, 0, tile, face, level->getData(x, y, z), textures) ) )->init(x, y, z, level->getData(x, y, z))->setPower(0.2f)->scale(0.6f)); - + add((std::shared_ptr( + new TerrainParticle(level, xp, yp, zp, 0, 0, 0, tile, face, + level->getData(x, y, z), textures))) + ->init(x, y, z, level->getData(x, y, z)) + ->setPower(0.2f) + ->scale(0.6f)); } -std::wstring ParticleEngine::countParticles() -{ - int l = level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2 ); - return _toString((int)(particles[l][0].size() + particles[l][1].size() + particles[l][2].size())); +std::wstring ParticleEngine::countParticles() { + int l = + level->dimension->id == 0 ? 0 : (level->dimension->id == -1 ? 1 : 2); + return _toString((int)(particles[l][0].size() + + particles[l][1].size() + + particles[l][2].size())); } diff --git a/Minecraft.Client/Rendering/Particles/ParticleEngine.h b/Minecraft.Client/Rendering/Particles/ParticleEngine.h index 0d06d6590..271bd90ca 100644 --- a/Minecraft.Client/Rendering/Particles/ParticleEngine.h +++ b/Minecraft.Client/Rendering/Particles/ParticleEngine.h @@ -1,43 +1,43 @@ #pragma once - class Particle; class Level; class Textures; class Entity; class Random; - -class ParticleEngine -{ +class ParticleEngine { private: - static const int MAX_PARTICLES_PER_LAYER = 200; // 4J - reduced from 4000 - static const int MAX_DRAGON_BREATH_PARTICLES = 1000; + static const int MAX_PARTICLES_PER_LAYER = 200; // 4J - reduced from 4000 + static const int MAX_DRAGON_BREATH_PARTICLES = 1000; public: - static const int MISC_TEXTURE = 0; + 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 DRAGON_BREATH_TEXTURE = 4; // 4J Added + static const int DRAGON_BREATH_TEXTURE = 4; // 4J Added static const int TEXTURE_COUNT = 5; protected: - Level *level; + Level* level; + private: - std::deque > particles[3][TEXTURE_COUNT]; // 4J made two arrays to cope with simultaneous two dimensions - Textures *textures; - Random *random; + std::deque > + particles[3][TEXTURE_COUNT]; // 4J made two arrays to cope with + // simultaneous two dimensions + Textures* textures; + Random* random; public: - ParticleEngine(Level *level, Textures *textures); - ~ParticleEngine(); + ParticleEngine(Level* level, Textures* textures); + ~ParticleEngine(); void add(std::shared_ptr p); void tick(); void render(std::shared_ptr player, float a); void renderLit(std::shared_ptr player, float a); - void setLevel(Level *level); + void setLevel(Level* level); void destroy(int x, int y, int z, int tid, int data); void crack(int x, int y, int z, int face); std::wstring countParticles(); diff --git a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp index f11b6f961..145630db1 100644 --- a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.cpp @@ -5,64 +5,62 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.phys.h" -PlayerCloudParticle::PlayerCloudParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x,y,z,0,0,0) -{ - float scale = 2.5f; - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa; - yd += ya; - zd += za; +PlayerCloudParticle::PlayerCloudParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, 0, 0, 0) { + float scale = 2.5f; + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa; + yd += ya; + zd += za; - rCol = gCol = bCol = 1 - (float) (Math::random() * 0.3f); - size *= 0.75f; - size *= scale; - oSize = size; + rCol = gCol = bCol = 1 - (float)(Math::random() * 0.3f); + size *= 0.75f; + size *= scale; + oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.3)); - lifetime *= scale; - noPhysics = false; + lifetime = (int)(8 / (Math::random() * 0.8 + 0.3)); + lifetime *= scale; + noPhysics = false; } -void PlayerCloudParticle::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; +void PlayerCloudParticle::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; - Particle::render(t, a, xa, ya, za, xa2, za2); + size = oSize * l; + Particle::render(t, a, xa, ya, za, xa2, za2); } -void PlayerCloudParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void PlayerCloudParticle::tick() { + xo = x; + yo = y; + zo = z; - if (age++ >= lifetime) remove(); + if (age++ >= lifetime) remove(); - setMiscTex(7 - age * 8 / lifetime); + setMiscTex(7 - age * 8 / lifetime); - move(xd, yd, zd); - xd *= 0.96f; - yd *= 0.96f; - zd *= 0.96f; - std::shared_ptr p = level->getNearestPlayer(shared_from_this(), 2); - if (p != NULL) - { - if (y > p->bb->y0) - { - y+=(p->bb->y0-y)*0.2; - yd += (p->yd-yd)*0.2; - setPos(x, y, z); - } - } + move(xd, yd, zd); + xd *= 0.96f; + yd *= 0.96f; + zd *= 0.96f; + std::shared_ptr p = level->getNearestPlayer(shared_from_this(), 2); + if (p != NULL) { + if (y > p->bb->y0) { + y += (p->bb->y0 - y) * 0.2; + yd += (p->yd - yd) * 0.2; + setPos(x, y, z); + } + } - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - } + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h index 410020176..7004eca2f 100644 --- a/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h +++ b/Minecraft.Client/Rendering/Particles/PlayerCloudParticle.h @@ -2,14 +2,15 @@ #include "Particle.h" -class PlayerCloudParticle : public Particle -{ +class PlayerCloudParticle : public Particle { private: - float oSize; + float oSize; public: - virtual eINSTANCEOF GetType() { return eType_PLAYERCLOUDPARTICLEPARTICLE; } - PlayerCloudParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - void tick(); + virtual eINSTANCEOF GetType() { return eType_PLAYERCLOUDPARTICLEPARTICLE; } + PlayerCloudParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + void render(Tesselator* t, float a, float xa, float ya, float za, float xa2, + float za2); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp b/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp index e10544ddb..aac218649 100644 --- a/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/RedDustParticle.cpp @@ -2,43 +2,46 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "RedDustParticle.h" -void RedDustParticle::init(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol) -{ +void RedDustParticle::init(Level* level, double x, double y, double z, + float scale, float rCol, float gCol, float bCol) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; - // 4J Stu - If they are all 0 then this particle has been created differently - // If just red is 0 it could be because we have made redstone a completely different colour (eg blue) - if (rCol == 0 && gCol == 0 && bCol == 0) - { + // 4J Stu - If they are all 0 then this particle has been created + // differently If just red is 0 it could be because we have made redstone a + // completely different colour (eg blue) + if (rCol == 0 && gCol == 0 && bCol == 0) { rCol = 1; } - float brr = (float) Math::random() * 0.4f + 0.6f; - this->rCol = ((float) (Math::random() * 0.2f) + 0.8f) * rCol * brr; - this->gCol = ((float) (Math::random() * 0.2f) + 0.8f) * gCol * brr; - this->bCol = ((float) (Math::random() * 0.2f) + 0.8f) * bCol * brr; + float brr = (float)Math::random() * 0.4f + 0.6f; + this->rCol = ((float)(Math::random() * 0.2f) + 0.8f) * rCol * brr; + this->gCol = ((float)(Math::random() * 0.2f) + 0.8f) * gCol * brr; + this->bCol = ((float)(Math::random() * 0.2f) + 0.8f) * bCol * brr; size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); lifetime = (int)(lifetime * scale); noPhysics = false; } -RedDustParticle::RedDustParticle(Level *level, double x, double y, double z, float rCol, float gCol, float bCol) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, 1, rCol, gCol, bCol); +RedDustParticle::RedDustParticle(Level* level, double x, double y, double z, + float rCol, float gCol, float bCol) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, 1, rCol, gCol, bCol); } -RedDustParticle::RedDustParticle(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, scale, rCol, gCol, bCol); +RedDustParticle::RedDustParticle(Level* level, double x, double y, double z, + float scale, float rCol, float gCol, + float bCol) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, scale, rCol, gCol, bCol); } -void RedDustParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void RedDustParticle::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; @@ -47,8 +50,7 @@ void RedDustParticle::render(Tesselator *t, float a, float xa, float ya, float z Particle::render(t, a, xa, ya, za, xa2, za2); } -void RedDustParticle::tick() -{ +void RedDustParticle::tick() { xo = x; yo = y; zo = z; @@ -58,8 +60,7 @@ void RedDustParticle::tick() setMiscTex(7 - age * 8 / lifetime); move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -67,8 +68,7 @@ void RedDustParticle::tick() yd *= 0.96f; zd *= 0.96f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/RedDustParticle.h b/Minecraft.Client/Rendering/Particles/RedDustParticle.h index b1903b6ef..f5a5cc63c 100644 --- a/Minecraft.Client/Rendering/Particles/RedDustParticle.h +++ b/Minecraft.Client/Rendering/Particles/RedDustParticle.h @@ -1,17 +1,21 @@ #pragma once #include "Particle.h" -class RedDustParticle : public Particle -{ +class RedDustParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_REDDUSTPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_REDDUSTPARTICLE; } + private: - void init(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol); // 4J - added + void init(Level* level, double x, double y, double z, float scale, + float rCol, float gCol, float bCol); // 4J - added public: - RedDustParticle(Level *level, double x, double y, double z, float rCol, float gCol, float bCol); + RedDustParticle(Level* level, double x, double y, double z, float rCol, + float gCol, float bCol); float oSize; - RedDustParticle(Level *level, double x, double y, double z, float scale, float rCol, float gCol, float bCol); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + RedDustParticle(Level* level, double x, double y, double z, float scale, + float rCol, float gCol, float bCol); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp b/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp index 15cf3b5d7..58794dbc7 100644 --- a/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SmokeParticle.cpp @@ -2,8 +2,8 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "SmokeParticle.h" -void SmokeParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void SmokeParticle::init(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; @@ -11,38 +11,41 @@ void SmokeParticle::init(Level *level, double x, double y, double z, double xa, yd += ya; zd += za; - //rCol = gCol = bCol = (float) (Math::random() * 0.3f); + // rCol = gCol = bCol = (float) (Math::random() * 0.3f); - float br = Math::random(); - unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Smoke ); - int r = (colour>>16)&0xFF; - int g = (colour>>8)&0xFF; - int b = colour&0xFF; - rCol = (r/255.0f)*br; - gCol = (g/255.0f)*br; - bCol = (b/255.0f)*br; + float br = Math::random(); + unsigned int colour = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Smoke); + int r = (colour >> 16) & 0xFF; + int g = (colour >> 8) & 0xFF; + int b = colour & 0xFF; + rCol = (r / 255.0f) * br; + gCol = (g / 255.0f) * br; + bCol = (b / 255.0f) * br; size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) (lifetime * scale); + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(lifetime * scale); noPhysics = false; } -SmokeParticle::SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, 1); +SmokeParticle::SmokeParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, 1); } -SmokeParticle::SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, 0, 0, 0) -{ - init(level, x, y, z, xa, ya, za, scale); +SmokeParticle::SmokeParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) + : Particle(level, x, y, z, 0, 0, 0) { + init(level, x, y, z, xa, ya, za, scale); } -void SmokeParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void SmokeParticle::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; @@ -51,8 +54,7 @@ void SmokeParticle::render(Tesselator *t, float a, float xa, float ya, float za, Particle::render(t, a, xa, ya, za, xa2, za2); } -void SmokeParticle::tick() -{ +void SmokeParticle::tick() { xo = x; yo = y; zo = z; @@ -63,8 +65,7 @@ void SmokeParticle::tick() yd += 0.004; move(xd, yd, zd); - if (y == yo) - { + if (y == yo) { xd *= 1.1; zd *= 1.1; } @@ -72,8 +73,7 @@ void SmokeParticle::tick() yd *= 0.96f; zd *= 0.96f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/SmokeParticle.h b/Minecraft.Client/Rendering/Particles/SmokeParticle.h index 51ee5e17a..f1cf05da5 100644 --- a/Minecraft.Client/Rendering/Particles/SmokeParticle.h +++ b/Minecraft.Client/Rendering/Particles/SmokeParticle.h @@ -1,18 +1,21 @@ #pragma once #include "Particle.h" -class SmokeParticle : public Particle -{ +class SmokeParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SMOKEPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_SMOKEPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + SmokeParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - SmokeParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + SmokeParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); - }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp index 6e57fc8b5..4dd53aaa3 100644 --- a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.cpp @@ -2,8 +2,8 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "SnowShovelParticle.h" -void SnowShovelParticle::init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) -{ +void SnowShovelParticle::init(Level* level, double x, double y, double z, + double xa, double ya, double za, float scale) { xd *= 0.1f; yd *= 0.1f; zd *= 0.1f; @@ -11,39 +11,41 @@ void SnowShovelParticle::init(Level *level, double x, double y, double z, double yd += ya; zd += za; - rCol = gCol = bCol = 1 - (float) (Math::random() * 0.3f); + rCol = gCol = bCol = 1 - (float)(Math::random() * 0.3f); size *= 0.75f; size *= scale; oSize = size; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - lifetime = (int) ( lifetime * scale ); + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(lifetime * scale); noPhysics = false; } -SnowShovelParticle::SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - init(level, x, y, z, xa, ya, za, 1); +SnowShovelParticle::SnowShovelParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, xa, ya, za) { + init(level, x, y, z, xa, ya, za, 1); } -SnowShovelParticle::SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale) : Particle(level, x, y, z, xa, ya, za) -{ - init(level, x, y, z, xa, ya, za, scale); +SnowShovelParticle::SnowShovelParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za, float scale) + : Particle(level, x, y, z, xa, ya, za) { + init(level, x, y, z, xa, ya, za, scale); } -void SnowShovelParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void SnowShovelParticle::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; Particle::render(t, a, xa, ya, za, xa2, za2); - } -void SnowShovelParticle::tick() -{ +void SnowShovelParticle::tick() { xo = x; yo = y; zo = z; @@ -58,8 +60,7 @@ void SnowShovelParticle::tick() yd *= 0.99f; zd *= 0.99f; - if (onGround) - { + if (onGround) { xd *= 0.7f; zd *= 0.7f; } diff --git a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h index 3570e2467..065d45941 100644 --- a/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h +++ b/Minecraft.Client/Rendering/Particles/SnowShovelParticle.h @@ -1,17 +1,21 @@ #pragma once #include "Particle.h" -class SnowShovelParticle : public Particle -{ +class SnowShovelParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SNOWSHOVELPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_SNOWSHOVELPARTICLE; } + private: - void init(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); // 4J - added + void init(Level* level, double x, double y, double z, double xa, double ya, + double za, float scale); // 4J - added public: - SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + SnowShovelParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); float oSize; - SnowShovelParticle(Level *level, double x, double y, double z, double xa, double ya, double za, float scale); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + SnowShovelParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, float scale); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SpellParticle.cpp b/Minecraft.Client/Rendering/Particles/SpellParticle.cpp index f53228112..661f24d2d 100644 --- a/Minecraft.Client/Rendering/Particles/SpellParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SpellParticle.cpp @@ -2,61 +2,55 @@ #include "../../../Minecraft.World/Util/JavaMath.h" #include "SpellParticle.h" -SpellParticle::SpellParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - yd *= 0.2f; - if (xa == 0 && za == 0) - { - xd *= 0.1f; - zd *= 0.1f; - } +SpellParticle::SpellParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y, z, xa, ya, za) { + yd *= 0.2f; + if (xa == 0 && za == 0) { + xd *= 0.1f; + zd *= 0.1f; + } - size *= 0.75f; + size *= 0.75f; - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); - noPhysics = false; + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); + noPhysics = false; - baseTex = 8 * 16; + baseTex = 8 * 16; } -void SpellParticle::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; +void SpellParticle::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; - Particle::render(t, a, xa, ya, za, xa2, za2); + Particle::render(t, a, xa, ya, za, xa2, za2); } -void SpellParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void SpellParticle::tick() { + xo = x; + yo = y; + zo = z; - if (age++ >= lifetime) remove(); + if (age++ >= lifetime) remove(); - setMiscTex(baseTex + (7 - age * 8 / lifetime)); + setMiscTex(baseTex + (7 - age * 8 / lifetime)); - yd += 0.004; - move(xd, yd, zd); - if (y == yo) - { - xd *= 1.1; - zd *= 1.1; - } - xd *= 0.96f; - yd *= 0.96f; - zd *= 0.96f; + yd += 0.004; + move(xd, yd, zd); + if (y == yo) { + xd *= 1.1; + zd *= 1.1; + } + xd *= 0.96f; + yd *= 0.96f; + zd *= 0.96f; - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - } + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } } -void SpellParticle::setBaseTex(int baseTex) -{ - this->baseTex = baseTex; -} \ No newline at end of file +void SpellParticle::setBaseTex(int baseTex) { this->baseTex = baseTex; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SpellParticle.h b/Minecraft.Client/Rendering/Particles/SpellParticle.h index 212fab0bd..29e6d9721 100644 --- a/Minecraft.Client/Rendering/Particles/SpellParticle.h +++ b/Minecraft.Client/Rendering/Particles/SpellParticle.h @@ -2,17 +2,18 @@ #include "Particle.h" -class SpellParticle : public Particle -{ +class SpellParticle : public Particle { private: - int baseTex; + int baseTex; public: - virtual eINSTANCEOF GetType() { return eTYPE_SPELLPARTICLE; } + virtual eINSTANCEOF GetType() { return eTYPE_SPELLPARTICLE; } - SpellParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + SpellParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); - virtual void tick(); - virtual void setBaseTex(int baseTex); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); + virtual void tick(); + virtual void setBaseTex(int baseTex); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SplashParticle.cpp b/Minecraft.Client/Rendering/Particles/SplashParticle.cpp index b71fa6b72..5704aff6d 100644 --- a/Minecraft.Client/Rendering/Particles/SplashParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SplashParticle.cpp @@ -1,12 +1,12 @@ #include "../../Platform/stdafx.h" #include "SplashParticle.h" -SplashParticle::SplashParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : WaterDropParticle(level, x, y, z) -{ +SplashParticle::SplashParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : WaterDropParticle(level, x, y, z) { gravity = 0.04f; setNextMiscAnimTex(); - if (ya == 0 && (xa != 0 || za != 0)) - { + if (ya == 0 && (xa != 0 || za != 0)) { this->xd = xa; this->yd = ya + 0.1; this->zd = za; diff --git a/Minecraft.Client/Rendering/Particles/SplashParticle.h b/Minecraft.Client/Rendering/Particles/SplashParticle.h index 176b2c872..3bcbccab0 100644 --- a/Minecraft.Client/Rendering/Particles/SplashParticle.h +++ b/Minecraft.Client/Rendering/Particles/SplashParticle.h @@ -1,9 +1,9 @@ #pragma once #include "WaterDropParticle.h" -class SplashParticle : public WaterDropParticle -{ +class SplashParticle : public WaterDropParticle { public: - virtual eINSTANCEOF GetType() { return eType_SPLASHPARTICLE; } - SplashParticle(Level *level, double x, double y, double z, double xa, double ya, double za); + virtual eINSTANCEOF GetType() { return eType_SPLASHPARTICLE; } + SplashParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp b/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp index 81d62e265..924611472 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SuspendedParticle.cpp @@ -6,37 +6,41 @@ #include "../../../Minecraft.World/Util/Mth.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.material.h" -SuspendedParticle::SuspendedParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level,x, y - 2 / 16.0f, z, xa, ya, za) -{ - // 4J-JEV: Set particle colour from colour-table. - unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( eMinecraftColour_Particle_Suspend ); - rCol = ( (col>>16)&0xFF )/255.0f, gCol = ( (col>>8)&0xFF )/255.0, bCol = ( col&0xFF )/255.0; +SuspendedParticle::SuspendedParticle(Level* level, double x, double y, double z, + double xa, double ya, double za) + : Particle(level, x, y - 2 / 16.0f, z, xa, ya, za) { + // 4J-JEV: Set particle colour from colour-table. + unsigned int col = Minecraft::GetInstance()->getColourTable()->getColor( + eMinecraftColour_Particle_Suspend); + rCol = ((col >> 16) & 0xFF) / 255.0f, gCol = ((col >> 8) & 0xFF) / 255.0, + bCol = (col & 0xFF) / 255.0; - //rCol = 0.4f; - //gCol = 0.4f; - //bCol = 0.7f; + // rCol = 0.4f; + // gCol = 0.4f; + // bCol = 0.7f; - setMiscTex(0); - this->setSize(0.01f, 0.01f); + setMiscTex(0); + this->setSize(0.01f, 0.01f); - size = size * (random->nextFloat() * 0.6f + 0.2f); + size = size * (random->nextFloat() * 0.6f + 0.2f); - xd = xa * 0.0f; - yd = ya * 0.0f; - zd = za * 0.0f; + xd = xa * 0.0f; + yd = ya * 0.0f; + zd = za * 0.0f; - lifetime = (int) (16 / (Math::random() * 0.8 + 0.2)); + lifetime = (int)(16 / (Math::random() * 0.8 + 0.2)); } -void SuspendedParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void SuspendedParticle::tick() { + xo = x; + yo = y; + zo = z; - move(xd, yd, zd); + move(xd, yd, zd); - if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != Material::water) remove(); + if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != + Material::water) + remove(); - if (lifetime-- <= 0) remove(); + if (lifetime-- <= 0) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedParticle.h b/Minecraft.Client/Rendering/Particles/SuspendedParticle.h index 8273b423e..d3843cc1c 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedParticle.h +++ b/Minecraft.Client/Rendering/Particles/SuspendedParticle.h @@ -2,10 +2,10 @@ #include "Particle.h" -class SuspendedParticle : public Particle -{ +class SuspendedParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SUSPENDEDPARTICLE; } - SuspendedParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void tick(); + virtual eINSTANCEOF GetType() { return eType_SUSPENDEDPARTICLE; } + SuspendedParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp index 7d719ec32..c25074575 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.cpp @@ -3,35 +3,36 @@ #include "../../../Minecraft.World/Util/Random.h" #include "../../../Minecraft.World/Util/JavaMath.h" -SuspendedTownParticle::SuspendedTownParticle(Level *level, double x, double y, double z, double xa, double ya, double za) : Particle(level, x, y, z, xa, ya, za) -{ - float br = random->nextFloat() * 0.1f + 0.2f; - rCol = br; - gCol = br; - bCol = br; - setMiscTex(0); - this->setSize(0.02f, 0.02f); +SuspendedTownParticle::SuspendedTownParticle(Level* level, double x, double y, + double z, double xa, double ya, + double za) + : Particle(level, x, y, z, xa, ya, za) { + float br = random->nextFloat() * 0.1f + 0.2f; + rCol = br; + gCol = br; + bCol = br; + setMiscTex(0); + this->setSize(0.02f, 0.02f); - size = size * (random->nextFloat() * 0.6f + 0.5f); + size = size * (random->nextFloat() * 0.6f + 0.5f); - xd *= 0.02f; - yd *= 0.02f; - zd *= 0.02f; + xd *= 0.02f; + yd *= 0.02f; + zd *= 0.02f; - lifetime = (int) (20 / (Math::random() * 0.8 + 0.2)); - this->noPhysics = true; + lifetime = (int)(20 / (Math::random() * 0.8 + 0.2)); + this->noPhysics = true; } -void SuspendedTownParticle::tick() -{ - xo = x; - yo = y; - zo = z; +void SuspendedTownParticle::tick() { + xo = x; + yo = y; + zo = z; - move(xd, yd, zd); - xd *= 0.99; - yd *= 0.99; - zd *= 0.99; + move(xd, yd, zd); + xd *= 0.99; + yd *= 0.99; + zd *= 0.99; - if (lifetime-- <= 0) remove(); + if (lifetime-- <= 0) remove(); } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h index 1d5318413..d443456ec 100644 --- a/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h +++ b/Minecraft.Client/Rendering/Particles/SuspendedTownParticle.h @@ -2,10 +2,10 @@ #include "Particle.h" -class SuspendedTownParticle : public Particle -{ +class SuspendedTownParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_SUSPENDEDTOWNPARTICLE; } - SuspendedTownParticle(Level *level, double x, double y, double z, double xa, double ya, double za); - void tick(); + virtual eINSTANCEOF GetType() { return eType_SUSPENDEDTOWNPARTICLE; } + SuspendedTownParticle(Level* level, double x, double y, double z, double xa, + double ya, double za); + void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp index 7f6318fe9..0272da4b9 100644 --- a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.cpp @@ -5,76 +5,70 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../../Minecraft.World/Util/Mth.h" -TakeAnimationParticle::TakeAnimationParticle(Level *level, std::shared_ptr item, std::shared_ptr target, float yOffs) : Particle(level, item->x, item->y, item->z, item->xd, item->yd, item->zd) -{ - // 4J - added initialisers - life = 0; - lifeTime = 0; +TakeAnimationParticle::TakeAnimationParticle(Level* level, + std::shared_ptr item, + std::shared_ptr target, + float yOffs) + : Particle(level, item->x, item->y, item->z, item->xd, item->yd, item->zd) { + // 4J - added initialisers + life = 0; + lifeTime = 0; this->item = item; this->target = target; lifeTime = 3; this->yOffs = yOffs; - } -TakeAnimationParticle::~TakeAnimationParticle() -{ -} +TakeAnimationParticle::~TakeAnimationParticle() {} -void TakeAnimationParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void TakeAnimationParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float time = (life + a) / lifeTime; - time = time*time; + time = time * time; double xo = item->x; double yo = item->y; double zo = item->z; double xt = target->xOld + (target->x - target->xOld) * a; - double yt = target->yOld + (target->y - target->yOld) * a+yOffs; + double yt = target->yOld + (target->y - target->yOld) * a + yOffs; double zt = target->zOld + (target->z - target->zOld) * a; double xx = xo + (xt - xo) * time; double yy = yo + (yt - yo) * time; double zz = zo + (zt - zo) * time; - + int xTile = Mth::floor(xx); int yTile = Mth::floor(yy + heightOffset / 2.0f); int zTile = Mth::floor(zz); - // 4J - change brought forward from 1.8.2 - if (SharedConstants::TEXTURE_LIGHTING) - { + // 4J - change brought forward from 1.8.2 + if (SharedConstants::TEXTURE_LIGHTING) { int col = getLightColor(a); - int u = col%65536; - int v = col/65536; - glMultiTexCoord2f(GL_TEXTURE1, u/1.0f, v/1.0f); + int u = col % 65536; + int v = col / 65536; + glMultiTexCoord2f(GL_TEXTURE1, u / 1.0f, v / 1.0f); glColor4f(1, 1, 1, 1); + } else { + float br = level->getBrightness(xTile, yTile, zTile); + glColor4f(br, br, br, 1); } - else - { - float br = level->getBrightness(xTile, yTile, zTile); - glColor4f(br, br, br, 1); - } - - xx-=xOff; - yy-=yOff; - zz-=zOff; - - - EntityRenderDispatcher::instance->render(item, (float)xx, (float)yy, (float)zz, item->yRot, a); + xx -= xOff; + yy -= yOff; + zz -= zOff; + + EntityRenderDispatcher::instance->render(item, (float)xx, (float)yy, + (float)zz, item->yRot, a); } -void TakeAnimationParticle::tick() -{ +void TakeAnimationParticle::tick() { life++; if (life == lifeTime) remove(); } -int TakeAnimationParticle::getParticleTexture() -{ - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; +int TakeAnimationParticle::getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; } diff --git a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h index 33c4535f3..d1943b536 100644 --- a/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h +++ b/Minecraft.Client/Rendering/Particles/TakeAnimationParticle.h @@ -2,10 +2,10 @@ #include "Particle.h" class Entity; -class TakeAnimationParticle : public Particle -{ +class TakeAnimationParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_TAKEANIMATIONPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_TAKEANIMATIONPARTICLE; } + private: std::shared_ptr item; std::shared_ptr target; @@ -14,9 +14,11 @@ private: float yOffs; public: - TakeAnimationParticle(Level *level, std::shared_ptr item, std::shared_ptr target, float yOffs); - ~TakeAnimationParticle(); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + TakeAnimationParticle(Level* level, std::shared_ptr item, + std::shared_ptr target, float yOffs); + ~TakeAnimationParticle(); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); virtual void tick(); virtual int getParticleTexture(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp b/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp index 8cac8d642..3dcff7e57 100644 --- a/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/TerrainParticle.cpp @@ -5,71 +5,84 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.h" -TerrainParticle::TerrainParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Tile *tile, int face, int data, Textures *textures) : Particle(level, x, y, z, xa, ya, za) -{ +TerrainParticle::TerrainParticle(Level* level, double x, double y, double z, + double xa, double ya, double za, Tile* tile, + int face, int data, Textures* textures) + : Particle(level, x, y, z, xa, ya, za) { this->tile = tile; - this->setTex(textures, tile->getTexture(0, data)); // 4J - change brought forward from 1.8.2 to fix purple particles on door damage + this->setTex( + textures, + tile->getTexture(0, data)); // 4J - change brought forward from 1.8.2 + // to fix purple particles on door damage this->gravity = tile->gravity; rCol = gCol = bCol = 0.6f; size /= 2; } -std::shared_ptr TerrainParticle::init(int x, int y, int z, int data) // 4J - added data parameter +std::shared_ptr TerrainParticle::init( + int x, int y, int z, int data) // 4J - added data parameter { - if (tile == Tile::grass) return std::dynamic_pointer_cast( shared_from_this() ); - int col = tile->getColor(level, x, y, z, data); // 4J - added data parameter + if (tile == Tile::grass) + return std::dynamic_pointer_cast(shared_from_this()); + int col = + tile->getColor(level, x, y, z, data); // 4J - added data parameter rCol *= ((col >> 16) & 0xff) / 255.0f; gCol *= ((col >> 8) & 0xff) / 255.0f; bCol *= ((col) & 0xff) / 255.0f; - return std::dynamic_pointer_cast( shared_from_this() ); + return std::dynamic_pointer_cast(shared_from_this()); } -std::shared_ptr TerrainParticle::init(int data) -{ - if (tile == Tile::grass) return std::dynamic_pointer_cast( shared_from_this() ); - int col = tile->getColor(data); - rCol *= ((col >> 16) & 0xff) / 255.0f; - gCol *= ((col >> 8) & 0xff) / 255.0f; - bCol *= ((col) & 0xff) / 255.0f; - return std::dynamic_pointer_cast( shared_from_this() ); +std::shared_ptr TerrainParticle::init(int data) { + if (tile == Tile::grass) + return std::dynamic_pointer_cast(shared_from_this()); + int col = tile->getColor(data); + rCol *= ((col >> 16) & 0xff) / 255.0f; + gCol *= ((col >> 8) & 0xff) / 255.0f; + bCol *= ((col) & 0xff) / 255.0f; + return std::dynamic_pointer_cast(shared_from_this()); } -int TerrainParticle::getParticleTexture() -{ - return ParticleEngine::TERRAIN_TEXTURE; +int TerrainParticle::getParticleTexture() { + return ParticleEngine::TERRAIN_TEXTURE; } -void TerrainParticle::render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2) -{ +void TerrainParticle::render(Tesselator* t, float a, float xa, float ya, + float za, float xa2, float za2) { float u0 = (texX + uo / 4.0f) / 16.0f; float u1 = u0 + 0.999f / 16.0f / 4; float v0 = (texY + vo / 4.0f) / 16.0f; float v1 = v0 + 0.999f / 16.0f / 4; float r = 0.1f * size; - if (tex != NULL) - { - u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); - v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); - } + if (tex != NULL) { + u0 = tex->getU((uo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + u1 = tex->getU(((uo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v0 = tex->getV((vo / 4.0f) * SharedConstants::WORLD_RESOLUTION); + v1 = tex->getV(((vo + 1) / 4.0f) * SharedConstants::WORLD_RESOLUTION); + } - 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 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); - // 4J - don't render terrain particles that are less than a metre away, to try and avoid large particles that are causing us problems with - // photosensitivity testing - float distSq = (x*x + y*y + z*z); - if( distSq < 1.0f ) return; + // 4J - don't render terrain particles that are less than a metre away, to + // try and avoid large particles that are causing us problems with + // photosensitivity testing + float distSq = (x * x + y * y + z * z); + if (distSq < 1.0f) return; - float br = SharedConstants::TEXTURE_LIGHTING ? 1.0f : getBrightness(a); // 4J - change brought forward from 1.8.2 + float br = + SharedConstants::TEXTURE_LIGHTING + ? 1.0f + : getBrightness(a); // 4J - change brought forward from 1.8.2 t->color(br * rCol, br * gCol, br * bCol); - t->vertexUV((float)(x - xa * r - xa2 * r), (float)( y - ya * r), (float)( z - za * r - za2 * r), (float)( u0), (float)( v1)); - t->vertexUV((float)(x - xa * r + xa2 * r), (float)( y + ya * r), (float)( z - za * r + za2 * r), (float)( u0), (float)( v0)); - t->vertexUV((float)(x + xa * r + xa2 * r), (float)( y + ya * r), (float)( z + za * r + za2 * r), (float)( u1), (float)( v0)); - t->vertexUV((float)(x + xa * r - xa2 * r), (float)( y - ya * r), (float)( z + za * r - za2 * r), (float)( u1), (float)( v1)); - + t->vertexUV((float)(x - xa * r - xa2 * r), (float)(y - ya * r), + (float)(z - za * r - za2 * r), (float)(u0), (float)(v1)); + t->vertexUV((float)(x - xa * r + xa2 * r), (float)(y + ya * r), + (float)(z - za * r + za2 * r), (float)(u0), (float)(v0)); + t->vertexUV((float)(x + xa * r + xa2 * r), (float)(y + ya * r), + (float)(z + za * r + za2 * r), (float)(u1), (float)(v0)); + t->vertexUV((float)(x + xa * r - xa2 * r), (float)(y - ya * r), + (float)(z + za * r - za2 * r), (float)(u1), (float)(v1)); } diff --git a/Minecraft.Client/Rendering/Particles/TerrainParticle.h b/Minecraft.Client/Rendering/Particles/TerrainParticle.h index df9ca42fe..28db9b2d8 100644 --- a/Minecraft.Client/Rendering/Particles/TerrainParticle.h +++ b/Minecraft.Client/Rendering/Particles/TerrainParticle.h @@ -2,17 +2,21 @@ #include "Particle.h" class Tile; -class TerrainParticle : public Particle -{ +class TerrainParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_TERRAINPARTICLE; } + virtual eINSTANCEOF GetType() { return eType_TERRAINPARTICLE; } + private: - Tile *tile; + Tile* tile; public: - TerrainParticle(Level *level, double x, double y, double z, double xa, double ya, double za, Tile *tile, int face, int data, Textures *textures); - std::shared_ptr init(int x, int y, int z, int data); // 4J - added data parameter - std::shared_ptr init(int data); + TerrainParticle(Level* level, double x, double y, double z, double xa, + double ya, double za, Tile* tile, int face, int data, + Textures* textures); + std::shared_ptr init( + int x, int y, int z, int data); // 4J - added data parameter + std::shared_ptr init(int data); virtual int getParticleTexture(); - virtual void render(Tesselator *t, float a, float xa, float ya, float za, float xa2, float za2); + virtual void render(Tesselator* t, float a, float xa, float ya, float za, + float xa2, float za2); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp b/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp index 36c14c98c..150dca852 100644 --- a/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp +++ b/Minecraft.Client/Rendering/Particles/WaterDropParticle.cpp @@ -5,25 +5,25 @@ #include "../../../Minecraft.World/Headers/net.minecraft.world.level.material.h" #include "../../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" -WaterDropParticle::WaterDropParticle(Level *level, double x, double y, double z) : Particle(level, x, y, z, 0, 0, 0) -{ +WaterDropParticle::WaterDropParticle(Level* level, double x, double y, double z) + : Particle(level, x, y, z, 0, 0, 0) { xd *= 0.3f; - yd = (float) Math::random() * 0.2f + 0.1f; + yd = (float)Math::random() * 0.2f + 0.1f; zd *= 0.3f; rCol = 1.0f; gCol = 1.0f; bCol = 1.0f; - setMiscTex(16+3+random->nextInt(4)); + setMiscTex(16 + 3 + random->nextInt(4)); this->setSize(0.01f, 0.01f); gravity = 0.06f; - noPhysics = true; // 4J - optimisation - do we really need collision on these? its really slow... - lifetime = (int) (8 / (Math::random() * 0.8 + 0.2)); + noPhysics = true; // 4J - optimisation - do we really need collision on + // these? its really slow... + lifetime = (int)(8 / (Math::random() * 0.8 + 0.2)); } -void WaterDropParticle::tick() -{ +void WaterDropParticle::tick() { xo = x; yo = y; zo = z; @@ -36,19 +36,19 @@ void WaterDropParticle::tick() if (lifetime-- <= 0) remove(); - if (onGround) - { + if (onGround) { if (Math::random() < 0.5) remove(); xd *= 0.7f; zd *= 0.7f; } - Material *m = level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); - if (m->isLiquid() || m->isSolid()) - { - double y0 = Mth::floor(y) + 1 - LiquidTile::getHeight(level->getData(Mth::floor(x), Mth::floor(y), Mth::floor(z))); - if (y < y0) - { + Material* m = + level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)); + if (m->isLiquid() || m->isSolid()) { + double y0 = Mth::floor(y) + 1 - + LiquidTile::getHeight(level->getData( + Mth::floor(x), Mth::floor(y), Mth::floor(z))); + if (y < y0) { remove(); } } diff --git a/Minecraft.Client/Rendering/Particles/WaterDropParticle.h b/Minecraft.Client/Rendering/Particles/WaterDropParticle.h index 0822cef8a..a1e501a5c 100644 --- a/Minecraft.Client/Rendering/Particles/WaterDropParticle.h +++ b/Minecraft.Client/Rendering/Particles/WaterDropParticle.h @@ -1,10 +1,9 @@ #pragma once #include "Particle.h" -class WaterDropParticle : public Particle -{ +class WaterDropParticle : public Particle { public: - virtual eINSTANCEOF GetType() { return eType_WATERDROPPARTICLE; } - WaterDropParticle(Level *level, double x, double y, double z) ; + virtual eINSTANCEOF GetType() { return eType_WATERDROPPARTICLE; } + WaterDropParticle(Level* level, double x, double y, double z); virtual void tick(); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Polygon.cpp b/Minecraft.Client/Rendering/Polygon.cpp index 73c7cca83..28c37260e 100644 --- a/Minecraft.Client/Rendering/Polygon.cpp +++ b/Minecraft.Client/Rendering/Polygon.cpp @@ -2,8 +2,7 @@ #include "Polygon.h" // 4J added for common init code -void _Polygon::_init(VertexArray vertices) -{ +void _Polygon::_init(VertexArray vertices) { vertexCount = 0; _flipNormal = false; @@ -11,18 +10,15 @@ void _Polygon::_init(VertexArray vertices) vertexCount = vertices.length; } -_Polygon::_Polygon(VertexArray vertices) -{ - _init(vertices); -} +_Polygon::_Polygon(VertexArray vertices) { _init(vertices); } -_Polygon::_Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, float xTexSize, float yTexSize) -{ - _init(vertices); +_Polygon::_Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, + float xTexSize, float yTexSize) { + _init(vertices); - // 4J - added - don't assume that u1 > u0, v1 > v0 - float us = ( u1 > u0 ) ? ( 0.1f / xTexSize ) : ( -0.1f / xTexSize ); - float vs = ( v1 > v0 ) ? ( 0.1f / yTexSize ) : ( -0.1f / yTexSize ); + // 4J - added - don't assume that u1 > u0, v1 > v0 + float us = (u1 > u0) ? (0.1f / xTexSize) : (-0.1f / xTexSize); + float vs = (v1 > v0) ? (0.1f / yTexSize) : (-0.1f / yTexSize); vertices[0] = vertices[0]->remap(u1 / xTexSize - us, v0 / yTexSize + vs); vertices[1] = vertices[1]->remap(u0 / xTexSize + us, v0 / yTexSize + vs); @@ -30,8 +26,8 @@ _Polygon::_Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, float x vertices[3] = vertices[3]->remap(u1 / xTexSize - us, v1 / yTexSize - vs); } -_Polygon::_Polygon(VertexArray vertices, float u0, float v0, float u1, float v1) -{ +_Polygon::_Polygon(VertexArray vertices, float u0, float v0, float u1, + float v1) { _init(vertices); vertices[0] = vertices[0]->remap(u1, v0); @@ -40,41 +36,35 @@ _Polygon::_Polygon(VertexArray vertices, float u0, float v0, float u1, float v1) vertices[3] = vertices[3]->remap(u1, v1); } -void _Polygon::mirror() -{ +void _Polygon::mirror() { VertexArray newVertices = VertexArray(vertices.length); for (unsigned int i = 0; i < vertices.length; i++) newVertices[i] = vertices[vertices.length - i - 1]; - delete [] vertices.data; + delete[] vertices.data; vertices = newVertices; } -void _Polygon::render(Tesselator *t, float scale) -{ - Vec3 *v0 = vertices[1]->pos->vectorTo(vertices[0]->pos); - Vec3 *v1 = vertices[1]->pos->vectorTo(vertices[2]->pos); - Vec3 *n = v1->cross(v0)->normalize(); - +void _Polygon::render(Tesselator* t, float scale) { + Vec3* v0 = vertices[1]->pos->vectorTo(vertices[0]->pos); + Vec3* v1 = vertices[1]->pos->vectorTo(vertices[2]->pos); + Vec3* n = v1->cross(v0)->normalize(); + t->begin(); - if (_flipNormal) - { + if (_flipNormal) { t->normal(-(float)n->x, -(float)n->y, -(float)n->z); - } - else - { + } else { t->normal((float)n->x, (float)n->y, (float)n->z); } - for (int i = 0; i < 4; i++) - { - Vertex *v = vertices[i]; - t->vertexUV((float)(v->pos->x * scale), (float)( v->pos->y * scale), (float)( v->pos->z * scale), (float)( v->u), (float)( v->v)); + for (int i = 0; i < 4; i++) { + Vertex* v = vertices[i]; + t->vertexUV((float)(v->pos->x * scale), (float)(v->pos->y * scale), + (float)(v->pos->z * scale), (float)(v->u), (float)(v->v)); } t->end(); } -_Polygon *_Polygon::flipNormal() -{ +_Polygon* _Polygon::flipNormal() { _flipNormal = true; return this; } \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Polygon.h b/Minecraft.Client/Rendering/Polygon.h index e8c71f8b0..38c6e9094 100644 --- a/Minecraft.Client/Rendering/Polygon.h +++ b/Minecraft.Client/Rendering/Polygon.h @@ -3,20 +3,21 @@ #include "Tesselator.h" #include "../../Minecraft.World/Util/ArrayWithLength.h" -class _Polygon -{ +class _Polygon { public: - VertexArray vertices; + VertexArray vertices; int vertexCount; + private: - bool _flipNormal; + bool _flipNormal; public: - void _init(VertexArray vertices); // 4J added for common init code - _Polygon(VertexArray vertices); - _Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, float xTexSize, float yTexSize); + void _init(VertexArray vertices); // 4J added for common init code + _Polygon(VertexArray vertices); + _Polygon(VertexArray vertices, int u0, int v0, int u1, int v1, + float xTexSize, float yTexSize); _Polygon(VertexArray vertices, float u0, float v0, float u1, float v1); void mirror(); - void render(Tesselator *t, float scale); - _Polygon *flipNormal(); + void render(Tesselator* t, float scale); + _Polygon* flipNormal(); }; diff --git a/Minecraft.Client/Rendering/Tesselator.cpp b/Minecraft.Client/Rendering/Tesselator.cpp index 517c8a61d..acc2ce854 100644 --- a/Minecraft.Client/Rendering/Tesselator.cpp +++ b/Minecraft.Client/Rendering/Tesselator.cpp @@ -26,176 +26,197 @@ int normal; */ unsigned int Tesselator::tlsIdx = TlsAlloc(); -Tesselator *Tesselator::getInstance() -{ - return (Tesselator *)TlsGetValue(tlsIdx); +Tesselator* Tesselator::getInstance() { + return (Tesselator*)TlsGetValue(tlsIdx); } -void Tesselator::CreateNewThreadStorage(int bytes) -{ - Tesselator *instance = new Tesselator(bytes/4); - TlsSetValue(tlsIdx, instance); +void Tesselator::CreateNewThreadStorage(int bytes) { + Tesselator* instance = new Tesselator(bytes / 4); + TlsSetValue(tlsIdx, instance); } // she tessalate my vertices till i render -Tesselator::Tesselator(int size) -{ - // 4J - this block of things moved to constructor from general initialisations round Java class - vertices = 0; - hasColor = false; - hasTexture = false; - hasTexture2 = false; - hasNormal = false; - p = 0; - count = 0; - _noColor = false; - tesselating = false; - vboMode = false; - vboId = 0; - vboCounts = 10; +Tesselator::Tesselator(int size) { + // 4J - this block of things moved to constructor from general + // initialisations round Java class + vertices = 0; + hasColor = false; + hasTexture = false; + hasTexture2 = false; + hasNormal = false; + p = 0; + count = 0; + _noColor = false; + tesselating = false; + vboMode = false; + vboId = 0; + vboCounts = 10; - // 4J - adding these things to constructor just to be sure that they are initialised with something - u = v = 0; - col = 0; - mode = 0; - xo = yo = zo = 0; - xoo = yoo = zoo = 0; // 4J added - _normal = 0; + // 4J - adding these things to constructor just to be sure that they are + // initialised with something + u = v = 0; + col = 0; + mode = 0; + xo = yo = zo = 0; + xoo = yoo = zoo = 0; // 4J added + _normal = 0; - useCompactFormat360 = false; // 4J added - mipmapEnable = true; // 4J added - useProjectedTexturePixelShader = false; // 4J added + useCompactFormat360 = false; // 4J added + mipmapEnable = true; // 4J added + useProjectedTexturePixelShader = false; // 4J added - this->size = size; + this->size = size; - _array = new intArray(size); + _array = new intArray(size); - vboMode = USE_VBO; // 4J removed - && GLContext.getCapabilities().GL_ARB_vertex_buffer_object; - if (vboMode) - { - vboIds = MemoryTracker::createIntBuffer(vboCounts); - ARBVertexBufferObject::glGenBuffersARB(vboIds); - } + vboMode = + USE_VBO; // 4J removed - && + // GLContext.getCapabilities().GL_ARB_vertex_buffer_object; + if (vboMode) { + vboIds = MemoryTracker::createIntBuffer(vboCounts); + ARBVertexBufferObject::glGenBuffersARB(vboIds); + } #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha - alphaCutOutEnabled = false; + // AP - alpha cut out is expensive on vita. Use this to defer primitives + // that use icons with alpha + alphaCutOutEnabled = false; - // this is the cut out enabled vertex array - _array2 = new intArray(size); + // this is the cut out enabled vertex array + _array2 = new intArray(size); vertices2 = 0; p2 = 0; #endif } -Tesselator *Tesselator::getUniqueInstance(int size) -{ +Tesselator* Tesselator::getUniqueInstance(int size) { return new Tesselator(size); } -void Tesselator::end() -{ -// if (!tesselating) throw new IllegalStateException("Not tesselating!"); // 4J - removed +void Tesselator::end() { + // if (!tesselating) throw new IllegalStateException("Not tesselating!"); + // // 4J - removed tesselating = false; #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Check both counts for valid vertices - if( vertices > 0 || vertices2 > 0 ) + // AP - alpha cut out is expensive on vita. Check both counts for valid + // vertices + if (vertices > 0 || vertices2 > 0) #else if (vertices > 0) #endif - { - // 4J - a lot of stuff taken out here for fiddling round with enable client states etc. - // that don't matter for our renderer - if (!hasColor) - { - // 4J - TEMP put in fixed vertex colors if we don't have any, until we have a shader that can cope without them - // Use 0x00000000 (not 0xffffffff) so DrawVertices skips glColor for these vertices, - // letting any caller-set GL colour (e.g. sky colour) pass through unmodified. - unsigned int *pColData = (unsigned int *)_array->data; - pColData += 5; - for( int i = 0; i < vertices; i++ ) - { - *pColData = 0x00000000; - pColData += 8; - } + { + // 4J - a lot of stuff taken out here for fiddling round with enable + // client states etc. that don't matter for our renderer + if (!hasColor) { + // 4J - TEMP put in fixed vertex colors if we don't have any, until + // we have a shader that can cope without them Use 0x00000000 (not + // 0xffffffff) so DrawVertices skips glColor for these vertices, + // letting any caller-set GL colour (e.g. sky colour) pass through + // unmodified. + unsigned int* pColData = (unsigned int*)_array->data; + pColData += 5; + for (int i = 0; i < vertices; i++) { + *pColData = 0x00000000; + pColData += 8; + } #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Check both counts for valid vertices - pColData = (unsigned int *)_array2->data; - pColData += 5; - for( int i = 0; i < vertices2; i++ ) - { - *pColData = 0xffffffff; - pColData += 8; - } -#endif - } - if (mode == GL_QUADS && TRIANGLE_MODE) - { - // glDrawArrays(GL_TRIANGLES, 0, vertices); // 4J - changed for xbox -#ifdef _XBOX - RenderManager.DrawVertices(D3DPT_TRIANGLELIST,vertices,_array->data, - useCompactFormat360?C4JRender::VERTEX_TYPE_PS3_TS2_CS1:C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, - useProjectedTexturePixelShader?C4JRender::PIXEL_SHADER_TYPE_PROJECTION:C4JRender::PIXEL_SHADER_TYPE_STANDARD); -#else - RenderManager.DrawVertices(C4JRender::PRIMITIVE_TYPE_TRIANGLE_LIST,vertices,_array->data, - useCompactFormat360?C4JRender::VERTEX_TYPE_COMPRESSED:C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, - useProjectedTexturePixelShader?C4JRender::PIXEL_SHADER_TYPE_PROJECTION:C4JRender::PIXEL_SHADER_TYPE_STANDARD); + // AP - alpha cut out is expensive on vita. Check both counts for + // valid vertices + pColData = (unsigned int*)_array2->data; + pColData += 5; + for (int i = 0; i < vertices2; i++) { + *pColData = 0xffffffff; + pColData += 8; + } #endif } - else - { -// glDrawArrays(mode, 0, vertices); // 4J - changed for xbox - // For compact vertices, the vertexCount has to be calculated from the amount of data written, as - // we insert extra fake vertices to encode supplementary data for more awkward quads that have non - // axis aligned UVs (eg flowing lava/water) + if (mode == GL_QUADS && TRIANGLE_MODE) { + // glDrawArrays(GL_TRIANGLES, 0, vertices); // 4J - changed for xbox #ifdef _XBOX - int vertexCount = vertices; - if( useCompactFormat360 ) - { - vertexCount = p / 2; - RenderManager.DrawVertices((D3DPRIMITIVETYPE)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PS3_TS2_CS1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - else - { - if( useProjectedTexturePixelShader ) - { - RenderManager.DrawVertices((D3DPRIMITIVETYPE)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, C4JRender::PIXEL_SHADER_TYPE_PROJECTION); - } - else - { - RenderManager.DrawVertices((D3DPRIMITIVETYPE)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - } + RenderManager.DrawVertices( + D3DPT_TRIANGLELIST, vertices, _array->data, + useCompactFormat360 + ? C4JRender::VERTEX_TYPE_PS3_TS2_CS1 + : C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + useProjectedTexturePixelShader + ? C4JRender::PIXEL_SHADER_TYPE_PROJECTION + : C4JRender::PIXEL_SHADER_TYPE_STANDARD); #else - int vertexCount = vertices; - if( useCompactFormat360 ) - { + RenderManager.DrawVertices( + C4JRender::PRIMITIVE_TYPE_TRIANGLE_LIST, vertices, _array->data, + useCompactFormat360 + ? C4JRender::VERTEX_TYPE_COMPRESSED + : C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + useProjectedTexturePixelShader + ? C4JRender::PIXEL_SHADER_TYPE_PROJECTION + : C4JRender::PIXEL_SHADER_TYPE_STANDARD); +#endif + } else { +// glDrawArrays(mode, 0, vertices); // 4J - changed for xbox +// For compact vertices, the vertexCount has to be calculated from the amount of +// data written, as we insert extra fake vertices to encode supplementary data +// for more awkward quads that have non axis aligned UVs (eg flowing lava/water) +#ifdef _XBOX + int vertexCount = vertices; + if (useCompactFormat360) { + vertexCount = p / 2; + RenderManager.DrawVertices( + (D3DPRIMITIVETYPE)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_PS3_TS2_CS1, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } else { + if (useProjectedTexturePixelShader) { + RenderManager.DrawVertices( + (D3DPRIMITIVETYPE)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, + C4JRender::PIXEL_SHADER_TYPE_PROJECTION); + } else { + RenderManager.DrawVertices( + (D3DPRIMITIVETYPE)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } + } +#else + int vertexCount = vertices; + if (useCompactFormat360) { #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Render non-cut out stuff first then send the cut out stuff - if( vertexCount ) - { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - if( vertices2 ) - { - RenderManager.DrawVerticesCutOut((C4JRender::ePrimitiveType)mode,vertices2,_array2->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } + // AP - alpha cut out is expensive on vita. Render non-cut out + // stuff first then send the cut out stuff + if (vertexCount) { + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, + _array->data, C4JRender::VERTEX_TYPE_COMPRESSED, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } + if (vertices2) { + RenderManager.DrawVerticesCutOut( + (C4JRender::ePrimitiveType)mode, vertices2, + _array2->data, C4JRender::VERTEX_TYPE_COMPRESSED, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } #else - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_COMPRESSED, C4JRender::PIXEL_SHADER_TYPE_STANDARD); + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, _array->data, + C4JRender::VERTEX_TYPE_COMPRESSED, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); #endif - } - else - { - if( useProjectedTexturePixelShader ) - { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, C4JRender::PIXEL_SHADER_TYPE_PROJECTION); - } - else - { - RenderManager.DrawVertices((C4JRender::ePrimitiveType)mode,vertexCount,_array->data,C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, C4JRender::PIXEL_SHADER_TYPE_STANDARD); - } - } + } else { + if (useProjectedTexturePixelShader) { + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, + _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, + C4JRender::PIXEL_SHADER_TYPE_PROJECTION); + } else { + RenderManager.DrawVertices( + (C4JRender::ePrimitiveType)mode, vertexCount, + _array->data, + C4JRender::VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, + C4JRender::PIXEL_SHADER_TYPE_STANDARD); + } + } #endif } glDisableClientState(GL_VERTEX_ARRAY); @@ -207,71 +228,58 @@ void Tesselator::end() clear(); } -void Tesselator::clear() -{ +void Tesselator::clear() { vertices = 0; p = 0; count = 0; #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Clear the cut out variables + // AP - alpha cut out is expensive on vita. Clear the cut out variables vertices2 = 0; p2 = 0; #endif } -void Tesselator::begin() -{ +void Tesselator::begin() { begin(GL_QUADS); - bounds.reset(); // 4J MGH - added -} - -void Tesselator::useProjectedTexture(bool enable) -{ - useProjectedTexturePixelShader = enable; + bounds.reset(); // 4J MGH - added } -void Tesselator::useCompactVertices(bool enable) -{ - useCompactFormat360 = enable; +void Tesselator::useProjectedTexture(bool enable) { + useProjectedTexturePixelShader = enable; } -bool Tesselator::getCompactVertices() -{ - return useCompactFormat360; +void Tesselator::useCompactVertices(bool enable) { + useCompactFormat360 = enable; } -bool Tesselator::setMipmapEnable(bool enable) -{ - bool prev = mipmapEnable; - mipmapEnable = enable; - return prev; +bool Tesselator::getCompactVertices() { return useCompactFormat360; } + +bool Tesselator::setMipmapEnable(bool enable) { + bool prev = mipmapEnable; + mipmapEnable = enable; + return prev; } #ifdef __PSVITA__ -// AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha -void Tesselator::setAlphaCutOut(bool enable) -{ - alphaCutOutEnabled = enable; -} +// AP - alpha cut out is expensive on vita. Use this to defer primitives that +// use icons with alpha +void Tesselator::setAlphaCutOut(bool enable) { alphaCutOutEnabled = enable; } // AP - was any cut out geometry added since the last call to Clear -bool Tesselator::getCutOutFound() -{ - if( vertices2 ) - return true; +bool Tesselator::getCutOutFound() { + if (vertices2) return true; - return false; + return false; } #endif -void Tesselator::begin(int mode) -{ - /* // 4J - removed - if (tesselating) { - throw new IllegalStateException("Already tesselating!"); - } */ +void Tesselator::begin(int mode) { + /* // 4J - removed +if (tesselating) { + throw new IllegalStateException("Already tesselating!"); +} */ tesselating = true; clear(); @@ -279,40 +287,32 @@ void Tesselator::begin(int mode) hasNormal = false; hasColor = false; hasTexture = false; - hasTexture2 = false; + hasTexture2 = false; _noColor = false; } -void Tesselator::tex(float u, float v) -{ +void Tesselator::tex(float u, float v) { hasTexture = true; this->u = u; this->v = v; } -void Tesselator::tex2(int tex2) -{ +void Tesselator::tex2(int tex2) { hasTexture2 = true; - this->_tex2 = tex2; + this->_tex2 = tex2; } -void Tesselator::color(float r, float g, float b) -{ - color((int) (r * 255), (int) (g * 255), (int) (b * 255)); +void Tesselator::color(float r, float g, float b) { + color((int)(r * 255), (int)(g * 255), (int)(b * 255)); } -void Tesselator::color(float r, float g, float b, float a) -{ - color((int) (r * 255), (int) (g * 255), (int) (b * 255), (int) (a * 255)); +void Tesselator::color(float r, float g, float b, float a) { + color((int)(r * 255), (int)(g * 255), (int)(b * 255), (int)(a * 255)); } -void Tesselator::color(int r, int g, int b) -{ - color(r, g, b, 255); -} +void Tesselator::color(int r, int g, int b) { color(r, g, b, 255); } -void Tesselator::color(int r, int g, int b, int a) -{ +void Tesselator::color(int r, int g, int b, int a) { if (_noColor) return; if (r > 255) r = 255; @@ -325,48 +325,52 @@ void Tesselator::color(int r, int g, int b, int a) if (a < 0) a = 0; hasColor = true; - // 4J - removed little-endian option + // 4J - removed little-endian option col = (r << 24) | (g << 16) | (b << 8) | (a); } -void Tesselator::color(std::uint8_t r, std::uint8_t g, std::uint8_t b) -{ - color(r & 0xff, g & 0xff, b & 0xff); +void Tesselator::color(std::uint8_t r, std::uint8_t g, std::uint8_t b) { + color(r & 0xff, g & 0xff, b & 0xff); } -void Tesselator::vertexUV(float x, float y, float z, float u, float v) -{ +void Tesselator::vertexUV(float x, float y, float z, float u, float v) { tex(u, v); vertex(x, y, z); } -// Pack the 4 vertices of a quad up into a compact format. This is structured as 8 bytes per vertex, -// arranged in blocks of 4 vertices per quad. Currently this is (one letter per nyblle): +// Pack the 4 vertices of a quad up into a compact format. This is structured as +// 8 bytes per vertex, arranged in blocks of 4 vertices per quad. Currently this +// is (one letter per nyblle): // // cccc xxyy zzll rgbi (vertex 0) // umin xxyy zzll rgbi (vertex 1) // vmin xxyy zzll rgbi (vertex 2) // udvd xxyy zzll rgbi (vertex 3) // -// where: cccc is a 15-bit (5 bits per x/y/z) origin position / offset for the whole quad. Each -// component is unsigned, and offset by 16 so has a range 0 to 31 actually representing -16 to 15 -// xx,yy,zz are 8-bit deltas from this origin to each vertex. These are unsigned 1.7 fixed point, ie +// where: cccc is a 15-bit (5 bits per x/y/z) origin position / offset +// for the whole quad. Each +// component is unsigned, and offset by 16 +//so has a range 0 to 31 actually representing -16 to 15 +// xx,yy,zz are 8-bit deltas from this origin to each vertex. These are +// unsigned 1.7 fixed point, ie // representing a range of 0 to 1.9921875 // rgb is 4:4:4 RGB -// umin, vmin are 3:13 unsigned fixed point UVs reprenting the min u and v required by the quad -// ud,vd are 8-bit unsigned fixed pont UV deltas, which can be added to umin/vmin to get umax, vmax -// and therefore define the 4 corners of an axis aligned UV mapping -// i is a code per vertex that indicates which of umin/umax should be used for u, and which -// of vmin/vmax should be used for v for this vertex. The coding is: -// 0 - u = umin, v = vmin -// 1 - u = umin, v = vmax -// 2 - u = umax, v = vmin -// 3 - u = umax, v = vmax -// 4 - not axis aligned, use uv stored in the vertex data 4 on from this one -// ll is an 8-bit (4 bit per u/v) index into the current lighting texture +// umin, vmin are 3:13 unsigned fixed point UVs reprenting the min u and +// v required by the quad ud,vd are 8-bit unsigned fixed pont +// UV deltas, which can be added to umin/vmin to get umax, vmax +// and therefore define the 4 corners of +//an axis aligned UV mapping +// i is a code per vertex that indicates which of umin/umax +// should be used for u, and which +// of vmin/vmax should be used for v for +//this vertex. The coding is: 0 - u = umin, v = vmin 1 - u = umin, v = vmax 2 - +//u = umax, v = vmin 3 - u = umax, v = vmax 4 - not axis aligned, use uv stored +//in the vertex data 4 on from this one ll is an 8-bit (4 bit per +//u/v) index into the current lighting texture // -// For quads that don't have axis aligned UVs (ie have a code for 4 in i as described above) the 8 byte vertex -// is followed by a further 8 bytes which have explicit UVs defined for each vertex: +// For quads that don't have axis aligned UVs (ie have a code for 4 in i as +// described above) the 8 byte vertex is followed by a further 8 bytes which +// have explicit UVs defined for each vertex: // // 0000 0000 uuuu vvvv (vertex 0) // 0000 0000 uuuu vvvv (vertex 1) @@ -374,489 +378,481 @@ void Tesselator::vertexUV(float x, float y, float z, float u, float v) // 0000 0000 uuuu vvvv (vertex 3) // -void Tesselator::packCompactQuad() -{ - // Offset x/y/z by 16 so that we can deal with a -16 -> 16 range - for( int i = 0; i < 4; i++ ) - { - m_ix[i] += 16 * 128; - m_iy[i] += 16 * 128; - m_iz[i] += 16 * 128; - } - // Find min x/y/z - unsigned int minx = m_ix[0]; - unsigned int miny = m_iy[0]; - unsigned int minz = m_iz[0]; - for( int i = 1; i < 4; i++ ) - { - if( m_ix[i] < minx ) minx = m_ix[i]; - if( m_iy[i] < miny ) miny = m_iy[i]; - if( m_iz[i] < minz ) minz = m_iz[i]; - } - // Everything has been scaled by a factor of 128 to get it into an int, and so - // the minimum now should be in the range of (0->32) * 128. Get the base x/y/z - // that our quad will be referenced from now, which can be stored in 5 bits - unsigned int basex = ( minx >> 7 ); - unsigned int basey = ( miny >> 7 ); - unsigned int basez = ( minz >> 7 ); - // If the min is 32, then this whole quad must be in that plane - make the min 15 instead so - // we can still offset from that with our delta to get to the exact edge - if( basex == 32 ) basex = 31; - if( basey == 32 ) basey = 31; - if( basez == 32 ) basez = 31; - // Now get deltas to each vertex - these have an 8-bit range so they can span a - // full unit range from the base position - for( int i = 0; i < 4; i++ ) - { - m_ix[i] -= basex << 7; - m_iy[i] -= basey << 7; - m_iz[i] -= basez << 7; - } - // Now write the data out - unsigned int *data = (unsigned int *)&_array->data[p]; - - for( int i = 0; i < 4; i++ ) - { - data[i * 2 + 0] = ( m_ix[i] << 8 ) | ( m_iy[i] ); - data[i * 2 + 1] = ( m_iz[i] << 24 ) | ( m_clr[i] ); - } - data[0] |= ( basex << 26 ) | ( basey << 21 )| ( basez << 16 ); +void Tesselator::packCompactQuad() { + // Offset x/y/z by 16 so that we can deal with a -16 -> 16 range + for (int i = 0; i < 4; i++) { + m_ix[i] += 16 * 128; + m_iy[i] += 16 * 128; + m_iz[i] += 16 * 128; + } + // Find min x/y/z + unsigned int minx = m_ix[0]; + unsigned int miny = m_iy[0]; + unsigned int minz = m_iz[0]; + for (int i = 1; i < 4; i++) { + if (m_ix[i] < minx) minx = m_ix[i]; + if (m_iy[i] < miny) miny = m_iy[i]; + if (m_iz[i] < minz) minz = m_iz[i]; + } + // Everything has been scaled by a factor of 128 to get it into an int, and + // so the minimum now should be in the range of (0->32) * 128. Get the base + // x/y/z that our quad will be referenced from now, which can be stored in 5 + // bits + unsigned int basex = (minx >> 7); + unsigned int basey = (miny >> 7); + unsigned int basez = (minz >> 7); + // If the min is 32, then this whole quad must be in that plane - make the + // min 15 instead so we can still offset from that with our delta to get to + // the exact edge + if (basex == 32) basex = 31; + if (basey == 32) basey = 31; + if (basez == 32) basez = 31; + // Now get deltas to each vertex - these have an 8-bit range so they can + // span a full unit range from the base position + for (int i = 0; i < 4; i++) { + m_ix[i] -= basex << 7; + m_iy[i] -= basey << 7; + m_iz[i] -= basez << 7; + } + // Now write the data out + unsigned int* data = (unsigned int*)&_array->data[p]; - // Now process UVs. First find min & max U & V - unsigned int minu = m_u[0]; - unsigned int minv = m_v[0]; - unsigned int maxu = m_u[0]; - unsigned int maxv = m_v[0]; + for (int i = 0; i < 4; i++) { + data[i * 2 + 0] = (m_ix[i] << 8) | (m_iy[i]); + data[i * 2 + 1] = (m_iz[i] << 24) | (m_clr[i]); + } + data[0] |= (basex << 26) | (basey << 21) | (basez << 16); - for( int i = 1; i < 4; i++ ) - { - if( m_u[i] < minu ) minu = m_u[i]; - if( m_v[i] < minv ) minv = m_v[i]; - if( m_u[i] > maxu ) maxu = m_u[i]; - if( m_v[i] > maxv ) maxv = m_v[i]; - } - // In nearly all cases, all our UVs should be axis aligned for this quad. So the only values they should - // have in each dimension should be the min/max. We're going to store: - // (1) minu/maxu (16 bits each, only actuall needs to store 14 bits to get a 0 to 2 range for each - // (2) du/dv ( ie maxu-minu, maxv-minv) - 8 bits each, to store a range of 0 to 15.9375 texels. This - // should be enough to map the full UV range of a single 16x16 region of the terrain texture, since - // we always pull UVs in by 1/16th of their range at the sides - unsigned int du = maxu - minu; - unsigned int dv = maxv - minv; - if( du > 255 ) du = 255; - if( dv > 255 ) dv = 255; - // Check if this quad has UVs that can be referenced this way. This should only happen for flowing water - // and lava, where the texture coordinates are rotated for the top surface of the tile. - bool axisAligned = true; - for( int i = 0; i < 4; i++ ) - { - if(! ( ( ( m_u[i] == minu ) || ( m_u[i] == maxu ) ) && - ( ( m_v[i] == minv ) || ( m_v[i] == maxv ) ) ) ) - { - axisAligned = false; - } - } + // Now process UVs. First find min & max U & V + unsigned int minu = m_u[0]; + unsigned int minv = m_v[0]; + unsigned int maxu = m_u[0]; + unsigned int maxv = m_v[0]; - if( axisAligned ) - { - // Now go through each vertex, and work out which of the min/max should be used for each dimension, - // and store - for( int i = 0; i < 4; i++ ) - { - unsigned int code = 0; - if( m_u[i] == maxu ) code |= 2; - if( m_v[i] == maxv ) code |= 1; - data[i * 2 + 1] |= code; - data[i * 2 + 1] |= m_t2[i] << 16; - } - // Finally, store the minu/minv/du/dv - data[1 * 2 + 0] |= minu << 16; - data[2 * 2 + 0] |= minv << 16; - data[3 * 2 + 0] |= ( du << 24 | dv << 16 ); + for (int i = 1; i < 4; i++) { + if (m_u[i] < minu) minu = m_u[i]; + if (m_v[i] < minv) minv = m_v[i]; + if (m_u[i] > maxu) maxu = m_u[i]; + if (m_v[i] > maxv) maxv = m_v[i]; + } + // In nearly all cases, all our UVs should be axis aligned for this quad. So + // the only values they should have in each dimension should be the min/max. + // We're going to store: (1) minu/maxu (16 bits each, only actuall needs to + // store 14 bits to get a 0 to 2 range for each (2) du/dv ( ie maxu-minu, + // maxv-minv) - 8 bits each, to store a range of 0 to 15.9375 texels. This + // should be enough to map the full UV range of a single 16x16 region of the + // terrain texture, since we always pull UVs in by 1/16th of their range at + // the sides + unsigned int du = maxu - minu; + unsigned int dv = maxv - minv; + if (du > 255) du = 255; + if (dv > 255) dv = 255; + // Check if this quad has UVs that can be referenced this way. This should + // only happen for flowing water and lava, where the texture coordinates are + // rotated for the top surface of the tile. + bool axisAligned = true; + for (int i = 0; i < 4; i++) { + if (!(((m_u[i] == minu) || (m_u[i] == maxu)) && + ((m_v[i] == minv) || (m_v[i] == maxv)))) { + axisAligned = false; + } + } - p += 4 * 2; - } - else - { - // The UVs aren't axis aligned - store them in the next 4 vertices. These will be indexed from - // our base vertices because we'll set a special code (4) for the UVs. They won't be drawn as actual - // verts when these extra vertices go through the vertex shader, because we'll make sure that - // they get interpreted as a zero area quad and so they'll be quickly eliminated from rendering post-tranform + if (axisAligned) { + // Now go through each vertex, and work out which of the min/max should + // be used for each dimension, and store + for (int i = 0; i < 4; i++) { + unsigned int code = 0; + if (m_u[i] == maxu) code |= 2; + if (m_v[i] == maxv) code |= 1; + data[i * 2 + 1] |= code; + data[i * 2 + 1] |= m_t2[i] << 16; + } + // Finally, store the minu/minv/du/dv + data[1 * 2 + 0] |= minu << 16; + data[2 * 2 + 0] |= minv << 16; + data[3 * 2 + 0] |= (du << 24 | dv << 16); - for( int i = 0; i < 4; i++ ) - { - data[i * 2 + 1] |= ( 4 ); // The special code to indicate they need further data to be fetched - data[i * 2 + 1] |= m_t2[i] << 16; - data[8 + i * 2] = 0; // This includes x/y coordinate of each vert as (0,0) so they will be interpreted as a zero area quad - data[9 + i * 2] = m_u[i] << 16 | m_v[i]; - } + p += 4 * 2; + } else { + // The UVs aren't axis aligned - store them in the next 4 vertices. + // These will be indexed from our base vertices because we'll set a + // special code (4) for the UVs. They won't be drawn as actual verts + // when these extra vertices go through the vertex shader, because we'll + // make sure that they get interpreted as a zero area quad and so + // they'll be quickly eliminated from rendering post-tranform - // Extra 8 bytes required - p += 8 * 2; - } + for (int i = 0; i < 4; i++) { + data[i * 2 + 1] |= (4); // The special code to indicate they need + // further data to be fetched + data[i * 2 + 1] |= m_t2[i] << 16; + data[8 + i * 2] = + 0; // This includes x/y coordinate of each vert as (0,0) so + // they will be interpreted as a zero area quad + data[9 + i * 2] = m_u[i] << 16 | m_v[i]; + } + + // Extra 8 bytes required + p += 8 * 2; + } } #ifdef __PSVITA__ -void Tesselator::tileQuad(float x1, float y1, float z1, float u1, float v1, float r1, float g1, float b1, int tex1, - float x2, float y2, float z2, float u2, float v2, float r2, float g2, float b2, int tex2, - float x3, float y3, float z3, float u3, float v3, float r3, float g3, float b3, int tex3, - float x4, float y4, float z4, float u4, float v4, float r4, float g4, float b4, int tex4 - ) -{ +void Tesselator::tileQuad(float x1, float y1, float z1, float u1, float v1, + float r1, float g1, float b1, int tex1, float x2, + float y2, float z2, float u2, float v2, float r2, + float g2, float b2, int tex2, float x3, float y3, + float z3, float u3, float v3, float r3, float g3, + float b3, int tex3, float x4, float y4, float z4, + float u4, float v4, float r4, float g4, float b4, + int tex4) { hasTexture = true; hasTexture2 = true; - hasColor = true; + hasColor = true; - count+=4; + count += 4; - // AP - alpha cut out is expensive on vita. This will choose the correct data buffer depending on cut out enabled - std::int16_t* pShortData; - if( !alphaCutOutEnabled ) - { - pShortData = (std::int16_t*)&_array->data[p]; - p += 16; - vertices+=4; - } - else - { - pShortData = (std::int16_t*)&_array2->data[p2]; - p2 += 16; - vertices2+=4; - } + // AP - alpha cut out is expensive on vita. This will choose the correct + // data buffer depending on cut out enabled + std::int16_t* pShortData; + if (!alphaCutOutEnabled) { + pShortData = (std::int16_t*)&_array->data[p]; + p += 16; + vertices += 4; + } else { + pShortData = (std::int16_t*)&_array2->data[p2]; + p2 += 16; + vertices2 += 4; + } - int r = ((int) (r1 * 31)) << 11; - int g = ((int) (g1 * 63)) << 5; - int b = ((int) (b1 * 31)); - int ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + int r = ((int)(r1 * 31)) << 11; + int g = ((int)(g1 * 63)) << 5; + int b = ((int)(b1 * 31)); + int ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x1+xo, y1+yo, z1+zo); // 4J MGH - added - pShortData[0] = (((int)((x1 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y1 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z1 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u1 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v1 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex1; - pShortData += 8; + bounds.addVert(x1 + xo, y1 + yo, z1 + zo); // 4J MGH - added + pShortData[0] = (((int)((x1 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y1 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z1 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u1 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v1 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex1; + pShortData += 8; - r = ((int) (r2 * 31)) << 11; - g = ((int) (g2 * 63)) << 5; - b = ((int) (b2 * 31)); - ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + r = ((int)(r2 * 31)) << 11; + g = ((int)(g2 * 63)) << 5; + b = ((int)(b2 * 31)); + ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x2+xo, y2+yo, z2+zo); // 4J MGH - added - pShortData[0] = (((int)((x2 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y2 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z2 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u2 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v2 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex2; - pShortData += 8; + bounds.addVert(x2 + xo, y2 + yo, z2 + zo); // 4J MGH - added + pShortData[0] = (((int)((x2 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y2 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z2 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u2 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v2 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex2; + pShortData += 8; - r = ((int) (r3 * 31)) << 11; - g = ((int) (g3 * 63)) << 5; - b = ((int) (b3 * 31)); - ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + r = ((int)(r3 * 31)) << 11; + g = ((int)(g3 * 63)) << 5; + b = ((int)(b3 * 31)); + ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x3+xo, y3+yo, z3+zo); // 4J MGH - added - pShortData[0] = (((int)((x3 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y3 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z3 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u3 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v3 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex3; - pShortData += 8; + bounds.addVert(x3 + xo, y3 + yo, z3 + zo); // 4J MGH - added + pShortData[0] = (((int)((x3 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y3 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z3 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u3 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v3 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex3; + pShortData += 8; - r = ((int) (r4 * 31)) << 11; - g = ((int) (g4 * 63)) << 5; - b = ((int) (b4 * 31)); - ipackedcol = r | g | b; - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + r = ((int)(r4 * 31)) << 11; + g = ((int)(g4 * 63)) << 5; + b = ((int)(b4 * 31)); + ipackedcol = r | g | b; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; - bounds.addVert(x4+xo, y4+yo, z4+zo); // 4J MGH - added - pShortData[0] = (((int)((x4 + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y4 + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z4 + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(u4 * 8192.0f))&0xffff); - pShortData[5] = (((int)(v4 * 8192.0f))&0xffff); - ((int *)pShortData)[3] = tex4; + bounds.addVert(x4 + xo, y4 + yo, z4 + zo); // 4J MGH - added + pShortData[0] = (((int)((x4 + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y4 + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z4 + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(u4 * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v4 * 8192.0f)) & 0xffff); + ((int*)pShortData)[3] = tex4; - // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it - if ( (!alphaCutOutEnabled && vertices % 4 == 0 && ( ( p >= size - 4 * 4 ) || ( ( p / 4 ) >= 65532 ) )) || - (alphaCutOutEnabled && vertices2 % 4 == 0 && ( ( p2 >= size - 4 * 4 ) || ( ( p2 / 4 ) >= 65532 ) )) ) - { - end(); - tesselating = true; - } + // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad + // to catch it + if ((!alphaCutOutEnabled && vertices % 4 == 0 && + ((p >= size - 4 * 4) || ((p / 4) >= 65532))) || + (alphaCutOutEnabled && vertices2 % 4 == 0 && + ((p2 >= size - 4 * 4) || ((p2 / 4) >= 65532)))) { + end(); + tesselating = true; + } } -void Tesselator::tileRainQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1, - float r2, float g2, float b2, float a2, - int tex1 - ) -{ +void Tesselator::tileRainQuad(float x1, float y1, float z1, float u1, float v1, + float x2, float y2, float z2, float u2, float v2, + float x3, float y3, float z3, float u3, float v3, + float x4, float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1, float r2, + float g2, float b2, float a2, int tex1) { hasTexture = true; hasTexture2 = true; - hasColor = true; + hasColor = true; - float* pfData = (float*)&_array->data[p]; + float* pfData = (float*)&_array->data[p]; - count+=4; - p += 4 * 8; - vertices+=4; + count += 4; + p += 4 * 8; + vertices += 4; - unsigned int col1 = ((int)(r1*255) << 24) | ((int)(g1*255) << 16) | ((int)(b1*255) << 8) | (int)(a1*255); + unsigned int col1 = ((int)(r1 * 255) << 24) | ((int)(g1 * 255) << 16) | + ((int)(b1 * 255) << 8) | (int)(a1 * 255); - bounds.addVert(x1+xo, y1+yo, z1+zo); - pfData[0] = (x1 + xo); - pfData[1] = (y1 + yo); - pfData[2] = (z1 + zo); - pfData[3] = u1; - pfData[4] = v1; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x1 + xo, y1 + yo, z1 + zo); + pfData[0] = (x1 + xo); + pfData[1] = (y1 + yo); + pfData[2] = (z1 + zo); + pfData[3] = u1; + pfData[4] = v1; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - bounds.addVert(x2+xo, y2+yo, z2+zo); - pfData[0] = (x2 + xo); - pfData[1] = (y2 + yo); - pfData[2] = (z2 + zo); - pfData[3] = u2; - pfData[4] = v2; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x2 + xo, y2 + yo, z2 + zo); + pfData[0] = (x2 + xo); + pfData[1] = (y2 + yo); + pfData[2] = (z2 + zo); + pfData[3] = u2; + pfData[4] = v2; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - col1 = ((int)(r2*255) << 24) | ((int)(g2*255) << 16) | ((int)(b2*255) << 8) | (int)(a2*255); + col1 = ((int)(r2 * 255) << 24) | ((int)(g2 * 255) << 16) | + ((int)(b2 * 255) << 8) | (int)(a2 * 255); - bounds.addVert(x3+xo, y3+yo, z3+zo); - pfData[0] = (x3 + xo); - pfData[1] = (y3 + yo); - pfData[2] = (z3 + zo); - pfData[3] = u3; - pfData[4] = v3; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x3 + xo, y3 + yo, z3 + zo); + pfData[0] = (x3 + xo); + pfData[1] = (y3 + yo); + pfData[2] = (z3 + zo); + pfData[3] = u3; + pfData[4] = v3; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - bounds.addVert(x4+xo, y4+yo, z4+zo); - pfData[0] = (x4 + xo); - pfData[1] = (y4 + yo); - pfData[2] = (z4 + zo); - pfData[3] = u4; - pfData[4] = v4; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = tex1; - pfData += 8; + bounds.addVert(x4 + xo, y4 + yo, z4 + zo); + pfData[0] = (x4 + xo); + pfData[1] = (y4 + yo); + pfData[2] = (z4 + zo); + pfData[3] = u4; + pfData[4] = v4; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = tex1; + pfData += 8; - if (vertices % 4 == 0 && p >= size - 8 * 4) - { - end(); - tesselating = true; - } + if (vertices % 4 == 0 && p >= size - 8 * 4) { + end(); + tesselating = true; + } } -void Tesselator::tileParticleQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1) -{ +void Tesselator::tileParticleQuad(float x1, float y1, float z1, float u1, + float v1, float x2, float y2, float z2, + float u2, float v2, float x3, float y3, + float z3, float u3, float v3, float x4, + float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1) { hasTexture = true; hasTexture2 = true; - hasColor = true; + hasColor = true; - float* pfData = (float*)&_array->data[p]; + float* pfData = (float*)&_array->data[p]; - count+=4; - p += 4 * 8; - vertices+=4; + count += 4; + p += 4 * 8; + vertices += 4; - unsigned int col1 = ((int)(r1*255) << 24) | ((int)(g1*255) << 16) | ((int)(b1*255) << 8) | (int)(a1*255); + unsigned int col1 = ((int)(r1 * 255) << 24) | ((int)(g1 * 255) << 16) | + ((int)(b1 * 255) << 8) | (int)(a1 * 255); - bounds.addVert(x1+xo, y1+yo, z1+zo); - pfData[0] = (x1 + xo); - pfData[1] = (y1 + yo); - pfData[2] = (z1 + zo); - pfData[3] = u1; - pfData[4] = v1; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x1 + xo, y1 + yo, z1 + zo); + pfData[0] = (x1 + xo); + pfData[1] = (y1 + yo); + pfData[2] = (z1 + zo); + pfData[3] = u1; + pfData[4] = v1; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - bounds.addVert(x2+xo, y2+yo, z2+zo); - pfData[0] = (x2 + xo); - pfData[1] = (y2 + yo); - pfData[2] = (z2 + zo); - pfData[3] = u2; - pfData[4] = v2; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x2 + xo, y2 + yo, z2 + zo); + pfData[0] = (x2 + xo); + pfData[1] = (y2 + yo); + pfData[2] = (z2 + zo); + pfData[3] = u2; + pfData[4] = v2; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - bounds.addVert(x3+xo, y3+yo, z3+zo); - pfData[0] = (x3 + xo); - pfData[1] = (y3 + yo); - pfData[2] = (z3 + zo); - pfData[3] = u3; - pfData[4] = v3; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x3 + xo, y3 + yo, z3 + zo); + pfData[0] = (x3 + xo); + pfData[1] = (y3 + yo); + pfData[2] = (z3 + zo); + pfData[3] = u3; + pfData[4] = v3; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - bounds.addVert(x4+xo, y4+yo, z4+zo); - pfData[0] = (x4 + xo); - pfData[1] = (y4 + yo); - pfData[2] = (z4 + zo); - pfData[3] = u4; - pfData[4] = v4; - ((int*)pfData)[5] = col1; - ((int*)pfData)[7] = _tex2; - pfData += 8; + bounds.addVert(x4 + xo, y4 + yo, z4 + zo); + pfData[0] = (x4 + xo); + pfData[1] = (y4 + yo); + pfData[2] = (z4 + zo); + pfData[3] = u4; + pfData[4] = v4; + ((int*)pfData)[5] = col1; + ((int*)pfData)[7] = _tex2; + pfData += 8; - if (vertices % 4 == 0 && p >= size - 8 * 4) - { - end(); - tesselating = true; - } + if (vertices % 4 == 0 && p >= size - 8 * 4) { + end(); + tesselating = true; + } } #endif -typedef unsigned short hfloat; +typedef unsigned short hfloat; extern hfloat convertFloatToHFloat(float f); extern float convertHFloatToFloat(hfloat hf); -void Tesselator::vertex(float x, float y, float z) -{ - bounds.addVert(x+xo, y+yo, z+zo); // 4J MGH - added +void Tesselator::vertex(float x, float y, float z) { + bounds.addVert(x + xo, y + yo, z + zo); // 4J MGH - added count++; - // Signal to pixel shader whether to use mipmapping or not, by putting u into > 1 range if it is to be disabled - float uu = mipmapEnable ? u : (u + 1.0f); + // Signal to pixel shader whether to use mipmapping or not, by putting u + // into > 1 range if it is to be disabled + float uu = mipmapEnable ? u : (u + 1.0f); - // 4J - this format added for 360 to keep memory size of tesselated tiles down - - // see comments in packCompactQuad() for exact format - if( useCompactFormat360 ) - { - unsigned int ucol = (unsigned int)col; + // 4J - this format added for 360 to keep memory size of tesselated tiles + // down - see comments in packCompactQuad() for exact format + if (useCompactFormat360) { + unsigned int ucol = (unsigned int)col; #ifdef _XBOX - // Pack as 4:4:4 RGB_ - unsigned short packedcol = (((col & 0xf0000000 ) >> 16 ) | - ((col & 0x00f00000 ) >> 12 ) | - ((col & 0x0000f000 ) >> 8 )); - int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range + // Pack as 4:4:4 RGB_ + unsigned short packedcol = + (((col & 0xf0000000) >> 16) | ((col & 0x00f00000) >> 12) | + ((col & 0x0000f000) >> 8)); + int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range - int quadIdx = vertices % 4; - m_ix[ quadIdx ] = (unsigned int)((x + xo) * 128.0f); - m_iy[ quadIdx ] = (unsigned int)((y + yo) * 128.0f); - m_iz[ quadIdx ] = (unsigned int)((z + zo) * 128.0f); - m_clr[ quadIdx ] = (unsigned int)ipackedcol; - m_u[ quadIdx ] = (int)(uu * 4096.0f); - m_v[ quadIdx ] = (int)(v * 4096.0f); - m_t2[ quadIdx ] = ( ( _tex2 & 0x00f00000 ) >> 20 ) | ( _tex2 & 0x000000f0 ); - if( quadIdx == 3 ) - { - packCompactQuad(); - } + int quadIdx = vertices % 4; + m_ix[quadIdx] = (unsigned int)((x + xo) * 128.0f); + m_iy[quadIdx] = (unsigned int)((y + yo) * 128.0f); + m_iz[quadIdx] = (unsigned int)((z + zo) * 128.0f); + m_clr[quadIdx] = (unsigned int)ipackedcol; + m_u[quadIdx] = (int)(uu * 4096.0f); + m_v[quadIdx] = (int)(v * 4096.0f); + m_t2[quadIdx] = ((_tex2 & 0x00f00000) >> 20) | (_tex2 & 0x000000f0); + if (quadIdx == 3) { + packCompactQuad(); + } #else - unsigned short packedcol = ((col & 0xf8000000 ) >> 16 ) | - ((col & 0x00fc0000 ) >> 13 ) | - ((col & 0x0000f800 ) >> 11 ); - int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range + unsigned short packedcol = ((col & 0xf8000000) >> 16) | + ((col & 0x00fc0000) >> 13) | + ((col & 0x0000f800) >> 11); + int ipackedcol = ((int)packedcol) & 0xffff; // 0 to 65535 range - ipackedcol -= 32768; // -32768 to 32767 range - ipackedcol &= 0xffff; + ipackedcol -= 32768; // -32768 to 32767 range + ipackedcol &= 0xffff; #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. This will choose the correct data buffer depending on cut out enabled - std::int16_t* pShortData; - if( !alphaCutOutEnabled ) - { - pShortData = (std::int16_t*)&_array->data[p]; - } - else - { - pShortData = (std::int16_t*)&_array2->data[p2]; - } + // AP - alpha cut out is expensive on vita. This will choose the correct + // data buffer depending on cut out enabled + std::int16_t* pShortData; + if (!alphaCutOutEnabled) { + pShortData = (std::int16_t*)&_array->data[p]; + } else { + pShortData = (std::int16_t*)&_array2->data[p2]; + } #else - std::int16_t* pShortData = (std::int16_t*)&_array->data[p]; + std::int16_t* pShortData = (std::int16_t*)&_array->data[p]; #endif - - #ifdef __PS3__ - float tex2U = ((std::int16_t*)&_tex2)[1] + 8; - float tex2V = ((std::int16_t*)&_tex2)[0] + 8; - float colVal1 = ((col&0xff000000)>>24)/256.0f; - float colVal2 = ((col&0x00ff0000)>>16)/256.0f; - float colVal3 = ((col&0x0000ff00)>>8)/256.0f; + float tex2U = ((std::int16_t*)&_tex2)[1] + 8; + float tex2V = ((std::int16_t*)&_tex2)[0] + 8; + float colVal1 = ((col & 0xff000000) >> 24) / 256.0f; + float colVal2 = ((col & 0x00ff0000) >> 16) / 256.0f; + float colVal3 = ((col & 0x0000ff00) >> 8) / 256.0f; -// pShortData[0] = convertFloatToHFloat(x + xo); -// pShortData[1] = convertFloatToHFloat(y + yo); -// pShortData[2] = convertFloatToHFloat(z + zo); -// pShortData[3] = convertFloatToHFloat(uu); -// pShortData[4] = convertFloatToHFloat(tex2U + colVal1); -// pShortData[5] = convertFloatToHFloat(tex2V + colVal2); -// pShortData[6] = convertFloatToHFloat(colVal3); -// pShortData[7] = convertFloatToHFloat(v); + // pShortData[0] = convertFloatToHFloat(x + xo); + // pShortData[1] = convertFloatToHFloat(y + yo); + // pShortData[2] = convertFloatToHFloat(z + zo); + // pShortData[3] = convertFloatToHFloat(uu); + // pShortData[4] = convertFloatToHFloat(tex2U + colVal1); + // pShortData[5] = convertFloatToHFloat(tex2V + colVal2); + // pShortData[6] = convertFloatToHFloat(colVal3); + // pShortData[7] = convertFloatToHFloat(v); - pShortData[0] = (((int)((x + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(uu * 8192.0f))&0xffff); - pShortData[5] = (((int)(v * 8192.0f))&0xffff); - pShortData[6] = (((int)(tex2U * (8192.0f/256.0f)))&0xffff); - pShortData[7] = (((int)(tex2V * (8192.0f/256.0f)))&0xffff); + pShortData[0] = (((int)((x + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(uu * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v * 8192.0f)) & 0xffff); + pShortData[6] = (((int)(tex2U * (8192.0f / 256.0f))) & 0xffff); + pShortData[7] = (((int)(tex2V * (8192.0f / 256.0f))) & 0xffff); - p += 4; + p += 4; #else - pShortData[0] = (((int)((x + xo ) * 1024.0f))&0xffff); - pShortData[1] = (((int)((y + yo ) * 1024.0f))&0xffff); - pShortData[2] = (((int)((z + zo ) * 1024.0f))&0xffff); - pShortData[3] = ipackedcol; - pShortData[4] = (((int)(uu * 8192.0f))&0xffff); - pShortData[5] = (((int)(v * 8192.0f))&0xffff); - std::int16_t u2 = ((std::int16_t*)&_tex2)[0]; - std::int16_t v2 = ((std::int16_t*)&_tex2)[1]; + pShortData[0] = (((int)((x + xo) * 1024.0f)) & 0xffff); + pShortData[1] = (((int)((y + yo) * 1024.0f)) & 0xffff); + pShortData[2] = (((int)((z + zo) * 1024.0f)) & 0xffff); + pShortData[3] = ipackedcol; + pShortData[4] = (((int)(uu * 8192.0f)) & 0xffff); + pShortData[5] = (((int)(v * 8192.0f)) & 0xffff); + std::int16_t u2 = ((std::int16_t*)&_tex2)[0]; + std::int16_t v2 = ((std::int16_t*)&_tex2)[1]; #if defined _XBOX_ONE || defined __ORBIS__ - // Optimisation - pack the second UVs into a single short (they could actually go in a byte), which frees up a short to store the x offset for this chunk in the vertex itself. - // This means that when rendering chunks, we don't need to update the vertex constants that specify the location for a chunk, when only the x offset has changed. - pShortData[6] = ( u2 << 8 ) | v2; - pShortData[7] = -xoo; + // Optimisation - pack the second UVs into a single short (they could + // actually go in a byte), which frees up a short to store the x offset + // for this chunk in the vertex itself. This means that when rendering + // chunks, we don't need to update the vertex constants that specify the + // location for a chunk, when only the x offset has changed. + pShortData[6] = (u2 << 8) | v2; + pShortData[7] = -xoo; #else - pShortData[6] = u2; - pShortData[7] = v2; + pShortData[6] = u2; + pShortData[7] = v2; #endif #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. This will choose the correct data buffer depending on cut out enabled - if( !alphaCutOutEnabled ) - { - p += 4; - } - else - { - p2 += 4; - } + // AP - alpha cut out is expensive on vita. This will choose the correct + // data buffer depending on cut out enabled + if (!alphaCutOutEnabled) { + p += 4; + } else { + p2 += 4; + } #else - p += 4; + p += 4; #endif #endif @@ -864,152 +860,143 @@ void Tesselator::vertex(float x, float y, float z) #endif #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Increase the correct vertices depending on cut out enabled - if( !alphaCutOutEnabled ) - { - vertices++; - } - else - { - vertices2++; - } + // AP - alpha cut out is expensive on vita. Increase the correct + // vertices depending on cut out enabled + if (!alphaCutOutEnabled) { + vertices++; + } else { + vertices2++; + } #else - vertices++; + vertices++; #endif #ifdef _XBOX - if (vertices % 4 == 0 && ( ( p >= size - 8 * 2 ) || ( ( p / 2 ) >= 65532 ) ) ) // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it + if (vertices % 4 == 0 && + ((p >= size - 8 * 2) || + ((p / 2) >= + 65532))) // Max 65535 verts in D3D, so 65532 is the last point at + // the end of a quad to catch it #else #ifdef __PSVITA__ - // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it - if ( (!alphaCutOutEnabled && vertices % 4 == 0 && ( ( p >= size - 4 * 4 ) || ( ( p / 4 ) >= 65532 ) )) || - (alphaCutOutEnabled && vertices2 % 4 == 0 && ( ( p2 >= size - 4 * 4 ) || ( ( p2 / 4 ) >= 65532 ) )) ) + // Max 65535 verts in D3D, so 65532 is the last point at the end of a + // quad to catch it + if ((!alphaCutOutEnabled && vertices % 4 == 0 && + ((p >= size - 4 * 4) || ((p / 4) >= 65532))) || + (alphaCutOutEnabled && vertices2 % 4 == 0 && + ((p2 >= size - 4 * 4) || ((p2 / 4) >= 65532)))) #else - if (vertices % 4 == 0 && ( ( p >= size - 4 * 4 ) || ( ( p / 4 ) >= 65532 ) ) ) // Max 65535 verts in D3D, so 65532 is the last point at the end of a quad to catch it + if (vertices % 4 == 0 && + ((p >= size - 4 * 4) || + ((p / 4) >= + 65532))) // Max 65535 verts in D3D, so 65532 is the last point at + // the end of a quad to catch it #endif #endif - { - end(); - tesselating = true; - } - } - else - { - if (mode == GL_QUADS && TRIANGLE_MODE && count % 4 == 0) - { - for (int i = 0; i < 2; i++) - { - int offs = 8 * (3 - i); - if (hasTexture) - { - _array->data[p + 3] = _array->data[p - offs + 3]; - _array->data[p + 4] = _array->data[p - offs + 4]; - } - if (hasColor) - { - _array->data[p + 5] = _array->data[p - offs + 5]; - } + { + end(); + tesselating = true; + } + } else { + if (mode == GL_QUADS && TRIANGLE_MODE && count % 4 == 0) { + for (int i = 0; i < 2; i++) { + int offs = 8 * (3 - i); + if (hasTexture) { + _array->data[p + 3] = _array->data[p - offs + 3]; + _array->data[p + 4] = _array->data[p - offs + 4]; + } + if (hasColor) { + _array->data[p + 5] = _array->data[p - offs + 5]; + } - _array->data[p + 0] = _array->data[p - offs + 0]; - _array->data[p + 1] = _array->data[p - offs + 1]; - _array->data[p + 2] = _array->data[p - offs + 2]; + _array->data[p + 0] = _array->data[p - offs + 0]; + _array->data[p + 1] = _array->data[p - offs + 1]; + _array->data[p + 2] = _array->data[p - offs + 2]; - vertices++; - p += 8; - } - } + vertices++; + p += 8; + } + } - if (hasTexture) - { - float *fdata = (float *)(_array->data + p + 3); - *fdata++ = uu; - *fdata++ = v; - } - if (hasColor) - { - _array->data[p + 5] = col; - } - if (hasNormal) - { - _array->data[p + 6] = _normal; - } - if (hasTexture2) - { + if (hasTexture) { + float* fdata = (float*)(_array->data + p + 3); + *fdata++ = uu; + *fdata++ = v; + } + if (hasColor) { + _array->data[p + 5] = col; + } + if (hasNormal) { + _array->data[p + 6] = _normal; + } + if (hasTexture2) { #ifdef _XBOX - _array->data[p + 7] = ( ( _tex2 >> 16 ) & 0xffff ) | ( _tex2 << 16 ); + _array->data[p + 7] = ((_tex2 >> 16) & 0xffff) | (_tex2 << 16); #else - // 4jcraft: we will be lighting the blocks right in here - #if defined(__PS3__) || defined (__linux__) - #ifdef __PS3__ - std::int16_t tex2U = ((std::int16_t*)&_tex2)[1] + 8; - std::int16_t tex2V = ((std::int16_t*)&_tex2)[0] + 8; - #else - std::int16_t tex2U = ((std::int16_t*)&_tex2)[0] + 8; - std::int16_t tex2V = ((std::int16_t*)&_tex2)[1] + 8; - #endif - std::int16_t* pShortArray = (std::int16_t*)&_array->data[p + 7]; - pShortArray[0] = tex2U; - pShortArray[1] = tex2V; - #else - _array->data[p + 7] = _tex2; - #endif +// 4jcraft: we will be lighting the blocks right in here +#if defined(__PS3__) || defined(__linux__) +#ifdef __PS3__ + std::int16_t tex2U = ((std::int16_t*)&_tex2)[1] + 8; + std::int16_t tex2V = ((std::int16_t*)&_tex2)[0] + 8; +#else + std::int16_t tex2U = ((std::int16_t*)&_tex2)[0] + 8; + std::int16_t tex2V = ((std::int16_t*)&_tex2)[1] + 8; #endif - } - else - { - // -512 each for u/v will mean that the renderer will use global settings (set via - // RenderManager.StateSetVertexTextureUV) rather than these local ones - *(unsigned int *)(&_array->data[p + 7]) = 0xfe00fe00; - } + std::int16_t* pShortArray = (std::int16_t*)&_array->data[p + 7]; + pShortArray[0] = tex2U; + pShortArray[1] = tex2V; +#else + _array->data[p + 7] = _tex2; +#endif +#endif + } else { + // -512 each for u/v will mean that the renderer will use global + // settings (set via RenderManager.StateSetVertexTextureUV) rather + // than these local ones + *(unsigned int*)(&_array->data[p + 7]) = 0xfe00fe00; + } - float *fdata = (float *)(_array->data + p); - *fdata++ = (x + xo); - *fdata++ = (y + yo); - *fdata++ = (z + zo); - p += 8; + float* fdata = (float*)(_array->data + p); + *fdata++ = (x + xo); + *fdata++ = (y + yo); + *fdata++ = (z + zo); + p += 8; - vertices++; - if (vertices % 4 == 0 && p >= size - 8 * 4) - { - end(); - tesselating = true; - } - } + vertices++; + if (vertices % 4 == 0 && p >= size - 8 * 4) { + end(); + tesselating = true; + } + } } -void Tesselator::color(int c) -{ +void Tesselator::color(int c) { int r = ((c >> 16) & 255); int g = ((c >> 8) & 255); int b = ((c) & 255); color(r, g, b); } -void Tesselator::color(int c, int alpha) -{ +void Tesselator::color(int c, int alpha) { int r = ((c >> 16) & 255); int g = ((c >> 8) & 255); int b = ((c) & 255); color(r, g, b, alpha); } -void Tesselator::noColor() -{ - _noColor = true; -} +void Tesselator::noColor() { _noColor = true; } #ifdef __PS3__ -std::uint32_t _ConvertF32toX11Y11Z10N(float x, float y, float z) -{ - // 11111111111 X 0x000007FF - // 1111111111100000000000 Y 0x003FF800 - // 11111111110000000000000000000000 Z 0xFFC00000 - // ZZZZZZZZZZYYYYYYYYYYYXXXXXXXXXXX - // #defines for X11Y11Z10N format +std::uint32_t _ConvertF32toX11Y11Z10N(float x, float y, float z) { + // 11111111111 X 0x000007FF + // 1111111111100000000000 Y 0x003FF800 + // 11111111110000000000000000000000 Z 0xFFC00000 + // ZZZZZZZZZZYYYYYYYYYYYXXXXXXXXXXX + // #defines for X11Y11Z10N format #define X11Y11Z10N_X_MASK 0x000007FF #define X11Y11Z10N_X_BITS 11 #define X11Y11Z10N_X_SHIFT 0 @@ -1023,68 +1010,93 @@ std::uint32_t _ConvertF32toX11Y11Z10N(float x, float y, float z) #define X11Y11Z10N_Z_SHIFT 22 #ifndef _CONTENT_PACKAGE - if (x<-1.0f || x>1.0f) { printf("Value (%5.3f) should be in range [-1..1]. Conversion will clamp to X11Y11Z10N.\n", x); } - if (y<-1.0f || y>1.0f) { printf("Value (%5.3f) should be in range [-1..1]. Conversion will clamp to X11Y11Z10N.\n", y); } - if (z<-1.0f || z>1.0f) { printf("Value (%5.3f) should be in range [-1..1]. Conversion will clamp to X11Y11Z10N.\n", z); } + if (x < -1.0f || x > 1.0f) { + printf( + "Value (%5.3f) should be in range [-1..1]. Conversion will clamp " + "to X11Y11Z10N.\n", + x); + } + if (y < -1.0f || y > 1.0f) { + printf( + "Value (%5.3f) should be in range [-1..1]. Conversion will clamp " + "to X11Y11Z10N.\n", + y); + } + if (z < -1.0f || z > 1.0f) { + printf( + "Value (%5.3f) should be in range [-1..1]. Conversion will clamp " + "to X11Y11Z10N.\n", + z); + } #endif - const std::uint32_t uX = ((std::int32_t(std::max(std::min(((x)*2047.f - 1.f)*0.5f, 1023.f), -1024.f)) & (X11Y11Z10N_X_MASK >> X11Y11Z10N_X_SHIFT)) << X11Y11Z10N_X_SHIFT); - const std::uint32_t uY = ((std::int32_t(std::max(std::min(((y)*2047.f - 1.f)*0.5f, 1023.f), -1024.f)) & (X11Y11Z10N_Y_MASK >> X11Y11Z10N_Y_SHIFT)) << X11Y11Z10N_Y_SHIFT); - const std::uint32_t uZ = ((std::int32_t(std::max(std::min(((z)*1023.f - 1.f)*0.5f, 511.f), -512.f )) & (X11Y11Z10N_Z_MASK >> X11Y11Z10N_Z_SHIFT)) << X11Y11Z10N_Z_SHIFT); - const std::uint32_t xyz = uX | uY | uZ; - return xyz; + const std::uint32_t uX = + ((std::int32_t(std::max(std::min(((x) * 2047.f - 1.f) * 0.5f, 1023.f), + -1024.f)) & + (X11Y11Z10N_X_MASK >> X11Y11Z10N_X_SHIFT)) + << X11Y11Z10N_X_SHIFT); + const std::uint32_t uY = + ((std::int32_t(std::max(std::min(((y) * 2047.f - 1.f) * 0.5f, 1023.f), + -1024.f)) & + (X11Y11Z10N_Y_MASK >> X11Y11Z10N_Y_SHIFT)) + << X11Y11Z10N_Y_SHIFT); + const std::uint32_t uZ = + ((std::int32_t( + std::max(std::min(((z) * 1023.f - 1.f) * 0.5f, 511.f), -512.f)) & + (X11Y11Z10N_Z_MASK >> X11Y11Z10N_Z_SHIFT)) + << X11Y11Z10N_Z_SHIFT); + const std::uint32_t xyz = uX | uY | uZ; + return xyz; } -#endif // __PS3__ +#endif // __PS3__ -void Tesselator::normal(float x, float y, float z) -{ +void Tesselator::normal(float x, float y, float z) { hasNormal = true; #ifdef __PS3__ - _normal = _ConvertF32toX11Y11Z10N(x,y,z); + _normal = _ConvertF32toX11Y11Z10N(x, y, z); #elif __PSVITA__ - // AP - casting a negative value to 'byte' on Vita results in zero. changed to a signed 8 value - std::int8_t xx = (std::int8_t) (x * 127); - std::int8_t yy = (std::int8_t) (y * 127); - std::int8_t zz = (std::int8_t) (z * 127); - _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); + // AP - casting a negative value to 'byte' on Vita results in zero. changed + // to a signed 8 value + std::int8_t xx = (std::int8_t)(x * 127); + std::int8_t yy = (std::int8_t)(y * 127); + std::int8_t zz = (std::int8_t)(z * 127); + _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); #else - // 4jcraft copied the PSVITA branch, read comment above - std::int8_t xx = (std::int8_t) (x * 127); - std::int8_t yy = (std::int8_t) (y * 127); - std::int8_t zz = (std::int8_t) (z * 127); - _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); + // 4jcraft copied the PSVITA branch, read comment above + std::int8_t xx = (std::int8_t)(x * 127); + std::int8_t yy = (std::int8_t)(y * 127); + std::int8_t zz = (std::int8_t)(z * 127); + _normal = (xx & 0xff) | ((yy & 0xff) << 8) | ((zz & 0xff) << 16); #endif } -void Tesselator::offset(float xo, float yo, float zo) -{ +void Tesselator::offset(float xo, float yo, float zo) { this->xo = xo; this->yo = yo; this->zo = zo; - // 4J added + // 4J added this->xoo = xo; this->yoo = yo; this->zoo = zo; } -void Tesselator::addOffset(float x, float y, float z) -{ +void Tesselator::addOffset(float x, float y, float z) { xo += x; yo += y; zo += z; } -bool Tesselator::hasMaxVertices() -{ +bool Tesselator::hasMaxVertices() { #ifdef __ORBIS__ - // On PS4, the way we push data to the command buffer has a maximum size of a single command packet of 2^16 bytes, - // and the effective maximum size will be slightly less than that due to packet headers and padding. - int bytes = vertices * (useCompactFormat360?16:32); + // On PS4, the way we push data to the command buffer has a maximum size of + // a single command packet of 2^16 bytes, and the effective maximum size + // will be slightly less than that due to packet headers and padding. + int bytes = vertices * (useCompactFormat360 ? 16 : 32); - return bytes > 60 * 1024; + return bytes > 60 * 1024; #else - return false; + return false; #endif } diff --git a/Minecraft.Client/Rendering/Tesselator.h b/Minecraft.Client/Rendering/Tesselator.h index eefeaa73a..02d43a12c 100644 --- a/Minecraft.Client/Rendering/Tesselator.h +++ b/Minecraft.Client/Rendering/Tesselator.h @@ -4,136 +4,133 @@ class ChunkRebuildData; class Tesselator { // private static boolean TRIANGLE_MODE = false; - friend ChunkRebuildData; + friend ChunkRebuildData; + private: - static bool TRIANGLE_MODE; + static bool TRIANGLE_MODE; static bool USE_VBO; static const int MAX_MEMORY_USE = 16 * 1024 * 1024; static const int MAX_FLOATS = MAX_MEMORY_USE / 4 / 2; - intArray *_array; + intArray* _array; int vertices; float u, v; - int _tex2; + int _tex2; int col; bool hasColor; bool hasTexture; - bool hasTexture2; + bool hasTexture2; bool hasNormal; - int p ; - bool useCompactFormat360; // 4J - added - bool useProjectedTexturePixelShader; // 4J - added + int p; + bool useCompactFormat360; // 4J - added + bool useProjectedTexturePixelShader; // 4J - added public: int count; + private: bool _noColor; int mode; float xo, yo, zo; - float xoo, yoo, zoo; + float xoo, yoo, zoo; int _normal; - // 4J - added for thread local storage + // 4J - added for thread local storage public: - static void CreateNewThreadStorage(int bytes); -private: - static unsigned int tlsIdx; -public: - static Tesselator *getInstance(); + static void CreateNewThreadStorage(int bytes); private: - bool tesselating; - bool mipmapEnable; // 4J added + static unsigned int tlsIdx; + +public: + static Tesselator* getInstance(); + +private: + bool tesselating; + bool mipmapEnable; // 4J added bool vboMode; - IntBuffer *vboIds; + IntBuffer* vboIds; int vboId; int vboCounts; int size; Tesselator(int size); -public: - Tesselator *getUniqueInstance(int size); - void end(); -private: - void clear(); - // 4J - added to handle compact quad vertex format, which need packaged up as quads - unsigned int m_ix[4],m_iy[4],m_iz[4]; - unsigned int m_clr[4]; - unsigned int m_u[4], m_v[4]; - unsigned int m_t2[4]; - void packCompactQuad(); +public: + Tesselator* getUniqueInstance(int size); + void end(); + +private: + void clear(); + + // 4J - added to handle compact quad vertex format, which need packaged up + // as quads + unsigned int m_ix[4], m_iy[4], m_iz[4]; + unsigned int m_clr[4]; + unsigned int m_u[4], m_v[4]; + unsigned int m_t2[4]; + void packCompactQuad(); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha - bool alphaCutOutEnabled; + // AP - alpha cut out is expensive on vita. Use this to defer primitives + // that use icons with alpha + bool alphaCutOutEnabled; - // this is the cut out enabled vertex array - intArray *_array2; + // this is the cut out enabled vertex array + intArray* _array2; int vertices2; int p2; #endif public: + // 4J MGH - added, to calculate tight bounds + class Bounds { + public: + void reset() { + boundingBox[0] = FLT_MAX; + boundingBox[1] = FLT_MAX; + boundingBox[2] = FLT_MAX; + boundingBox[3] = -FLT_MAX; + boundingBox[4] = -FLT_MAX; + boundingBox[5] = -FLT_MAX; + } + void addVert(float x, float y, float z) { + if (x < boundingBox[0]) boundingBox[0] = x; + if (y < boundingBox[1]) boundingBox[1] = y; + if (z < boundingBox[2]) boundingBox[2] = z; - // 4J MGH - added, to calculate tight bounds - class Bounds - { - public: - void reset() - { - boundingBox[0] = FLT_MAX; - boundingBox[1] = FLT_MAX; - boundingBox[2] = FLT_MAX; - boundingBox[3] = -FLT_MAX; - boundingBox[4] = -FLT_MAX; - boundingBox[5] = -FLT_MAX; - } - void addVert(float x, float y, float z) - { - if(x < boundingBox[0]) - boundingBox[0] = x; - if(y < boundingBox[1]) - boundingBox[1] = y; - if(z < boundingBox[2]) - boundingBox[2] = z; + if (x > boundingBox[3]) boundingBox[3] = x; + if (y > boundingBox[4]) boundingBox[4] = y; + if (z > boundingBox[5]) boundingBox[5] = z; + } + void addBounds(Bounds& ob) { + if (ob.boundingBox[0] < boundingBox[0]) + boundingBox[0] = ob.boundingBox[0]; + if (ob.boundingBox[1] < boundingBox[1]) + boundingBox[1] = ob.boundingBox[1]; + if (ob.boundingBox[2] < boundingBox[2]) + boundingBox[2] = ob.boundingBox[2]; - if(x > boundingBox[3]) - boundingBox[3] = x; - if(y > boundingBox[4]) - boundingBox[4] = y; - if(z > boundingBox[5]) - boundingBox[5] = z; - } - void addBounds(Bounds& ob) - { - if(ob.boundingBox[0] < boundingBox[0]) - boundingBox[0] = ob.boundingBox[0]; - if(ob.boundingBox[1] < boundingBox[1]) - boundingBox[1] = ob.boundingBox[1]; - if(ob.boundingBox[2] < boundingBox[2]) - boundingBox[2] = ob.boundingBox[2]; + if (ob.boundingBox[3] > boundingBox[3]) + boundingBox[3] = ob.boundingBox[3]; + if (ob.boundingBox[4] > boundingBox[4]) + boundingBox[4] = ob.boundingBox[4]; + if (ob.boundingBox[5] > boundingBox[5]) + boundingBox[5] = ob.boundingBox[5]; + } + float boundingBox[6]; // 4J MGH added - if(ob.boundingBox[3] > boundingBox[3]) - boundingBox[3] = ob.boundingBox[3]; - if(ob.boundingBox[4] > boundingBox[4]) - boundingBox[4] = ob.boundingBox[4]; - if(ob.boundingBox[5] > boundingBox[5]) - boundingBox[5] = ob.boundingBox[5]; - } - float boundingBox[6]; // 4J MGH added + } bounds; - } bounds; - - void begin(); + void begin(); void begin(int mode); - void useCompactVertices(bool enable); // 4J added - bool getCompactVertices(); // AP added - void useProjectedTexture(bool enable); // 4J added + void useCompactVertices(bool enable); // 4J added + bool getCompactVertices(); // AP added + void useProjectedTexture(bool enable); // 4J added void tex(float u, float v); - void tex2(int tex2); // 4J - change brought forward from 1.8.2 + void tex2(int tex2); // 4J - change brought forward from 1.8.2 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); @@ -147,32 +144,34 @@ public: void normal(float x, float y, float z); void offset(float xo, float yo, float zo); void addOffset(float x, float y, float z); - bool setMipmapEnable(bool enable); // 4J added + bool setMipmapEnable(bool enable); // 4J added - bool hasMaxVertices(); // 4J Added + bool hasMaxVertices(); // 4J Added #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita. Use this to defer primitives that use icons with alpha - void setAlphaCutOut(bool enable); - bool getCutOutFound(); + // AP - alpha cut out is expensive on vita. Use this to defer primitives + // that use icons with alpha + void setAlphaCutOut(bool enable); + bool getCutOutFound(); - // AP - a faster way of creating a compressed tile quad - void tileQuad(float x1, float y1, float z1, float u1, float v1, float r1, float g1, float b1, int tex1, - float x2, float y2, float z2, float u2, float v2, float r2, float g2, float b2, int tex2, - float x3, float y3, float z3, float u3, float v3, float r3, float g3, float b3, int tex3, - float x4, float y4, float z4, float u4, float v4, float r4, float g4, float b4, int tex4); - // AP - a faster way of creating rain quads - void tileRainQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1, - float r2, float g2, float b2, float a2, int tex1); - // AP - a faster way of creating particles - void tileParticleQuad(float x1, float y1, float z1, float u1, float v1, - float x2, float y2, float z2, float u2, float v2, - float x3, float y3, float z3, float u3, float v3, - float x4, float y4, float z4, float u4, float v4, - float r1, float g1, float b1, float a1); + // AP - a faster way of creating a compressed tile quad + void tileQuad(float x1, float y1, float z1, float u1, float v1, float r1, + float g1, float b1, int tex1, float x2, float y2, float z2, + float u2, float v2, float r2, float g2, float b2, int tex2, + float x3, float y3, float z3, float u3, float v3, float r3, + float g3, float b3, int tex3, float x4, float y4, float z4, + float u4, float v4, float r4, float g4, float b4, int tex4); + // AP - a faster way of creating rain quads + void tileRainQuad(float x1, float y1, float z1, float u1, float v1, + float x2, float y2, float z2, float u2, float v2, + float x3, float y3, float z3, float u3, float v3, + float x4, float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1, float r2, + float g2, float b2, float a2, int tex1); + // AP - a faster way of creating particles + void tileParticleQuad(float x1, float y1, float z1, float u1, float v1, + float x2, float y2, float z2, float u2, float v2, + float x3, float y3, float z3, float u3, float v3, + float x4, float y4, float z4, float u4, float v4, + float r1, float g1, float b1, float a1); #endif - }; diff --git a/Minecraft.Client/Rendering/TexOffs.cpp b/Minecraft.Client/Rendering/TexOffs.cpp index 372023966..4cb40a021 100644 --- a/Minecraft.Client/Rendering/TexOffs.cpp +++ b/Minecraft.Client/Rendering/TexOffs.cpp @@ -1,9 +1,4 @@ #include "../Platform/stdafx.h" #include "TexOffs.h" -TexOffs::TexOffs(int x, int y) : -x(x), -y(y) -{ - -} \ No newline at end of file +TexOffs::TexOffs(int x, int y) : x(x), y(y) {} \ No newline at end of file diff --git a/Minecraft.Client/Rendering/TexOffs.h b/Minecraft.Client/Rendering/TexOffs.h index df3c22b71..367add126 100644 --- a/Minecraft.Client/Rendering/TexOffs.h +++ b/Minecraft.Client/Rendering/TexOffs.h @@ -1,9 +1,8 @@ #pragma once -class TexOffs -{ +class TexOffs { public: - const int x, y; + const int x, y; - TexOffs(int x, int y); + TexOffs(int x, int y); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/Vertex.cpp b/Minecraft.Client/Rendering/Vertex.cpp index 42c79ac3e..b4c70ae19 100644 --- a/Minecraft.Client/Rendering/Vertex.cpp +++ b/Minecraft.Client/Rendering/Vertex.cpp @@ -1,27 +1,21 @@ #include "../Platform/stdafx.h" #include "Vertex.h" -Vertex::Vertex(float x, float y, float z, float u, float v) -{ - this->pos = Vec3::newPermanent(x,y,z); +Vertex::Vertex(float x, float y, float z, float u, float v) { + this->pos = Vec3::newPermanent(x, y, z); this->u = u; this->v = v; } -Vertex *Vertex::remap(float u, float v) -{ - return new Vertex(this, u, v); -} +Vertex* Vertex::remap(float u, float v) { return new Vertex(this, u, v); } -Vertex::Vertex(Vertex *vertex, float u, float v) -{ +Vertex::Vertex(Vertex* vertex, float u, float v) { this->pos = vertex->pos; this->u = u; this->v = v; } -Vertex::Vertex(Vec3 *pos, float u, float v) -{ +Vertex::Vertex(Vec3* pos, float u, float v) { this->pos = pos; this->u = u; this->v = v; diff --git a/Minecraft.Client/Rendering/Vertex.h b/Minecraft.Client/Rendering/Vertex.h index 0c446ddea..99166d1ee 100644 --- a/Minecraft.Client/Rendering/Vertex.h +++ b/Minecraft.Client/Rendering/Vertex.h @@ -1,14 +1,14 @@ #pragma once #include "../../Minecraft.World/Util/Vec3.h" -class Vertex -{ +class Vertex { public: - Vec3 *pos; - float u,v; + Vec3* pos; + float u, v; + public: - Vertex(float x, float y, float z, float u, float v); - Vertex *remap(float u, float v); - Vertex(Vertex *vertex, float u, float v); - Vertex(Vec3 *pos, float u, float v); + Vertex(float x, float y, float z, float u, float v); + Vertex* remap(float u, float v); + Vertex(Vertex* vertex, float u, float v); + Vertex(Vec3* pos, float u, float v); }; \ No newline at end of file diff --git a/Minecraft.Client/Rendering/glWrapper.cpp b/Minecraft.Client/Rendering/glWrapper.cpp index 7b13fc285..c1a3628ef 100644 --- a/Minecraft.Client/Rendering/glWrapper.cpp +++ b/Minecraft.Client/Rendering/glWrapper.cpp @@ -6,389 +6,312 @@ #include "../../Minecraft.World/IO/Streams/IntBuffer.h" #include "../../Minecraft.World/IO/Streams/ByteBuffer.h" -void glViewport(int x, int y, int w, int h) -{ - // We don't really need anything here because minecraft doesn't current do anything other than the default viewport +void glViewport(int x, int y, int w, int h) { + // We don't really need anything here because minecraft doesn't current do + // anything other than the default viewport } -void glTranslatef(float x,float y,float z) -{ - RenderManager.MatrixTranslate(x,y,z); +void glTranslatef(float x, float y, float z) { + RenderManager.MatrixTranslate(x, y, z); } -void glRotatef(float angle, float x, float y, float z) -{ - RenderManager.MatrixRotate(angle*(PI/180.0f),x,y,z); +void glRotatef(float angle, float x, float y, float z) { + RenderManager.MatrixRotate(angle * (PI / 180.0f), x, y, z); } -void glPopMatrix() -{ - RenderManager.MatrixPop(); +void glPopMatrix() { RenderManager.MatrixPop(); } + +void glPushMatrix() { RenderManager.MatrixPush(); } + +void glScalef(float x, float y, float z) { RenderManager.MatrixScale(x, y, z); } + +void glMultMatrixf(float* m) { RenderManager.MatrixMult(m); } + +void glMatrixMode(int type) { RenderManager.MatrixMode(type); } + +void glLoadIdentity() { RenderManager.MatrixSetIdentity(); } + +void gluPerspective(float fovy, float aspect, float zNear, float zFar) { + RenderManager.MatrixPerspective(fovy, aspect, zNear, zFar); } -void glPushMatrix() -{ - RenderManager.MatrixPush(); +void glOrtho(float left, float right, float bottom, float top, float zNear, + float zFar) { + RenderManager.MatrixOrthogonal(left, right, bottom, top, zNear, zFar); } -void glScalef(float x, float y, float z) -{ - RenderManager.MatrixScale(x,y,z); +void glScaled(double x, double y, double z) { + RenderManager.MatrixScale((float)x, (float)y, (float)z); } -void glMultMatrixf(float *m) -{ - RenderManager.MatrixMult(m); +void glGetFloat(int type, FloatBuffer* buff) { + memcpy(buff->_getDataPointer(), RenderManager.MatrixGet(type), 64); } -void glMatrixMode(int type) -{ - RenderManager.MatrixMode(type); +void glDeleteLists(int first, int count) { + RenderManager.CBuffDelete(first, count); } -void glLoadIdentity() -{ - RenderManager.MatrixSetIdentity(); -} +int glGenLists(int count) { return RenderManager.CBuffCreate(count); } -void gluPerspective(float fovy, float aspect, float zNear, float zFar) -{ - RenderManager.MatrixPerspective(fovy,aspect,zNear,zFar); -} +void glNewList(int index, int mode) { RenderManager.CBuffStart(index); } -void glOrtho(float left,float right,float bottom,float top,float zNear,float zFar) -{ - RenderManager.MatrixOrthogonal(left,right,bottom,top,zNear,zFar); -} - -void glScaled(double x,double y,double z) -{ - RenderManager.MatrixScale((float)x,(float)y,(float)z); -} - -void glGetFloat(int type, FloatBuffer *buff) -{ - memcpy(buff->_getDataPointer(),RenderManager.MatrixGet(type),64); -} - -void glDeleteLists(int first,int count) -{ - RenderManager.CBuffDelete(first,count); -} - -int glGenLists(int count) -{ - return RenderManager.CBuffCreate(count); -} - -void glNewList(int index, int mode) -{ - RenderManager.CBuffStart(index); -} - -void glEndList(int vertexCount) -{ +void glEndList(int vertexCount) { #ifdef _XBOX - RenderManager.CBuffEnd(vertexCount); + RenderManager.CBuffEnd(vertexCount); #else - RenderManager.CBuffEnd(); + RenderManager.CBuffEnd(); #endif } -void glCallList(int index) -{ - RenderManager.CBuffCall(index); +void glCallList(int index) { RenderManager.CBuffCall(index); } + +void glCallLists(IntBuffer* ib) { + for (unsigned int i = 0; i < ib->limit(); i++) { + RenderManager.CBuffCall(ib->get(i)); + } } -void glCallLists(IntBuffer *ib) -{ - for(unsigned int i = 0; i < ib->limit(); i++) - { - RenderManager.CBuffCall(ib->get(i)); - } -} +void glClear(int flags) { RenderManager.Clear(flags); } -void glClear(int flags) -{ - RenderManager.Clear(flags); -} - -void glClearColor(float r, float g, float b, float a) -{ +void glClearColor(float r, float g, float b, float a) { #ifdef _XBOX - int ir = (int)(r * 255.0f); if( ir < 0 ) ir = 0; if( ir > 255 ) ir = 255; - int ig = (int)(g * 255.0f); if( ig < 0 ) ig = 0; if( ig > 255 ) ig = 255; - int ib = (int)(b * 255.0f); if( ib < 0 ) ib = 0; if( ib > 255 ) ib = 255; - int ia = (int)(a * 255.0f); if( ia < 0 ) ia = 0; if( ia > 255 ) ia = 255; + int ir = (int)(r * 255.0f); + if (ir < 0) ir = 0; + if (ir > 255) ir = 255; + int ig = (int)(g * 255.0f); + if (ig < 0) ig = 0; + if (ig > 255) ig = 255; + int ib = (int)(b * 255.0f); + if (ib < 0) ib = 0; + if (ib > 255) ib = 255; + int ia = (int)(a * 255.0f); + if (ia < 0) ia = 0; + if (ia > 255) ia = 255; - RenderManager.SetClearColour(D3DCOLOR_RGBA(ir,ig,ib,ia)); + RenderManager.SetClearColour(D3DCOLOR_RGBA(ir, ig, ib, ia)); #else - float rgba[4] = {r,g,b,a}; - RenderManager.SetClearColour(rgba); + float rgba[4] = {r, g, b, a}; + RenderManager.SetClearColour(rgba); #endif } -void Display::update() -{ +void Display::update() {} + +void Display::swapBuffers() {} + +void glBindTexture(int target, int texture) { + RenderManager.TextureBind(texture); } -void Display::swapBuffers() -{ +void glTexImage2D(int target, int level, int internalformat, int width, + int height, int border, int format, int type, + ByteBuffer* data) { + RenderManager.TextureData(width, height, data->getBuffer(), level); } -void glBindTexture(int target,int texture) -{ - RenderManager.TextureBind(texture); -} - -void glTexImage2D(int target,int level,int internalformat,int width,int height,int border,int format,int type, ByteBuffer *data) -{ - RenderManager.TextureData(width,height,data->getBuffer(),level); -} - -void glDeleteTextures(IntBuffer *ib) -{ - for(unsigned int i = 0; i < ib->limit(); i++) - { - RenderManager.TextureFree(ib->get(i)); - } +void glDeleteTextures(IntBuffer* ib) { + for (unsigned int i = 0; i < ib->limit(); i++) { + RenderManager.TextureFree(ib->get(i)); + } } // 4J Stu - I'm pretty sure this is what it should do -void glDeleteTextures(int id) -{ - RenderManager.TextureFree(id); -} +void glDeleteTextures(int id) { RenderManager.TextureFree(id); } -void glGenTextures(IntBuffer *ib) -{ - for(unsigned int i = 0; i < ib->limit(); i++) - { - ib->put(RenderManager.TextureCreate()); - } +void glGenTextures(IntBuffer* ib) { + for (unsigned int i = 0; i < ib->limit(); i++) { + ib->put(RenderManager.TextureCreate()); + } } // 4J Stu - I'm pretty sure this is what it should do -int glGenTextures() -{ - return RenderManager.TextureCreate(); +int glGenTextures() { return RenderManager.TextureCreate(); } + +void glColor3f(float r, float g, float b) { + RenderManager.StateSetColour(r, g, b, 1.0f); } -void glColor3f(float r, float g, float b) -{ - RenderManager.StateSetColour(r,g,b,1.0f); +void glColor4f(float r, float g, float b, float a) { + RenderManager.StateSetColour(r, g, b, a); } -void glColor4f(float r, float g, float b, float a) -{ - RenderManager.StateSetColour(r,g,b,a); +void glDisable(int state) { + switch (state) { + case GL_TEXTURE_2D: + RenderManager.TextureBind(-1); + break; + case GL_BLEND: + RenderManager.StateSetBlendEnable(false); + break; + case GL_CULL_FACE: + RenderManager.StateSetFaceCull(false); + break; + case GL_DEPTH_TEST: + RenderManager.StateSetDepthTestEnable(false); + break; + case GL_ALPHA_TEST: + RenderManager.StateSetAlphaTestEnable(false); + break; + case GL_FOG: + RenderManager.StateSetFogEnable(false); + break; + case GL_LIGHTING: + RenderManager.StateSetLightingEnable(false); + break; + case GL_LIGHT0: + RenderManager.StateSetLightEnable(0, false); + break; + case GL_LIGHT1: + RenderManager.StateSetLightEnable(1, false); + break; + } } -void glDisable(int state) -{ - switch(state) - { - case GL_TEXTURE_2D: - RenderManager.TextureBind(-1); - break; - case GL_BLEND: - RenderManager.StateSetBlendEnable(false); - break; - case GL_CULL_FACE: - RenderManager.StateSetFaceCull(false); - break; - case GL_DEPTH_TEST: - RenderManager.StateSetDepthTestEnable(false); - break; - case GL_ALPHA_TEST: - RenderManager.StateSetAlphaTestEnable(false); - break; - case GL_FOG: - RenderManager.StateSetFogEnable(false); - break; - case GL_LIGHTING: - RenderManager.StateSetLightingEnable(false); - break; - case GL_LIGHT0: - RenderManager.StateSetLightEnable(0,false); - break; - case GL_LIGHT1: - RenderManager.StateSetLightEnable(1,false); - break; - } +void glEnable(int state) { + switch (state) { + case GL_BLEND: + RenderManager.StateSetBlendEnable(true); + break; + case GL_CULL_FACE: + RenderManager.StateSetFaceCull(true); + break; + case GL_DEPTH_TEST: + RenderManager.StateSetDepthTestEnable(true); + break; + case GL_ALPHA_TEST: + RenderManager.StateSetAlphaTestEnable(true); + break; + case GL_FOG: + RenderManager.StateSetFogEnable(true); + break; + case GL_LIGHTING: + RenderManager.StateSetLightingEnable(true); + break; + case GL_LIGHT0: + RenderManager.StateSetLightEnable(0, true); + break; + case GL_LIGHT1: + RenderManager.StateSetLightEnable(1, true); + break; + } } -void glEnable(int state) -{ - switch(state) - { - case GL_BLEND: - RenderManager.StateSetBlendEnable(true); - break; - case GL_CULL_FACE: - RenderManager.StateSetFaceCull(true); - break; - case GL_DEPTH_TEST: - RenderManager.StateSetDepthTestEnable(true); - break; - case GL_ALPHA_TEST: - RenderManager.StateSetAlphaTestEnable(true); - break; - case GL_FOG: - RenderManager.StateSetFogEnable(true); - break; - case GL_LIGHTING: - RenderManager.StateSetLightingEnable(true); - break; - case GL_LIGHT0: - RenderManager.StateSetLightEnable(0,true); - break; - case GL_LIGHT1: - RenderManager.StateSetLightEnable(1,true); - break; - } +void glDepthMask(bool enable) { RenderManager.StateSetDepthMask(enable); } + +void glBlendFunc(int src, int dst) { + RenderManager.StateSetBlendFunc(src, dst); } -void glDepthMask(bool enable) -{ - RenderManager.StateSetDepthMask(enable); +void glAlphaFunc(int func, float param) { + RenderManager.StateSetAlphaFunc(func, param); } -void glBlendFunc(int src, int dst) -{ - RenderManager.StateSetBlendFunc(src,dst); -} - -void glAlphaFunc(int func,float param) -{ - RenderManager.StateSetAlphaFunc(func, param); -} - -void glDepthFunc(int func) -{ +void glDepthFunc(int func) { #ifdef _XBOX - RenderManager.StateSetDepthFunc(func); + RenderManager.StateSetDepthFunc(func); #else - RenderManager.StateSetDepthFunc(func); + RenderManager.StateSetDepthFunc(func); #endif } -void glTexParameteri(int target, int param, int value) -{ - RenderManager.TextureSetParam(param,value); +void glTexParameteri(int target, int param, int value) { + RenderManager.TextureSetParam(param, value); } -void glPolygonOffset(float factor, float units) -{ +void glPolygonOffset(float factor, float units) { #ifdef __PS3__ - RenderManager.StateSetDepthSlopeAndBias(factor, units); + RenderManager.StateSetDepthSlopeAndBias(factor, units); #else - // DirectX specifies these offsets in z buffer 0 to 1 sort of range, whereas opengl seems to be in a 0 -> depth buffer size sort of range. - // The slope factor is quite possibly different too. Magic factor for now anyway. - const float magicFactor = 65536.0f; - RenderManager.StateSetDepthSlopeAndBias(factor / magicFactor, units / magicFactor); + // DirectX specifies these offsets in z buffer 0 to 1 sort of range, whereas + // opengl seems to be in a 0 -> depth buffer size sort of range. The slope + // factor is quite possibly different too. Magic factor for now anyway. + const float magicFactor = 65536.0f; + RenderManager.StateSetDepthSlopeAndBias(factor / magicFactor, + units / magicFactor); #endif } -void glFogi(int param, int value) -{ - if( param == GL_FOG_MODE ) - { - RenderManager.StateSetFogMode(value); - } +void glFogi(int param, int value) { + if (param == GL_FOG_MODE) { + RenderManager.StateSetFogMode(value); + } } -void glFogf(int param, float value) -{ - switch(param) - { - case GL_FOG_START: - RenderManager.StateSetFogNearDistance(value); - break; - case GL_FOG_END: - RenderManager.StateSetFogFarDistance(value); - break; - case GL_FOG_DENSITY: - RenderManager.StateSetFogDensity(value); - break; - } +void glFogf(int param, float value) { + switch (param) { + case GL_FOG_START: + RenderManager.StateSetFogNearDistance(value); + break; + case GL_FOG_END: + RenderManager.StateSetFogFarDistance(value); + break; + case GL_FOG_DENSITY: + RenderManager.StateSetFogDensity(value); + break; + } } -void glFog(int param,FloatBuffer *values) -{ - if( param == GL_FOG_COLOR ) - { - float *data = values->_getDataPointer(); - RenderManager.StateSetFogColour(data[0],data[1],data[2]); - } +void glFog(int param, FloatBuffer* values) { + if (param == GL_FOG_COLOR) { + float* data = values->_getDataPointer(); + RenderManager.StateSetFogColour(data[0], data[1], data[2]); + } } -void glLight(int light, int mode,FloatBuffer *values) -{ - int idx; - if( light == GL_LIGHT0 ) - { - idx = 0; - } - else if( light == GL_LIGHT1 ) - { - idx = 1; - } - else return; - float *data =values->_getDataPointer(); - switch( mode ) - { - case GL_POSITION: - RenderManager.StateSetLightDirection(idx, data[0], data[1], data[2]); - break; - case GL_DIFFUSE: - RenderManager.StateSetLightColour(idx, data[0], data[1], data[2]); - break; - case GL_AMBIENT: - break; - case GL_SPECULAR: - break; - } +void glLight(int light, int mode, FloatBuffer* values) { + int idx; + if (light == GL_LIGHT0) { + idx = 0; + } else if (light == GL_LIGHT1) { + idx = 1; + } else + return; + float* data = values->_getDataPointer(); + switch (mode) { + case GL_POSITION: + RenderManager.StateSetLightDirection(idx, data[0], data[1], + data[2]); + break; + case GL_DIFFUSE: + RenderManager.StateSetLightColour(idx, data[0], data[1], data[2]); + break; + case GL_AMBIENT: + break; + case GL_SPECULAR: + break; + } } -void glLightModel(int mode, FloatBuffer *values) -{ - float *data =values->_getDataPointer(); - if( mode == GL_LIGHT_MODEL_AMBIENT ) - { - RenderManager.StateSetLightAmbientColour(data[0],data[1],data[2]); - } +void glLightModel(int mode, FloatBuffer* values) { + float* data = values->_getDataPointer(); + if (mode == GL_LIGHT_MODEL_AMBIENT) { + RenderManager.StateSetLightAmbientColour(data[0], data[1], data[2]); + } } -void glLineWidth(float width) -{ - RenderManager.StateSetLineWidth(width); +void glLineWidth(float width) { RenderManager.StateSetLineWidth(width); } + +void glColorMask(bool red, bool green, bool blue, bool alpha) { + RenderManager.StateSetWriteEnable(red, green, blue, alpha); } -void glColorMask(bool red, bool green, bool blue, bool alpha) -{ - RenderManager.StateSetWriteEnable(red, green, blue, alpha); +void glMultiTexCoord2f(int, float u, float v) { + // Clamp these values just to be safe - the lighting code can get broken if + // we pass things to StateSetVertexTextureUV that are >= 1 + if (u > 255.0f) u = 255.0f; + if (v > 255.0f) v = 255.0f; + + RenderManager.StateSetVertexTextureUV(u / 256.0f, v / 256.0f); } -void glMultiTexCoord2f(int, float u , float v) -{ - // Clamp these values just to be safe - the lighting code can get broken if we pass things to StateSetVertexTextureUV that are >= 1 - if( u > 255.0f ) u = 255.0f; - if( v > 255.0f ) v = 255.0f; +void glTexGen(int coord, int mode, FloatBuffer* vec) { + float* data = vec->_getDataPointer(); - RenderManager.StateSetVertexTextureUV( u / 256.0f, v / 256.0f); + RenderManager.StateSetTexGenCol(coord, data[0], data[1], data[2], data[3], + mode == GL_EYE_PLANE); } -void glTexGen(int coord, int mode, FloatBuffer *vec) -{ - float *data = vec->_getDataPointer(); - - RenderManager.StateSetTexGenCol( coord, data[0], data[1], data[2], data[3], mode == GL_EYE_PLANE ); -} - -void glCullFace(int dir) -{ - RenderManager.StateSetFaceCullCW( dir == GL_BACK); -} +void glCullFace(int dir) { RenderManager.StateSetFaceCullCW(dir == GL_BACK); } #endif diff --git a/Minecraft.Client/Textures/BufferedImage.cpp b/Minecraft.Client/Textures/BufferedImage.cpp index d8065851f..0c505003d 100644 --- a/Minecraft.Client/Textures/BufferedImage.cpp +++ b/Minecraft.Client/Textures/BufferedImage.cpp @@ -1,400 +1,336 @@ -#include "../Platform/stdafx.h" +#include "../Platform/stdafx.h" #include "../../Minecraft.World/Util/StringHelpers.h" #include "Textures.h" #include "../../Minecraft.World/Util/ArrayWithLength.h" #include "BufferedImage.h" #ifdef _XBOX -typedef struct -{ - unsigned int filesz; - unsigned short creator1; - unsigned short creator2; - unsigned int bmp_offset; - unsigned int header_sz; - unsigned int width; - unsigned int height; - unsigned short nplanes; - unsigned short bitspp; - unsigned int compress_type; - unsigned int bmp_bytesz; - int hres; - int vres; - unsigned int ncolors; - unsigned int nimpcolors; +typedef struct { + unsigned int filesz; + unsigned short creator1; + unsigned short creator2; + unsigned int bmp_offset; + unsigned int header_sz; + unsigned int width; + unsigned int height; + unsigned short nplanes; + unsigned short bitspp; + unsigned int compress_type; + unsigned int bmp_bytesz; + int hres; + int vres; + unsigned int ncolors; + unsigned int nimpcolors; } BITMAPINFOHEADER; #endif -BufferedImage::BufferedImage(int width,int height,int type) -{ - data[0] = new int[width*height]; +BufferedImage::BufferedImage(int width, int height, int type) { + data[0] = new int[width * height]; - for( int i = 1 ; i < 10; i++ ) - { - data[i] = NULL; - } - this->width = width; - this->height = height; + for (int i = 1; i < 10; i++) { + data[i] = NULL; + } + this->width = width; + this->height = height; } -void BufferedImage::ByteFlip4(unsigned int &data) -{ - data = ( data >> 24 ) | - ( ( data >> 8 ) & 0x0000ff00 ) | - ( ( data << 8 ) & 0x00ff0000 ) | - ( data << 24 ); +void BufferedImage::ByteFlip4(unsigned int& data) { + data = (data >> 24) | ((data >> 8) & 0x0000ff00) | + ((data << 8) & 0x00ff0000) | (data << 24); } -// Loads a bitmap into a buffered image - only currently supports the 2 types of 32-bit image that we've made so far -// and determines which of these is which by the compression method. Compression method 3 is a 32-bit image with only -// 24-bits used (ie no alpha channel) whereas method 0 is a full 32-bit image with a valid alpha channel. -BufferedImage::BufferedImage(const std::wstring& File, bool filenameHasExtension /*=false*/, bool bTitleUpdateTexture /*=false*/, const std::wstring &drive /*=L""*/) -{ - HRESULT hr; - std::wstring wDrive; - std::wstring filePath; - filePath = File; +// Loads a bitmap into a buffered image - only currently supports the 2 types of +// 32-bit image that we've made so far and determines which of these is which by +// the compression method. Compression method 3 is a 32-bit image with only +// 24-bits used (ie no alpha channel) whereas method 0 is a full 32-bit image +// with a valid alpha channel. +BufferedImage::BufferedImage(const std::wstring& File, + bool filenameHasExtension /*=false*/, + bool bTitleUpdateTexture /*=false*/, + const std::wstring& drive /*=L""*/) { + HRESULT hr; + std::wstring wDrive; + std::wstring filePath; + filePath = File; - wDrive = drive; - if(wDrive.empty()) - { + wDrive = drive; + if (wDrive.empty()) { #ifdef _XBOX - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed #ifdef _TU_BUILD - wDrive=L"UPDATE:\\"; + wDrive = L"UPDATE:\\"; #else - wDrive=L"GAME:\\res\\TitleUpdate\\"; + wDrive = L"GAME:\\res\\TitleUpdate\\"; #endif - } - else - { - wDrive=L"GAME:\\"; - } + } else { + wDrive = L"GAME:\\"; + } #else #ifdef __PS3__ - char *pchUsrDir; - if(app.GetBootedFromDiscPatch()) - { - const char *pchTextureName=wstringtofilename(File); - pchUsrDir = app.GetBDUsrDirPath(pchTextureName); - } - else - { - pchUsrDir=getUsrDirPath(); - } + char* pchUsrDir; + if (app.GetBootedFromDiscPatch()) { + const char* pchTextureName = wstringtofilename(File); + pchUsrDir = app.GetBDUsrDirPath(pchTextureName); + } else { + pchUsrDir = getUsrDirPath(); + } - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"/Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = wstr + L"\\Common\\res\\TitleUpdate\\"; + } else { + wDrive = wstr + L"/Common/"; + } #elif __PSVITA__ - /*char *pchUsrDir=getUsrDirPath(); + /*char *pchUsrDir=getUsrDirPath(); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"/Common/"; - }*/ + if(bTitleUpdateTexture) + { + // Make the content package point to to the UPDATE: drive is + needed wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; + } + else + { + wDrive= wstr + L"/Common/"; + }*/ - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= L"Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = L"Common/"; + } #else - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= L"Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = L"Common/"; + } #endif #endif - } + } - for( int l = 0 ; l < 10; l++ ) - { - data[l] = NULL; - } + for (int l = 0; l < 10; l++) { + data[l] = NULL; + } - for( int l = 0; l < 10; l++ ) - { - std::wstring name; - std::wstring mipMapPath = L""; - if( l != 0 ) - { - mipMapPath = L"MipMapLevel" + _toString(l+1); - } - if( filenameHasExtension ) - { - name = wDrive + L"res" + filePath.substr(0,filePath.length()); - } - else - { - name = wDrive + L"res" + filePath.substr(0,filePath.length()-4) + mipMapPath + L".png"; - } + for (int l = 0; l < 10; l++) { + std::wstring name; + std::wstring mipMapPath = L""; + if (l != 0) { + mipMapPath = L"MipMapLevel" + _toString(l + 1); + } + if (filenameHasExtension) { + name = wDrive + L"res" + filePath.substr(0, filePath.length()); + } else { + name = wDrive + L"res" + filePath.substr(0, filePath.length() - 4) + + mipMapPath + L".png"; + } - const char *pchTextureName=wstringtofilename(name); + const char* pchTextureName = wstringtofilename(name); #ifdef _DEBUG - app.DebugPrintf("\n--- Loading TEXTURE - %s\n\n",pchTextureName); + app.DebugPrintf("\n--- Loading TEXTURE - %s\n\n", pchTextureName); #endif - D3DXIMAGE_INFO ImageInfo; - ZeroMemory(&ImageInfo,sizeof(D3DXIMAGE_INFO)); - hr=RenderManager.LoadTextureData(pchTextureName,&ImageInfo,&data[l]); + D3DXIMAGE_INFO ImageInfo; + ZeroMemory(&ImageInfo, sizeof(D3DXIMAGE_INFO)); + hr = + RenderManager.LoadTextureData(pchTextureName, &ImageInfo, &data[l]); + if (hr != ERROR_SUCCESS) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - if(hr!=ERROR_SUCCESS) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } - - if( l == 0 ) - { - width=ImageInfo.Width; - height=ImageInfo.Height; - } - } + if (l == 0) { + width = ImageInfo.Width; + height = ImageInfo.Height; + } + } } -BufferedImage::BufferedImage(DLCPack *dlcPack, const std::wstring& File, bool filenameHasExtension /*= false*/ ) -{ - HRESULT hr; - std::wstring filePath = File; - std::uint8_t *pbData = NULL; - std::uint32_t dataBytes = 0; +BufferedImage::BufferedImage(DLCPack* dlcPack, const std::wstring& File, + bool filenameHasExtension /*= false*/) { + HRESULT hr; + std::wstring filePath = File; + std::uint8_t* pbData = NULL; + std::uint32_t dataBytes = 0; - for( int l = 0 ; l < 10; l++ ) - { - data[l] = NULL; - } + for (int l = 0; l < 10; l++) { + data[l] = NULL; + } - for( int l = 0; l < 10; l++ ) - { - std::wstring name; - std::wstring mipMapPath = L""; - if( l != 0 ) - { - mipMapPath = L"MipMapLevel" + _toString(l+1); - } - if( filenameHasExtension ) - { - name = L"res" + filePath.substr(0,filePath.length()); - } - else - { - name = L"res" + filePath.substr(0,filePath.length()-4) + mipMapPath + L".png"; - } + for (int l = 0; l < 10; l++) { + std::wstring name; + std::wstring mipMapPath = L""; + if (l != 0) { + mipMapPath = L"MipMapLevel" + _toString(l + 1); + } + if (filenameHasExtension) { + name = L"res" + filePath.substr(0, filePath.length()); + } else { + name = L"res" + filePath.substr(0, filePath.length() - 4) + + mipMapPath + L".png"; + } - if(!dlcPack->doesPackContainFile(DLCManager::e_DLCType_All, name)) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } + if (!dlcPack->doesPackContainFile(DLCManager::e_DLCType_All, name)) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - DLCFile *dlcFile = dlcPack->getFile(DLCManager::e_DLCType_All, name); - pbData = dlcFile->getData(dataBytes); - if(pbData == NULL || dataBytes == 0) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } + DLCFile* dlcFile = dlcPack->getFile(DLCManager::e_DLCType_All, name); + pbData = dlcFile->getData(dataBytes); + if (pbData == NULL || dataBytes == 0) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - D3DXIMAGE_INFO ImageInfo; - ZeroMemory(&ImageInfo,sizeof(D3DXIMAGE_INFO)); - hr=RenderManager.LoadTextureData(pbData,dataBytes,&ImageInfo,&data[l]); + D3DXIMAGE_INFO ImageInfo; + ZeroMemory(&ImageInfo, sizeof(D3DXIMAGE_INFO)); + hr = RenderManager.LoadTextureData(pbData, dataBytes, &ImageInfo, + &data[l]); + if (hr != ERROR_SUCCESS) { + // 4J - If we haven't loaded the non-mipmap version then exit the + // game + if (l == 0) { + app.FatalLoadError(); + } + return; + } - if(hr!=ERROR_SUCCESS) - { - // 4J - If we haven't loaded the non-mipmap version then exit the game - if( l == 0 ) - { - app.FatalLoadError(); - } - return; - } - - if( l == 0 ) - { - width=ImageInfo.Width; - height=ImageInfo.Height; - } - } + if (l == 0) { + width = ImageInfo.Width; + height = ImageInfo.Height; + } + } } +BufferedImage::BufferedImage(std::uint8_t* pbData, std::uint32_t dataBytes) { + int iCurrentByte = 0; + for (int l = 0; l < 10; l++) { + data[l] = NULL; + } -BufferedImage::BufferedImage(std::uint8_t *pbData, std::uint32_t dataBytes) -{ - int iCurrentByte=0; - for( int l = 0 ; l < 10; l++ ) - { - data[l] = NULL; - } + D3DXIMAGE_INFO ImageInfo; + ZeroMemory(&ImageInfo, sizeof(D3DXIMAGE_INFO)); + HRESULT hr = + RenderManager.LoadTextureData(pbData, dataBytes, &ImageInfo, &data[0]); - D3DXIMAGE_INFO ImageInfo; - ZeroMemory(&ImageInfo,sizeof(D3DXIMAGE_INFO)); - HRESULT hr=RenderManager.LoadTextureData(pbData,dataBytes,&ImageInfo,&data[0]); - - if(hr==ERROR_SUCCESS) - { - width=ImageInfo.Width; - height=ImageInfo.Height; - } - else - { - app.FatalLoadError(); - } + if (hr == ERROR_SUCCESS) { + width = ImageInfo.Width; + height = ImageInfo.Height; + } else { + app.FatalLoadError(); + } } -BufferedImage::~BufferedImage() -{ - for(int i = 0; i < 10; i++ ) - { - delete[] data[i]; - } +BufferedImage::~BufferedImage() { + for (int i = 0; i < 10; i++) { + delete[] data[i]; + } } -int BufferedImage::getWidth() -{ - return width; +int BufferedImage::getWidth() { return width; } + +int BufferedImage::getHeight() { return height; } + +void BufferedImage::getRGB(int startX, int startY, int w, int h, intArray out, + int offset, int scansize, int level) { + int ww = width >> level; + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + out[y * scansize + offset + x] = + data[level][startX + x + ww * (startY + y)]; + } + } } -int BufferedImage::getHeight() -{ - return height; +int* BufferedImage::getData() { return data[0]; } + +int* BufferedImage::getData(int level) { return data[level]; } + +Graphics* BufferedImage::getGraphics() { return NULL; } + +// Returns the transparency. Returns either OPAQUE, BITMASK, or TRANSLUCENT. +// Specified by: +// getTransparency in interface Transparency +// Returns: +// the transparency of this BufferedImage. +int BufferedImage::getTransparency() { + // TODO - 4J Implement? + return 0; } -void BufferedImage::getRGB(int startX, int startY, int w, int h, intArray out,int offset,int scansize, int level) -{ - int ww = width >> level; - for( int y = 0; y < h; y++ ) - { - for( int x = 0; x < w; x++ ) - { - out[ y * scansize + offset + x] = data[level][ startX + x + ww * ( startY + y ) ]; - } - } +// Returns a subimage defined by a specified rectangular region. The returned +// BufferedImage shares the same data array as the original image. Parameters: +// x, y - the coordinates of the upper-left corner of the specified rectangular +// region w - the width of the specified rectangular region h - the height of +// the specified rectangular region Returns: a BufferedImage that is the +// subimage of this BufferedImage. +BufferedImage* BufferedImage::getSubimage(int x, int y, int w, int h) { + // TODO - 4J Implement + + BufferedImage* img = new BufferedImage(w, h, 0); + intArray arrayWrapper(img->data[0], w * h); + this->getRGB(x, y, w, h, arrayWrapper, 0, w); + + int level = 1; + while (getData(level) != NULL) { + int ww = w >> level; + int hh = h >> level; + int xx = x >> level; + int yy = y >> level; + img->data[level] = new int[ww * hh]; + intArray arrayWrapper(img->data[level], ww * hh); + this->getRGB(xx, yy, ww, hh, arrayWrapper, 0, ww, level); + + ++level; + } + + return img; } -int *BufferedImage::getData() -{ - return data[0]; -} - -int *BufferedImage::getData(int level) -{ - return data[level]; -} - -Graphics *BufferedImage::getGraphics() -{ - return NULL; -} - -//Returns the transparency. Returns either OPAQUE, BITMASK, or TRANSLUCENT. -//Specified by: -//getTransparency in interface Transparency -//Returns: -//the transparency of this BufferedImage. -int BufferedImage::getTransparency() -{ - // TODO - 4J Implement? - return 0; -} - -//Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image. -//Parameters: -//x, y - the coordinates of the upper-left corner of the specified rectangular region -//w - the width of the specified rectangular region -//h - the height of the specified rectangular region -//Returns: -//a BufferedImage that is the subimage of this BufferedImage. -BufferedImage *BufferedImage::getSubimage(int x ,int y, int w, int h) -{ - // TODO - 4J Implement - - BufferedImage *img = new BufferedImage(w,h,0); - intArray arrayWrapper(img->data[0], w*h); - this->getRGB(x, y, w, h, arrayWrapper,0,w); - - int level = 1; - while(getData(level) != NULL) - { - int ww = w >> level; - int hh = h >> level; - int xx = x >> level; - int yy = y >> level; - img->data[level] = new int[ww*hh]; - intArray arrayWrapper(img->data[level], ww*hh); - this->getRGB(xx, yy, ww, hh, arrayWrapper,0,ww,level); - - ++level; - } - - return img; -} - - -void BufferedImage::preMultiplyAlpha() -{ - int *curData = data[0]; - - int cur = 0; - int alpha = 0; - int r = 0; - int g = 0; - int b = 0; - - int total = width * height; - for(unsigned int i = 0; i < total; ++i) - { - cur = curData[i]; - alpha = (cur >> 24) & 0xff; - r = ((cur >> 16) & 0xff) * (float)alpha/255; - g = ((cur >> 8) & 0xff) * (float)alpha/255; - b = (cur & 0xff) * (float)alpha/255; - - curData[i] = (r << 16) | (g << 8) | (b ) | (alpha << 24); - } +void BufferedImage::preMultiplyAlpha() { + int* curData = data[0]; + + int cur = 0; + int alpha = 0; + int r = 0; + int g = 0; + int b = 0; + + int total = width * height; + for (unsigned int i = 0; i < total; ++i) { + cur = curData[i]; + alpha = (cur >> 24) & 0xff; + r = ((cur >> 16) & 0xff) * (float)alpha / 255; + g = ((cur >> 8) & 0xff) * (float)alpha / 255; + b = (cur & 0xff) * (float)alpha / 255; + + curData[i] = (r << 16) | (g << 8) | (b) | (alpha << 24); + } } diff --git a/Minecraft.Client/Textures/BufferedImage.h b/Minecraft.Client/Textures/BufferedImage.h index 94ffe0576..fbbf39283 100644 --- a/Minecraft.Client/Textures/BufferedImage.h +++ b/Minecraft.Client/Textures/BufferedImage.h @@ -1,34 +1,36 @@ #pragma once #include - class Graphics; class DLCPack; -class BufferedImage -{ +class BufferedImage { private: - int *data[10]; // Arrays for mipmaps - NULL if not used - int width; - int height; - void ByteFlip4(unsigned int &data); // 4J added + int* data[10]; // Arrays for mipmaps - NULL if not used + int width; + int height; + void ByteFlip4(unsigned int& data); // 4J added public: - static const int TYPE_INT_ARGB = 0; - static const int TYPE_INT_RGB = 1; - BufferedImage(int width,int height,int type); - BufferedImage(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L""); // 4J added - BufferedImage(DLCPack *dlcPack, const std::wstring& File, bool filenameHasExtension = false ); // 4J Added - BufferedImage(std::uint8_t *pbData, std::uint32_t dataBytes); // 4J added - ~BufferedImage(); + static const int TYPE_INT_ARGB = 0; + static const int TYPE_INT_RGB = 1; + BufferedImage(int width, int height, int type); + BufferedImage(const std::wstring& File, bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, + const std::wstring& drive = L""); // 4J added + BufferedImage(DLCPack* dlcPack, const std::wstring& File, + bool filenameHasExtension = false); // 4J Added + BufferedImage(std::uint8_t* pbData, std::uint32_t dataBytes); // 4J added + ~BufferedImage(); - int getWidth(); - int getHeight(); - void getRGB(int startX, int startY, int w, int h, intArray out,int offset,int scansize, int level = 0); // 4J Added level param - int *getData(); // 4J added - int *getData(int level); // 4J added - Graphics *getGraphics(); - int getTransparency(); - BufferedImage *getSubimage(int x, int y, int w, int h); + int getWidth(); + int getHeight(); + void getRGB(int startX, int startY, int w, int h, intArray out, int offset, + int scansize, int level = 0); // 4J Added level param + int* getData(); // 4J added + int* getData(int level); // 4J added + Graphics* getGraphics(); + int getTransparency(); + BufferedImage* getSubimage(int x, int y, int w, int h); - void preMultiplyAlpha(); + void preMultiplyAlpha(); }; diff --git a/Minecraft.Client/Textures/ClockTexture.cpp b/Minecraft.Client/Textures/ClockTexture.cpp index 592b1260d..65420510e 100644 --- a/Minecraft.Client/Textures/ClockTexture.cpp +++ b/Minecraft.Client/Textures/ClockTexture.cpp @@ -7,113 +7,87 @@ #include "Texture.h" #include "ClockTexture.h" -ClockTexture::ClockTexture() : StitchedTexture(L"compass") -{ - rot = rota = 0.0; - m_dataTexture = NULL; - m_iPad = XUSER_INDEX_ANY; +ClockTexture::ClockTexture() : StitchedTexture(L"compass") { + rot = rota = 0.0; + m_dataTexture = NULL; + m_iPad = XUSER_INDEX_ANY; } -ClockTexture::ClockTexture(int iPad, ClockTexture *dataTexture) : StitchedTexture(L"compass") -{ - rot = rota = 0.0; - m_dataTexture = dataTexture; - m_iPad = iPad; +ClockTexture::ClockTexture(int iPad, ClockTexture* dataTexture) + : StitchedTexture(L"compass") { + rot = rota = 0.0; + m_dataTexture = dataTexture; + m_iPad = iPad; } -void ClockTexture::cycleFrames() -{ +void ClockTexture::cycleFrames() { + Minecraft* mc = Minecraft::GetInstance(); - Minecraft *mc = Minecraft::GetInstance(); + double rott = 0; + if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && + mc->localplayers[m_iPad] != NULL) { + float time = mc->localplayers[m_iPad]->level->getTimeOfDay(1); + rott = time; + if (!mc->localplayers[m_iPad]->level->dimension->isNaturalDimension()) { + rott = Math::random(); + } + } else { + // 4J Stu - For the static version, pretend we are already on a frame + // other than 0 + frame = 1; + } - double rott = 0; - if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && mc->localplayers[m_iPad] != NULL) - { - float time = mc->localplayers[m_iPad]->level->getTimeOfDay(1); - rott = time; - if (!mc->localplayers[m_iPad]->level->dimension->isNaturalDimension()) - { - rott = Math::random(); - } - } - else - { - // 4J Stu - For the static version, pretend we are already on a frame other than 0 - frame = 1; - } + double rotd = rott - rot; + while (rotd < -.5) rotd += 1.0; + while (rotd >= .5) rotd -= 1.0; + if (rotd < -1) rotd = -1; + if (rotd > 1) rotd = 1; + rota += rotd * 0.1; + rota *= 0.8; - double rotd = rott - rot; - while (rotd < -.5) - rotd += 1.0; - while (rotd >= .5) - rotd -= 1.0; - if (rotd < -1) rotd = -1; - if (rotd > 1) rotd = 1; - rota += rotd * 0.1; - rota *= 0.8; + rot += rota; - rot += rota; - - // 4J Stu - We share data with another texture - if(m_dataTexture != NULL) - { - int newFrame = (int) ((rot + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - m_dataTexture->source->blit(x, y, m_dataTexture->frames->at(this->frame), rotated); - } - } - else - { - int newFrame = (int) ((rot + 1.0) * frames->size()) % frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + frames->size()) % frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - source->blit(x, y, frames->at(this->frame), rotated); - } - } + // 4J Stu - We share data with another texture + if (m_dataTexture != NULL) { + int newFrame = (int)((rot + 1.0) * m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + m_dataTexture->source->blit( + x, y, m_dataTexture->frames->at(this->frame), rotated); + } + } else { + int newFrame = (int)((rot + 1.0) * frames->size()) % frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + frames->size()) % frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + source->blit(x, y, frames->at(this->frame), rotated); + } + } } -int ClockTexture::getSourceWidth() const -{ - return source->getWidth(); +int ClockTexture::getSourceWidth() const { return source->getWidth(); } + +int ClockTexture::getSourceHeight() const { return source->getHeight(); } + +int ClockTexture::getFrames() { + if (m_dataTexture == NULL) { + return StitchedTexture::getFrames(); + } else { + return m_dataTexture->getFrames(); + } } -int ClockTexture::getSourceHeight() const -{ - return source->getHeight(); +void ClockTexture::freeFrameTextures() { + if (m_dataTexture == NULL) { + StitchedTexture::freeFrameTextures(); + } } -int ClockTexture::getFrames() -{ - if(m_dataTexture == NULL) - { - return StitchedTexture::getFrames(); - } - else - { - return m_dataTexture->getFrames(); - } -} - -void ClockTexture::freeFrameTextures() -{ - if(m_dataTexture == NULL) - { - StitchedTexture::freeFrameTextures(); - } -} - -bool ClockTexture::hasOwnData() -{ - return m_dataTexture == NULL; -} \ No newline at end of file +bool ClockTexture::hasOwnData() { return m_dataTexture == NULL; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/ClockTexture.h b/Minecraft.Client/Textures/ClockTexture.h index ea9011c3e..fc745bed7 100644 --- a/Minecraft.Client/Textures/ClockTexture.h +++ b/Minecraft.Client/Textures/ClockTexture.h @@ -1,21 +1,20 @@ #pragma once #include "Stitching/StitchedTexture.h" -class ClockTexture : public StitchedTexture -{ +class ClockTexture : public StitchedTexture { private: - double rot, rota; - int m_iPad; - ClockTexture* m_dataTexture; + double rot, rota; + int m_iPad; + ClockTexture* m_dataTexture; public: - ClockTexture(); - ClockTexture(int iPad, ClockTexture *dataTexture); - void cycleFrames(); - - virtual int getSourceWidth() const; - virtual int getSourceHeight() const; - virtual int getFrames(); - virtual void freeFrameTextures(); // 4J added - virtual bool hasOwnData(); // 4J Added + ClockTexture(); + ClockTexture(int iPad, ClockTexture* dataTexture); + void cycleFrames(); + + virtual int getSourceWidth() const; + virtual int getSourceHeight() const; + virtual int getFrames(); + virtual void freeFrameTextures(); // 4J added + virtual bool hasOwnData(); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/CompassTexture.cpp b/Minecraft.Client/Textures/CompassTexture.cpp index fe26b4222..e09cfcadc 100644 --- a/Minecraft.Client/Textures/CompassTexture.cpp +++ b/Minecraft.Client/Textures/CompassTexture.cpp @@ -7,136 +7,113 @@ #include "Texture.h" #include "CompassTexture.h" -CompassTexture *CompassTexture::instance = NULL; +CompassTexture* CompassTexture::instance = NULL; -CompassTexture::CompassTexture() : StitchedTexture(L"compass") -{ - instance = this; +CompassTexture::CompassTexture() : StitchedTexture(L"compass") { + instance = this; - m_dataTexture = NULL; - m_iPad = XUSER_INDEX_ANY; + m_dataTexture = NULL; + m_iPad = XUSER_INDEX_ANY; - rot = rota = 0.0; + rot = rota = 0.0; } -CompassTexture::CompassTexture(int iPad, CompassTexture *dataTexture) : StitchedTexture(L"compass") -{ - m_dataTexture = dataTexture; - m_iPad = iPad; +CompassTexture::CompassTexture(int iPad, CompassTexture* dataTexture) + : StitchedTexture(L"compass") { + m_dataTexture = dataTexture; + m_iPad = iPad; - rot = rota = 0.0; + rot = rota = 0.0; } -void CompassTexture::cycleFrames() -{ - Minecraft *mc = Minecraft::GetInstance(); +void CompassTexture::cycleFrames() { + Minecraft* mc = Minecraft::GetInstance(); - if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && mc->localplayers[m_iPad] != NULL) - { - updateFromPosition(mc->localplayers[m_iPad]->level, mc->localplayers[m_iPad]->x, mc->localplayers[m_iPad]->z, mc->localplayers[m_iPad]->yRot, false, false); - } - else - { - frame = 1; - updateFromPosition(NULL, 0, 0, 0, false, true); - } + if (m_iPad >= 0 && m_iPad < XUSER_MAX_COUNT && mc->level != NULL && + mc->localplayers[m_iPad] != NULL) { + updateFromPosition(mc->localplayers[m_iPad]->level, + mc->localplayers[m_iPad]->x, + mc->localplayers[m_iPad]->z, + mc->localplayers[m_iPad]->yRot, false, false); + } else { + frame = 1; + updateFromPosition(NULL, 0, 0, 0, false, true); + } } -void CompassTexture::updateFromPosition(Level *level, double x, double z, double yRot, bool noNeedle, bool instant) -{ - double rott = 0; - if (level != NULL && !noNeedle) - { - Pos *spawnPos = level->getSharedSpawnPos(); - double xa = spawnPos->x - x; - double za = spawnPos->z - z; - delete spawnPos; - yRot = (int)yRot % 360; - rott = -((yRot - 90) * PI / 180 - atan2(za, xa)); - if (!level->dimension->isNaturalDimension()) - { - rott = Math::random() * PI * 2; - } - } +void CompassTexture::updateFromPosition(Level* level, double x, double z, + double yRot, bool noNeedle, + bool instant) { + double rott = 0; + if (level != NULL && !noNeedle) { + Pos* spawnPos = level->getSharedSpawnPos(); + double xa = spawnPos->x - x; + double za = spawnPos->z - z; + delete spawnPos; + yRot = (int)yRot % 360; + rott = -((yRot - 90) * PI / 180 - atan2(za, xa)); + if (!level->dimension->isNaturalDimension()) { + rott = Math::random() * PI * 2; + } + } - if (instant) - { - rot = rott; - } - else - { - double rotd = rott - rot; - while (rotd < -PI) - rotd += PI * 2; - while (rotd >= PI) - rotd -= PI * 2; - if (rotd < -1) rotd = -1; - if (rotd > 1) rotd = 1; - rota += rotd * 0.1; - rota *= 0.8; - rot += rota; - } + if (instant) { + rot = rott; + } else { + double rotd = rott - rot; + while (rotd < -PI) rotd += PI * 2; + while (rotd >= PI) rotd -= PI * 2; + if (rotd < -1) rotd = -1; + if (rotd > 1) rotd = 1; + rota += rotd * 0.1; + rota *= 0.8; + rot += rota; + } - // 4J Stu - We share data with another texture - if(m_dataTexture != NULL) - { - int newFrame = (int) (((rot / (PI * 2)) + 1.0) * m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + m_dataTexture->frames->size()) % m_dataTexture->frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - m_dataTexture->source->blit(this->x, this->y, m_dataTexture->frames->at(this->frame), rotated); - } - } - else - { - int newFrame = (int) (((rot / (PI * 2)) + 1.0) * frames->size()) % frames->size(); - while (newFrame < 0) - { - newFrame = (newFrame + frames->size()) % frames->size(); - } - if (newFrame != frame) - { - frame = newFrame; - source->blit(this->x, this->y, frames->at(this->frame), rotated); - } - } + // 4J Stu - We share data with another texture + if (m_dataTexture != NULL) { + int newFrame = + (int)(((rot / (PI * 2)) + 1.0) * m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + m_dataTexture->frames->size()) % + m_dataTexture->frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + m_dataTexture->source->blit(this->x, this->y, + m_dataTexture->frames->at(this->frame), + rotated); + } + } else { + int newFrame = + (int)(((rot / (PI * 2)) + 1.0) * frames->size()) % frames->size(); + while (newFrame < 0) { + newFrame = (newFrame + frames->size()) % frames->size(); + } + if (newFrame != frame) { + frame = newFrame; + source->blit(this->x, this->y, frames->at(this->frame), rotated); + } + } } -int CompassTexture::getSourceWidth() const -{ - return source->getWidth(); +int CompassTexture::getSourceWidth() const { return source->getWidth(); } + +int CompassTexture::getSourceHeight() const { return source->getHeight(); } + +int CompassTexture::getFrames() { + if (m_dataTexture == NULL) { + return StitchedTexture::getFrames(); + } else { + return m_dataTexture->getFrames(); + } } -int CompassTexture::getSourceHeight() const -{ - return source->getHeight(); +void CompassTexture::freeFrameTextures() { + if (m_dataTexture == NULL) { + StitchedTexture::freeFrameTextures(); + } } -int CompassTexture::getFrames() -{ - if(m_dataTexture == NULL) - { - return StitchedTexture::getFrames(); - } - else - { - return m_dataTexture->getFrames(); - } -} - -void CompassTexture::freeFrameTextures() -{ - if(m_dataTexture == NULL) - { - StitchedTexture::freeFrameTextures(); - } -} - -bool CompassTexture::hasOwnData() -{ - return m_dataTexture == NULL; -} \ No newline at end of file +bool CompassTexture::hasOwnData() { return m_dataTexture == NULL; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/CompassTexture.h b/Minecraft.Client/Textures/CompassTexture.h index fc7897095..50121d7db 100644 --- a/Minecraft.Client/Textures/CompassTexture.h +++ b/Minecraft.Client/Textures/CompassTexture.h @@ -1,25 +1,25 @@ #pragma once #include "Stitching/StitchedTexture.h" -class CompassTexture : public StitchedTexture -{ +class CompassTexture : public StitchedTexture { private: - int m_iPad; - CompassTexture* m_dataTexture; + int m_iPad; + CompassTexture* m_dataTexture; public: - static CompassTexture *instance; - double rot, rota; + static CompassTexture* instance; + double rot, rota; - CompassTexture(); - CompassTexture(int iPad, CompassTexture *dataTexture); + CompassTexture(); + CompassTexture(int iPad, CompassTexture* dataTexture); - void cycleFrames(); - void updateFromPosition(Level *level, double x, double z, double yRot, bool noNeedle, bool instant); - - virtual int getSourceWidth() const; - virtual int getSourceHeight() const; - virtual int getFrames(); - virtual void freeFrameTextures(); // 4J added - virtual bool hasOwnData(); // 4J Added + void cycleFrames(); + void updateFromPosition(Level* level, double x, double z, double yRot, + bool noNeedle, bool instant); + + virtual int getSourceWidth() const; + virtual int getSourceHeight() const; + virtual int getFrames(); + virtual void freeFrameTextures(); // 4J added + virtual bool hasOwnData(); // 4J Added }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/HttpTexture.cpp b/Minecraft.Client/Textures/HttpTexture.cpp index 05ea7e8fb..f7a658f42 100644 --- a/Minecraft.Client/Textures/HttpTexture.cpp +++ b/Minecraft.Client/Textures/HttpTexture.cpp @@ -1,12 +1,12 @@ #include "../Platform/stdafx.h" #include "HttpTexture.h" -HttpTexture::HttpTexture(const std::wstring& _url, HttpTextureProcessor *processor) -{ - // 4J - added +HttpTexture::HttpTexture(const std::wstring& _url, + HttpTextureProcessor* processor) { + // 4J - added count = 1; id = -1; isLoaded = false; - // 4J - TODO - actually implement + // 4J - TODO - actually implement } \ No newline at end of file diff --git a/Minecraft.Client/Textures/HttpTexture.h b/Minecraft.Client/Textures/HttpTexture.h index 3c87cd8f0..4737b13f0 100644 --- a/Minecraft.Client/Textures/HttpTexture.h +++ b/Minecraft.Client/Textures/HttpTexture.h @@ -2,13 +2,12 @@ class BufferedImage; class HttpTextureProcessor; - class HttpTexture { public: - BufferedImage *loadedImage; + BufferedImage* loadedImage; int count; int id; bool isLoaded; - HttpTexture(const std::wstring& _url, HttpTextureProcessor *processor); + HttpTexture(const std::wstring& _url, HttpTextureProcessor* processor); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/HttpTextureProcessor.h b/Minecraft.Client/Textures/HttpTextureProcessor.h index a585a0345..351c9f124 100644 --- a/Minecraft.Client/Textures/HttpTextureProcessor.h +++ b/Minecraft.Client/Textures/HttpTextureProcessor.h @@ -1,8 +1,7 @@ #pragma once class BufferedImage; -class HttpTextureProcessor -{ +class HttpTextureProcessor { public: - virtual BufferedImage *process(BufferedImage *read) = 0; + virtual BufferedImage* process(BufferedImage* read) = 0; }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/MemTexture.cpp b/Minecraft.Client/Textures/MemTexture.cpp index e243a94ce..c6e337639 100644 --- a/Minecraft.Client/Textures/MemTexture.cpp +++ b/Minecraft.Client/Textures/MemTexture.cpp @@ -1,33 +1,26 @@ #include "../Platform/stdafx.h" #include "MemTexture.h" -MemTexture::MemTexture(const std::wstring& _url, std::uint8_t *pbData, std::uint32_t dataBytes, MemTextureProcessor *processor) -{ - // 4J - added +MemTexture::MemTexture(const std::wstring& _url, std::uint8_t* pbData, + std::uint32_t dataBytes, + MemTextureProcessor* processor) { + // 4J - added count = 1; id = -1; isLoaded = false; - ticksSinceLastUse = 0; + ticksSinceLastUse = 0; - // 4J - TODO - actually implement - - // load the texture, and process it - //loadedImage=Textures::getTexture() - // 4J - remember to add deletes in here for any created BufferedImages when implemented - loadedImage = new BufferedImage(pbData,dataBytes); - if(processor==NULL) - { - - } - else - { - //loadedImage=processor.process(ImageIO.read(huc.getInputStream())); - } - + // 4J - TODO - actually implement + // load the texture, and process it + // loadedImage=Textures::getTexture() + // 4J - remember to add deletes in here for any created BufferedImages when + // implemented + loadedImage = new BufferedImage(pbData, dataBytes); + if (processor == NULL) { + } else { + // loadedImage=processor.process(ImageIO.read(huc.getInputStream())); + } } -MemTexture::~MemTexture() -{ - delete loadedImage; -} +MemTexture::~MemTexture() { delete loadedImage; } diff --git a/Minecraft.Client/Textures/MemTexture.h b/Minecraft.Client/Textures/MemTexture.h index d8c9c4d1a..0cbbce319 100644 --- a/Minecraft.Client/Textures/MemTexture.h +++ b/Minecraft.Client/Textures/MemTexture.h @@ -3,16 +3,16 @@ class BufferedImage; class MemTextureProcessor; - class MemTexture { public: - BufferedImage *loadedImage; + BufferedImage* loadedImage; int count; int id; bool isLoaded; - int ticksSinceLastUse; - static const int UNUSED_TICKS_TO_FREE = 20; + int ticksSinceLastUse; + static const int UNUSED_TICKS_TO_FREE = 20; - MemTexture(const std::wstring& _name, std::uint8_t *pbData, std::uint32_t dataBytes, MemTextureProcessor *processor); - ~MemTexture(); + MemTexture(const std::wstring& _name, std::uint8_t* pbData, + std::uint32_t dataBytes, MemTextureProcessor* processor); + ~MemTexture(); }; diff --git a/Minecraft.Client/Textures/MemTextureProcessor.h b/Minecraft.Client/Textures/MemTextureProcessor.h index 56590d428..3d48cb8aa 100644 --- a/Minecraft.Client/Textures/MemTextureProcessor.h +++ b/Minecraft.Client/Textures/MemTextureProcessor.h @@ -1,9 +1,8 @@ #pragma once class BufferedImage; -class MemTextureProcessor -{ +class MemTextureProcessor { public: - virtual ~MemTextureProcessor(){} - virtual BufferedImage *process(BufferedImage *read) = 0; + virtual ~MemTextureProcessor() {} + virtual BufferedImage* process(BufferedImage* read) = 0; }; diff --git a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp index 73122d7ef..81e0d69d0 100644 --- a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp +++ b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.cpp @@ -1,15 +1,15 @@ #include "../Platform/stdafx.h" #include "MobSkinMemTextureProcessor.h" -BufferedImage *MobSkinMemTextureProcessor::process(BufferedImage *in) -{ +BufferedImage* MobSkinMemTextureProcessor::process(BufferedImage* in) { if (in == NULL) return NULL; width = 64; height = 32; - BufferedImage *out = new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); - Graphics *g = out->getGraphics(); + BufferedImage* out = + new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); + Graphics* g = out->getGraphics(); g->drawImage(in, 0, 0, NULL); g->dispose(); @@ -20,18 +20,16 @@ BufferedImage *MobSkinMemTextureProcessor::process(BufferedImage *in) setNoAlpha(0, 16, 64, 32); bool hasAlpha = false; for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } - // 4J-PB - looks like the code below is wrong, and really should be looping from 0 to <32 - if (!hasAlpha) - { + // 4J-PB - looks like the code below is wrong, and really should be looping + // from 0 to <32 + if (!hasAlpha) { for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } @@ -40,31 +38,25 @@ BufferedImage *MobSkinMemTextureProcessor::process(BufferedImage *in) return out; } -void MobSkinMemTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinMemTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) { if (hasAlpha(x0, y0, x1, y1)) return; for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] &= 0x00ffffff; } } -void MobSkinMemTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinMemTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] |= 0xff000000; } } -bool MobSkinMemTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) -{ +bool MobSkinMemTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { int pix = pixels[x + y * width]; if (((pix >> 24) & 0xff) < 128) return true; } diff --git a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h index a28f80a3d..6a06aaaad 100644 --- a/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h +++ b/Minecraft.Client/Textures/MobSkinMemTextureProcessor.h @@ -1,16 +1,16 @@ #pragma once #include "MemTextureProcessor.h" -class MobSkinMemTextureProcessor : public MemTextureProcessor -{ +class MobSkinMemTextureProcessor : public MemTextureProcessor { private: - int *pixels; - int width, height; + int* pixels; + int width, height; + public: - virtual BufferedImage *process(BufferedImage *in); + virtual BufferedImage* process(BufferedImage* in); private: - void setForceAlpha(int x0, int y0, int x1, int y1); + void setForceAlpha(int x0, int y0, int x1, int y1); void setNoAlpha(int x0, int y0, int x1, int y1); bool hasAlpha(int x0, int y0, int x1, int y1); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp b/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp index aea0f4b17..ee2962f70 100644 --- a/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp +++ b/Minecraft.Client/Textures/MobSkinTextureProcessor.cpp @@ -1,15 +1,15 @@ #include "../Platform/stdafx.h" #include "MobSkinTextureProcessor.h" -BufferedImage *MobSkinTextureProcessor::process(BufferedImage *in) -{ +BufferedImage* MobSkinTextureProcessor::process(BufferedImage* in) { if (in == NULL) return NULL; width = 64; height = 32; - BufferedImage *out = new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); - Graphics *g = out->getGraphics(); + BufferedImage* out = + new BufferedImage(width, height, BufferedImage::TYPE_INT_ARGB); + Graphics* g = out->getGraphics(); g->drawImage(in, 0, 0, NULL); g->dispose(); @@ -20,17 +20,14 @@ BufferedImage *MobSkinTextureProcessor::process(BufferedImage *in) setNoAlpha(0, 16, 64, 32); bool hasAlpha = false; for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } - if (!hasAlpha) - { + if (!hasAlpha) { for (int x = 32; x < 64; x++) - for (int y = 0; y < 16; y++) - { + for (int y = 0; y < 16; y++) { int pix = pixels[x + y * 64]; if (((pix >> 24) & 0xff) < 128) hasAlpha = true; } @@ -39,31 +36,25 @@ BufferedImage *MobSkinTextureProcessor::process(BufferedImage *in) return out; } -void MobSkinTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinTextureProcessor::setForceAlpha(int x0, int y0, int x1, int y1) { if (hasAlpha(x0, y0, x1, y1)) return; for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] &= 0x00ffffff; } } -void MobSkinTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) -{ +void MobSkinTextureProcessor::setNoAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { pixels[x + y * width] |= 0xff000000; } } -bool MobSkinTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) -{ +bool MobSkinTextureProcessor::hasAlpha(int x0, int y0, int x1, int y1) { for (int x = x0; x < x1; x++) - for (int y = y0; y < y1; y++) - { + for (int y = y0; y < y1; y++) { int pix = pixels[x + y * width]; if (((pix >> 24) & 0xff) < 128) return true; } diff --git a/Minecraft.Client/Textures/MobSkinTextureProcessor.h b/Minecraft.Client/Textures/MobSkinTextureProcessor.h index ee51a8a3d..a4aba77f6 100644 --- a/Minecraft.Client/Textures/MobSkinTextureProcessor.h +++ b/Minecraft.Client/Textures/MobSkinTextureProcessor.h @@ -1,16 +1,16 @@ #pragma once #include "HttpTextureProcessor.h" -class MobSkinTextureProcessor : public HttpTextureProcessor -{ +class MobSkinTextureProcessor : public HttpTextureProcessor { private: - int *pixels; - int width, height; + int* pixels; + int width, height; + public: - virtual BufferedImage *process(BufferedImage *in); + virtual BufferedImage* process(BufferedImage* in); private: - void setForceAlpha(int x0, int y0, int x1, int y1); + void setForceAlpha(int x0, int y0, int x1, int y1); void setNoAlpha(int x0, int y0, int x1, int y1); bool hasAlpha(int x0, int y0, int x1, int y1); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp b/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp index 8821e6068..c65a973cb 100644 --- a/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/AbstractTexturePack.cpp @@ -6,71 +6,73 @@ #include -AbstractTexturePack::AbstractTexturePack(std::uint32_t id, File *file, const std::wstring &name, TexturePack *fallback) : id(id), name(name) -{ - // 4J init - textureId = -1; - m_colourTable = NULL; +AbstractTexturePack::AbstractTexturePack(std::uint32_t id, File* file, + const std::wstring& name, + TexturePack* fallback) + : id(id), name(name) { + // 4J init + textureId = -1; + m_colourTable = NULL; + this->file = file; + this->fallback = fallback; - this->file = file; - this->fallback = fallback; + m_iconData = NULL; + m_iconSize = 0; - m_iconData = NULL; - m_iconSize = 0; + m_comparisonData = NULL; + m_comparisonSize = 0; - m_comparisonData = NULL; - m_comparisonSize = 0; - - // 4J Stu - These calls need to be in the most derived version of the class - //loadIcon(); - //loadDescription(); + // 4J Stu - These calls need to be in the most derived version of the class + // loadIcon(); + // loadDescription(); } -std::wstring AbstractTexturePack::trim(std::wstring line) -{ - if (!line.empty() && line.length() > 34) - { - line = line.substr(0, 34); - } - return line; +std::wstring AbstractTexturePack::trim(std::wstring line) { + if (!line.empty() && line.length() > 34) { + line = line.substr(0, 34); + } + return line; } -void AbstractTexturePack::loadIcon() -{ +void AbstractTexturePack::loadIcon() { #ifdef _XBOX - // 4J Stu - Temporary only - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // 4J Stu - Temporary only + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/TexturePackIcon.png"); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/Graphics/TexturePackIcon.png"); - unsigned int size = 0; - HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); - m_iconSize = static_cast(size); + unsigned int size = 0; + HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); + m_iconSize = static_cast(size); #endif } -void AbstractTexturePack::loadComparison() -{ +void AbstractTexturePack::loadComparison() { #ifdef _XBOX - // 4J Stu - Temporary only - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // 4J Stu - Temporary only + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/DefaultPack_Comparison.png"); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", + L"media/Graphics/DefaultPack_Comparison.png"); - unsigned int size = 0; - HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_comparisonData, &size); - m_comparisonSize = static_cast(size); + unsigned int size = 0; + HRESULT hr = + XuiResourceLoadAllNoLoc(szResourceLocator, &m_comparisonData, &size); + m_comparisonSize = static_cast(size); #endif } -void AbstractTexturePack::loadDescription() -{ - // 4J Unused currently +void AbstractTexturePack::loadDescription() { + // 4J Unused currently #if 0 InputStream *inputStream = NULL; BufferedReader *br = NULL; @@ -99,311 +101,286 @@ void AbstractTexturePack::loadDescription() #endif } -void AbstractTexturePack::loadName() -{ -} +void AbstractTexturePack::loadName() {} -InputStream *AbstractTexturePack::getResource(const std::wstring &name, bool allowFallback) //throws IOException +InputStream* AbstractTexturePack::getResource( + const std::wstring& name, bool allowFallback) // throws IOException { - app.DebugPrintf("texture - %ls\n",name.c_str()); - InputStream *is = getResourceImplementation(name); - if (is == NULL && fallback != NULL && allowFallback) - { - is = fallback->getResource(name, true); - } + app.DebugPrintf("texture - %ls\n", name.c_str()); + InputStream* is = getResourceImplementation(name); + if (is == NULL && fallback != NULL && allowFallback) { + is = fallback->getResource(name, true); + } - return is; + return is; } // 4J Currently removed due to override in TexturePack class -//InputStream *AbstractTexturePack::getResource(const std::wstring &name) //throws IOException +// InputStream *AbstractTexturePack::getResource(const std::wstring &name) +// //throws IOException //{ // return getResource(name, true); //} -void AbstractTexturePack::unload(Textures *textures) -{ - if (iconImage != NULL && textureId != -1) - { - textures->releaseTexture(textureId); - } +void AbstractTexturePack::unload(Textures* textures) { + if (iconImage != NULL && textureId != -1) { + textures->releaseTexture(textureId); + } } -void AbstractTexturePack::load(Textures *textures) -{ - if (iconImage != NULL) - { - if (textureId == -1) - { - textureId = textures->getTexture(iconImage); - } - glBindTexture(GL_TEXTURE_2D, textureId); - textures->clearLastBoundId(); - } - else - { - // 4J Stu - Don't do this - //textures->bindTexture(L"/gui/unknown_pack.png"); - } +void AbstractTexturePack::load(Textures* textures) { + if (iconImage != NULL) { + if (textureId == -1) { + textureId = textures->getTexture(iconImage); + } + glBindTexture(GL_TEXTURE_2D, textureId); + textures->clearLastBoundId(); + } else { + // 4J Stu - Don't do this + // textures->bindTexture(L"/gui/unknown_pack.png"); + } } -bool AbstractTexturePack::hasFile(const std::wstring &name, bool allowFallback) -{ - bool hasFile = this->hasFile(name); +bool AbstractTexturePack::hasFile(const std::wstring& name, + bool allowFallback) { + bool hasFile = this->hasFile(name); - return !hasFile && (allowFallback && fallback != NULL) ? fallback->hasFile(name, allowFallback) : hasFile; + return !hasFile && (allowFallback && fallback != NULL) + ? fallback->hasFile(name, allowFallback) + : hasFile; } -std::uint32_t AbstractTexturePack::getId() -{ - return id; +std::uint32_t AbstractTexturePack::getId() { return id; } + +std::wstring AbstractTexturePack::getName() { return texname; } + +std::wstring AbstractTexturePack::getWorldName() { return m_wsWorldName; } + +std::wstring AbstractTexturePack::getDesc1() { return desc1; } + +std::wstring AbstractTexturePack::getDesc2() { return desc2; } + +std::wstring AbstractTexturePack::getAnimationString( + const std::wstring& textureName, const std::wstring& path, + bool allowFallback) { + return getAnimationString(textureName, path); } -std::wstring AbstractTexturePack::getName() -{ - return texname; -} +std::wstring AbstractTexturePack::getAnimationString( + const std::wstring& textureName, const std::wstring& path) { + std::wstring animationDefinitionFile = textureName + L".txt"; -std::wstring AbstractTexturePack::getWorldName() -{ - return m_wsWorldName; -} + bool requiresFallback = !hasFile(L"\\" + textureName + L".png", false); -std::wstring AbstractTexturePack::getDesc1() -{ - return desc1; -} + InputStream* fileStream = + getResource(L"\\" + path + animationDefinitionFile, requiresFallback); -std::wstring AbstractTexturePack::getDesc2() -{ - return desc2; -} - -std::wstring AbstractTexturePack::getAnimationString(const std::wstring &textureName, const std::wstring &path, bool allowFallback) -{ - return getAnimationString(textureName, path); -} - -std::wstring AbstractTexturePack::getAnimationString(const std::wstring &textureName, const std::wstring &path) -{ - std::wstring animationDefinitionFile = textureName + L".txt"; - - bool requiresFallback = !hasFile(L"\\" + textureName + L".png", false); - - InputStream *fileStream = getResource(L"\\" + path + animationDefinitionFile, requiresFallback); - - //Minecraft::getInstance()->getLogger().info("Found animation info for: " + animationDefinitionFile); + // Minecraft::getInstance()->getLogger().info("Found animation info for: " + + // animationDefinitionFile); #ifndef _CONTENT_PACKAGE - wprintf(L"Found animation info for: %ls\n", animationDefinitionFile.c_str() ); + wprintf(L"Found animation info for: %ls\n", + animationDefinitionFile.c_str()); #endif - InputStreamReader isr(fileStream); - BufferedReader br(&isr); - - std::wstring result = L""; + InputStreamReader isr(fileStream); + BufferedReader br(&isr); - std::wstring line = br.readLine(); - while (!line.empty()) - { - line = trimString(line); - if (line.length() > 0) - { - result.append(L","); - result.append(line); - } - line = br.readLine(); - } - delete fileStream; + std::wstring result = L""; - return result; + std::wstring line = br.readLine(); + while (!line.empty()) { + line = trimString(line); + if (line.length() > 0) { + result.append(L","); + result.append(line); + } + line = br.readLine(); + } + delete fileStream; + + return result; } -BufferedImage *AbstractTexturePack::getImageResource(const std::wstring& File, bool filenameHasExtension /*= false*/, bool bTitleUpdateTexture /*=false*/, const std::wstring &drive /*=L""*/) -{ - const char *pchTexture=wstringtofilename(File); - app.DebugPrintf("AbstractTexturePack::getImageResource - %s, drive is %s\n",pchTexture, wstringtofilename(drive)); +BufferedImage* AbstractTexturePack::getImageResource( + const std::wstring& File, bool filenameHasExtension /*= false*/, + bool bTitleUpdateTexture /*=false*/, const std::wstring& drive /*=L""*/) { + const char* pchTexture = wstringtofilename(File); + app.DebugPrintf("AbstractTexturePack::getImageResource - %s, drive is %s\n", + pchTexture, wstringtofilename(drive)); - return new BufferedImage(TexturePack::getResource(L"/" + File),filenameHasExtension,bTitleUpdateTexture,drive); + return new BufferedImage(TexturePack::getResource(L"/" + File), + filenameHasExtension, bTitleUpdateTexture, drive); } -void AbstractTexturePack::loadDefaultUI() -{ +void AbstractTexturePack::loadDefaultUI() { #ifdef _XBOX - // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + // load from the .xzp file + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - // Load new skin - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // Load new skin + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/skin_Minecraft.xur"); - - XuiFreeVisuals(L""); - app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); - //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/skin_Minecraft.xur"); + + XuiFreeVisuals(L""); + app.LoadSkin(szResourceLocator, NULL); // L"TexturePack"); + // CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #else - ui.ReloadSkin(); + ui.ReloadSkin(); #endif } -void AbstractTexturePack::loadColourTable() -{ - loadDefaultColourTable(); - loadDefaultHTMLColourTable(); +void AbstractTexturePack::loadColourTable() { + loadDefaultColourTable(); + loadDefaultHTMLColourTable(); } -void AbstractTexturePack::loadDefaultColourTable() -{ - // Load the file - File coloursFile(AbstractTexturePack::getPath(true).append(L"res/colours.col")); +void AbstractTexturePack::loadDefaultColourTable() { + // Load the file + File coloursFile( + AbstractTexturePack::getPath(true).append(L"res/colours.col")); - if(coloursFile.exists()) - { - const __int64 colourTableLength = coloursFile.length(); - if(colourTableLength < 0 || colourTableLength > static_cast<__int64>(std::numeric_limits::max())) - { - app.DebugPrintf("Failed to load the default colours table\n"); - app.FatalLoadError(); - return; - } + if (coloursFile.exists()) { + const __int64 colourTableLength = coloursFile.length(); + if (colourTableLength < 0 || + colourTableLength > static_cast<__int64>( + std::numeric_limits::max())) { + app.DebugPrintf("Failed to load the default colours table\n"); + app.FatalLoadError(); + return; + } - const unsigned int dataLength = static_cast(colourTableLength); - byteArray data(dataLength); + const unsigned int dataLength = + static_cast(colourTableLength); + byteArray data(dataLength); - FileInputStream fis(coloursFile); - fis.read(data,0,dataLength); - fis.close(); - if(m_colourTable != NULL) delete m_colourTable; - m_colourTable = new ColourTable(data.data, dataLength); + FileInputStream fis(coloursFile); + fis.read(data, 0, dataLength); + fis.close(); + if (m_colourTable != NULL) delete m_colourTable; + m_colourTable = new ColourTable(data.data, dataLength); - delete [] data.data; - } - else - { - app.DebugPrintf("Failed to load the default colours table\n"); - app.FatalLoadError(); - } + delete[] data.data; + } else { + app.DebugPrintf("Failed to load the default colours table\n"); + app.FatalLoadError(); + } } -void AbstractTexturePack::loadDefaultHTMLColourTable() -{ +void AbstractTexturePack::loadDefaultHTMLColourTable() { #ifdef _XBOX - // load from the .xzp file - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + // load from the .xzp file + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - // Try and load the HTMLColours.col based off the common XML first, before the deprecated xuiscene_colourtable - wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/HTMLColours.col"); - std::uint8_t *data; - unsigned int dataLength; - if(XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) - { - m_colourTable->loadColoursFromData(data,dataLength); + // Try and load the HTMLColours.col based off the common XML first, before + // the deprecated xuiscene_colourtable + wsprintfW(szResourceLocator, L"section://%X,%s#%s", c_ModuleHandle, + L"media", L"media/HTMLColours.col"); + std::uint8_t* data; + unsigned int dataLength; + if (XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) { + m_colourTable->loadColoursFromData(data, dataLength); - XuiFree(data); - } - else - { - wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/"); - HXUIOBJ hScene; - HRESULT hr = XuiSceneCreate(szResourceLocator,L"xuiscene_colourtable.xur", NULL, &hScene); + XuiFree(data); + } else { + wsprintfW(szResourceLocator, L"section://%X,%s#%s", c_ModuleHandle, + L"media", L"media/"); + HXUIOBJ hScene; + HRESULT hr = XuiSceneCreate(szResourceLocator, + L"xuiscene_colourtable.xur", NULL, &hScene); - if(HRESULT_SUCCEEDED(hr)) - { - loadHTMLColourTableFromXuiScene(hScene); - } - } + if (HRESULT_SUCCEEDED(hr)) { + loadHTMLColourTableFromXuiScene(hScene); + } + } #else - if(app.hasArchiveFile(L"HTMLColours.col")) - { - byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); - m_colourTable->loadColoursFromData(textColours.data,textColours.length); + if (app.hasArchiveFile(L"HTMLColours.col")) { + byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); + m_colourTable->loadColoursFromData(textColours.data, + textColours.length); - delete [] textColours.data; - } + delete[] textColours.data; + } #endif } #ifdef _XBOX -void AbstractTexturePack::loadHTMLColourTableFromXuiScene(HXUIOBJ hObj) -{ - HXUIOBJ child; - HRESULT hr = XuiElementGetFirstChild(hObj, &child); +void AbstractTexturePack::loadHTMLColourTableFromXuiScene(HXUIOBJ hObj) { + HXUIOBJ child; + HRESULT hr = XuiElementGetFirstChild(hObj, &child); - while(HRESULT_SUCCEEDED(hr) && child != NULL) - { - LPCWSTR childName; - XuiElementGetId(child,&childName); - m_colourTable->setColour(childName,XuiTextElementGetText(child)); + while (HRESULT_SUCCEEDED(hr) && child != NULL) { + LPCWSTR childName; + XuiElementGetId(child, &childName); + m_colourTable->setColour(childName, XuiTextElementGetText(child)); - //eMinecraftTextColours colourIndex = eTextColor_NONE; - //for(int i = 0; i < (int)eTextColor_MAX; i++) - //{ - // if(wcscmp(HTMLColourTableElements[i],childName)==0) - // { - // colourIndex = (eMinecraftTextColours)i; - // break; - // } - //} + // eMinecraftTextColours colourIndex = eTextColor_NONE; + // for(int i = 0; i < (int)eTextColor_MAX; i++) + //{ + // if(wcscmp(HTMLColourTableElements[i],childName)==0) + // { + // colourIndex = (eMinecraftTextColours)i; + // break; + // } + // } - //LPCWSTR stringValue = XuiTextElementGetText(child); + // LPCWSTR stringValue = XuiTextElementGetText(child); - //m_htmlColourTable[colourIndex] = XuiTextElementGetText(child); + // m_htmlColourTable[colourIndex] = XuiTextElementGetText(child); - hr = XuiElementGetNext(child, &child); - } + hr = XuiElementGetNext(child, &child); + } } #endif -void AbstractTexturePack::loadUI() -{ - loadColourTable(); - +void AbstractTexturePack::loadUI() { + loadColourTable(); + #ifdef _XBOX - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #endif } -void AbstractTexturePack::unloadUI() -{ - // Do nothing +void AbstractTexturePack::unloadUI() { + // Do nothing } -std::wstring AbstractTexturePack::getXuiRootPath() -{ - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); +std::wstring AbstractTexturePack::getXuiRootPath() { + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - // Load new skin - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // Load new skin + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/"); - return szResourceLocator; + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/"); + return szResourceLocator; } -std::uint8_t *AbstractTexturePack::getPackIcon(std::uint32_t &imageBytes) -{ - if(m_iconSize == 0 || m_iconData == NULL) loadIcon(); - imageBytes = m_iconSize; - return m_iconData; +std::uint8_t* AbstractTexturePack::getPackIcon(std::uint32_t& imageBytes) { + if (m_iconSize == 0 || m_iconData == NULL) loadIcon(); + imageBytes = m_iconSize; + return m_iconData; } -std::uint8_t *AbstractTexturePack::getPackComparison(std::uint32_t &imageBytes) -{ - if(m_comparisonSize == 0 || m_comparisonData == NULL) loadComparison(); +std::uint8_t* AbstractTexturePack::getPackComparison( + std::uint32_t& imageBytes) { + if (m_comparisonSize == 0 || m_comparisonData == NULL) loadComparison(); - imageBytes = m_comparisonSize; - return m_comparisonData; + imageBytes = m_comparisonSize; + return m_comparisonData; } -unsigned int AbstractTexturePack::getDLCParentPackId() -{ - return 0; -} +unsigned int AbstractTexturePack::getDLCParentPackId() { return 0; } -unsigned char AbstractTexturePack::getDLCSubPackId() -{ - return 0; -} +unsigned char AbstractTexturePack::getDLCSubPackId() { return 0; } diff --git a/Minecraft.Client/Textures/Packs/AbstractTexturePack.h b/Minecraft.Client/Textures/Packs/AbstractTexturePack.h index d9cbd8222..b633ff31b 100644 --- a/Minecraft.Client/Textures/Packs/AbstractTexturePack.h +++ b/Minecraft.Client/Textures/Packs/AbstractTexturePack.h @@ -1,93 +1,100 @@ #pragma once - #include "TexturePack.h" class BufferedImage; -class AbstractTexturePack : public TexturePack -{ +class AbstractTexturePack : public TexturePack { private: - const std::uint32_t id; - const std::wstring name; + const std::uint32_t id; + const std::wstring name; protected: - File *file; - std::wstring texname; - std::wstring m_wsWorldName; + File* file; + std::wstring texname; + std::wstring m_wsWorldName; - std::wstring desc1; - std::wstring desc2; + std::wstring desc1; + std::wstring desc2; - std::uint8_t *m_iconData; - std::uint32_t m_iconSize; + std::uint8_t* m_iconData; + std::uint32_t m_iconSize; - std::uint8_t *m_comparisonData; - std::uint32_t m_comparisonSize; + std::uint8_t* m_comparisonData; + std::uint32_t m_comparisonSize; - TexturePack *fallback; + TexturePack* fallback; - ColourTable *m_colourTable; + ColourTable* m_colourTable; protected: - BufferedImage *iconImage; + BufferedImage* iconImage; private: - int textureId; + int textureId; protected: - AbstractTexturePack(std::uint32_t id, File *file, const std::wstring &name, TexturePack *fallback); + AbstractTexturePack(std::uint32_t id, File* file, const std::wstring& name, + TexturePack* fallback); private: - static std::wstring trim(std::wstring line); - + static std::wstring trim(std::wstring line); + protected: - virtual void loadIcon(); - virtual void loadComparison(); - virtual void loadDescription(); - virtual void loadName(); + virtual void loadIcon(); + virtual void loadComparison(); + virtual void loadDescription(); + virtual void loadName(); public: - virtual InputStream *getResource(const std::wstring &name, bool allowFallback); //throws IOException - // 4J Removed do to current override in TexturePack class - //virtual InputStream *getResource(const std::wstring &name); //throws IOException - virtual DLCPack * getDLCPack() =0; - + virtual InputStream* getResource(const std::wstring& name, + bool allowFallback); // throws IOException + // 4J Removed do to current override in TexturePack class + // virtual InputStream *getResource(const std::wstring &name); //throws + // IOException + virtual DLCPack* getDLCPack() = 0; protected: - virtual InputStream *getResourceImplementation(const std::wstring &name) = 0; // throws IOException; + virtual InputStream* getResourceImplementation( + const std::wstring& name) = 0; // throws IOException; public: - virtual void unload(Textures *textures); - virtual void load(Textures *textures); - virtual bool hasFile(const std::wstring &name, bool allowFallback); - virtual bool hasFile(const std::wstring &name) = 0; - virtual std::uint32_t getId(); - virtual std::wstring getName(); - virtual std::wstring getDesc1(); - virtual std::wstring getDesc2(); - virtual std::wstring getWorldName(); - - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path, bool allowFallback); + virtual void unload(Textures* textures); + virtual void load(Textures* textures); + virtual bool hasFile(const std::wstring& name, bool allowFallback); + virtual bool hasFile(const std::wstring& name) = 0; + virtual std::uint32_t getId(); + virtual std::wstring getName(); + virtual std::wstring getDesc1(); + virtual std::wstring getDesc2(); + virtual std::wstring getWorldName(); + + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path, + bool allowFallback); protected: - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path); - void loadDefaultUI(); - void loadDefaultColourTable(); - void loadDefaultHTMLColourTable(); + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path); + void loadDefaultUI(); + void loadDefaultColourTable(); + void loadDefaultHTMLColourTable(); #ifdef _XBOX - void loadHTMLColourTableFromXuiScene(HXUIOBJ hObj); + void loadHTMLColourTableFromXuiScene(HXUIOBJ hObj); #endif public: - virtual BufferedImage *getImageResource(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L""); - virtual void loadColourTable(); - virtual void loadUI(); - virtual void unloadUI(); - virtual std::wstring getXuiRootPath(); - virtual std::uint8_t *getPackIcon(std::uint32_t &imageBytes); - virtual std::uint8_t *getPackComparison(std::uint32_t &imageBytes); - virtual unsigned int getDLCParentPackId(); - virtual unsigned char getDLCSubPackId(); - virtual ColourTable *getColourTable() { return m_colourTable; } - virtual ArchiveFile *getArchiveFile() { return NULL; } + virtual BufferedImage* getImageResource(const std::wstring& File, + bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, + const std::wstring& drive = L""); + virtual void loadColourTable(); + virtual void loadUI(); + virtual void unloadUI(); + virtual std::wstring getXuiRootPath(); + virtual std::uint8_t* getPackIcon(std::uint32_t& imageBytes); + virtual std::uint8_t* getPackComparison(std::uint32_t& imageBytes); + virtual unsigned int getDLCParentPackId(); + virtual unsigned char getDLCSubPackId(); + virtual ColourTable* getColourTable() { return m_colourTable; } + virtual ArchiveFile* getArchiveFile() { return NULL; } }; diff --git a/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp b/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp index 4d56cf46e..4c58b82a0 100644 --- a/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/DLCTexturePack.cpp @@ -20,567 +20,580 @@ #include "../../Platform/Xbox/XML/xmlFilesCallback.h" #endif -namespace -{ - bool ReadPortableBinaryFile(File &file, std::uint8_t *&data, unsigned int &size) - { - const __int64 fileLength = file.length(); - if (fileLength < 0 || fileLength > static_cast<__int64>(std::numeric_limits::max())) - { - data = NULL; - size = 0; - return false; - } +namespace { +bool ReadPortableBinaryFile(File& file, std::uint8_t*& data, + unsigned int& size) { + const __int64 fileLength = file.length(); + if (fileLength < 0 || + fileLength > + static_cast<__int64>(std::numeric_limits::max())) { + data = NULL; + size = 0; + return false; + } - const std::size_t capacity = static_cast(fileLength); - std::uint8_t *buffer = new std::uint8_t[capacity == 0 ? 1 : capacity]; - const PortableFileIO::BinaryReadResult readResult = PortableFileIO::ReadBinaryFile(file.getPath(), buffer, capacity); - if (readResult.status != PortableFileIO::BinaryReadStatus::ok - || readResult.fileSize > std::numeric_limits::max()) - { - delete [] buffer; - data = NULL; - size = 0; - return false; - } + const std::size_t capacity = static_cast(fileLength); + std::uint8_t* buffer = new std::uint8_t[capacity == 0 ? 1 : capacity]; + const PortableFileIO::BinaryReadResult readResult = + PortableFileIO::ReadBinaryFile(file.getPath(), buffer, capacity); + if (readResult.status != PortableFileIO::BinaryReadStatus::ok || + readResult.fileSize > std::numeric_limits::max()) { + delete[] buffer; + data = NULL; + size = 0; + return false; + } - data = buffer; - size = static_cast(readResult.fileSize); - return true; - } + data = buffer; + size = static_cast(readResult.fileSize); + return true; } +} // namespace -DLCTexturePack::DLCTexturePack(std::uint32_t id, DLCPack *pack, TexturePack *fallback) : AbstractTexturePack(id, NULL, pack->getName(), fallback) -{ - m_dlcInfoPack = pack; - m_dlcDataPack = NULL; - bUILoaded = false; - m_bLoadingData = false; - m_bHasLoadedData = false; - m_archiveFile = NULL; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - m_bUsingDefaultColourTable = true; +DLCTexturePack::DLCTexturePack(std::uint32_t id, DLCPack* pack, + TexturePack* fallback) + : AbstractTexturePack(id, NULL, pack->getName(), fallback) { + m_dlcInfoPack = pack; + m_dlcDataPack = NULL; + bUILoaded = false; + m_bLoadingData = false; + m_bHasLoadedData = false; + m_archiveFile = NULL; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + m_bUsingDefaultColourTable = true; - m_stringTable = NULL; + m_stringTable = NULL; #ifdef _XBOX - m_pStreamedWaveBank=NULL; - m_pSoundBank=NULL; + m_pStreamedWaveBank = NULL; + m_pSoundBank = NULL; #endif - if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc")) - { - DLCLocalisationFile *localisationFile = (DLCLocalisationFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_LocalisationData, L"languages.loc"); - m_stringTable = localisationFile->getStringTable(); - } + if (m_dlcInfoPack->doesPackContainFile( + DLCManager::e_DLCType_LocalisationData, L"languages.loc")) { + DLCLocalisationFile* localisationFile = + (DLCLocalisationFile*)m_dlcInfoPack->getFile( + DLCManager::e_DLCType_LocalisationData, L"languages.loc"); + m_stringTable = localisationFile->getStringTable(); + } - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); - loadDescription(); - //loadDefaultHTMLColourTable(); + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); + loadDescription(); + // loadDefaultHTMLColourTable(); } -void DLCTexturePack::loadIcon() -{ - if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, L"icon.png")) - { - DLCTextureFile *textureFile = (DLCTextureFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"icon.png"); - std::uint32_t iconSize = 0; - m_iconData = textureFile->getData(iconSize); - m_iconSize = iconSize; - } - else - { - AbstractTexturePack::loadIcon(); - } +void DLCTexturePack::loadIcon() { + if (m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, + L"icon.png")) { + DLCTextureFile* textureFile = (DLCTextureFile*)m_dlcInfoPack->getFile( + DLCManager::e_DLCType_Texture, L"icon.png"); + std::uint32_t iconSize = 0; + m_iconData = textureFile->getData(iconSize); + m_iconSize = iconSize; + } else { + AbstractTexturePack::loadIcon(); + } } -void DLCTexturePack::loadComparison() -{ - if(m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, L"comparison.png")) - { - DLCTextureFile *textureFile = (DLCTextureFile *)m_dlcInfoPack->getFile(DLCManager::e_DLCType_Texture, L"comparison.png"); - std::uint32_t comparisonSize = 0; - m_comparisonData = textureFile->getData(comparisonSize); - m_comparisonSize = comparisonSize; - } +void DLCTexturePack::loadComparison() { + if (m_dlcInfoPack->doesPackContainFile(DLCManager::e_DLCType_Texture, + L"comparison.png")) { + DLCTextureFile* textureFile = (DLCTextureFile*)m_dlcInfoPack->getFile( + DLCManager::e_DLCType_Texture, L"comparison.png"); + std::uint32_t comparisonSize = 0; + m_comparisonData = textureFile->getData(comparisonSize); + m_comparisonSize = comparisonSize; + } } -void DLCTexturePack::loadName() -{ - texname = L""; - - if(m_dlcInfoPack->GetPackID()&1024) - { - if(m_stringTable != NULL) - { - texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); - m_wsWorldName=m_stringTable->getString(L"IDS_WORLD_NAME"); - } - } - else - { - if(m_stringTable != NULL) - { - texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); - } - } +void DLCTexturePack::loadName() { + texname = L""; + if (m_dlcInfoPack->GetPackID() & 1024) { + if (m_stringTable != NULL) { + texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); + m_wsWorldName = m_stringTable->getString(L"IDS_WORLD_NAME"); + } + } else { + if (m_stringTable != NULL) { + texname = m_stringTable->getString(L"IDS_DISPLAY_NAME"); + } + } } -void DLCTexturePack::loadDescription() -{ - desc1 = L""; +void DLCTexturePack::loadDescription() { + desc1 = L""; - if(m_stringTable != NULL) - { - desc1 = m_stringTable->getString(L"IDS_TP_DESCRIPTION"); - } + if (m_stringTable != NULL) { + desc1 = m_stringTable->getString(L"IDS_TP_DESCRIPTION"); + } } -std::wstring DLCTexturePack::getResource(const std::wstring& name) -{ - // 4J Stu - We should never call this function +std::wstring DLCTexturePack::getResource(const std::wstring& name) { + // 4J Stu - We should never call this function #ifndef __CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - return L""; + return L""; } -InputStream *DLCTexturePack::getResourceImplementation(const std::wstring &name) //throws IOException +InputStream* DLCTexturePack::getResourceImplementation( + const std::wstring& name) // throws IOException { - // 4J Stu - We should never call this function + // 4J Stu - We should never call this function #ifndef _CONTENT_PACKAGE - __debugbreak(); - if(hasFile(name)) return NULL; + __debugbreak(); + if (hasFile(name)) return NULL; #endif - return NULL; //resource; + return NULL; // resource; } -bool DLCTexturePack::hasFile(const std::wstring &name) -{ - bool hasFile = false; - if(m_dlcDataPack != NULL) hasFile = m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_Texture, name); - return hasFile; +bool DLCTexturePack::hasFile(const std::wstring& name) { + bool hasFile = false; + if (m_dlcDataPack != NULL) + hasFile = m_dlcDataPack->doesPackContainFile( + DLCManager::e_DLCType_Texture, name); + return hasFile; } -bool DLCTexturePack::isTerrainUpdateCompatible() -{ - return true; +bool DLCTexturePack::isTerrainUpdateCompatible() { return true; } + +std::wstring DLCTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) { + return L""; } -std::wstring DLCTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) -{ - return L""; +std::wstring DLCTexturePack::getAnimationString(const std::wstring& textureName, + const std::wstring& path) { + std::wstring result = L""; + + std::wstring fullpath = L"res/" + path + textureName + L".png"; + if (hasFile(fullpath)) { + result = m_dlcDataPack->getFile(DLCManager::e_DLCType_Texture, fullpath) + ->getParameterAsString(DLCManager::e_DLCParamType_Anim); + } + + return result; } -std::wstring DLCTexturePack::getAnimationString(const std::wstring &textureName, const std::wstring &path) -{ - std::wstring result = L""; - - std::wstring fullpath = L"res/" + path + textureName + L".png"; - if(hasFile(fullpath)) - { - result = m_dlcDataPack->getFile(DLCManager::e_DLCType_Texture, fullpath)->getParameterAsString(DLCManager::e_DLCParamType_Anim); - } - - return result; +BufferedImage* DLCTexturePack::getImageResource( + const std::wstring& File, bool filenameHasExtension /*= false*/, + bool bTitleUpdateTexture /*=false*/, const std::wstring& drive /*=L""*/) { + if (m_dlcDataPack) + return new BufferedImage(m_dlcDataPack, L"/" + File, + filenameHasExtension); + else + return fallback->getImageResource(File, filenameHasExtension, + bTitleUpdateTexture, drive); } -BufferedImage *DLCTexturePack::getImageResource(const std::wstring& File, bool filenameHasExtension /*= false*/, bool bTitleUpdateTexture /*=false*/, const std::wstring &drive /*=L""*/) -{ - if(m_dlcDataPack) return new BufferedImage(m_dlcDataPack, L"/" + File, filenameHasExtension); - else return fallback->getImageResource(File, filenameHasExtension, bTitleUpdateTexture, drive); -} +DLCPack* DLCTexturePack::getDLCPack() { return m_dlcDataPack; } -DLCPack * DLCTexturePack::getDLCPack() -{ - return m_dlcDataPack; -} +void DLCTexturePack::loadColourTable() { + // Load the game colours + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_ColourTable, + L"colours.col")) { + DLCColourTableFile* colourFile = + (DLCColourTableFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_ColourTable, L"colours.col"); + m_colourTable = colourFile->getColourTable(); + m_bUsingDefaultColourTable = false; + } else { + // 4J Stu - We can delete the default colour table, but not the one from + // the DLCColourTableFile + if (!m_bUsingDefaultColourTable) m_colourTable = NULL; + loadDefaultColourTable(); + m_bUsingDefaultColourTable = true; + } -void DLCTexturePack::loadColourTable() -{ - // Load the game colours - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_ColourTable, L"colours.col")) - { - DLCColourTableFile *colourFile = (DLCColourTableFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_ColourTable, L"colours.col"); - m_colourTable = colourFile->getColourTable(); - m_bUsingDefaultColourTable = false; - } - else - { - // 4J Stu - We can delete the default colour table, but not the one from the DLCColourTableFile - if(!m_bUsingDefaultColourTable) m_colourTable = NULL; - loadDefaultColourTable(); - m_bUsingDefaultColourTable = true; - } - - // Load the text colours + // Load the text colours #ifdef _XBOX - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) - { - DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, + L"TexturePack.xzp")) { + DLCUIDataFile* dataFile = (DLCUIDataFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); - std::uint32_t dwSize = 0; - std::uint8_t *pbData = dataFile->getData(dwSize); + std::uint32_t dwSize = 0; + std::uint8_t* pbData = dataFile->getData(dwSize); - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; - - // Try and load the HTMLColours.col based off the common XML first, before the deprecated xuiscene_colourtable - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#HTMLColours.col",pbData, dwSize); - std::uint8_t *data; - unsigned int dataLength; - if(XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) - { - m_colourTable->loadColoursFromData(data,dataLength); + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - XuiFree(data); - } - else - { + // Try and load the HTMLColours.col based off the common XML first, + // before the deprecated xuiscene_colourtable + swprintf(szResourceLocator, LOCATOR_SIZE, + L"memory://%08X,%04X#HTMLColours.col", pbData, dwSize); + std::uint8_t* data; + unsigned int dataLength; + if (XuiResourceLoadAll(szResourceLocator, &data, &dataLength) == S_OK) { + m_colourTable->loadColoursFromData(data, dataLength); - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#xuiscene_colourtable.xur",pbData, dwSize); - HXUIOBJ hScene; - HRESULT hr = XuiSceneCreate(szResourceLocator,szResourceLocator, NULL, &hScene); + XuiFree(data); + } else { + swprintf(szResourceLocator, LOCATOR_SIZE, + L"memory://%08X,%04X#xuiscene_colourtable.xur", pbData, + dwSize); + HXUIOBJ hScene; + HRESULT hr = XuiSceneCreate(szResourceLocator, szResourceLocator, + NULL, &hScene); - if(HRESULT_SUCCEEDED(hr)) - { - loadHTMLColourTableFromXuiScene(hScene); - } - else - { - loadDefaultHTMLColourTable(); - } - } - } - else - { - loadDefaultHTMLColourTable(); - } + if (HRESULT_SUCCEEDED(hr)) { + loadHTMLColourTableFromXuiScene(hScene); + } else { + loadDefaultHTMLColourTable(); + } + } + } else { + loadDefaultHTMLColourTable(); + } #else - if(app.hasArchiveFile(L"HTMLColours.col")) - { - byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); - m_colourTable->loadColoursFromData(textColours.data,textColours.length); + if (app.hasArchiveFile(L"HTMLColours.col")) { + byteArray textColours = app.getArchiveFile(L"HTMLColours.col"); + m_colourTable->loadColoursFromData(textColours.data, + textColours.length); - delete [] textColours.data; - } + delete[] textColours.data; + } #endif } -void DLCTexturePack::loadData() -{ - int mountIndex = m_dlcInfoPack->GetDLCMountIndex(); +void DLCTexturePack::loadData() { + int mountIndex = m_dlcInfoPack->GetDLCMountIndex(); - if(mountIndex > -1) - { + if (mountIndex > -1) { #ifdef _DURANGO - if(StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(),mountIndex,&DLCTexturePack::packMounted,this,L"TPACK")!=ERROR_IO_PENDING) + if (StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(), + mountIndex, + &DLCTexturePack::packMounted, this, + L"TPACK") != ERROR_IO_PENDING) #else - if(StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(),mountIndex,&DLCTexturePack::packMounted,this,"TPACK")!=ERROR_IO_PENDING) + if (StorageManager.MountInstalledDLC(ProfileManager.GetPrimaryPad(), + mountIndex, + &DLCTexturePack::packMounted, this, + "TPACK") != ERROR_IO_PENDING) #endif - { - // corrupt DLC - m_bHasLoadedData = true; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - app.DebugPrintf("Failed to mount texture pack DLC %d for pad %d\n",mountIndex,ProfileManager.GetPrimaryPad()); - } - else - { - m_bLoadingData = true; - app.DebugPrintf("Attempted to mount DLC data for texture pack %d\n", mountIndex); - } - } - else - { - m_bHasLoadedData = true; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); - } + { + // corrupt DLC + m_bHasLoadedData = true; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + app.DebugPrintf("Failed to mount texture pack DLC %d for pad %d\n", + mountIndex, ProfileManager.GetPrimaryPad()); + } else { + m_bLoadingData = true; + app.DebugPrintf("Attempted to mount DLC data for texture pack %d\n", + mountIndex); + } + } else { + m_bHasLoadedData = true; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_ReloadTexturePack); + } } - - - - -std::wstring DLCTexturePack::getFilePath(std::uint32_t packId, std::wstring filename, bool bAddDataFolder) -{ - return app.getFilePath(packId,filename,bAddDataFolder); +std::wstring DLCTexturePack::getFilePath(std::uint32_t packId, + std::wstring filename, + bool bAddDataFolder) { + return app.getFilePath(packId, filename, bAddDataFolder); } -int DLCTexturePack::packMounted(void *pParam,int iPad,std::uint32_t dwErr,std::uint32_t dwLicenceMask) -{ - DLCTexturePack *texturePack = static_cast(pParam); - texturePack->m_bLoadingData = false; - if(dwErr!=ERROR_SUCCESS) - { - // corrupt DLC - app.DebugPrintf("Failed to mount DLC for pad %d: %u\n",iPad,dwErr); - } - else - { - app.DebugPrintf("Mounted DLC for texture pack, attempting to load data\n"); - texturePack->m_dlcDataPack = new DLCPack(texturePack->m_dlcInfoPack->getName(), dwLicenceMask); - texturePack->setHasAudio(false); - unsigned int dwFilesProcessed = 0; - // Load the DLC textures - std::wstring dataFilePath = texturePack->m_dlcInfoPack->getFullDataPath(); - if(!dataFilePath.empty()) - { - if(!app.m_dlcManager.readDLCDataFile(dwFilesProcessed, getFilePath(texturePack->m_dlcInfoPack->GetPackID(), dataFilePath),texturePack->m_dlcDataPack)) - { - delete texturePack->m_dlcDataPack; - texturePack->m_dlcDataPack = NULL; - } +int DLCTexturePack::packMounted(void* pParam, int iPad, std::uint32_t dwErr, + std::uint32_t dwLicenceMask) { + DLCTexturePack* texturePack = static_cast(pParam); + texturePack->m_bLoadingData = false; + if (dwErr != ERROR_SUCCESS) { + // corrupt DLC + app.DebugPrintf("Failed to mount DLC for pad %d: %u\n", iPad, dwErr); + } else { + app.DebugPrintf( + "Mounted DLC for texture pack, attempting to load data\n"); + texturePack->m_dlcDataPack = + new DLCPack(texturePack->m_dlcInfoPack->getName(), dwLicenceMask); + texturePack->setHasAudio(false); + unsigned int dwFilesProcessed = 0; + // Load the DLC textures + std::wstring dataFilePath = + texturePack->m_dlcInfoPack->getFullDataPath(); + if (!dataFilePath.empty()) { + if (!app.m_dlcManager.readDLCDataFile( + dwFilesProcessed, + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + dataFilePath), + texturePack->m_dlcDataPack)) { + delete texturePack->m_dlcDataPack; + texturePack->m_dlcDataPack = NULL; + } - // Load the UI data - if(texturePack->m_dlcDataPack != NULL) - { + // Load the UI data + if (texturePack->m_dlcDataPack != NULL) { #ifdef _XBOX - File xzpPath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"TexturePack.xzp") ) ); + File xzpPath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"TexturePack.xzp"))); - if(xzpPath.exists()) - { - std::uint8_t *pbData = NULL; - unsigned int bytesRead = 0; - if( ReadPortableBinaryFile(xzpPath, pbData, bytesRead) ) - { - DLCUIDataFile *uiDLCFile = (DLCUIDataFile *)texturePack->m_dlcDataPack->addFile(DLCManager::e_DLCType_UIData,L"TexturePack.xzp"); - uiDLCFile->addData(pbData,bytesRead,true); - } - } + if (xzpPath.exists()) { + std::uint8_t* pbData = NULL; + unsigned int bytesRead = 0; + if (ReadPortableBinaryFile(xzpPath, pbData, bytesRead)) { + DLCUIDataFile* uiDLCFile = + (DLCUIDataFile*)texturePack->m_dlcDataPack->addFile( + DLCManager::e_DLCType_UIData, + L"TexturePack.xzp"); + uiDLCFile->addData(pbData, bytesRead, true); + } + } #else - File archivePath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"media.arc") ) ); - if(archivePath.exists()) texturePack->m_archiveFile = new ArchiveFile(archivePath); + File archivePath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"media.arc"))); + if (archivePath.exists()) + texturePack->m_archiveFile = new ArchiveFile(archivePath); #endif - /** - 4J-JEV: - For all the GameRuleHeader files we find - */ - DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); - LevelGenerationOptions *levelGen = app.getLevelGenerationOptions(); - if (levelGen != NULL && !levelGen->hasLoadedData()) - { - int gameRulesCount = pack->getDLCItemsCount(DLCManager::e_DLCType_GameRulesHeader); - for(int i = 0; i < gameRulesCount; ++i) - { - DLCGameRulesHeader *dlcFile = (DLCGameRulesHeader *) pack->getFile(DLCManager::e_DLCType_GameRulesHeader, i); - - if (!dlcFile->getGrfPath().empty()) - { - File grf( getFilePath(texturePack->m_dlcInfoPack->GetPackID(), dlcFile->getGrfPath() ) ); - if (grf.exists()) - { - std::uint8_t *pbData = NULL; - unsigned int fileSize = 0; - if( ReadPortableBinaryFile(grf, pbData, fileSize) ) - { - // 4J-PB - is it possible that we can get here after a read fail and it's not an error? - dlcFile->setGrfData(pbData, fileSize, texturePack->m_stringTable); + /** + 4J-JEV: + For all the GameRuleHeader files we find + */ + DLCPack* pack = texturePack->m_dlcInfoPack->GetParentPack(); + LevelGenerationOptions* levelGen = + app.getLevelGenerationOptions(); + if (levelGen != NULL && !levelGen->hasLoadedData()) { + int gameRulesCount = pack->getDLCItemsCount( + DLCManager::e_DLCType_GameRulesHeader); + for (int i = 0; i < gameRulesCount; ++i) { + DLCGameRulesHeader* dlcFile = + (DLCGameRulesHeader*)pack->getFile( + DLCManager::e_DLCType_GameRulesHeader, i); - delete [] pbData; + if (!dlcFile->getGrfPath().empty()) { + File grf(getFilePath( + texturePack->m_dlcInfoPack->GetPackID(), + dlcFile->getGrfPath())); + if (grf.exists()) { + std::uint8_t* pbData = NULL; + unsigned int fileSize = 0; + if (ReadPortableBinaryFile(grf, pbData, + fileSize)) { + // 4J-PB - is it possible that we can get + // here after a read fail and it's not an + // error? + dlcFile->setGrfData( + pbData, fileSize, + texturePack->m_stringTable); - app.m_gameRules.setLevelGenerationOptions( dlcFile->lgo ); - } - else - { - app.FatalLoadError(); - } - } - } - } - if(levelGen->requiresBaseSave() && !levelGen->getBaseSavePath().empty() ) - { - File grf(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), levelGen->getBaseSavePath() )); - if (grf.exists()) - { - std::uint8_t *pbData = NULL; - unsigned int fileSize = 0; - if( ReadPortableBinaryFile(grf, pbData, fileSize) ) - { - // 4J-PB - is it possible that we can get here after a read fail and it's not an error? - levelGen->setBaseSaveData(pbData, fileSize); - } - else - { - app.FatalLoadError(); - } - } - } - } - + delete[] pbData; - // any audio data? -#ifdef _XBOX - File audioXSBPath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"MashUp.xsb") ) ); - File audioXWBPath(getFilePath(texturePack->m_dlcInfoPack->GetPackID(), std::wstring(L"MashUp.xwb") ) ); - - if(audioXSBPath.exists() && audioXWBPath.exists()) - { + app.m_gameRules.setLevelGenerationOptions( + dlcFile->lgo); + } else { + app.FatalLoadError(); + } + } + } + } + if (levelGen->requiresBaseSave() && + !levelGen->getBaseSavePath().empty()) { + File grf( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + levelGen->getBaseSavePath())); + if (grf.exists()) { + std::uint8_t* pbData = NULL; + unsigned int fileSize = 0; + if (ReadPortableBinaryFile(grf, pbData, fileSize)) { + // 4J-PB - is it possible that we can get here + // after a read fail and it's not an error? + levelGen->setBaseSaveData(pbData, fileSize); + } else { + app.FatalLoadError(); + } + } + } + } - texturePack->setHasAudio(true); - const char *pchXWBFilename=wstringtofilename(audioXWBPath.getPath()); - Minecraft::GetInstance()->soundEngine->CreateStreamingWavebank(pchXWBFilename,&texturePack->m_pStreamedWaveBank); - const char *pchXSBFilename=wstringtofilename(audioXSBPath.getPath()); - Minecraft::GetInstance()->soundEngine->CreateSoundbank(pchXSBFilename,&texturePack->m_pSoundBank); - - } -#else - //DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); - if(pack->getDLCItemsCount(DLCManager::e_DLCType_Audio)>0) - { - DLCAudioFile *dlcFile = (DLCAudioFile *) pack->getFile(DLCManager::e_DLCType_Audio, 0); - texturePack->setHasAudio(true); - // init the streaming sound ids for this texture pack - int iOverworldStart, iNetherStart, iEndStart; - int iOverworldC, iNetherC, iEndC; - - iOverworldStart=0; - iOverworldC=dlcFile->GetCountofType(DLCAudioFile::e_AudioType_Overworld); - iNetherStart=iOverworldC; - iNetherC=dlcFile->GetCountofType(DLCAudioFile::e_AudioType_Nether); - iEndStart=iOverworldC+iNetherC; - iEndC=dlcFile->GetCountofType(DLCAudioFile::e_AudioType_End); - - Minecraft::GetInstance()->soundEngine->SetStreamingSounds(iOverworldStart,iOverworldStart+iOverworldC, - iNetherStart,iNetherStart+iNetherC,iEndStart,iEndStart+iEndC,iEndStart+iEndC); // push the CD start to after - } -#endif -} - texturePack->loadColourTable(); - } - - // 4J-PB - we need to leave the texture pack mounted if it contained streaming audio - if(texturePack->hasAudio()==false) - { + // any audio data? #ifdef _XBOX - StorageManager.UnmountInstalledDLC("TPACK"); -#endif - } - } - - texturePack->m_bHasLoadedData = true; - if (app.getLevelGenerationOptions()) app.getLevelGenerationOptions()->setLoadedData(); - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); + File audioXSBPath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"MashUp.xsb"))); + File audioXWBPath( + getFilePath(texturePack->m_dlcInfoPack->GetPackID(), + std::wstring(L"MashUp.xwb"))); - return 0; -} - -void DLCTexturePack::loadUI() -{ -#ifdef _XBOX -//Syntax: "memory://" + Address + "," + Size + "#" + File -//L"memory://0123ABCD,21A3#skin_default.xur" - - // Load new skin - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) - { - DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); - - std::uint32_t dwSize = 0; - std::uint8_t *pbData = dataFile->getData(dwSize); - - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#skin_Minecraft.xur",pbData, dwSize); - - XuiFreeVisuals(L""); - - - HRESULT hr = app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); - if(HRESULT_SUCCEEDED(hr)) - { - bUILoaded = true; - //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); - //CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); - } - } + if (audioXSBPath.exists() && audioXWBPath.exists()) { + texturePack->setHasAudio(true); + const char* pchXWBFilename = + wstringtofilename(audioXWBPath.getPath()); + Minecraft::GetInstance() + ->soundEngine->CreateStreamingWavebank( + pchXWBFilename, &texturePack->m_pStreamedWaveBank); + const char* pchXSBFilename = + wstringtofilename(audioXSBPath.getPath()); + Minecraft::GetInstance()->soundEngine->CreateSoundbank( + pchXSBFilename, &texturePack->m_pSoundBank); + } #else - if(m_archiveFile && m_archiveFile->hasFile(L"skin.swf")) - { - ui.ReloadSkin(); - bUILoaded = true; - } -#endif - else - { - loadDefaultUI(); - bUILoaded = true; - } + // DLCPack *pack = texturePack->m_dlcInfoPack->GetParentPack(); + if (pack->getDLCItemsCount(DLCManager::e_DLCType_Audio) > 0) { + DLCAudioFile* dlcFile = (DLCAudioFile*)pack->getFile( + DLCManager::e_DLCType_Audio, 0); + texturePack->setHasAudio(true); + // init the streaming sound ids for this texture pack + int iOverworldStart, iNetherStart, iEndStart; + int iOverworldC, iNetherC, iEndC; - AbstractTexturePack::loadUI(); + iOverworldStart = 0; + iOverworldC = dlcFile->GetCountofType( + DLCAudioFile::e_AudioType_Overworld); + iNetherStart = iOverworldC; + iNetherC = dlcFile->GetCountofType( + DLCAudioFile::e_AudioType_Nether); + iEndStart = iOverworldC + iNetherC; + iEndC = + dlcFile->GetCountofType(DLCAudioFile::e_AudioType_End); + + Minecraft::GetInstance()->soundEngine->SetStreamingSounds( + iOverworldStart, iOverworldStart + iOverworldC, + iNetherStart, iNetherStart + iNetherC, iEndStart, + iEndStart + iEndC, + iEndStart + iEndC); // push the CD start to after + } +#endif + } + texturePack->loadColourTable(); + } + + // 4J-PB - we need to leave the texture pack mounted if it contained + // streaming audio + if (texturePack->hasAudio() == false) { +#ifdef _XBOX + StorageManager.UnmountInstalledDLC("TPACK"); +#endif + } + } + + texturePack->m_bHasLoadedData = true; + if (app.getLevelGenerationOptions()) + app.getLevelGenerationOptions()->setLoadedData(); + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); + + return 0; +} + +void DLCTexturePack::loadUI() { +#ifdef _XBOX + // Syntax: "memory://" + Address + "," + Size + "#" + File + // L"memory://0123ABCD,21A3#skin_default.xur" + + // Load new skin + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, + L"TexturePack.xzp")) { + DLCUIDataFile* dataFile = (DLCUIDataFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); + + std::uint32_t dwSize = 0; + std::uint8_t* pbData = dataFile->getData(dwSize); + + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; + swprintf(szResourceLocator, LOCATOR_SIZE, + L"memory://%08X,%04X#skin_Minecraft.xur", pbData, dwSize); + + XuiFreeVisuals(L""); + + HRESULT hr = app.LoadSkin(szResourceLocator, NULL); // L"TexturePack"); + if (HRESULT_SUCCEEDED(hr)) { + bUILoaded = true; + // CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); + // CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + } + } +#else + if (m_archiveFile && m_archiveFile->hasFile(L"skin.swf")) { + ui.ReloadSkin(); + bUILoaded = true; + } +#endif + else { + loadDefaultUI(); + bUILoaded = true; + } + + AbstractTexturePack::loadUI(); #ifndef _XBOX - if(hasAudio()==false && !ui.IsReloadingSkin()) - { + if (hasAudio() == false && !ui.IsReloadingSkin()) { #ifdef _DURANGO - StorageManager.UnmountInstalledDLC(L"TPACK"); + StorageManager.UnmountInstalledDLC(L"TPACK"); #else - StorageManager.UnmountInstalledDLC("TPACK"); + StorageManager.UnmountInstalledDLC("TPACK"); #endif - } + } #endif } -void DLCTexturePack::unloadUI() -{ - // Unload skin - if(bUILoaded) - { +void DLCTexturePack::unloadUI() { + // Unload skin + if (bUILoaded) { #ifdef _XBOX - XuiFreeVisuals(L"TexturePack"); - XuiFreeVisuals(L""); - CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + XuiFreeVisuals(L"TexturePack"); + XuiFreeVisuals(L""); + CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #endif - setHasAudio(false); - } - AbstractTexturePack::unloadUI(); + setHasAudio(false); + } + AbstractTexturePack::unloadUI(); - app.m_dlcManager.removePack(m_dlcDataPack); - m_dlcDataPack = NULL; - delete m_archiveFile; - m_bHasLoadedData = false; + app.m_dlcManager.removePack(m_dlcDataPack); + m_dlcDataPack = NULL; + delete m_archiveFile; + m_bHasLoadedData = false; - bUILoaded = false; + bUILoaded = false; } -std::wstring DLCTexturePack::getXuiRootPath() -{ - std::wstring path = L""; - if(m_dlcDataPack != NULL && m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp")) - { - DLCUIDataFile *dataFile = (DLCUIDataFile *)m_dlcDataPack->getFile(DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); +std::wstring DLCTexturePack::getXuiRootPath() { + std::wstring path = L""; + if (m_dlcDataPack != NULL && + m_dlcDataPack->doesPackContainFile(DLCManager::e_DLCType_UIData, + L"TexturePack.xzp")) { + DLCUIDataFile* dataFile = (DLCUIDataFile*)m_dlcDataPack->getFile( + DLCManager::e_DLCType_UIData, L"TexturePack.xzp"); - std::uint32_t dwSize = 0; - std::uint8_t *pbData = dataFile->getData(dwSize); + std::uint32_t dwSize = 0; + std::uint8_t* pbData = dataFile->getData(dwSize); - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"memory://%08X,%04X#",pbData, dwSize); - path = szResourceLocator; - } - return path; + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; + swprintf(szResourceLocator, LOCATOR_SIZE, L"memory://%08X,%04X#", + pbData, dwSize); + path = szResourceLocator; + } + return path; } -unsigned int DLCTexturePack::getDLCParentPackId() -{ - return m_dlcInfoPack->GetParentPackId(); +unsigned int DLCTexturePack::getDLCParentPackId() { + return m_dlcInfoPack->GetParentPackId(); } -unsigned char DLCTexturePack::getDLCSubPackId() -{ - return (m_dlcInfoPack->GetPackId()>>24)&0xFF; +unsigned char DLCTexturePack::getDLCSubPackId() { + return (m_dlcInfoPack->GetPackId() >> 24) & 0xFF; } -DLCPack * DLCTexturePack::getDLCInfoParentPack() -{ - return m_dlcInfoPack->GetParentPack(); +DLCPack* DLCTexturePack::getDLCInfoParentPack() { + return m_dlcInfoPack->GetParentPack(); } -XCONTENTDEVICEID DLCTexturePack::GetDLCDeviceID() -{ - return m_dlcInfoPack->GetDLCDeviceID(); +XCONTENTDEVICEID DLCTexturePack::GetDLCDeviceID() { + return m_dlcInfoPack->GetDLCDeviceID(); } diff --git a/Minecraft.Client/Textures/Packs/DLCTexturePack.h b/Minecraft.Client/Textures/Packs/DLCTexturePack.h index 39ca39e27..1d2c7acde 100644 --- a/Minecraft.Client/Textures/Packs/DLCTexturePack.h +++ b/Minecraft.Client/Textures/Packs/DLCTexturePack.h @@ -5,68 +5,73 @@ class DLCPack; class StringTable; -class DLCTexturePack : public AbstractTexturePack -{ +class DLCTexturePack : public AbstractTexturePack { private: - DLCPack *m_dlcInfoPack; // Description, icon etc - DLCPack *m_dlcDataPack; // Actual textures - StringTable *m_stringTable; - bool bUILoaded; - bool m_bLoadingData, m_bHasLoadedData; - bool m_bUsingDefaultColourTable; - //bool m_bHasAudio; - ArchiveFile *m_archiveFile; - - + DLCPack* m_dlcInfoPack; // Description, icon etc + DLCPack* m_dlcDataPack; // Actual textures + StringTable* m_stringTable; + bool bUILoaded; + bool m_bLoadingData, m_bHasLoadedData; + bool m_bUsingDefaultColourTable; + // bool m_bHasAudio; + ArchiveFile* m_archiveFile; public: - using AbstractTexturePack::getResource; + using AbstractTexturePack::getResource; - DLCTexturePack(std::uint32_t id, DLCPack *pack, TexturePack *fallback); - ~DLCTexturePack(){}; + DLCTexturePack(std::uint32_t id, DLCPack* pack, TexturePack* fallback); + ~DLCTexturePack() {}; - virtual std::wstring getResource(const std::wstring& name); - virtual DLCPack * getDLCPack(); - // Added for sound banks with MashUp packs + virtual std::wstring getResource(const std::wstring& name); + virtual DLCPack* getDLCPack(); + // Added for sound banks with MashUp packs #ifdef _XBOX - IXACT3WaveBank *m_pStreamedWaveBank; - IXACT3SoundBank *m_pSoundBank; + IXACT3WaveBank* m_pStreamedWaveBank; + IXACT3SoundBank* m_pSoundBank; #endif protected: - //@Override - void loadIcon(); - void loadComparison(); - void loadName(); - void loadDescription(); - InputStream *getResourceImplementation(const std::wstring &name); //throws IOException + //@Override + void loadIcon(); + void loadComparison(); + void loadName(); + void loadDescription(); + InputStream* getResourceImplementation( + const std::wstring& name); // throws IOException public: - //@Override - bool hasFile(const std::wstring &name); - bool isTerrainUpdateCompatible(); + //@Override + bool hasFile(const std::wstring& name); + bool isTerrainUpdateCompatible(); - // 4J Added - virtual std::wstring getPath(bool bTitleUpdateTexture = false); - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path); - virtual BufferedImage *getImageResource(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L""); - virtual void loadColourTable(); - virtual bool hasData() { return m_bHasLoadedData; } - virtual bool isLoadingData() { return m_bLoadingData; } + // 4J Added + virtual std::wstring getPath(bool bTitleUpdateTexture = false); + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path); + virtual BufferedImage* getImageResource(const std::wstring& File, + bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, + const std::wstring& drive = L""); + virtual void loadColourTable(); + virtual bool hasData() { return m_bHasLoadedData; } + virtual bool isLoadingData() { return m_bLoadingData; } private: - static std::wstring getRootPath(std::uint32_t packId, bool allowOverride, bool bAddDataFolder); - static std::wstring getFilePath(std::uint32_t packId, std::wstring filename, bool bAddDataFolder=true); + static std::wstring getRootPath(std::uint32_t packId, bool allowOverride, + bool bAddDataFolder); + static std::wstring getFilePath(std::uint32_t packId, std::wstring filename, + bool bAddDataFolder = true); public: - static int packMounted(void *pParam,int iPad,std::uint32_t dwErr,std::uint32_t dwLicenceMask); - virtual void loadData(); - virtual void loadUI(); - virtual void unloadUI(); - virtual std::wstring getXuiRootPath(); - virtual ArchiveFile *getArchiveFile() { return m_archiveFile; } + static int packMounted(void* pParam, int iPad, std::uint32_t dwErr, + std::uint32_t dwLicenceMask); + virtual void loadData(); + virtual void loadUI(); + virtual void unloadUI(); + virtual std::wstring getXuiRootPath(); + virtual ArchiveFile* getArchiveFile() { return m_archiveFile; } - virtual unsigned int getDLCParentPackId(); - virtual DLCPack *getDLCInfoParentPack(); - virtual unsigned char getDLCSubPackId(); - XCONTENTDEVICEID GetDLCDeviceID(); + virtual unsigned int getDLCParentPackId(); + virtual DLCPack* getDLCInfoParentPack(); + virtual unsigned char getDLCSubPackId(); + XCONTENTDEVICEID GetDLCDeviceID(); }; diff --git a/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp b/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp index a6e59d471..e1a92faef 100644 --- a/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/DefaultTexturePack.cpp @@ -3,129 +3,122 @@ #include "../Textures.h" #include "../../../Minecraft.World/Util/StringHelpers.h" - -DefaultTexturePack::DefaultTexturePack() : AbstractTexturePack(0, NULL, L"Minecraft", NULL) -{ - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); // 4J-PB - added so the PS3 can have localised texture names' - loadDescription(); - loadColourTable(); +DefaultTexturePack::DefaultTexturePack() + : AbstractTexturePack(0, NULL, L"Minecraft", NULL) { + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); // 4J-PB - added so the PS3 can have localised texture names' + loadDescription(); + loadColourTable(); } -void DefaultTexturePack::loadIcon() -{ +void DefaultTexturePack::loadIcon() { #ifdef _XBOX - // 4J Stu - Temporary only - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // 4J Stu - Temporary only + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - swprintf(szResourceLocator, LOCATOR_SIZE ,L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/Graphics/TexturePackIcon.png"); + const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); + swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls", + c_ModuleHandle, L"media", L"media/Graphics/TexturePackIcon.png"); - unsigned int size = 0; - HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); - m_iconSize = size; + unsigned int size = 0; + HRESULT hr = XuiResourceLoadAllNoLoc(szResourceLocator, &m_iconData, &size); + m_iconSize = size; #else - if(app.hasArchiveFile(L"Graphics\\TexturePackIcon.png")) - { - byteArray ba = app.getArchiveFile(L"Graphics\\TexturePackIcon.png"); - m_iconData = ba.data; - m_iconSize = static_cast(ba.length); - } + if (app.hasArchiveFile(L"Graphics\\TexturePackIcon.png")) { + byteArray ba = app.getArchiveFile(L"Graphics\\TexturePackIcon.png"); + m_iconData = ba.data; + m_iconSize = static_cast(ba.length); + } #endif } -void DefaultTexturePack::loadDescription() -{ - desc1 = L"LOCALISE ME: The default look of Minecraft"; +void DefaultTexturePack::loadDescription() { + desc1 = L"LOCALISE ME: The default look of Minecraft"; } -void DefaultTexturePack::loadName() -{ - texname = L"Minecraft"; +void DefaultTexturePack::loadName() { texname = L"Minecraft"; } + +bool DefaultTexturePack::hasFile(const std::wstring& name) { + // return DefaultTexturePack::class->getResourceAsStream(name) != null; + return true; } -bool DefaultTexturePack::hasFile(const std::wstring &name) -{ -// return DefaultTexturePack::class->getResourceAsStream(name) != null; - return true; -} +bool DefaultTexturePack::isTerrainUpdateCompatible() { return true; } -bool DefaultTexturePack::isTerrainUpdateCompatible() +InputStream* DefaultTexturePack::getResourceImplementation( + const std::wstring& name) // throws FileNotFoundException { - return true; -} - -InputStream *DefaultTexturePack::getResourceImplementation(const std::wstring &name)// throws FileNotFoundException -{ - std::wstring wDrive = L""; - // Make the content package point to to the UPDATE: drive is needed + std::wstring wDrive = L""; + // Make the content package point to to the UPDATE: drive is needed #ifdef _XBOX - #ifdef _TU_BUILD - wDrive=L"UPDATE:\\res"; - #else - - wDrive=L"GAME:\\res\\TitleUpdate\\res"; - #endif +#ifdef _TU_BUILD + wDrive = L"UPDATE:\\res"; +#else + + wDrive = L"GAME:\\res\\TitleUpdate\\res"; +#endif #elif __PS3__ - char *pchUsrDir; - if(app.GetBootedFromDiscPatch()) - { - const char *pchTextureName=wstringtofilename(name); - pchUsrDir = app.GetBDUsrDirPath(pchTextureName); - app.DebugPrintf("DefaultTexturePack::getResourceImplementation - texture %s - Drive - %s\n",pchTextureName,pchUsrDir); - } - else - { - const char *pchTextureName=wstringtofilename(name); - pchUsrDir=getUsrDirPath(); - app.DebugPrintf("DefaultTexturePack::getResourceImplementation - texture %s - Drive - %s\n",pchTextureName,pchUsrDir); - } + char* pchUsrDir; + if (app.GetBootedFromDiscPatch()) { + const char* pchTextureName = wstringtofilename(name); + pchUsrDir = app.GetBDUsrDirPath(pchTextureName); + app.DebugPrintf( + "DefaultTexturePack::getResourceImplementation - texture %s - " + "Drive - %s\n", + pchTextureName, pchUsrDir); + } else { + const char* pchTextureName = wstringtofilename(name); + pchUsrDir = getUsrDirPath(); + app.DebugPrintf( + "DefaultTexturePack::getResourceImplementation - texture %s - " + "Drive - %s\n", + pchTextureName, pchUsrDir); + } + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - - wDrive = wstr + L"\\Common\\res\\TitleUpdate\\res"; + wDrive = wstr + L"\\Common\\res\\TitleUpdate\\res"; #elif __PSVITA__ - /* - char *pchUsrDir=getUsrDirPath(); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - - wDrive = wstr + L"Common\\res\\TitleUpdate\\res"; - */ - wDrive = L"Common\\res\\TitleUpdate\\res"; + /* + char *pchUsrDir=getUsrDirPath(); + std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + + wDrive = wstr + L"Common\\res\\TitleUpdate\\res"; + */ + wDrive = L"Common\\res\\TitleUpdate\\res"; #else - wDrive = L"Common\\res\\TitleUpdate\\res"; + wDrive = L"Common\\res\\TitleUpdate\\res"; #endif - InputStream *resource = InputStream::getResourceAsStream(wDrive + name); - //InputStream *stream = DefaultTexturePack::class->getResourceAsStream(name); - //if (stream == NULL) - //{ - // throw new FileNotFoundException(name); - //} + InputStream* resource = InputStream::getResourceAsStream(wDrive + name); + // InputStream *stream = + // DefaultTexturePack::class->getResourceAsStream(name); if (stream == NULL) + //{ + // throw new FileNotFoundException(name); + // } - //return stream; - return resource; + // return stream; + return resource; } -void DefaultTexturePack::loadUI() -{ - loadDefaultUI(); +void DefaultTexturePack::loadUI() { + loadDefaultUI(); - AbstractTexturePack::loadUI(); + AbstractTexturePack::loadUI(); } -void DefaultTexturePack::unloadUI() -{ +void DefaultTexturePack::unloadUI() { #ifdef _XBOX - // Unload skin - XuiFreeVisuals(L"TexturePack"); - XuiFreeVisuals(L""); - CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); + // Unload skin + XuiFreeVisuals(L"TexturePack"); + XuiFreeVisuals(L""); + CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); #endif - AbstractTexturePack::unloadUI(); + AbstractTexturePack::unloadUI(); } diff --git a/Minecraft.Client/Textures/Packs/DefaultTexturePack.h b/Minecraft.Client/Textures/Packs/DefaultTexturePack.h index 1b46f22f3..a3f5f9efb 100644 --- a/Minecraft.Client/Textures/Packs/DefaultTexturePack.h +++ b/Minecraft.Client/Textures/Packs/DefaultTexturePack.h @@ -1,33 +1,33 @@ #pragma once #include "AbstractTexturePack.h" -class DefaultTexturePack : public AbstractTexturePack -{ +class DefaultTexturePack : public AbstractTexturePack { public: - DefaultTexturePack(); - DLCPack * getDLCPack() {return NULL;} + DefaultTexturePack(); + DLCPack* getDLCPack() { return NULL; } protected: - //@Override - void loadIcon(); - void loadName(); - void loadDescription(); + //@Override + void loadIcon(); + void loadName(); + void loadDescription(); public: - //@Override - bool hasFile(const std::wstring &name); - bool isTerrainUpdateCompatible(); + //@Override + bool hasFile(const std::wstring& name); + bool isTerrainUpdateCompatible(); - std::wstring getDesc1() {return app.GetString(IDS_DEFAULT_TEXTUREPACK);} + std::wstring getDesc1() { return app.GetString(IDS_DEFAULT_TEXTUREPACK); } protected: - //@Override - InputStream *getResourceImplementation(const std::wstring &name); // throws FileNotFoundException + //@Override + InputStream* getResourceImplementation( + const std::wstring& name); // throws FileNotFoundException public: - virtual bool hasData() { return true; } - virtual bool hasAudio() { return false; } - virtual bool isLoadingData() { return false; } - virtual void loadUI(); - virtual void unloadUI(); + virtual bool hasData() { return true; } + virtual bool hasAudio() { return false; } + virtual bool isLoadingData() { return false; } + virtual void loadUI(); + virtual void unloadUI(); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Packs/FileTexturePack.cpp b/Minecraft.Client/Textures/Packs/FileTexturePack.cpp index c70b462d6..5d0dee1b8 100644 --- a/Minecraft.Client/Textures/Packs/FileTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/FileTexturePack.cpp @@ -1,16 +1,16 @@ #include "../../Platform/stdafx.h" #include "FileTexturePack.h" -FileTexturePack::FileTexturePack(std::uint32_t id, File *file, TexturePack *fallback) : AbstractTexturePack(id, file, file->getName(), fallback) -{ - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); - loadDescription(); +FileTexturePack::FileTexturePack(std::uint32_t id, File* file, + TexturePack* fallback) + : AbstractTexturePack(id, file, file->getName(), fallback) { + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); + loadDescription(); } -void FileTexturePack::unload(Textures *textures) -{ +void FileTexturePack::unload(Textures* textures) { #if 0 super.unload(textures); @@ -24,7 +24,8 @@ void FileTexturePack::unload(Textures *textures) #endif } -InputStream *FileTexturePack::getResourceImplementation(const std::wstring &name) //throws IOException +InputStream* FileTexturePack::getResourceImplementation( + const std::wstring& name) // throws IOException { #if 0 loadZipFile(); @@ -36,11 +37,10 @@ InputStream *FileTexturePack::getResourceImplementation(const std::wstring &name return zipFile.getInputStream(entry); #endif - return NULL; + return NULL; } -bool FileTexturePack::hasFile(const std::wstring &name) -{ +bool FileTexturePack::hasFile(const std::wstring& name) { #if 0 try { loadZipFile(); @@ -50,10 +50,10 @@ bool FileTexturePack::hasFile(const std::wstring &name) return false; } #endif - return false; + return false; } -void FileTexturePack::loadZipFile() //throws IOException +void FileTexturePack::loadZipFile() // throws IOException { #if 0 if (zipFile != null) { @@ -64,8 +64,7 @@ void FileTexturePack::loadZipFile() //throws IOException #endif } -bool FileTexturePack::isTerrainUpdateCompatible() -{ +bool FileTexturePack::isTerrainUpdateCompatible() { #if 0 try { loadZipFile(); @@ -82,5 +81,5 @@ bool FileTexturePack::isTerrainUpdateCompatible() boolean hasOldFiles = hasFile("terrain.png") || hasFile("gui/items.png"); return !hasOldFiles; #endif - return false; + return false; } diff --git a/Minecraft.Client/Textures/Packs/FileTexturePack.h b/Minecraft.Client/Textures/Packs/FileTexturePack.h index 3643d6f74..6db1ca759 100644 --- a/Minecraft.Client/Textures/Packs/FileTexturePack.h +++ b/Minecraft.Client/Textures/Packs/FileTexturePack.h @@ -1,32 +1,31 @@ #pragma once #include "AbstractTexturePack.h" -//class ZipFile; +// class ZipFile; class BufferedImage; class File; class Textures; - -class FileTexturePack : public AbstractTexturePack -{ +class FileTexturePack : public AbstractTexturePack { private: - //ZipFile *zipFile; + // ZipFile *zipFile; public: - FileTexturePack(std::uint32_t id, File *file, TexturePack *fallback); + FileTexturePack(std::uint32_t id, File* file, TexturePack* fallback); - //@Override - void unload(Textures *textures); + //@Override + void unload(Textures* textures); protected: - InputStream *getResourceImplementation(const std::wstring &name); //throws IOException + InputStream* getResourceImplementation( + const std::wstring& name); // throws IOException public: - //@Override - bool hasFile(const std::wstring &name); + //@Override + bool hasFile(const std::wstring& name); private: - void loadZipFile(); //throws IOException + void loadZipFile(); // throws IOException public: - bool isTerrainUpdateCompatible(); + bool isTerrainUpdateCompatible(); }; diff --git a/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp b/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp index 2365d08cb..8ca9267d9 100644 --- a/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/FolderTexturePack.cpp @@ -1,17 +1,19 @@ #include "../../Platform/stdafx.h" #include "FolderTexturePack.h" -FolderTexturePack::FolderTexturePack(std::uint32_t id, const std::wstring &name, File *folder, TexturePack *fallback) : AbstractTexturePack(id, folder, name, fallback) -{ - // 4J Stu - These calls need to be in the most derived version of the class - loadIcon(); - loadName(); - loadDescription(); +FolderTexturePack::FolderTexturePack(std::uint32_t id, const std::wstring& name, + File* folder, TexturePack* fallback) + : AbstractTexturePack(id, folder, name, fallback) { + // 4J Stu - These calls need to be in the most derived version of the class + loadIcon(); + loadName(); + loadDescription(); - bUILoaded = false; + bUILoaded = false; } -InputStream *FolderTexturePack::getResourceImplementation(const std::wstring &name) //throws IOException +InputStream* FolderTexturePack::getResourceImplementation( + const std::wstring& name) // throws IOException { #if 0 final File file = new File(this.file, name.substring(1)); @@ -22,89 +24,86 @@ InputStream *FolderTexturePack::getResourceImplementation(const std::wstring &na return new BufferedInputStream(new FileInputStream(file)); #endif - std::wstring wDrive = L""; - // Make the content package point to to the UPDATE: drive is needed + std::wstring wDrive = L""; + // Make the content package point to to the UPDATE: drive is needed #ifdef _XBOX - wDrive=L"GAME:\\DummyTexturePack\\res"; + wDrive = L"GAME:\\DummyTexturePack\\res"; #else - wDrive = L"Common\\DummyTexturePack\\res"; + wDrive = L"Common\\DummyTexturePack\\res"; #endif - InputStream *resource = InputStream::getResourceAsStream(wDrive + name); - //InputStream *stream = DefaultTexturePack::class->getResourceAsStream(name); - //if (stream == NULL) - //{ - // throw new FileNotFoundException(name); - //} + InputStream* resource = InputStream::getResourceAsStream(wDrive + name); + // InputStream *stream = + // DefaultTexturePack::class->getResourceAsStream(name); if (stream == NULL) + //{ + // throw new FileNotFoundException(name); + // } - //return stream; - return resource; + // return stream; + return resource; } -bool FolderTexturePack::hasFile(const std::wstring &name) -{ - File file = File( getPath() + name); - return file.exists() && file.isFile(); - //return true; +bool FolderTexturePack::hasFile(const std::wstring& name) { + File file = File(getPath() + name); + return file.exists() && file.isFile(); + // return true; } -bool FolderTexturePack::isTerrainUpdateCompatible() -{ +bool FolderTexturePack::isTerrainUpdateCompatible() { #if 0 final File dir = new File(this.file, "textures/"); final boolean hasTexturesFolder = dir.exists() && dir.isDirectory(); final boolean hasOldFiles = hasFile("terrain.png") || hasFile("gui/items.png"); return hasTexturesFolder || !hasOldFiles; #endif - return true; + return true; } -std::wstring FolderTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) -{ - std::wstring wDrive; +std::wstring FolderTexturePack::getPath(bool bTitleUpdateTexture /*= false*/) { + std::wstring wDrive; #ifdef _XBOX - wDrive=L"GAME:\\" + file->getPath() + L"\\"; + wDrive = L"GAME:\\" + file->getPath() + L"\\"; #else - wDrive=L"Common\\" + file->getPath() + L"\\"; + wDrive = L"Common\\" + file->getPath() + L"\\"; #endif - return wDrive; + return wDrive; } -void FolderTexturePack::loadUI() -{ +void FolderTexturePack::loadUI() { #ifdef _XBOX - //"file://" + Drive + PathToXZP + "#" + PathInsideXZP + //"file://" + Drive + PathToXZP + "#" + PathInsideXZP - //L"file://game:/ui.xzp#skin_default.xur" + // L"file://game:/ui.xzp#skin_default.xur" - // Load new skin - if(hasFile(L"TexturePack.xzp")) - { - constexpr int LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string - WCHAR szResourceLocator[ LOCATOR_SIZE ]; + // Load new skin + if (hasFile(L"TexturePack.xzp")) { + constexpr int LOCATOR_SIZE = + 256; // Use this to allocate space to hold a ResourceLocator string + WCHAR szResourceLocator[LOCATOR_SIZE]; - swprintf(szResourceLocator, LOCATOR_SIZE,L"file://%lsTexturePack.xzp#skin_Minecraft.xur",getPath().c_str()); + swprintf(szResourceLocator, LOCATOR_SIZE, + L"file://%lsTexturePack.xzp#skin_Minecraft.xur", + getPath().c_str()); - XuiFreeVisuals(L""); - app.LoadSkin(szResourceLocator,NULL);//L"TexturePack"); - bUILoaded = true; - //CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); - } + XuiFreeVisuals(L""); + app.LoadSkin(szResourceLocator, NULL); // L"TexturePack"); + bUILoaded = true; + // CXuiSceneBase::GetInstance()->SetVisualPrefix(L"TexturePack"); + } - AbstractTexturePack::loadUI(); + AbstractTexturePack::loadUI(); #endif } -void FolderTexturePack::unloadUI() -{ +void FolderTexturePack::unloadUI() { #ifdef _XBOX - // Unload skin - if(bUILoaded) - { - XuiFreeVisuals(L"TexturePack"); - XuiFreeVisuals(L""); - CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); - CXuiSceneBase::GetInstance()->SkinChanged(CXuiSceneBase::GetInstance()->m_hObj); - } - AbstractTexturePack::unloadUI(); + // Unload skin + if (bUILoaded) { + XuiFreeVisuals(L"TexturePack"); + XuiFreeVisuals(L""); + CXuiSceneBase::GetInstance()->SetVisualPrefix(L""); + CXuiSceneBase::GetInstance()->SkinChanged( + CXuiSceneBase::GetInstance()->m_hObj); + } + AbstractTexturePack::unloadUI(); #endif } diff --git a/Minecraft.Client/Textures/Packs/FolderTexturePack.h b/Minecraft.Client/Textures/Packs/FolderTexturePack.h index 3cd30859e..24105b1a1 100644 --- a/Minecraft.Client/Textures/Packs/FolderTexturePack.h +++ b/Minecraft.Client/Textures/Packs/FolderTexturePack.h @@ -2,25 +2,26 @@ #include "AbstractTexturePack.h" -class FolderTexturePack : public AbstractTexturePack -{ +class FolderTexturePack : public AbstractTexturePack { private: - bool bUILoaded; + bool bUILoaded; public: - FolderTexturePack(std::uint32_t id, const std::wstring &name, File *folder, TexturePack *fallback); + FolderTexturePack(std::uint32_t id, const std::wstring& name, File* folder, + TexturePack* fallback); protected: - //@Override - InputStream *getResourceImplementation(const std::wstring &name); //throws IOException + //@Override + InputStream* getResourceImplementation( + const std::wstring& name); // throws IOException public: - //@Override - bool hasFile(const std::wstring &name); - bool isTerrainUpdateCompatible(); + //@Override + bool hasFile(const std::wstring& name); + bool isTerrainUpdateCompatible(); - // 4J Added - virtual std::wstring getPath(bool bTitleUpdateTexture = false); - virtual void loadUI(); - virtual void unloadUI(); + // 4J Added + virtual std::wstring getPath(bool bTitleUpdateTexture = false); + virtual void loadUI(); + virtual void unloadUI(); }; diff --git a/Minecraft.Client/Textures/Packs/TexturePack.cpp b/Minecraft.Client/Textures/Packs/TexturePack.cpp index cd9a0adf8..eeccc03f3 100644 --- a/Minecraft.Client/Textures/Packs/TexturePack.cpp +++ b/Minecraft.Client/Textures/Packs/TexturePack.cpp @@ -1,70 +1,57 @@ #include "../../Platform/stdafx.h" #include "TexturePack.h" -std::wstring TexturePack::getPath(bool bTitleUpdateTexture /*= false*/) -{ - std::wstring wDrive; +std::wstring TexturePack::getPath(bool bTitleUpdateTexture /*= false*/) { + std::wstring wDrive; #ifdef _XBOX - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed #ifdef _TU_BUILD - wDrive=L"UPDATE:\\"; + wDrive = L"UPDATE:\\"; #else - wDrive=L"GAME:\\res\\TitleUpdate\\"; + wDrive = L"GAME:\\res\\TitleUpdate\\"; #endif - } - else - { - wDrive=L"GAME:\\"; - } + } else { + wDrive = L"GAME:\\"; + } #else #ifdef __PS3__ - // 4J-PB - we need to check for a BD patch - this is going to be an issue for full DLC texture packs (Halloween) + // 4J-PB - we need to check for a BD patch - this is going to be an issue + // for full DLC texture packs (Halloween) - char *pchUsrDir=getUsrDirPath(); - - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + char* pchUsrDir = getUsrDirPath(); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"/Common/"; - } + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = wstr + L"\\Common\\res\\TitleUpdate\\"; + } else { + wDrive = wstr + L"/Common/"; + } #elif __PSVITA__ - char *pchUsrDir="";//getUsrDirPath(); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + char* pchUsrDir = ""; // getUsrDirPath(); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive= wstr + L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive= wstr + L"Common\\"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = wstr + L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = wstr + L"Common\\"; + } #else - if(bTitleUpdateTexture) - { - // Make the content package point to to the UPDATE: drive is needed - wDrive=L"Common\\res\\TitleUpdate\\"; - } - else - { - wDrive=L"Common/"; - } + if (bTitleUpdateTexture) { + // Make the content package point to to the UPDATE: drive is needed + wDrive = L"Common\\res\\TitleUpdate\\"; + } else { + wDrive = L"Common/"; + } #endif #endif - return wDrive; + return wDrive; } diff --git a/Minecraft.Client/Textures/Packs/TexturePack.h b/Minecraft.Client/Textures/Packs/TexturePack.h index 621c3d458..cbd7f649b 100644 --- a/Minecraft.Client/Textures/Packs/TexturePack.h +++ b/Minecraft.Client/Textures/Packs/TexturePack.h @@ -8,54 +8,59 @@ class InputStream; class Minecraft; class ArchiveFile; -class TexturePack -{ +class TexturePack { public: - - TexturePack() { m_bHasAudio=false;} - virtual ~TexturePack(){} - virtual bool hasData() = 0; - virtual bool hasAudio() { return m_bHasAudio;} - virtual void setHasAudio(bool bVal) {m_bHasAudio=bVal;} - virtual bool isLoadingData() = 0; - virtual void loadData() {} - virtual void unload(Textures *textures) = 0; - virtual void load(Textures *textures) = 0; - virtual InputStream *getResource(const std::wstring &name, bool allowFallback) = 0;// throws IOException; - //virtual InputStream *getResource(const std::wstring &name) = 0;// throws IOException; + TexturePack() { m_bHasAudio = false; } + virtual ~TexturePack() {} + virtual bool hasData() = 0; + virtual bool hasAudio() { return m_bHasAudio; } + virtual void setHasAudio(bool bVal) { m_bHasAudio = bVal; } + virtual bool isLoadingData() = 0; + virtual void loadData() {} + virtual void unload(Textures* textures) = 0; + virtual void load(Textures* textures) = 0; + virtual InputStream* getResource( + const std::wstring& name, + bool allowFallback) = 0; // throws IOException; + // virtual InputStream *getResource(const std::wstring &name) = 0;// throws + // IOException; virtual std::uint32_t getId() = 0; virtual std::wstring getName() = 0; virtual std::wstring getDesc1() = 0; virtual std::wstring getDesc2() = 0; - virtual bool hasFile(const std::wstring &name, bool allowFallback) = 0; + virtual bool hasFile(const std::wstring& name, bool allowFallback) = 0; virtual bool isTerrainUpdateCompatible() = 0; - virtual std::wstring getResource(const std::wstring& name) // 4J - changed to just return a name rather than an input stream - { - /* 4J - TODO - return TexturePack.class.getResourceAsStream(name); - */ - return name; + virtual std::wstring getResource( + const std::wstring& name) // 4J - changed to just return a name rather + // than an input stream + { + /* 4J - TODO +return TexturePack.class.getResourceAsStream(name); + */ + return name; } - virtual DLCPack * getDLCPack() { return NULL;} + virtual DLCPack* getDLCPack() { return NULL; } - - // 4J Added - virtual std::wstring getPath(bool bTitleUpdateTexture = false); - virtual std::wstring getAnimationString(const std::wstring &textureName, const std::wstring &path, bool allowFallback) = 0; - virtual BufferedImage *getImageResource(const std::wstring& File, bool filenameHasExtension = false, bool bTitleUpdateTexture=false, const std::wstring &drive =L"") = 0; - virtual void loadColourTable() = 0; - virtual void loadUI() = 0; - virtual void unloadUI() = 0; - virtual std::wstring getXuiRootPath() = 0; - virtual std::uint8_t *getPackIcon(std::uint32_t &imageBytes) = 0; - virtual std::uint8_t *getPackComparison(std::uint32_t &imageBytes) = 0; - virtual unsigned int getDLCParentPackId() = 0; - virtual unsigned char getDLCSubPackId() = 0; - virtual ColourTable *getColourTable() = 0; - virtual ArchiveFile *getArchiveFile() = 0; + // 4J Added + virtual std::wstring getPath(bool bTitleUpdateTexture = false); + virtual std::wstring getAnimationString(const std::wstring& textureName, + const std::wstring& path, + bool allowFallback) = 0; + virtual BufferedImage* getImageResource( + const std::wstring& File, bool filenameHasExtension = false, + bool bTitleUpdateTexture = false, const std::wstring& drive = L"") = 0; + virtual void loadColourTable() = 0; + virtual void loadUI() = 0; + virtual void unloadUI() = 0; + virtual std::wstring getXuiRootPath() = 0; + virtual std::uint8_t* getPackIcon(std::uint32_t& imageBytes) = 0; + virtual std::uint8_t* getPackComparison(std::uint32_t& imageBytes) = 0; + virtual unsigned int getDLCParentPackId() = 0; + virtual unsigned char getDLCSubPackId() = 0; + virtual ColourTable* getColourTable() = 0; + virtual ArchiveFile* getArchiveFile() = 0; private: - bool m_bHasAudio; - + bool m_bHasAudio; }; diff --git a/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp b/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp index 9eccc3ff6..892e025d2 100644 --- a/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp +++ b/Minecraft.Client/Textures/Packs/TexturePackRepository.cpp @@ -9,77 +9,76 @@ #include "../../../Minecraft.World/Util/StringHelpers.h" #include "../../Rendering/Minimap.h" -TexturePack *TexturePackRepository::DEFAULT_TEXTURE_PACK = NULL; +TexturePack* TexturePackRepository::DEFAULT_TEXTURE_PACK = NULL; -TexturePackRepository::TexturePackRepository(File workingDirectory, Minecraft *minecraft) -{ - if(!DEFAULT_TEXTURE_PACK) DEFAULT_TEXTURE_PACK = new DefaultTexturePack(); +TexturePackRepository::TexturePackRepository(File workingDirectory, + Minecraft* minecraft) { + if (!DEFAULT_TEXTURE_PACK) DEFAULT_TEXTURE_PACK = new DefaultTexturePack(); - // 4J - added - usingWeb = false; - selected = NULL; - texturePacks = new std::vector; + // 4J - added + usingWeb = false; + selected = NULL; + texturePacks = new std::vector; this->minecraft = minecraft; - texturePacks->push_back(DEFAULT_TEXTURE_PACK); - cacheById[DEFAULT_TEXTURE_PACK->getId()] = DEFAULT_TEXTURE_PACK; + texturePacks->push_back(DEFAULT_TEXTURE_PACK); + cacheById[DEFAULT_TEXTURE_PACK->getId()] = DEFAULT_TEXTURE_PACK; selected = DEFAULT_TEXTURE_PACK; - DEFAULT_TEXTURE_PACK->loadColourTable(); + DEFAULT_TEXTURE_PACK->loadColourTable(); - m_dummyTexturePack = NULL; - m_dummyDLCTexturePack = NULL; - lastSelected = NULL; + m_dummyTexturePack = NULL; + m_dummyDLCTexturePack = NULL; + lastSelected = NULL; updateList(); } -void TexturePackRepository::addDebugPacks() -{ +void TexturePackRepository::addDebugPacks() { #ifndef _CONTENT_PACKAGE - //File *file = new File(L"DummyTexturePack"); // Path to the test texture pack - //m_dummyTexturePack = new FolderTexturePack(FOLDER_TEST_TEXTURE_PACK_ID, L"FolderTestPack", file, DEFAULT_TEXTURE_PACK); - //texturePacks->push_back(m_dummyTexturePack); - //cacheById[m_dummyTexturePack->getId()] = m_dummyTexturePack; + // File *file = new File(L"DummyTexturePack"); // Path to the test texture + // pack m_dummyTexturePack = new + // FolderTexturePack(FOLDER_TEST_TEXTURE_PACK_ID, L"FolderTestPack", file, + // DEFAULT_TEXTURE_PACK); texturePacks->push_back(m_dummyTexturePack); + // cacheById[m_dummyTexturePack->getId()] = m_dummyTexturePack; #ifdef _XBOX - File packedTestFile(L"GAME:\\DummyTexturePack\\TexturePack.pck"); - if(packedTestFile.exists()) - { - DLCPack *pack = app.m_dlcManager.getPack(L"DLCTestPack"); + File packedTestFile(L"GAME:\\DummyTexturePack\\TexturePack.pck"); + if (packedTestFile.exists()) { + DLCPack* pack = app.m_dlcManager.getPack(L"DLCTestPack"); - if( pack != NULL && pack->IsCorrupt() ) - { - app.m_dlcManager.removePack(pack); - pack = NULL; - } + if (pack != NULL && pack->IsCorrupt()) { + app.m_dlcManager.removePack(pack); + pack = NULL; + } - if(pack == NULL) - { - wprintf(L"Pack \"%ls\" is not installed, so adding it\n", L"DLCTestPack"); - pack = new DLCPack(L"DLCTestPack",0xffffffff); - unsigned int dwFilesProcessed = 0; - if( app.m_dlcManager.readDLCDataFile(dwFilesProcessed, "GAME:\\DummyTexturePack\\TexturePack.pck",pack)) - { - // 4J Stu - Don't need to do this, as the readDLCDataFile now adds texture packs - //m_dummyDLCTexturePack = addTexturePackFromDLC(pack, DLC_TEST_TEXTURE_PACK_ID); //new DLCTexturePack(0xFFFFFFFE, L"DLCTestPack", pack, DEFAULT_TEXTURE_PACK); - app.m_dlcManager.addPack(pack); - } - else - { - delete pack; - } - } - } + if (pack == NULL) { + wprintf(L"Pack \"%ls\" is not installed, so adding it\n", + L"DLCTestPack"); + pack = new DLCPack(L"DLCTestPack", 0xffffffff); + unsigned int dwFilesProcessed = 0; + if (app.m_dlcManager.readDLCDataFile( + dwFilesProcessed, + "GAME:\\DummyTexturePack\\TexturePack.pck", pack)) { + // 4J Stu - Don't need to do this, as the readDLCDataFile now + // adds texture packs + // m_dummyDLCTexturePack = addTexturePackFromDLC(pack, + // DLC_TEST_TEXTURE_PACK_ID); //new DLCTexturePack(0xFFFFFFFE, + // L"DLCTestPack", pack, DEFAULT_TEXTURE_PACK); + app.m_dlcManager.addPack(pack); + } else { + delete pack; + } + } + } -#endif // _XBOX -#endif // _CONTENT_PACKAGE +#endif // _XBOX +#endif // _CONTENT_PACKAGE } -void TexturePackRepository::createWorkingDirecoryUnlessExists() -{ - // 4J Unused +void TexturePackRepository::createWorkingDirecoryUnlessExists() { + // 4J Unused #if 0 if (!workDir.isDirectory()) { workDir.delete(); @@ -93,21 +92,20 @@ void TexturePackRepository::createWorkingDirecoryUnlessExists() #endif } -bool TexturePackRepository::selectSkin(TexturePack *skin) -{ - if (skin==selected) return false; - - lastSelected = selected; +bool TexturePackRepository::selectSkin(TexturePack* skin) { + if (skin == selected) return false; + + lastSelected = selected; usingWeb = false; selected = skin; - //minecraft->options->skin = skin->getName(); - //minecraft->options->save(); + // minecraft->options->skin = skin->getName(); + // minecraft->options->save(); return true; } -void TexturePackRepository::selectWebSkin(const std::wstring &url) -{ - app.DebugPrintf("TexturePackRepository::selectWebSkin is not implemented\n"); +void TexturePackRepository::selectWebSkin(const std::wstring& url) { + app.DebugPrintf( + "TexturePackRepository::selectWebSkin is not implemented\n"); #if 0 String filename = url.substring(url.lastIndexOf("/") + 1); if (filename.contains("?")) filename = filename.substring(0, filename.indexOf("?")); @@ -117,9 +115,10 @@ void TexturePackRepository::selectWebSkin(const std::wstring &url) #endif } -void TexturePackRepository::downloadWebSkin(const std::wstring &url, File file) -{ - app.DebugPrintf("TexturePackRepository::selectWebSkin is not implemented\n"); +void TexturePackRepository::downloadWebSkin(const std::wstring& url, + File file) { + app.DebugPrintf( + "TexturePackRepository::selectWebSkin is not implemented\n"); #if 0 Map headers = new HashMap(); final ProgressScreen listener = new ProgressScreen(); @@ -141,21 +140,17 @@ void TexturePackRepository::downloadWebSkin(const std::wstring &url, File file) #endif } -bool TexturePackRepository::isUsingWebSkin() -{ - return usingWeb; +bool TexturePackRepository::isUsingWebSkin() { return usingWeb; } + +void TexturePackRepository::resetWebSkin() { + usingWeb = false; + updateList(); + minecraft->delayTextureReload(); } -void TexturePackRepository::resetWebSkin() -{ - usingWeb = false; - updateList(); - minecraft->delayTextureReload(); -} - -void TexturePackRepository::updateList() -{ - // 4J Stu - We don't ever want to completely refresh the lists, we keep them up-to-date as we go +void TexturePackRepository::updateList() { + // 4J Stu - We don't ever want to completely refresh the lists, we keep them + // up-to-date as we go #if 0 std::vector *currentPacks = new std::vector; currentPacks->push_back(DEFAULT_TEXTURE_PACK); @@ -219,9 +214,8 @@ void TexturePackRepository::updateList() #endif } -std::wstring TexturePackRepository::getIdOrNull(File file) -{ - app.DebugPrintf("TexturePackRepository::getIdOrNull is not implemented\n"); +std::wstring TexturePackRepository::getIdOrNull(File file) { + app.DebugPrintf("TexturePackRepository::getIdOrNull is not implemented\n"); #if 0 if (file.isFile() && file.getName().toLowerCase().endsWith(".zip")) { return file.getName() + ":" + file.length() + ":" + file.lastModified(); @@ -231,12 +225,12 @@ std::wstring TexturePackRepository::getIdOrNull(File file) return NULL; #endif - return L""; + return L""; } -std::vector TexturePackRepository::getWorkDirContents() -{ - app.DebugPrintf("TexturePackRepository::getWorkDirContents is not implemented\n"); +std::vector TexturePackRepository::getWorkDirContents() { + app.DebugPrintf( + "TexturePackRepository::getWorkDirContents is not implemented\n"); #if 0 if (workDir.exists() && workDir.isDirectory()) { return Arrays.asList(workDir.listFiles()); @@ -244,24 +238,24 @@ std::vector TexturePackRepository::getWorkDirContents() return Collections.emptyList(); #endif - return std::vector(); + return std::vector(); } -std::vector *TexturePackRepository::getAll() -{ - // 4J - note that original constucted a copy of texturePacks here - return texturePacks; +std::vector* TexturePackRepository::getAll() { + // 4J - note that original constucted a copy of texturePacks here + return texturePacks; } -TexturePack *TexturePackRepository::getSelected() -{ - if(selected->hasData()) return selected; - else return DEFAULT_TEXTURE_PACK; +TexturePack* TexturePackRepository::getSelected() { + if (selected->hasData()) + return selected; + else + return DEFAULT_TEXTURE_PACK; } -bool TexturePackRepository::shouldPromptForWebSkin() -{ - app.DebugPrintf("TexturePackRepository::shouldPromptForWebSkin is not implemented\n"); +bool TexturePackRepository::shouldPromptForWebSkin() { + app.DebugPrintf( + "TexturePackRepository::shouldPromptForWebSkin is not implemented\n"); #if 0 if (!minecraft.options.serverTextures) return false; ServerData data = minecraft.getCurrentServer(); @@ -272,12 +266,12 @@ bool TexturePackRepository::shouldPromptForWebSkin() return data.promptOnTextures(); } #endif - return false; + return false; } -bool TexturePackRepository::canUseWebSkin() -{ - app.DebugPrintf("TexturePackRepository::canUseWebSkin is not implemented\n"); +bool TexturePackRepository::canUseWebSkin() { + app.DebugPrintf( + "TexturePackRepository::canUseWebSkin is not implemented\n"); #if 0 if (!minecraft.options.serverTextures) return false; ServerData data = minecraft.getCurrentServer(); @@ -288,177 +282,158 @@ bool TexturePackRepository::canUseWebSkin() return data.allowTextures(); } #endif - return false; + return false; } -std::vector< std::pair > *TexturePackRepository::getTexturePackIdNames() -{ - std::vector< std::pair > *packList = new std::vector< std::pair >(); +std::vector >* +TexturePackRepository::getTexturePackIdNames() { + std::vector >* packList = + new std::vector >(); - for(AUTO_VAR(it,texturePacks->begin()); it != texturePacks->end(); ++it) - { - TexturePack *pack = *it; - packList->push_back( std::pair(pack->getId(),pack->getName()) ); - } - return packList; + for (AUTO_VAR(it, texturePacks->begin()); it != texturePacks->end(); ++it) { + TexturePack* pack = *it; + packList->push_back(std::pair( + pack->getId(), pack->getName())); + } + return packList; } -bool TexturePackRepository::selectTexturePackById(std::uint32_t id) -{ - bool bDidSelect = false; +bool TexturePackRepository::selectTexturePackById(std::uint32_t id) { + bool bDidSelect = false; - //4J-PB - add in a store of the texture pack required, so that join from invite games - // (where they don't have the texture pack) can check this when the texture pack is installed - app.SetRequiredTexturePackID(id); + // 4J-PB - add in a store of the texture pack required, so that join from + // invite games + // (where they don't have the texture pack) can check this when the texture + // pack is installed + app.SetRequiredTexturePackID(id); - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) - { - TexturePack *newPack = it->second; - if(newPack != selected) - { - selectSkin(newPack); + AUTO_VAR(it, cacheById.find(id)); + if (it != cacheById.end()) { + TexturePack* newPack = it->second; + if (newPack != selected) { + selectSkin(newPack); - if(newPack->hasData()) - { - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); - } - else - { - newPack->loadData(); - } - //Minecraft *pMinecraft = Minecraft::GetInstance(); - //pMinecraft->textures->reloadAll(); - } - else - { - app.DebugPrintf("TexturePack with id %d is already selected\n",id); - } - bDidSelect = true; - } - else - { - app.DebugPrintf("Failed to select texture pack %d as it is not in the list\n", id); + if (newPack->hasData()) { + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_ReloadTexturePack); + } else { + newPack->loadData(); + } + // Minecraft *pMinecraft = Minecraft::GetInstance(); + // pMinecraft->textures->reloadAll(); + } else { + app.DebugPrintf("TexturePack with id %d is already selected\n", id); + } + bDidSelect = true; + } else { + app.DebugPrintf( + "Failed to select texture pack %d as it is not in the list\n", id); #ifndef _CONTENT_PACKAGE - // TODO - 4J Stu: We should report this to the player in some way - //__debugbreak(); + // TODO - 4J Stu: We should report this to the player in some way + //__debugbreak(); #endif - // Fail safely - if( selectSkin( DEFAULT_TEXTURE_PACK ) ) - { - app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ReloadTexturePack); - } - } - return bDidSelect; + // Fail safely + if (selectSkin(DEFAULT_TEXTURE_PACK)) { + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_ReloadTexturePack); + } + } + return bDidSelect; } -TexturePack *TexturePackRepository::getTexturePackById(std::uint32_t id) -{ - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) - { - return it->second; - } +TexturePack* TexturePackRepository::getTexturePackById(std::uint32_t id) { + AUTO_VAR(it, cacheById.find(id)); + if (it != cacheById.end()) { + return it->second; + } - return NULL; + return NULL; } -TexturePack *TexturePackRepository::addTexturePackFromDLC(DLCPack *dlcPack, std::uint32_t id) -{ - TexturePack *newPack = NULL; - // 4J-PB - The City texture pack went out with a child id for the texture pack of 1 instead of zero - // we need to mask off the child id here to deal with this - const std::uint32_t parentId = id & 0xFFFFFFu; // child id is <<24 and Or'd with parent +TexturePack* TexturePackRepository::addTexturePackFromDLC(DLCPack* dlcPack, + std::uint32_t id) { + TexturePack* newPack = NULL; + // 4J-PB - The City texture pack went out with a child id for the texture + // pack of 1 instead of zero we need to mask off the child id here to deal + // with this + const std::uint32_t parentId = + id & 0xFFFFFFu; // child id is <<24 and Or'd with parent - if(dlcPack != NULL) - { - newPack = new DLCTexturePack(parentId, dlcPack, DEFAULT_TEXTURE_PACK); - texturePacks->push_back(newPack); - cacheById[parentId] = newPack; + if (dlcPack != NULL) { + newPack = new DLCTexturePack(parentId, dlcPack, DEFAULT_TEXTURE_PACK); + texturePacks->push_back(newPack); + cacheById[parentId] = newPack; #ifndef _CONTENT_PACKAGE - if(dlcPack->hasPurchasedFile(DLCManager::e_DLCType_TexturePack,L"")) - { - wprintf(L"Added new FULL DLCTexturePack: %ls - id=%u\n", dlcPack->getName().c_str(), parentId ); - } - else - { - wprintf(L"Added new TRIAL DLCTexturePack: %ls - id=%u\n", dlcPack->getName().c_str(), parentId ); - } + if (dlcPack->hasPurchasedFile(DLCManager::e_DLCType_TexturePack, L"")) { + wprintf(L"Added new FULL DLCTexturePack: %ls - id=%u\n", + dlcPack->getName().c_str(), parentId); + } else { + wprintf(L"Added new TRIAL DLCTexturePack: %ls - id=%u\n", + dlcPack->getName().c_str(), parentId); + } #endif - } - return newPack; + } + return newPack; } -void TexturePackRepository::clearInvalidTexturePacks() -{ - for(AUTO_VAR(it, m_texturePacksToDelete.begin()); it != m_texturePacksToDelete.end(); ++it) - { - delete *it; - } +void TexturePackRepository::clearInvalidTexturePacks() { + for (AUTO_VAR(it, m_texturePacksToDelete.begin()); + it != m_texturePacksToDelete.end(); ++it) { + delete *it; + } } -void TexturePackRepository::removeTexturePackById(std::uint32_t id) -{ - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) - { - TexturePack *oldPack = it->second; +void TexturePackRepository::removeTexturePackById(std::uint32_t id) { + AUTO_VAR(it, cacheById.find(id)); + if (it != cacheById.end()) { + TexturePack* oldPack = it->second; - AUTO_VAR(it2, find(texturePacks->begin(), texturePacks->end(),oldPack) ); - if(it2 != texturePacks->end()) - { - texturePacks->erase(it2); - if(lastSelected == oldPack) - { - lastSelected = NULL; - } - } - m_texturePacksToDelete.push_back(oldPack); - } + AUTO_VAR(it2, + find(texturePacks->begin(), texturePacks->end(), oldPack)); + if (it2 != texturePacks->end()) { + texturePacks->erase(it2); + if (lastSelected == oldPack) { + lastSelected = NULL; + } + } + m_texturePacksToDelete.push_back(oldPack); + } } -void TexturePackRepository::updateUI() -{ - if(lastSelected != NULL && lastSelected != selected) - { - lastSelected->unloadUI(); - selected->loadUI(); - Minimap::reloadColours(); - ui.StartReloadSkinThread(); - lastSelected = NULL; - } +void TexturePackRepository::updateUI() { + if (lastSelected != NULL && lastSelected != selected) { + lastSelected->unloadUI(); + selected->loadUI(); + Minimap::reloadColours(); + ui.StartReloadSkinThread(); + lastSelected = NULL; + } } -bool TexturePackRepository::needsUIUpdate() -{ - return lastSelected != NULL && lastSelected != selected; +bool TexturePackRepository::needsUIUpdate() { + return lastSelected != NULL && lastSelected != selected; } -unsigned int TexturePackRepository::getTexturePackCount() -{ - return texturePacks->size(); +unsigned int TexturePackRepository::getTexturePackCount() { + return texturePacks->size(); } -TexturePack *TexturePackRepository::getTexturePackByIndex(unsigned int index) -{ - TexturePack *pack = NULL; - if(index < texturePacks->size()) - { - pack = texturePacks->at(index); - } - return pack; +TexturePack* TexturePackRepository::getTexturePackByIndex(unsigned int index) { + TexturePack* pack = NULL; + if (index < texturePacks->size()) { + pack = texturePacks->at(index); + } + return pack; } -unsigned int TexturePackRepository::getTexturePackIndex(std::uint32_t id) -{ - int currentIndex = 0; - for(AUTO_VAR(it,texturePacks->begin()); it != texturePacks->end(); ++it) - { - TexturePack *pack = *it; - if(pack->getId() == id) break; - ++currentIndex; - } - if(currentIndex >= texturePacks->size()) currentIndex = 0; - return currentIndex; +unsigned int TexturePackRepository::getTexturePackIndex(std::uint32_t id) { + int currentIndex = 0; + for (AUTO_VAR(it, texturePacks->begin()); it != texturePacks->end(); ++it) { + TexturePack* pack = *it; + if (pack->getId() == id) break; + ++currentIndex; + } + if (currentIndex >= texturePacks->size()) currentIndex = 0; + return currentIndex; } diff --git a/Minecraft.Client/Textures/Packs/TexturePackRepository.h b/Minecraft.Client/Textures/Packs/TexturePackRepository.h index a93e1f7c6..105c634e0 100644 --- a/Minecraft.Client/Textures/Packs/TexturePackRepository.h +++ b/Minecraft.Client/Textures/Packs/TexturePackRepository.h @@ -1,77 +1,82 @@ #pragma once #include "TexturePack.h" - class Minecraft; -class TexturePackRepository -{ +class TexturePackRepository { public: - static constexpr std::uint32_t DEFAULT_TEXTURE_PACK_ID = 0; - static constexpr std::uint32_t FOLDER_TEST_TEXTURE_PACK_ID = 1; - static constexpr std::uint32_t DLC_TEST_TEXTURE_PACK_ID = 2; + static constexpr std::uint32_t DEFAULT_TEXTURE_PACK_ID = 0; + static constexpr std::uint32_t FOLDER_TEST_TEXTURE_PACK_ID = 1; + static constexpr std::uint32_t DLC_TEST_TEXTURE_PACK_ID = 2; + private: - static TexturePack *DEFAULT_TEXTURE_PACK; - TexturePack *m_dummyTexturePack; - TexturePack *m_dummyDLCTexturePack; + static TexturePack* DEFAULT_TEXTURE_PACK; + TexturePack* m_dummyTexturePack; + TexturePack* m_dummyDLCTexturePack; - Minecraft *minecraft; - File workDir; - File multiplayerDir; - std::vector *texturePacks; - std::vector m_texturePacksToDelete; + Minecraft* minecraft; + File workDir; + File multiplayerDir; + std::vector* texturePacks; + std::vector m_texturePacksToDelete; - std::unordered_map cacheById; + std::unordered_map cacheById; - TexturePack *selected; - TexturePack *lastSelected; + TexturePack* selected; + TexturePack* lastSelected; bool usingWeb; - static const int MAX_WEB_FILESIZE = 10 * 1000 * 1000; // 10 Megabytes + static const int MAX_WEB_FILESIZE = 10 * 1000 * 1000; // 10 Megabytes public: - TexturePackRepository(File workingDirectory, Minecraft *minecraft); - void addDebugPacks(); -private: - void createWorkingDirecoryUnlessExists(); - -public: - bool selectSkin(TexturePack *skin); - - void selectWebSkin(const std::wstring &url); + TexturePackRepository(File workingDirectory, Minecraft* minecraft); + void addDebugPacks(); private: - void downloadWebSkin(const std::wstring &url, File file); + void createWorkingDirecoryUnlessExists(); public: - bool isUsingWebSkin(); - void resetWebSkin(); + bool selectSkin(TexturePack* skin); + + void selectWebSkin(const std::wstring& url); + +private: + void downloadWebSkin(const std::wstring& url, File file); + +public: + bool isUsingWebSkin(); + void resetWebSkin(); void updateList(); private: - std::wstring getIdOrNull(File file); + std::wstring getIdOrNull(File file); std::vector getWorkDirContents(); public: - std::vector *getAll(); + std::vector* getAll(); - TexturePack *getSelected(); - bool shouldPromptForWebSkin(); - bool canUseWebSkin(); - bool isUsingDefaultSkin() { return selected == DEFAULT_TEXTURE_PACK; } // 4J Added - TexturePack *getDefault() { return DEFAULT_TEXTURE_PACK; } // 4J Added + TexturePack* getSelected(); + bool shouldPromptForWebSkin(); + bool canUseWebSkin(); + bool isUsingDefaultSkin() { + return selected == DEFAULT_TEXTURE_PACK; + } // 4J Added + TexturePack* getDefault() { return DEFAULT_TEXTURE_PACK; } // 4J Added - std::vector< std::pair > *getTexturePackIdNames(); - bool selectTexturePackById(std::uint32_t id); // 4J Added - TexturePack *getTexturePackById(std::uint32_t id); // 4J Added + std::vector >* + getTexturePackIdNames(); + bool selectTexturePackById(std::uint32_t id); // 4J Added + TexturePack* getTexturePackById(std::uint32_t id); // 4J Added + + TexturePack* addTexturePackFromDLC(DLCPack* dlcPack, std::uint32_t id); + void clearInvalidTexturePacks(); + void updateUI(); + bool needsUIUpdate(); - TexturePack *addTexturePackFromDLC(DLCPack *dlcPack, std::uint32_t id); - void clearInvalidTexturePacks(); - void updateUI(); - bool needsUIUpdate(); private: - void removeTexturePackById(std::uint32_t id); + void removeTexturePackById(std::uint32_t id); + public: - unsigned int getTexturePackCount(); - TexturePack *getTexturePackByIndex(unsigned int index); - unsigned int getTexturePackIndex(std::uint32_t id); + unsigned int getTexturePackCount(); + TexturePack* getTexturePackByIndex(unsigned int index); + unsigned int getTexturePackIndex(std::uint32_t id); }; diff --git a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp index 99066524e..431037140 100644 --- a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp +++ b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.cpp @@ -22,210 +22,216 @@ const std::wstring PreStitchedTextureMap::NAME_MISSING_TEXTURE = L"missingno"; -PreStitchedTextureMap::PreStitchedTextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipmap) : iconType(type), name(name), path(path), extension(L".png") -{ - this->missingTexture = missingTexture; +PreStitchedTextureMap::PreStitchedTextureMap(int type, const std::wstring& name, + const std::wstring& path, + BufferedImage* missingTexture, + bool mipmap) + : iconType(type), name(name), path(path), extension(L".png") { + this->missingTexture = missingTexture; - // 4J Initialisers - missingPosition = NULL; - stitchResult = NULL; + // 4J Initialisers + missingPosition = NULL; + stitchResult = NULL; - m_mipMap = mipmap; - missingPosition = (StitchedTexture *)(new SimpleIcon(NAME_MISSING_TEXTURE,0,0,1,1)); + m_mipMap = mipmap; + missingPosition = + (StitchedTexture*)(new SimpleIcon(NAME_MISSING_TEXTURE, 0, 0, 1, 1)); } -void PreStitchedTextureMap::stitch() -{ - // Animated StitchedTextures store a vector of textures for each frame of the animation. Free any pre-existing ones here. - for(AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); ++it) - { - StitchedTexture *animatedStitchedTexture = (StitchedTexture *)texturesByName[it->first]; - animatedStitchedTexture->freeFrameTextures(); - } +void PreStitchedTextureMap::stitch() { + // Animated StitchedTextures store a vector of textures for each frame of + // the animation. Free any pre-existing ones here. + for (AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); + ++it) { + StitchedTexture* animatedStitchedTexture = + (StitchedTexture*)texturesByName[it->first]; + animatedStitchedTexture->freeFrameTextures(); + } - loadUVs(); + loadUVs(); - if (iconType == Icon::TYPE_TERRAIN) - { - //for (Tile tile : Tile.tiles) - for(unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) - { - if (Tile::tiles[i] != NULL) - { - Tile::tiles[i]->registerIcons(this); - } - } + if (iconType == Icon::TYPE_TERRAIN) { + // for (Tile tile : Tile.tiles) + for (unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) { + if (Tile::tiles[i] != NULL) { + Tile::tiles[i]->registerIcons(this); + } + } - Minecraft::GetInstance()->levelRenderer->registerTextures(this); - EntityRenderDispatcher::instance->registerTerrainTextures(this); - } + Minecraft::GetInstance()->levelRenderer->registerTextures(this); + EntityRenderDispatcher::instance->registerTerrainTextures(this); + } - //for (Item item : Item.items) - for(unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) - { - Item *item = Item::items[i]; - if (item != NULL && item->getIconType() == iconType) - { - item->registerIcons(this); - } - } + // for (Item item : Item.items) + for (unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) { + Item* item = Item::items[i]; + if (item != NULL && item->getIconType() == iconType) { + item->registerIcons(this); + } + } - // Collection bucket for multiple frames per texture - std::unordered_map * > textures; // = new HashMap>(); + // Collection bucket for multiple frames per texture + std::unordered_map*> + textures; // = new HashMap>(); - Stitcher *stitcher = TextureManager::getInstance()->createStitcher(name); + Stitcher* stitcher = TextureManager::getInstance()->createStitcher(name); - animatedTextures.clear(); + animatedTextures.clear(); - // Create the final image - std::wstring filename = name + extension; + // Create the final image + std::wstring filename = name + extension; - TexturePack *texturePack = Minecraft::GetInstance()->skins->getSelected(); - //try { - int mode = Texture::TM_DYNAMIC; - int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues with how we signal non-mipmmapped textures to the pixel shader //Texture::WM_CLAMP; - int minFilter = Texture::TFLT_NEAREST; - int magFilter = Texture::TFLT_NEAREST; + TexturePack* texturePack = Minecraft::GetInstance()->skins->getSelected(); + // try { + int mode = Texture::TM_DYNAMIC; + int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues + // with how we signal non-mipmmapped textures + // to the pixel shader //Texture::WM_CLAMP; + int minFilter = Texture::TFLT_NEAREST; + int magFilter = Texture::TFLT_NEAREST; - MemSect(32); - std::wstring drive = L""; - if(texturePack->hasFile(L"res/" + filename,false)) - { - drive = texturePack->getPath(true); - } - else - { - drive = Minecraft::GetInstance()->skins->getDefault()->getPath(true); - texturePack = Minecraft::GetInstance()->skins->getDefault(); - } - //BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + filename),false,true,drive); //ImageIO::read(texturePack->getResource(L"/" + filename)); - BufferedImage *image = texturePack->getImageResource(filename, false, true, drive); - MemSect(0); - int height = image->getHeight(); - int width = image->getWidth(); + MemSect(32); + std::wstring drive = L""; + if (texturePack->hasFile(L"res/" + filename, false)) { + drive = texturePack->getPath(true); + } else { + drive = Minecraft::GetInstance()->skins->getDefault()->getPath(true); + texturePack = Minecraft::GetInstance()->skins->getDefault(); + } + // BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + + // filename),false,true,drive); + // //ImageIO::read(texturePack->getResource(L"/" + filename)); + BufferedImage* image = + texturePack->getImageResource(filename, false, true, drive); + MemSect(0); + int height = image->getHeight(); + int width = image->getWidth(); - if(stitchResult != NULL) - { - TextureManager::getInstance()->unregisterTexture(name, stitchResult); - delete stitchResult; - } - stitchResult = TextureManager::getInstance()->createTexture(name, Texture::TM_DYNAMIC, width, height, Texture::TFMT_RGBA, m_mipMap); - stitchResult->transferFromImage(image); - delete image; - TextureManager::getInstance()->registerName(name, stitchResult); - //stitchResult = stitcher->constructTexture(m_mipMap); + if (stitchResult != NULL) { + TextureManager::getInstance()->unregisterTexture(name, stitchResult); + delete stitchResult; + } + stitchResult = TextureManager::getInstance()->createTexture( + name, Texture::TM_DYNAMIC, width, height, Texture::TFMT_RGBA, m_mipMap); + stitchResult->transferFromImage(image); + delete image; + TextureManager::getInstance()->registerName(name, stitchResult); + // stitchResult = stitcher->constructTexture(m_mipMap); - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) - { - StitchedTexture *preStitched = (StitchedTexture *)it->second; + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + StitchedTexture* preStitched = (StitchedTexture*)it->second; - int x = preStitched->getU0() * stitchResult->getWidth(); - int y = preStitched->getV0() * stitchResult->getHeight(); - int width = (preStitched->getU1() * stitchResult->getWidth()) - x; - int height = (preStitched->getV1() * stitchResult->getHeight()) - y; + int x = preStitched->getU0() * stitchResult->getWidth(); + int y = preStitched->getV0() * stitchResult->getHeight(); + int width = (preStitched->getU1() * stitchResult->getWidth()) - x; + int height = (preStitched->getV1() * stitchResult->getHeight()) - y; - preStitched->init(stitchResult, NULL, x, y, width, height, false); - } + preStitched->init(stitchResult, NULL, x, y, width, height, false); + } - MemSect(52); - for(AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); ++it) - { - std::wstring textureName = it->first; - std::wstring textureFileName = it->second; + MemSect(52); + for (AUTO_VAR(it, texturesToAnimate.begin()); it != texturesToAnimate.end(); + ++it) { + std::wstring textureName = it->first; + std::wstring textureFileName = it->second; - StitchedTexture *preStitched = (StitchedTexture *)texturesByName[textureName]; + StitchedTexture* preStitched = + (StitchedTexture*)texturesByName[textureName]; - if(!preStitched->hasOwnData()) - { - if(preStitched->getFrames() > 1) animatedTextures.push_back(preStitched); - continue; - } + if (!preStitched->hasOwnData()) { + if (preStitched->getFrames() > 1) + animatedTextures.push_back(preStitched); + continue; + } - std::wstring filename = path + textureFileName + extension; + std::wstring filename = path + textureFileName + extension; - // TODO: [EB] Put the frames into a proper object, not this inside out hack - std::vector *frames = TextureManager::getInstance()->createTextures(filename, m_mipMap); - if (frames == NULL || frames->empty()) - { - continue; // Couldn't load a texture, skip it - } + // TODO: [EB] Put the frames into a proper object, not this inside out + // hack + std::vector* frames = + TextureManager::getInstance()->createTextures(filename, m_mipMap); + if (frames == NULL || frames->empty()) { + continue; // Couldn't load a texture, skip it + } - Texture *first = frames->at(0); + Texture* first = frames->at(0); #ifndef _CONTENT_PACKAGE - if(first->getWidth() != preStitched->getWidth() || first->getHeight() != preStitched->getHeight()) - { - __debugbreak(); - } + if (first->getWidth() != preStitched->getWidth() || + first->getHeight() != preStitched->getHeight()) { + __debugbreak(); + } #endif - preStitched->init(stitchResult, frames, preStitched->getX(), preStitched->getY(), first->getWidth(), first->getHeight(), false); + preStitched->init(stitchResult, frames, preStitched->getX(), + preStitched->getY(), first->getWidth(), + first->getHeight(), false); - if (frames->size() > 1) - { - animatedTextures.push_back(preStitched); + if (frames->size() > 1) { + animatedTextures.push_back(preStitched); - std::wstring animString = texturePack->getAnimationString(textureFileName, path, true); + std::wstring animString = + texturePack->getAnimationString(textureFileName, path, true); - preStitched->loadAnimationFrames(animString); - } - } - MemSect(0); - //missingPosition = (StitchedTexture *)texturesByName.find(NAME_MISSING_TEXTURE)->second; - - stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); - stitchResult->updateOnGPU(); + preStitched->loadAnimationFrames(animString); + } + } + MemSect(0); + // missingPosition = (StitchedTexture + // *)texturesByName.find(NAME_MISSING_TEXTURE)->second; + stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); + stitchResult->updateOnGPU(); #ifdef __PSVITA__ - // AP - alpha cut out is expensive on vita so we mark which icons actually require it - const std::uint8_t *data = this->getStitchedTexture()->getData()->getBuffer(); - int Width = this->getStitchedTexture()->getWidth(); - int Height = this->getStitchedTexture()->getHeight(); - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) - { - StitchedTexture *preStitched = (StitchedTexture *)it->second; + // AP - alpha cut out is expensive on vita so we mark which icons actually + // require it + const std::uint8_t* data = + this->getStitchedTexture()->getData()->getBuffer(); + int Width = this->getStitchedTexture()->getWidth(); + int Height = this->getStitchedTexture()->getHeight(); + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + StitchedTexture* preStitched = (StitchedTexture*)it->second; - bool Found = false; - int u0 = preStitched->getU0() * Width; - int u1 = preStitched->getU1() * Width; - int v0 = preStitched->getV0() * Height; - int v1 = preStitched->getV1() * Height; + bool Found = false; + int u0 = preStitched->getU0() * Width; + int u1 = preStitched->getU1() * Width; + int v0 = preStitched->getV0() * Height; + int v1 = preStitched->getV1() * Height; - // check all the texels for this icon. If ANY are transparent we mark it as 'cut out' - for( int v = v0;v < v1; v+= 1 ) - { - for( int u = u0;u < u1; u+= 1 ) - { - std::uint32_t pixel = 0; - std::memcpy(&pixel, data + ((v * Width + u) * sizeof(pixel)), sizeof(pixel)); - // is this texel alpha value < 0.1 - if( (pixel & 0xff000000) < 0x20000000 ) - { - // this texel is transparent. Mark the icon as such and bail - preStitched->setFlags(Icon::IS_ALPHA_CUT_OUT); - Found = true; - break; - } - } + // check all the texels for this icon. If ANY are transparent we mark it + // as 'cut out' + for (int v = v0; v < v1; v += 1) { + for (int u = u0; u < u1; u += 1) { + std::uint32_t pixel = 0; + std::memcpy(&pixel, data + ((v * Width + u) * sizeof(pixel)), + sizeof(pixel)); + // is this texel alpha value < 0.1 + if ((pixel & 0xff000000) < 0x20000000) { + // this texel is transparent. Mark the icon as such and bail + preStitched->setFlags(Icon::IS_ALPHA_CUT_OUT); + Found = true; + break; + } + } - if( Found ) - { - // move onto the next icon - break; - } - } - } + if (Found) { + // move onto the next icon + break; + } + } + } #endif } -StitchedTexture *PreStitchedTextureMap::getTexture(const std::wstring &name) -{ +StitchedTexture* PreStitchedTextureMap::getTexture(const std::wstring& name) { #ifndef _CONTENT_PACKAGE - app.DebugPrintf("Not implemented!\n"); - __debugbreak(); + app.DebugPrintf("Not implemented!\n"); + __debugbreak(); #endif - return NULL; + return NULL; #if 0 StitchedTexture *result = texturesByName.find(name)->second; if (result == NULL) result = missingPosition; @@ -233,624 +239,1986 @@ StitchedTexture *PreStitchedTextureMap::getTexture(const std::wstring &name) #endif } -void PreStitchedTextureMap::cycleAnimationFrames() -{ - //for (StitchedTexture texture : animatedTextures) - for(AUTO_VAR(it, animatedTextures.begin() ); it != animatedTextures.end(); ++it) - { - StitchedTexture *texture = *it; - texture->cycleFrames(); - } +void PreStitchedTextureMap::cycleAnimationFrames() { + // for (StitchedTexture texture : animatedTextures) + for (AUTO_VAR(it, animatedTextures.begin()); it != animatedTextures.end(); + ++it) { + StitchedTexture* texture = *it; + texture->cycleFrames(); + } } -Texture *PreStitchedTextureMap::getStitchedTexture() -{ - return stitchResult; -} +Texture* PreStitchedTextureMap::getStitchedTexture() { return stitchResult; } // 4J Stu - register is a reserved keyword in C++ -Icon *PreStitchedTextureMap::registerIcon(const std::wstring &name) -{ - Icon *result = NULL; - if (name.empty()) - { - app.DebugPrintf("Don't register NULL\n"); +Icon* PreStitchedTextureMap::registerIcon(const std::wstring& name) { + Icon* result = NULL; + if (name.empty()) { + app.DebugPrintf("Don't register NULL\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - result = missingPosition; - //new RuntimeException("Don't register null!").printStackTrace(); - } + result = missingPosition; + // new RuntimeException("Don't register null!").printStackTrace(); + } - AUTO_VAR(it, texturesByName.find(name)); - if(it != texturesByName.end()) result = it->second; + AUTO_VAR(it, texturesByName.find(name)); + if (it != texturesByName.end()) result = it->second; - if (result == NULL) - { + if (result == NULL) { #ifndef _CONTENT_PACKAGE - wprintf(L"Could not find uv data for icon %ls\n", name.c_str() ); - __debugbreak(); + wprintf(L"Could not find uv data for icon %ls\n", name.c_str()); + __debugbreak(); #endif - result = missingPosition; - } + result = missingPosition; + } - return result; + return result; } -int PreStitchedTextureMap::getIconType() -{ - return iconType; -} - -Icon *PreStitchedTextureMap::getMissingIcon() -{ - return missingPosition; -} - -void PreStitchedTextureMap::loadUVs() -{ - if(!texturesByName.empty()) - { - // 4J Stu - We only need to populate this once at the moment as we have hardcoded positions for each texture - // If we ever load that dynamically, be aware that the Icon objects could currently be being used by the - // GameRenderer::runUpdate thread - return; - } - - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) - { - delete it->second; - } - texturesByName.clear(); - texturesToAnimate.clear(); - - float slotSize = 1.0f/16.0f; - if(iconType != Icon::TYPE_TERRAIN) - { - texturesByName.insert(stringIconMap::value_type(L"helmetCloth",new SimpleIcon(L"helmetCloth",slotSize*0,slotSize*0,slotSize*(0+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetChain",new SimpleIcon(L"helmetChain",slotSize*1,slotSize*0,slotSize*(1+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetIron",new SimpleIcon(L"helmetIron",slotSize*2,slotSize*0,slotSize*(2+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetDiamond",new SimpleIcon(L"helmetDiamond",slotSize*3,slotSize*0,slotSize*(3+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetGold",new SimpleIcon(L"helmetGold",slotSize*4,slotSize*0,slotSize*(4+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"flintAndSteel",new SimpleIcon(L"flintAndSteel",slotSize*5,slotSize*0,slotSize*(5+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"flint",new SimpleIcon(L"flint",slotSize*6,slotSize*0,slotSize*(6+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"coal",new SimpleIcon(L"coal",slotSize*7,slotSize*0,slotSize*(7+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"string",new SimpleIcon(L"string",slotSize*8,slotSize*0,slotSize*(8+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"seeds",new SimpleIcon(L"seeds",slotSize*9,slotSize*0,slotSize*(9+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"apple",new SimpleIcon(L"apple",slotSize*10,slotSize*0,slotSize*(10+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"appleGold",new SimpleIcon(L"appleGold",slotSize*11,slotSize*0,slotSize*(11+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"egg",new SimpleIcon(L"egg",slotSize*12,slotSize*0,slotSize*(12+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"sugar",new SimpleIcon(L"sugar",slotSize*13,slotSize*0,slotSize*(13+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"snowball",new SimpleIcon(L"snowball",slotSize*14,slotSize*0,slotSize*(14+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_helmet",new SimpleIcon(L"slot_empty_helmet",slotSize*15,slotSize*0,slotSize*(15+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateCloth",new SimpleIcon(L"chestplateCloth",slotSize*0,slotSize*1,slotSize*(0+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateChain",new SimpleIcon(L"chestplateChain",slotSize*1,slotSize*1,slotSize*(1+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateIron",new SimpleIcon(L"chestplateIron",slotSize*2,slotSize*1,slotSize*(2+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateDiamond",new SimpleIcon(L"chestplateDiamond",slotSize*3,slotSize*1,slotSize*(3+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateGold",new SimpleIcon(L"chestplateGold",slotSize*4,slotSize*1,slotSize*(4+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow",new SimpleIcon(L"bow",slotSize*5,slotSize*1,slotSize*(5+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"brick",new SimpleIcon(L"brick",slotSize*6,slotSize*1,slotSize*(6+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"ingotIron",new SimpleIcon(L"ingotIron",slotSize*7,slotSize*1,slotSize*(7+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"feather",new SimpleIcon(L"feather",slotSize*8,slotSize*1,slotSize*(8+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"wheat",new SimpleIcon(L"wheat",slotSize*9,slotSize*1,slotSize*(9+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"painting",new SimpleIcon(L"painting",slotSize*10,slotSize*1,slotSize*(10+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"reeds",new SimpleIcon(L"reeds",slotSize*11,slotSize*1,slotSize*(11+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"bone",new SimpleIcon(L"bone",slotSize*12,slotSize*1,slotSize*(12+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake",new SimpleIcon(L"cake",slotSize*13,slotSize*1,slotSize*(13+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"slimeball",new SimpleIcon(L"slimeball",slotSize*14,slotSize*1,slotSize*(14+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_chestplate",new SimpleIcon(L"slot_empty_chestplate",slotSize*15,slotSize*1,slotSize*(15+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsCloth",new SimpleIcon(L"leggingsCloth",slotSize*0,slotSize*2,slotSize*(0+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsChain",new SimpleIcon(L"leggingsChain",slotSize*1,slotSize*2,slotSize*(1+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsIron",new SimpleIcon(L"leggingsIron",slotSize*2,slotSize*2,slotSize*(2+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsDiamond",new SimpleIcon(L"leggingsDiamond",slotSize*3,slotSize*2,slotSize*(3+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsGold",new SimpleIcon(L"leggingsGold",slotSize*4,slotSize*2,slotSize*(4+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"arrow",new SimpleIcon(L"arrow",slotSize*5,slotSize*2,slotSize*(5+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"quiver",new SimpleIcon(L"quiver",slotSize*6,slotSize*2,slotSize*(6+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"ingotGold",new SimpleIcon(L"ingotGold",slotSize*7,slotSize*2,slotSize*(7+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"sulphur",new SimpleIcon(L"sulphur",slotSize*8,slotSize*2,slotSize*(8+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bread",new SimpleIcon(L"bread",slotSize*9,slotSize*2,slotSize*(9+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"sign",new SimpleIcon(L"sign",slotSize*10,slotSize*2,slotSize*(10+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorWood",new SimpleIcon(L"doorWood",slotSize*11,slotSize*2,slotSize*(11+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorIron",new SimpleIcon(L"doorIron",slotSize*12,slotSize*2,slotSize*(12+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed",new SimpleIcon(L"bed",slotSize*13,slotSize*2,slotSize*(13+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireball",new SimpleIcon(L"fireball",slotSize*14,slotSize*2,slotSize*(14+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_leggings",new SimpleIcon(L"slot_empty_leggings",slotSize*15,slotSize*2,slotSize*(15+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsCloth",new SimpleIcon(L"bootsCloth",slotSize*0,slotSize*3,slotSize*(0+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsChain",new SimpleIcon(L"bootsChain",slotSize*1,slotSize*3,slotSize*(1+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsIron",new SimpleIcon(L"bootsIron",slotSize*2,slotSize*3,slotSize*(2+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsDiamond",new SimpleIcon(L"bootsDiamond",slotSize*3,slotSize*3,slotSize*(3+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsGold",new SimpleIcon(L"bootsGold",slotSize*4,slotSize*3,slotSize*(4+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"stick",new SimpleIcon(L"stick",slotSize*5,slotSize*3,slotSize*(5+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"compass",new SimpleIcon(L"compass",slotSize*6,slotSize*3,slotSize*(6+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP0",new SimpleIcon(L"compassP0",slotSize*7,slotSize*14,slotSize*(7+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP1",new SimpleIcon(L"compassP1",slotSize*8,slotSize*14,slotSize*(8+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP2",new SimpleIcon(L"compassP2",slotSize*9,slotSize*14,slotSize*(9+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"compassP3",new SimpleIcon(L"compassP3",slotSize*10,slotSize*14,slotSize*(10+1),slotSize*(14+1)))); - texturesToAnimate.push_back(std::pair(L"compass",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP0",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP1",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP2",L"compass")); - texturesToAnimate.push_back(std::pair(L"compassP3",L"compass")); - texturesByName.insert(stringIconMap::value_type(L"diamond",new SimpleIcon(L"diamond",slotSize*7,slotSize*3,slotSize*(7+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstone",new SimpleIcon(L"redstone",slotSize*8,slotSize*3,slotSize*(8+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"clay",new SimpleIcon(L"clay",slotSize*9,slotSize*3,slotSize*(9+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"paper",new SimpleIcon(L"paper",slotSize*10,slotSize*3,slotSize*(10+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"book",new SimpleIcon(L"book",slotSize*11,slotSize*3,slotSize*(11+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"map",new SimpleIcon(L"map",slotSize*12,slotSize*3,slotSize*(12+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"seeds_pumpkin",new SimpleIcon(L"seeds_pumpkin",slotSize*13,slotSize*3,slotSize*(13+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"seeds_melon",new SimpleIcon(L"seeds_melon",slotSize*14,slotSize*3,slotSize*(14+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"slot_empty_boots",new SimpleIcon(L"slot_empty_boots",slotSize*15,slotSize*3,slotSize*(15+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordWood",new SimpleIcon(L"swordWood",slotSize*0,slotSize*4,slotSize*(0+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordStone",new SimpleIcon(L"swordStone",slotSize*1,slotSize*4,slotSize*(1+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordIron",new SimpleIcon(L"swordIron",slotSize*2,slotSize*4,slotSize*(2+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordDiamond",new SimpleIcon(L"swordDiamond",slotSize*3,slotSize*4,slotSize*(3+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"swordGold",new SimpleIcon(L"swordGold",slotSize*4,slotSize*4,slotSize*(4+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishingRod",new SimpleIcon(L"fishingRod",slotSize*5,slotSize*4,slotSize*(5+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"clock",new SimpleIcon(L"clock",slotSize*6,slotSize*4,slotSize*(6+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP0",new SimpleIcon(L"clockP0",slotSize*11,slotSize*14,slotSize*(11+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP1",new SimpleIcon(L"clockP1",slotSize*12,slotSize*14,slotSize*(12+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP2",new SimpleIcon(L"clockP2",slotSize*13,slotSize*14,slotSize*(13+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"clockP3",new SimpleIcon(L"clockP3",slotSize*14,slotSize*14,slotSize*(14+1),slotSize*(14+1)))); - texturesToAnimate.push_back(std::pair(L"clock",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP0",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP1",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP2",L"clock")); - texturesToAnimate.push_back(std::pair(L"clockP3",L"clock")); - texturesByName.insert(stringIconMap::value_type(L"bowl",new SimpleIcon(L"bowl",slotSize*7,slotSize*4,slotSize*(7+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroomStew",new SimpleIcon(L"mushroomStew",slotSize*8,slotSize*4,slotSize*(8+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"yellowDust",new SimpleIcon(L"yellowDust",slotSize*9,slotSize*4,slotSize*(9+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"bucket",new SimpleIcon(L"bucket",slotSize*10,slotSize*4,slotSize*(10+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"bucketWater",new SimpleIcon(L"bucketWater",slotSize*11,slotSize*4,slotSize*(11+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"bucketLava",new SimpleIcon(L"bucketLava",slotSize*12,slotSize*4,slotSize*(12+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"milk",new SimpleIcon(L"milk",slotSize*13,slotSize*4,slotSize*(13+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_black",new SimpleIcon(L"dyePowder_black",slotSize*14,slotSize*4,slotSize*(14+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_gray",new SimpleIcon(L"dyePowder_gray",slotSize*15,slotSize*4,slotSize*(15+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelWood",new SimpleIcon(L"shovelWood",slotSize*0,slotSize*5,slotSize*(0+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelStone",new SimpleIcon(L"shovelStone",slotSize*1,slotSize*5,slotSize*(1+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelIron",new SimpleIcon(L"shovelIron",slotSize*2,slotSize*5,slotSize*(2+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelDiamond",new SimpleIcon(L"shovelDiamond",slotSize*3,slotSize*5,slotSize*(3+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shovelGold",new SimpleIcon(L"shovelGold",slotSize*4,slotSize*5,slotSize*(4+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishingRod_empty",new SimpleIcon(L"fishingRod_empty",slotSize*5,slotSize*5,slotSize*(5+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"diode",new SimpleIcon(L"diode",slotSize*6,slotSize*5,slotSize*(6+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"porkchopRaw",new SimpleIcon(L"porkchopRaw",slotSize*7,slotSize*5,slotSize*(7+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"porkchopCooked",new SimpleIcon(L"porkchopCooked",slotSize*8,slotSize*5,slotSize*(8+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishRaw",new SimpleIcon(L"fishRaw",slotSize*9,slotSize*5,slotSize*(9+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fishCooked",new SimpleIcon(L"fishCooked",slotSize*10,slotSize*5,slotSize*(10+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"rottenFlesh",new SimpleIcon(L"rottenFlesh",slotSize*11,slotSize*5,slotSize*(11+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"cookie",new SimpleIcon(L"cookie",slotSize*12,slotSize*5,slotSize*(12+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"shears",new SimpleIcon(L"shears",slotSize*13,slotSize*5,slotSize*(13+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_red",new SimpleIcon(L"dyePowder_red",slotSize*14,slotSize*5,slotSize*(14+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_pink",new SimpleIcon(L"dyePowder_pink",slotSize*15,slotSize*5,slotSize*(15+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeWood",new SimpleIcon(L"pickaxeWood",slotSize*0,slotSize*6,slotSize*(0+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeStone",new SimpleIcon(L"pickaxeStone",slotSize*1,slotSize*6,slotSize*(1+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeIron",new SimpleIcon(L"pickaxeIron",slotSize*2,slotSize*6,slotSize*(2+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeDiamond",new SimpleIcon(L"pickaxeDiamond",slotSize*3,slotSize*6,slotSize*(3+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pickaxeGold",new SimpleIcon(L"pickaxeGold",slotSize*4,slotSize*6,slotSize*(4+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow_pull_0",new SimpleIcon(L"bow_pull_0",slotSize*5,slotSize*6,slotSize*(5+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrotOnAStick",new SimpleIcon(L"carrotOnAStick",slotSize*6,slotSize*6,slotSize*(6+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"leather",new SimpleIcon(L"leather",slotSize*7,slotSize*6,slotSize*(7+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"saddle",new SimpleIcon(L"saddle",slotSize*8,slotSize*6,slotSize*(8+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"beefRaw",new SimpleIcon(L"beefRaw",slotSize*9,slotSize*6,slotSize*(9+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"beefCooked",new SimpleIcon(L"beefCooked",slotSize*10,slotSize*6,slotSize*(10+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"enderPearl",new SimpleIcon(L"enderPearl",slotSize*11,slotSize*6,slotSize*(11+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"blazeRod",new SimpleIcon(L"blazeRod",slotSize*12,slotSize*6,slotSize*(12+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"melon",new SimpleIcon(L"melon",slotSize*13,slotSize*6,slotSize*(13+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_green",new SimpleIcon(L"dyePowder_green",slotSize*14,slotSize*6,slotSize*(14+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_lime",new SimpleIcon(L"dyePowder_lime",slotSize*15,slotSize*6,slotSize*(15+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetWood",new SimpleIcon(L"hatchetWood",slotSize*0,slotSize*7,slotSize*(0+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetStone",new SimpleIcon(L"hatchetStone",slotSize*1,slotSize*7,slotSize*(1+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetIron",new SimpleIcon(L"hatchetIron",slotSize*2,slotSize*7,slotSize*(2+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetDiamond",new SimpleIcon(L"hatchetDiamond",slotSize*3,slotSize*7,slotSize*(3+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hatchetGold",new SimpleIcon(L"hatchetGold",slotSize*4,slotSize*7,slotSize*(4+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow_pull_1",new SimpleIcon(L"bow_pull_1",slotSize*5,slotSize*7,slotSize*(5+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoBaked",new SimpleIcon(L"potatoBaked",slotSize*6,slotSize*7,slotSize*(6+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"potato",new SimpleIcon(L"potato",slotSize*7,slotSize*7,slotSize*(7+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots",new SimpleIcon(L"carrots",slotSize*8,slotSize*7,slotSize*(8+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"chickenRaw",new SimpleIcon(L"chickenRaw",slotSize*9,slotSize*7,slotSize*(9+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"chickenCooked",new SimpleIcon(L"chickenCooked",slotSize*10,slotSize*7,slotSize*(10+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"ghastTear",new SimpleIcon(L"ghastTear",slotSize*11,slotSize*7,slotSize*(11+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"goldNugget",new SimpleIcon(L"goldNugget",slotSize*12,slotSize*7,slotSize*(12+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalkSeeds",new SimpleIcon(L"netherStalkSeeds",slotSize*13,slotSize*7,slotSize*(13+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_brown",new SimpleIcon(L"dyePowder_brown",slotSize*14,slotSize*7,slotSize*(14+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_yellow",new SimpleIcon(L"dyePowder_yellow",slotSize*15,slotSize*7,slotSize*(15+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeWood",new SimpleIcon(L"hoeWood",slotSize*0,slotSize*8,slotSize*(0+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeStone",new SimpleIcon(L"hoeStone",slotSize*1,slotSize*8,slotSize*(1+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeIron",new SimpleIcon(L"hoeIron",slotSize*2,slotSize*8,slotSize*(2+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeDiamond",new SimpleIcon(L"hoeDiamond",slotSize*3,slotSize*8,slotSize*(3+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"hoeGold",new SimpleIcon(L"hoeGold",slotSize*4,slotSize*8,slotSize*(4+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"bow_pull_2",new SimpleIcon(L"bow_pull_2",slotSize*5,slotSize*8,slotSize*(5+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoPoisonous",new SimpleIcon(L"potatoPoisonous",slotSize*6,slotSize*8,slotSize*(6+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecart",new SimpleIcon(L"minecart",slotSize*7,slotSize*8,slotSize*(7+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"boat",new SimpleIcon(L"boat",slotSize*8,slotSize*8,slotSize*(8+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"speckledMelon",new SimpleIcon(L"speckledMelon",slotSize*9,slotSize*8,slotSize*(9+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"fermentedSpiderEye",new SimpleIcon(L"fermentedSpiderEye",slotSize*10,slotSize*8,slotSize*(10+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"spiderEye",new SimpleIcon(L"spiderEye",slotSize*11,slotSize*8,slotSize*(11+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"potion",new SimpleIcon(L"potion",slotSize*12,slotSize*8,slotSize*(12+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"glassBottle",new SimpleIcon(L"glassBottle",slotSize*12,slotSize*8,slotSize*(12+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"potion_contents",new SimpleIcon(L"potion_contents",slotSize*13,slotSize*8,slotSize*(13+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_blue",new SimpleIcon(L"dyePowder_blue",slotSize*14,slotSize*8,slotSize*(14+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_lightBlue",new SimpleIcon(L"dyePowder_lightBlue",slotSize*15,slotSize*8,slotSize*(15+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"helmetCloth_overlay",new SimpleIcon(L"helmetCloth_overlay",slotSize*0,slotSize*9,slotSize*(0+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"comparator",new SimpleIcon(L"comparator",slotSize*5,slotSize*9,slotSize*(5+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrotGolden",new SimpleIcon(L"carrotGolden",slotSize*6,slotSize*9,slotSize*(6+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartChest",new SimpleIcon(L"minecartChest",slotSize*7,slotSize*9,slotSize*(7+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkinPie",new SimpleIcon(L"pumpkinPie",slotSize*8,slotSize*9,slotSize*(8+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"monsterPlacer",new SimpleIcon(L"monsterPlacer",slotSize*9,slotSize*9,slotSize*(9+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"potion_splash",new SimpleIcon(L"potion_splash",slotSize*10,slotSize*9,slotSize*(10+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"eyeOfEnder",new SimpleIcon(L"eyeOfEnder",slotSize*11,slotSize*9,slotSize*(11+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron",new SimpleIcon(L"cauldron",slotSize*12,slotSize*9,slotSize*(12+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"blazePowder",new SimpleIcon(L"blazePowder",slotSize*13,slotSize*9,slotSize*(13+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_purple",new SimpleIcon(L"dyePowder_purple",slotSize*14,slotSize*9,slotSize*(14+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_magenta",new SimpleIcon(L"dyePowder_magenta",slotSize*15,slotSize*9,slotSize*(15+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"chestplateCloth_overlay",new SimpleIcon(L"chestplateCloth_overlay",slotSize*0,slotSize*10,slotSize*(0+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherbrick",new SimpleIcon(L"netherbrick",slotSize*5,slotSize*10,slotSize*(5+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartFurnace",new SimpleIcon(L"minecartFurnace",slotSize*7,slotSize*10,slotSize*(7+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"monsterPlacer_overlay",new SimpleIcon(L"monsterPlacer_overlay",slotSize*9,slotSize*10,slotSize*(9+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"ruby",new SimpleIcon(L"ruby",slotSize*10,slotSize*10,slotSize*(10+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"expBottle",new SimpleIcon(L"expBottle",slotSize*11,slotSize*10,slotSize*(11+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"brewingStand",new SimpleIcon(L"brewingStand",slotSize*12,slotSize*10,slotSize*(12+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"magmaCream",new SimpleIcon(L"magmaCream",slotSize*13,slotSize*10,slotSize*(13+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_cyan",new SimpleIcon(L"dyePowder_cyan",slotSize*14,slotSize*10,slotSize*(14+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_orange",new SimpleIcon(L"dyePowder_orange",slotSize*15,slotSize*10,slotSize*(15+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"leggingsCloth_overlay",new SimpleIcon(L"leggingsCloth_overlay",slotSize*0,slotSize*11,slotSize*(0+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartHopper",new SimpleIcon(L"minecartHopper",slotSize*7,slotSize*11,slotSize*(7+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper",new SimpleIcon(L"hopper",slotSize*8,slotSize*11,slotSize*(8+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStar",new SimpleIcon(L"netherStar",slotSize*9,slotSize*11,slotSize*(9+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"emerald",new SimpleIcon(L"emerald",slotSize*10,slotSize*11,slotSize*(10+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"writingBook",new SimpleIcon(L"writingBook",slotSize*11,slotSize*11,slotSize*(11+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"writtenBook",new SimpleIcon(L"writtenBook",slotSize*12,slotSize*11,slotSize*(12+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"flowerPot",new SimpleIcon(L"flowerPot",slotSize*13,slotSize*11,slotSize*(13+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_silver",new SimpleIcon(L"dyePowder_silver",slotSize*14,slotSize*11,slotSize*(14+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"dyePowder_white",new SimpleIcon(L"dyePowder_white",slotSize*15,slotSize*11,slotSize*(15+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"bootsCloth_overlay",new SimpleIcon(L"bootsCloth_overlay",slotSize*0,slotSize*12,slotSize*(0+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"minecartTnt",new SimpleIcon(L"minecartTnt",slotSize*7,slotSize*12,slotSize*(7+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireworks",new SimpleIcon(L"fireworks",slotSize*9,slotSize*12,slotSize*(9+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireworksCharge",new SimpleIcon(L"fireworksCharge",slotSize*10,slotSize*12,slotSize*(10+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"fireworksCharge_overlay",new SimpleIcon(L"fireworksCharge_overlay",slotSize*11,slotSize*12,slotSize*(11+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherquartz",new SimpleIcon(L"netherquartz",slotSize*12,slotSize*12,slotSize*(12+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"emptyMap",new SimpleIcon(L"emptyMap",slotSize*13,slotSize*12,slotSize*(13+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"frame",new SimpleIcon(L"frame",slotSize*14,slotSize*12,slotSize*(14+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantedBook",new SimpleIcon(L"enchantedBook",slotSize*15,slotSize*12,slotSize*(15+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_skeleton",new SimpleIcon(L"skull_skeleton",slotSize*0,slotSize*14,slotSize*(0+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_wither",new SimpleIcon(L"skull_wither",slotSize*1,slotSize*14,slotSize*(1+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_zombie",new SimpleIcon(L"skull_zombie",slotSize*2,slotSize*14,slotSize*(2+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_char",new SimpleIcon(L"skull_char",slotSize*3,slotSize*14,slotSize*(3+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"skull_creeper",new SimpleIcon(L"skull_creeper",slotSize*4,slotSize*14,slotSize*(4+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"dragonFireball",new SimpleIcon(L"dragonFireball",slotSize*15,slotSize*14,slotSize*(15+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_13",new SimpleIcon(L"record_13",slotSize*0,slotSize*15,slotSize*(0+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_cat",new SimpleIcon(L"record_cat",slotSize*1,slotSize*15,slotSize*(1+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_blocks",new SimpleIcon(L"record_blocks",slotSize*2,slotSize*15,slotSize*(2+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_chirp",new SimpleIcon(L"record_chirp",slotSize*3,slotSize*15,slotSize*(3+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_far",new SimpleIcon(L"record_far",slotSize*4,slotSize*15,slotSize*(4+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_mall",new SimpleIcon(L"record_mall",slotSize*5,slotSize*15,slotSize*(5+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_mellohi",new SimpleIcon(L"record_mellohi",slotSize*6,slotSize*15,slotSize*(6+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_stal",new SimpleIcon(L"record_stal",slotSize*7,slotSize*15,slotSize*(7+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_strad",new SimpleIcon(L"record_strad",slotSize*8,slotSize*15,slotSize*(8+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_ward",new SimpleIcon(L"record_ward",slotSize*9,slotSize*15,slotSize*(9+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_11",new SimpleIcon(L"record_11",slotSize*10,slotSize*15,slotSize*(10+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"record_where are we now",new SimpleIcon(L"record_where are we now",slotSize*11,slotSize*15,slotSize*(11+1),slotSize*(15+1)))); - - // Special cases - ClockTexture *dataClock = new ClockTexture(); - Icon *oldClock = texturesByName[L"clock"]; - dataClock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clock"] = dataClock; - - ClockTexture *clock = new ClockTexture(0, dataClock); - oldClock = texturesByName[L"clockP0"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP0"] = clock; - - clock = new ClockTexture(1, dataClock); - oldClock = texturesByName[L"clockP1"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP1"] = clock; - - clock = new ClockTexture(2, dataClock); - oldClock = texturesByName[L"clockP2"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP2"] = clock; - - clock = new ClockTexture(3, dataClock); - oldClock = texturesByName[L"clockP3"]; - clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), oldClock->getV1() ); - delete oldClock; - texturesByName[L"clockP3"] = clock; - - CompassTexture *dataCompass = new CompassTexture(); - Icon *oldCompass = texturesByName[L"compass"]; - dataCompass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compass"] = dataCompass; - - CompassTexture *compass = new CompassTexture(0, dataCompass); - oldCompass = texturesByName[L"compassP0"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP0"] = compass; - - compass = new CompassTexture(1, dataCompass); - oldCompass = texturesByName[L"compassP1"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP1"] = compass; - - compass = new CompassTexture(2, dataCompass); - oldCompass = texturesByName[L"compassP2"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP2"] = compass; - - compass = new CompassTexture(3, dataCompass); - oldCompass = texturesByName[L"compassP3"]; - compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), oldCompass->getU1(), oldCompass->getV1() ); - delete oldCompass; - texturesByName[L"compassP3"] = compass; - } - else - { - texturesByName.insert(stringIconMap::value_type(L"grass_top",new SimpleIcon(L"grass_top",slotSize*0,slotSize*0,slotSize*(0+1),slotSize*(0+1)))); - texturesByName[L"grass_top"]->setFlags(Icon::IS_GRASS_TOP); // 4J added for faster determination of texture type in tesselation - texturesByName.insert(stringIconMap::value_type(L"stone",new SimpleIcon(L"stone",slotSize*1,slotSize*0,slotSize*(1+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"dirt",new SimpleIcon(L"dirt",slotSize*2,slotSize*0,slotSize*(2+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"grass_side",new SimpleIcon(L"grass_side",slotSize*3,slotSize*0,slotSize*(3+1),slotSize*(0+1)))); - texturesByName[L"grass_side"]->setFlags(Icon::IS_GRASS_SIDE); // 4J added for faster determination of texture type in tesselation - texturesByName.insert(stringIconMap::value_type(L"wood",new SimpleIcon(L"wood",slotSize*4,slotSize*0,slotSize*(4+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"stoneslab_side",new SimpleIcon(L"stoneslab_side",slotSize*5,slotSize*0,slotSize*(5+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"stoneslab_top",new SimpleIcon(L"stoneslab_top",slotSize*6,slotSize*0,slotSize*(6+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"brick",new SimpleIcon(L"brick",slotSize*7,slotSize*0,slotSize*(7+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"tnt_side",new SimpleIcon(L"tnt_side",slotSize*8,slotSize*0,slotSize*(8+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"tnt_top",new SimpleIcon(L"tnt_top",slotSize*9,slotSize*0,slotSize*(9+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"tnt_bottom",new SimpleIcon(L"tnt_bottom",slotSize*10,slotSize*0,slotSize*(10+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"web",new SimpleIcon(L"web",slotSize*11,slotSize*0,slotSize*(11+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"rose",new SimpleIcon(L"rose",slotSize*12,slotSize*0,slotSize*(12+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"flower",new SimpleIcon(L"flower",slotSize*13,slotSize*0,slotSize*(13+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"portal",new SimpleIcon(L"portal",slotSize*14,slotSize*0,slotSize*(14+1),slotSize*(0+1)))); - texturesToAnimate.push_back(std::pair(L"portal",L"portal")); - texturesByName.insert(stringIconMap::value_type(L"sapling",new SimpleIcon(L"sapling",slotSize*15,slotSize*0,slotSize*(15+1),slotSize*(0+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebrick",new SimpleIcon(L"stonebrick",slotSize*0,slotSize*1,slotSize*(0+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"bedrock",new SimpleIcon(L"bedrock",slotSize*1,slotSize*1,slotSize*(1+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"sand",new SimpleIcon(L"sand",slotSize*2,slotSize*1,slotSize*(2+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"gravel",new SimpleIcon(L"gravel",slotSize*3,slotSize*1,slotSize*(3+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_side",new SimpleIcon(L"tree_side",slotSize*4,slotSize*1,slotSize*(4+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_top",new SimpleIcon(L"tree_top",slotSize*5,slotSize*1,slotSize*(5+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockIron",new SimpleIcon(L"blockIron",slotSize*6,slotSize*1,slotSize*(6+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockGold",new SimpleIcon(L"blockGold",slotSize*7,slotSize*1,slotSize*(7+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockDiamond",new SimpleIcon(L"blockDiamond",slotSize*8,slotSize*1,slotSize*(8+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockEmerald",new SimpleIcon(L"blockEmerald",slotSize*9,slotSize*1,slotSize*(9+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockRedstone",new SimpleIcon(L"blockRedstone",slotSize*10,slotSize*1,slotSize*(10+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"dropper_front",new SimpleIcon(L"dropper_front",slotSize*11,slotSize*1,slotSize*(11+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_red",new SimpleIcon(L"mushroom_red",slotSize*12,slotSize*1,slotSize*(12+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_brown",new SimpleIcon(L"mushroom_brown",slotSize*13,slotSize*1,slotSize*(13+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"sapling_jungle",new SimpleIcon(L"sapling_jungle",slotSize*14,slotSize*1,slotSize*(14+1),slotSize*(1+1)))); - texturesByName.insert(stringIconMap::value_type(L"fire_0",new SimpleIcon(L"fire_0",slotSize*15,slotSize*1,slotSize*(15+1),slotSize*(1+1)))); - texturesToAnimate.push_back(std::pair(L"fire_0",L"fire_0")); - texturesByName.insert(stringIconMap::value_type(L"oreGold",new SimpleIcon(L"oreGold",slotSize*0,slotSize*2,slotSize*(0+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreIron",new SimpleIcon(L"oreIron",slotSize*1,slotSize*2,slotSize*(1+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreCoal",new SimpleIcon(L"oreCoal",slotSize*2,slotSize*2,slotSize*(2+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"bookshelf",new SimpleIcon(L"bookshelf",slotSize*3,slotSize*2,slotSize*(3+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"stoneMoss",new SimpleIcon(L"stoneMoss",slotSize*4,slotSize*2,slotSize*(4+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"obsidian",new SimpleIcon(L"obsidian",slotSize*5,slotSize*2,slotSize*(5+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"grass_side_overlay",new SimpleIcon(L"grass_side_overlay",slotSize*6,slotSize*2,slotSize*(6+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"tallgrass",new SimpleIcon(L"tallgrass",slotSize*7,slotSize*2,slotSize*(7+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"dispenser_front_vertical",new SimpleIcon(L"dispenser_front_vertical",slotSize*8,slotSize*2,slotSize*(8+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"beacon",new SimpleIcon(L"beacon",slotSize*9,slotSize*2,slotSize*(9+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"dropper_front_vertical",new SimpleIcon(L"dropper_front_vertical",slotSize*10,slotSize*2,slotSize*(10+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"workbench_top",new SimpleIcon(L"workbench_top",slotSize*11,slotSize*2,slotSize*(11+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_front",new SimpleIcon(L"furnace_front",slotSize*12,slotSize*2,slotSize*(12+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_side",new SimpleIcon(L"furnace_side",slotSize*13,slotSize*2,slotSize*(13+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"dispenser_front",new SimpleIcon(L"dispenser_front",slotSize*14,slotSize*2,slotSize*(14+1),slotSize*(2+1)))); - texturesByName.insert(stringIconMap::value_type(L"fire_1",new SimpleIcon(L"fire_1",slotSize*15,slotSize*1,slotSize*(15+1),slotSize*(1+1)))); - texturesToAnimate.push_back(std::pair(L"fire_1",L"fire_1")); - texturesByName.insert(stringIconMap::value_type(L"sponge",new SimpleIcon(L"sponge",slotSize*0,slotSize*3,slotSize*(0+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"glass",new SimpleIcon(L"glass",slotSize*1,slotSize*3,slotSize*(1+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreDiamond",new SimpleIcon(L"oreDiamond",slotSize*2,slotSize*3,slotSize*(2+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreRedstone",new SimpleIcon(L"oreRedstone",slotSize*3,slotSize*3,slotSize*(3+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves",new SimpleIcon(L"leaves",slotSize*4,slotSize*3,slotSize*(4+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_opaque",new SimpleIcon(L"leaves_opaque",slotSize*5,slotSize*3,slotSize*(5+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth",new SimpleIcon(L"stonebricksmooth",slotSize*6,slotSize*3,slotSize*(6+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"deadbush",new SimpleIcon(L"deadbush",slotSize*7,slotSize*3,slotSize*(7+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"fern",new SimpleIcon(L"fern",slotSize*8,slotSize*3,slotSize*(8+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"daylightDetector_top",new SimpleIcon(L"daylightDetector_top",slotSize*9,slotSize*3,slotSize*(9+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"daylightDetector_side",new SimpleIcon(L"daylightDetector_side",slotSize*10,slotSize*3,slotSize*(10+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"workbench_side",new SimpleIcon(L"workbench_side",slotSize*11,slotSize*3,slotSize*(11+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"workbench_front",new SimpleIcon(L"workbench_front",slotSize*12,slotSize*3,slotSize*(12+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_front_lit",new SimpleIcon(L"furnace_front_lit",slotSize*13,slotSize*3,slotSize*(13+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"furnace_top",new SimpleIcon(L"furnace_top",slotSize*14,slotSize*3,slotSize*(14+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"sapling_spruce",new SimpleIcon(L"sapling_spruce",slotSize*15,slotSize*3,slotSize*(15+1),slotSize*(3+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_0",new SimpleIcon(L"cloth_0",slotSize*0,slotSize*4,slotSize*(0+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mobSpawner",new SimpleIcon(L"mobSpawner",slotSize*1,slotSize*4,slotSize*(1+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"snow",new SimpleIcon(L"snow",slotSize*2,slotSize*4,slotSize*(2+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"ice",new SimpleIcon(L"ice",slotSize*3,slotSize*4,slotSize*(3+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"snow_side",new SimpleIcon(L"snow_side",slotSize*4,slotSize*4,slotSize*(4+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"cactus_top",new SimpleIcon(L"cactus_top",slotSize*5,slotSize*4,slotSize*(5+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"cactus_side",new SimpleIcon(L"cactus_side",slotSize*6,slotSize*4,slotSize*(6+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"cactus_bottom",new SimpleIcon(L"cactus_bottom",slotSize*7,slotSize*4,slotSize*(7+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"clay",new SimpleIcon(L"clay",slotSize*8,slotSize*4,slotSize*(8+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"reeds",new SimpleIcon(L"reeds",slotSize*9,slotSize*4,slotSize*(9+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"musicBlock",new SimpleIcon(L"musicBlock",slotSize*10,slotSize*4,slotSize*(10+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"jukebox_top",new SimpleIcon(L"jukebox_top",slotSize*11,slotSize*4,slotSize*(11+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"waterlily",new SimpleIcon(L"waterlily",slotSize*12,slotSize*4,slotSize*(12+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mycel_side",new SimpleIcon(L"mycel_side",slotSize*13,slotSize*4,slotSize*(13+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"mycel_top",new SimpleIcon(L"mycel_top",slotSize*14,slotSize*4,slotSize*(14+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"sapling_birch",new SimpleIcon(L"sapling_birch",slotSize*15,slotSize*4,slotSize*(15+1),slotSize*(4+1)))); - texturesByName.insert(stringIconMap::value_type(L"torch",new SimpleIcon(L"torch",slotSize*0,slotSize*5,slotSize*(0+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorWood_upper",new SimpleIcon(L"doorWood_upper",slotSize*1,slotSize*5,slotSize*(1+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorIron_upper",new SimpleIcon(L"doorIron_upper",slotSize*2,slotSize*5,slotSize*(2+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"ladder",new SimpleIcon(L"ladder",slotSize*3,slotSize*5,slotSize*(3+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"trapdoor",new SimpleIcon(L"trapdoor",slotSize*4,slotSize*5,slotSize*(4+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"fenceIron",new SimpleIcon(L"fenceIron",slotSize*5,slotSize*5,slotSize*(5+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"farmland_wet",new SimpleIcon(L"farmland_wet",slotSize*6,slotSize*5,slotSize*(6+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"farmland_dry",new SimpleIcon(L"farmland_dry",slotSize*7,slotSize*5,slotSize*(7+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_0",new SimpleIcon(L"crops_0",slotSize*8,slotSize*5,slotSize*(8+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_1",new SimpleIcon(L"crops_1",slotSize*9,slotSize*5,slotSize*(9+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_2",new SimpleIcon(L"crops_2",slotSize*10,slotSize*5,slotSize*(10+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_3",new SimpleIcon(L"crops_3",slotSize*11,slotSize*5,slotSize*(11+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_4",new SimpleIcon(L"crops_4",slotSize*12,slotSize*5,slotSize*(12+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_5",new SimpleIcon(L"crops_5",slotSize*13,slotSize*5,slotSize*(13+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_6",new SimpleIcon(L"crops_6",slotSize*14,slotSize*5,slotSize*(14+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"crops_7",new SimpleIcon(L"crops_7",slotSize*15,slotSize*5,slotSize*(15+1),slotSize*(5+1)))); - texturesByName.insert(stringIconMap::value_type(L"lever",new SimpleIcon(L"lever",slotSize*0,slotSize*6,slotSize*(0+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorWood_lower",new SimpleIcon(L"doorWood_lower",slotSize*1,slotSize*6,slotSize*(1+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"doorIron_lower",new SimpleIcon(L"doorIron_lower",slotSize*2,slotSize*6,slotSize*(2+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"redtorch_lit",new SimpleIcon(L"redtorch_lit",slotSize*3,slotSize*6,slotSize*(3+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth_mossy",new SimpleIcon(L"stonebricksmooth_mossy",slotSize*4,slotSize*6,slotSize*(4+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth_cracked",new SimpleIcon(L"stonebricksmooth_cracked",slotSize*5,slotSize*6,slotSize*(5+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_top",new SimpleIcon(L"pumpkin_top",slotSize*6,slotSize*6,slotSize*(6+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"hellrock",new SimpleIcon(L"hellrock",slotSize*7,slotSize*6,slotSize*(7+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"hellsand",new SimpleIcon(L"hellsand",slotSize*8,slotSize*6,slotSize*(8+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"lightgem",new SimpleIcon(L"lightgem",slotSize*9,slotSize*6,slotSize*(9+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_top_sticky",new SimpleIcon(L"piston_top_sticky",slotSize*10,slotSize*6,slotSize*(10+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_top",new SimpleIcon(L"piston_top",slotSize*11,slotSize*6,slotSize*(11+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_side",new SimpleIcon(L"piston_side",slotSize*12,slotSize*6,slotSize*(12+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_bottom",new SimpleIcon(L"piston_bottom",slotSize*13,slotSize*6,slotSize*(13+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"piston_inner_top",new SimpleIcon(L"piston_inner_top",slotSize*14,slotSize*6,slotSize*(14+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"stem_straight",new SimpleIcon(L"stem_straight",slotSize*15,slotSize*6,slotSize*(15+1),slotSize*(6+1)))); - texturesByName.insert(stringIconMap::value_type(L"rail_turn",new SimpleIcon(L"rail_turn",slotSize*0,slotSize*7,slotSize*(0+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_15",new SimpleIcon(L"cloth_15",slotSize*1,slotSize*7,slotSize*(1+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_7",new SimpleIcon(L"cloth_7",slotSize*2,slotSize*7,slotSize*(2+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"redtorch",new SimpleIcon(L"redtorch",slotSize*3,slotSize*7,slotSize*(3+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_spruce",new SimpleIcon(L"tree_spruce",slotSize*4,slotSize*7,slotSize*(4+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_birch",new SimpleIcon(L"tree_birch",slotSize*5,slotSize*7,slotSize*(5+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_side",new SimpleIcon(L"pumpkin_side",slotSize*6,slotSize*7,slotSize*(6+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_face",new SimpleIcon(L"pumpkin_face",slotSize*7,slotSize*7,slotSize*(7+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"pumpkin_jack",new SimpleIcon(L"pumpkin_jack",slotSize*8,slotSize*7,slotSize*(8+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_top",new SimpleIcon(L"cake_top",slotSize*9,slotSize*7,slotSize*(9+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_side",new SimpleIcon(L"cake_side",slotSize*10,slotSize*7,slotSize*(10+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_inner",new SimpleIcon(L"cake_inner",slotSize*11,slotSize*7,slotSize*(11+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"cake_bottom",new SimpleIcon(L"cake_bottom",slotSize*12,slotSize*7,slotSize*(12+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_skin_red",new SimpleIcon(L"mushroom_skin_red",slotSize*13,slotSize*7,slotSize*(13+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_skin_brown",new SimpleIcon(L"mushroom_skin_brown",slotSize*14,slotSize*7,slotSize*(14+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"stem_bent",new SimpleIcon(L"stem_bent",slotSize*15,slotSize*7,slotSize*(15+1),slotSize*(7+1)))); - texturesByName.insert(stringIconMap::value_type(L"rail",new SimpleIcon(L"rail",slotSize*0,slotSize*8,slotSize*(0+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_14",new SimpleIcon(L"cloth_14",slotSize*1,slotSize*8,slotSize*(1+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_6",new SimpleIcon(L"cloth_6",slotSize*2,slotSize*8,slotSize*(2+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"repeater",new SimpleIcon(L"repeater",slotSize*3,slotSize*8,slotSize*(3+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_spruce",new SimpleIcon(L"leaves_spruce",slotSize*4,slotSize*8,slotSize*(4+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_spruce_opaque",new SimpleIcon(L"leaves_spruce_opaque",slotSize*5,slotSize*8,slotSize*(5+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_feet_top",new SimpleIcon(L"bed_feet_top",slotSize*6,slotSize*8,slotSize*(6+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_head_top",new SimpleIcon(L"bed_head_top",slotSize*7,slotSize*8,slotSize*(7+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"melon_side",new SimpleIcon(L"melon_side",slotSize*8,slotSize*8,slotSize*(8+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"melon_top",new SimpleIcon(L"melon_top",slotSize*9,slotSize*8,slotSize*(9+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_top",new SimpleIcon(L"cauldron_top",slotSize*10,slotSize*8,slotSize*(10+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_inner",new SimpleIcon(L"cauldron_inner",slotSize*11,slotSize*8,slotSize*(11+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_skin_stem",new SimpleIcon(L"mushroom_skin_stem",slotSize*13,slotSize*8,slotSize*(13+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"mushroom_inside",new SimpleIcon(L"mushroom_inside",slotSize*14,slotSize*8,slotSize*(14+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"vine",new SimpleIcon(L"vine",slotSize*15,slotSize*8,slotSize*(15+1),slotSize*(8+1)))); - texturesByName.insert(stringIconMap::value_type(L"blockLapis",new SimpleIcon(L"blockLapis",slotSize*0,slotSize*9,slotSize*(0+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_13",new SimpleIcon(L"cloth_13",slotSize*1,slotSize*9,slotSize*(1+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_5",new SimpleIcon(L"cloth_5",slotSize*2,slotSize*9,slotSize*(2+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"repeater_lit",new SimpleIcon(L"repeater_lit",slotSize*3,slotSize*9,slotSize*(3+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"thinglass_top",new SimpleIcon(L"thinglass_top",slotSize*4,slotSize*9,slotSize*(4+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_feet_end",new SimpleIcon(L"bed_feet_end",slotSize*5,slotSize*9,slotSize*(5+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_feet_side",new SimpleIcon(L"bed_feet_side",slotSize*6,slotSize*9,slotSize*(6+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_head_side",new SimpleIcon(L"bed_head_side",slotSize*7,slotSize*9,slotSize*(7+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"bed_head_end",new SimpleIcon(L"bed_head_end",slotSize*8,slotSize*9,slotSize*(8+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"tree_jungle",new SimpleIcon(L"tree_jungle",slotSize*9,slotSize*9,slotSize*(9+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_side",new SimpleIcon(L"cauldron_side",slotSize*10,slotSize*9,slotSize*(10+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"cauldron_bottom",new SimpleIcon(L"cauldron_bottom",slotSize*11,slotSize*9,slotSize*(11+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"brewingStand_base",new SimpleIcon(L"brewingStand_base",slotSize*12,slotSize*9,slotSize*(12+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"brewingStand",new SimpleIcon(L"brewingStand",slotSize*13,slotSize*9,slotSize*(13+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"endframe_top",new SimpleIcon(L"endframe_top",slotSize*14,slotSize*9,slotSize*(14+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"endframe_side",new SimpleIcon(L"endframe_side",slotSize*15,slotSize*9,slotSize*(15+1),slotSize*(9+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreLapis",new SimpleIcon(L"oreLapis",slotSize*0,slotSize*10,slotSize*(0+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_12",new SimpleIcon(L"cloth_12",slotSize*1,slotSize*10,slotSize*(1+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_4",new SimpleIcon(L"cloth_4",slotSize*2,slotSize*10,slotSize*(2+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"goldenRail",new SimpleIcon(L"goldenRail",slotSize*3,slotSize*10,slotSize*(3+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_cross",new SimpleIcon(L"redstoneDust_cross",slotSize*4,slotSize*10,slotSize*(4+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_line",new SimpleIcon(L"redstoneDust_line",slotSize*5,slotSize*10,slotSize*(5+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantment_top",new SimpleIcon(L"enchantment_top",slotSize*6,slotSize*10,slotSize*(6+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"dragonEgg",new SimpleIcon(L"dragonEgg",slotSize*7,slotSize*10,slotSize*(7+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cocoa_2",new SimpleIcon(L"cocoa_2",slotSize*8,slotSize*10,slotSize*(8+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cocoa_1",new SimpleIcon(L"cocoa_1",slotSize*9,slotSize*10,slotSize*(9+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"cocoa_0",new SimpleIcon(L"cocoa_0",slotSize*10,slotSize*10,slotSize*(10+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"oreEmerald",new SimpleIcon(L"oreEmerald",slotSize*11,slotSize*10,slotSize*(11+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"tripWireSource",new SimpleIcon(L"tripWireSource",slotSize*12,slotSize*10,slotSize*(12+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"tripWire",new SimpleIcon(L"tripWire",slotSize*13,slotSize*10,slotSize*(13+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"endframe_eye",new SimpleIcon(L"endframe_eye",slotSize*14,slotSize*10,slotSize*(14+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"whiteStone",new SimpleIcon(L"whiteStone",slotSize*15,slotSize*10,slotSize*(15+1),slotSize*(10+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_top",new SimpleIcon(L"sandstone_top",slotSize*0,slotSize*11,slotSize*(0+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_11",new SimpleIcon(L"cloth_11",slotSize*1,slotSize*11,slotSize*(1+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_3",new SimpleIcon(L"cloth_3",slotSize*2,slotSize*11,slotSize*(2+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"goldenRail_powered",new SimpleIcon(L"goldenRail_powered",slotSize*3,slotSize*11,slotSize*(3+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_cross_overlay",new SimpleIcon(L"redstoneDust_cross_overlay",slotSize*4,slotSize*11,slotSize*(4+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneDust_line_overlay",new SimpleIcon(L"redstoneDust_line_overlay",slotSize*5,slotSize*11,slotSize*(5+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantment_side",new SimpleIcon(L"enchantment_side",slotSize*6,slotSize*11,slotSize*(6+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"enchantment_bottom",new SimpleIcon(L"enchantment_bottom",slotSize*7,slotSize*11,slotSize*(7+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"commandBlock",new SimpleIcon(L"commandBlock",slotSize*8,slotSize*11,slotSize*(8+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"itemframe_back",new SimpleIcon(L"itemframe_back",slotSize*9,slotSize*11,slotSize*(9+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"flowerPot",new SimpleIcon(L"flowerPot",slotSize*10,slotSize*11,slotSize*(10+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"comparator",new SimpleIcon(L"comparator",slotSize*11,slotSize*11,slotSize*(11+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"comparator_lit",new SimpleIcon(L"comparator_lit",slotSize*12,slotSize*11,slotSize*(12+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"activatorRail",new SimpleIcon(L"activatorRail",slotSize*13,slotSize*11,slotSize*(13+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"activatorRail_powered",new SimpleIcon(L"activatorRail_powered",slotSize*14,slotSize*11,slotSize*(14+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherquartz",new SimpleIcon(L"netherquartz",slotSize*15,slotSize*11,slotSize*(15+1),slotSize*(11+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_side",new SimpleIcon(L"sandstone_side",slotSize*0,slotSize*12,slotSize*(0+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_10",new SimpleIcon(L"cloth_10",slotSize*1,slotSize*12,slotSize*(1+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_2",new SimpleIcon(L"cloth_2",slotSize*2,slotSize*12,slotSize*(2+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"detectorRail",new SimpleIcon(L"detectorRail",slotSize*3,slotSize*12,slotSize*(3+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_jungle",new SimpleIcon(L"leaves_jungle",slotSize*4,slotSize*12,slotSize*(4+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"leaves_jungle_opaque",new SimpleIcon(L"leaves_jungle_opaque",slotSize*5,slotSize*12,slotSize*(5+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"wood_spruce",new SimpleIcon(L"wood_spruce",slotSize*6,slotSize*12,slotSize*(6+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"wood_jungle",new SimpleIcon(L"wood_jungle",slotSize*7,slotSize*12,slotSize*(7+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_0",new SimpleIcon(L"carrots_0",slotSize*8,slotSize*12,slotSize*(8+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_1",new SimpleIcon(L"carrots_1",slotSize*9,slotSize*12,slotSize*(9+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_2",new SimpleIcon(L"carrots_2",slotSize*10,slotSize*12,slotSize*(10+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"carrots_3",new SimpleIcon(L"carrots_3",slotSize*11,slotSize*12,slotSize*(11+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_0",new SimpleIcon(L"potatoes_0",slotSize*8,slotSize*12,slotSize*(8+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_1",new SimpleIcon(L"potatoes_1",slotSize*9,slotSize*12,slotSize*(9+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_2",new SimpleIcon(L"potatoes_2",slotSize*10,slotSize*12,slotSize*(10+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"potatoes_3",new SimpleIcon(L"potatoes_3",slotSize*12,slotSize*12,slotSize*(12+1),slotSize*(12+1)))); - texturesByName.insert(stringIconMap::value_type(L"water",new SimpleIcon(L"water",slotSize*13,slotSize*12,slotSize*(13+1),slotSize*(12+1)))); - texturesToAnimate.push_back(std::pair(L"water",L"water")); - texturesByName.insert(stringIconMap::value_type(L"water_flow",new SimpleIcon(L"water_flow",slotSize*14,slotSize*12,slotSize*(14+2),slotSize*(12+2)))); - texturesToAnimate.push_back(std::pair(L"water_flow",L"water_flow")); - texturesByName.insert(stringIconMap::value_type(L"sandstone_bottom",new SimpleIcon(L"sandstone_bottom",slotSize*0,slotSize*13,slotSize*(0+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_9",new SimpleIcon(L"cloth_9",slotSize*1,slotSize*13,slotSize*(1+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_1",new SimpleIcon(L"cloth_1",slotSize*2,slotSize*13,slotSize*(2+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneLight",new SimpleIcon(L"redstoneLight",slotSize*3,slotSize*13,slotSize*(3+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"redstoneLight_lit",new SimpleIcon(L"redstoneLight_lit",slotSize*4,slotSize*13,slotSize*(4+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"stonebricksmooth_carved",new SimpleIcon(L"stonebricksmooth_carved",slotSize*5,slotSize*13,slotSize*(5+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"wood_birch",new SimpleIcon(L"wood_birch",slotSize*6,slotSize*13,slotSize*(6+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_base",new SimpleIcon(L"anvil_base",slotSize*7,slotSize*13,slotSize*(7+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_top_damaged_1",new SimpleIcon(L"anvil_top_damaged_1",slotSize*8,slotSize*13,slotSize*(8+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_chiseled_top",new SimpleIcon(L"quartzblock_chiseled_top",slotSize*9,slotSize*13,slotSize*(9+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_lines_top",new SimpleIcon(L"quartzblock_lines_top",slotSize*10,slotSize*13,slotSize*(10+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_top",new SimpleIcon(L"quartzblock_top",slotSize*11,slotSize*13,slotSize*(11+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper",new SimpleIcon(L"hopper",slotSize*12,slotSize*13,slotSize*(12+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"detectorRail_on",new SimpleIcon(L"detectorRail_on",slotSize*13,slotSize*13,slotSize*(13+1),slotSize*(13+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherBrick",new SimpleIcon(L"netherBrick",slotSize*0,slotSize*14,slotSize*(0+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"cloth_8",new SimpleIcon(L"cloth_8",slotSize*1,slotSize*14,slotSize*(1+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalk_0",new SimpleIcon(L"netherStalk_0",slotSize*2,slotSize*14,slotSize*(2+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalk_1",new SimpleIcon(L"netherStalk_1",slotSize*3,slotSize*14,slotSize*(3+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"netherStalk_2",new SimpleIcon(L"netherStalk_2",slotSize*4,slotSize*14,slotSize*(4+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_carved",new SimpleIcon(L"sandstone_carved",slotSize*5,slotSize*14,slotSize*(5+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"sandstone_smooth",new SimpleIcon(L"sandstone_smooth",slotSize*6,slotSize*14,slotSize*(6+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_top",new SimpleIcon(L"anvil_top",slotSize*7,slotSize*14,slotSize*(7+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"anvil_top_damaged_2",new SimpleIcon(L"anvil_top_damaged_2",slotSize*8,slotSize*14,slotSize*(8+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_chiseled",new SimpleIcon(L"quartzblock_chiseled",slotSize*9,slotSize*14,slotSize*(9+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_lines",new SimpleIcon(L"quartzblock_lines",slotSize*10,slotSize*14,slotSize*(10+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_side",new SimpleIcon(L"quartzblock_side",slotSize*11,slotSize*14,slotSize*(11+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper_inside",new SimpleIcon(L"hopper_inside",slotSize*12,slotSize*14,slotSize*(12+1),slotSize*(14+1)))); - texturesByName.insert(stringIconMap::value_type(L"lava",new SimpleIcon(L"lava",slotSize*13,slotSize*14,slotSize*(13+1),slotSize*(14+1)))); - texturesToAnimate.push_back(std::pair(L"lava",L"lava")); - texturesByName.insert(stringIconMap::value_type(L"lava_flow",new SimpleIcon(L"lava_flow",slotSize*14,slotSize*14,slotSize*(14+2),slotSize*(14+2)))); - texturesToAnimate.push_back(std::pair(L"lava_flow",L"lava_flow")); - texturesByName.insert(stringIconMap::value_type(L"destroy_0",new SimpleIcon(L"destroy_0",slotSize*0,slotSize*15,slotSize*(0+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_1",new SimpleIcon(L"destroy_1",slotSize*1,slotSize*15,slotSize*(1+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_2",new SimpleIcon(L"destroy_2",slotSize*2,slotSize*15,slotSize*(2+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_3",new SimpleIcon(L"destroy_3",slotSize*3,slotSize*15,slotSize*(3+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_4",new SimpleIcon(L"destroy_4",slotSize*4,slotSize*15,slotSize*(4+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_5",new SimpleIcon(L"destroy_5",slotSize*5,slotSize*15,slotSize*(5+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_6",new SimpleIcon(L"destroy_6",slotSize*6,slotSize*15,slotSize*(6+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_7",new SimpleIcon(L"destroy_7",slotSize*7,slotSize*15,slotSize*(7+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_8",new SimpleIcon(L"destroy_8",slotSize*8,slotSize*15,slotSize*(8+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"destroy_9",new SimpleIcon(L"destroy_9",slotSize*9,slotSize*15,slotSize*(9+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"quartzblock_bottom",new SimpleIcon(L"quartzblock_bottom",slotSize*11,slotSize*15,slotSize*(11+1),slotSize*(15+1)))); - texturesByName.insert(stringIconMap::value_type(L"hopper_top",new SimpleIcon(L"hopper_top",slotSize*12,slotSize*15,slotSize*(12+1),slotSize*(15+1)))); - } +int PreStitchedTextureMap::getIconType() { return iconType; } + +Icon* PreStitchedTextureMap::getMissingIcon() { return missingPosition; } + +void PreStitchedTextureMap::loadUVs() { + if (!texturesByName.empty()) { + // 4J Stu - We only need to populate this once at the moment as we have + // hardcoded positions for each texture If we ever load that + // dynamically, be aware that the Icon objects could currently be being + // used by the GameRenderer::runUpdate thread + return; + } + + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + delete it->second; + } + texturesByName.clear(); + texturesToAnimate.clear(); + + float slotSize = 1.0f / 16.0f; + if (iconType != Icon::TYPE_TERRAIN) { + texturesByName.insert(stringIconMap::value_type( + L"helmetCloth", + new SimpleIcon(L"helmetCloth", slotSize * 0, slotSize * 0, + slotSize * (0 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetChain", + new SimpleIcon(L"helmetChain", slotSize * 1, slotSize * 0, + slotSize * (1 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetIron", + new SimpleIcon(L"helmetIron", slotSize * 2, slotSize * 0, + slotSize * (2 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetDiamond", + new SimpleIcon(L"helmetDiamond", slotSize * 3, slotSize * 0, + slotSize * (3 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetGold", + new SimpleIcon(L"helmetGold", slotSize * 4, slotSize * 0, + slotSize * (4 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flintAndSteel", + new SimpleIcon(L"flintAndSteel", slotSize * 5, slotSize * 0, + slotSize * (5 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flint", new SimpleIcon(L"flint", slotSize * 6, slotSize * 0, + slotSize * (6 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"coal", new SimpleIcon(L"coal", slotSize * 7, slotSize * 0, + slotSize * (7 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"string", new SimpleIcon(L"string", slotSize * 8, slotSize * 0, + slotSize * (8 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"seeds", new SimpleIcon(L"seeds", slotSize * 9, slotSize * 0, + slotSize * (9 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"apple", new SimpleIcon(L"apple", slotSize * 10, slotSize * 0, + slotSize * (10 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"appleGold", + new SimpleIcon(L"appleGold", slotSize * 11, slotSize * 0, + slotSize * (11 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"egg", new SimpleIcon(L"egg", slotSize * 12, slotSize * 0, + slotSize * (12 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sugar", new SimpleIcon(L"sugar", slotSize * 13, slotSize * 0, + slotSize * (13 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"snowball", + new SimpleIcon(L"snowball", slotSize * 14, slotSize * 0, + slotSize * (14 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_helmet", + new SimpleIcon(L"slot_empty_helmet", slotSize * 15, slotSize * 0, + slotSize * (15 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateCloth", + new SimpleIcon(L"chestplateCloth", slotSize * 0, slotSize * 1, + slotSize * (0 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateChain", + new SimpleIcon(L"chestplateChain", slotSize * 1, slotSize * 1, + slotSize * (1 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateIron", + new SimpleIcon(L"chestplateIron", slotSize * 2, slotSize * 1, + slotSize * (2 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateDiamond", + new SimpleIcon(L"chestplateDiamond", slotSize * 3, slotSize * 1, + slotSize * (3 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateGold", + new SimpleIcon(L"chestplateGold", slotSize * 4, slotSize * 1, + slotSize * (4 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow", new SimpleIcon(L"bow", slotSize * 5, slotSize * 1, + slotSize * (5 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brick", new SimpleIcon(L"brick", slotSize * 6, slotSize * 1, + slotSize * (6 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ingotIron", + new SimpleIcon(L"ingotIron", slotSize * 7, slotSize * 1, + slotSize * (7 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"feather", + new SimpleIcon(L"feather", slotSize * 8, slotSize * 1, + slotSize * (8 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wheat", new SimpleIcon(L"wheat", slotSize * 9, slotSize * 1, + slotSize * (9 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"painting", + new SimpleIcon(L"painting", slotSize * 10, slotSize * 1, + slotSize * (10 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"reeds", new SimpleIcon(L"reeds", slotSize * 11, slotSize * 1, + slotSize * (11 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bone", new SimpleIcon(L"bone", slotSize * 12, slotSize * 1, + slotSize * (12 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake", new SimpleIcon(L"cake", slotSize * 13, slotSize * 1, + slotSize * (13 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slimeball", + new SimpleIcon(L"slimeball", slotSize * 14, slotSize * 1, + slotSize * (14 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_chestplate", + new SimpleIcon(L"slot_empty_chestplate", slotSize * 15, + slotSize * 1, slotSize * (15 + 1), + slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsCloth", + new SimpleIcon(L"leggingsCloth", slotSize * 0, slotSize * 2, + slotSize * (0 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsChain", + new SimpleIcon(L"leggingsChain", slotSize * 1, slotSize * 2, + slotSize * (1 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsIron", + new SimpleIcon(L"leggingsIron", slotSize * 2, slotSize * 2, + slotSize * (2 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsDiamond", + new SimpleIcon(L"leggingsDiamond", slotSize * 3, slotSize * 2, + slotSize * (3 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsGold", + new SimpleIcon(L"leggingsGold", slotSize * 4, slotSize * 2, + slotSize * (4 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"arrow", new SimpleIcon(L"arrow", slotSize * 5, slotSize * 2, + slotSize * (5 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quiver", new SimpleIcon(L"quiver", slotSize * 6, slotSize * 2, + slotSize * (6 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ingotGold", + new SimpleIcon(L"ingotGold", slotSize * 7, slotSize * 2, + slotSize * (7 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sulphur", + new SimpleIcon(L"sulphur", slotSize * 8, slotSize * 2, + slotSize * (8 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bread", new SimpleIcon(L"bread", slotSize * 9, slotSize * 2, + slotSize * (9 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sign", new SimpleIcon(L"sign", slotSize * 10, slotSize * 2, + slotSize * (10 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorWood", + new SimpleIcon(L"doorWood", slotSize * 11, slotSize * 2, + slotSize * (11 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorIron", + new SimpleIcon(L"doorIron", slotSize * 12, slotSize * 2, + slotSize * (12 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed", new SimpleIcon(L"bed", slotSize * 13, slotSize * 2, + slotSize * (13 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireball", + new SimpleIcon(L"fireball", slotSize * 14, slotSize * 2, + slotSize * (14 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_leggings", + new SimpleIcon(L"slot_empty_leggings", slotSize * 15, slotSize * 2, + slotSize * (15 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsCloth", + new SimpleIcon(L"bootsCloth", slotSize * 0, slotSize * 3, + slotSize * (0 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsChain", + new SimpleIcon(L"bootsChain", slotSize * 1, slotSize * 3, + slotSize * (1 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsIron", + new SimpleIcon(L"bootsIron", slotSize * 2, slotSize * 3, + slotSize * (2 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsDiamond", + new SimpleIcon(L"bootsDiamond", slotSize * 3, slotSize * 3, + slotSize * (3 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsGold", + new SimpleIcon(L"bootsGold", slotSize * 4, slotSize * 3, + slotSize * (4 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stick", new SimpleIcon(L"stick", slotSize * 5, slotSize * 3, + slotSize * (5 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compass", + new SimpleIcon(L"compass", slotSize * 6, slotSize * 3, + slotSize * (6 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP0", + new SimpleIcon(L"compassP0", slotSize * 7, slotSize * 14, + slotSize * (7 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP1", + new SimpleIcon(L"compassP1", slotSize * 8, slotSize * 14, + slotSize * (8 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP2", + new SimpleIcon(L"compassP2", slotSize * 9, slotSize * 14, + slotSize * (9 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"compassP3", + new SimpleIcon(L"compassP3", slotSize * 10, slotSize * 14, + slotSize * (10 + 1), slotSize * (14 + 1)))); + texturesToAnimate.push_back( + std::pair(L"compass", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP0", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP1", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP2", L"compass")); + texturesToAnimate.push_back( + std::pair(L"compassP3", L"compass")); + texturesByName.insert(stringIconMap::value_type( + L"diamond", + new SimpleIcon(L"diamond", slotSize * 7, slotSize * 3, + slotSize * (7 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstone", + new SimpleIcon(L"redstone", slotSize * 8, slotSize * 3, + slotSize * (8 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clay", new SimpleIcon(L"clay", slotSize * 9, slotSize * 3, + slotSize * (9 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"paper", new SimpleIcon(L"paper", slotSize * 10, slotSize * 3, + slotSize * (10 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"book", new SimpleIcon(L"book", slotSize * 11, slotSize * 3, + slotSize * (11 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"map", new SimpleIcon(L"map", slotSize * 12, slotSize * 3, + slotSize * (12 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"seeds_pumpkin", + new SimpleIcon(L"seeds_pumpkin", slotSize * 13, slotSize * 3, + slotSize * (13 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"seeds_melon", + new SimpleIcon(L"seeds_melon", slotSize * 14, slotSize * 3, + slotSize * (14 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"slot_empty_boots", + new SimpleIcon(L"slot_empty_boots", slotSize * 15, slotSize * 3, + slotSize * (15 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordWood", + new SimpleIcon(L"swordWood", slotSize * 0, slotSize * 4, + slotSize * (0 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordStone", + new SimpleIcon(L"swordStone", slotSize * 1, slotSize * 4, + slotSize * (1 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordIron", + new SimpleIcon(L"swordIron", slotSize * 2, slotSize * 4, + slotSize * (2 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordDiamond", + new SimpleIcon(L"swordDiamond", slotSize * 3, slotSize * 4, + slotSize * (3 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"swordGold", + new SimpleIcon(L"swordGold", slotSize * 4, slotSize * 4, + slotSize * (4 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishingRod", + new SimpleIcon(L"fishingRod", slotSize * 5, slotSize * 4, + slotSize * (5 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clock", new SimpleIcon(L"clock", slotSize * 6, slotSize * 4, + slotSize * (6 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP0", + new SimpleIcon(L"clockP0", slotSize * 11, slotSize * 14, + slotSize * (11 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP1", + new SimpleIcon(L"clockP1", slotSize * 12, slotSize * 14, + slotSize * (12 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP2", + new SimpleIcon(L"clockP2", slotSize * 13, slotSize * 14, + slotSize * (13 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clockP3", + new SimpleIcon(L"clockP3", slotSize * 14, slotSize * 14, + slotSize * (14 + 1), slotSize * (14 + 1)))); + texturesToAnimate.push_back( + std::pair(L"clock", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP0", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP1", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP2", L"clock")); + texturesToAnimate.push_back( + std::pair(L"clockP3", L"clock")); + texturesByName.insert(stringIconMap::value_type( + L"bowl", new SimpleIcon(L"bowl", slotSize * 7, slotSize * 4, + slotSize * (7 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroomStew", + new SimpleIcon(L"mushroomStew", slotSize * 8, slotSize * 4, + slotSize * (8 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"yellowDust", + new SimpleIcon(L"yellowDust", slotSize * 9, slotSize * 4, + slotSize * (9 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bucket", + new SimpleIcon(L"bucket", slotSize * 10, slotSize * 4, + slotSize * (10 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bucketWater", + new SimpleIcon(L"bucketWater", slotSize * 11, slotSize * 4, + slotSize * (11 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bucketLava", + new SimpleIcon(L"bucketLava", slotSize * 12, slotSize * 4, + slotSize * (12 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"milk", new SimpleIcon(L"milk", slotSize * 13, slotSize * 4, + slotSize * (13 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_black", + new SimpleIcon(L"dyePowder_black", slotSize * 14, slotSize * 4, + slotSize * (14 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_gray", + new SimpleIcon(L"dyePowder_gray", slotSize * 15, slotSize * 4, + slotSize * (15 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelWood", + new SimpleIcon(L"shovelWood", slotSize * 0, slotSize * 5, + slotSize * (0 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelStone", + new SimpleIcon(L"shovelStone", slotSize * 1, slotSize * 5, + slotSize * (1 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelIron", + new SimpleIcon(L"shovelIron", slotSize * 2, slotSize * 5, + slotSize * (2 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelDiamond", + new SimpleIcon(L"shovelDiamond", slotSize * 3, slotSize * 5, + slotSize * (3 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shovelGold", + new SimpleIcon(L"shovelGold", slotSize * 4, slotSize * 5, + slotSize * (4 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishingRod_empty", + new SimpleIcon(L"fishingRod_empty", slotSize * 5, slotSize * 5, + slotSize * (5 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"diode", new SimpleIcon(L"diode", slotSize * 6, slotSize * 5, + slotSize * (6 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"porkchopRaw", + new SimpleIcon(L"porkchopRaw", slotSize * 7, slotSize * 5, + slotSize * (7 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"porkchopCooked", + new SimpleIcon(L"porkchopCooked", slotSize * 8, slotSize * 5, + slotSize * (8 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishRaw", + new SimpleIcon(L"fishRaw", slotSize * 9, slotSize * 5, + slotSize * (9 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fishCooked", + new SimpleIcon(L"fishCooked", slotSize * 10, slotSize * 5, + slotSize * (10 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rottenFlesh", + new SimpleIcon(L"rottenFlesh", slotSize * 11, slotSize * 5, + slotSize * (11 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cookie", + new SimpleIcon(L"cookie", slotSize * 12, slotSize * 5, + slotSize * (12 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"shears", + new SimpleIcon(L"shears", slotSize * 13, slotSize * 5, + slotSize * (13 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_red", + new SimpleIcon(L"dyePowder_red", slotSize * 14, slotSize * 5, + slotSize * (14 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_pink", + new SimpleIcon(L"dyePowder_pink", slotSize * 15, slotSize * 5, + slotSize * (15 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeWood", + new SimpleIcon(L"pickaxeWood", slotSize * 0, slotSize * 6, + slotSize * (0 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeStone", + new SimpleIcon(L"pickaxeStone", slotSize * 1, slotSize * 6, + slotSize * (1 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeIron", + new SimpleIcon(L"pickaxeIron", slotSize * 2, slotSize * 6, + slotSize * (2 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeDiamond", + new SimpleIcon(L"pickaxeDiamond", slotSize * 3, slotSize * 6, + slotSize * (3 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pickaxeGold", + new SimpleIcon(L"pickaxeGold", slotSize * 4, slotSize * 6, + slotSize * (4 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow_pull_0", + new SimpleIcon(L"bow_pull_0", slotSize * 5, slotSize * 6, + slotSize * (5 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrotOnAStick", + new SimpleIcon(L"carrotOnAStick", slotSize * 6, slotSize * 6, + slotSize * (6 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leather", + new SimpleIcon(L"leather", slotSize * 7, slotSize * 6, + slotSize * (7 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"saddle", new SimpleIcon(L"saddle", slotSize * 8, slotSize * 6, + slotSize * (8 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"beefRaw", + new SimpleIcon(L"beefRaw", slotSize * 9, slotSize * 6, + slotSize * (9 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"beefCooked", + new SimpleIcon(L"beefCooked", slotSize * 10, slotSize * 6, + slotSize * (10 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enderPearl", + new SimpleIcon(L"enderPearl", slotSize * 11, slotSize * 6, + slotSize * (11 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blazeRod", + new SimpleIcon(L"blazeRod", slotSize * 12, slotSize * 6, + slotSize * (12 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"melon", new SimpleIcon(L"melon", slotSize * 13, slotSize * 6, + slotSize * (13 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_green", + new SimpleIcon(L"dyePowder_green", slotSize * 14, slotSize * 6, + slotSize * (14 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_lime", + new SimpleIcon(L"dyePowder_lime", slotSize * 15, slotSize * 6, + slotSize * (15 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetWood", + new SimpleIcon(L"hatchetWood", slotSize * 0, slotSize * 7, + slotSize * (0 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetStone", + new SimpleIcon(L"hatchetStone", slotSize * 1, slotSize * 7, + slotSize * (1 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetIron", + new SimpleIcon(L"hatchetIron", slotSize * 2, slotSize * 7, + slotSize * (2 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetDiamond", + new SimpleIcon(L"hatchetDiamond", slotSize * 3, slotSize * 7, + slotSize * (3 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hatchetGold", + new SimpleIcon(L"hatchetGold", slotSize * 4, slotSize * 7, + slotSize * (4 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow_pull_1", + new SimpleIcon(L"bow_pull_1", slotSize * 5, slotSize * 7, + slotSize * (5 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoBaked", + new SimpleIcon(L"potatoBaked", slotSize * 6, slotSize * 7, + slotSize * (6 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potato", new SimpleIcon(L"potato", slotSize * 7, slotSize * 7, + slotSize * (7 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots", + new SimpleIcon(L"carrots", slotSize * 8, slotSize * 7, + slotSize * (8 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chickenRaw", + new SimpleIcon(L"chickenRaw", slotSize * 9, slotSize * 7, + slotSize * (9 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chickenCooked", + new SimpleIcon(L"chickenCooked", slotSize * 10, slotSize * 7, + slotSize * (10 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ghastTear", + new SimpleIcon(L"ghastTear", slotSize * 11, slotSize * 7, + slotSize * (11 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"goldNugget", + new SimpleIcon(L"goldNugget", slotSize * 12, slotSize * 7, + slotSize * (12 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalkSeeds", + new SimpleIcon(L"netherStalkSeeds", slotSize * 13, slotSize * 7, + slotSize * (13 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_brown", + new SimpleIcon(L"dyePowder_brown", slotSize * 14, slotSize * 7, + slotSize * (14 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_yellow", + new SimpleIcon(L"dyePowder_yellow", slotSize * 15, slotSize * 7, + slotSize * (15 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeWood", + new SimpleIcon(L"hoeWood", slotSize * 0, slotSize * 8, + slotSize * (0 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeStone", + new SimpleIcon(L"hoeStone", slotSize * 1, slotSize * 8, + slotSize * (1 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeIron", + new SimpleIcon(L"hoeIron", slotSize * 2, slotSize * 8, + slotSize * (2 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeDiamond", + new SimpleIcon(L"hoeDiamond", slotSize * 3, slotSize * 8, + slotSize * (3 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hoeGold", + new SimpleIcon(L"hoeGold", slotSize * 4, slotSize * 8, + slotSize * (4 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bow_pull_2", + new SimpleIcon(L"bow_pull_2", slotSize * 5, slotSize * 8, + slotSize * (5 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoPoisonous", + new SimpleIcon(L"potatoPoisonous", slotSize * 6, slotSize * 8, + slotSize * (6 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecart", + new SimpleIcon(L"minecart", slotSize * 7, slotSize * 8, + slotSize * (7 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"boat", new SimpleIcon(L"boat", slotSize * 8, slotSize * 8, + slotSize * (8 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"speckledMelon", + new SimpleIcon(L"speckledMelon", slotSize * 9, slotSize * 8, + slotSize * (9 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fermentedSpiderEye", + new SimpleIcon(L"fermentedSpiderEye", slotSize * 10, slotSize * 8, + slotSize * (10 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"spiderEye", + new SimpleIcon(L"spiderEye", slotSize * 11, slotSize * 8, + slotSize * (11 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potion", + new SimpleIcon(L"potion", slotSize * 12, slotSize * 8, + slotSize * (12 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"glassBottle", + new SimpleIcon(L"glassBottle", slotSize * 12, slotSize * 8, + slotSize * (12 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potion_contents", + new SimpleIcon(L"potion_contents", slotSize * 13, slotSize * 8, + slotSize * (13 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_blue", + new SimpleIcon(L"dyePowder_blue", slotSize * 14, slotSize * 8, + slotSize * (14 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_lightBlue", + new SimpleIcon(L"dyePowder_lightBlue", slotSize * 15, slotSize * 8, + slotSize * (15 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"helmetCloth_overlay", + new SimpleIcon(L"helmetCloth_overlay", slotSize * 0, slotSize * 9, + slotSize * (0 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"comparator", + new SimpleIcon(L"comparator", slotSize * 5, slotSize * 9, + slotSize * (5 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrotGolden", + new SimpleIcon(L"carrotGolden", slotSize * 6, slotSize * 9, + slotSize * (6 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartChest", + new SimpleIcon(L"minecartChest", slotSize * 7, slotSize * 9, + slotSize * (7 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkinPie", + new SimpleIcon(L"pumpkinPie", slotSize * 8, slotSize * 9, + slotSize * (8 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"monsterPlacer", + new SimpleIcon(L"monsterPlacer", slotSize * 9, slotSize * 9, + slotSize * (9 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potion_splash", + new SimpleIcon(L"potion_splash", slotSize * 10, slotSize * 9, + slotSize * (10 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"eyeOfEnder", + new SimpleIcon(L"eyeOfEnder", slotSize * 11, slotSize * 9, + slotSize * (11 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron", + new SimpleIcon(L"cauldron", slotSize * 12, slotSize * 9, + slotSize * (12 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blazePowder", + new SimpleIcon(L"blazePowder", slotSize * 13, slotSize * 9, + slotSize * (13 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_purple", + new SimpleIcon(L"dyePowder_purple", slotSize * 14, slotSize * 9, + slotSize * (14 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_magenta", + new SimpleIcon(L"dyePowder_magenta", slotSize * 15, slotSize * 9, + slotSize * (15 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"chestplateCloth_overlay", + new SimpleIcon(L"chestplateCloth_overlay", slotSize * 0, + slotSize * 10, slotSize * (0 + 1), + slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherbrick", + new SimpleIcon(L"netherbrick", slotSize * 5, slotSize * 10, + slotSize * (5 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartFurnace", + new SimpleIcon(L"minecartFurnace", slotSize * 7, slotSize * 10, + slotSize * (7 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"monsterPlacer_overlay", + new SimpleIcon(L"monsterPlacer_overlay", slotSize * 9, + slotSize * 10, slotSize * (9 + 1), + slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ruby", new SimpleIcon(L"ruby", slotSize * 10, slotSize * 10, + slotSize * (10 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"expBottle", + new SimpleIcon(L"expBottle", slotSize * 11, slotSize * 10, + slotSize * (11 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brewingStand", + new SimpleIcon(L"brewingStand", slotSize * 12, slotSize * 10, + slotSize * (12 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"magmaCream", + new SimpleIcon(L"magmaCream", slotSize * 13, slotSize * 10, + slotSize * (13 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_cyan", + new SimpleIcon(L"dyePowder_cyan", slotSize * 14, slotSize * 10, + slotSize * (14 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_orange", + new SimpleIcon(L"dyePowder_orange", slotSize * 15, slotSize * 10, + slotSize * (15 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leggingsCloth_overlay", + new SimpleIcon(L"leggingsCloth_overlay", slotSize * 0, + slotSize * 11, slotSize * (0 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartHopper", + new SimpleIcon(L"minecartHopper", slotSize * 7, slotSize * 11, + slotSize * (7 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper", + new SimpleIcon(L"hopper", slotSize * 8, slotSize * 11, + slotSize * (8 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStar", + new SimpleIcon(L"netherStar", slotSize * 9, slotSize * 11, + slotSize * (9 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"emerald", + new SimpleIcon(L"emerald", slotSize * 10, slotSize * 11, + slotSize * (10 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"writingBook", + new SimpleIcon(L"writingBook", slotSize * 11, slotSize * 11, + slotSize * (11 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"writtenBook", + new SimpleIcon(L"writtenBook", slotSize * 12, slotSize * 11, + slotSize * (12 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flowerPot", + new SimpleIcon(L"flowerPot", slotSize * 13, slotSize * 11, + slotSize * (13 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_silver", + new SimpleIcon(L"dyePowder_silver", slotSize * 14, slotSize * 11, + slotSize * (14 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dyePowder_white", + new SimpleIcon(L"dyePowder_white", slotSize * 15, slotSize * 11, + slotSize * (15 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bootsCloth_overlay", + new SimpleIcon(L"bootsCloth_overlay", slotSize * 0, slotSize * 12, + slotSize * (0 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"minecartTnt", + new SimpleIcon(L"minecartTnt", slotSize * 7, slotSize * 12, + slotSize * (7 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireworks", + new SimpleIcon(L"fireworks", slotSize * 9, slotSize * 12, + slotSize * (9 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireworksCharge", + new SimpleIcon(L"fireworksCharge", slotSize * 10, slotSize * 12, + slotSize * (10 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fireworksCharge_overlay", + new SimpleIcon(L"fireworksCharge_overlay", slotSize * 11, + slotSize * 12, slotSize * (11 + 1), + slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherquartz", + new SimpleIcon(L"netherquartz", slotSize * 12, slotSize * 12, + slotSize * (12 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"emptyMap", + new SimpleIcon(L"emptyMap", slotSize * 13, slotSize * 12, + slotSize * (13 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"frame", + new SimpleIcon(L"frame", slotSize * 14, slotSize * 12, + slotSize * (14 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantedBook", + new SimpleIcon(L"enchantedBook", slotSize * 15, slotSize * 12, + slotSize * (15 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_skeleton", + new SimpleIcon(L"skull_skeleton", slotSize * 0, slotSize * 14, + slotSize * (0 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_wither", + new SimpleIcon(L"skull_wither", slotSize * 1, slotSize * 14, + slotSize * (1 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_zombie", + new SimpleIcon(L"skull_zombie", slotSize * 2, slotSize * 14, + slotSize * (2 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_char", + new SimpleIcon(L"skull_char", slotSize * 3, slotSize * 14, + slotSize * (3 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"skull_creeper", + new SimpleIcon(L"skull_creeper", slotSize * 4, slotSize * 14, + slotSize * (4 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dragonFireball", + new SimpleIcon(L"dragonFireball", slotSize * 15, slotSize * 14, + slotSize * (15 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_13", + new SimpleIcon(L"record_13", slotSize * 0, slotSize * 15, + slotSize * (0 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_cat", + new SimpleIcon(L"record_cat", slotSize * 1, slotSize * 15, + slotSize * (1 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_blocks", + new SimpleIcon(L"record_blocks", slotSize * 2, slotSize * 15, + slotSize * (2 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_chirp", + new SimpleIcon(L"record_chirp", slotSize * 3, slotSize * 15, + slotSize * (3 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_far", + new SimpleIcon(L"record_far", slotSize * 4, slotSize * 15, + slotSize * (4 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_mall", + new SimpleIcon(L"record_mall", slotSize * 5, slotSize * 15, + slotSize * (5 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_mellohi", + new SimpleIcon(L"record_mellohi", slotSize * 6, slotSize * 15, + slotSize * (6 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_stal", + new SimpleIcon(L"record_stal", slotSize * 7, slotSize * 15, + slotSize * (7 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_strad", + new SimpleIcon(L"record_strad", slotSize * 8, slotSize * 15, + slotSize * (8 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_ward", + new SimpleIcon(L"record_ward", slotSize * 9, slotSize * 15, + slotSize * (9 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_11", + new SimpleIcon(L"record_11", slotSize * 10, slotSize * 15, + slotSize * (10 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"record_where are we now", + new SimpleIcon(L"record_where are we now", slotSize * 11, + slotSize * 15, slotSize * (11 + 1), + slotSize * (15 + 1)))); + + // Special cases + ClockTexture* dataClock = new ClockTexture(); + Icon* oldClock = texturesByName[L"clock"]; + dataClock->initUVs(oldClock->getU0(), oldClock->getV0(), + oldClock->getU1(), oldClock->getV1()); + delete oldClock; + texturesByName[L"clock"] = dataClock; + + ClockTexture* clock = new ClockTexture(0, dataClock); + oldClock = texturesByName[L"clockP0"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP0"] = clock; + + clock = new ClockTexture(1, dataClock); + oldClock = texturesByName[L"clockP1"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP1"] = clock; + + clock = new ClockTexture(2, dataClock); + oldClock = texturesByName[L"clockP2"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP2"] = clock; + + clock = new ClockTexture(3, dataClock); + oldClock = texturesByName[L"clockP3"]; + clock->initUVs(oldClock->getU0(), oldClock->getV0(), oldClock->getU1(), + oldClock->getV1()); + delete oldClock; + texturesByName[L"clockP3"] = clock; + + CompassTexture* dataCompass = new CompassTexture(); + Icon* oldCompass = texturesByName[L"compass"]; + dataCompass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compass"] = dataCompass; + + CompassTexture* compass = new CompassTexture(0, dataCompass); + oldCompass = texturesByName[L"compassP0"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP0"] = compass; + + compass = new CompassTexture(1, dataCompass); + oldCompass = texturesByName[L"compassP1"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP1"] = compass; + + compass = new CompassTexture(2, dataCompass); + oldCompass = texturesByName[L"compassP2"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP2"] = compass; + + compass = new CompassTexture(3, dataCompass); + oldCompass = texturesByName[L"compassP3"]; + compass->initUVs(oldCompass->getU0(), oldCompass->getV0(), + oldCompass->getU1(), oldCompass->getV1()); + delete oldCompass; + texturesByName[L"compassP3"] = compass; + } else { + texturesByName.insert(stringIconMap::value_type( + L"grass_top", + new SimpleIcon(L"grass_top", slotSize * 0, slotSize * 0, + slotSize * (0 + 1), slotSize * (0 + 1)))); + texturesByName[L"grass_top"]->setFlags( + Icon::IS_GRASS_TOP); // 4J added for faster determination of + // texture type in tesselation + texturesByName.insert(stringIconMap::value_type( + L"stone", new SimpleIcon(L"stone", slotSize * 1, slotSize * 0, + slotSize * (1 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dirt", new SimpleIcon(L"dirt", slotSize * 2, slotSize * 0, + slotSize * (2 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"grass_side", + new SimpleIcon(L"grass_side", slotSize * 3, slotSize * 0, + slotSize * (3 + 1), slotSize * (0 + 1)))); + texturesByName[L"grass_side"]->setFlags( + Icon::IS_GRASS_SIDE); // 4J added for faster determination of + // texture type in tesselation + texturesByName.insert(stringIconMap::value_type( + L"wood", new SimpleIcon(L"wood", slotSize * 4, slotSize * 0, + slotSize * (4 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stoneslab_side", + new SimpleIcon(L"stoneslab_side", slotSize * 5, slotSize * 0, + slotSize * (5 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stoneslab_top", + new SimpleIcon(L"stoneslab_top", slotSize * 6, slotSize * 0, + slotSize * (6 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brick", new SimpleIcon(L"brick", slotSize * 7, slotSize * 0, + slotSize * (7 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tnt_side", + new SimpleIcon(L"tnt_side", slotSize * 8, slotSize * 0, + slotSize * (8 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tnt_top", + new SimpleIcon(L"tnt_top", slotSize * 9, slotSize * 0, + slotSize * (9 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tnt_bottom", + new SimpleIcon(L"tnt_bottom", slotSize * 10, slotSize * 0, + slotSize * (10 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"web", new SimpleIcon(L"web", slotSize * 11, slotSize * 0, + slotSize * (11 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rose", new SimpleIcon(L"rose", slotSize * 12, slotSize * 0, + slotSize * (12 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flower", + new SimpleIcon(L"flower", slotSize * 13, slotSize * 0, + slotSize * (13 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"portal", + new SimpleIcon(L"portal", slotSize * 14, slotSize * 0, + slotSize * (14 + 1), slotSize * (0 + 1)))); + texturesToAnimate.push_back( + std::pair(L"portal", L"portal")); + texturesByName.insert(stringIconMap::value_type( + L"sapling", + new SimpleIcon(L"sapling", slotSize * 15, slotSize * 0, + slotSize * (15 + 1), slotSize * (0 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebrick", + new SimpleIcon(L"stonebrick", slotSize * 0, slotSize * 1, + slotSize * (0 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bedrock", + new SimpleIcon(L"bedrock", slotSize * 1, slotSize * 1, + slotSize * (1 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sand", new SimpleIcon(L"sand", slotSize * 2, slotSize * 1, + slotSize * (2 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"gravel", new SimpleIcon(L"gravel", slotSize * 3, slotSize * 1, + slotSize * (3 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_side", + new SimpleIcon(L"tree_side", slotSize * 4, slotSize * 1, + slotSize * (4 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_top", + new SimpleIcon(L"tree_top", slotSize * 5, slotSize * 1, + slotSize * (5 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockIron", + new SimpleIcon(L"blockIron", slotSize * 6, slotSize * 1, + slotSize * (6 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockGold", + new SimpleIcon(L"blockGold", slotSize * 7, slotSize * 1, + slotSize * (7 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockDiamond", + new SimpleIcon(L"blockDiamond", slotSize * 8, slotSize * 1, + slotSize * (8 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockEmerald", + new SimpleIcon(L"blockEmerald", slotSize * 9, slotSize * 1, + slotSize * (9 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockRedstone", + new SimpleIcon(L"blockRedstone", slotSize * 10, slotSize * 1, + slotSize * (10 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dropper_front", + new SimpleIcon(L"dropper_front", slotSize * 11, slotSize * 1, + slotSize * (11 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_red", + new SimpleIcon(L"mushroom_red", slotSize * 12, slotSize * 1, + slotSize * (12 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_brown", + new SimpleIcon(L"mushroom_brown", slotSize * 13, slotSize * 1, + slotSize * (13 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sapling_jungle", + new SimpleIcon(L"sapling_jungle", slotSize * 14, slotSize * 1, + slotSize * (14 + 1), slotSize * (1 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fire_0", + new SimpleIcon(L"fire_0", slotSize * 15, slotSize * 1, + slotSize * (15 + 1), slotSize * (1 + 1)))); + texturesToAnimate.push_back( + std::pair(L"fire_0", L"fire_0")); + texturesByName.insert(stringIconMap::value_type( + L"oreGold", + new SimpleIcon(L"oreGold", slotSize * 0, slotSize * 2, + slotSize * (0 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreIron", + new SimpleIcon(L"oreIron", slotSize * 1, slotSize * 2, + slotSize * (1 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreCoal", + new SimpleIcon(L"oreCoal", slotSize * 2, slotSize * 2, + slotSize * (2 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bookshelf", + new SimpleIcon(L"bookshelf", slotSize * 3, slotSize * 2, + slotSize * (3 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stoneMoss", + new SimpleIcon(L"stoneMoss", slotSize * 4, slotSize * 2, + slotSize * (4 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"obsidian", + new SimpleIcon(L"obsidian", slotSize * 5, slotSize * 2, + slotSize * (5 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"grass_side_overlay", + new SimpleIcon(L"grass_side_overlay", slotSize * 6, slotSize * 2, + slotSize * (6 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tallgrass", + new SimpleIcon(L"tallgrass", slotSize * 7, slotSize * 2, + slotSize * (7 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dispenser_front_vertical", + new SimpleIcon(L"dispenser_front_vertical", slotSize * 8, + slotSize * 2, slotSize * (8 + 1), + slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"beacon", new SimpleIcon(L"beacon", slotSize * 9, slotSize * 2, + slotSize * (9 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dropper_front_vertical", + new SimpleIcon(L"dropper_front_vertical", slotSize * 10, + slotSize * 2, slotSize * (10 + 1), + slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"workbench_top", + new SimpleIcon(L"workbench_top", slotSize * 11, slotSize * 2, + slotSize * (11 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_front", + new SimpleIcon(L"furnace_front", slotSize * 12, slotSize * 2, + slotSize * (12 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_side", + new SimpleIcon(L"furnace_side", slotSize * 13, slotSize * 2, + slotSize * (13 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dispenser_front", + new SimpleIcon(L"dispenser_front", slotSize * 14, slotSize * 2, + slotSize * (14 + 1), slotSize * (2 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fire_1", + new SimpleIcon(L"fire_1", slotSize * 15, slotSize * 1, + slotSize * (15 + 1), slotSize * (1 + 1)))); + texturesToAnimate.push_back( + std::pair(L"fire_1", L"fire_1")); + texturesByName.insert(stringIconMap::value_type( + L"sponge", new SimpleIcon(L"sponge", slotSize * 0, slotSize * 3, + slotSize * (0 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"glass", new SimpleIcon(L"glass", slotSize * 1, slotSize * 3, + slotSize * (1 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreDiamond", + new SimpleIcon(L"oreDiamond", slotSize * 2, slotSize * 3, + slotSize * (2 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreRedstone", + new SimpleIcon(L"oreRedstone", slotSize * 3, slotSize * 3, + slotSize * (3 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves", new SimpleIcon(L"leaves", slotSize * 4, slotSize * 3, + slotSize * (4 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_opaque", + new SimpleIcon(L"leaves_opaque", slotSize * 5, slotSize * 3, + slotSize * (5 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth", + new SimpleIcon(L"stonebricksmooth", slotSize * 6, slotSize * 3, + slotSize * (6 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"deadbush", + new SimpleIcon(L"deadbush", slotSize * 7, slotSize * 3, + slotSize * (7 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fern", new SimpleIcon(L"fern", slotSize * 8, slotSize * 3, + slotSize * (8 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"daylightDetector_top", + new SimpleIcon(L"daylightDetector_top", slotSize * 9, slotSize * 3, + slotSize * (9 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"daylightDetector_side", + new SimpleIcon(L"daylightDetector_side", slotSize * 10, + slotSize * 3, slotSize * (10 + 1), + slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"workbench_side", + new SimpleIcon(L"workbench_side", slotSize * 11, slotSize * 3, + slotSize * (11 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"workbench_front", + new SimpleIcon(L"workbench_front", slotSize * 12, slotSize * 3, + slotSize * (12 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_front_lit", + new SimpleIcon(L"furnace_front_lit", slotSize * 13, slotSize * 3, + slotSize * (13 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"furnace_top", + new SimpleIcon(L"furnace_top", slotSize * 14, slotSize * 3, + slotSize * (14 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sapling_spruce", + new SimpleIcon(L"sapling_spruce", slotSize * 15, slotSize * 3, + slotSize * (15 + 1), slotSize * (3 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_0", + new SimpleIcon(L"cloth_0", slotSize * 0, slotSize * 4, + slotSize * (0 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mobSpawner", + new SimpleIcon(L"mobSpawner", slotSize * 1, slotSize * 4, + slotSize * (1 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"snow", new SimpleIcon(L"snow", slotSize * 2, slotSize * 4, + slotSize * (2 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ice", new SimpleIcon(L"ice", slotSize * 3, slotSize * 4, + slotSize * (3 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"snow_side", + new SimpleIcon(L"snow_side", slotSize * 4, slotSize * 4, + slotSize * (4 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cactus_top", + new SimpleIcon(L"cactus_top", slotSize * 5, slotSize * 4, + slotSize * (5 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cactus_side", + new SimpleIcon(L"cactus_side", slotSize * 6, slotSize * 4, + slotSize * (6 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cactus_bottom", + new SimpleIcon(L"cactus_bottom", slotSize * 7, slotSize * 4, + slotSize * (7 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"clay", new SimpleIcon(L"clay", slotSize * 8, slotSize * 4, + slotSize * (8 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"reeds", new SimpleIcon(L"reeds", slotSize * 9, slotSize * 4, + slotSize * (9 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"musicBlock", + new SimpleIcon(L"musicBlock", slotSize * 10, slotSize * 4, + slotSize * (10 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"jukebox_top", + new SimpleIcon(L"jukebox_top", slotSize * 11, slotSize * 4, + slotSize * (11 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"waterlily", + new SimpleIcon(L"waterlily", slotSize * 12, slotSize * 4, + slotSize * (12 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mycel_side", + new SimpleIcon(L"mycel_side", slotSize * 13, slotSize * 4, + slotSize * (13 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mycel_top", + new SimpleIcon(L"mycel_top", slotSize * 14, slotSize * 4, + slotSize * (14 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sapling_birch", + new SimpleIcon(L"sapling_birch", slotSize * 15, slotSize * 4, + slotSize * (15 + 1), slotSize * (4 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"torch", new SimpleIcon(L"torch", slotSize * 0, slotSize * 5, + slotSize * (0 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorWood_upper", + new SimpleIcon(L"doorWood_upper", slotSize * 1, slotSize * 5, + slotSize * (1 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorIron_upper", + new SimpleIcon(L"doorIron_upper", slotSize * 2, slotSize * 5, + slotSize * (2 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"ladder", new SimpleIcon(L"ladder", slotSize * 3, slotSize * 5, + slotSize * (3 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"trapdoor", + new SimpleIcon(L"trapdoor", slotSize * 4, slotSize * 5, + slotSize * (4 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"fenceIron", + new SimpleIcon(L"fenceIron", slotSize * 5, slotSize * 5, + slotSize * (5 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"farmland_wet", + new SimpleIcon(L"farmland_wet", slotSize * 6, slotSize * 5, + slotSize * (6 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"farmland_dry", + new SimpleIcon(L"farmland_dry", slotSize * 7, slotSize * 5, + slotSize * (7 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_0", + new SimpleIcon(L"crops_0", slotSize * 8, slotSize * 5, + slotSize * (8 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_1", + new SimpleIcon(L"crops_1", slotSize * 9, slotSize * 5, + slotSize * (9 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_2", + new SimpleIcon(L"crops_2", slotSize * 10, slotSize * 5, + slotSize * (10 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_3", + new SimpleIcon(L"crops_3", slotSize * 11, slotSize * 5, + slotSize * (11 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_4", + new SimpleIcon(L"crops_4", slotSize * 12, slotSize * 5, + slotSize * (12 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_5", + new SimpleIcon(L"crops_5", slotSize * 13, slotSize * 5, + slotSize * (13 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_6", + new SimpleIcon(L"crops_6", slotSize * 14, slotSize * 5, + slotSize * (14 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"crops_7", + new SimpleIcon(L"crops_7", slotSize * 15, slotSize * 5, + slotSize * (15 + 1), slotSize * (5 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"lever", new SimpleIcon(L"lever", slotSize * 0, slotSize * 6, + slotSize * (0 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorWood_lower", + new SimpleIcon(L"doorWood_lower", slotSize * 1, slotSize * 6, + slotSize * (1 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"doorIron_lower", + new SimpleIcon(L"doorIron_lower", slotSize * 2, slotSize * 6, + slotSize * (2 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redtorch_lit", + new SimpleIcon(L"redtorch_lit", slotSize * 3, slotSize * 6, + slotSize * (3 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth_mossy", + new SimpleIcon(L"stonebricksmooth_mossy", slotSize * 4, + slotSize * 6, slotSize * (4 + 1), + slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth_cracked", + new SimpleIcon(L"stonebricksmooth_cracked", slotSize * 5, + slotSize * 6, slotSize * (5 + 1), + slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_top", + new SimpleIcon(L"pumpkin_top", slotSize * 6, slotSize * 6, + slotSize * (6 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hellrock", + new SimpleIcon(L"hellrock", slotSize * 7, slotSize * 6, + slotSize * (7 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hellsand", + new SimpleIcon(L"hellsand", slotSize * 8, slotSize * 6, + slotSize * (8 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"lightgem", + new SimpleIcon(L"lightgem", slotSize * 9, slotSize * 6, + slotSize * (9 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_top_sticky", + new SimpleIcon(L"piston_top_sticky", slotSize * 10, slotSize * 6, + slotSize * (10 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_top", + new SimpleIcon(L"piston_top", slotSize * 11, slotSize * 6, + slotSize * (11 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_side", + new SimpleIcon(L"piston_side", slotSize * 12, slotSize * 6, + slotSize * (12 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_bottom", + new SimpleIcon(L"piston_bottom", slotSize * 13, slotSize * 6, + slotSize * (13 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"piston_inner_top", + new SimpleIcon(L"piston_inner_top", slotSize * 14, slotSize * 6, + slotSize * (14 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stem_straight", + new SimpleIcon(L"stem_straight", slotSize * 15, slotSize * 6, + slotSize * (15 + 1), slotSize * (6 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rail_turn", + new SimpleIcon(L"rail_turn", slotSize * 0, slotSize * 7, + slotSize * (0 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_15", + new SimpleIcon(L"cloth_15", slotSize * 1, slotSize * 7, + slotSize * (1 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_7", + new SimpleIcon(L"cloth_7", slotSize * 2, slotSize * 7, + slotSize * (2 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redtorch", + new SimpleIcon(L"redtorch", slotSize * 3, slotSize * 7, + slotSize * (3 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_spruce", + new SimpleIcon(L"tree_spruce", slotSize * 4, slotSize * 7, + slotSize * (4 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_birch", + new SimpleIcon(L"tree_birch", slotSize * 5, slotSize * 7, + slotSize * (5 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_side", + new SimpleIcon(L"pumpkin_side", slotSize * 6, slotSize * 7, + slotSize * (6 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_face", + new SimpleIcon(L"pumpkin_face", slotSize * 7, slotSize * 7, + slotSize * (7 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"pumpkin_jack", + new SimpleIcon(L"pumpkin_jack", slotSize * 8, slotSize * 7, + slotSize * (8 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_top", + new SimpleIcon(L"cake_top", slotSize * 9, slotSize * 7, + slotSize * (9 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_side", + new SimpleIcon(L"cake_side", slotSize * 10, slotSize * 7, + slotSize * (10 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_inner", + new SimpleIcon(L"cake_inner", slotSize * 11, slotSize * 7, + slotSize * (11 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cake_bottom", + new SimpleIcon(L"cake_bottom", slotSize * 12, slotSize * 7, + slotSize * (12 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_skin_red", + new SimpleIcon(L"mushroom_skin_red", slotSize * 13, slotSize * 7, + slotSize * (13 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_skin_brown", + new SimpleIcon(L"mushroom_skin_brown", slotSize * 14, slotSize * 7, + slotSize * (14 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stem_bent", + new SimpleIcon(L"stem_bent", slotSize * 15, slotSize * 7, + slotSize * (15 + 1), slotSize * (7 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"rail", new SimpleIcon(L"rail", slotSize * 0, slotSize * 8, + slotSize * (0 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_14", + new SimpleIcon(L"cloth_14", slotSize * 1, slotSize * 8, + slotSize * (1 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_6", + new SimpleIcon(L"cloth_6", slotSize * 2, slotSize * 8, + slotSize * (2 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"repeater", + new SimpleIcon(L"repeater", slotSize * 3, slotSize * 8, + slotSize * (3 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_spruce", + new SimpleIcon(L"leaves_spruce", slotSize * 4, slotSize * 8, + slotSize * (4 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_spruce_opaque", + new SimpleIcon(L"leaves_spruce_opaque", slotSize * 5, slotSize * 8, + slotSize * (5 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_feet_top", + new SimpleIcon(L"bed_feet_top", slotSize * 6, slotSize * 8, + slotSize * (6 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_head_top", + new SimpleIcon(L"bed_head_top", slotSize * 7, slotSize * 8, + slotSize * (7 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"melon_side", + new SimpleIcon(L"melon_side", slotSize * 8, slotSize * 8, + slotSize * (8 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"melon_top", + new SimpleIcon(L"melon_top", slotSize * 9, slotSize * 8, + slotSize * (9 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_top", + new SimpleIcon(L"cauldron_top", slotSize * 10, slotSize * 8, + slotSize * (10 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_inner", + new SimpleIcon(L"cauldron_inner", slotSize * 11, slotSize * 8, + slotSize * (11 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_skin_stem", + new SimpleIcon(L"mushroom_skin_stem", slotSize * 13, slotSize * 8, + slotSize * (13 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"mushroom_inside", + new SimpleIcon(L"mushroom_inside", slotSize * 14, slotSize * 8, + slotSize * (14 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"vine", new SimpleIcon(L"vine", slotSize * 15, slotSize * 8, + slotSize * (15 + 1), slotSize * (8 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"blockLapis", + new SimpleIcon(L"blockLapis", slotSize * 0, slotSize * 9, + slotSize * (0 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_13", + new SimpleIcon(L"cloth_13", slotSize * 1, slotSize * 9, + slotSize * (1 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_5", + new SimpleIcon(L"cloth_5", slotSize * 2, slotSize * 9, + slotSize * (2 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"repeater_lit", + new SimpleIcon(L"repeater_lit", slotSize * 3, slotSize * 9, + slotSize * (3 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"thinglass_top", + new SimpleIcon(L"thinglass_top", slotSize * 4, slotSize * 9, + slotSize * (4 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_feet_end", + new SimpleIcon(L"bed_feet_end", slotSize * 5, slotSize * 9, + slotSize * (5 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_feet_side", + new SimpleIcon(L"bed_feet_side", slotSize * 6, slotSize * 9, + slotSize * (6 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_head_side", + new SimpleIcon(L"bed_head_side", slotSize * 7, slotSize * 9, + slotSize * (7 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"bed_head_end", + new SimpleIcon(L"bed_head_end", slotSize * 8, slotSize * 9, + slotSize * (8 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tree_jungle", + new SimpleIcon(L"tree_jungle", slotSize * 9, slotSize * 9, + slotSize * (9 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_side", + new SimpleIcon(L"cauldron_side", slotSize * 10, slotSize * 9, + slotSize * (10 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cauldron_bottom", + new SimpleIcon(L"cauldron_bottom", slotSize * 11, slotSize * 9, + slotSize * (11 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brewingStand_base", + new SimpleIcon(L"brewingStand_base", slotSize * 12, slotSize * 9, + slotSize * (12 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"brewingStand", + new SimpleIcon(L"brewingStand", slotSize * 13, slotSize * 9, + slotSize * (13 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"endframe_top", + new SimpleIcon(L"endframe_top", slotSize * 14, slotSize * 9, + slotSize * (14 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"endframe_side", + new SimpleIcon(L"endframe_side", slotSize * 15, slotSize * 9, + slotSize * (15 + 1), slotSize * (9 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreLapis", + new SimpleIcon(L"oreLapis", slotSize * 0, slotSize * 10, + slotSize * (0 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_12", + new SimpleIcon(L"cloth_12", slotSize * 1, slotSize * 10, + slotSize * (1 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_4", + new SimpleIcon(L"cloth_4", slotSize * 2, slotSize * 10, + slotSize * (2 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"goldenRail", + new SimpleIcon(L"goldenRail", slotSize * 3, slotSize * 10, + slotSize * (3 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_cross", + new SimpleIcon(L"redstoneDust_cross", slotSize * 4, slotSize * 10, + slotSize * (4 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_line", + new SimpleIcon(L"redstoneDust_line", slotSize * 5, slotSize * 10, + slotSize * (5 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantment_top", + new SimpleIcon(L"enchantment_top", slotSize * 6, slotSize * 10, + slotSize * (6 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"dragonEgg", + new SimpleIcon(L"dragonEgg", slotSize * 7, slotSize * 10, + slotSize * (7 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cocoa_2", + new SimpleIcon(L"cocoa_2", slotSize * 8, slotSize * 10, + slotSize * (8 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cocoa_1", + new SimpleIcon(L"cocoa_1", slotSize * 9, slotSize * 10, + slotSize * (9 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cocoa_0", + new SimpleIcon(L"cocoa_0", slotSize * 10, slotSize * 10, + slotSize * (10 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"oreEmerald", + new SimpleIcon(L"oreEmerald", slotSize * 11, slotSize * 10, + slotSize * (11 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tripWireSource", + new SimpleIcon(L"tripWireSource", slotSize * 12, slotSize * 10, + slotSize * (12 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"tripWire", + new SimpleIcon(L"tripWire", slotSize * 13, slotSize * 10, + slotSize * (13 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"endframe_eye", + new SimpleIcon(L"endframe_eye", slotSize * 14, slotSize * 10, + slotSize * (14 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"whiteStone", + new SimpleIcon(L"whiteStone", slotSize * 15, slotSize * 10, + slotSize * (15 + 1), slotSize * (10 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_top", + new SimpleIcon(L"sandstone_top", slotSize * 0, slotSize * 11, + slotSize * (0 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_11", + new SimpleIcon(L"cloth_11", slotSize * 1, slotSize * 11, + slotSize * (1 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_3", + new SimpleIcon(L"cloth_3", slotSize * 2, slotSize * 11, + slotSize * (2 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"goldenRail_powered", + new SimpleIcon(L"goldenRail_powered", slotSize * 3, slotSize * 11, + slotSize * (3 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_cross_overlay", + new SimpleIcon(L"redstoneDust_cross_overlay", slotSize * 4, + slotSize * 11, slotSize * (4 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneDust_line_overlay", + new SimpleIcon(L"redstoneDust_line_overlay", slotSize * 5, + slotSize * 11, slotSize * (5 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantment_side", + new SimpleIcon(L"enchantment_side", slotSize * 6, slotSize * 11, + slotSize * (6 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"enchantment_bottom", + new SimpleIcon(L"enchantment_bottom", slotSize * 7, slotSize * 11, + slotSize * (7 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"commandBlock", + new SimpleIcon(L"commandBlock", slotSize * 8, slotSize * 11, + slotSize * (8 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"itemframe_back", + new SimpleIcon(L"itemframe_back", slotSize * 9, slotSize * 11, + slotSize * (9 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"flowerPot", + new SimpleIcon(L"flowerPot", slotSize * 10, slotSize * 11, + slotSize * (10 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"comparator", + new SimpleIcon(L"comparator", slotSize * 11, slotSize * 11, + slotSize * (11 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"comparator_lit", + new SimpleIcon(L"comparator_lit", slotSize * 12, slotSize * 11, + slotSize * (12 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"activatorRail", + new SimpleIcon(L"activatorRail", slotSize * 13, slotSize * 11, + slotSize * (13 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"activatorRail_powered", + new SimpleIcon(L"activatorRail_powered", slotSize * 14, + slotSize * 11, slotSize * (14 + 1), + slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherquartz", + new SimpleIcon(L"netherquartz", slotSize * 15, slotSize * 11, + slotSize * (15 + 1), slotSize * (11 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_side", + new SimpleIcon(L"sandstone_side", slotSize * 0, slotSize * 12, + slotSize * (0 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_10", + new SimpleIcon(L"cloth_10", slotSize * 1, slotSize * 12, + slotSize * (1 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_2", + new SimpleIcon(L"cloth_2", slotSize * 2, slotSize * 12, + slotSize * (2 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"detectorRail", + new SimpleIcon(L"detectorRail", slotSize * 3, slotSize * 12, + slotSize * (3 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_jungle", + new SimpleIcon(L"leaves_jungle", slotSize * 4, slotSize * 12, + slotSize * (4 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"leaves_jungle_opaque", + new SimpleIcon(L"leaves_jungle_opaque", slotSize * 5, slotSize * 12, + slotSize * (5 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wood_spruce", + new SimpleIcon(L"wood_spruce", slotSize * 6, slotSize * 12, + slotSize * (6 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wood_jungle", + new SimpleIcon(L"wood_jungle", slotSize * 7, slotSize * 12, + slotSize * (7 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_0", + new SimpleIcon(L"carrots_0", slotSize * 8, slotSize * 12, + slotSize * (8 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_1", + new SimpleIcon(L"carrots_1", slotSize * 9, slotSize * 12, + slotSize * (9 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_2", + new SimpleIcon(L"carrots_2", slotSize * 10, slotSize * 12, + slotSize * (10 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"carrots_3", + new SimpleIcon(L"carrots_3", slotSize * 11, slotSize * 12, + slotSize * (11 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_0", + new SimpleIcon(L"potatoes_0", slotSize * 8, slotSize * 12, + slotSize * (8 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_1", + new SimpleIcon(L"potatoes_1", slotSize * 9, slotSize * 12, + slotSize * (9 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_2", + new SimpleIcon(L"potatoes_2", slotSize * 10, slotSize * 12, + slotSize * (10 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"potatoes_3", + new SimpleIcon(L"potatoes_3", slotSize * 12, slotSize * 12, + slotSize * (12 + 1), slotSize * (12 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"water", + new SimpleIcon(L"water", slotSize * 13, slotSize * 12, + slotSize * (13 + 1), slotSize * (12 + 1)))); + texturesToAnimate.push_back( + std::pair(L"water", L"water")); + texturesByName.insert(stringIconMap::value_type( + L"water_flow", + new SimpleIcon(L"water_flow", slotSize * 14, slotSize * 12, + slotSize * (14 + 2), slotSize * (12 + 2)))); + texturesToAnimate.push_back(std::pair( + L"water_flow", L"water_flow")); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_bottom", + new SimpleIcon(L"sandstone_bottom", slotSize * 0, slotSize * 13, + slotSize * (0 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_9", + new SimpleIcon(L"cloth_9", slotSize * 1, slotSize * 13, + slotSize * (1 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_1", + new SimpleIcon(L"cloth_1", slotSize * 2, slotSize * 13, + slotSize * (2 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneLight", + new SimpleIcon(L"redstoneLight", slotSize * 3, slotSize * 13, + slotSize * (3 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"redstoneLight_lit", + new SimpleIcon(L"redstoneLight_lit", slotSize * 4, slotSize * 13, + slotSize * (4 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"stonebricksmooth_carved", + new SimpleIcon(L"stonebricksmooth_carved", slotSize * 5, + slotSize * 13, slotSize * (5 + 1), + slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"wood_birch", + new SimpleIcon(L"wood_birch", slotSize * 6, slotSize * 13, + slotSize * (6 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_base", + new SimpleIcon(L"anvil_base", slotSize * 7, slotSize * 13, + slotSize * (7 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_top_damaged_1", + new SimpleIcon(L"anvil_top_damaged_1", slotSize * 8, slotSize * 13, + slotSize * (8 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_chiseled_top", + new SimpleIcon(L"quartzblock_chiseled_top", slotSize * 9, + slotSize * 13, slotSize * (9 + 1), + slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_lines_top", + new SimpleIcon(L"quartzblock_lines_top", slotSize * 10, + slotSize * 13, slotSize * (10 + 1), + slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_top", + new SimpleIcon(L"quartzblock_top", slotSize * 11, slotSize * 13, + slotSize * (11 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper", + new SimpleIcon(L"hopper", slotSize * 12, slotSize * 13, + slotSize * (12 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"detectorRail_on", + new SimpleIcon(L"detectorRail_on", slotSize * 13, slotSize * 13, + slotSize * (13 + 1), slotSize * (13 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherBrick", + new SimpleIcon(L"netherBrick", slotSize * 0, slotSize * 14, + slotSize * (0 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"cloth_8", + new SimpleIcon(L"cloth_8", slotSize * 1, slotSize * 14, + slotSize * (1 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalk_0", + new SimpleIcon(L"netherStalk_0", slotSize * 2, slotSize * 14, + slotSize * (2 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalk_1", + new SimpleIcon(L"netherStalk_1", slotSize * 3, slotSize * 14, + slotSize * (3 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"netherStalk_2", + new SimpleIcon(L"netherStalk_2", slotSize * 4, slotSize * 14, + slotSize * (4 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_carved", + new SimpleIcon(L"sandstone_carved", slotSize * 5, slotSize * 14, + slotSize * (5 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"sandstone_smooth", + new SimpleIcon(L"sandstone_smooth", slotSize * 6, slotSize * 14, + slotSize * (6 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_top", + new SimpleIcon(L"anvil_top", slotSize * 7, slotSize * 14, + slotSize * (7 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"anvil_top_damaged_2", + new SimpleIcon(L"anvil_top_damaged_2", slotSize * 8, slotSize * 14, + slotSize * (8 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_chiseled", + new SimpleIcon(L"quartzblock_chiseled", slotSize * 9, slotSize * 14, + slotSize * (9 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_lines", + new SimpleIcon(L"quartzblock_lines", slotSize * 10, slotSize * 14, + slotSize * (10 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_side", + new SimpleIcon(L"quartzblock_side", slotSize * 11, slotSize * 14, + slotSize * (11 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper_inside", + new SimpleIcon(L"hopper_inside", slotSize * 12, slotSize * 14, + slotSize * (12 + 1), slotSize * (14 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"lava", new SimpleIcon(L"lava", slotSize * 13, slotSize * 14, + slotSize * (13 + 1), slotSize * (14 + 1)))); + texturesToAnimate.push_back( + std::pair(L"lava", L"lava")); + texturesByName.insert(stringIconMap::value_type( + L"lava_flow", + new SimpleIcon(L"lava_flow", slotSize * 14, slotSize * 14, + slotSize * (14 + 2), slotSize * (14 + 2)))); + texturesToAnimate.push_back( + std::pair(L"lava_flow", L"lava_flow")); + texturesByName.insert(stringIconMap::value_type( + L"destroy_0", + new SimpleIcon(L"destroy_0", slotSize * 0, slotSize * 15, + slotSize * (0 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_1", + new SimpleIcon(L"destroy_1", slotSize * 1, slotSize * 15, + slotSize * (1 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_2", + new SimpleIcon(L"destroy_2", slotSize * 2, slotSize * 15, + slotSize * (2 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_3", + new SimpleIcon(L"destroy_3", slotSize * 3, slotSize * 15, + slotSize * (3 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_4", + new SimpleIcon(L"destroy_4", slotSize * 4, slotSize * 15, + slotSize * (4 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_5", + new SimpleIcon(L"destroy_5", slotSize * 5, slotSize * 15, + slotSize * (5 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_6", + new SimpleIcon(L"destroy_6", slotSize * 6, slotSize * 15, + slotSize * (6 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_7", + new SimpleIcon(L"destroy_7", slotSize * 7, slotSize * 15, + slotSize * (7 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_8", + new SimpleIcon(L"destroy_8", slotSize * 8, slotSize * 15, + slotSize * (8 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"destroy_9", + new SimpleIcon(L"destroy_9", slotSize * 9, slotSize * 15, + slotSize * (9 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"quartzblock_bottom", + new SimpleIcon(L"quartzblock_bottom", slotSize * 11, slotSize * 15, + slotSize * (11 + 1), slotSize * (15 + 1)))); + texturesByName.insert(stringIconMap::value_type( + L"hopper_top", + new SimpleIcon(L"hopper_top", slotSize * 12, slotSize * 15, + slotSize * (12 + 1), slotSize * (15 + 1)))); + } } diff --git a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h index 3d6cac29e..76798e707 100644 --- a/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h +++ b/Minecraft.Client/Textures/Stitching/PreStitchedTextureMap.h @@ -1,6 +1,5 @@ #pragma once - #include "../../../Minecraft.World/Util/IconRegister.h" class Icon; @@ -9,43 +8,47 @@ class Texture; class BufferedImage; // 4J Added this class to stop having to do texture stitching at runtime -class PreStitchedTextureMap : public IconRegister -{ +class PreStitchedTextureMap : public IconRegister { public: - static const std::wstring NAME_MISSING_TEXTURE; + static const std::wstring NAME_MISSING_TEXTURE; private: - const int iconType; + const int iconType; - const std::wstring name; - const std::wstring path; - const std::wstring extension; + const std::wstring name; + const std::wstring path; + const std::wstring extension; - bool m_mipMap; + bool m_mipMap; - typedef std::unordered_map stringIconMap; - stringIconMap texturesByName; // = new HashMap(); - BufferedImage *missingTexture; // = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); - StitchedTexture *missingPosition; - Texture *stitchResult; - std::vector animatedTextures; // = new ArrayList(); + typedef std::unordered_map stringIconMap; + stringIconMap texturesByName; // = new HashMap(); + BufferedImage* missingTexture; // = new BufferedImage(64, 64, + // BufferedImage.TYPE_INT_ARGB); + StitchedTexture* missingPosition; + Texture* stitchResult; + std::vector + animatedTextures; // = new ArrayList(); - std::vector > texturesToAnimate; + std::vector > texturesToAnimate; + + void loadUVs(); - void loadUVs(); public: - PreStitchedTextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipMap = false); + PreStitchedTextureMap(int type, const std::wstring& name, + const std::wstring& path, + BufferedImage* missingTexture, bool mipMap = false); - void stitch(); - StitchedTexture *getTexture(const std::wstring &name); - void cycleAnimationFrames(); - Texture *getStitchedTexture(); + void stitch(); + StitchedTexture* getTexture(const std::wstring& name); + void cycleAnimationFrames(); + Texture* getStitchedTexture(); - // 4J Stu - register is a reserved keyword in C++ - Icon *registerIcon(const std::wstring &name); + // 4J Stu - register is a reserved keyword in C++ + Icon* registerIcon(const std::wstring& name); - int getIconType(); - Icon *getMissingIcon(); + int getIconType(); + Icon* getMissingIcon(); - int getFlags() const; + int getFlags() const; }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/StitchSlot.cpp b/Minecraft.Client/Textures/Stitching/StitchSlot.cpp index c79b57bb9..4186ddde9 100644 --- a/Minecraft.Client/Textures/Stitching/StitchSlot.cpp +++ b/Minecraft.Client/Textures/Stitching/StitchSlot.cpp @@ -3,154 +3,138 @@ #include "../../../Minecraft.World/Util/StringHelpers.h" #include "StitchSlot.h" -StitchSlot::StitchSlot(int originX, int originY, int width, int height) : originX(originX), originY(originY), width(width), height(height) -{ - subSlots = NULL; - textureHolder = NULL; +StitchSlot::StitchSlot(int originX, int originY, int width, int height) + : originX(originX), originY(originY), width(width), height(height) { + subSlots = NULL; + textureHolder = NULL; } -TextureHolder *StitchSlot::getHolder() -{ - return textureHolder; +TextureHolder* StitchSlot::getHolder() { return textureHolder; } + +int StitchSlot::getX() { return originX; } + +int StitchSlot::getY() { return originY; } + +bool StitchSlot::add(TextureHolder* textureHolder) { + // Already holding a texture -- doesn't account for subslots. + if (this->textureHolder != NULL) { + return false; + } + + int textureWidth = textureHolder->getWidth(); + int textureHeight = textureHolder->getHeight(); + + // We're too small to fit the texture + if (textureWidth > width || textureHeight > height) { + return false; + } + + // Exact fit! best-case-solution + if (textureWidth == width && textureHeight == height && subSlots == NULL) { + // Store somehow + this->textureHolder = textureHolder; + return true; + } + + // See if we're already divided before, if not, setup subSlots + if (subSlots == NULL) { + subSlots = new std::vector(); + + // First slot is for the new texture + subSlots->push_back( + new StitchSlot(originX, originY, textureWidth, textureHeight)); + + int spareWidth = width - textureWidth; + int spareHeight = height - textureHeight; + + if (spareHeight > 0 && spareWidth > 0) { + // Space below AND right + // + // <-right-> + // +-----+-------+ + // | | | + // | Tex | | + // | | | + // |-----+ | ^ + // | | |- bottom + // +-------------+ v + // We need to add two more areas, the one with the 'biggest' + // dimensions should be used (In the case of this ASCII drawing, + // it's the 'right hand side' that should win) + + // The 'fattest' area should be used (or when tied, the right hand + // one) + int right = std::max(height, spareWidth); + int bottom = std::max(width, spareHeight); + if (right >= bottom) { + subSlots->push_back(new StitchSlot(originX, + originY + textureHeight, + textureWidth, spareHeight)); + subSlots->push_back(new StitchSlot( + originX + textureWidth, originY, spareWidth, height)); + } else { + subSlots->push_back(new StitchSlot(originX + textureWidth, + originY, spareWidth, + textureHeight)); + subSlots->push_back(new StitchSlot( + originX, originY + textureHeight, width, spareHeight)); + } + + } else if (spareWidth == 0) { + // We just have space left below + // + // +-------------+ + // | | + // | Tex | + // | | + // |-------------+ ^ + // | | |- bottom + // +-------------+ v + subSlots->push_back(new StitchSlot(originX, originY + textureHeight, + textureWidth, spareHeight)); + } else if (spareHeight == 0) { + // Only space to the right + // + // <-right-> + // +-----+-------+ + // | | | + // | Tex | | + // | | | + // | | | + // | | | + // +-----+-------+ + subSlots->push_back(new StitchSlot(originX + textureWidth, originY, + spareWidth, textureHeight)); + } + } + + // for (final StitchSlot subSlot : subSlots) + for (AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) { + StitchSlot* subSlot = *it; + if (subSlot->add(textureHolder)) { + return true; + } + } + + return false; } -int StitchSlot::getX() -{ - return originX; -} - -int StitchSlot::getY() -{ - return originY; -} - -bool StitchSlot::add(TextureHolder *textureHolder) -{ - // Already holding a texture -- doesn't account for subslots. - if (this->textureHolder != NULL) - { - return false; - } - - int textureWidth = textureHolder->getWidth(); - int textureHeight = textureHolder->getHeight(); - - // We're too small to fit the texture - if (textureWidth > width || textureHeight > height) - { - return false; - } - - // Exact fit! best-case-solution - if (textureWidth == width && textureHeight == height && subSlots == NULL) - { - // Store somehow - this->textureHolder = textureHolder; - return true; - } - - // See if we're already divided before, if not, setup subSlots - if (subSlots == NULL) - { - subSlots = new std::vector(); - - // First slot is for the new texture - subSlots->push_back(new StitchSlot(originX, originY, textureWidth, textureHeight)); - - int spareWidth = width - textureWidth; - int spareHeight = height - textureHeight; - - if (spareHeight > 0 && spareWidth > 0) - { - // Space below AND right - // - // <-right-> - // +-----+-------+ - // | | | - // | Tex | | - // | | | - // |-----+ | ^ - // | | |- bottom - // +-------------+ v - // We need to add two more areas, the one with the 'biggest' dimensions should be used - // (In the case of this ASCII drawing, it's the 'right hand side' that should win) - - // The 'fattest' area should be used (or when tied, the right hand one) - int right = std::max(height, spareWidth); - int bottom = std::max(width, spareHeight); - if (right >= bottom) - { - subSlots->push_back(new StitchSlot(originX, originY + textureHeight, textureWidth, spareHeight)); - subSlots->push_back(new StitchSlot(originX + textureWidth, originY, spareWidth, height)); - } - else - { - subSlots->push_back(new StitchSlot(originX + textureWidth, originY, spareWidth, textureHeight)); - subSlots->push_back(new StitchSlot(originX, originY + textureHeight, width, spareHeight)); - } - - } - else if (spareWidth == 0) - { - // We just have space left below - // - // +-------------+ - // | | - // | Tex | - // | | - // |-------------+ ^ - // | | |- bottom - // +-------------+ v - subSlots->push_back(new StitchSlot(originX, originY + textureHeight, textureWidth, spareHeight)); - } - else if (spareHeight == 0) - { - // Only space to the right - // - // <-right-> - // +-----+-------+ - // | | | - // | Tex | | - // | | | - // | | | - // | | | - // +-----+-------+ - subSlots->push_back(new StitchSlot(originX + textureWidth, originY, spareWidth, textureHeight)); - } - } - - //for (final StitchSlot subSlot : subSlots) - for(AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) - { - StitchSlot *subSlot = *it; - if (subSlot->add(textureHolder)) - { - return true; - } - } - - return false; -} - -void StitchSlot::collectAssignments(std::vector *result) -{ - if (textureHolder != NULL) - { - result->push_back(this); - } - else if (subSlots != NULL) - { - //for (StitchSlot subSlot : subSlots) - for(AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) - { - StitchSlot *subSlot = *it; - subSlot->collectAssignments(result); - } - } +void StitchSlot::collectAssignments(std::vector* result) { + if (textureHolder != NULL) { + result->push_back(this); + } else if (subSlots != NULL) { + // for (StitchSlot subSlot : subSlots) + for (AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) { + StitchSlot* subSlot = *it; + subSlot->collectAssignments(result); + } + } } //@Override -std::wstring StitchSlot::toString() -{ - return L"Slot{originX=" + _toString(originX) + L", originY=" + _toString(originY) + L", width=" + _toString(width) + L", height=" + _toString(height) + L", texture=" + _toString(textureHolder) + L", subSlots=" + _toString(subSlots) + L'}'; +std::wstring StitchSlot::toString() { + return L"Slot{originX=" + _toString(originX) + L", originY=" + + _toString(originY) + L", width=" + _toString(width) + L", height=" + + _toString(height) + L", texture=" + _toString(textureHolder) + + L", subSlots=" + _toString(subSlots) + L'}'; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/StitchSlot.h b/Minecraft.Client/Textures/Stitching/StitchSlot.h index a1a7dc832..b9725d674 100644 --- a/Minecraft.Client/Textures/Stitching/StitchSlot.h +++ b/Minecraft.Client/Textures/Stitching/StitchSlot.h @@ -1,28 +1,26 @@ #pragma once - class TextureHolder; -class StitchSlot -{ +class StitchSlot { private: - const int originX; - const int originY; + const int originX; + const int originY; - const int width; - const int height; - std::vector *subSlots; - TextureHolder *textureHolder; + const int width; + const int height; + std::vector* subSlots; + TextureHolder* textureHolder; public: - StitchSlot(int originX, int originY, int width, int height); + StitchSlot(int originX, int originY, int width, int height); - TextureHolder *getHolder(); - int getX(); - int getY(); - bool add(TextureHolder *textureHolder); - void collectAssignments(std::vector *result); + TextureHolder* getHolder(); + int getX(); + int getY(); + bool add(TextureHolder* textureHolder); + void collectAssignments(std::vector* result); - //@Override - std::wstring toString(); + //@Override + std::wstring toString(); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp b/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp index 124c7207f..48baaf6ad 100644 --- a/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp +++ b/Minecraft.Client/Textures/Stitching/StitchedTexture.cpp @@ -6,355 +6,275 @@ #include "StitchedTexture.h" #include "../TextureManager.h" -StitchedTexture *StitchedTexture::create(const std::wstring &name) -{ - // TODO: Generalize? - if (name.compare(L"clock") == 0) - { - return new ClockTexture(); - } - else if (name.compare(L"compass") == 0) - { - return new CompassTexture(); - } - else - { - return new StitchedTexture(name); - } +StitchedTexture* StitchedTexture::create(const std::wstring& name) { + // TODO: Generalize? + if (name.compare(L"clock") == 0) { + return new ClockTexture(); + } else if (name.compare(L"compass") == 0) { + return new CompassTexture(); + } else { + return new StitchedTexture(name); + } } -StitchedTexture::StitchedTexture(const std::wstring &name) : name(name) -{ - // 4J Initialisers - source = NULL; - rotated = false; - x = 0; - y = 0; - width = 0; - height = 0; - u0 = 0.0f; - u1 = 0.0f; - v0 = 0.0f; - v1 = 0.0f; - widthTranslation = 0.0f; - heightTranslation = 0.0f; - frame = 0; - subFrame = 0; - frameOverride = NULL; - flags = 0; - frames = NULL; +StitchedTexture::StitchedTexture(const std::wstring& name) : name(name) { + // 4J Initialisers + source = NULL; + rotated = false; + x = 0; + y = 0; + width = 0; + height = 0; + u0 = 0.0f; + u1 = 0.0f; + v0 = 0.0f; + v1 = 0.0f; + widthTranslation = 0.0f; + heightTranslation = 0.0f; + frame = 0; + subFrame = 0; + frameOverride = NULL; + flags = 0; + frames = NULL; } -void StitchedTexture::freeFrameTextures() -{ - if( frames ) - { - for(AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) - { - TextureManager::getInstance()->unregisterTexture(L"", *it); - delete *it; - } - delete frames; - } +void StitchedTexture::freeFrameTextures() { + if (frames) { + for (AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) { + TextureManager::getInstance()->unregisterTexture(L"", *it); + delete *it; + } + delete frames; + } } -StitchedTexture::~StitchedTexture() -{ - // 4jcraft, added null check - // the constructor does not allocate the frames vector. - // in some scenarios the destructor/delete is called - // without ever calling ::init() - if(frames) { - for(AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) - { - delete *it; - } - delete frames; - } +StitchedTexture::~StitchedTexture() { + // 4jcraft, added null check + // the constructor does not allocate the frames vector. + // in some scenarios the destructor/delete is called + // without ever calling ::init() + if (frames) { + for (AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) { + delete *it; + } + delete frames; + } } -void StitchedTexture::initUVs(float U0, float V0, float U1, float V1) -{ - u0 = U0; - u1 = U1; - v0 = V0; - v1 = V1; +void StitchedTexture::initUVs(float U0, float V0, float U1, float V1) { + u0 = U0; + u1 = U1; + v0 = V0; + v1 = V1; } -void StitchedTexture::init(Texture *source, std::vector *frames, int x, int y, int width, int height, bool rotated) -{ - this->source = source; - this->frames = frames; - frame = -1; // Force an update of animated textures - this->x = x; - this->y = y; - this->width = width; - this->height = height; - this->rotated = rotated; +void StitchedTexture::init(Texture* source, std::vector* frames, + int x, int y, int width, int height, bool rotated) { + this->source = source; + this->frames = frames; + frame = -1; // Force an update of animated textures + this->x = x; + this->y = y; + this->width = width; + this->height = height; + this->rotated = rotated; - float marginX = 0.0f; //0.01f / source->getWidth(); - float marginY = 0.0f; //0.01f / source->getHeight(); + float marginX = 0.0f; // 0.01f / source->getWidth(); + float marginY = 0.0f; // 0.01f / source->getHeight(); - this->u0 = x / (float) source->getWidth() + marginX; - this->u1 = (x + width) / (float) source->getWidth() - marginX; - this->v0 = y / (float) source->getHeight() + marginY; - this->v1 = (y + height) / (float) source->getHeight() - marginY; + this->u0 = x / (float)source->getWidth() + marginX; + this->u1 = (x + width) / (float)source->getWidth() - marginX; + this->v0 = y / (float)source->getHeight() + marginY; + this->v1 = (y + height) / (float)source->getHeight() - marginY; #ifndef _CONTENT_PACKAGE - bool addBreakpoint = false; - if(addBreakpoint) - { - printf("\nTreeTop\n"); - printf("u0 = %f\n", u0); - printf("u1 = %f\n", u1); - printf("v0 = %f\n", v0); - printf("v1 = %f\n", v1); - printf("\n\n"); - } + bool addBreakpoint = false; + if (addBreakpoint) { + printf("\nTreeTop\n"); + printf("u0 = %f\n", u0); + printf("u1 = %f\n", u1); + printf("v0 = %f\n", v0); + printf("v1 = %f\n", v1); + printf("\n\n"); + } #endif - this->widthTranslation = width / (float) SharedConstants::WORLD_RESOLUTION; - this->heightTranslation = height / (float) SharedConstants::WORLD_RESOLUTION; + this->widthTranslation = width / (float)SharedConstants::WORLD_RESOLUTION; + this->heightTranslation = height / (float)SharedConstants::WORLD_RESOLUTION; } -void StitchedTexture::replaceWith(StitchedTexture *texture) -{ - init(texture->source, texture->frames, texture->x, texture->y, texture->width, texture->height, texture->rotated); +void StitchedTexture::replaceWith(StitchedTexture* texture) { + init(texture->source, texture->frames, texture->x, texture->y, + texture->width, texture->height, texture->rotated); } -int StitchedTexture::getX() const -{ - return x; +int StitchedTexture::getX() const { return x; } + +int StitchedTexture::getY() const { return y; } + +int StitchedTexture::getWidth() const { return width; } + +int StitchedTexture::getHeight() const { return height; } + +static const float UVAdjust = (1.0f / 16.0f) / 256.0f; + +float StitchedTexture::getU0(bool adjust /*=false*/) const { + return adjust ? (u0 + UVAdjust) : u0; } -int StitchedTexture::getY() const -{ - return y; +float StitchedTexture::getU1(bool adjust /*=false*/) const { + return adjust ? (u1 - UVAdjust) : u1; } -int StitchedTexture::getWidth() const -{ - return width; +float StitchedTexture::getU(double offset, bool adjust /*=false*/) const { + float diff = getU1(adjust) - getU0(adjust); + return getU0(adjust) + + (diff * ((float)offset / SharedConstants::WORLD_RESOLUTION)); } -int StitchedTexture::getHeight() const -{ - return height; +float StitchedTexture::getV0(bool adjust /*=false*/) const { + return adjust ? (v0 + UVAdjust) : v0; } -static const float UVAdjust = (1.0f/16.0f)/256.0f; - -float StitchedTexture::getU0(bool adjust/*=false*/) const -{ - return adjust ? ( u0 + UVAdjust ) : u0; +float StitchedTexture::getV1(bool adjust /*=false*/) const { + return adjust ? (v1 - UVAdjust) : v1; } -float StitchedTexture::getU1(bool adjust/*=false*/) const -{ - return adjust ? ( u1 - UVAdjust ) : u1; +float StitchedTexture::getV(double offset, bool adjust /*=false*/) const { + float diff = getV1(adjust) - getV0(adjust); + return getV0(adjust) + + (diff * ((float)offset / SharedConstants::WORLD_RESOLUTION)); } -float StitchedTexture::getU(double offset, bool adjust/*=false*/) const -{ - float diff = getU1(adjust) - getU0(adjust); - return getU0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); +std::wstring StitchedTexture::getName() const { return name; } + +int StitchedTexture::getSourceWidth() const { return source->getWidth(); } + +int StitchedTexture::getSourceHeight() const { return source->getHeight(); } + +void StitchedTexture::cycleFrames() { + if (frameOverride != NULL) { + std::pair current = frameOverride->at(frame); + subFrame++; + if (subFrame >= current.second) { + int oldFrame = current.first; + frame = (frame + 1) % frameOverride->size(); + subFrame = 0; + + current = frameOverride->at(frame); + int newFrame = current.first; + if (oldFrame != newFrame && newFrame >= 0 && + newFrame < frames->size()) { + source->blit(x, y, frames->at(newFrame), rotated); + } + } + + } else { + int oldFrame = frame; + frame = (frame + 1) % frames->size(); + + if (oldFrame != frame) { + source->blit(x, y, frames->at(this->frame), rotated); + } + } } -float StitchedTexture::getV0(bool adjust/*=false*/) const -{ - return adjust ? ( v0 + UVAdjust ) : v0; -} +Texture* StitchedTexture::getSource() { return source; } -float StitchedTexture::getV1(bool adjust/*=false*/) const -{ - return adjust ? ( v1 - UVAdjust ) : v1; -} +Texture* StitchedTexture::getFrame(int i) { return frames->at(i); } -float StitchedTexture::getV(double offset, bool adjust/*=false*/) const -{ - float diff = getV1(adjust) - getV0(adjust); - return getV0(adjust) + (diff * ((float) offset / SharedConstants::WORLD_RESOLUTION)); -} - -std::wstring StitchedTexture::getName() const -{ - return name; -} - -int StitchedTexture::getSourceWidth() const -{ - return source->getWidth(); -} - -int StitchedTexture::getSourceHeight() const -{ - return source->getHeight(); -} - -void StitchedTexture::cycleFrames() -{ - if (frameOverride != NULL) - { - std::pair current = frameOverride->at(frame); - subFrame++; - if (subFrame >= current.second) - { - int oldFrame = current.first; - frame = (frame + 1) % frameOverride->size(); - subFrame = 0; - - current = frameOverride->at(frame); - int newFrame = current.first; - if (oldFrame != newFrame && newFrame >= 0 && newFrame < frames->size()) - { - source->blit(x, y, frames->at(newFrame), rotated); - } - } - - } - else - { - int oldFrame = frame; - frame = (frame + 1) % frames->size(); - - if (oldFrame != frame) - { - source->blit(x, y, frames->at(this->frame), rotated); - } - } -} - -Texture *StitchedTexture::getSource() -{ - return source; -} - -Texture *StitchedTexture::getFrame(int i) -{ - return frames->at(i); -} - -int StitchedTexture::getFrames() -{ - return frames?frames->size():0; -} +int StitchedTexture::getFrames() { return frames ? frames->size() : 0; } /** -* Loads animation frames from a file with the syntax, -* 0,1,2,3, -* 4*10,5*10, -* 4*10,3,2,1, -* 0 -* or similar -* -* @param bufferedReader -*/ -void StitchedTexture::loadAnimationFrames(BufferedReader *bufferedReader) -{ - if(frameOverride != NULL) - { - delete frameOverride; - frameOverride = NULL; - } - frame = 0; - subFrame = 0; + * Loads animation frames from a file with the syntax, + * 0,1,2,3, + * 4*10,5*10, + * 4*10,3,2,1, + * 0 + * or similar + * + * @param bufferedReader + */ +void StitchedTexture::loadAnimationFrames(BufferedReader* bufferedReader) { + if (frameOverride != NULL) { + delete frameOverride; + frameOverride = NULL; + } + frame = 0; + subFrame = 0; - intPairVector *results = new intPairVector(); + intPairVector* results = new intPairVector(); - //try { - std::wstring line = bufferedReader->readLine(); - while (!line.empty()) - { - line = trimString(line); - if (line.length() > 0) - { - std::vector tokens = stringSplit(line, L','); - //for (String token : tokens) - for(AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) - { - std::wstring token = *it; - int multiPos = token.find_first_of('*'); - if (multiPos > 0) - { - int frame = _fromString(token.substr(0, multiPos)); - int count = _fromString(token.substr(multiPos + 1)); - results->push_back( intPairVector::value_type(frame, count)); - } - else - { - int tokenVal = _fromString(token); - results->push_back( intPairVector::value_type(tokenVal, 1)); - } - } - } - line = bufferedReader->readLine(); - } - //} catch (Exception e) { - // System.err.println("Failed to read animation info for " + name + ": " + e.getMessage()); - //} + // try { + std::wstring line = bufferedReader->readLine(); + while (!line.empty()) { + line = trimString(line); + if (line.length() > 0) { + std::vector tokens = stringSplit(line, L','); + // for (String token : tokens) + for (AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) { + std::wstring token = *it; + int multiPos = token.find_first_of('*'); + if (multiPos > 0) { + int frame = _fromString(token.substr(0, multiPos)); + int count = _fromString(token.substr(multiPos + 1)); + results->push_back(intPairVector::value_type(frame, count)); + } else { + int tokenVal = _fromString(token); + results->push_back(intPairVector::value_type(tokenVal, 1)); + } + } + } + line = bufferedReader->readLine(); + } + //} catch (Exception e) { + // System.err.println("Failed to read animation info for " + name + ": " + + //e.getMessage()); + //} - if (!results->empty() && results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) - { - frameOverride = results; - } - else - { - delete results; - } + if (!results->empty() && + results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) { + frameOverride = results; + } else { + delete results; + } } -void StitchedTexture::loadAnimationFrames(const std::wstring &string) -{ - if(frameOverride != NULL) - { - delete frameOverride; - frameOverride = NULL; - } - frame = 0; - subFrame = 0; +void StitchedTexture::loadAnimationFrames(const std::wstring& string) { + if (frameOverride != NULL) { + delete frameOverride; + frameOverride = NULL; + } + frame = 0; + subFrame = 0; - intPairVector *results = new intPairVector(); + intPairVector* results = new intPairVector(); - std::vector tokens = stringSplit(trimString(string), L','); - //for (String token : tokens) - for(AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) - { - std::wstring token = trimString(*it); - int multiPos = token.find_first_of('*'); - if (multiPos > 0) - { - int frame = _fromString(token.substr(0, multiPos)); - int count = _fromString(token.substr(multiPos + 1)); - results->push_back( intPairVector::value_type(frame, count)); - } - else if(!token.empty()) - { - int tokenVal = _fromString(token); - results->push_back( intPairVector::value_type(tokenVal, 1)); - } - } + std::vector tokens = stringSplit(trimString(string), L','); + // for (String token : tokens) + for (AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) { + std::wstring token = trimString(*it); + int multiPos = token.find_first_of('*'); + if (multiPos > 0) { + int frame = _fromString(token.substr(0, multiPos)); + int count = _fromString(token.substr(multiPos + 1)); + results->push_back(intPairVector::value_type(frame, count)); + } else if (!token.empty()) { + int tokenVal = _fromString(token); + results->push_back(intPairVector::value_type(tokenVal, 1)); + } + } - if (!results->empty() && results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) - { - frameOverride = results; - } - else - { - delete results; - } + if (!results->empty() && + results->size() < (SharedConstants::TICKS_PER_SECOND * 30)) { + frameOverride = results; + } else { + delete results; + } } -void StitchedTexture::setFlags(int flags) -{ - this->flags = flags; -} +void StitchedTexture::setFlags(int flags) { this->flags = flags; } -int StitchedTexture::getFlags() const -{ - return this->flags; -} +int StitchedTexture::getFlags() const { return this->flags; } -bool StitchedTexture::hasOwnData() -{ - return true; -} +bool StitchedTexture::hasOwnData() { return true; } diff --git a/Minecraft.Client/Textures/Stitching/StitchedTexture.h b/Minecraft.Client/Textures/Stitching/StitchedTexture.h index 306ffd1b7..e1059ed5e 100644 --- a/Minecraft.Client/Textures/Stitching/StitchedTexture.h +++ b/Minecraft.Client/Textures/Stitching/StitchedTexture.h @@ -1,89 +1,89 @@ #pragma once - #include "../../../Minecraft.World/Util/Icon.h" class Texture; -class StitchedTexture : public Icon -{ +class StitchedTexture : public Icon { private: - const std::wstring name; + const std::wstring name; protected: - Texture *source; - std::vector *frames; + Texture* source; + std::vector* frames; private: - typedef std::vector > intPairVector; - intPairVector *frameOverride; - int flags; + typedef std::vector > intPairVector; + intPairVector* frameOverride; + int flags; protected: - bool rotated; + bool rotated; - int x; - int y; + int x; + int y; protected: - int width; - int height; + int width; + int height; - float u0; - float u1; - float v0; - float v1; + float u0; + float u1; + float v0; + float v1; - float widthTranslation; - float heightTranslation; + float widthTranslation; + float heightTranslation; protected: - int frame; - int subFrame; + int frame; + int subFrame; public: - static StitchedTexture *create(const std::wstring &name); - - ~StitchedTexture(); + static StitchedTexture* create(const std::wstring& name); + + ~StitchedTexture(); + protected: - StitchedTexture(const std::wstring &name); + StitchedTexture(const std::wstring& name); public: - void initUVs(float U0, float V0, float U1, float V1); - void init(Texture *source, std::vector *frames, int x, int y, int width, int height, bool rotated); - void replaceWith(StitchedTexture *texture); - int getX() const; - int getY() const; - int getWidth() const; - int getHeight() const; - float getU0(bool adjust = false) const; - float getU1(bool adjust = false) const; - float getU(double offset, bool adjust = false) const; - float getV0(bool adjust = false) const; - float getV1(bool adjust = false) const; - float getV(double offset, bool adjust = false) const; - std::wstring getName() const; - virtual int getSourceWidth() const; - virtual int getSourceHeight() const; - virtual void cycleFrames(); - Texture *getSource(); - Texture *getFrame(int i); - virtual int getFrames(); + void initUVs(float U0, float V0, float U1, float V1); + void init(Texture* source, std::vector* frames, int x, int y, + int width, int height, bool rotated); + void replaceWith(StitchedTexture* texture); + int getX() const; + int getY() const; + int getWidth() const; + int getHeight() const; + float getU0(bool adjust = false) const; + float getU1(bool adjust = false) const; + float getU(double offset, bool adjust = false) const; + float getV0(bool adjust = false) const; + float getV1(bool adjust = false) const; + float getV(double offset, bool adjust = false) const; + std::wstring getName() const; + virtual int getSourceWidth() const; + virtual int getSourceHeight() const; + virtual void cycleFrames(); + Texture* getSource(); + Texture* getFrame(int i); + virtual int getFrames(); - /** - * Loads animation frames from a file with the syntax, - * 0,1,2,3, - * 4*10,5*10, - * 4*10,3,2,1, - * 0 - * or similar - * - * @param bufferedReader - */ - void loadAnimationFrames(BufferedReader *bufferedReader); - void loadAnimationFrames(const std::wstring &string); // 4J Added + /** + * Loads animation frames from a file with the syntax, + * 0,1,2,3, + * 4*10,5*10, + * 4*10,3,2,1, + * 0 + * or similar + * + * @param bufferedReader + */ + void loadAnimationFrames(BufferedReader* bufferedReader); + void loadAnimationFrames(const std::wstring& string); // 4J Added - int getFlags() const ; // 4J added - void setFlags(int flags); // 4J added - virtual void freeFrameTextures(); // 4J added - virtual bool hasOwnData(); // 4J Added + int getFlags() const; // 4J added + void setFlags(int flags); // 4J added + virtual void freeFrameTextures(); // 4J added + virtual bool hasOwnData(); // 4J Added }; diff --git a/Minecraft.Client/Textures/Stitching/Stitcher.cpp b/Minecraft.Client/Textures/Stitching/Stitcher.cpp index b70751dde..24f3332d1 100644 --- a/Minecraft.Client/Textures/Stitching/Stitcher.cpp +++ b/Minecraft.Client/Textures/Stitching/Stitcher.cpp @@ -6,256 +6,233 @@ #include "StitchedTexture.h" #include "Stitcher.h" -void Stitcher::_init(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale) -{ - this->name = name; - this->maxWidth = maxWidth; - this->maxHeight = maxHeight; - this->forcePowerOfTwo = forcePowerOfTwo; - this->forcedScale = forcedScale; +void Stitcher::_init(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale) { + this->name = name; + this->maxWidth = maxWidth; + this->maxHeight = maxHeight; + this->forcePowerOfTwo = forcePowerOfTwo; + this->forcedScale = forcedScale; - // 4J init - storageX = 0; - storageY = 0; - stitchedTexture = NULL; + // 4J init + storageX = 0; + storageY = 0; + stitchedTexture = NULL; } -Stitcher::Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo) -{ - _init(name, maxWidth, maxHeight, forcePowerOfTwo, 0); +Stitcher::Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo) { + _init(name, maxWidth, maxHeight, forcePowerOfTwo, 0); } -Stitcher::Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale) -{ - _init(name, maxWidth, maxHeight, forcePowerOfTwo, forcedScale); +Stitcher::Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale) { + _init(name, maxWidth, maxHeight, forcePowerOfTwo, forcedScale); } -int Stitcher::getWidth() -{ - return storageX; +int Stitcher::getWidth() { return storageX; } + +int Stitcher::getHeight() { return storageY; } + +void Stitcher::addTexture(TextureHolder* textureHolder) { + if (forcedScale > 0) { + textureHolder->setForcedScale(forcedScale); + } + texturesToBeStitched.insert(textureHolder); } -int Stitcher::getHeight() -{ - return storageY; +Texture* Stitcher::constructTexture(bool mipmap) { + if (forcePowerOfTwo) { + storageX = smallestEncompassingPowerOfTwo(storageX); + storageY = smallestEncompassingPowerOfTwo(storageY); + } + + stitchedTexture = TextureManager::getInstance()->createTexture( + name, Texture::TM_DYNAMIC, storageX, storageY, Texture::TFMT_RGBA, + mipmap); + stitchedTexture->fill(stitchedTexture->getRect(), 0xffff0000); + + std::vector* slots = gatherAreas(); + for (int index = 0; index < slots->size(); index++) { + StitchSlot* slot = slots->at(index); + TextureHolder* textureHolder = slot->getHolder(); + stitchedTexture->blit(slot->getX(), slot->getY(), + textureHolder->getTexture(), + textureHolder->isRotated()); + } + delete slots; + TextureManager::getInstance()->registerName(name, stitchedTexture); + + return stitchedTexture; } -void Stitcher::addTexture(TextureHolder *textureHolder) -{ - if (forcedScale > 0) - { - textureHolder->setForcedScale(forcedScale); - } - texturesToBeStitched.insert(textureHolder); -} +void Stitcher::stitch() { + // TextureHolder[] textureHolders = texturesToBeStitched.toArray(new + // TextureHolder[texturesToBeStitched.size()]); Arrays.sort(textureHolders); -Texture *Stitcher::constructTexture(bool mipmap) -{ - if (forcePowerOfTwo) - { - storageX = smallestEncompassingPowerOfTwo(storageX); - storageY = smallestEncompassingPowerOfTwo(storageY); - } + stitchedTexture = NULL; - stitchedTexture = TextureManager::getInstance()->createTexture(name, Texture::TM_DYNAMIC, storageX, storageY, Texture::TFMT_RGBA, mipmap); - stitchedTexture->fill(stitchedTexture->getRect(), 0xffff0000); + // for (int i = 0; i < textureHolders.length; i++) + for (AUTO_VAR(it, texturesToBeStitched.begin()); + it != texturesToBeStitched.end(); ++it) { + TextureHolder* textureHolder = *it; // textureHolders[i]; - std::vector *slots = gatherAreas(); - for (int index = 0; index < slots->size(); index++) - { - StitchSlot *slot = slots->at(index); - TextureHolder *textureHolder = slot->getHolder(); - stitchedTexture->blit(slot->getX(), slot->getY(), textureHolder->getTexture(), textureHolder->isRotated()); - } - delete slots; - TextureManager::getInstance()->registerName(name, stitchedTexture); - - return stitchedTexture; -} - -void Stitcher::stitch() -{ - //TextureHolder[] textureHolders = texturesToBeStitched.toArray(new TextureHolder[texturesToBeStitched.size()]); - //Arrays.sort(textureHolders); - - stitchedTexture = NULL; - - //for (int i = 0; i < textureHolders.length; i++) - for(AUTO_VAR(it, texturesToBeStitched.begin()); it != texturesToBeStitched.end(); ++it) - { - TextureHolder *textureHolder = *it; //textureHolders[i]; - - if (!addToStorage(textureHolder)) - { - app.DebugPrintf("Stitcher exception!\n"); + if (!addToStorage(textureHolder)) { + app.DebugPrintf("Stitcher exception!\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - //throw new StitcherException(textureHolder); - } - } + // throw new StitcherException(textureHolder); + } + } } -std::vector *Stitcher::gatherAreas() -{ - std::vector *result = new std::vector(); +std::vector* Stitcher::gatherAreas() { + std::vector* result = new std::vector(); - //for (StitchSlot slot : storage) - for(AUTO_VAR(it, storage.begin()); it != storage.end(); ++it) - { - StitchSlot *slot = *it; - slot->collectAssignments(result); - } + // for (StitchSlot slot : storage) + for (AUTO_VAR(it, storage.begin()); it != storage.end(); ++it) { + StitchSlot* slot = *it; + slot->collectAssignments(result); + } - return result; + return result; } // Based on: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 -int Stitcher::smallestEncompassingPowerOfTwo(int input) -{ - int result = input - 1; - result |= result >> 1; - result |= result >> 2; - result |= result >> 4; - result |= result >> 8; - result |= result >> 16; - return result + 1; +int Stitcher::smallestEncompassingPowerOfTwo(int input) { + int result = input - 1; + result |= result >> 1; + result |= result >> 2; + result |= result >> 4; + result |= result >> 8; + result |= result >> 16; + return result + 1; } -bool Stitcher::addToStorage(TextureHolder *textureHolder) -{ - for (int i = 0; i < storage.size(); i++) - { - if (storage.at(i)->add(textureHolder)) - { - return true; - } +bool Stitcher::addToStorage(TextureHolder* textureHolder) { + for (int i = 0; i < storage.size(); i++) { + if (storage.at(i)->add(textureHolder)) { + return true; + } - // Try rotated - textureHolder->rotate(); - if (storage.at(i)->add(textureHolder)) - { - return true; - } + // Try rotated + textureHolder->rotate(); + if (storage.at(i)->add(textureHolder)) { + return true; + } - // Undo rotation - textureHolder->rotate(); - } + // Undo rotation + textureHolder->rotate(); + } - return expand(textureHolder); + return expand(textureHolder); } /** -* Expand the current storage to take in account the new texture. -* This should only be called if it didn't fit anywhere. -* -* @param textureHolder -* @return Boolean indicating if it could accommodate for the growth -*/ -bool Stitcher::expand(TextureHolder *textureHolder) -{ - int minDistance = std::min(textureHolder->getHeight(), textureHolder->getWidth()); - bool firstAddition = storageX == 0 && storageY == 0; + * Expand the current storage to take in account the new texture. + * This should only be called if it didn't fit anywhere. + * + * @param textureHolder + * @return Boolean indicating if it could accommodate for the growth + */ +bool Stitcher::expand(TextureHolder* textureHolder) { + int minDistance = + std::min(textureHolder->getHeight(), textureHolder->getWidth()); + bool firstAddition = storageX == 0 && storageY == 0; - // It couldn't fit, decide which direction to grow to - bool growOnX; - if (forcePowerOfTwo) - { - int xCurrentSize = smallestEncompassingPowerOfTwo(storageX); - int yCurrentSize = smallestEncompassingPowerOfTwo(storageY); - int xNewSize = smallestEncompassingPowerOfTwo(storageX + minDistance); - int yNewSize = smallestEncompassingPowerOfTwo(storageY + minDistance); + // It couldn't fit, decide which direction to grow to + bool growOnX; + if (forcePowerOfTwo) { + int xCurrentSize = smallestEncompassingPowerOfTwo(storageX); + int yCurrentSize = smallestEncompassingPowerOfTwo(storageY); + int xNewSize = smallestEncompassingPowerOfTwo(storageX + minDistance); + int yNewSize = smallestEncompassingPowerOfTwo(storageY + minDistance); - bool xCanGrow = xNewSize <= maxWidth; - bool yCanGrow = yNewSize <= maxHeight; + bool xCanGrow = xNewSize <= maxWidth; + bool yCanGrow = yNewSize <= maxHeight; - if (!xCanGrow && !yCanGrow) - { - return false; - } + if (!xCanGrow && !yCanGrow) { + return false; + } - // Even if the smallest side fits the larger might not >.> - int maxDistance = std::max(textureHolder->getHeight(), textureHolder->getWidth()); - // TODO: This seems wrong ... - if (firstAddition && !xCanGrow && !(smallestEncompassingPowerOfTwo(storageY + maxDistance) <= maxHeight)) - { - return false; - } + // Even if the smallest side fits the larger might not >.> + int maxDistance = + std::max(textureHolder->getHeight(), textureHolder->getWidth()); + // TODO: This seems wrong ... + if (firstAddition && !xCanGrow && + !(smallestEncompassingPowerOfTwo(storageY + maxDistance) <= + maxHeight)) { + return false; + } - bool xWillGrow = xCurrentSize != xNewSize; - bool yWillGrow = yCurrentSize != yNewSize; + bool xWillGrow = xCurrentSize != xNewSize; + bool yWillGrow = yCurrentSize != yNewSize; - if (xWillGrow ^ yWillGrow) - { - // Either grows - //only pick X if it can grow AND it wanted to grow - // if !xCanGrow then yCanGrow + if (xWillGrow ^ yWillGrow) { + // Either grows + // only pick X if it can grow AND it wanted to grow + // if !xCanGrow then yCanGrow + growOnX = xWillGrow && xCanGrow; + } else { + // Both or Neither grow -- smallest side wins + growOnX = xCanGrow && xCurrentSize <= yCurrentSize; + } + } else { + // We need to figure out to either expand + bool xCanGrow = (storageX + minDistance) <= maxWidth; + bool yCanGrow = (storageY + minDistance) <= maxHeight; - growOnX = xWillGrow && xCanGrow; - } - else - { - // Both or Neither grow -- smallest side wins - growOnX = xCanGrow && xCurrentSize <= yCurrentSize; - } - } - else - { - // We need to figure out to either expand - bool xCanGrow = (storageX + minDistance) <= maxWidth; - bool yCanGrow = (storageY + minDistance) <= maxHeight; + if (!xCanGrow && !yCanGrow) { + return false; + } - if (!xCanGrow && !yCanGrow) - { - return false; - } + // Prefer growing on X when its: first addition *or* its the smaller of + // the two sides + growOnX = (firstAddition || storageX <= storageY) && xCanGrow; + } - // Prefer growing on X when its: first addition *or* its the smaller of the two sides - growOnX = (firstAddition || storageX <= storageY) && xCanGrow; - } + StitchSlot* slot; + if (growOnX) { + if (textureHolder->getWidth() > textureHolder->getHeight()) { + textureHolder->rotate(); + } - StitchSlot *slot; - if (growOnX) - { - if (textureHolder->getWidth() > textureHolder->getHeight()) - { - textureHolder->rotate(); - } + // Grow the 'Y' when it has no size yet + if (storageY == 0) { + storageY = textureHolder->getHeight(); + } - // Grow the 'Y' when it has no size yet - if (storageY == 0) - { - storageY = textureHolder->getHeight(); - } + int newSlotWidth = textureHolder->getWidth(); + // 4J Stu - If we are expanding the texture, then allocate the full + // powerOfTwo size that we are going to eventually create + if (forcePowerOfTwo) { + newSlotWidth = + smallestEncompassingPowerOfTwo(storageX + newSlotWidth) - + storageX; + } + slot = new StitchSlot(storageX, 0, newSlotWidth, storageY); + // storageX += textureHolder->getWidth(); + storageX += newSlotWidth; + } else { + int newSlotHeight = textureHolder->getHeight(); + // 4J Stu - If we are expanding the texture, then allocate the full + // powerOfTwo size that we are going to eventually create + if (forcePowerOfTwo) { + newSlotHeight = + smallestEncompassingPowerOfTwo(storageY + newSlotHeight) - + storageY; + } - int newSlotWidth = textureHolder->getWidth(); - // 4J Stu - If we are expanding the texture, then allocate the full powerOfTwo size that we are going to eventually create - if (forcePowerOfTwo) - { - newSlotWidth = smallestEncompassingPowerOfTwo(storageX + newSlotWidth) - storageX; - } - slot = new StitchSlot(storageX, 0, newSlotWidth, storageY); - //storageX += textureHolder->getWidth(); - storageX += newSlotWidth; - } - else - { - int newSlotHeight = textureHolder->getHeight(); - // 4J Stu - If we are expanding the texture, then allocate the full powerOfTwo size that we are going to eventually create - if (forcePowerOfTwo) - { - newSlotHeight = smallestEncompassingPowerOfTwo(storageY + newSlotHeight) - storageY; - } + // grow on Y + slot = new StitchSlot(0, storageY, storageX, newSlotHeight); + // storageY += textureHolder->getHeight(); + storageY += newSlotHeight; + } - // grow on Y - slot = new StitchSlot(0, storageY, storageX, newSlotHeight); - //storageY += textureHolder->getHeight(); - storageY += newSlotHeight; - } + slot->add(textureHolder); + storage.push_back(slot); - slot->add(textureHolder); - storage.push_back(slot); - - return true; + return true; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/Stitcher.h b/Minecraft.Client/Textures/Stitching/Stitcher.h index 7ade956a8..ca5c7846a 100644 --- a/Minecraft.Client/Textures/Stitching/Stitcher.h +++ b/Minecraft.Client/Textures/Stitching/Stitcher.h @@ -1,60 +1,64 @@ #pragma once - class StitchSlot; class Texture; #include "../TextureHolder.h" -class Stitcher -{ +class Stitcher { public: - static const int STITCH_SUCCESS = 0; - static const int STITCH_RETRY = 1; - static const int STITCH_ABORT = 2; + static const int STITCH_SUCCESS = 0; + static const int STITCH_RETRY = 1; + static const int STITCH_ABORT = 2; - static const int MAX_MIPLEVEL = 0; // This should be 4 again later when we *ACTUALLY* mipmap - static const int MIN_TEXEL = 1 << MAX_MIPLEVEL; + static const int MAX_MIPLEVEL = + 0; // This should be 4 again later when we *ACTUALLY* mipmap + static const int MIN_TEXEL = 1 << MAX_MIPLEVEL; private: - std::set texturesToBeStitched; // = new HashSet(256); - std::vector storage; // = new ArrayList(256); - int storageX; - int storageY; + std::set + texturesToBeStitched; // = new HashSet(256); + std::vector storage; // = new ArrayList(256); + int storageX; + int storageY; - int maxWidth; - int maxHeight; - bool forcePowerOfTwo; - int forcedScale; + int maxWidth; + int maxHeight; + bool forcePowerOfTwo; + int forcedScale; - Texture *stitchedTexture; + Texture* stitchedTexture; - std::wstring name; + std::wstring name; - void _init(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale); + void _init(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale); public: - Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo); - Stitcher(const std::wstring &name, int maxWidth, int maxHeight, bool forcePowerOfTwo, int forcedScale); + Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo); + Stitcher(const std::wstring& name, int maxWidth, int maxHeight, + bool forcePowerOfTwo, int forcedScale); - int getWidth(); - int getHeight(); - void addTexture(TextureHolder *textureHolder); - Texture *constructTexture(bool mipmap = true); // 4J Added mipmap param - void stitch(); - std::vector *gatherAreas(); + int getWidth(); + int getHeight(); + void addTexture(TextureHolder* textureHolder); + Texture* constructTexture(bool mipmap = true); // 4J Added mipmap param + void stitch(); + std::vector* gatherAreas(); -private: - // Based on: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 - int smallestEncompassingPowerOfTwo(int input); +private: + // Based on: + // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 + int smallestEncompassingPowerOfTwo(int input); - bool addToStorage(TextureHolder *textureHolder); + bool addToStorage(TextureHolder* textureHolder); - /** - * Expand the current storage to take in account the new texture. - * This should only be called if it didn't fit anywhere. - * - * @param textureHolder - * @return Boolean indicating if it could accommodate for the growth - */ - bool expand(TextureHolder *textureHolder); + /** + * Expand the current storage to take in account the new texture. + * This should only be called if it didn't fit anywhere. + * + * @param textureHolder + * @return Boolean indicating if it could accommodate for the growth + */ + bool expand(TextureHolder* textureHolder); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/TextureMap.cpp b/Minecraft.Client/Textures/Stitching/TextureMap.cpp index dc8efa546..a0af280bb 100644 --- a/Minecraft.Client/Textures/Stitching/TextureMap.cpp +++ b/Minecraft.Client/Textures/Stitching/TextureMap.cpp @@ -17,232 +17,234 @@ const std::wstring TextureMap::NAME_MISSING_TEXTURE = L"missingno"; -TextureMap::TextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipmap) : iconType(type), name(name), path(path), extension(L".png") -{ - this->missingTexture = missingTexture; +TextureMap::TextureMap(int type, const std::wstring& name, + const std::wstring& path, BufferedImage* missingTexture, + bool mipmap) + : iconType(type), name(name), path(path), extension(L".png") { + this->missingTexture = missingTexture; - // 4J Initialisers - missingPosition = NULL; - stitchResult = NULL; + // 4J Initialisers + missingPosition = NULL; + stitchResult = NULL; - m_mipMap = mipmap; + m_mipMap = mipmap; } -void TextureMap::stitch() -{ - texturesToRegister.clear(); +void TextureMap::stitch() { + texturesToRegister.clear(); - if (iconType == Icon::TYPE_TERRAIN) - { - //for (Tile tile : Tile.tiles) - for(unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) - { - if (Tile::tiles[i] != NULL) - { - Tile::tiles[i]->registerIcons(this); - } - } + if (iconType == Icon::TYPE_TERRAIN) { + // for (Tile tile : Tile.tiles) + for (unsigned int i = 0; i < Tile::TILE_NUM_COUNT; ++i) { + if (Tile::tiles[i] != NULL) { + Tile::tiles[i]->registerIcons(this); + } + } - Minecraft::GetInstance()->levelRenderer->registerTextures(this); - EntityRenderDispatcher::instance->registerTerrainTextures(this); - } + Minecraft::GetInstance()->levelRenderer->registerTextures(this); + EntityRenderDispatcher::instance->registerTerrainTextures(this); + } - //for (Item item : Item.items) - for(unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) - { - Item *item = Item::items[i]; - if (item != NULL && item->getIconType() == iconType) - { - item->registerIcons(this); - } - } + // for (Item item : Item.items) + for (unsigned int i = 0; i < Item::ITEM_NUM_COUNT; ++i) { + Item* item = Item::items[i]; + if (item != NULL && item->getIconType() == iconType) { + item->registerIcons(this); + } + } - // Collection bucket for multiple frames per texture - std::unordered_map * > textures; // = new HashMap>(); + // Collection bucket for multiple frames per texture + std::unordered_map*> + textures; // = new HashMap>(); - Stitcher *stitcher = TextureManager::getInstance()->createStitcher(name); - - for(AUTO_VAR(it,texturesByName.begin()); it != texturesByName.end(); ++it) - { - delete it->second; - } - texturesByName.clear(); - animatedTextures.clear(); + Stitcher* stitcher = TextureManager::getInstance()->createStitcher(name); - // Prep missing texture -- anything that has no resources will get pointed at this one - Texture *missingTex = TextureManager::getInstance()->createTexture(NAME_MISSING_TEXTURE, Texture::TM_CONTAINER, missingTexture->getWidth(), missingTexture->getHeight(), Texture::WM_CLAMP, Texture::TFMT_RGBA, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, m_mipMap, missingTexture); - TextureHolder *missingHolder = new TextureHolder(missingTex); + for (AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); + ++it) { + delete it->second; + } + texturesByName.clear(); + animatedTextures.clear(); - stitcher->addTexture(missingHolder); - std::vector *missingVec = new std::vector(); - missingVec->push_back(missingTex); - textures.insert( std::unordered_map * >::value_type( missingHolder, missingVec )); + // Prep missing texture -- anything that has no resources will get pointed + // at this one + Texture* missingTex = TextureManager::getInstance()->createTexture( + NAME_MISSING_TEXTURE, Texture::TM_CONTAINER, missingTexture->getWidth(), + missingTexture->getHeight(), Texture::WM_CLAMP, Texture::TFMT_RGBA, + Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, m_mipMap, missingTexture); + TextureHolder* missingHolder = new TextureHolder(missingTex); - // Extract frames from textures and add them to the stitchers - //for (final String name : texturesToRegister.keySet()) - for(AUTO_VAR(it, texturesToRegister.begin()); it != texturesToRegister.end(); ++it) - { - std::wstring name = it->first; + stitcher->addTexture(missingHolder); + std::vector* missingVec = new std::vector(); + missingVec->push_back(missingTex); + textures.insert( + std::unordered_map*>::value_type( + missingHolder, missingVec)); - std::wstring filename = path + name + extension; + // Extract frames from textures and add them to the stitchers + // for (final String name : texturesToRegister.keySet()) + for (AUTO_VAR(it, texturesToRegister.begin()); + it != texturesToRegister.end(); ++it) { + std::wstring name = it->first; - // TODO: [EB] Put the frames into a proper object, not this inside out hack - std::vector *frames = TextureManager::getInstance()->createTextures(filename, m_mipMap); + std::wstring filename = path + name + extension; - if (frames == NULL || frames->empty()) - { - continue; // Couldn't load a texture, skip it - } + // TODO: [EB] Put the frames into a proper object, not this inside out + // hack + std::vector* frames = + TextureManager::getInstance()->createTextures(filename, m_mipMap); - TextureHolder *holder = new TextureHolder(frames->at(0)); - stitcher->addTexture(holder); + if (frames == NULL || frames->empty()) { + continue; // Couldn't load a texture, skip it + } - // Store frames - textures.insert( std::unordered_map * >::value_type( holder, frames ) ); - } + TextureHolder* holder = new TextureHolder(frames->at(0)); + stitcher->addTexture(holder); - // Stitch! - //try { - stitcher->stitch(); - //} catch (StitcherException e) { - // throw e; - // TODO: [EB] Retry mechanism - //} + // Store frames + textures.insert( + std::unordered_map*>::value_type(holder, + frames)); + } - // Create the final image - stitchResult = stitcher->constructTexture(m_mipMap); + // Stitch! + // try { + stitcher->stitch(); + //} catch (StitcherException e) { + // throw e; + // TODO: [EB] Retry mechanism + //} - // Extract all the final positions and store them - AUTO_VAR(areas, stitcher->gatherAreas()); - //for (StitchSlot slot : stitcher.gatherAreas()) - for(AUTO_VAR(it, areas->begin()); it != areas->end(); ++it) - { - StitchSlot *slot = *it; - TextureHolder *textureHolder = slot->getHolder(); + // Create the final image + stitchResult = stitcher->constructTexture(m_mipMap); - Texture *texture = textureHolder->getTexture(); - std::wstring textureName = texture->getName(); + // Extract all the final positions and store them + AUTO_VAR(areas, stitcher->gatherAreas()); + // for (StitchSlot slot : stitcher.gatherAreas()) + for (AUTO_VAR(it, areas->begin()); it != areas->end(); ++it) { + StitchSlot* slot = *it; + TextureHolder* textureHolder = slot->getHolder(); - std::vector *frames = textures.find(textureHolder)->second; + Texture* texture = textureHolder->getTexture(); + std::wstring textureName = texture->getName(); - StitchedTexture *stored = NULL; - - AUTO_VAR(itTex, texturesToRegister.find(textureName) ); - if(itTex != texturesToRegister.end() ) stored = itTex->second; + std::vector* frames = textures.find(textureHolder)->second; - // [EB]: What is this code for? debug warnings for when during transition? - bool missing = false; - if (stored == NULL) - { - missing = true; - stored = StitchedTexture::create(textureName); + StitchedTexture* stored = NULL; - if (textureName.compare(NAME_MISSING_TEXTURE)!=0) - { - //Minecraft::getInstance()->getLogger().warning("Couldn't find premade icon for " + textureName + " doing " + name); + AUTO_VAR(itTex, texturesToRegister.find(textureName)); + if (itTex != texturesToRegister.end()) stored = itTex->second; + + // [EB]: What is this code for? debug warnings for when during + // transition? + bool missing = false; + if (stored == NULL) { + missing = true; + stored = StitchedTexture::create(textureName); + + if (textureName.compare(NAME_MISSING_TEXTURE) != 0) { + // Minecraft::getInstance()->getLogger().warning("Couldn't find + // premade icon for " + textureName + " doing " + name); #ifndef _CONTENT_PACKAGE - wprintf(L"Couldn't find premade icon for %ls doing %ls\n", textureName.c_str(), name.c_str() ); + wprintf(L"Couldn't find premade icon for %ls doing %ls\n", + textureName.c_str(), name.c_str()); #endif - } - } + } + } - stored->init(stitchResult, frames, slot->getX(), slot->getY(), textureHolder->getTexture()->getWidth(), textureHolder->getTexture()->getHeight(), textureHolder->isRotated()); + stored->init(stitchResult, frames, slot->getX(), slot->getY(), + textureHolder->getTexture()->getWidth(), + textureHolder->getTexture()->getHeight(), + textureHolder->isRotated()); - texturesByName.insert( stringStitchedTextureMap::value_type(textureName, stored) ); - if (!missing) texturesToRegister.erase(textureName); + texturesByName.insert( + stringStitchedTextureMap::value_type(textureName, stored)); + if (!missing) texturesToRegister.erase(textureName); - if (frames->size() > 1) - { - animatedTextures.push_back(stored); + if (frames->size() > 1) { + animatedTextures.push_back(stored); - std::wstring animationDefinitionFile = textureName + L".txt"; + std::wstring animationDefinitionFile = textureName + L".txt"; - TexturePack *texturePack = Minecraft::GetInstance()->skins->getSelected(); - bool requiresFallback = !texturePack->hasFile(L"\\" + textureName + L".png", false); - //try { - InputStream *fileStream = texturePack->getResource(L"\\" + path + animationDefinitionFile, requiresFallback); + TexturePack* texturePack = + Minecraft::GetInstance()->skins->getSelected(); + bool requiresFallback = + !texturePack->hasFile(L"\\" + textureName + L".png", false); + // try { + InputStream* fileStream = texturePack->getResource( + L"\\" + path + animationDefinitionFile, requiresFallback); - //Minecraft::getInstance()->getLogger().info("Found animation info for: " + animationDefinitionFile); + // Minecraft::getInstance()->getLogger().info("Found animation info + // for: " + animationDefinitionFile); #ifndef _CONTENT_PACKAGE - wprintf(L"Found animation info for: %ls\n", animationDefinitionFile.c_str() ); + wprintf(L"Found animation info for: %ls\n", + animationDefinitionFile.c_str()); #endif - InputStreamReader isr(fileStream); - BufferedReader br(&isr); - stored->loadAnimationFrames(&br); - delete fileStream; - //} catch (IOException ignored) { - //} - } - } - delete areas; + InputStreamReader isr(fileStream); + BufferedReader br(&isr); + stored->loadAnimationFrames(&br); + delete fileStream; + //} catch (IOException ignored) { + //} + } + } + delete areas; - missingPosition = texturesByName.find(NAME_MISSING_TEXTURE)->second; + missingPosition = texturesByName.find(NAME_MISSING_TEXTURE)->second; - //for (StitchedTexture texture : texturesToRegister.values()) - for(AUTO_VAR(it, texturesToRegister.begin() ); it != texturesToRegister.end(); ++it) - { - StitchedTexture *texture = it->second; - texture->replaceWith(missingPosition); - } + // for (StitchedTexture texture : texturesToRegister.values()) + for (AUTO_VAR(it, texturesToRegister.begin()); + it != texturesToRegister.end(); ++it) { + StitchedTexture* texture = it->second; + texture->replaceWith(missingPosition); + } - stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); - stitchResult->updateOnGPU(); + stitchResult->writeAsPNG(L"debug.stitched_" + name + L".png"); + stitchResult->updateOnGPU(); } -StitchedTexture *TextureMap::getTexture(const std::wstring &name) -{ - StitchedTexture *result = texturesByName.find(name)->second; - if (result == NULL) result = missingPosition; - return result; +StitchedTexture* TextureMap::getTexture(const std::wstring& name) { + StitchedTexture* result = texturesByName.find(name)->second; + if (result == NULL) result = missingPosition; + return result; } -void TextureMap::cycleAnimationFrames() -{ - //for (StitchedTexture texture : animatedTextures) - for(AUTO_VAR(it, animatedTextures.begin() ); it != animatedTextures.end(); ++it) - { - StitchedTexture *texture = *it; - texture->cycleFrames(); - } +void TextureMap::cycleAnimationFrames() { + // for (StitchedTexture texture : animatedTextures) + for (AUTO_VAR(it, animatedTextures.begin()); it != animatedTextures.end(); + ++it) { + StitchedTexture* texture = *it; + texture->cycleFrames(); + } } -Texture *TextureMap::getStitchedTexture() -{ - return stitchResult; -} +Texture* TextureMap::getStitchedTexture() { return stitchResult; } // 4J Stu - register is a reserved keyword in C++ -Icon *TextureMap::registerIcon(const std::wstring &name) -{ - if (name.empty()) - { - app.DebugPrintf("Don't register NULL\n"); +Icon* TextureMap::registerIcon(const std::wstring& name) { + if (name.empty()) { + app.DebugPrintf("Don't register NULL\n"); #ifndef _CONTENT_PACKAGE - __debugbreak(); + __debugbreak(); #endif - //new RuntimeException("Don't register null!").printStackTrace(); - } + // new RuntimeException("Don't register null!").printStackTrace(); + } - // TODO: [EB]: Why do we allow multiple registrations? - StitchedTexture *result = NULL; - AUTO_VAR(it, texturesToRegister.find(name)); - if(it != texturesToRegister.end()) result = it->second; + // TODO: [EB]: Why do we allow multiple registrations? + StitchedTexture* result = NULL; + AUTO_VAR(it, texturesToRegister.find(name)); + if (it != texturesToRegister.end()) result = it->second; - if (result == NULL) - { - result = StitchedTexture::create(name); - texturesToRegister.insert( stringStitchedTextureMap::value_type(name, result) ); - } + if (result == NULL) { + result = StitchedTexture::create(name); + texturesToRegister.insert( + stringStitchedTextureMap::value_type(name, result)); + } - return result; + return result; } -int TextureMap::getIconType() -{ - return iconType; -} +int TextureMap::getIconType() { return iconType; } -Icon *TextureMap::getMissingIcon() -{ - return missingPosition; -} \ No newline at end of file +Icon* TextureMap::getMissingIcon() { return missingPosition; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/Stitching/TextureMap.h b/Minecraft.Client/Textures/Stitching/TextureMap.h index af13345ef..d139b1e4e 100644 --- a/Minecraft.Client/Textures/Stitching/TextureMap.h +++ b/Minecraft.Client/Textures/Stitching/TextureMap.h @@ -1,46 +1,50 @@ #pragma once - #include "../../../Minecraft.World/Util/IconRegister.h" class StitchedTexture; class Texture; class BufferedImage; -class TextureMap : public IconRegister -{ +class TextureMap : public IconRegister { public: - static const std::wstring NAME_MISSING_TEXTURE; + static const std::wstring NAME_MISSING_TEXTURE; private: - const int iconType; + const int iconType; - const std::wstring name; - const std::wstring path; - const std::wstring extension; + const std::wstring name; + const std::wstring path; + const std::wstring extension; - bool m_mipMap; + bool m_mipMap; - typedef std::unordered_map stringStitchedTextureMap; - stringStitchedTextureMap texturesByName; // = new HashMap(); - BufferedImage *missingTexture; // = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); - StitchedTexture *missingPosition; - Texture *stitchResult; - std::vector animatedTextures; // = new ArrayList(); + typedef std::unordered_map + stringStitchedTextureMap; + stringStitchedTextureMap + texturesByName; // = new HashMap(); + BufferedImage* missingTexture; // = new BufferedImage(64, 64, + // BufferedImage.TYPE_INT_ARGB); + StitchedTexture* missingPosition; + Texture* stitchResult; + std::vector + animatedTextures; // = new ArrayList(); - stringStitchedTextureMap texturesToRegister; // = new HashMap(); + stringStitchedTextureMap + texturesToRegister; // = new HashMap(); public: - TextureMap(int type, const std::wstring &name, const std::wstring &path, BufferedImage *missingTexture, bool mipMap = false); + TextureMap(int type, const std::wstring& name, const std::wstring& path, + BufferedImage* missingTexture, bool mipMap = false); - void stitch(); - StitchedTexture *getTexture(const std::wstring &name); - void cycleAnimationFrames(); - Texture *getStitchedTexture(); + void stitch(); + StitchedTexture* getTexture(const std::wstring& name); + void cycleAnimationFrames(); + Texture* getStitchedTexture(); - // 4J Stu - register is a reserved keyword in C++ - Icon *registerIcon(const std::wstring &name); + // 4J Stu - register is a reserved keyword in C++ + Icon* registerIcon(const std::wstring& name); - int getIconType(); - Icon *getMissingIcon(); + int getIconType(); + Icon* getMissingIcon(); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Texture.cpp b/Minecraft.Client/Textures/Texture.cpp index f01691229..efed2bb17 100644 --- a/Minecraft.Client/Textures/Texture.cpp +++ b/Minecraft.Client/Textures/Texture.cpp @@ -8,243 +8,229 @@ #include "../Platform/PS3/SPU_Tasks/Texture_blit/Texture_blit.h" #include "../Platform/PS3/PS3Extras/C4JSpursJob.h" static const int sc_maxTextureBlits = 256; -static Texture_blit_DataIn g_textureBlitDataIn[sc_maxTextureBlits] __attribute__((__aligned__(16))); +static Texture_blit_DataIn g_textureBlitDataIn[sc_maxTextureBlits] + __attribute__((__aligned__(16))); static int g_currentTexBlit = 0; C4JSpursJobQueue::Port* g_texBlitJobQueuePort; -#endif //__PS3__ +#endif //__PS3__ #define MAX_MIP_LEVELS 5 -Texture::Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap) -{ - _init(name, mode, width, height, depth, wrapMode, format, minFilter, magFilter, mipMap); +Texture::Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, bool mipMap) { + _init(name, mode, width, height, depth, wrapMode, format, minFilter, + magFilter, mipMap); } -void Texture::_init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap) -{ +void Texture::_init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, bool mipMap) { #ifdef __PS3__ - if(g_texBlitJobQueuePort == NULL) - g_texBlitJobQueuePort = new C4JSpursJobQueue::Port("C4JSpursJob_Texture_blit"); + if (g_texBlitJobQueuePort == NULL) + g_texBlitJobQueuePort = + new C4JSpursJobQueue::Port("C4JSpursJob_Texture_blit"); #endif - this->name = name; - this->mode = mode; - this->width = width; - this->height = height; - this->depth = depth; - this->format = format; - this->minFilter = minFilter; - this->magFilter = magFilter; - this->wrapMode = wrapMode; - immediateUpdate = false; - m_bInitialised = false; - for( int i = 0 ; i < 10; i++ ) - { - data[i] = NULL; - } + this->name = name; + this->mode = mode; + this->width = width; + this->height = height; + this->depth = depth; + this->format = format; + this->minFilter = minFilter; + this->magFilter = magFilter; + this->wrapMode = wrapMode; + immediateUpdate = false; + m_bInitialised = false; + for (int i = 0; i < 10; i++) { + data[i] = NULL; + } - rect = new Rect2i(0, 0, width, height); - // 4J Removed 1D and 3D - //if (height == 1 && depth == 1) - //{ - // type = GL_TEXTURE_1D; - //} - //else if(depth == 1) - //{ - type = GL_TEXTURE_2D; - //} - //else - //{ - // type = GL_TEXTURE_3D; - //} + rect = new Rect2i(0, 0, width, height); + // 4J Removed 1D and 3D + // if (height == 1 && depth == 1) + //{ + // type = GL_TEXTURE_1D; + //} + // else if(depth == 1) + //{ + type = GL_TEXTURE_2D; + //} + // else + //{ + // type = GL_TEXTURE_3D; + //} - mipmapped = mipMap || (minFilter != GL_NEAREST && minFilter != GL_LINEAR) || - (magFilter != GL_NEAREST && magFilter != GL_LINEAR); - m_iMipLevels=1; - - if(mipmapped) - { - // 4J-PB - In the new XDK, the CreateTexture will fail if the number of mipmaps is higher than the width & height passed in will allow! - int iWidthMips=1; - int iHeightMips=1; - while((8< MAX_MIP_LEVELS) m_iMipLevels = MAX_MIP_LEVELS; - } + if (mipmapped) { + // 4J-PB - In the new XDK, the CreateTexture will fail if the number of + // mipmaps is higher than the width & height passed in will allow! + int iWidthMips = 1; + int iHeightMips = 1; + while ((8 << iWidthMips) < width) iWidthMips++; + while ((8 << iHeightMips) < height) iHeightMips++; + + m_iMipLevels = (iWidthMips < iHeightMips) ? iWidthMips : iHeightMips; + + // TODO - The render libs currently limit max mip map levels to 5 + if (m_iMipLevels > MAX_MIP_LEVELS) m_iMipLevels = MAX_MIP_LEVELS; + } #ifdef __PSVITA__ - // vita doesn't have a mipmap conditional shader because it's too slow so make sure this texture don't look awful at the lower mips - if( name == L"terrain" ) - { - m_iMipLevels = 3; - } + // vita doesn't have a mipmap conditional shader because it's too slow so + // make sure this texture don't look awful at the lower mips + if (name == L"terrain") { + m_iMipLevels = 3; + } #endif - if (mode != TM_CONTAINER) - { - glId = glGenTextures(); + if (mode != TM_CONTAINER) { + glId = glGenTextures(); - glBindTexture(type, glId); - glTexParameteri(type, GL_TEXTURE_MIN_FILTER, minFilter); - glTexParameteri(type, GL_TEXTURE_MAG_FILTER, magFilter); - glTexParameteri(type, GL_TEXTURE_WRAP_S, wrapMode); - glTexParameteri(type, GL_TEXTURE_WRAP_T, wrapMode); - } - else - { - glId = -1; - } + glBindTexture(type, glId); + glTexParameteri(type, GL_TEXTURE_MIN_FILTER, minFilter); + glTexParameteri(type, GL_TEXTURE_MAG_FILTER, magFilter); + glTexParameteri(type, GL_TEXTURE_WRAP_S, wrapMode); + glTexParameteri(type, GL_TEXTURE_WRAP_T, wrapMode); + } else { + glId = -1; + } - managerId = TextureManager::getInstance()->createTextureID(); + managerId = TextureManager::getInstance()->createTextureID(); } -void Texture::_init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap) -{ - _init(name, mode, width, height, depth, wrapMode, format, minFilter, magFilter, mipMap); - if (image == NULL) - { - if (width == -1 || height == -1) - { - valid = false; - } - else - { - byteArray tempBytes = byteArray(width * height * depth * 4); - for (int index = 0; index < tempBytes.length; index++) - { - tempBytes[index] = 0; - } +void Texture::_init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, BufferedImage* image, bool mipMap) { + _init(name, mode, width, height, depth, wrapMode, format, minFilter, + magFilter, mipMap); + if (image == NULL) { + if (width == -1 || height == -1) { + valid = false; + } else { + byteArray tempBytes = byteArray(width * height * depth * 4); + for (int index = 0; index < tempBytes.length; index++) { + tempBytes[index] = 0; + } #ifdef __PS3__ - data[0] = new ByteBuffer_IO(tempBytes.length); + data[0] = new ByteBuffer_IO(tempBytes.length); #else - data[0] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __{S3__ - data[0]->clear(); - data[0]->put(tempBytes); - data[0]->position(0)->limit(tempBytes.length); + data[0] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __{S3__ + data[0]->clear(); + data[0]->put(tempBytes); + data[0]->position(0)->limit(tempBytes.length); - delete [] tempBytes.data; + delete[] tempBytes.data; - if(mipmapped) - { - for(unsigned int level = 1; level < m_iMipLevels; ++level) - { - int ww = width >> level; - int hh = height >> level; + if (mipmapped) { + for (unsigned int level = 1; level < m_iMipLevels; ++level) { + int ww = width >> level; + int hh = height >> level; - byteArray tempBytes = byteArray(ww * hh * depth * 4); - for (int index = 0; index < tempBytes.length; index++) - { - tempBytes[index] = 0; - } + byteArray tempBytes = byteArray(ww * hh * depth * 4); + for (int index = 0; index < tempBytes.length; index++) { + tempBytes[index] = 0; + } #ifdef __PS3__ - data[level] = new ByteBuffer_IO(tempBytes.length); + data[level] = new ByteBuffer_IO(tempBytes.length); #else - data[level] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __PS3__ - data[level]->clear(); - data[level]->put(tempBytes); - data[level]->position(0)->limit(tempBytes.length); + data[level] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __PS3__ + data[level]->clear(); + data[level]->put(tempBytes); + data[level]->position(0)->limit(tempBytes.length); - delete [] tempBytes.data; - } - } + delete[] tempBytes.data; + } + } - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } - } - } - else - { - valid = true; + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } + } + } else { + valid = true; - transferFromImage(image); + transferFromImage(image); - if (mode != TM_CONTAINER) - { - updateOnGPU(); - immediateUpdate = false; - } - } + if (mode != TM_CONTAINER) { + updateOnGPU(); + immediateUpdate = false; + } + } } -Texture::Texture(const std::wstring &name, int mode, int width, int height, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap) -{ - _init(name, mode, width, height, 1, wrapMode, format, minFilter, magFilter, image, mipMap); +Texture::Texture(const std::wstring& name, int mode, int width, int height, + int wrapMode, int format, int minFilter, int magFilter, + BufferedImage* image, bool mipMap) { + _init(name, mode, width, height, 1, wrapMode, format, minFilter, magFilter, + image, mipMap); } -Texture::Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap) -{ - _init(name, mode, width, height, depth, wrapMode, format, minFilter, magFilter, image, mipMap); +Texture::Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, BufferedImage* image, bool mipMap) { + _init(name, mode, width, height, depth, wrapMode, format, minFilter, + magFilter, image, mipMap); } -Texture::~Texture() -{ - delete rect; - - for(int i = 0; i < 10; i++ ) - { - if(data[i] != NULL) delete data[i]; - } +Texture::~Texture() { + delete rect; - if(glId >= 0) - { - glDeleteTextures(glId); - } + for (int i = 0; i < 10; i++) { + if (data[i] != NULL) delete data[i]; + } + + if (glId >= 0) { + glDeleteTextures(glId); + } } -const Rect2i *Texture::getRect() -{ - return rect; +const Rect2i* Texture::getRect() { return rect; } + +void Texture::fill(const Rect2i* rect, int color) { + // 4J Remove 3D + // if (type == GL_TEXTURE_3D) + //{ + // return; + //} + + Rect2i* myRect = new Rect2i(0, 0, width, height); + myRect->intersect(rect); + data[0]->position(0); + for (int y = myRect->getY(); y < (myRect->getY() + myRect->getHeight()); + y++) { + int line = y * width * 4; + for (int x = myRect->getX(); x < (myRect->getX() + myRect->getWidth()); + x++) { + data[0]->put(line + x * 4 + 0, + static_cast((color >> 24) & 0x000000ff)); + data[0]->put(line + x * 4 + 1, + static_cast((color >> 16) & 0x000000ff)); + data[0]->put(line + x * 4 + 2, + static_cast((color >> 8) & 0x000000ff)); + data[0]->put(line + x * 4 + 3, + static_cast((color >> 0) & 0x000000ff)); + } + } + delete myRect; + + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } } -void Texture::fill(const Rect2i *rect, int color) -{ - // 4J Remove 3D - //if (type == GL_TEXTURE_3D) - //{ - // return; - //} - - Rect2i *myRect = new Rect2i(0, 0, width, height); - myRect->intersect(rect); - data[0]->position(0); - for (int y = myRect->getY(); y < (myRect->getY() + myRect->getHeight()); y++) - { - int line = y * width * 4; - for (int x = myRect->getX(); x < (myRect->getX() + myRect->getWidth()); x++) - { - data[0]->put(line + x * 4 + 0, static_cast((color >> 24) & 0x000000ff)); - data[0]->put(line + x * 4 + 1, static_cast((color >> 16) & 0x000000ff)); - data[0]->put(line + x * 4 + 2, static_cast((color >> 8) & 0x000000ff)); - data[0]->put(line + x * 4 + 3, static_cast((color >> 0) & 0x000000ff)); - } - } - delete myRect; - - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } -} - -void Texture::writeAsBMP(const std::wstring &name) -{ - // 4J Don't need +void Texture::writeAsBMP(const std::wstring& name) { + // 4J Don't need #if 0 if (type == GL_TEXTURE_3D) { @@ -329,9 +315,8 @@ void Texture::writeAsBMP(const std::wstring &name) #endif } -void Texture::writeAsPNG(const std::wstring &filename) -{ - // 4J Don't need +void Texture::writeAsPNG(const std::wstring& filename) { + // 4J Don't need #if 0 BufferedImage *image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); ByteBuffer *buffer = this->getData(); @@ -366,535 +351,507 @@ void Texture::writeAsPNG(const std::wstring &filename) #endif } -void Texture::blit(int x, int y, Texture *source) -{ - blit(x, y, source, false); -} +void Texture::blit(int x, int y, Texture* source) { blit(x, y, source, false); } -void Texture::blit(int x, int y, Texture *source, bool rotated) -{ - // 4J Remove 3D - //if (type == GL_TEXTURE_3D) - //{ - // return; - //} +void Texture::blit(int x, int y, Texture* source, bool rotated) { + // 4J Remove 3D + // if (type == GL_TEXTURE_3D) + //{ + // return; + //} - for(unsigned int level = 0; level < m_iMipLevels; ++level) - { - ByteBuffer *srcBuffer = source->getData(level); + for (unsigned int level = 0; level < m_iMipLevels; ++level) { + ByteBuffer* srcBuffer = source->getData(level); - if(srcBuffer == NULL) break; + if (srcBuffer == NULL) break; - int yy = y >> level; - int xx = x >> level; - int hh = height >> level; - int ww = width >> level; - int shh = source->getHeight() >> level; - int sww = source->getWidth() >> level; + int yy = y >> level; + int xx = x >> level; + int hh = height >> level; + int ww = width >> level; + int shh = source->getHeight() >> level; + int sww = source->getWidth() >> level; - data[level]->position(0); - srcBuffer->position(0); + data[level]->position(0); + srcBuffer->position(0); #if defined __PS3__ && !defined DISABLE_SPU_CODE - if(g_texBlitJobQueuePort->hasCompleted()) - { - // all outstanding blits have completed, so reset to the start of the blit list - g_currentTexBlit = 0; - } - Texture_blit_DataIn& dataIn = g_textureBlitDataIn[g_currentTexBlit]; - g_currentTexBlit++; - if(g_currentTexBlit >= sc_maxTextureBlits) - { - app.DebugPrintf("ran out of tex blit slots, stalling for completion\n"); - g_texBlitJobQueuePort->waitForCompletion(); - g_currentTexBlit = 0; - } - dataIn.pSrcData = srcBuffer->getBuffer(); - dataIn.pDstData = data[level]->getBuffer(); - dataIn.yy = yy; - dataIn.xx = xx; - dataIn.hh = hh; - dataIn.ww = ww; - dataIn.shh = shh; - dataIn.sww = sww; - dataIn.rotated = rotated; + if (g_texBlitJobQueuePort->hasCompleted()) { + // all outstanding blits have completed, so reset to the start of + // the blit list + g_currentTexBlit = 0; + } + Texture_blit_DataIn& dataIn = g_textureBlitDataIn[g_currentTexBlit]; + g_currentTexBlit++; + if (g_currentTexBlit >= sc_maxTextureBlits) { + app.DebugPrintf( + "ran out of tex blit slots, stalling for completion\n"); + g_texBlitJobQueuePort->waitForCompletion(); + g_currentTexBlit = 0; + } + dataIn.pSrcData = srcBuffer->getBuffer(); + dataIn.pDstData = data[level]->getBuffer(); + dataIn.yy = yy; + dataIn.xx = xx; + dataIn.hh = hh; + dataIn.ww = ww; + dataIn.shh = shh; + dataIn.sww = sww; + dataIn.rotated = rotated; - C4JSpursJob_Texture_blit blitJob(&dataIn); - g_texBlitJobQueuePort->submitJob(&blitJob); -// p.waitForCompletion(); + C4JSpursJob_Texture_blit blitJob(&dataIn); + g_texBlitJobQueuePort->submitJob(&blitJob); + // p.waitForCompletion(); #elif __PSVITA__ - unsigned int *src = (unsigned int *) srcBuffer->getBuffer(); - unsigned int *dst = (unsigned int *) data[level]->getBuffer(); + unsigned int* src = (unsigned int*)srcBuffer->getBuffer(); + unsigned int* dst = (unsigned int*)data[level]->getBuffer(); - for (int srcY = 0; srcY < shh; srcY++) - { - int dstY = yy + srcY; - int srcLine = srcY * sww; - int dstLine = dstY * ww; + for (int srcY = 0; srcY < shh; srcY++) { + int dstY = yy + srcY; + int srcLine = srcY * sww; + int dstLine = dstY * ww; - if (rotated) - { - dstY = yy + (shh - srcY); - } + if (rotated) { + dstY = yy + (shh - srcY); + } - if (!rotated) - { - memcpy(dst + dstLine + xx, src + srcLine, sww * 4); - } - else - { - for (int srcX = 0; srcX < sww; srcX++) - { - int dstPos = dstLine + (srcX + xx); - int srcPos = srcLine + srcX; + if (!rotated) { + memcpy(dst + dstLine + xx, src + srcLine, sww * 4); + } else { + for (int srcX = 0; srcX < sww; srcX++) { + int dstPos = dstLine + (srcX + xx); + int srcPos = srcLine + srcX; - if (rotated) - { - dstPos = (xx + srcX * ww) + dstY; - } + if (rotated) { + dstPos = (xx + srcX * ww) + dstY; + } - dst[dstPos] = src[srcPos]; - } - } - } + dst[dstPos] = src[srcPos]; + } + } + } #else - for (int srcY = 0; srcY < shh; srcY++) - { - int dstY = yy + srcY; - int srcLine = srcY * sww * 4; - int dstLine = dstY * ww * 4; + for (int srcY = 0; srcY < shh; srcY++) { + int dstY = yy + srcY; + int srcLine = srcY * sww * 4; + int dstLine = dstY * ww * 4; - if (rotated) - { - dstY = yy + (shh - srcY); - } + if (rotated) { + dstY = yy + (shh - srcY); + } - for (int srcX = 0; srcX < sww; srcX++) - { - int dstPos = dstLine + (srcX + xx) * 4; - int srcPos = srcLine + srcX * 4; + for (int srcX = 0; srcX < sww; srcX++) { + int dstPos = dstLine + (srcX + xx) * 4; + int srcPos = srcLine + srcX * 4; - if (rotated) - { - dstPos = (xx + srcX * ww * 4) + dstY * 4; - } + if (rotated) { + dstPos = (xx + srcX * ww * 4) + dstY * 4; + } - data[level]->put(dstPos + 0, srcBuffer->get(srcPos + 0)); - data[level]->put(dstPos + 1, srcBuffer->get(srcPos + 1)); - data[level]->put(dstPos + 2, srcBuffer->get(srcPos + 2)); - data[level]->put(dstPos + 3, srcBuffer->get(srcPos + 3)); - } - } - // Don't delete this, as it belongs to the source texture - //delete srcBuffer; + data[level]->put(dstPos + 0, srcBuffer->get(srcPos + 0)); + data[level]->put(dstPos + 1, srcBuffer->get(srcPos + 1)); + data[level]->put(dstPos + 2, srcBuffer->get(srcPos + 2)); + data[level]->put(dstPos + 3, srcBuffer->get(srcPos + 3)); + } + } + // Don't delete this, as it belongs to the source texture + // delete srcBuffer; #endif - data[level]->position(ww * hh * 4); - } + data[level]->position(ww * hh * 4); + } - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } } -void Texture::transferFromBuffer(intArray buffer) -{ - if (depth == 1) - { - return; - } +void Texture::transferFromBuffer(intArray buffer) { + if (depth == 1) { + return; + } -// #ifdef __PS3__ -// int byteRemapRGBA[] = { 3, 0, 1, 2 }; -// int byteRemapBGRA[] = { 3, 2, 1, 0 }; -// #else - int byteRemapRGBA[] = { 0, 1, 2, 3 }; - int byteRemapBGRA[] = { 2, 1, 0, 3 }; -// #endif - int *byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); + // #ifdef __PS3__ + // int byteRemapRGBA[] = { 3, 0, 1, 2 }; + // int byteRemapBGRA[] = { 3, 2, 1, 0 }; + // #else + int byteRemapRGBA[] = {0, 1, 2, 3}; + int byteRemapBGRA[] = {2, 1, 0, 3}; + // #endif + int* byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); - for (int z = 0; z < depth; z++) - { - int plane = z * height * width * 4; - for (int y = 0; y < height; y++) - { - int column = plane + y * width * 4; - for (int x = 0; x < width; x++) - { - int texel = column + x * 4; - data[0]->position(0); - data[0]->put(texel + byteRemap[0], (uint8_t)((buffer[texel >> 2] >> 24) & 0xff)); - data[0]->put(texel + byteRemap[1], (uint8_t)((buffer[texel >> 2] >> 16) & 0xff)); - data[0]->put(texel + byteRemap[2], (uint8_t)((buffer[texel >> 2] >> 8) & 0xff)); - data[0]->put(texel + byteRemap[3], (uint8_t)((buffer[texel >> 2] >> 0) & 0xff)); - } - } - } + for (int z = 0; z < depth; z++) { + int plane = z * height * width * 4; + for (int y = 0; y < height; y++) { + int column = plane + y * width * 4; + for (int x = 0; x < width; x++) { + int texel = column + x * 4; + data[0]->position(0); + data[0]->put(texel + byteRemap[0], + (uint8_t)((buffer[texel >> 2] >> 24) & 0xff)); + data[0]->put(texel + byteRemap[1], + (uint8_t)((buffer[texel >> 2] >> 16) & 0xff)); + data[0]->put(texel + byteRemap[2], + (uint8_t)((buffer[texel >> 2] >> 8) & 0xff)); + data[0]->put(texel + byteRemap[3], + (uint8_t)((buffer[texel >> 2] >> 0) & 0xff)); + } + } + } - data[0]->position(width * height * depth * 4); + data[0]->position(width * height * depth * 4); - updateOnGPU(); + updateOnGPU(); } -void Texture::transferFromImage(BufferedImage *image) -{ - // 4J Remove 3D - //if (type == GL_TEXTURE_3D) - //{ - // return; - //} +void Texture::transferFromImage(BufferedImage* image) { + // 4J Remove 3D + // if (type == GL_TEXTURE_3D) + //{ + // return; + //} - int imgWidth = image->getWidth(); - int imgHeight = image->getHeight(); - if (imgWidth > width || imgHeight > height) - { - //Minecraft::GetInstance().getLogger().warning("transferFromImage called with a BufferedImage with dimensions (" + - // imgWidth + ", " + imgHeight + ") larger than the Texture dimensions (" + width + - // ", " + height + "). Ignoring."); - app.DebugPrintf("transferFromImage called with a BufferedImage with dimensions (%d, %d) larger than the Texture dimensions (%d, %d). Ignoring.\n", imgWidth, imgHeight, width, height); - return; - } + int imgWidth = image->getWidth(); + int imgHeight = image->getHeight(); + if (imgWidth > width || imgHeight > height) { + // Minecraft::GetInstance().getLogger().warning("transferFromImage + // called with a BufferedImage with dimensions (" + imgWidth + ", " + + //imgHeight + ") larger than the Texture dimensions (" + width + + // ", " + height + "). Ignoring."); + app.DebugPrintf( + "transferFromImage called with a BufferedImage with dimensions " + "(%d, %d) larger than the Texture dimensions (%d, %d). Ignoring.\n", + imgWidth, imgHeight, width, height); + return; + } // #ifdef __PS3__ // int byteRemapRGBA[] = { 0, 1, 2, 3 }; // int byteRemapBGRA[] = { 2, 1, 0, 3 }; // #else #ifdef _XBOX - int byteRemapRGBA[] = { 0, 1, 2, 3 }; + int byteRemapRGBA[] = {0, 1, 2, 3}; #else - int byteRemapRGBA[] = { 3, 0, 1, 2 }; + int byteRemapRGBA[] = {3, 0, 1, 2}; #endif - int byteRemapBGRA[] = { 3, 2, 1, 0 }; -// #endif - int *byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); + int byteRemapBGRA[] = {3, 2, 1, 0}; + // #endif + int* byteRemap = ((format == TFMT_BGRA) ? byteRemapBGRA : byteRemapRGBA); - intArray tempPixels = intArray(width * height); - int transparency = image->getTransparency(); - image->getRGB(0, 0, width, height, tempPixels, 0, imgWidth); + intArray tempPixels = intArray(width * height); + int transparency = image->getTransparency(); + image->getRGB(0, 0, width, height, tempPixels, 0, imgWidth); - byteArray tempBytes = byteArray(width * height * 4); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - int intIndex = y * width + x; - int byteIndex = intIndex * 4; + byteArray tempBytes = byteArray(width * height * 4); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int intIndex = y * width + x; + int byteIndex = intIndex * 4; - // Pull ARGB bytes into either RGBA or BGRA depending on format + // Pull ARGB bytes into either RGBA or BGRA depending on format - tempBytes[byteIndex + byteRemap[0]] = (uint8_t)((tempPixels[intIndex] >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (uint8_t)((tempPixels[intIndex] >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (uint8_t)((tempPixels[intIndex] >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (uint8_t)((tempPixels[intIndex] >> 0) & 0xff); - } - } + tempBytes[byteIndex + byteRemap[0]] = + (uint8_t)((tempPixels[intIndex] >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = + (uint8_t)((tempPixels[intIndex] >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = + (uint8_t)((tempPixels[intIndex] >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = + (uint8_t)((tempPixels[intIndex] >> 0) & 0xff); + } + } - for(int i = 0; i < 10; i++ ) - { - if(data[i] != NULL) - { - delete data[i]; - data[i] = NULL; - } - } + for (int i = 0; i < 10; i++) { + if (data[i] != NULL) { + delete data[i]; + data[i] = NULL; + } + } - MemSect(51); + MemSect(51); #ifdef __PS3__ - data[0] = new ByteBuffer_IO(tempBytes.length); + data[0] = new ByteBuffer_IO(tempBytes.length); #else - data[0] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __{S3__ - MemSect(0); - data[0]->clear(); - data[0]->put(tempBytes); - data[0]->limit(tempBytes.length); + data[0] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __{S3__ + MemSect(0); + data[0]->clear(); + data[0]->put(tempBytes); + data[0]->limit(tempBytes.length); - delete [] tempBytes.data; + delete[] tempBytes.data; - if(mipmapped || image->getData(1) != NULL) - { - mipmapped = true; - for(unsigned int level = 1; level < MAX_MIP_LEVELS; ++level) - { - int ww = width >> level; - int hh = height >> level; + if (mipmapped || image->getData(1) != NULL) { + mipmapped = true; + for (unsigned int level = 1; level < MAX_MIP_LEVELS; ++level) { + int ww = width >> level; + int hh = height >> level; - byteArray tempBytes = byteArray(ww * hh * 4); - unsigned int *tempData = new unsigned int[ww * hh]; + byteArray tempBytes = byteArray(ww * hh * 4); + unsigned int* tempData = new unsigned int[ww * hh]; - if( image->getData( level ) ) - { - memcpy( tempData, image->getData( level ), ww * hh * 4); - for (int y = 0; y < hh; y++) - { - for (int x = 0; x < ww; x++) - { - int intIndex = y * ww + x; - int byteIndex = intIndex * 4; + if (image->getData(level)) { + memcpy(tempData, image->getData(level), ww * hh * 4); + for (int y = 0; y < hh; y++) { + for (int x = 0; x < ww; x++) { + int intIndex = y * ww + x; + int byteIndex = intIndex * 4; - // Pull ARGB bytes into either RGBA or BGRA depending on format + // Pull ARGB bytes into either RGBA or BGRA depending on + // format - tempBytes[byteIndex + byteRemap[0]] = (uint8_t)((tempData[intIndex] >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (uint8_t)((tempData[intIndex] >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (uint8_t)((tempData[intIndex] >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (uint8_t)((tempData[intIndex] >> 0) & 0xff); - } - } - } - else - { - int ow = width >> (level - 1); - - for (int x = 0; x < ww; x++) - for (int y = 0; y < hh; y++) - { - int c0 = data[level - 1]->getInt(((x * 2 + 0) + (y * 2 + 0) * ow) * 4); - int c1 = data[level - 1]->getInt(((x * 2 + 1) + (y * 2 + 0) * ow) * 4); - int c2 = data[level - 1]->getInt(((x * 2 + 1) + (y * 2 + 1) * ow) * 4); - int c3 = data[level - 1]->getInt(((x * 2 + 0) + (y * 2 + 1) * ow) * 4); + tempBytes[byteIndex + byteRemap[0]] = + (uint8_t)((tempData[intIndex] >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = + (uint8_t)((tempData[intIndex] >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = + (uint8_t)((tempData[intIndex] >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = + (uint8_t)((tempData[intIndex] >> 0) & 0xff); + } + } + } else { + int ow = width >> (level - 1); + + for (int x = 0; x < ww; x++) + for (int y = 0; y < hh; y++) { + int c0 = data[level - 1]->getInt( + ((x * 2 + 0) + (y * 2 + 0) * ow) * 4); + int c1 = data[level - 1]->getInt( + ((x * 2 + 1) + (y * 2 + 0) * ow) * 4); + int c2 = data[level - 1]->getInt( + ((x * 2 + 1) + (y * 2 + 1) * ow) * 4); + int c3 = data[level - 1]->getInt( + ((x * 2 + 0) + (y * 2 + 1) * ow) * 4); #ifndef _XBOX - // 4J - convert our RGBA texels to ARGB that crispBlend is expecting - // 4jcraft, added uint cast to pervent shift of neg int - c0 = ( ( c0 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c0 << 24 ); - c1 = ( ( c1 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c1 << 24 ); - c2 = ( ( c2 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c2 << 24 ); - c3 = ( ( c3 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c3 << 24 ); + // 4J - convert our RGBA texels to ARGB that crispBlend + // is expecting 4jcraft, added uint cast to pervent + // shift of neg int + c0 = + ((c0 >> 8) & 0x00ffffff) | ((unsigned int)c0 << 24); + c1 = + ((c1 >> 8) & 0x00ffffff) | ((unsigned int)c1 << 24); + c2 = + ((c2 >> 8) & 0x00ffffff) | ((unsigned int)c2 << 24); + c3 = + ((c3 >> 8) & 0x00ffffff) | ((unsigned int)c3 << 24); #endif - int col = crispBlend(crispBlend(c0, c1), crispBlend(c2, c3)); - // 4J - and back from ARGB -> RGBA - //col = ( col << 8 ) | (( col >> 24 ) & 0xff); - //tempData[x + y * ww] = col; + int col = + crispBlend(crispBlend(c0, c1), crispBlend(c2, c3)); + // 4J - and back from ARGB -> RGBA + // col = ( col << 8 ) | (( col >> 24 ) & 0xff); + // tempData[x + y * ww] = col; - int intIndex = y * ww + x; - int byteIndex = intIndex * 4; + int intIndex = y * ww + x; + int byteIndex = intIndex * 4; - // Pull ARGB bytes into either RGBA or BGRA depending on format + // Pull ARGB bytes into either RGBA or BGRA depending on + // format - tempBytes[byteIndex + byteRemap[0]] = (uint8_t)((col >> 24) & 0xff); - tempBytes[byteIndex + byteRemap[1]] = (uint8_t)((col >> 16) & 0xff); - tempBytes[byteIndex + byteRemap[2]] = (uint8_t)((col >> 8) & 0xff); - tempBytes[byteIndex + byteRemap[3]] = (uint8_t)((col >> 0) & 0xff); - } - } + tempBytes[byteIndex + byteRemap[0]] = + (uint8_t)((col >> 24) & 0xff); + tempBytes[byteIndex + byteRemap[1]] = + (uint8_t)((col >> 16) & 0xff); + tempBytes[byteIndex + byteRemap[2]] = + (uint8_t)((col >> 8) & 0xff); + tempBytes[byteIndex + byteRemap[3]] = + (uint8_t)((col >> 0) & 0xff); + } + } - MemSect(51); + MemSect(51); #ifdef __PS3__ - data[level] = new ByteBuffer_IO(tempBytes.length); + data[level] = new ByteBuffer_IO(tempBytes.length); #else - data[level] = ByteBuffer::allocateDirect(tempBytes.length); -#endif // __{S3__ - MemSect(0); - data[level]->clear(); - data[level]->put(tempBytes); - data[level]->limit(tempBytes.length); - delete [] tempBytes.data; - delete [] tempData; - } - } + data[level] = ByteBuffer::allocateDirect(tempBytes.length); +#endif // __{S3__ + MemSect(0); + data[level]->clear(); + data[level]->put(tempBytes); + data[level]->limit(tempBytes.length); + delete[] tempBytes.data; + delete[] tempData; + } + } - delete [] tempPixels.data; + delete[] tempPixels.data; - if (immediateUpdate) - { - updateOnGPU(); - } - else - { - updated = false; - } + if (immediateUpdate) { + updateOnGPU(); + } else { + updated = false; + } } -// 4J Kept from older versions for where we create mip-maps for levels that do not have pre-made graphics -int Texture::crispBlend(int c0, int c1) -{ - int a0 = (int) (((c0 & 0xff000000) >> 24)) & 0xff; - int a1 = (int) (((c1 & 0xff000000) >> 24)) & 0xff; +// 4J Kept from older versions for where we create mip-maps for levels that do +// not have pre-made graphics +int Texture::crispBlend(int c0, int c1) { + int a0 = (int)(((c0 & 0xff000000) >> 24)) & 0xff; + int a1 = (int)(((c1 & 0xff000000) >> 24)) & 0xff; - int a = 255; - if (a0 + a1 < 255) - { - a = 0; - a0 = 1; - a1 = 1; - } - else if (a0 > a1) - { - a0 = 255; - a1 = 1; - } - else - { - a0 = 1; - a1 = 255; + int a = 255; + if (a0 + a1 < 255) { + a = 0; + a0 = 1; + a1 = 1; + } else if (a0 > a1) { + a0 = 255; + a1 = 1; + } else { + a0 = 1; + a1 = 255; + } - } + int r0 = ((c0 >> 16) & 0xff) * a0; + int g0 = ((c0 >> 8) & 0xff) * a0; + int b0 = ((c0) & 0xff) * a0; - int r0 = ((c0 >> 16) & 0xff) * a0; - int g0 = ((c0 >> 8) & 0xff) * a0; - int b0 = ((c0) & 0xff) * a0; + int r1 = ((c1 >> 16) & 0xff) * a1; + int g1 = ((c1 >> 8) & 0xff) * a1; + int b1 = ((c1) & 0xff) * a1; - int r1 = ((c1 >> 16) & 0xff) * a1; - int g1 = ((c1 >> 8) & 0xff) * a1; - int b1 = ((c1) & 0xff) * a1; + int r = (r0 + r1) / (a0 + a1); + int g = (g0 + g1) / (a0 + a1); + int b = (b0 + b1) / (a0 + a1); - int r = (r0 + r1) / (a0 + a1); - int g = (g0 + g1) / (a0 + a1); - int b = (b0 + b1) / (a0 + a1); - - return (a << 24) | (r << 16) | (g << 8) | b; + return (a << 24) | (r << 16) | (g << 8) | b; } -int Texture::getManagerId() -{ - return managerId; +int Texture::getManagerId() { return managerId; } + +int Texture::getGlId() { return glId; } + +int Texture::getWidth() { return width; } + +int Texture::getHeight() { return height; } + +std::wstring Texture::getName() { return name; } + +void Texture::setImmediateUpdate(bool immediateUpdate) { + this->immediateUpdate = immediateUpdate; } -int Texture::getGlId() -{ - return glId; +void Texture::bind(int mipMapIndex) { + // 4J Removed 3D + // if (depth == 1) + //{ + glEnable(GL_TEXTURE_2D); + //} + // else + //{ + // glEnable(GL_TEXTURE_3D); + //} + + glActiveTexture(GL_TEXTURE0 + mipMapIndex); + glBindTexture(type, glId); + if (!updated) { + updateOnGPU(); + } } -int Texture::getWidth() -{ - return width; -} +void Texture::updateOnGPU() { + data[0]->flip(); + if (mipmapped) { + for (int level = 1; level < m_iMipLevels; level++) { + if (data[level] == NULL) break; -int Texture::getHeight() -{ - return height; -} - -std::wstring Texture::getName() -{ - return name; -} - -void Texture::setImmediateUpdate(bool immediateUpdate) -{ - this->immediateUpdate = immediateUpdate; -} - -void Texture::bind(int mipMapIndex) -{ - // 4J Removed 3D - //if (depth == 1) - //{ - glEnable(GL_TEXTURE_2D); - //} - //else - //{ - // glEnable(GL_TEXTURE_3D); - //} - - glActiveTexture(GL_TEXTURE0 + mipMapIndex); - glBindTexture(type, glId); - if (!updated) - { - updateOnGPU(); - } -} - -void Texture::updateOnGPU() -{ - data[0]->flip(); - if(mipmapped) - { - for (int level = 1; level < m_iMipLevels; level++) - { - if(data[level] == NULL) break; - - data[level]->flip(); - } - } - // 4J remove 3D and 1D - //if (height != 1 && depth != 1) - //{ - // glTexImage3D(type, 0, format, width, height, depth, 0, format, GL_UNSIGNED_BYTE, data); - //} - //else if(height != 1) - //{ - // 4J Added check so we can differentiate between which RenderManager function to call - if(!m_bInitialised) - { - RenderManager.TextureSetTextureLevels(m_iMipLevels); // 4J added + data[level]->flip(); + } + } + // 4J remove 3D and 1D + // if (height != 1 && depth != 1) + //{ + // glTexImage3D(type, 0, format, width, height, depth, 0, format, + //GL_UNSIGNED_BYTE, data); + //} + // else if(height != 1) + //{ + // 4J Added check so we can differentiate between which RenderManager + // function to call + if (!m_bInitialised) { + RenderManager.TextureSetTextureLevels(m_iMipLevels); // 4J added #ifdef __PSVITA__ - // AP - replace the dynamic ram buffer to one that points to a newly allocated video ram texture buffer. This means we don't have to memcpy - // the ram based buffer to it any more inside RenderManager.TextureDataUpdate - unsigned char *newData = RenderManager.TextureData(width,height,data[0]->getBuffer(),0,C4JRender::TEXTURE_FORMAT_RxGyBzAw); - ByteBuffer *oldBuffer = data[0]; - data[0] = new ByteBuffer(data[0]->getSize(), (uint8_t*) newData); - delete oldBuffer; - newData += width * height * 4; + // AP - replace the dynamic ram buffer to one that points to a newly + // allocated video ram texture buffer. This means we don't have to + // memcpy the ram based buffer to it any more inside + // RenderManager.TextureDataUpdate + unsigned char* newData = + RenderManager.TextureData(width, height, data[0]->getBuffer(), 0, + C4JRender::TEXTURE_FORMAT_RxGyBzAw); + ByteBuffer* oldBuffer = data[0]; + data[0] = new ByteBuffer(data[0]->getSize(), (uint8_t*)newData); + delete oldBuffer; + newData += width * height * 4; #else - RenderManager.TextureData(width,height,data[0]->getBuffer(),0,C4JRender::TEXTURE_FORMAT_RxGyBzAw); + RenderManager.TextureData(width, height, data[0]->getBuffer(), 0, + C4JRender::TEXTURE_FORMAT_RxGyBzAw); #endif - if(mipmapped) - { - for (int level = 1; level < m_iMipLevels; level++) - { - int levelWidth = width >> level; - int levelHeight = height >> level; + if (mipmapped) { + for (int level = 1; level < m_iMipLevels; level++) { + int levelWidth = width >> level; + int levelHeight = height >> level; #ifdef __PSVITA__ - // AP - replace the dynamic ram buffer to one that points to a newly allocated video ram texture buffer. This means we don't have to memcpy - // the ram based buffer to it any more inside RenderManager.TextureDataUpdate - RenderManager.TextureDataUpdate(0, 0,levelWidth,levelHeight,data[level]->getBuffer(),level); - ByteBuffer *oldBuffer = data[level]; - data[level] = new ByteBuffer(data[level]->getSize(), (uint8_t*) newData); - delete oldBuffer; - newData += levelWidth * levelHeight * 4; + // AP - replace the dynamic ram buffer to one that points to a + // newly allocated video ram texture buffer. This means we don't + // have to memcpy the ram based buffer to it any more inside + // RenderManager.TextureDataUpdate + RenderManager.TextureDataUpdate(0, 0, levelWidth, levelHeight, + data[level]->getBuffer(), + level); + ByteBuffer* oldBuffer = data[level]; + data[level] = + new ByteBuffer(data[level]->getSize(), (uint8_t*)newData); + delete oldBuffer; + newData += levelWidth * levelHeight * 4; #else - RenderManager.TextureData(levelWidth,levelHeight,data[level]->getBuffer(),level,C4JRender::TEXTURE_FORMAT_RxGyBzAw); + RenderManager.TextureData(levelWidth, levelHeight, + data[level]->getBuffer(), level, + C4JRender::TEXTURE_FORMAT_RxGyBzAw); #endif - } - } + } + } - m_bInitialised = true; - } - else - { + m_bInitialised = true; + } else { #ifdef _XBOX - RenderManager.TextureDataUpdate(data[0]->getBuffer(),0); + RenderManager.TextureDataUpdate(data[0]->getBuffer(), 0); #else - RenderManager.TextureDataUpdate(0, 0,width,height,data[0]->getBuffer(),0); + RenderManager.TextureDataUpdate(0, 0, width, height, + data[0]->getBuffer(), 0); #endif - if(mipmapped) - { - if (RenderManager.TextureGetTextureLevels() > 1) - { - for (int level = 1; level < m_iMipLevels; level++) - { - int levelWidth = width >> level; - int levelHeight = height >> level; - + if (mipmapped) { + if (RenderManager.TextureGetTextureLevels() > 1) { + for (int level = 1; level < m_iMipLevels; level++) { + int levelWidth = width >> level; + int levelHeight = height >> level; + #ifdef _XBOX - RenderManager.TextureDataUpdate(data[level]->getBuffer(),level); + RenderManager.TextureDataUpdate(data[level]->getBuffer(), + level); #else - RenderManager.TextureDataUpdate(0, 0,levelWidth,levelHeight,data[level]->getBuffer(),level); + RenderManager.TextureDataUpdate( + 0, 0, levelWidth, levelHeight, data[level]->getBuffer(), + level); #endif - } - } - } - } - //glTexImage2D(type, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); - //} - //else - //{ - // glTexImage1D(type, 0, format, width, 0, format, GL_UNSIGNED_BYTE, data); - //} - updated = true; + } + } + } + } + // glTexImage2D(type, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, + // data); + //} + // else + //{ + // glTexImage1D(type, 0, format, width, 0, format, GL_UNSIGNED_BYTE, data); + //} + updated = true; } -ByteBuffer *Texture::getData(unsigned int level) -{ - return data[level]; -} +ByteBuffer* Texture::getData(unsigned int level) { return data[level]; } diff --git a/Minecraft.Client/Textures/Texture.h b/Minecraft.Client/Textures/Texture.h index 74afaea66..732c1960c 100644 --- a/Minecraft.Client/Textures/Texture.h +++ b/Minecraft.Client/Textures/Texture.h @@ -8,91 +8,103 @@ class BufferedImage; class ByteBuffer_IO; #endif -class Texture -{ +class Texture { public: - static const int WM_WRAP = GL_REPEAT; - static const int WM_CLAMP = GL_CLAMP; - static const int WM_MIRROR = 0; //GL_MIRRORED_REPEAT; + static const int WM_WRAP = GL_REPEAT; + static const int WM_CLAMP = GL_CLAMP; + static const int WM_MIRROR = 0; // GL_MIRRORED_REPEAT; - static const int TFMT_RGBA = GL_RGBA; - static const int TFMT_BGRA = GL_BGRA; + static const int TFMT_RGBA = GL_RGBA; + static const int TFMT_BGRA = GL_BGRA; - static const int TFLT_NEAREST = GL_NEAREST; - static const int TFLT_LINEAR = GL_LINEAR; - static const int TFLT_LINEAR_MIP_NEAREST = 0; //GL_LINEAR_MIPMAP_NEAREST; - static const int TFLT_LINEAR_MIP_LINEAR = 0; //GL_LINEAR_MIPMAP_LINEAR; - static const int TFLT_NEAREST_MIP_NEAREST = 0; //GL_NEAREST_MIPMAP_NEAREST; - static const int TFLT_NEAREST_MIP_LINEAR = GL_NEAREST_MIPMAP_LINEAR; + static const int TFLT_NEAREST = GL_NEAREST; + static const int TFLT_LINEAR = GL_LINEAR; + static const int TFLT_LINEAR_MIP_NEAREST = 0; // GL_LINEAR_MIPMAP_NEAREST; + static const int TFLT_LINEAR_MIP_LINEAR = 0; // GL_LINEAR_MIPMAP_LINEAR; + static const int TFLT_NEAREST_MIP_NEAREST = 0; // GL_NEAREST_MIPMAP_NEAREST; + static const int TFLT_NEAREST_MIP_LINEAR = GL_NEAREST_MIPMAP_LINEAR; - static const int TM_STATIC = 0; - static const int TM_DYNAMIC = 1; - static const int TM_CONTAINER = 2; + static const int TM_STATIC = 0; + static const int TM_DYNAMIC = 1; + static const int TM_CONTAINER = 2; private: - int glId; - int managerId; + int glId; + int managerId; - // Indicates certain aspects of this texture's behavior in terms of how tightly it is bound, conceptually. A static - // texture is loaded once, uploaded to the GPU, and discarded CPU-side. A dynamic texture is kept on both the CPU - // and GPU, as it will likely be dynamically updated on the CPU. A container texture exists only to keep the data - // on the CPU, usually for later combination into a larger texture via the Stitcher class. - int mode; + // Indicates certain aspects of this texture's behavior in terms of how + // tightly it is bound, conceptually. A static texture is loaded once, + // uploaded to the GPU, and discarded CPU-side. A dynamic texture is kept on + // both the CPU and GPU, as it will likely be dynamically updated on the + // CPU. A container texture exists only to keep the data on the CPU, usually + // for later combination into a larger texture via the Stitcher class. + int mode; - int width; - int height; - int depth; - int format; - int type; - int minFilter; - int magFilter; - int wrapMode; - bool mipmapped; - std::wstring name; + int width; + int height; + int depth; + int format; + int type; + int minFilter; + int magFilter; + int wrapMode; + bool mipmapped; + std::wstring name; - Rect2i *rect; + Rect2i* rect; - bool valid; - bool immediateUpdate; - bool updated; - int m_iMipLevels; + bool valid; + bool immediateUpdate; + bool updated; + int m_iMipLevels; #ifdef __PS3__ - ByteBuffer_IO *data[10]; + ByteBuffer_IO* data[10]; #else - ByteBuffer *data[10]; // Arrays for mipmaps - NULL if not used + ByteBuffer* data[10]; // Arrays for mipmaps - NULL if not used #endif public: - bool m_bInitialised; // 4J Added + bool m_bInitialised; // 4J Added + + ~Texture(); - ~Texture(); private: - Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap = true); + Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, int magFilter, + bool mipMap = true); - void _init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, bool mipMap); - void _init(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap); + void _init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, bool mipMap); + void _init(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, + int magFilter, BufferedImage* image, bool mipMap); public: - Texture(const std::wstring &name, int mode, int width, int height, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap = true); - Texture(const std::wstring &name, int mode, int width, int height, int depth, int wrapMode, int format, int minFilter, int magFilter, BufferedImage *image, bool mipMap = true); + Texture(const std::wstring& name, int mode, int width, int height, + int wrapMode, int format, int minFilter, int magFilter, + BufferedImage* image, bool mipMap = true); + Texture(const std::wstring& name, int mode, int width, int height, + int depth, int wrapMode, int format, int minFilter, int magFilter, + BufferedImage* image, bool mipMap = true); - const Rect2i *getRect(); - void fill(const Rect2i *rect, int color); - void writeAsBMP(const std::wstring &name); - void writeAsPNG(const std::wstring &filename); - void blit(int x, int y, Texture *source); - void blit(int x, int y, Texture *source, bool rotated); - void transferFromBuffer(intArray buffer); - void transferFromImage(BufferedImage *image); - int getManagerId(); - int getGlId(); - int getWidth(); - int getHeight(); - std::wstring getName(); - void setImmediateUpdate(bool immediateUpdate); - void bind(int mipMapIndex); - void updateOnGPU(); - ByteBuffer *getData(unsigned int level = 0); + const Rect2i* getRect(); + void fill(const Rect2i* rect, int color); + void writeAsBMP(const std::wstring& name); + void writeAsPNG(const std::wstring& filename); + void blit(int x, int y, Texture* source); + void blit(int x, int y, Texture* source, bool rotated); + void transferFromBuffer(intArray buffer); + void transferFromImage(BufferedImage* image); + int getManagerId(); + int getGlId(); + int getWidth(); + int getHeight(); + std::wstring getName(); + void setImmediateUpdate(bool immediateUpdate); + void bind(int mipMapIndex); + void updateOnGPU(); + ByteBuffer* getData(unsigned int level = 0); - static int crispBlend(int c0, int c1); + static int crispBlend(int c0, int c1); }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/TextureHolder.cpp b/Minecraft.Client/Textures/TextureHolder.cpp index 9723e420e..3c29330c6 100644 --- a/Minecraft.Client/Textures/TextureHolder.cpp +++ b/Minecraft.Client/Textures/TextureHolder.cpp @@ -4,81 +4,65 @@ #include "../../Minecraft.World/Util/StringHelpers.h" #include "TextureHolder.h" -TextureHolder::TextureHolder(Texture *texture) -{ - scale = 1.0f; +TextureHolder::TextureHolder(Texture* texture) { + scale = 1.0f; - this->texture = texture; - this->width = texture->getWidth(); - this->height = texture->getHeight(); + this->texture = texture; + this->width = texture->getWidth(); + this->height = texture->getHeight(); - this->rotated = smallestFittingMinTexel(height) > smallestFittingMinTexel(width); + this->rotated = + smallestFittingMinTexel(height) > smallestFittingMinTexel(width); } -Texture *TextureHolder::getTexture() -{ - return texture; +Texture* TextureHolder::getTexture() { return texture; } + +int TextureHolder::getWidth() const { + return rotated ? smallestFittingMinTexel((int)(height * scale)) + : smallestFittingMinTexel((int)(width * scale)); } -int TextureHolder::getWidth() const -{ - return rotated ? smallestFittingMinTexel((int) (height * scale)) : smallestFittingMinTexel((int) (width * scale)); +int TextureHolder::getHeight() const { + return rotated ? smallestFittingMinTexel((int)(width * scale)) + : smallestFittingMinTexel((int)(height * scale)); } -int TextureHolder::getHeight() const -{ - return rotated ? smallestFittingMinTexel((int) (width * scale)) : smallestFittingMinTexel((int) (height * scale)); +void TextureHolder::rotate() { rotated = !rotated; } + +bool TextureHolder::isRotated() { return rotated; } + +int TextureHolder::smallestFittingMinTexel(int input) const { + return ((input >> Stitcher::MAX_MIPLEVEL) + + ((input & (Stitcher::MIN_TEXEL - 1)) == 0 ? 0 : 1)) + << Stitcher::MAX_MIPLEVEL; } -void TextureHolder::rotate() -{ - rotated = !rotated; -} +void TextureHolder::setForcedScale(int targetSize) { + if (width <= targetSize || height <= targetSize) { + return; + } -bool TextureHolder::isRotated() -{ - return rotated; -} - -int TextureHolder::smallestFittingMinTexel(int input) const -{ - return ((input >> Stitcher::MAX_MIPLEVEL) + ((input & (Stitcher::MIN_TEXEL - 1)) == 0 ? 0 : 1)) << Stitcher::MAX_MIPLEVEL; -} - -void TextureHolder::setForcedScale(int targetSize) -{ - if (width <= targetSize || height <= targetSize) - { - return; - } - - scale = (float) targetSize / std::min(width, height); + scale = (float)targetSize / std::min(width, height); } //@Override -std::wstring TextureHolder::toString() -{ - return L"TextureHolder{width=" + _toString(width) + L", height=" + _toString(height) + L'}'; +std::wstring TextureHolder::toString() { + return L"TextureHolder{width=" + _toString(width) + L", height=" + + _toString(height) + L'}'; } -int TextureHolder::compareTo(const TextureHolder *other) const -{ - int result = 0; - if (this->getHeight() == other->getHeight()) - { - if (this->getWidth() == other->getWidth()) - { - if (texture->getName().empty()) - { - return other->texture->getName().empty() ? 0 : -1; - } - return texture->getName().compare(other->texture->getName()); - } - result = this->getWidth() < other->getWidth() ? 1 : -1; - } - else - { - result = this->getHeight() < other->getHeight() ? 1 : -1; - } - return result; +int TextureHolder::compareTo(const TextureHolder* other) const { + int result = 0; + if (this->getHeight() == other->getHeight()) { + if (this->getWidth() == other->getWidth()) { + if (texture->getName().empty()) { + return other->texture->getName().empty() ? 0 : -1; + } + return texture->getName().compare(other->texture->getName()); + } + result = this->getWidth() < other->getWidth() ? 1 : -1; + } else { + result = this->getHeight() < other->getHeight() ? 1 : -1; + } + return result; } \ No newline at end of file diff --git a/Minecraft.Client/Textures/TextureHolder.h b/Minecraft.Client/Textures/TextureHolder.h index cab827dd1..5215b7ffd 100644 --- a/Minecraft.Client/Textures/TextureHolder.h +++ b/Minecraft.Client/Textures/TextureHolder.h @@ -2,35 +2,37 @@ class Texture; -class TextureHolder //implements Comparable { +class TextureHolder // implements Comparable { { private: - Texture *texture; - int width; - int height; - bool rotated; - float scale; + Texture* texture; + int width; + int height; + bool rotated; + float scale; public: - TextureHolder(Texture *texture); + TextureHolder(Texture* texture); - Texture *getTexture(); - int getWidth() const; - int getHeight() const; - void rotate(); - bool isRotated(); + Texture* getTexture(); + int getWidth() const; + int getHeight() const; + void rotate(); + bool isRotated(); private: - int smallestFittingMinTexel(int input) const; + int smallestFittingMinTexel(int input) const; public: - void setForcedScale(int targetSize); - //@Override - std::wstring toString(); - int compareTo(const TextureHolder *other) const; + void setForcedScale(int targetSize); + //@Override + std::wstring toString(); + int compareTo(const TextureHolder* other) const; }; -struct TextureHolderLessThan -{ - bool operator() (const TextureHolder *first, const TextureHolder *second) const { return first->compareTo(second) >= 0; } +struct TextureHolderLessThan { + bool operator()(const TextureHolder* first, + const TextureHolder* second) const { + return first->compareTo(second) >= 0; + } }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/TextureManager.cpp b/Minecraft.Client/Textures/TextureManager.cpp index 546bdc17f..a618be6d1 100644 --- a/Minecraft.Client/Textures/TextureManager.cpp +++ b/Minecraft.Client/Textures/TextureManager.cpp @@ -7,190 +7,196 @@ #include "TextureManager.h" #include "../../Minecraft.World/Util/StringHelpers.h" -TextureManager *TextureManager::instance = NULL; +TextureManager* TextureManager::instance = NULL; -void TextureManager::createInstance() -{ - instance = new TextureManager(); +void TextureManager::createInstance() { instance = new TextureManager(); } + +TextureManager* TextureManager::getInstance() { return instance; } + +TextureManager::TextureManager() { nextID = 0; } + +int TextureManager::createTextureID() { return nextID++; } + +Texture* TextureManager::getTexture(const std::wstring& name) { + if (stringToIDMap.find(name) != stringToIDMap.end()) { + return idToTextureMap.find(stringToIDMap.find(name)->second)->second; + } + + return NULL; } -TextureManager *TextureManager::getInstance() -{ - return instance; +void TextureManager::registerName(const std::wstring& name, Texture* texture) { + stringToIDMap.insert( + stringIntMap::value_type(name, texture->getManagerId())); + + if (idToTextureMap.find(texture->getManagerId()) == idToTextureMap.end()) { + idToTextureMap.insert( + intTextureMap::value_type(texture->getManagerId(), texture)); + } } -TextureManager::TextureManager() -{ - nextID = 0; +void TextureManager::registerTexture(Texture* texture) { + for (AUTO_VAR(it, idToTextureMap.begin()); it != idToTextureMap.end(); + ++it) { + if (it->second == texture) { + // Minecraft.getInstance().getLogger().warning("TextureManager.registerTexture + // called, but this texture has " + "already been registered. + // ignoring."); + app.DebugPrintf( + "TextureManager.registerTexture called, but this texture has " + "already been registered. ignoring."); + return; + } + } + + idToTextureMap.insert( + intTextureMap::value_type(texture->getManagerId(), texture)); } -int TextureManager::createTextureID() -{ - return nextID++; +void TextureManager::unregisterTexture(const std::wstring& name, + Texture* texture) { + AUTO_VAR(it, idToTextureMap.find(texture->getManagerId())); + if (it != idToTextureMap.end()) idToTextureMap.erase(it); + + AUTO_VAR(it2, stringToIDMap.find(name)); + if (it2 != stringToIDMap.end()) stringToIDMap.erase(it2); } -Texture *TextureManager::getTexture(const std::wstring &name) -{ - if (stringToIDMap.find(name) != stringToIDMap.end()) - { - return idToTextureMap.find(stringToIDMap.find(name)->second)->second; - } +Stitcher* TextureManager::createStitcher(const std::wstring& name) { + int maxTextureSize = Minecraft::maxSupportedTextureSize(); - return NULL; + return new Stitcher(name, maxTextureSize, maxTextureSize, true); } -void TextureManager::registerName(const std::wstring &name, Texture *texture) -{ - stringToIDMap.insert( stringIntMap::value_type( name, texture->getManagerId() ) ); +std::vector* TextureManager::createTextures( + const std::wstring& filename, bool mipmap) { + std::vector* result = new std::vector(); + TexturePack* texturePack = Minecraft::GetInstance()->skins->getSelected(); + // try { + int mode = Texture::TM_CONTAINER; // Most important -- so it doesn't get + // uploaded to videoram + int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues + // with how we signal non-mipmmapped textures + // to the pixel shader //Texture::WM_CLAMP; + int format = Texture::TFMT_RGBA; + int minFilter = Texture::TFLT_NEAREST; + int magFilter = Texture::TFLT_NEAREST; - if (idToTextureMap.find(texture->getManagerId()) == idToTextureMap.end()) - { - idToTextureMap.insert( intTextureMap::value_type( texture->getManagerId(), texture) ); - } -} + MemSect(32); + std::wstring drive = L""; -void TextureManager::registerTexture(Texture *texture) -{ - for(AUTO_VAR(it, idToTextureMap.begin()); it != idToTextureMap.end(); ++it) - { - if(it->second == texture) - { - //Minecraft.getInstance().getLogger().warning("TextureManager.registerTexture called, but this texture has " + "already been registered. ignoring."); - app.DebugPrintf("TextureManager.registerTexture called, but this texture has already been registered. ignoring."); - return; - } - } - - idToTextureMap.insert( intTextureMap::value_type( texture->getManagerId(), texture ) ); -} - -void TextureManager::unregisterTexture(const std::wstring &name, Texture *texture) -{ - AUTO_VAR(it, idToTextureMap.find(texture->getManagerId())); - if(it != idToTextureMap.end()) idToTextureMap.erase(it); - - AUTO_VAR(it2, stringToIDMap.find(name)); - if(it2 != stringToIDMap.end()) stringToIDMap.erase(it2); -} - -Stitcher *TextureManager::createStitcher(const std::wstring &name) -{ - int maxTextureSize = Minecraft::maxSupportedTextureSize(); - - return new Stitcher(name, maxTextureSize, maxTextureSize, true); -} - -std::vector *TextureManager::createTextures(const std::wstring &filename, bool mipmap) -{ - std::vector *result = new std::vector(); - TexturePack *texturePack = Minecraft::GetInstance()->skins->getSelected(); - //try { - int mode = Texture::TM_CONTAINER; // Most important -- so it doesn't get uploaded to videoram - int clamp = Texture::WM_WRAP; // 4J Stu - Don't clamp as it causes issues with how we signal non-mipmmapped textures to the pixel shader //Texture::WM_CLAMP; - int format = Texture::TFMT_RGBA; - int minFilter = Texture::TFLT_NEAREST; - int magFilter = Texture::TFLT_NEAREST; - - MemSect(32); - std::wstring drive = L""; - - - if(texturePack->hasFile(L"res/" + filename,false)) - { - drive = texturePack->getPath(true); - } - else - { + if (texturePack->hasFile(L"res/" + filename, false)) { + drive = texturePack->getPath(true); + } else { #ifdef __PS3__ - if(app.GetBootedFromDiscPatch()) - { - const char *pchTextureName=wstringtofilename(filename); - char *pchUsrDir = app.GetBDUsrDirPath(pchTextureName); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); - drive= wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else -#endif - { - drive = Minecraft::GetInstance()->skins->getDefault()->getPath(true); - } - } - - //BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + filename),false,true,drive); //ImageIO::read(texturePack->getResource(L"/" + filename)); - - BufferedImage *image = texturePack->getImageResource(filename, false, true, drive); - MemSect(0); - int height = image->getHeight(); - int width = image->getWidth(); - - std::wstring texName = getTextureNameFromPath(filename); - - if (isAnimation(filename, texturePack)) - { - // TODO: Read this information from the animation file later - int frameWidth = width; - int frameHeight = width; - - // This could end as 0 frames - int frameCount = height / frameWidth; - for (int i = 0; i < frameCount; i++) - { - BufferedImage *subImage = image->getSubimage(0, frameHeight * i, frameWidth, frameHeight); - Texture *texture = createTexture(texName, mode, frameWidth, frameHeight, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != NULL, subImage); - delete subImage; - result->push_back(texture); - } - } - else - { - // TODO: Remove this hack -- fix proper rotation support (needed for 'off-aspect textures') - if (width == height) - { - result->push_back(createTexture(texName, mode, width, height, clamp, format, minFilter, magFilter, mipmap || image->getData(1) != NULL, image)); - } - else - { - //Minecraft.getInstance().getLogger().warning("TextureManager.createTexture: Skipping " + filename + " because of broken aspect ratio and not animation"); -#ifndef _CONTENT_PACKAGE - wprintf(L"TextureManager.createTexture: Skipping %ls because of broken aspect ratio and not animation\n", filename.c_str()); + if (app.GetBootedFromDiscPatch()) { + const char* pchTextureName = wstringtofilename(filename); + char* pchUsrDir = app.GetBDUsrDirPath(pchTextureName); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); + drive = wstr + L"\\Common\\res\\TitleUpdate\\"; + } else #endif - } - } - delete image; + { + drive = + Minecraft::GetInstance()->skins->getDefault()->getPath(true); + } + } + // BufferedImage *image = new BufferedImage(texturePack->getResource(L"/" + + // filename),false,true,drive); + // //ImageIO::read(texturePack->getResource(L"/" + filename)); - //return result; - //} catch (FileNotFoundException e) { - // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture called for file " + filename + ", but that file does not exist. Ignoring."); - //} catch (IOException e) { - // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture encountered an IOException when " + "trying to read file " + filename + ". Ignoring."); - //} - return result; + BufferedImage* image = + texturePack->getImageResource(filename, false, true, drive); + MemSect(0); + int height = image->getHeight(); + int width = image->getWidth(); + + std::wstring texName = getTextureNameFromPath(filename); + + if (isAnimation(filename, texturePack)) { + // TODO: Read this information from the animation file later + int frameWidth = width; + int frameHeight = width; + + // This could end as 0 frames + int frameCount = height / frameWidth; + for (int i = 0; i < frameCount; i++) { + BufferedImage* subImage = + image->getSubimage(0, frameHeight * i, frameWidth, frameHeight); + Texture* texture = + createTexture(texName, mode, frameWidth, frameHeight, clamp, + format, minFilter, magFilter, + mipmap || image->getData(1) != NULL, subImage); + delete subImage; + result->push_back(texture); + } + } else { + // TODO: Remove this hack -- fix proper rotation support (needed for + // 'off-aspect textures') + if (width == height) { + result->push_back(createTexture( + texName, mode, width, height, clamp, format, minFilter, + magFilter, mipmap || image->getData(1) != NULL, image)); + } else { + // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture: + // Skipping " + filename + " because of broken aspect ratio and not + // animation"); +#ifndef _CONTENT_PACKAGE + wprintf( + L"TextureManager.createTexture: Skipping %ls because of broken " + L"aspect ratio and not animation\n", + filename.c_str()); +#endif + } + } + delete image; + + // return result; + // } catch (FileNotFoundException e) { + // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture + //called for file " + filename + ", but that file does not exist. + //Ignoring."); } catch (IOException e) { + // Minecraft.getInstance().getLogger().warning("TextureManager.createTexture + //encountered an IOException when " + "trying to read file " + filename + ". + //Ignoring."); + // } + return result; } -std::wstring TextureManager::getTextureNameFromPath(const std::wstring &filename) -{ - File file(filename); - return file.getName().substr(0, file.getName().find_last_of(L'.')); +std::wstring TextureManager::getTextureNameFromPath( + const std::wstring& filename) { + File file(filename); + return file.getName().substr(0, file.getName().find_last_of(L'.')); } -bool TextureManager::isAnimation(const std::wstring &filename, TexturePack *texturePack) -{ - std::wstring dataFileName = L"/" + filename.substr(0, filename.find_last_of(L'.')) + L".txt"; - bool hasOriginalImage = texturePack->hasFile(L"/" + filename, false); - return Minecraft::GetInstance()->skins->getSelected()->hasFile(dataFileName, !hasOriginalImage); +bool TextureManager::isAnimation(const std::wstring& filename, + TexturePack* texturePack) { + std::wstring dataFileName = + L"/" + filename.substr(0, filename.find_last_of(L'.')) + L".txt"; + bool hasOriginalImage = texturePack->hasFile(L"/" + filename, false); + return Minecraft::GetInstance()->skins->getSelected()->hasFile( + dataFileName, !hasOriginalImage); } -Texture *TextureManager::createTexture(const std::wstring &name, int mode, int width, int height, int wrap, int format, int minFilter, int magFilter, bool mipmap, BufferedImage *image) -{ - Texture *newTex = new Texture(name, mode, width, height, wrap, format, minFilter, magFilter, image, mipmap); - registerTexture(newTex); - return newTex; +Texture* TextureManager::createTexture(const std::wstring& name, int mode, + int width, int height, int wrap, + int format, int minFilter, int magFilter, + bool mipmap, BufferedImage* image) { + Texture* newTex = new Texture(name, mode, width, height, wrap, format, + minFilter, magFilter, image, mipmap); + registerTexture(newTex); + return newTex; } -Texture *TextureManager::createTexture(const std::wstring &name, int mode, int width, int height, int format, bool mipmap) -{ - // 4J Stu - Don't clamp as it causes issues with how we signal non-mipmmapped textures to the pixel shader - //return createTexture(name, mode, width, height, Texture::WM_CLAMP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); - return createTexture(name, mode, width, height, Texture::WM_WRAP, format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); +Texture* TextureManager::createTexture(const std::wstring& name, int mode, + int width, int height, int format, + bool mipmap) { + // 4J Stu - Don't clamp as it causes issues with how we signal + // non-mipmmapped textures to the pixel shader + // return createTexture(name, mode, width, height, Texture::WM_CLAMP, + // format, Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, NULL); + return createTexture(name, mode, width, height, Texture::WM_WRAP, format, + Texture::TFLT_NEAREST, Texture::TFLT_NEAREST, mipmap, + NULL); } diff --git a/Minecraft.Client/Textures/TextureManager.h b/Minecraft.Client/Textures/TextureManager.h index 4fb859546..cf1f96b12 100644 --- a/Minecraft.Client/Textures/TextureManager.h +++ b/Minecraft.Client/Textures/TextureManager.h @@ -4,38 +4,42 @@ class Texture; class Stitcher; class TexturePack; -class TextureManager -{ +class TextureManager { private: - static TextureManager *instance; + static TextureManager* instance; - int nextID; - typedef std::unordered_map stringIntMap; - typedef std::unordered_map intTextureMap; - intTextureMap idToTextureMap; - stringIntMap stringToIDMap; + int nextID; + typedef std::unordered_map stringIntMap; + typedef std::unordered_map intTextureMap; + intTextureMap idToTextureMap; + stringIntMap stringToIDMap; public: - static void createInstance(); - static TextureManager *getInstance(); + static void createInstance(); + static TextureManager* getInstance(); private: - TextureManager(); + TextureManager(); public: - int createTextureID(); - Texture *getTexture(const std::wstring &name); - void registerName(const std::wstring &name, Texture *texture); - void registerTexture(Texture *texture); - void unregisterTexture(const std::wstring &name, Texture *texture); - Stitcher *createStitcher(const std::wstring &name); - std::vector *createTextures(const std::wstring &filename, bool mipmap); // 4J added mipmap param + int createTextureID(); + Texture* getTexture(const std::wstring& name); + void registerName(const std::wstring& name, Texture* texture); + void registerTexture(Texture* texture); + void unregisterTexture(const std::wstring& name, Texture* texture); + Stitcher* createStitcher(const std::wstring& name); + std::vector* createTextures( + const std::wstring& filename, bool mipmap); // 4J added mipmap param private: - std::wstring getTextureNameFromPath(const std::wstring &filename); - bool isAnimation(const std::wstring &filename, TexturePack *texturePack); + std::wstring getTextureNameFromPath(const std::wstring& filename); + bool isAnimation(const std::wstring& filename, TexturePack* texturePack); public: - Texture *createTexture(const std::wstring &name, int mode, int width, int height, int wrap, int format, int minFilter, int magFilter, bool mipmap, BufferedImage *image); - Texture *createTexture(const std::wstring &name, int mode, int width, int height, int format, bool mipmap); // 4J Added mipmap param + Texture* createTexture(const std::wstring& name, int mode, int width, + int height, int wrap, int format, int minFilter, + int magFilter, bool mipmap, BufferedImage* image); + Texture* createTexture(const std::wstring& name, int mode, int width, + int height, int format, + bool mipmap); // 4J Added mipmap param }; \ No newline at end of file diff --git a/Minecraft.Client/Textures/Textures.cpp b/Minecraft.Client/Textures/Textures.cpp index eecc06df1..98d7d1211 100644 --- a/Minecraft.Client/Textures/Textures.cpp +++ b/Minecraft.Client/Textures/Textures.cpp @@ -17,520 +17,488 @@ #include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Util/StringHelpers.h" -// Linux/PC port: disable mipmapping globally so textures are always sampled from -// the full-resolution level 0 with GL_NEAREST, giving pixel-crisp Minecraft blocks -// at all distances. Mipmapping causes glGenerateMipmap() to fire (which resets the -// min-filter to GL_NEAREST_MIPMAP_LINEAR on many Mesa/Nvidia drivers) and the -// per-level crispBlend loop is both wasteful and still causes visible blurring. +// Linux/PC port: disable mipmapping globally so textures are always sampled +// from the full-resolution level 0 with GL_NEAREST, giving pixel-crisp +// Minecraft blocks at all distances. Mipmapping causes glGenerateMipmap() to +// fire (which resets the min-filter to GL_NEAREST_MIPMAP_LINEAR on many +// Mesa/Nvidia drivers) and the per-level crispBlend loop is both wasteful and +// still causes visible blurring. bool Textures::MIPMAP = false; -C4JRender::eTextureFormat Textures::TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; +C4JRender::eTextureFormat Textures::TEXTURE_FORMAT = + C4JRender::TEXTURE_FORMAT_RxGyBzAw; int Textures::preLoadedIdx[TN_COUNT]; -const wchar_t *Textures::preLoaded[TN_COUNT] = -{ - L"%blur%misc/pumpkinblur", -// L"%blur%/misc/vignette", // Not currently used - L"%clamp%misc/shadow", -// L"/achievement/bg", // Not currently used - L"art/kz", - L"environment/clouds", - L"environment/rain", - L"environment/snow", - L"gui/gui", - L"gui/icons", - L"item/arrows", - L"item/boat", - L"item/cart", - L"item/sign", - L"misc/mapbg", - L"misc/mapicons", - L"misc/water", - L"misc/footprint", - L"mob/saddle", - L"mob/sheep_fur", - L"mob/spider_eyes", - L"particles", - L"mob/chicken", - L"mob/cow", - L"mob/pig", - L"mob/sheep", - L"mob/squid", - L"mob/wolf", - L"mob/wolf_tame", - L"mob/wolf_angry", - L"mob/creeper", - L"mob/ghast", - L"mob/ghast_fire", - L"mob/zombie", - L"mob/pigzombie", - L"mob/skeleton", - L"mob/slime", - L"mob/spider", - L"mob/char", - L"mob/char1", - L"mob/char2", - L"mob/char3", - L"mob/char4", - L"mob/char5", - L"mob/char6", - L"mob/char7", - L"terrain/moon", - L"terrain/sun", - L"armor/power", +const wchar_t* Textures::preLoaded[TN_COUNT] = { + L"%blur%misc/pumpkinblur", + // L"%blur%/misc/vignette", // Not currently used + L"%clamp%misc/shadow", + // L"/achievement/bg", // Not currently used + L"art/kz", + L"environment/clouds", + L"environment/rain", + L"environment/snow", + L"gui/gui", + L"gui/icons", + L"item/arrows", + L"item/boat", + L"item/cart", + L"item/sign", + L"misc/mapbg", + L"misc/mapicons", + L"misc/water", + L"misc/footprint", + L"mob/saddle", + L"mob/sheep_fur", + L"mob/spider_eyes", + L"particles", + L"mob/chicken", + L"mob/cow", + L"mob/pig", + L"mob/sheep", + L"mob/squid", + L"mob/wolf", + L"mob/wolf_tame", + L"mob/wolf_angry", + L"mob/creeper", + L"mob/ghast", + L"mob/ghast_fire", + L"mob/zombie", + L"mob/pigzombie", + L"mob/skeleton", + L"mob/slime", + L"mob/spider", + L"mob/char", + L"mob/char1", + L"mob/char2", + L"mob/char3", + L"mob/char4", + L"mob/char5", + L"mob/char6", + L"mob/char7", + L"terrain/moon", + L"terrain/sun", + L"armor/power", - // 1.8.2 - L"mob/cavespider", - L"mob/enderman", - L"mob/silverfish", - L"mob/enderman_eyes", - L"misc/explosion", - L"item/xporb", - L"item/chest", - L"item/largechest", + // 1.8.2 + L"mob/cavespider", + L"mob/enderman", + L"mob/silverfish", + L"mob/enderman_eyes", + L"misc/explosion", + L"item/xporb", + L"item/chest", + L"item/largechest", - // 1.3.2 - L"item/enderchest", + // 1.3.2 + L"item/enderchest", - // 1.0.1 - L"mob/redcow", - L"mob/snowman", - L"mob/enderdragon/ender", - L"mob/fire", - L"mob/lava", - L"mob/villager/villager", - L"mob/villager/farmer", - L"mob/villager/librarian", - L"mob/villager/priest", - L"mob/villager/smith", - L"mob/villager/butcher", - L"mob/enderdragon/crystal", - L"mob/enderdragon/shuffle", - L"mob/enderdragon/beam", - L"mob/enderdragon/ender_eyes", - L"%blur%misc/glint", - L"item/book", - L"misc/tunnel", - L"misc/particlefield", - L"terrain/moon_phases", + // 1.0.1 + L"mob/redcow", + L"mob/snowman", + L"mob/enderdragon/ender", + L"mob/fire", + L"mob/lava", + L"mob/villager/villager", + L"mob/villager/farmer", + L"mob/villager/librarian", + L"mob/villager/priest", + L"mob/villager/smith", + L"mob/villager/butcher", + L"mob/enderdragon/crystal", + L"mob/enderdragon/shuffle", + L"mob/enderdragon/beam", + L"mob/enderdragon/ender_eyes", + L"%blur%misc/glint", + L"item/book", + L"misc/tunnel", + L"misc/particlefield", + L"terrain/moon_phases", - // 1.2.3 - L"mob/ozelot", - L"mob/cat_black", - L"mob/cat_red", - L"mob/cat_siamese", - L"mob/villager_golem", - L"mob/skeleton_wither", + // 1.2.3 + L"mob/ozelot", + L"mob/cat_black", + L"mob/cat_red", + L"mob/cat_siamese", + L"mob/villager_golem", + L"mob/skeleton_wither", - // TU 14 - L"mob/wolf_collar", - L"mob/zombie_villager", + // TU 14 + L"mob/wolf_collar", + L"mob/zombie_villager", #ifdef _LARGE_WORLDS - L"misc/additionalmapicons", + L"misc/additionalmapicons", #endif - L"font/Default", - L"font/alternate", + L"font/Default", + L"font/alternate", - // skin packs -/* L"/SP1", - L"/SP2", - L"/SP3", - L"/SPF", + // skin packs + /* L"/SP1", + L"/SP2", + L"/SP3", + L"/SPF", - // themes - L"/ThSt", - L"/ThIr", - L"/ThGo", - L"/ThDi", + // themes + L"/ThSt", + L"/ThIr", + L"/ThGo", + L"/ThDi", - // gamerpics - L"/GPAn", - L"/GPCo", - L"/GPEn", - L"/GPFo", - L"/GPTo", - L"/GPBA", - L"/GPFa", - L"/GPME", - L"/GPMF", - L"/GPMM", - L"/GPSE", + // gamerpics + L"/GPAn", + L"/GPCo", + L"/GPEn", + L"/GPFo", + L"/GPTo", + L"/GPBA", + L"/GPFa", + L"/GPME", + L"/GPMF", + L"/GPMM", + L"/GPSE", - // avatar items - - L"/AH_0006", - L"/AH_0003", - L"/AH_0007", - L"/AH_0005", - L"/AH_0004", - L"/AH_0001", - L"/AH_0002", - L"/AT_0001", - L"/AT_0002", - L"/AT_0003", - L"/AT_0004", - L"/AT_0005", - L"/AT_0006", - L"/AT_0007", - L"/AT_0008", - L"/AT_0009", - L"/AT_0010", - L"/AT_0011", - L"/AT_0012", - L"/AP_0001", - L"/AP_0002", - L"/AP_0003", - L"/AP_0004", - L"/AP_0005", - L"/AP_0006", - L"/AP_0007", - L"/AP_0009", - L"/AP_0010", - L"/AP_0011", - L"/AP_0012", - L"/AP_0013", - L"/AP_0014", - L"/AP_0015", - L"/AP_0016", - L"/AP_0017", - L"/AP_0018", - L"/AA_0001", - L"/AT_0013", - L"/AT_0014", - L"/AT_0015", - L"/AT_0016", - L"/AT_0017", - L"/AT_0018", - L"/AP_0019", - L"/AP_0020", - L"/AP_0021", - L"/AP_0022", - L"/AP_0023", - L"/AH_0008", - L"/AH_0009",*/ + // avatar items - L"gui/items", - L"terrain", + L"/AH_0006", + L"/AH_0003", + L"/AH_0007", + L"/AH_0005", + L"/AH_0004", + L"/AH_0001", + L"/AH_0002", + L"/AT_0001", + L"/AT_0002", + L"/AT_0003", + L"/AT_0004", + L"/AT_0005", + L"/AT_0006", + L"/AT_0007", + L"/AT_0008", + L"/AT_0009", + L"/AT_0010", + L"/AT_0011", + L"/AT_0012", + L"/AP_0001", + L"/AP_0002", + L"/AP_0003", + L"/AP_0004", + L"/AP_0005", + L"/AP_0006", + L"/AP_0007", + L"/AP_0009", + L"/AP_0010", + L"/AP_0011", + L"/AP_0012", + L"/AP_0013", + L"/AP_0014", + L"/AP_0015", + L"/AP_0016", + L"/AP_0017", + L"/AP_0018", + L"/AA_0001", + L"/AT_0013", + L"/AT_0014", + L"/AT_0015", + L"/AT_0016", + L"/AT_0017", + L"/AT_0018", + L"/AP_0019", + L"/AP_0020", + L"/AP_0021", + L"/AP_0022", + L"/AP_0023", + L"/AH_0008", + L"/AH_0009",*/ + + L"gui/items", + L"terrain", }; -Textures::Textures(TexturePackRepository *skins, Options *options) -{ -// pixels = MemoryTracker::createIntBuffer(2048 * 2048); // 4J removed - now just creating this buffer when we need it - missingNo = new BufferedImage(16, 16, BufferedImage::TYPE_INT_ARGB); +Textures::Textures(TexturePackRepository* skins, Options* options) { + // pixels = MemoryTracker::createIntBuffer(2048 * 2048); // 4J removed - + // now just creating this buffer when we need it + missingNo = new BufferedImage(16, 16, BufferedImage::TYPE_INT_ARGB); this->skins = skins; this->options = options; - /* 4J - TODO, maybe... - Graphics g = missingNo.getGraphics(); - g.setColor(Color.WHITE); - g.fillRect(0, 0, 64, 64); - g.setColor(Color.BLACK); - int y = 10; - int i = 0; - while (y < 64) { - String text = (i++ % 2 == 0) ? "missing" : "texture"; - g.drawString(text, 1, y); - y += g.getFont().getSize(); - if (i % 2 == 0) y += 5; - } + /* 4J - TODO, maybe... + Graphics g = missingNo.getGraphics(); + g.setColor(Color.WHITE); + g.fillRect(0, 0, 64, 64); + g.setColor(Color.BLACK); + int y = 10; + int i = 0; + while (y < 64) { + String text = (i++ % 2 == 0) ? "missing" : "texture"; + g.drawString(text, 1, y); + y += g.getFont().getSize(); + if (i % 2 == 0) y += 5; + } - g.dispose(); - */ +g.dispose(); + */ - // 4J Stu - Changed these to our PreStitchedTextureMap from TextureMap - terrain = new PreStitchedTextureMap(Icon::TYPE_TERRAIN, L"terrain", L"textures/blocks/", missingNo, true); - items = new PreStitchedTextureMap(Icon::TYPE_ITEM, L"items", L"textures/items/", missingNo, true); + // 4J Stu - Changed these to our PreStitchedTextureMap from TextureMap + terrain = new PreStitchedTextureMap(Icon::TYPE_TERRAIN, L"terrain", + L"textures/blocks/", missingNo, true); + items = new PreStitchedTextureMap(Icon::TYPE_ITEM, L"items", + L"textures/items/", missingNo, true); - // 4J - added - preload a set of commonly used textures that can then be referenced directly be an enumerated type rather by string - loadIndexedTextures(); + // 4J - added - preload a set of commonly used textures that can then be + // referenced directly be an enumerated type rather by string + loadIndexedTextures(); } -void Textures::loadIndexedTextures() -{ - // 4J - added - preload a set of commonly used textures that can then be referenced directly be an enumerated type rather by string - for( int i = 0; i < TN_COUNT - 2; i++ ) - { - preLoadedIdx[i] = loadTexture((TEXTURE_NAME)i, std::wstring(preLoaded[i]) + L".png"); - } +void Textures::loadIndexedTextures() { + // 4J - added - preload a set of commonly used textures that can then be + // referenced directly be an enumerated type rather by string + for (int i = 0; i < TN_COUNT - 2; i++) { + preLoadedIdx[i] = + loadTexture((TEXTURE_NAME)i, std::wstring(preLoaded[i]) + L".png"); + } } -intArray Textures::loadTexturePixels(TEXTURE_NAME texId, const std::wstring& resourceName) -{ - TexturePack *skin = skins->getSelected(); +intArray Textures::loadTexturePixels(TEXTURE_NAME texId, + const std::wstring& resourceName) { + TexturePack* skin = skins->getSelected(); { intArray id = pixelsMap[resourceName]; - // 4J - if resourceName isn't in the map, it should add an element and as that will use the default constructor, its - // internal data pointer will be NULL + // 4J - if resourceName isn't in the map, it should add an element and + // as that will use the default constructor, its internal data pointer + // will be NULL if (id.data != NULL) return id; } - // 4J - removed try/catch -// try { - intArray res; - //std::wstring in = skin->getResource(resourceName); - if (false)// 4J - removed - was ( in == NULL) - { - res = loadTexturePixels(missingNo); - } - else - { - BufferedImage *bufImage = readImage(texId, resourceName); //in); - res = loadTexturePixels(bufImage); - delete bufImage; - } - - pixelsMap[resourceName] = res; - return res; -/* -} - catch (IOException e) { - e.printStackTrace(); - int[] res = loadTexturePixels(missingNo); - pixelsMap.put(resourceName, res); - return res; + // 4J - removed try/catch + // try { + intArray res; + // std::wstring in = skin->getResource(resourceName); + if (false) // 4J - removed - was ( in == NULL) + { + res = loadTexturePixels(missingNo); + } else { + BufferedImage* bufImage = readImage(texId, resourceName); // in); + res = loadTexturePixels(bufImage); + delete bufImage; } - */ + + pixelsMap[resourceName] = res; + return res; + /* + } + catch (IOException e) { + e.printStackTrace(); + int[] res = loadTexturePixels(missingNo); + pixelsMap.put(resourceName, res); + return res; + } + */ } -intArray Textures::loadTexturePixels(BufferedImage *img) -{ +intArray Textures::loadTexturePixels(BufferedImage* img) { int w = img->getWidth(); int h = img->getHeight(); - intArray pixels(w*h); + intArray pixels(w * h); return loadTexturePixels(img, pixels); } -intArray Textures::loadTexturePixels(BufferedImage *img, intArray pixels) -{ +intArray Textures::loadTexturePixels(BufferedImage* img, intArray pixels) { int w = img->getWidth(); int h = img->getHeight(); img->getRGB(0, 0, w, h, pixels, 0, w); return pixels; } -int Textures::loadTexture(int idx) -{ - if( idx == -1 ) - { - return 0; - } - else - { - if ( idx == TN_TERRAIN ) - { - terrain->getStitchedTexture()->bind(0); - return terrain->getStitchedTexture()->getGlId(); - } - if ( idx == TN_GUI_ITEMS) - { - items->getStitchedTexture()->bind(0); - return items->getStitchedTexture()->getGlId(); - } - return preLoadedIdx[idx]; - } +int Textures::loadTexture(int idx) { + if (idx == -1) { + return 0; + } else { + if (idx == TN_TERRAIN) { + terrain->getStitchedTexture()->bind(0); + return terrain->getStitchedTexture()->getGlId(); + } + if (idx == TN_GUI_ITEMS) { + items->getStitchedTexture()->bind(0); + return items->getStitchedTexture()->getGlId(); + } + return preLoadedIdx[idx]; + } } -// 4J added - textures default to standard 32-bit RGBA format, but where we can, use an 8-bit format. There's 3 different varieties of these currently -// in the renderer that map the single 8-bit channel to RGBA differently. -void Textures::setTextureFormat(const std::wstring& resourceName) -{ - // 4J Stu - These texture formats are not currently in the render header +// 4J added - textures default to standard 32-bit RGBA format, but where we can, +// use an 8-bit format. There's 3 different varieties of these currently in the +// renderer that map the single 8-bit channel to RGBA differently. +void Textures::setTextureFormat(const std::wstring& resourceName) { + // 4J Stu - These texture formats are not currently in the render header #ifdef _XBOX - if(resourceName == L"/environment/clouds.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R1G1B1Ax; - } - else if(resourceName == L"%blur%/misc/pumpkinblur.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; - } - else if(resourceName == L"%clamp%/misc/shadow.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; - } - else if(resourceName == L"/environment/snow.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; - } - else if(resourceName == L"/1_2_2/misc/explosion.png") - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; - } - else + if (resourceName == L"/environment/clouds.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R1G1B1Ax; + } else if (resourceName == L"%blur%/misc/pumpkinblur.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; + } else if (resourceName == L"%clamp%/misc/shadow.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_R0G0B0Ax; + } else if (resourceName == L"/environment/snow.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; + } else if (resourceName == L"/1_2_2/misc/explosion.png") { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGxBxAx; + } else #endif - { - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; - } + { + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; + } } -void Textures::bindTexture(const std::wstring &resourceName) -{ - bind(loadTexture(TN_COUNT,resourceName)); +void Textures::bindTexture(const std::wstring& resourceName) { + bind(loadTexture(TN_COUNT, resourceName)); } // 4J Added -void Textures::bindTexture(int resourceId) -{ - bind(loadTexture(resourceId)); +void Textures::bindTexture(int resourceId) { bind(loadTexture(resourceId)); } + +void Textures::bind(int id) { + // if (id != lastBoundId) + { + if (id < 0) return; + glBindTexture(GL_TEXTURE_2D, id); + // lastBoundId = id; + } } -void Textures::bind(int id) -{ - //if (id != lastBoundId) - { - if(id < 0) return; - glBindTexture(GL_TEXTURE_2D, id); - // lastBoundId = id; - } -} +void Textures::clearLastBoundId() { lastBoundId = -1; } -void Textures::clearLastBoundId() -{ - lastBoundId = -1; -} +int Textures::loadTexture(TEXTURE_NAME texId, + const std::wstring& resourceName) { + // char buf[256]; + // wcstombs(buf, resourceName.c_str(), 256); + // printf("Textures::loadTexture name - %s\n",buf); -int Textures::loadTexture(TEXTURE_NAME texId, const std::wstring& resourceName) -{ -// char buf[256]; -// wcstombs(buf, resourceName.c_str(), 256); -// printf("Textures::loadTexture name - %s\n",buf); + // if (resourceName.compare(L"/terrain.png") == 0) + //{ + // terrain->getStitchedTexture()->bind(0); + // return terrain->getStitchedTexture()->getGlId(); + // } + // if (resourceName.compare(L"/gui/items.png") == 0) + //{ + // items->getStitchedTexture()->bind(0); + // return items->getStitchedTexture()->getGlId(); + // } - //if (resourceName.compare(L"/terrain.png") == 0) - //{ - // terrain->getStitchedTexture()->bind(0); - // return terrain->getStitchedTexture()->getGlId(); - //} - //if (resourceName.compare(L"/gui/items.png") == 0) - //{ - // items->getStitchedTexture()->bind(0); - // return items->getStitchedTexture()->getGlId(); - //} - - // If the texture is not present in the idMap, load it, otherwise return its id + // If the texture is not present in the idMap, load it, otherwise return its + // id { - bool inMap = ( idMap.find(resourceName) != idMap.end() ); + bool inMap = (idMap.find(resourceName) != idMap.end()); int id = idMap[resourceName]; if (inMap) return id; } - std::wstring pathName = resourceName; + std::wstring pathName = resourceName; - // 4J - added special cases to avoid mipmapping on clouds & shadows - if( (resourceName == L"environment/clouds.png") || - (resourceName == L"%clamp%misc/shadow.png") || - (resourceName == L"%blur%misc/pumpkinblur.png") || - (resourceName == L"%clamp%misc/shadow.png") || - (resourceName == L"gui/icons.png" ) || - (resourceName == L"gui/gui.png" ) || - (resourceName == L"misc/footprint.png") ) - { - MIPMAP = false; - } - setTextureFormat(resourceName); - - // 4J - removed try/catch -// try { - int id = MemoryTracker::genTextures(); - - - std::wstring prefix = L"%blur%"; - bool blur = resourceName.substr(0, prefix.size()).compare(prefix) == 0; //resourceName.startsWith("%blur%"); - if (blur) pathName = resourceName.substr(6); - - prefix = L"%clamp%"; - bool clamp = resourceName.substr(0, prefix.size()).compare(prefix) == 0; //resourceName.startsWith("%clamp%"); - if (clamp) pathName = resourceName.substr(7); - - //std::wstring in = skins->getSelected()->getResource(pathName); - if (false ) // 4J - removed was ( in == NULL) - { - loadTexture(missingNo, id, blur, clamp); - } - else - { - // 4J Stu - Get resource above just returns the name for texture packs - BufferedImage *bufImage = readImage(texId, pathName); //in); - loadTexture(bufImage, id, blur, clamp); - delete bufImage; - } - - idMap[resourceName] = id; - MIPMAP = true; // 4J added - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; - return id; - /* - } catch (IOException e) { - e.printStackTrace(); - MemoryTracker.genTextures(ib); - int id = ib.get(0); - loadTexture(missingNo, id); - idMap.put(resourceName, id); - return id; + // 4J - added special cases to avoid mipmapping on clouds & shadows + if ((resourceName == L"environment/clouds.png") || + (resourceName == L"%clamp%misc/shadow.png") || + (resourceName == L"%blur%misc/pumpkinblur.png") || + (resourceName == L"%clamp%misc/shadow.png") || + (resourceName == L"gui/icons.png") || + (resourceName == L"gui/gui.png") || + (resourceName == L"misc/footprint.png")) { + MIPMAP = false; } - */ + setTextureFormat(resourceName); + + // 4J - removed try/catch + // try { + int id = MemoryTracker::genTextures(); + + std::wstring prefix = L"%blur%"; + bool blur = resourceName.substr(0, prefix.size()).compare(prefix) == + 0; // resourceName.startsWith("%blur%"); + if (blur) pathName = resourceName.substr(6); + + prefix = L"%clamp%"; + bool clamp = resourceName.substr(0, prefix.size()).compare(prefix) == + 0; // resourceName.startsWith("%clamp%"); + if (clamp) pathName = resourceName.substr(7); + + // std::wstring in = skins->getSelected()->getResource(pathName); + if (false) // 4J - removed was ( in == NULL) + { + loadTexture(missingNo, id, blur, clamp); + } else { + // 4J Stu - Get resource above just returns the name for texture packs + BufferedImage* bufImage = readImage(texId, pathName); // in); + loadTexture(bufImage, id, blur, clamp); + delete bufImage; + } + + idMap[resourceName] = id; + MIPMAP = true; // 4J added + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; + return id; + /* +} catch (IOException e) { +e.printStackTrace(); +MemoryTracker.genTextures(ib); +int id = ib.get(0); +loadTexture(missingNo, id); +idMap.put(resourceName, id); +return id; +} +*/ } -int Textures::getTexture(BufferedImage *img, C4JRender::eTextureFormat format, bool mipmap) -{ +int Textures::getTexture(BufferedImage* img, C4JRender::eTextureFormat format, + bool mipmap) { int id = MemoryTracker::genTextures(); - TEXTURE_FORMAT = format; - MIPMAP = mipmap; + TEXTURE_FORMAT = format; + MIPMAP = mipmap; loadTexture(img, id); - TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; - MIPMAP = true; + TEXTURE_FORMAT = C4JRender::TEXTURE_FORMAT_RxGyBzAw; + MIPMAP = true; loadedImages[id] = img; return id; } -void Textures::loadTexture(BufferedImage *img, int id) -{ -// printf("Textures::loadTexture BufferedImage %d\n",id); +void Textures::loadTexture(BufferedImage* img, int id) { + // printf("Textures::loadTexture BufferedImage %d\n",id); - loadTexture(img, id, false, false); + loadTexture(img, id, false, false); } -void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) -{ -// printf("Textures::loadTexture BufferedImage with blur and clamp %d\n",id); - int iMipLevels=1; - MemSect(33); +void Textures::loadTexture(BufferedImage* img, int id, bool blur, bool clamp) { + // printf("Textures::loadTexture BufferedImage with blur and clamp + //%d\n",id); + int iMipLevels = 1; + MemSect(33); glBindTexture(GL_TEXTURE_2D, id); - if (MIPMAP) - { - // Linux/PC port: force GL_NEAREST to avoid mip-level distance blurring and keep - // Minecraft textures pixel-crisp at all distances. + if (MIPMAP) { + // Linux/PC port: force GL_NEAREST to avoid mip-level distance blurring + // and keep Minecraft textures pixel-crisp at all distances. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); /* - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); - * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 4); - */ - } - else - { + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); + * glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 4); + */ + } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } - if (blur) - { + if (blur) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } - if (clamp) - { + if (clamp) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - } - else - { + } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } @@ -538,154 +506,154 @@ void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) int w = img->getWidth(); int h = img->getHeight(); - intArray rawPixels(w*h); + intArray rawPixels(w * h); img->getRGB(0, 0, w, h, rawPixels, 0, w); - if (options != NULL && options->anaglyph3d) - { - rawPixels = anaglyph(rawPixels); - } + if (options != NULL && options->anaglyph3d) { + rawPixels = anaglyph(rawPixels); + } - byteArray newPixels(w * h * 4); - for (unsigned int i = 0; i < rawPixels.length; i++) - { + byteArray newPixels(w * h * 4); + for (unsigned int i = 0; i < rawPixels.length; i++) { int a = (rawPixels[i] >> 24) & 0xff; int r = (rawPixels[i] >> 16) & 0xff; int g = (rawPixels[i] >> 8) & 0xff; int b = (rawPixels[i]) & 0xff; #ifdef _XBOX - newPixels[i * 4 + 0] = (uint8_t) a; - newPixels[i * 4 + 1] = (uint8_t) r; - newPixels[i * 4 + 2] = (uint8_t) g; - newPixels[i * 4 + 3] = (uint8_t) b; + newPixels[i * 4 + 0] = (uint8_t)a; + newPixels[i * 4 + 1] = (uint8_t)r; + newPixels[i * 4 + 2] = (uint8_t)g; + newPixels[i * 4 + 3] = (uint8_t)b; #else - newPixels[i * 4 + 0] = (uint8_t) r; - newPixels[i * 4 + 1] = (uint8_t) g; - newPixels[i * 4 + 2] = (uint8_t) b; - newPixels[i * 4 + 3] = (uint8_t) a; + newPixels[i * 4 + 0] = (uint8_t)r; + newPixels[i * 4 + 1] = (uint8_t)g; + newPixels[i * 4 + 2] = (uint8_t)b; + newPixels[i * 4 + 3] = (uint8_t)a; #endif } - // 4J - now creating a buffer of the size we require dynamically - ByteBuffer *pixels = MemoryTracker::createByteBuffer(w * h * 4); + // 4J - now creating a buffer of the size we require dynamically + ByteBuffer* pixels = MemoryTracker::createByteBuffer(w * h * 4); pixels->clear(); pixels->put(newPixels); pixels->position(0)->limit(newPixels.length); - delete[] rawPixels.data; - delete[] newPixels.data; - - if (MIPMAP) - { - // 4J-PB - In the new XDK, the CreateTexture will fail if the number of mipmaps is higher than the width & height passed in will allow! - int iWidthMips=1; - int iHeightMips=1; - while((8<5)iMipLevels = 5; - RenderManager.TextureSetTextureLevels(iMipLevels); // 4J added - } - RenderManager.TextureData(w,h,pixels->getBuffer(),0,TEXTURE_FORMAT); - //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); + delete[] rawPixels.data; + delete[] newPixels.data; - if (MIPMAP) - { - for (int level = 1; level < iMipLevels; level++) - { + if (MIPMAP) { + // 4J-PB - In the new XDK, the CreateTexture will fail if the number of + // mipmaps is higher than the width & height passed in will allow! + int iWidthMips = 1; + int iHeightMips = 1; + while ((8 << iWidthMips) < w) iWidthMips++; + while ((8 << iHeightMips) < h) iHeightMips++; + + iMipLevels = (iWidthMips < iHeightMips) ? iWidthMips : iHeightMips; + // RenderManager.TextureSetTextureLevels(5); // 4J added + if (iMipLevels > 5) iMipLevels = 5; + RenderManager.TextureSetTextureLevels(iMipLevels); // 4J added + } + RenderManager.TextureData(w, h, pixels->getBuffer(), 0, TEXTURE_FORMAT); + // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL12.GL_BGRA, + // GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); + + if (MIPMAP) { + for (int level = 1; level < iMipLevels; level++) { int ow = w >> (level - 1); // int oh = h >> (level - 1); int ww = w >> level; int hh = h >> level; - // 4J - added tempData so we aren't overwriting source data - unsigned int *tempData = new unsigned int[ww * hh]; - // 4J - added - have we loaded mipmap data for this level? Use that rather than generating if possible - if( img->getData( level ) ) - { - memcpy( tempData, img->getData( level ), ww * hh * 4); + // 4J - added tempData so we aren't overwriting source data + unsigned int* tempData = new unsigned int[ww * hh]; + // 4J - added - have we loaded mipmap data for this level? Use that + // rather than generating if possible + if (img->getData(level)) { + memcpy(tempData, img->getData(level), ww * hh * 4); #ifndef _XBOX - // Swap ARGB to RGBA - for( int i = 0; i < ww * hh ; i++ ) - { - tempData[i] = ( tempData[i] >> 24 ) | (tempData[i] << 8 ); - } + // Swap ARGB to RGBA + for (int i = 0; i < ww * hh; i++) { + tempData[i] = (tempData[i] >> 24) | (tempData[i] << 8); + } #endif - } - else - { - for (int x = 0; x < ww; x++) - for (int y = 0; y < hh; y++) - { - int c0 = pixels->getInt(((x * 2 + 0) + (y * 2 + 0) * ow) * 4); - int c1 = pixels->getInt(((x * 2 + 1) + (y * 2 + 0) * ow) * 4); - int c2 = pixels->getInt(((x * 2 + 1) + (y * 2 + 1) * ow) * 4); - int c3 = pixels->getInt(((x * 2 + 0) + (y * 2 + 1) * ow) * 4); + } else { + for (int x = 0; x < ww; x++) + for (int y = 0; y < hh; y++) { + int c0 = pixels->getInt( + ((x * 2 + 0) + (y * 2 + 0) * ow) * 4); + int c1 = pixels->getInt( + ((x * 2 + 1) + (y * 2 + 0) * ow) * 4); + int c2 = pixels->getInt( + ((x * 2 + 1) + (y * 2 + 1) * ow) * 4); + int c3 = pixels->getInt( + ((x * 2 + 0) + (y * 2 + 1) * ow) * 4); #ifndef _XBOX - // 4J - convert our RGBA texels to ARGB that crispBlend is expecting - // 4jcraft, added uint cast to pervent shift of neg int - c0 = ( ( c0 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c0 << 24 ); - c1 = ( ( c1 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c1 << 24 ); - c2 = ( ( c2 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c2 << 24 ); - c3 = ( ( c3 >> 8 ) & 0x00ffffff ) | ( (unsigned int) c3 << 24 ); + // 4J - convert our RGBA texels to ARGB that crispBlend + // is expecting 4jcraft, added uint cast to pervent + // shift of neg int + c0 = + ((c0 >> 8) & 0x00ffffff) | ((unsigned int)c0 << 24); + c1 = + ((c1 >> 8) & 0x00ffffff) | ((unsigned int)c1 << 24); + c2 = + ((c2 >> 8) & 0x00ffffff) | ((unsigned int)c2 << 24); + c3 = + ((c3 >> 8) & 0x00ffffff) | ((unsigned int)c3 << 24); #endif - int col = Texture::crispBlend(Texture::crispBlend(c0, c1), Texture::crispBlend(c2, c3)); + int col = + Texture::crispBlend(Texture::crispBlend(c0, c1), + Texture::crispBlend(c2, c3)); #ifndef _XBOX - // 4J - and back from ARGB -> RGBA - col = ( (unsigned int) col << 8 ) | (( col >> 24 ) & 0xff); + // 4J - and back from ARGB -> RGBA + col = ((unsigned int)col << 8) | ((col >> 24) & 0xff); #endif - tempData[x + y * ww] = col; - } - } - for (int x = 0; x < ww; x++ ) - for (int y = 0; y < hh; y++) - { - pixels->putInt((x + y * ww) * 4, tempData[x + y * ww]); - } - delete [] tempData; - RenderManager.TextureData(ww,hh,pixels->getBuffer(),level,TEXTURE_FORMAT); + tempData[x + y * ww] = col; + } + } + for (int x = 0; x < ww; x++) + for (int y = 0; y < hh; y++) { + pixels->putInt((x + y * ww) * 4, tempData[x + y * ww]); + } + delete[] tempData; + RenderManager.TextureData(ww, hh, pixels->getBuffer(), level, + TEXTURE_FORMAT); } } /* - * if (MIPMAP) { GLU.gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, w, h, - * GL_RGBA, GL_UNSIGNED_BYTE, pixels); } else { } - */ - delete pixels; // 4J - now creating this dynamically - MemSect(0); + * if (MIPMAP) { GLU.gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, w, h, + * GL_RGBA, GL_UNSIGNED_BYTE, pixels); } else { } + */ + delete pixels; // 4J - now creating this dynamically + MemSect(0); } -intArray Textures::anaglyph(intArray rawPixels) -{ - intArray result(rawPixels.length); - for (unsigned int i = 0; i < rawPixels.length; i++) - { - int a = (rawPixels[i] >> 24) & 0xff; - int r = (rawPixels[i] >> 16) & 0xff; - int g = (rawPixels[i] >> 8) & 0xff; - int b = (rawPixels[i]) & 0xff; +intArray Textures::anaglyph(intArray rawPixels) { + intArray result(rawPixels.length); + for (unsigned int i = 0; i < rawPixels.length; i++) { + int a = (rawPixels[i] >> 24) & 0xff; + int r = (rawPixels[i] >> 16) & 0xff; + int g = (rawPixels[i] >> 8) & 0xff; + int b = (rawPixels[i]) & 0xff; - int rr = (r * 30 + g * 59 + b * 11) / 100; - int gg = (r * 30 + g * 70) / (100); - int bb = (r * 30 + b * 70) / (100); + int rr = (r * 30 + g * 59 + b * 11) / 100; + int gg = (r * 30 + g * 70) / (100); + int bb = (r * 30 + b * 70) / (100); + result[i] = a << 24 | rr << 16 | gg << 8 | bb; + } - result[i] = a << 24 | rr << 16 | gg << 8 | bb; - } + delete[] rawPixels.data; - delete[] rawPixels.data; - - return result; + return result; } -void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) -{ +void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) { bind(id); - // Removed in Java + // Removed in Java #if 0 if (MIPMAP) { @@ -700,29 +668,26 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) } else #endif - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - if (options != NULL && options->anaglyph3d) - { - rawPixels = anaglyph(rawPixels); - } + if (options != NULL && options->anaglyph3d) { + rawPixels = anaglyph(rawPixels); + } - byteArray newPixels(w * h * 4); - for (unsigned int i = 0; i < rawPixels.length; i++) - { + byteArray newPixels(w * h * 4); + for (unsigned int i = 0; i < rawPixels.length; i++) { int a = (rawPixels[i] >> 24) & 0xff; int r = (rawPixels[i] >> 16) & 0xff; int g = (rawPixels[i] >> 8) & 0xff; int b = (rawPixels[i]) & 0xff; - if (options != NULL && options->anaglyph3d) - { + if (options != NULL && options->anaglyph3d) { int rr = (r * 30 + g * 59 + b * 11) / 100; int gg = (r * 30 + g * 70) / (100); int bb = (r * 30 + b * 70) / (100); @@ -732,35 +697,38 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) b = bb; } - newPixels[i * 4 + 0] = (uint8_t) r; - newPixels[i * 4 + 1] = (uint8_t) g; - newPixels[i * 4 + 2] = (uint8_t) b; - newPixels[i * 4 + 3] = (uint8_t) a; + newPixels[i * 4 + 0] = (uint8_t)r; + newPixels[i * 4 + 1] = (uint8_t)g; + newPixels[i * 4 + 2] = (uint8_t)b; + newPixels[i * 4 + 3] = (uint8_t)a; } - ByteBuffer *pixels = MemoryTracker::createByteBuffer(w * h * 4); // 4J - now creating dynamically + ByteBuffer* pixels = MemoryTracker::createByteBuffer( + w * h * 4); // 4J - now creating dynamically pixels->put(newPixels); pixels->position(0)->limit(newPixels.length); - delete [] newPixels.data; + delete[] newPixels.data; - // New - // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); + // New + // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL12.GL_BGRA, + // GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); #ifdef _XBOX - RenderManager.TextureDataUpdate(pixels->getBuffer(),0); + RenderManager.TextureDataUpdate(pixels->getBuffer(), 0); #else - RenderManager.TextureDataUpdate(0, 0,w,h,pixels->getBuffer(),0); + RenderManager.TextureDataUpdate(0, 0, w, h, pixels->getBuffer(), 0); #endif - // Old - //glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - delete pixels; + // Old + // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, + // pixels); + delete pixels; } -// 4J - added. This is a more minimal version of replaceTexture that assumes the texture bytes are already in order, and so doesn't do any of the extra copying round -// that the original java version does -void Textures::replaceTextureDirect(intArray rawPixels, int w, int h, int id) -{ +// 4J - added. This is a more minimal version of replaceTexture that assumes the +// texture bytes are already in order, and so doesn't do any of the extra +// copying round that the original java version does +void Textures::replaceTextureDirect(intArray rawPixels, int w, int h, int id) { glBindTexture(GL_TEXTURE_2D, id); - // Remove in Java + // Remove in Java #if 0 if (MIPMAP) { @@ -775,28 +743,29 @@ void Textures::replaceTextureDirect(intArray rawPixels, int w, int h, int id) } else #endif - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); #ifdef _XBOX - RenderManager.TextureDataUpdate(rawPixels.data, 0); + RenderManager.TextureDataUpdate(rawPixels.data, 0); #else - RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); + RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); #endif } -// 4J - added. This is a more minimal version of replaceTexture that assumes the texture bytes are already in order, and so doesn't do any of the extra copying round -// that the original java version does -void Textures::replaceTextureDirect(shortArray rawPixels, int w, int h, int id) -{ +// 4J - added. This is a more minimal version of replaceTexture that assumes the +// texture bytes are already in order, and so doesn't do any of the extra +// copying round that the original java version does +void Textures::replaceTextureDirect(shortArray rawPixels, int w, int h, + int id) { glBindTexture(GL_TEXTURE_2D, id); - // Remove in Java + // Remove in Java #if 0 if (MIPMAP) { @@ -811,105 +780,84 @@ void Textures::replaceTextureDirect(shortArray rawPixels, int w, int h, int id) } else #endif - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); #ifdef _XBOX - RenderManager.TextureDataUpdate(rawPixels.data, 0); + RenderManager.TextureDataUpdate(rawPixels.data, 0); #else - RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); + RenderManager.TextureDataUpdate(0, 0, w, h, rawPixels.data, 0); #endif } -void Textures::releaseTexture(int id) -{ +void Textures::releaseTexture(int id) { loadedImages.erase(id); glDeleteTextures(id); } -int Textures::loadHttpTexture(const std::wstring& url, const std::wstring& backup) -{ - HttpTexture *texture = httpTextures[url]; - if (texture != NULL) - { - if (texture->loadedImage != NULL && !texture->isLoaded) - { - if (texture->id < 0) - { +int Textures::loadHttpTexture(const std::wstring& url, + const std::wstring& backup) { + HttpTexture* texture = httpTextures[url]; + if (texture != NULL) { + if (texture->loadedImage != NULL && !texture->isLoaded) { + if (texture->id < 0) { texture->id = getTexture(texture->loadedImage); - } - else - { + } else { loadTexture(texture->loadedImage, texture->id); } texture->isLoaded = true; } } - if (texture == NULL || texture->id < 0) - { - if (backup.empty() ) return -1; + if (texture == NULL || texture->id < 0) { + if (backup.empty()) return -1; return loadTexture(TN_COUNT, backup); } return texture->id; } -int Textures::loadHttpTexture(const std::wstring& url, int backup) -{ - HttpTexture *texture = httpTextures[url]; - if (texture != NULL) - { - if (texture->loadedImage != NULL && !texture->isLoaded) - { - if (texture->id < 0) - { +int Textures::loadHttpTexture(const std::wstring& url, int backup) { + HttpTexture* texture = httpTextures[url]; + if (texture != NULL) { + if (texture->loadedImage != NULL && !texture->isLoaded) { + if (texture->id < 0) { texture->id = getTexture(texture->loadedImage); - } - else - { + } else { loadTexture(texture->loadedImage, texture->id); } texture->isLoaded = true; } } - if (texture == NULL || texture->id < 0) - { + if (texture == NULL || texture->id < 0) { return loadTexture(backup); } return texture->id; } -bool Textures::hasHttpTexture(const std::wstring &url) -{ - return httpTextures.find(url) != httpTextures.end(); +bool Textures::hasHttpTexture(const std::wstring& url) { + return httpTextures.find(url) != httpTextures.end(); } -HttpTexture *Textures::addHttpTexture(const std::wstring& url, HttpTextureProcessor *processor) -{ - HttpTexture *texture = httpTextures[url]; - if (texture == NULL) - { +HttpTexture* Textures::addHttpTexture(const std::wstring& url, + HttpTextureProcessor* processor) { + HttpTexture* texture = httpTextures[url]; + if (texture == NULL) { httpTextures[url] = new HttpTexture(url, processor); - } - else - { + } else { texture->count++; } return texture; } -void Textures::removeHttpTexture(const std::wstring& url) -{ - HttpTexture *texture = httpTextures[url]; - if (texture != NULL) - { +void Textures::removeHttpTexture(const std::wstring& url) { + HttpTexture* texture = httpTextures[url]; + if (texture != NULL) { texture->count--; - if (texture->count == 0) - { + if (texture->count == 0) { if (texture->id >= 0) releaseTexture(texture->id); httpTextures.erase(url); } @@ -917,130 +865,112 @@ void Textures::removeHttpTexture(const std::wstring& url) } // 4J-PB - adding for texture in memory (from global title storage) -int Textures::loadMemTexture(const std::wstring& url, const std::wstring& backup) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) - { - texture = (*it).second; - } - if(texture == NULL && app.IsFileInMemoryTextures(url)) - { - // If we haven't loaded it yet, but we have the data for it then add it - texture = addMemTexture(url, new MobSkinMemTextureProcessor() ); - } - if(texture != NULL) - { - if (texture->loadedImage != NULL && !texture->isLoaded) - { - // 4J - Disable mipmapping in general for skins & capes. Have seen problems with edge-on polys for some eg mumbo jumbo - if( ( url.substr(0,7) == L"dlcskin" ) || - ( url.substr(0,7) == L"dlccape" ) ) - { - MIPMAP = false; - } +int Textures::loadMemTexture(const std::wstring& url, + const std::wstring& backup) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(url)); + if (it != memTextures.end()) { + texture = (*it).second; + } + if (texture == NULL && app.IsFileInMemoryTextures(url)) { + // If we haven't loaded it yet, but we have the data for it then add it + texture = addMemTexture(url, new MobSkinMemTextureProcessor()); + } + if (texture != NULL) { + if (texture->loadedImage != NULL && !texture->isLoaded) { + // 4J - Disable mipmapping in general for skins & capes. Have seen + // problems with edge-on polys for some eg mumbo jumbo + if ((url.substr(0, 7) == L"dlcskin") || + (url.substr(0, 7) == L"dlccape")) { + MIPMAP = false; + } - if (texture->id < 0) - { - texture->id = getTexture(texture->loadedImage, C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); - } - else - { - loadTexture(texture->loadedImage, texture->id); - } - texture->isLoaded = true; - MIPMAP = true; - } - } - if (texture == NULL || texture->id < 0) - { - if (backup.empty() ) return -1; - return loadTexture(TN_COUNT,backup); - } - return texture->id; + if (texture->id < 0) { + texture->id = + getTexture(texture->loadedImage, + C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); + } else { + loadTexture(texture->loadedImage, texture->id); + } + texture->isLoaded = true; + MIPMAP = true; + } + } + if (texture == NULL || texture->id < 0) { + if (backup.empty()) return -1; + return loadTexture(TN_COUNT, backup); + } + return texture->id; } -int Textures::loadMemTexture(const std::wstring& url, int backup) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) - { - texture = (*it).second; - } - if(texture == NULL && app.IsFileInMemoryTextures(url)) - { - // If we haven't loaded it yet, but we have the data for it then add it - texture = addMemTexture(url, new MobSkinMemTextureProcessor() ); - } - if(texture != NULL) - { - texture->ticksSinceLastUse = 0; - if (texture->loadedImage != NULL && !texture->isLoaded) - { - // 4J - Disable mipmapping in general for skins & capes. Have seen problems with edge-on polys for some eg mumbo jumbo - if( ( url.substr(0,7) == L"dlcskin" ) || - ( url.substr(0,7) == L"dlccape" ) ) - { - MIPMAP = false; - } - if (texture->id < 0) - { - texture->id = getTexture(texture->loadedImage, C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); - } - else - { - loadTexture(texture->loadedImage, texture->id); - } - texture->isLoaded = true; - MIPMAP = true; - } - } - if (texture == NULL || texture->id < 0) - { - return loadTexture(backup); - } - return texture->id; +int Textures::loadMemTexture(const std::wstring& url, int backup) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(url)); + if (it != memTextures.end()) { + texture = (*it).second; + } + if (texture == NULL && app.IsFileInMemoryTextures(url)) { + // If we haven't loaded it yet, but we have the data for it then add it + texture = addMemTexture(url, new MobSkinMemTextureProcessor()); + } + if (texture != NULL) { + texture->ticksSinceLastUse = 0; + if (texture->loadedImage != NULL && !texture->isLoaded) { + // 4J - Disable mipmapping in general for skins & capes. Have seen + // problems with edge-on polys for some eg mumbo jumbo + if ((url.substr(0, 7) == L"dlcskin") || + (url.substr(0, 7) == L"dlccape")) { + MIPMAP = false; + } + if (texture->id < 0) { + texture->id = + getTexture(texture->loadedImage, + C4JRender::TEXTURE_FORMAT_RxGyBzAw, MIPMAP); + } else { + loadTexture(texture->loadedImage, texture->id); + } + texture->isLoaded = true; + MIPMAP = true; + } + } + if (texture == NULL || texture->id < 0) { + return loadTexture(backup); + } + return texture->id; } -MemTexture *Textures::addMemTexture(const std::wstring& name,MemTextureProcessor *processor) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(name) ); - if (it != memTextures.end()) - { - texture = (*it).second; - } - if(texture == NULL) - { - // can we find it in the app mem files? - std::uint8_t *pbData=NULL; - unsigned int dwBytes=0; - app.GetMemFileDetails(name,&pbData,&dwBytes); +MemTexture* Textures::addMemTexture(const std::wstring& name, + MemTextureProcessor* processor) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(name)); + if (it != memTextures.end()) { + texture = (*it).second; + } + if (texture == NULL) { + // can we find it in the app mem files? + std::uint8_t* pbData = NULL; + unsigned int dwBytes = 0; + app.GetMemFileDetails(name, &pbData, &dwBytes); - if(dwBytes!=0) - { - texture = new MemTexture(name, pbData, dwBytes, processor); - memTextures[name] = texture; - } - else - { - // 4J Stu - Make an entry for this anyway and we can populate it later - memTextures[name] = NULL; - } - } - else - { - texture->count++; - } + if (dwBytes != 0) { + texture = new MemTexture(name, pbData, dwBytes, processor); + memTextures[name] = texture; + } else { + // 4J Stu - Make an entry for this anyway and we can populate it + // later + memTextures[name] = NULL; + } + } else { + texture->count++; + } - delete processor; + delete processor; - return texture; + return texture; } -// MemTexture *Textures::getMemTexture(const std::wstring& url, MemTextureProcessor *processor) +// MemTexture *Textures::getMemTexture(const std::wstring& url, +// MemTextureProcessor *processor) // { // MemTexture *texture = memTextures[url]; // if (texture != NULL) @@ -1050,93 +980,90 @@ MemTexture *Textures::addMemTexture(const std::wstring& name,MemTextureProcessor // return texture; // } -void Textures::removeMemTexture(const std::wstring& url) -{ - MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) - { - texture = (*it).second; +void Textures::removeMemTexture(const std::wstring& url) { + MemTexture* texture = NULL; + AUTO_VAR(it, memTextures.find(url)); + if (it != memTextures.end()) { + texture = (*it).second; - // If it's NULL then we should just remove the entry - if( texture == NULL ) memTextures.erase(url); - } - if(texture != NULL) - { - texture->count--; - if (texture->count == 0) - { - if (texture->id >= 0) releaseTexture(texture->id); - memTextures.erase(url); - delete texture; - } - } + // If it's NULL then we should just remove the entry + if (texture == NULL) memTextures.erase(url); + } + if (texture != NULL) { + texture->count--; + if (texture->count == 0) { + if (texture->id >= 0) releaseTexture(texture->id); + memTextures.erase(url); + delete texture; + } + } } -void Textures::tick(bool updateTextures, bool tickDynamics) // 4J added updateTextures parameter & tickDynamics +void Textures::tick( + bool updateTextures, + bool tickDynamics) // 4J added updateTextures parameter & tickDynamics { - MemSect(22); - if(tickDynamics) - { - // 4J - added - if we aren't updating the final renderer textures, just tick each of the dynamic textures instead. This is used so that in frames were we have multiple - // ticks due to framerate compensation, that we don't lock the renderer textures twice needlessly and force the CPU to sync with the GPU. - if( !updateTextures ) - { - MemSect(0); - return; - } + MemSect(22); + if (tickDynamics) { + // 4J - added - if we aren't updating the final renderer textures, just + // tick each of the dynamic textures instead. This is used so that in + // frames were we have multiple ticks due to framerate compensation, + // that we don't lock the renderer textures twice needlessly and force + // the CPU to sync with the GPU. + if (!updateTextures) { + MemSect(0); + return; + } - // 4J - added - tell renderer that we're about to do a block of dynamic texture updates, so we can unlock the resources after they are done rather than a series of locks/unlocks - //RenderManager.TextureDynamicUpdateStart(); - terrain->cycleAnimationFrames(); + // 4J - added - tell renderer that we're about to do a block of dynamic + // texture updates, so we can unlock the resources after they are done + // rather than a series of locks/unlocks + // RenderManager.TextureDynamicUpdateStart(); + terrain->cycleAnimationFrames(); items->cycleAnimationFrames(); - //RenderManager.TextureDynamicUpdateEnd(); // 4J added - see comment above - } + // RenderManager.TextureDynamicUpdateEnd(); // 4J added - see + // comment above + } - // 4J - go over all the memory textures once per frame, and free any that haven't been used for a while. Ones that are being used will - // have their ticksSinceLastUse reset in Textures::loadMemTexture. - for( AUTO_VAR(it, memTextures.begin() ); it != memTextures.end(); ) - { - MemTexture *tex = it->second; + // 4J - go over all the memory textures once per frame, and free any that + // haven't been used for a while. Ones that are being used will have their + // ticksSinceLastUse reset in Textures::loadMemTexture. + for (AUTO_VAR(it, memTextures.begin()); it != memTextures.end();) { + MemTexture* tex = it->second; - if( tex && ( ++tex->ticksSinceLastUse > MemTexture::UNUSED_TICKS_TO_FREE ) ) - { - if (tex->id >= 0) releaseTexture(tex->id); - delete tex; - it = memTextures.erase(it); - } - else - { - it++; - } - - } - MemSect(0); + if (tex && + (++tex->ticksSinceLastUse > MemTexture::UNUSED_TICKS_TO_FREE)) { + if (tex->id >= 0) releaseTexture(tex->id); + delete tex; + it = memTextures.erase(it); + } else { + it++; + } + } + MemSect(0); } -void Textures::reloadAll() -{ - TexturePack *skin = skins->getSelected(); +void Textures::reloadAll() { + TexturePack* skin = skins->getSelected(); - for( int i = 0; i < TN_COUNT - 2; i++ ) - { - releaseTexture(preLoadedIdx[i]); - } + for (int i = 0; i < TN_COUNT - 2; i++) { + releaseTexture(preLoadedIdx[i]); + } - idMap.clear(); - loadedImages.clear(); + idMap.clear(); + loadedImages.clear(); - loadIndexedTextures(); + loadIndexedTextures(); - pixelsMap.clear(); - // 4J Stu - These are not used any more - //WaterColor::init(loadTexturePixels(L"misc/watercolor.png")); - //GrassColor::init(loadTexturePixels(L"misc/grasscolor.png")); - //FoliageColor::init(loadTexturePixels(L"misc/foliagecolor.png")); + pixelsMap.clear(); + // 4J Stu - These are not used any more + // WaterColor::init(loadTexturePixels(L"misc/watercolor.png")); + // GrassColor::init(loadTexturePixels(L"misc/grasscolor.png")); + // FoliageColor::init(loadTexturePixels(L"misc/foliagecolor.png")); - stitch(); + stitch(); - skins->clearInvalidTexturePacks(); + skins->clearInvalidTexturePacks(); #if 0 AUTO_VAR(itEndLI, loadedImages.end() ); @@ -1191,222 +1118,167 @@ void Textures::reloadAll() } #endif - // Recalculate fonts - //Minecraft::GetInstance()->font->loadCharacterWidths(); - //Minecraft::GetInstance()->altFont->loadCharacterWidths(); + // Recalculate fonts + // Minecraft::GetInstance()->font->loadCharacterWidths(); + // Minecraft::GetInstance()->altFont->loadCharacterWidths(); } -void Textures::stitch() -{ - terrain->stitch(); - items->stitch(); +void Textures::stitch() { + terrain->stitch(); + items->stitch(); } -Icon *Textures::getMissingIcon(int type) -{ - switch (type) - { - case Icon::TYPE_ITEM: - default: - return items->getMissingIcon(); - case Icon::TYPE_TERRAIN: - return terrain->getMissingIcon(); - } +Icon* Textures::getMissingIcon(int type) { + switch (type) { + case Icon::TYPE_ITEM: + default: + return items->getMissingIcon(); + case Icon::TYPE_TERRAIN: + return terrain->getMissingIcon(); + } } -BufferedImage *Textures::readImage(TEXTURE_NAME texId, const std::wstring& name) // 4J was InputStream *in +BufferedImage* Textures::readImage( + TEXTURE_NAME texId, const std::wstring& name) // 4J was InputStream *in { - BufferedImage *img=NULL; - MemSect(32); - // is this image one of the Title Update ones? - bool isTu = IsTUImage(texId, name); - std::wstring drive = L""; + BufferedImage* img = NULL; + MemSect(32); + // is this image one of the Title Update ones? + bool isTu = IsTUImage(texId, name); + std::wstring drive = L""; - if(!skins->isUsingDefaultSkin() && skins->getSelected()->hasFile(L"res/" + name,false)) - { - drive = skins->getSelected()->getPath(isTu); - img = skins->getSelected()->getImageResource(name, false, isTu, drive); //new BufferedImage(name,false,isTu,drive); - } - else - { - const char *pchName=wstringtofilename(name); + if (!skins->isUsingDefaultSkin() && + skins->getSelected()->hasFile(L"res/" + name, false)) { + drive = skins->getSelected()->getPath(isTu); + img = skins->getSelected()->getImageResource( + name, false, isTu, + drive); // new BufferedImage(name,false,isTu,drive); + } else { + const char* pchName = wstringtofilename(name); #ifdef __PS3__ - if(app.GetBootedFromDiscPatch() && app.IsFileInPatchList(pchName)) - { - char *pchUsrDir = app.GetBDUsrDirPath(pchName); - std::wstring wstr (pchUsrDir, pchUsrDir+strlen(pchUsrDir)); + if (app.GetBootedFromDiscPatch() && app.IsFileInPatchList(pchName)) { + char* pchUsrDir = app.GetBDUsrDirPath(pchName); + std::wstring wstr(pchUsrDir, pchUsrDir + strlen(pchUsrDir)); - if(isTu) - { - drive= wstr + L"\\Common\\res\\TitleUpdate\\"; + if (isTu) { + drive = wstr + L"\\Common\\res\\TitleUpdate\\"; - } - else - { - drive= wstr + L"\\Common\\"; - } - } - else + } else { + drive = wstr + L"\\Common\\"; + } + } else #endif - { - drive = skins->getDefault()->getPath(isTu); - } + { + drive = skins->getDefault()->getPath(isTu); + } - const char *pchDrive=wstringtofilename(drive); + const char* pchDrive = wstringtofilename(drive); - if(IsOriginalImage(texId, name) || isTu) - { - img = skins->getDefault()->getImageResource(name,false,isTu,drive); //new BufferedImage(name,false,isTu,drive); - } - else - { - img = skins->getDefault()->getImageResource(L"1_2_2/" + name, false, isTu, drive); //new BufferedImage(L"/1_2_2" + name,false,isTu,drive); - } - } + if (IsOriginalImage(texId, name) || isTu) { + img = skins->getDefault()->getImageResource( + name, false, isTu, + drive); // new BufferedImage(name,false,isTu,drive); + } else { + img = skins->getDefault()->getImageResource( + L"1_2_2/" + name, false, isTu, + drive); // new BufferedImage(L"/1_2_2" + + // name,false,isTu,drive); + } + } - MemSect(0); + MemSect(0); return img; } // Match the preload images from their enum to avoid a ton of string comparisons -TEXTURE_NAME TUImages[] = -{ - TN_POWERED_CREEPER, - TN_MOB_ENDERMAN_EYES, - TN_MISC_EXPLOSION, - TN_MOB_ZOMBIE, - TN_MISC_FOOTSTEP, - TN_MOB_RED_COW, - TN_MOB_SNOWMAN, - TN_MOB_ENDERDRAGON, - TN_MOB_VILLAGER_VILLAGER, - TN_MOB_VILLAGER_FARMER, - TN_MOB_VILLAGER_LIBRARIAN, - TN_MOB_VILLAGER_PRIEST, - TN_MOB_VILLAGER_SMITH, - TN_MOB_VILLAGER_BUTCHER, - TN_MOB_ENDERDRAGON_ENDEREYES, - TN__BLUR__MISC_GLINT, - TN_ITEM_BOOK, - TN_MISC_PARTICLEFIELD, +TEXTURE_NAME TUImages[] = { + TN_POWERED_CREEPER, TN_MOB_ENDERMAN_EYES, TN_MISC_EXPLOSION, TN_MOB_ZOMBIE, + TN_MISC_FOOTSTEP, TN_MOB_RED_COW, TN_MOB_SNOWMAN, TN_MOB_ENDERDRAGON, + TN_MOB_VILLAGER_VILLAGER, TN_MOB_VILLAGER_FARMER, TN_MOB_VILLAGER_LIBRARIAN, + TN_MOB_VILLAGER_PRIEST, TN_MOB_VILLAGER_SMITH, TN_MOB_VILLAGER_BUTCHER, + TN_MOB_ENDERDRAGON_ENDEREYES, TN__BLUR__MISC_GLINT, TN_ITEM_BOOK, + TN_MISC_PARTICLEFIELD, - // TU9 - TN_MISC_TUNNEL, - TN_MOB_ENDERDRAGON_BEAM, - TN_GUI_ITEMS, - TN_TERRAIN, - TN_MISC_MAPICONS, + // TU9 + TN_MISC_TUNNEL, TN_MOB_ENDERDRAGON_BEAM, TN_GUI_ITEMS, TN_TERRAIN, + TN_MISC_MAPICONS, - // TU12 - TN_MOB_WITHER_SKELETON, + // TU12 + TN_MOB_WITHER_SKELETON, - // TU14 - TN_TILE_ENDER_CHEST, - TN_ART_KZ, - TN_MOB_WOLF_TAME, - TN_MOB_WOLF_COLLAR, - TN_PARTICLES, - TN_MOB_ZOMBIE_VILLAGER, + // TU14 + TN_TILE_ENDER_CHEST, TN_ART_KZ, TN_MOB_WOLF_TAME, TN_MOB_WOLF_COLLAR, + TN_PARTICLES, TN_MOB_ZOMBIE_VILLAGER, #ifdef _LARGE_WORLDS - TN_MISC_ADDITIONALMAPICONS, + TN_MISC_ADDITIONALMAPICONS, #endif - // TU17 - TN_DEFAULT_FONT, - // TN_ALT_FONT, // Not in TU yet + // TU17 + TN_DEFAULT_FONT, + // TN_ALT_FONT, // Not in TU yet - TN_COUNT // Why is this here? + TN_COUNT // Why is this here? }; // This is for any TU textures that aren't part of our enum indexed preload set -const wchar_t *TUImagePaths[] = -{ - L"font/Default", - L"font/Mojangles_7", - L"font/Mojangles_11", +const wchar_t* TUImagePaths[] = {L"font/Default", L"font/Mojangles_7", + L"font/Mojangles_11", - // TU12 - L"armor/cloth_1.png", - L"armor/cloth_1_b.png", - L"armor/cloth_2.png", - L"armor/cloth_2_b.png", + // TU12 + L"armor/cloth_1.png", L"armor/cloth_1_b.png", + L"armor/cloth_2.png", L"armor/cloth_2_b.png", - NULL -}; + NULL}; -bool Textures::IsTUImage(TEXTURE_NAME texId, const std::wstring& name) -{ - int i = 0; - if(texId < TN_COUNT) - { - while(TUImages[i] < TN_COUNT) - { - if(texId == TUImages[i]) - { - return true; - } - i++; - } - } - i = 0; - while(TUImagePaths[i]) - { - if(name.compare(TUImagePaths[i])==0) - { - return true; - } - i++; - } - return false; +bool Textures::IsTUImage(TEXTURE_NAME texId, const std::wstring& name) { + int i = 0; + if (texId < TN_COUNT) { + while (TUImages[i] < TN_COUNT) { + if (texId == TUImages[i]) { + return true; + } + i++; + } + } + i = 0; + while (TUImagePaths[i]) { + if (name.compare(TUImagePaths[i]) == 0) { + return true; + } + i++; + } + return false; } -TEXTURE_NAME OriginalImages[] = -{ - TN_MOB_CHAR, - TN_MOB_CHAR1, - TN_MOB_CHAR2, - TN_MOB_CHAR3, - TN_MOB_CHAR4, - TN_MOB_CHAR5, - TN_MOB_CHAR6, - TN_MOB_CHAR7, +TEXTURE_NAME OriginalImages[] = {TN_MOB_CHAR, TN_MOB_CHAR1, TN_MOB_CHAR2, + TN_MOB_CHAR3, TN_MOB_CHAR4, TN_MOB_CHAR5, + TN_MOB_CHAR6, TN_MOB_CHAR7, - TN_MISC_MAPBG, + TN_MISC_MAPBG, - TN_COUNT -}; - -const wchar_t *OriginalImagesPaths[] = -{ - L"misc/watercolor.png", + TN_COUNT}; - NULL -}; +const wchar_t* OriginalImagesPaths[] = {L"misc/watercolor.png", -bool Textures::IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name) -{ - int i = 0; - if(texId < TN_COUNT) - { - while(OriginalImages[i] < TN_COUNT) - { - if(texId == OriginalImages[i]) - { - return true; - } - i++; - } - } - i = 0; - while(OriginalImagesPaths[i]) - { - if(name.compare(OriginalImagesPaths[i])==0) - { - return true; - } - i++; - } - return false; + NULL}; + +bool Textures::IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name) { + int i = 0; + if (texId < TN_COUNT) { + while (OriginalImages[i] < TN_COUNT) { + if (texId == OriginalImages[i]) { + return true; + } + i++; + } + } + i = 0; + while (OriginalImagesPaths[i]) { + if (name.compare(OriginalImagesPaths[i]) == 0) { + return true; + } + i++; + } + return false; } - diff --git a/Minecraft.Client/Textures/Textures.h b/Minecraft.Client/Textures/Textures.h index a96947384..f44075c58 100644 --- a/Minecraft.Client/Textures/Textures.h +++ b/Minecraft.Client/Textures/Textures.h @@ -13,275 +13,291 @@ class Options; class IntBuffer; class PreStitchedTextureMap; +typedef enum _TEXTURE_NAME { + TN__BLUR__MISC_PUMPKINBLUR, + // TN__BLUR__MISC_VIGNETTE, // Not currently used + TN__CLAMP__MISC_SHADOW, + // TN_ACHIEVEMENT_BG, // Not currently used + TN_ART_KZ, + TN_ENVIRONMENT_CLOUDS, + TN_ENVIRONMENT_RAIN, + TN_ENVIRONMENT_SNOW, + TN_GUI_GUI, + TN_GUI_ICONS, + TN_ITEM_ARROWS, + TN_ITEM_BOAT, + TN_ITEM_CART, + TN_ITEM_SIGN, + TN_MISC_MAPBG, + TN_MISC_MAPICONS, + TN_MISC_WATER, + TN_MISC_FOOTSTEP, + TN_MOB_SADDLE, + TN_MOB_SHEEP_FUR, + TN_MOB_SPIDER_EYES, + TN_PARTICLES, + TN_MOB_CHICKEN, + TN_MOB_COW, + TN_MOB_PIG, + TN_MOB_SHEEP, + TN_MOB_SQUID, + TN_MOB_WOLF, + TN_MOB_WOLF_TAME, + TN_MOB_WOLF_ANGRY, + TN_MOB_CREEPER, + TN_MOB_GHAST, + TN_MOB_GHAST_FIRE, + TN_MOB_ZOMBIE, + TN_MOB_PIGZOMBIE, + TN_MOB_SKELETON, + TN_MOB_SLIME, + TN_MOB_SPIDER, + TN_MOB_CHAR, + TN_MOB_CHAR1, + TN_MOB_CHAR2, + TN_MOB_CHAR3, + TN_MOB_CHAR4, + TN_MOB_CHAR5, + TN_MOB_CHAR6, + TN_MOB_CHAR7, + TN_TERRAIN_MOON, + TN_TERRAIN_SUN, + TN_POWERED_CREEPER, -typedef enum _TEXTURE_NAME -{ - TN__BLUR__MISC_PUMPKINBLUR, -// TN__BLUR__MISC_VIGNETTE, // Not currently used - TN__CLAMP__MISC_SHADOW, -// TN_ACHIEVEMENT_BG, // Not currently used - TN_ART_KZ, - TN_ENVIRONMENT_CLOUDS, - TN_ENVIRONMENT_RAIN, - TN_ENVIRONMENT_SNOW, - TN_GUI_GUI, - TN_GUI_ICONS, - TN_ITEM_ARROWS, - TN_ITEM_BOAT, - TN_ITEM_CART, - TN_ITEM_SIGN, - TN_MISC_MAPBG, - TN_MISC_MAPICONS, - TN_MISC_WATER, - TN_MISC_FOOTSTEP, - TN_MOB_SADDLE, - TN_MOB_SHEEP_FUR, - TN_MOB_SPIDER_EYES, - TN_PARTICLES, - TN_MOB_CHICKEN, - TN_MOB_COW, - TN_MOB_PIG, - TN_MOB_SHEEP, - TN_MOB_SQUID, - TN_MOB_WOLF, - TN_MOB_WOLF_TAME, - TN_MOB_WOLF_ANGRY, - TN_MOB_CREEPER, - TN_MOB_GHAST, - TN_MOB_GHAST_FIRE, - TN_MOB_ZOMBIE, - TN_MOB_PIGZOMBIE, - TN_MOB_SKELETON, - TN_MOB_SLIME, - TN_MOB_SPIDER, - TN_MOB_CHAR, - TN_MOB_CHAR1, - TN_MOB_CHAR2, - TN_MOB_CHAR3, - TN_MOB_CHAR4, - TN_MOB_CHAR5, - TN_MOB_CHAR6, - TN_MOB_CHAR7, - TN_TERRAIN_MOON, - TN_TERRAIN_SUN, - TN_POWERED_CREEPER, + // 1.8.2 + TN_MOB_CAVE_SPIDER, + TN_MOB_ENDERMAN, + TN_MOB_SILVERFISH, + TN_MOB_ENDERMAN_EYES, + TN_MISC_EXPLOSION, + TN_ITEM_EXPERIENCE_ORB, + TN_TILE_CHEST, + TN_TILE_LARGE_CHEST, - // 1.8.2 - TN_MOB_CAVE_SPIDER, - TN_MOB_ENDERMAN, - TN_MOB_SILVERFISH, - TN_MOB_ENDERMAN_EYES, - TN_MISC_EXPLOSION, - TN_ITEM_EXPERIENCE_ORB, - TN_TILE_CHEST, - TN_TILE_LARGE_CHEST, + // 1.3.2 + TN_TILE_ENDER_CHEST, - // 1.3.2 - TN_TILE_ENDER_CHEST, + // 1.0.1 + TN_MOB_RED_COW, + TN_MOB_SNOWMAN, + TN_MOB_ENDERDRAGON, + TN_MOB_BLAZE, + TN_MOB_LAVA, + TN_MOB_VILLAGER_VILLAGER, + TN_MOB_VILLAGER_FARMER, + TN_MOB_VILLAGER_LIBRARIAN, + TN_MOB_VILLAGER_PRIEST, + TN_MOB_VILLAGER_SMITH, + TN_MOB_VILLAGER_BUTCHER, + TN_MOB_ENDERDRAGON_ENDERCRYSTAL, + TN_MOB_ENDERDRAGON_SHUFFLE, + TN_MOB_ENDERDRAGON_BEAM, + TN_MOB_ENDERDRAGON_ENDEREYES, + TN__BLUR__MISC_GLINT, + TN_ITEM_BOOK, + TN_MISC_TUNNEL, + TN_MISC_PARTICLEFIELD, + TN_TERRAIN_MOON_PHASES, - // 1.0.1 - TN_MOB_RED_COW, - TN_MOB_SNOWMAN, - TN_MOB_ENDERDRAGON, - TN_MOB_BLAZE, - TN_MOB_LAVA, - TN_MOB_VILLAGER_VILLAGER, - TN_MOB_VILLAGER_FARMER, - TN_MOB_VILLAGER_LIBRARIAN, - TN_MOB_VILLAGER_PRIEST, - TN_MOB_VILLAGER_SMITH, - TN_MOB_VILLAGER_BUTCHER, - TN_MOB_ENDERDRAGON_ENDERCRYSTAL, - TN_MOB_ENDERDRAGON_SHUFFLE, - TN_MOB_ENDERDRAGON_BEAM, - TN_MOB_ENDERDRAGON_ENDEREYES, - TN__BLUR__MISC_GLINT, - TN_ITEM_BOOK, - TN_MISC_TUNNEL, - TN_MISC_PARTICLEFIELD, - TN_TERRAIN_MOON_PHASES, + // 1.2.3 + TN_MOB_OZELOT, + TN_MOB_CAT_BLACK, + TN_MOB_CAT_RED, + TN_MOB_CAT_SIAMESE, + TN_MOB_VILLAGER_GOLEM, + TN_MOB_WITHER_SKELETON, - // 1.2.3 - TN_MOB_OZELOT, - TN_MOB_CAT_BLACK, - TN_MOB_CAT_RED, - TN_MOB_CAT_SIAMESE, - TN_MOB_VILLAGER_GOLEM, - TN_MOB_WITHER_SKELETON, - - // TU14 - TN_MOB_WOLF_COLLAR, - TN_MOB_ZOMBIE_VILLAGER, + // TU14 + TN_MOB_WOLF_COLLAR, + TN_MOB_ZOMBIE_VILLAGER, #ifdef _LARGE_WORLDS - TN_MISC_ADDITIONALMAPICONS, + TN_MISC_ADDITIONALMAPICONS, #endif - TN_DEFAULT_FONT, - TN_ALT_FONT, + TN_DEFAULT_FONT, + TN_ALT_FONT, -/* TN_SP1, - TN_SP2, - TN_SP3, - TN_SPF, - TN_THST, - TN_THIR, - TN_THGO, - TN_THDI, - TN_GPAN, - TN_GPCO, - TN_GPEN, - TN_GPFO, - TN_GPTO, - TN_GPBA, - TN_GPFA, - TN_GPME, - TN_GPMF, - TN_GPMM, - TN_GPSE, - TN_AH_0006, - TN_AH_0003, - TN_AH_0007, - TN_AH_0005, - TN_AH_0004, - TN_AH_0001, - TN_AH_0002, - TN_AT_0001, - TN_AT_0002, - TN_AT_0003, - TN_AT_0004, - TN_AT_0005, - TN_AT_0006, - TN_AT_0007, - TN_AT_0008, - TN_AT_0009, - TN_AT_0010, - TN_AT_0011, - TN_AT_0012, - TN_AP_0001, - TN_AP_0002, - TN_AP_0003, - TN_AP_0004, - TN_AP_0005, - TN_AP_0006, - TN_AP_0007, - TN_AP_0009, - TN_AP_0010, - TN_AP_0011, - TN_AP_0012, - TN_AP_0013, - TN_AP_0014, - TN_AP_0015, - TN_AP_0016, - TN_AP_0017, - TN_AP_0018, - TN_AA_0001, - TN_AT_0013, - TN_AT_0014, - TN_AT_0015, - TN_AT_0016, - TN_AT_0017, - TN_AT_0018, - TN_AP_0019, - TN_AP_0020, - TN_AP_0021, - TN_AP_0022, - TN_AP_0023, - TN_AH_0008, - TN_AH_0009,*/ + /* TN_SP1, + TN_SP2, + TN_SP3, + TN_SPF, + TN_THST, + TN_THIR, + TN_THGO, + TN_THDI, + TN_GPAN, + TN_GPCO, + TN_GPEN, + TN_GPFO, + TN_GPTO, + TN_GPBA, + TN_GPFA, + TN_GPME, + TN_GPMF, + TN_GPMM, + TN_GPSE, + TN_AH_0006, + TN_AH_0003, + TN_AH_0007, + TN_AH_0005, + TN_AH_0004, + TN_AH_0001, + TN_AH_0002, + TN_AT_0001, + TN_AT_0002, + TN_AT_0003, + TN_AT_0004, + TN_AT_0005, + TN_AT_0006, + TN_AT_0007, + TN_AT_0008, + TN_AT_0009, + TN_AT_0010, + TN_AT_0011, + TN_AT_0012, + TN_AP_0001, + TN_AP_0002, + TN_AP_0003, + TN_AP_0004, + TN_AP_0005, + TN_AP_0006, + TN_AP_0007, + TN_AP_0009, + TN_AP_0010, + TN_AP_0011, + TN_AP_0012, + TN_AP_0013, + TN_AP_0014, + TN_AP_0015, + TN_AP_0016, + TN_AP_0017, + TN_AP_0018, + TN_AA_0001, + TN_AT_0013, + TN_AT_0014, + TN_AT_0015, + TN_AT_0016, + TN_AT_0017, + TN_AT_0018, + TN_AP_0019, + TN_AP_0020, + TN_AP_0021, + TN_AP_0022, + TN_AP_0023, + TN_AH_0008, + TN_AH_0009,*/ - TN_GUI_ITEMS, - TN_TERRAIN, + TN_GUI_ITEMS, + TN_TERRAIN, - TN_COUNT, - -} -TEXTURE_NAME; + TN_COUNT, -class Textures -{ +} TEXTURE_NAME; + +class Textures { public: - static bool MIPMAP; - static C4JRender::eTextureFormat TEXTURE_FORMAT; + static bool MIPMAP; + static C4JRender::eTextureFormat TEXTURE_FORMAT; private: - static const wchar_t *preLoaded[TN_COUNT]; - static int preLoadedIdx[TN_COUNT]; + static const wchar_t* preLoaded[TN_COUNT]; + static int preLoadedIdx[TN_COUNT]; - std::unordered_map idMap; + std::unordered_map idMap; std::unordered_map pixelsMap; - std::unordered_map loadedImages; - //IntBuffer *pixels; // 4J - removed so we don't have a permanent buffer kicking round using up 1MB + std::unordered_map loadedImages; + // IntBuffer *pixels; // 4J - removed so we don't have a permanent + // buffer kicking round using up 1MB - std::unordered_map httpTextures; - // 4J-PB - Added for GTS textures - std::unordered_map memTextures; - Options *options; + std::unordered_map httpTextures; + // 4J-PB - Added for GTS textures + std::unordered_map memTextures; + Options* options; private: - TexturePackRepository *skins; - BufferedImage *missingNo; - PreStitchedTextureMap *terrain; - PreStitchedTextureMap *items; + TexturePackRepository* skins; + BufferedImage* missingNo; + PreStitchedTextureMap* terrain; + PreStitchedTextureMap* items; + + int lastBoundId; - int lastBoundId; public: - Textures(TexturePackRepository *skins, Options *options); + Textures(TexturePackRepository* skins, Options* options); private: - void loadIndexedTextures(); // 4J Added + void loadIndexedTextures(); // 4J Added public: - intArray loadTexturePixels(TEXTURE_NAME texId, const std::wstring& resourceName); -private: - intArray loadTexturePixels(BufferedImage *img); - intArray loadTexturePixels(BufferedImage *img, intArray pixels); - void setTextureFormat(const std::wstring& resourceName); // 4J added - -public: - void bindTexture(const std::wstring &resourceName); - void bindTexture(int resourceId); // 4J Added - - // 4J Made public for use in XUI controls - void bind(int id); - -public: - void clearLastBoundId(); + intArray loadTexturePixels(TEXTURE_NAME texId, + const std::wstring& resourceName); private: - int loadTexture(TEXTURE_NAME texId, const std::wstring& resourceName); + intArray loadTexturePixels(BufferedImage* img); + intArray loadTexturePixels(BufferedImage* img, intArray pixels); + void setTextureFormat(const std::wstring& resourceName); // 4J added + public: - int loadTexture(int idx); // 4J added - int getTexture(BufferedImage *img, C4JRender::eTextureFormat format = C4JRender::TEXTURE_FORMAT_RxGyBzAw, bool mipmap = true); - void loadTexture(BufferedImage *img, int id); - void loadTexture(BufferedImage *img, int id, bool blur, bool clamp); + void bindTexture(const std::wstring& resourceName); + void bindTexture(int resourceId); // 4J Added + + // 4J Made public for use in XUI controls + void bind(int id); + +public: + void clearLastBoundId(); + private: - intArray anaglyph(intArray rawPixels); + int loadTexture(TEXTURE_NAME texId, const std::wstring& resourceName); + +public: + int loadTexture(int idx); // 4J added + int getTexture( + BufferedImage* img, + C4JRender::eTextureFormat format = C4JRender::TEXTURE_FORMAT_RxGyBzAw, + bool mipmap = true); + void loadTexture(BufferedImage* img, int id); + void loadTexture(BufferedImage* img, int id, bool blur, bool clamp); + +private: + intArray anaglyph(intArray rawPixels); + public: void replaceTexture(intArray rawPixels, int w, int h, int id); - void replaceTextureDirect(intArray rawPixels, int w, int h, int id); // 4J added as optimisation - void replaceTextureDirect(shortArray rawPixels, int w, int h, int id); // 4J added as optimisation - void releaseTexture(int id); + void replaceTextureDirect(intArray rawPixels, int w, int h, + int id); // 4J added as optimisation + void replaceTextureDirect(shortArray rawPixels, int w, int h, + int id); // 4J added as optimisation + void releaseTexture(int id); int loadHttpTexture(const std::wstring& url, const std::wstring& backup); - int loadHttpTexture(const std::wstring& url, int backup); // 4J added - bool hasHttpTexture(const std::wstring &url); - HttpTexture *addHttpTexture(const std::wstring& url, HttpTextureProcessor *processor); + int loadHttpTexture(const std::wstring& url, int backup); // 4J added + bool hasHttpTexture(const std::wstring& url); + HttpTexture* addHttpTexture(const std::wstring& url, + HttpTextureProcessor* processor); void removeHttpTexture(const std::wstring& url); - // 4J-PB - for the GTS textures - int loadMemTexture(const std::wstring& url, const std::wstring& backup); - int loadMemTexture(const std::wstring& url, int backup); - MemTexture * addMemTexture(const std::wstring& url, MemTextureProcessor *processor); - //MemTexture * getMemTexture(const std::wstring& url, MemTextureProcessor *processor); - void removeMemTexture(const std::wstring& url); + // 4J-PB - for the GTS textures + int loadMemTexture(const std::wstring& url, const std::wstring& backup); + int loadMemTexture(const std::wstring& url, int backup); + MemTexture* addMemTexture(const std::wstring& url, + MemTextureProcessor* processor); + // MemTexture * getMemTexture(const std::wstring& url, + // MemTextureProcessor *processor); + void removeMemTexture(const std::wstring& url); - void tick(bool updateTextures, bool tickDynamics = true); // 4J added updateTextures parameter & tickDynamics + void tick(bool updateTextures, + bool tickDynamics = + true); // 4J added updateTextures parameter & tickDynamics public: - void reloadAll(); - void stitch(); - Icon *getMissingIcon(int type); - BufferedImage *readImage(TEXTURE_NAME texId, const std::wstring& name); // Moved this to public for Font.cpp access - // check list of title update textures to see if we need to use the UPDATE: drive - static bool IsTUImage(TEXTURE_NAME texId, const std::wstring& name); - static bool IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name); + void reloadAll(); + void stitch(); + Icon* getMissingIcon(int type); + BufferedImage* readImage( + TEXTURE_NAME texId, + const std::wstring& name); // Moved this to public for Font.cpp access + // check list of title update textures to see if we need to use the UPDATE: + // drive + static bool IsTUImage(TEXTURE_NAME texId, const std::wstring& name); + static bool IsOriginalImage(TEXTURE_NAME texId, const std::wstring& name); }; diff --git a/Minecraft.Client/UI/Button.cpp b/Minecraft.Client/UI/Button.cpp index d3cfe3e3b..09630ed6b 100644 --- a/Minecraft.Client/UI/Button.cpp +++ b/Minecraft.Client/UI/Button.cpp @@ -2,23 +2,20 @@ #include "Button.h" #include "../Textures/Textures.h" -Button::Button(int id, int x, int y, const std::wstring& msg) -{ - init(id, x, y, 200, 20, msg); +Button::Button(int id, int x, int y, const std::wstring& msg) { + init(id, x, y, 200, 20, msg); } -Button::Button(int id, int x, int y, int w, int h, const std::wstring& msg) -{ - init(id, x, y, w, h, msg); +Button::Button(int id, int x, int y, int w, int h, const std::wstring& msg) { + init(id, x, y, w, h, msg); } // 4J - added -void Button::init(int id, int x, int y, int w, int h, const std::wstring& msg) -{ - active = true; - visible = true; +void Button::init(int id, int x, int y, int w, int h, const std::wstring& msg) { + active = true; + visible = true; - // this bit of code from original ctor + // this bit of code from original ctor this->id = id; this->x = x; this->y = y; @@ -27,24 +24,24 @@ void Button::init(int id, int x, int y, int w, int h, const std::wstring& msg) this->msg = msg; } -int Button::getYImage(bool hovered) -{ +int Button::getYImage(bool hovered) { int res = 1; - if (!active) res = 0; - else if (hovered) res = 2; + if (!active) + res = 0; + else if (hovered) + res = 2; return res; } -void Button::render(Minecraft *minecraft, int xm, int ym) -{ +void Button::render(Minecraft* minecraft, int xm, int ym) { if (!visible) return; - Font *font = minecraft->font; + Font* font = minecraft->font; - glBindTexture(GL_TEXTURE_2D, minecraft->textures->loadTexture(TN_GUI_GUI)); // 4J was L"/gui/gui.png" + glBindTexture(GL_TEXTURE_2D, minecraft->textures->loadTexture( + TN_GUI_GUI)); // 4J was L"/gui/gui.png" glColor4f(1, 1, 1, 1); - bool hovered = xm >= x && ym >= y && xm < x + w && ym < y + h; int yImage = getYImage(hovered); @@ -53,33 +50,21 @@ void Button::render(Minecraft *minecraft, int xm, int ym) renderBg(minecraft, xm, ym); - if (!active) - { + if (!active) { drawCenteredString(font, msg, x + w / 2, y + (h - 8) / 2, 0xffa0a0a0); - } - else - { - if (hovered) - { + } else { + if (hovered) { drawCenteredString(font, msg, x + w / 2, y + (h - 8) / 2, 0xffffa0); - } - else - { + } else { drawCenteredString(font, msg, x + w / 2, y + (h - 8) / 2, 0xe0e0e0); } } - } -void Button::renderBg(Minecraft *minecraft, int xm, int ym) -{ -} +void Button::renderBg(Minecraft* minecraft, int xm, int ym) {} -void Button::released(int mx, int my) -{ -} +void Button::released(int mx, int my) {} -bool Button::clicked(Minecraft *minecraft, int mx, int my) -{ - return active && mx >= x && my >= y && mx < x + w && my < y + h; +bool Button::clicked(Minecraft* minecraft, int mx, int my) { + return active && mx >= x && my >= y && mx < x + w && my < y + h; } \ No newline at end of file diff --git a/Minecraft.Client/UI/Button.h b/Minecraft.Client/UI/Button.h index aac43cda4..529ab0902 100644 --- a/Minecraft.Client/UI/Button.h +++ b/Minecraft.Client/UI/Button.h @@ -1,14 +1,13 @@ #pragma once #include "GuiComponent.h" - -class Button : public GuiComponent -{ +class Button : public GuiComponent { protected: - int w; + int w; int h; + public: - int x, y; + int x, y; std::wstring msg; int id; bool active; @@ -16,15 +15,18 @@ public: Button(int id, int x, int y, const std::wstring& msg); Button(int id, int x, int y, int w, int h, const std::wstring& msg); - void init(int id, int x, int y, int w, int h, const std::wstring& msg); // 4J - added + void init(int id, int x, int y, int w, int h, + const std::wstring& msg); // 4J - added protected: - virtual int getYImage(bool hovered); + virtual int getYImage(bool hovered); + public: - virtual void render(Minecraft *minecraft, int xm, int ym); + virtual void render(Minecraft* minecraft, int xm, int ym); protected: - virtual void renderBg(Minecraft *minecraft, int xm, int ym); + virtual void renderBg(Minecraft* minecraft, int xm, int ym); + public: - virtual void released(int mx, int my); - virtual bool clicked(Minecraft *minecraft, int mx, int my); + virtual void released(int mx, int my); + virtual bool clicked(Minecraft* minecraft, int mx, int my); }; diff --git a/Minecraft.Client/UI/EditBox.cpp b/Minecraft.Client/UI/EditBox.cpp index 0a0e9550e..2ce3d3224 100644 --- a/Minecraft.Client/UI/EditBox.cpp +++ b/Minecraft.Client/UI/EditBox.cpp @@ -2,109 +2,84 @@ #include "EditBox.h" #include "../../Minecraft.World/Util/SharedConstants.h" -EditBox::EditBox(Screen *screen, Font *font, int x, int y, int width, int height, const std::wstring& value) -{ - // 4J - added initialisers - maxLength = 0; - frame = 0; +EditBox::EditBox(Screen* screen, Font* font, int x, int y, int width, + int height, const std::wstring& value) { + // 4J - added initialisers + maxLength = 0; + frame = 0; - this->screen = screen; - this->font = font; - this->x = x; - this->y = y; - this->width = width; - this->height = height; - this->setValue(value); + this->screen = screen; + this->font = font; + this->x = x; + this->y = y; + this->width = width; + this->height = height; + this->setValue(value); } -void EditBox::setValue(const std::wstring& value) -{ - this->value = value; -} +void EditBox::setValue(const std::wstring& value) { this->value = value; } -std::wstring EditBox::getValue() -{ - return value; -} +std::wstring EditBox::getValue() { return value; } -void EditBox::tick() -{ - frame++; -} +void EditBox::tick() { frame++; } -void EditBox::keyPressed(wchar_t ch, int eventKey) -{ +void EditBox::keyPressed(wchar_t ch, int eventKey) { if (!active || !inFocus) { return; } - - if (ch == 9) - { + if (ch == 9) { screen->tabPressed(); } -/* 4J removed - if (ch == 22) - { - String msg = Screen.getClipboard(); - if (msg == null) msg = ""; - int toAdd = 32 - value.length(); - if (toAdd > msg.length()) toAdd = msg.length(); - if (toAdd > 0) { - value += msg.substring(0, toAdd); + /* 4J removed + if (ch == 22) + { + String msg = Screen.getClipboard(); + if (msg == null) msg = ""; + int toAdd = 32 - value.length(); + if (toAdd > msg.length()) toAdd = msg.length(); + if (toAdd > 0) { + value += msg.substring(0, toAdd); + } } - } - */ + */ - if (eventKey == Keyboard::KEY_BACK && value.length() > 0) - { + if (eventKey == Keyboard::KEY_BACK && value.length() > 0) { value = value.substr(0, value.length() - 1); } - if (SharedConstants::acceptableLetters.find(ch) != std::wstring::npos && (value.length() < maxLength || maxLength == 0)) - { + if (SharedConstants::acceptableLetters.find(ch) != std::wstring::npos && + (value.length() < maxLength || maxLength == 0)) { value += ch; } - } -void EditBox::mouseClicked(int mouseX, int mouseY, int buttonNum) -{ - bool newFocus = active && (mouseX >= x && mouseX < (x + width) && mouseY >= y && mouseY < (y + height)); +void EditBox::mouseClicked(int mouseX, int mouseY, int buttonNum) { + bool newFocus = active && (mouseX >= x && mouseX < (x + width) && + mouseY >= y && mouseY < (y + height)); focus(newFocus); } -void EditBox::focus(bool newFocus) -{ - if (newFocus && !inFocus) - { +void EditBox::focus(bool newFocus) { + if (newFocus && !inFocus) { // reset the underscore counter to give quicker selection feedback frame = 0; } inFocus = newFocus; } -void EditBox::render() -{ +void EditBox::render() { fill(x - 1, y - 1, x + width + 1, y + height + 1, 0xffa0a0a0); fill(x, y, x + width, y + height, 0xff000000); - if (active) - { + if (active) { bool renderUnderscore = inFocus && (frame / 6 % 2 == 0); - drawString(font, value + (renderUnderscore ? L"_" : L""), x + 4, y + (height - 8) / 2, 0xe0e0e0); - } - else - { + drawString(font, value + (renderUnderscore ? L"_" : L""), x + 4, + y + (height - 8) / 2, 0xe0e0e0); + } else { drawString(font, value, x + 4, y + (height - 8) / 2, 0x707070); } } -void EditBox::setMaxLength(int maxLength) -{ - this->maxLength = maxLength; -} +void EditBox::setMaxLength(int maxLength) { this->maxLength = maxLength; } -int EditBox::getMaxLength() -{ - return maxLength; -} \ No newline at end of file +int EditBox::getMaxLength() { return maxLength; } \ No newline at end of file diff --git a/Minecraft.Client/UI/EditBox.h b/Minecraft.Client/UI/EditBox.h index d0f2e8614..1b78d424f 100644 --- a/Minecraft.Client/UI/EditBox.h +++ b/Minecraft.Client/UI/EditBox.h @@ -4,10 +4,9 @@ class Font; class Screen; -class EditBox : public GuiComponent -{ +class EditBox : public GuiComponent { private: - Font *font; + Font* font; int x; int y; int width; @@ -17,13 +16,15 @@ private: int frame; public: - bool inFocus; + bool inFocus; bool active; + private: - Screen *screen; + Screen* screen; public: - EditBox(Screen *screen, Font *font, int x, int y, int width, int height, const std::wstring& value); + EditBox(Screen* screen, Font* font, int x, int y, int width, int height, + const std::wstring& value); void setValue(const std::wstring& value); std::wstring getValue(); void tick(); diff --git a/Minecraft.Client/UI/Font.cpp b/Minecraft.Client/UI/Font.cpp index 096e548a3..4ea8f151b 100644 --- a/Minecraft.Client/UI/Font.cpp +++ b/Minecraft.Client/UI/Font.cpp @@ -8,71 +8,69 @@ #include "../../Minecraft.World/Util/StringHelpers.h" #include "../../Minecraft.World/Util/Random.h" -Font::Font(Options *options, const std::wstring& name, Textures* textures, bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, int charWidth, int charHeight, unsigned short charMap[]/* = nullptr */) : textures(textures) -{ - int charC = cols * rows; // Number of characters in the font +Font::Font(Options* options, const std::wstring& name, Textures* textures, + bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, + int charWidth, int charHeight, + unsigned short charMap[] /* = nullptr */) + : textures(textures) { + int charC = cols * rows; // Number of characters in the font - charWidths = new int[charC]; + charWidths = new int[charC]; - // 4J - added initialisers - memset(charWidths, 0, charC); + // 4J - added initialisers + memset(charWidths, 0, charC); - enforceUnicodeSheet = false; - bidirectional = false; - xPos = yPos = 0.0f; + enforceUnicodeSheet = false; + bidirectional = false; + xPos = yPos = 0.0f; - // Set up member variables - m_cols = cols; - m_rows = rows; - m_charWidth = charWidth; - m_charHeight = charHeight; - m_textureName = textureName; + // Set up member variables + m_cols = cols; + m_rows = rows; + m_charWidth = charWidth; + m_charHeight = charHeight; + m_textureName = textureName; - // Build character map - if (charMap != NULL) - { - for(int i = 0; i < charC; i++) - { - m_charMap.insert(std::make_pair(charMap[i], i)); - } - } - - random = new Random(); - - // Load the image - BufferedImage *img = textures->readImage(m_textureName, name); - - /* - 4J - TODO - try { - img = ImageIO.read(Textures.class.getResourceAsStream(name)); - } catch (IOException e) { - throw new RuntimeException(e); + // Build character map + if (charMap != NULL) { + for (int i = 0; i < charC; i++) { + m_charMap.insert(std::make_pair(charMap[i], i)); + } } - */ + + random = new Random(); + + // Load the image + BufferedImage* img = textures->readImage(m_textureName, name); + + /* - 4J - TODO + try { + img = ImageIO.read(Textures.class.getResourceAsStream(name)); +} catch (IOException e) { + throw new RuntimeException(e); +} + */ int w = img->getWidth(); int h = img->getHeight(); intArray rawPixels(w * h); img->getRGB(0, 0, w, h, rawPixels, 0, w); - for (int i = 0; i < charC; i++) - { + for (int i = 0; i < charC; i++) { int xt = i % m_cols; int yt = i / m_cols; - + int x = 7; - for (; x >= 0; x--) - { + for (; x >= 0; x--) { int xPixel = xt * 8 + x; bool emptyColumn = true; - for (int y = 0; y < 8 && emptyColumn; y++) - { + for (int y = 0; y < 8 && emptyColumn; y++) { int yPixel = (yt * 8 + y) * w; - bool emptyPixel = (rawPixels[xPixel + yPixel] >> 24) == 0; // Check the alpha value - if (!emptyPixel) emptyColumn = false; + bool emptyPixel = (rawPixels[xPixel + yPixel] >> 24) == + 0; // Check the alpha value + if (!emptyPixel) emptyColumn = false; } - if (!emptyColumn) - { + if (!emptyColumn) { break; } } @@ -81,369 +79,326 @@ Font::Font(Options *options, const std::wstring& name, Textures* textures, bool charWidths[i] = x + 2; } - delete img; + delete img; - // calculate colors - for (int colorN = 0; colorN < 32; ++colorN) - { - int var10 = (colorN >> 3 & 1) * 85; - int red = (colorN >> 2 & 1) * 170 + var10; - int green = (colorN >> 1 & 1) * 170 + var10; - int blue = (colorN >> 0 & 1) * 170 + var10; + // calculate colors + for (int colorN = 0; colorN < 32; ++colorN) { + int var10 = (colorN >> 3 & 1) * 85; + int red = (colorN >> 2 & 1) * 170 + var10; + int green = (colorN >> 1 & 1) * 170 + var10; + int blue = (colorN >> 0 & 1) * 170 + var10; - if (colorN == 6) - { - red += 85; - } + if (colorN == 6) { + red += 85; + } - if (options->anaglyph3d) - { - int tmpRed = (red * 30 + green * 59 + blue * 11) / 100; - int tmpGreen = (red * 30 + green * 70) / 100; - int tmpBlue = (red * 30 + blue * 70) / 100; - red = tmpRed; - green = tmpGreen; - blue = tmpBlue; - } + if (options->anaglyph3d) { + int tmpRed = (red * 30 + green * 59 + blue * 11) / 100; + int tmpGreen = (red * 30 + green * 70) / 100; + int tmpBlue = (red * 30 + blue * 70) / 100; + red = tmpRed; + green = tmpGreen; + blue = tmpBlue; + } - if (colorN >= 16) - { - red /= 4; - green /= 4; - blue /= 4; - } + if (colorN >= 16) { + red /= 4; + green /= 4; + blue /= 4; + } - colors[colorN] = (red & 255) << 16 | (green & 255) << 8 | (blue & 255); - } + colors[colorN] = (red & 255) << 16 | (green & 255) << 8 | (blue & 255); + } } #ifndef _XBOX -// 4J Stu - This dtor clashes with one in xui! We never delete these anyway so take it out for now. Can go back when we have got rid of XUI -Font::~Font() -{ - delete[] charWidths; -} +// 4J Stu - This dtor clashes with one in xui! We never delete these anyway so +// take it out for now. Can go back when we have got rid of XUI +Font::~Font() { delete[] charWidths; } #endif -void Font::renderCharacter(wchar_t c) -{ - float xOff = c % m_cols * m_charWidth; - float yOff = c / m_cols * m_charWidth; +void Font::renderCharacter(wchar_t c) { + float xOff = c % m_cols * m_charWidth; + float yOff = c / m_cols * m_charWidth; - float width = charWidths[c] - .01f; - float height = m_charHeight - .01f; - - float fontWidth = m_cols * m_charWidth; - float fontHeight = m_rows * m_charHeight; + float width = charWidths[c] - .01f; + float height = m_charHeight - .01f; - Tesselator *t = Tesselator::getInstance(); - // 4J Stu - Changed to a quad so that we can use within a command buffer + float fontWidth = m_cols * m_charWidth; + float fontHeight = m_rows * m_charHeight; + + Tesselator* t = Tesselator::getInstance(); + // 4J Stu - Changed to a quad so that we can use within a command buffer #if 1 - t->begin(); - t->tex(xOff / fontWidth, (yOff + 7.99f) / fontHeight); - t->vertex(xPos, yPos + height, 0.0f); + t->begin(); + t->tex(xOff / fontWidth, (yOff + 7.99f) / fontHeight); + t->vertex(xPos, yPos + height, 0.0f); - t->tex((xOff + width) / fontWidth, (yOff + 7.99f) / fontHeight); - t->vertex(xPos + width, yPos + height, 0.0f); + t->tex((xOff + width) / fontWidth, (yOff + 7.99f) / fontHeight); + t->vertex(xPos + width, yPos + height, 0.0f); - t->tex((xOff + width) / fontWidth, yOff / fontHeight); - t->vertex(xPos + width, yPos, 0.0f); + t->tex((xOff + width) / fontWidth, yOff / fontHeight); + t->vertex(xPos + width, yPos, 0.0f); - t->tex(xOff / fontWidth, yOff / fontHeight); - t->vertex(xPos, yPos, 0.0f); + t->tex(xOff / fontWidth, yOff / fontHeight); + t->vertex(xPos, yPos, 0.0f); - t->end(); + t->end(); #else - t->begin(GL_TRIANGLE_STRIP); - t->tex(xOff / 128.0F, yOff / 128.0F); - t->vertex(xPos, yPos, 0.0f); - t->tex(xOff / 128.0F, (yOff + 7.99f) / 128.0F); - t->vertex(xPos, yPos + 7.99f, 0.0f); - t->tex((xOff + width) / 128.0F, yOff / 128.0F); - t->vertex(xPos + width, yPos, 0.0f); - t->tex((xOff + width) / 128.0F, (yOff + 7.99f) / 128.0F); - t->vertex(xPos + width, yPos + 7.99f, 0.0f); - t->end(); + t->begin(GL_TRIANGLE_STRIP); + t->tex(xOff / 128.0F, yOff / 128.0F); + t->vertex(xPos, yPos, 0.0f); + t->tex(xOff / 128.0F, (yOff + 7.99f) / 128.0F); + t->vertex(xPos, yPos + 7.99f, 0.0f); + t->tex((xOff + width) / 128.0F, yOff / 128.0F); + t->vertex(xPos + width, yPos, 0.0f); + t->tex((xOff + width) / 128.0F, (yOff + 7.99f) / 128.0F); + t->vertex(xPos + width, yPos + 7.99f, 0.0f); + t->end(); #endif - xPos += (float) charWidths[c]; + xPos += (float)charWidths[c]; } -void Font::drawShadow(const std::wstring& str, int x, int y, int color) -{ +void Font::drawShadow(const std::wstring& str, int x, int y, int color) { draw(str, x + 1, y + 1, color, true); draw(str, x, y, color, false); } -void Font::drawShadowWordWrap(const std::wstring &str, int x, int y, int w, int color, int h) -{ - drawWordWrapInternal(str, x + 1, y + 1, w, color, true, h); - drawWordWrapInternal(str, x, y, w, color, h); +void Font::drawShadowWordWrap(const std::wstring& str, int x, int y, int w, + int color, int h) { + drawWordWrapInternal(str, x + 1, y + 1, w, color, true, h); + drawWordWrapInternal(str, x, y, w, color, h); } -void Font::draw(const std::wstring& str, int x, int y, int color) -{ - draw(str, x, y, color, false); +void Font::draw(const std::wstring& str, int x, int y, int color) { + draw(str, x, y, color, false); } -std::wstring Font::reorderBidi(const std::wstring &str) -{ - // 4J Not implemented - return str; +std::wstring Font::reorderBidi(const std::wstring& str) { + // 4J Not implemented + return str; } -void Font::draw(const std::wstring &str, bool dropShadow) -{ - // Bind the texture - textures->bindTexture(m_textureName); +void Font::draw(const std::wstring& str, bool dropShadow) { + // Bind the texture + textures->bindTexture(m_textureName); - bool noise = false; - std::wstring cleanStr = sanitize(str); + bool noise = false; + std::wstring cleanStr = sanitize(str); - for (int i = 0; i < (int)cleanStr.length(); ++i) - { - // Map character - wchar_t c = cleanStr.at(i); + for (int i = 0; i < (int)cleanStr.length(); ++i) { + // Map character + wchar_t c = cleanStr.at(i); - if (c == 167 && i + 1 < cleanStr.length()) - { - // 4J - following block was: - // int colorN = L"0123456789abcdefk".indexOf(str.toLowerCase().charAt(i + 1)); - wchar_t ca = cleanStr[i+1]; - int colorN = 16; - if(( ca >= L'0' ) && (ca <= L'9')) colorN = ca - L'0'; - else if(( ca >= L'a' ) && (ca <= L'f')) colorN = (ca - L'a') + 10; - else if(( ca >= L'A' ) && (ca <= L'F')) colorN = (ca - L'A') + 10; + if (c == 167 && i + 1 < cleanStr.length()) { + // 4J - following block was: + // int colorN = + // L"0123456789abcdefk".indexOf(str.toLowerCase().charAt(i + 1)); + wchar_t ca = cleanStr[i + 1]; + int colorN = 16; + if ((ca >= L'0') && (ca <= L'9')) + colorN = ca - L'0'; + else if ((ca >= L'a') && (ca <= L'f')) + colorN = (ca - L'a') + 10; + else if ((ca >= L'A') && (ca <= L'F')) + colorN = (ca - L'A') + 10; - if (colorN == 16) - { - noise = true; - } - else - { - noise = false; - if (colorN < 0 || colorN > 15) colorN = 15; + if (colorN == 16) { + noise = true; + } else { + noise = false; + if (colorN < 0 || colorN > 15) colorN = 15; - if (dropShadow) colorN += 16; + if (dropShadow) colorN += 16; - int color = colors[colorN]; - glColor3f((color >> 16) / 255.0F, ((color >> 8) & 255) / 255.0F, (color & 255) / 255.0F); - } + int color = colors[colorN]; + glColor3f((color >> 16) / 255.0F, ((color >> 8) & 255) / 255.0F, + (color & 255) / 255.0F); + } + i += 1; + continue; + } - i += 1; - continue; - } - - // "noise" for crazy splash screen message - if (noise) - { - int newc; - do - { - newc = random->nextInt(SharedConstants::acceptableLetters.length()); - } while (charWidths[c + 32] != charWidths[newc + 32]); - c = newc; - } + // "noise" for crazy splash screen message + if (noise) { + int newc; + do { + newc = random->nextInt( + SharedConstants::acceptableLetters.length()); + } while (charWidths[c + 32] != charWidths[newc + 32]); + c = newc; + } - renderCharacter(c); - } + renderCharacter(c); + } } -void Font::draw(const std::wstring& str, int x, int y, int color, bool dropShadow) -{ - if (!str.empty()) - { - if ((color & 0xFC000000) == 0) color |= 0xFF000000; // force alpha - // if not set +void Font::draw(const std::wstring& str, int x, int y, int color, + bool dropShadow) { + if (!str.empty()) { + if ((color & 0xFC000000) == 0) color |= 0xFF000000; // force alpha + // if not set - if (dropShadow) // divide RGB by 4, preserve alpha - // 4jcraft changed -1 << 24 to the value of 1 (0xFF FF FF FF) - color = (color & 0xfcfcfc) >> 2 | (color & (0xFFFFFFFF << 24)); + if (dropShadow) // divide RGB by 4, preserve alpha + // 4jcraft changed -1 << 24 to the value of 1 (0xFF FF + // FF FF) + color = (color & 0xfcfcfc) >> 2 | (color & (0xFFFFFFFF << 24)); - glColor4f((color >> 16 & 255) / 255.0F, (color >> 8 & 255) / 255.0F, (color & 255) / 255.0F, (color >> 24 & 255) / 255.0F); + glColor4f((color >> 16 & 255) / 255.0F, (color >> 8 & 255) / 255.0F, + (color & 255) / 255.0F, (color >> 24 & 255) / 255.0F); - xPos = x; - yPos = y; - draw(str, dropShadow); - } + xPos = x; + yPos = y; + draw(str, dropShadow); + } } -int Font::width(const std::wstring& str) -{ - std::wstring cleanStr = sanitize(str); +int Font::width(const std::wstring& str) { + std::wstring cleanStr = sanitize(str); - if (cleanStr == L"") return 0; // 4J - was NULL comparison - int len = 0; + if (cleanStr == L"") return 0; // 4J - was NULL comparison + int len = 0; - for (int i = 0; i < cleanStr.length(); ++i) - { - wchar_t c = cleanStr.at(i); + for (int i = 0; i < cleanStr.length(); ++i) { + wchar_t c = cleanStr.at(i); - if(c == 167) - { - // Ignore the character used to define coloured text - ++i; - } - else - { - len += charWidths[c]; - } - } + if (c == 167) { + // Ignore the character used to define coloured text + ++i; + } else { + len += charWidths[c]; + } + } - return len; + return len; } -std::wstring Font::sanitize(const std::wstring& str) -{ - std::wstring sb = str; +std::wstring Font::sanitize(const std::wstring& str) { + std::wstring sb = str; - for (unsigned int i = 0; i < sb.length(); i++) - { - if (CharacterExists(sb[i])) - { - sb[i] = MapCharacter(sb[i]); - } - else - { - // If this character isn't supported, just show the first character (empty square box character) - sb[i] = 0; - } + for (unsigned int i = 0; i < sb.length(); i++) { + if (CharacterExists(sb[i])) { + sb[i] = MapCharacter(sb[i]); + } else { + // If this character isn't supported, just show the first character + // (empty square box character) + sb[i] = 0; + } } return sb; } -int Font::MapCharacter(wchar_t c) -{ - if (!m_charMap.empty()) - { - // Don't map space character - return c == ' ' ? c : m_charMap[c]; - } - else - { - return c; - } +int Font::MapCharacter(wchar_t c) { + if (!m_charMap.empty()) { + // Don't map space character + return c == ' ' ? c : m_charMap[c]; + } else { + return c; + } } -bool Font::CharacterExists(wchar_t c) -{ - if (!m_charMap.empty()) - { - return m_charMap.find(c) != m_charMap.end(); - } - else - { - return c >= 0 && c <= m_rows*m_cols; - } +bool Font::CharacterExists(wchar_t c) { + if (!m_charMap.empty()) { + return m_charMap.find(c) != m_charMap.end(); + } else { + return c >= 0 && c <= m_rows * m_cols; + } } -void Font::drawWordWrap(const std::wstring &string, int x, int y, int w, int col, int h) -{ - //if (bidirectional) - //{ - // string = reorderBidi(string); - //} - drawWordWrapInternal(string, x, y, w, col, h); +void Font::drawWordWrap(const std::wstring& string, int x, int y, int w, + int col, int h) { + // if (bidirectional) + //{ + // string = reorderBidi(string); + // } + drawWordWrapInternal(string, x, y, w, col, h); } -void Font::drawWordWrapInternal(const std::wstring &string, int x, int y, int w, int col, int h) -{ - drawWordWrapInternal(string, x, y, w, col, false, h); +void Font::drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, int h) { + drawWordWrapInternal(string, x, y, w, col, false, h); } -void Font::drawWordWrap(const std::wstring &string, int x, int y, int w, int col, bool darken, int h) -{ - //if (bidirectional) - //{ - // string = reorderBidi(string); - //} - drawWordWrapInternal(string, x, y, w, col, darken, h); +void Font::drawWordWrap(const std::wstring& string, int x, int y, int w, + int col, bool darken, int h) { + // if (bidirectional) + //{ + // string = reorderBidi(string); + // } + drawWordWrapInternal(string, x, y, w, col, darken, h); } -void Font::drawWordWrapInternal(const std::wstring& string, int x, int y, int w, int col, bool darken, int h) -{ - std::vectorlines = stringSplit(string,L'\n'); - if (lines.size() > 1) - { - AUTO_VAR(itEnd, lines.end()); - for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) - { - // 4J Stu - Don't draw text that will be partially cutoff/overlap something it shouldn't - if( (y + this->wordWrapHeight(*it, w)) > h) break; +void Font::drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, bool darken, int h) { + std::vector lines = stringSplit(string, L'\n'); + if (lines.size() > 1) { + AUTO_VAR(itEnd, lines.end()); + for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) { + // 4J Stu - Don't draw text that will be partially cutoff/overlap + // something it shouldn't + if ((y + this->wordWrapHeight(*it, w)) > h) break; drawWordWrapInternal(*it, x, y, w, col, h); y += this->wordWrapHeight(*it, w); } return; } - std::vector words = stringSplit(string,L' '); + std::vector words = stringSplit(string, L' '); unsigned int pos = 0; - while (pos < words.size()) - { + while (pos < words.size()) { std::wstring line = words[pos++] + L" "; - while (pos < words.size() && width(line + words[pos]) < w) - { + while (pos < words.size() && width(line + words[pos]) < w) { line += words[pos++] + L" "; } - while (width(line) > w) - { + while (width(line) > w) { int l = 0; - while (width(line.substr(0, l + 1)) <= w) - { + while (width(line.substr(0, l + 1)) <= w) { l++; } - if (trimString(line.substr(0, l)).length() > 0) - { + if (trimString(line.substr(0, l)).length() > 0) { draw(line.substr(0, l), x, y, col); y += 8; } line = line.substr(l); - // 4J Stu - Don't draw text that will be partially cutoff/overlap something it shouldn't - if( (y + 8) > h) break; + // 4J Stu - Don't draw text that will be partially cutoff/overlap + // something it shouldn't + if ((y + 8) > h) break; } - // 4J Stu - Don't draw text that will be partially cutoff/overlap something it shouldn't - if (trimString(line).length() > 0 && !( (y + 8) > h) ) - { + // 4J Stu - Don't draw text that will be partially cutoff/overlap + // something it shouldn't + if (trimString(line).length() > 0 && !((y + 8) > h)) { draw(line, x, y, col); y += 8; } } - } -int Font::wordWrapHeight(const std::wstring& string, int w) -{ - std::vector lines = stringSplit(string,L'\n'); - if (lines.size() > 1) - { +int Font::wordWrapHeight(const std::wstring& string, int w) { + std::vector lines = stringSplit(string, L'\n'); + if (lines.size() > 1) { int h = 0; - AUTO_VAR(itEnd, lines.end()); - for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) - { + AUTO_VAR(itEnd, lines.end()); + for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) { h += this->wordWrapHeight(*it, w); } return h; } - std::vector words = stringSplit(string,L' '); + std::vector words = stringSplit(string, L' '); unsigned int pos = 0; int y = 0; - while (pos < words.size()) - { + while (pos < words.size()) { std::wstring line = words[pos++] + L" "; - while (pos < words.size() && width(line + words[pos]) < w) - { + while (pos < words.size() && width(line + words[pos]) < w) { line += words[pos++] + L" "; } - while (width(line) > w) - { + while (width(line) > w) { int l = 0; - while (width(line.substr(0, l + 1)) <= w) - { + while (width(line.substr(0, l + 1)) <= w) { l++; } - if (trimString(line.substr(0, l)).length() > 0) - { + if (trimString(line.substr(0, l)).length() > 0) { y += 8; } line = line.substr(l); @@ -454,164 +409,162 @@ int Font::wordWrapHeight(const std::wstring& string, int w) } if (y < 8) y += 8; return y; - } -void Font::setEnforceUnicodeSheet(bool enforceUnicodeSheet) -{ - this->enforceUnicodeSheet = enforceUnicodeSheet; +void Font::setEnforceUnicodeSheet(bool enforceUnicodeSheet) { + this->enforceUnicodeSheet = enforceUnicodeSheet; } -void Font::setBidirectional(bool bidirectional) -{ - this->bidirectional = bidirectional; +void Font::setBidirectional(bool bidirectional) { + this->bidirectional = bidirectional; } -bool Font::AllCharactersValid(const std::wstring &str) -{ - for (int i = 0; i < (int)str.length(); ++i) - { - wchar_t c = str.at(i); +bool Font::AllCharactersValid(const std::wstring& str) { + for (int i = 0; i < (int)str.length(); ++i) { + wchar_t c = str.at(i); - if (c == 167 && i + 1 < str.length()) - { - // skip special color setting - i += 1; - continue; - } + if (c == 167 && i + 1 < str.length()) { + // skip special color setting + i += 1; + continue; + } - int index = SharedConstants::acceptableLetters.find(c); + int index = SharedConstants::acceptableLetters.find(c); - if ((c != ' ') && !(index > 0 && !enforceUnicodeSheet)) - { - return false; - } - } - return true; + if ((c != ' ') && !(index > 0 && !enforceUnicodeSheet)) { + return false; + } + } + return true; } // Not in use -/*// 4J - this code is lifted from #if 0 section above, so that we can directly create what would have gone in each of our 256 + 32 command buffers -void Font::renderFakeCB(IntBuffer *ib) +/*// 4J - this code is lifted from #if 0 section above, so that we can directly +create what would have gone in each of our 256 + 32 command buffers void +Font::renderFakeCB(IntBuffer *ib) { Tesselator *t = Tesselator::getInstance(); - int i; + int i; - for(unsigned int j = 0; j < ib->limit(); j++) - { - int cb = ib->get(j); + for(unsigned int j = 0; j < ib->limit(); j++) + { + int cb = ib->get(j); - if( cb < 256 ) - { - i = cb; - t->begin(); - int ix = i % 16 * 8; - int iy = i / 16 * 8; - // float s = 7.99f; - float s = 7.99f; + if( cb < 256 ) + { + i = cb; + t->begin(); + int ix = i % 16 * 8; + int iy = i / 16 * 8; + // float s = 7.99f; + float s = 7.99f; - float uo = (0.0f) / 128.0f; - float vo = (0.0f) / 128.0f; + float uo = (0.0f) / 128.0f; + float vo = (0.0f) / 128.0f; - t->vertexUV((float)(0), (float)( 0 + s), (float)( 0), (float)( ix / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); - t->vertexUV((float)(0 + s), (float)( 0 + s), (float)( 0), (float)( (ix + s) / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); - t->vertexUV((float)(0 + s), (float)( 0), (float)( 0), (float)( (ix + s) / 128.0f + uo), (float)( iy / 128.0f + vo)); - t->vertexUV((float)(0), (float)( 0), (float)( 0), (float)( ix / 128.0f + uo), (float)( iy / 128.0f + vo)); - // target.colorBlit(texture, x + xo, y, color, ix, iy, - // charWidths[chars[i]], 8); - t->end(); + t->vertexUV((float)(0), (float)( 0 + s), (float)( 0), +(float)( ix / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); + t->vertexUV((float)(0 + s), (float)( 0 + s), (float)( +0), (float)( (ix + s) / 128.0f + uo), (float)( (iy + s) / 128.0f + vo)); + t->vertexUV((float)(0 + s), (float)( 0), (float)( 0), +(float)( (ix + s) / 128.0f + uo), (float)( iy / 128.0f + vo)); + t->vertexUV((float)(0), (float)( 0), (float)( 0), +(float)( ix / 128.0f + uo), (float)( iy / 128.0f + vo)); + // target.colorBlit(texture, x + xo, y, color, ix, iy, + // charWidths[chars[i]], 8); + t->end(); - glTranslatef((float)charWidths[i], 0, 0); - } - else - { - i = cb - 256; + glTranslatef((float)charWidths[i], 0, 0); + } + else + { + i = cb - 256; - int br = ((i >> 3) & 1) * 0x55; - int r = ((i >> 2) & 1) * 0xaa + br; - int g = ((i >> 1) & 1) * 0xaa + br; - int b = ((i >> 0) & 1) * 0xaa + br; - if (i == 6) - { - r += 0x55; - } - bool darken = i >= 16; + int br = ((i >> 3) & 1) * 0x55; + int r = ((i >> 2) & 1) * 0xaa + br; + int g = ((i >> 1) & 1) * 0xaa + br; + int b = ((i >> 0) & 1) * 0xaa + br; + if (i == 6) + { + r += 0x55; + } + bool darken = i >= 16; - // color = r << 16 | g << 8 | b; - if (darken) - { - r /= 4; - g /= 4; - b /= 4; - } - glColor3f(r / 255.0f, g / 255.0f, b / 255.0f); - } - } + // color = r << 16 | g << 8 | b; + if (darken) + { + r /= 4; + g /= 4; + b /= 4; + } + glColor3f(r / 255.0f, g / 255.0f, b / 255.0f); + } + } } void Font::loadUnicodePage(int page) { - wchar_t fileName[25]; - //String fileName = String.format("/1_2_2/font/glyph_%02X.png", page); - swprintf(fileName,25,L"/1_2_2/font/glyph_%02X.png",page); - BufferedImage *image = new BufferedImage(fileName); - //try - //{ - // image = ImageIO.read(Textures.class.getResourceAsStream(fileName.toString())); - //} - //catch (IOException e) - //{ - // throw new RuntimeException(e); - //} + wchar_t fileName[25]; + //String fileName = String.format("/1_2_2/font/glyph_%02X.png", page); + swprintf(fileName,25,L"/1_2_2/font/glyph_%02X.png",page); + BufferedImage *image = new BufferedImage(fileName); + //try + //{ + // image = +ImageIO.read(Textures.class.getResourceAsStream(fileName.toString())); + //} + //catch (IOException e) + //{ + // throw new RuntimeException(e); + //} - unicodeTexID[page] = textures->getTexture(image); - lastBoundTexture = unicodeTexID[page]; + unicodeTexID[page] = textures->getTexture(image); + lastBoundTexture = unicodeTexID[page]; } void Font::renderUnicodeCharacter(wchar_t c) { - if (unicodeWidth[c] == 0) - { - // System.out.println("no-width char " + c); - return; - } + if (unicodeWidth[c] == 0) + { + // System.out.println("no-width char " + c); + return; + } - int page = c / 256; + int page = c / 256; - if (unicodeTexID[page] == 0) loadUnicodePage(page); + if (unicodeTexID[page] == 0) loadUnicodePage(page); - if (lastBoundTexture != unicodeTexID[page]) - { - glBindTexture(GL_TEXTURE_2D, unicodeTexID[page]); - lastBoundTexture = unicodeTexID[page]; - } + if (lastBoundTexture != unicodeTexID[page]) + { + glBindTexture(GL_TEXTURE_2D, unicodeTexID[page]); + lastBoundTexture = unicodeTexID[page]; + } - // first column with non-trans pixels - int firstLeft = unicodeWidth[c] >> 4; - // last column with non-trans pixels - int firstRight = unicodeWidth[c] & 0xF; + // first column with non-trans pixels + int firstLeft = unicodeWidth[c] >> 4; + // last column with non-trans pixels + int firstRight = unicodeWidth[c] & 0xF; - float left = firstLeft; - float right = firstRight + 1; + float left = firstLeft; + float right = firstRight + 1; + + float xOff = c % 16 * 16 + left; + float yOff = (c & 0xFF) / 16 * 16; + float width = right - left - .02f; - float xOff = c % 16 * 16 + left; - float yOff = (c & 0xFF) / 16 * 16; - float width = right - left - .02f; - Tesselator *t = Tesselator::getInstance(); - t->begin(GL_TRIANGLE_STRIP); - t->tex(xOff / 256.0F, yOff / 256.0F); - t->vertex(xPos, yPos, 0.0f); - t->tex(xOff / 256.0F, (yOff + 15.98f) / 256.0F); - t->vertex(xPos, yPos + 7.99f, 0.0f); - t->tex((xOff + width) / 256.0F, yOff / 256.0F); - t->vertex(xPos + width / 2, yPos, 0.0f); - t->tex((xOff + width) / 256.0F, (yOff + 15.98f) / 256.0F); - t->vertex(xPos + width / 2, yPos + 7.99f, 0.0f); - t->end(); + t->begin(GL_TRIANGLE_STRIP); + t->tex(xOff / 256.0F, yOff / 256.0F); + t->vertex(xPos, yPos, 0.0f); + t->tex(xOff / 256.0F, (yOff + 15.98f) / 256.0F); + t->vertex(xPos, yPos + 7.99f, 0.0f); + t->tex((xOff + width) / 256.0F, yOff / 256.0F); + t->vertex(xPos + width / 2, yPos, 0.0f); + t->tex((xOff + width) / 256.0F, (yOff + 15.98f) / 256.0F); + t->vertex(xPos + width / 2, yPos + 7.99f, 0.0f); + t->end(); - xPos += (right - left) / 2 + 1; + xPos += (right - left) / 2 + 1; } */ - diff --git a/Minecraft.Client/UI/Font.h b/Minecraft.Client/UI/Font.h index e7769698c..fcfe83359 100644 --- a/Minecraft.Client/UI/Font.h +++ b/Minecraft.Client/UI/Font.h @@ -3,81 +3,90 @@ class IntBuffer; class Options; class Textures; -class Font -{ +class Font { private: - int *charWidths; -public: - int fontTexture; - Random *random; - -private: - int colors[32]; // RGB colors for formatting - - Textures *textures; - - float xPos; - float yPos; - - bool enforceUnicodeSheet; // use unicode sheet for ascii - bool bidirectional; // use bidi to flip strings - - int m_cols; // Number of columns in font sheet - int m_rows; // Number of rows in font sheet - int m_charWidth; // Maximum character width - int m_charHeight; // Maximum character height - TEXTURE_NAME m_textureName; // Texture - std::map m_charMap; + int* charWidths; public: - Font(Options *options, const std::wstring& name, Textures* textures, bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, int charWidth, int charHeight, unsigned short charMap[] = NULL); + int fontTexture; + Random* random; + +private: + int colors[32]; // RGB colors for formatting + + Textures* textures; + + float xPos; + float yPos; + + bool enforceUnicodeSheet; // use unicode sheet for ascii + bool bidirectional; // use bidi to flip strings + + int m_cols; // Number of columns in font sheet + int m_rows; // Number of rows in font sheet + int m_charWidth; // Maximum character width + int m_charHeight; // Maximum character height + TEXTURE_NAME m_textureName; // Texture + std::map m_charMap; + +public: + Font(Options* options, const std::wstring& name, Textures* textures, + bool enforceUnicode, TEXTURE_NAME textureName, int cols, int rows, + int charWidth, int charHeight, unsigned short charMap[] = NULL); #ifndef _XBOX - // 4J Stu - This dtor clashes with one in xui! We never delete these anyway so take it out for now. Can go back when we have got rid of XUI - ~Font(); + // 4J Stu - This dtor clashes with one in xui! We never delete these anyway + // so take it out for now. Can go back when we have got rid of XUI + ~Font(); #endif - void renderFakeCB(IntBuffer *cb); // 4J added + void renderFakeCB(IntBuffer* cb); // 4J added private: - void renderCharacter(wchar_t c); // 4J added + void renderCharacter(wchar_t c); // 4J added public: void drawShadow(const std::wstring& str, int x, int y, int color); - void drawShadowWordWrap(const std::wstring &str, int x, int y, int w, int color, int h); // 4J Added h param - void draw(const std::wstring &str, int x, int y, int color); - /** - * Reorders the string according to bidirectional levels. A bit expensive at - * the moment. - * - * @param str - * @return - */ + void drawShadowWordWrap(const std::wstring& str, int x, int y, int w, + int color, int h); // 4J Added h param + void draw(const std::wstring& str, int x, int y, int color); + /** + * Reorders the string according to bidirectional levels. A bit expensive at + * the moment. + * + * @param str + * @return + */ private: - std::wstring reorderBidi(const std::wstring &str); + std::wstring reorderBidi(const std::wstring& str); - void draw(const std::wstring &str, bool dropShadow); - void draw(const std::wstring& str, int x, int y, int color, bool dropShadow); - int MapCharacter(wchar_t c); // 4J added - bool CharacterExists(wchar_t c); // 4J added + void draw(const std::wstring& str, bool dropShadow); + void draw(const std::wstring& str, int x, int y, int color, + bool dropShadow); + int MapCharacter(wchar_t c); // 4J added + bool CharacterExists(wchar_t c); // 4J added public: int width(const std::wstring& str); std::wstring sanitize(const std::wstring& str); - void drawWordWrap(const std::wstring &string, int x, int y, int w, int col, int h); // 4J Added h param + void drawWordWrap(const std::wstring& string, int x, int y, int w, int col, + int h); // 4J Added h param private: - void drawWordWrapInternal(const std::wstring &string, int x, int y, int w, int col, int h); // 4J Added h param + void drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, int h); // 4J Added h param public: - void drawWordWrap(const std::wstring &string, int x, int y, int w, int col, bool darken, int h); // 4J Added h param + void drawWordWrap(const std::wstring& string, int x, int y, int w, int col, + bool darken, int h); // 4J Added h param private: - void drawWordWrapInternal(const std::wstring& string, int x, int y, int w, int col, bool darken, int h); // 4J Added h param + void drawWordWrapInternal(const std::wstring& string, int x, int y, int w, + int col, bool darken, int h); // 4J Added h param public: int wordWrapHeight(const std::wstring& string, int w); - void setEnforceUnicodeSheet(bool enforceUnicodeSheet); - void setBidirectional(bool bidirectional); + void setEnforceUnicodeSheet(bool enforceUnicodeSheet); + void setBidirectional(bool bidirectional); - // 4J-PB - check for invalid player name - Japanese local name - bool AllCharactersValid(const std::wstring &str); + // 4J-PB - check for invalid player name - Japanese local name + bool AllCharactersValid(const std::wstring& str); }; diff --git a/Minecraft.Client/UI/Gui.cpp b/Minecraft.Client/UI/Gui.cpp index fc1f8ea47..04b8170f0 100644 --- a/Minecraft.Client/UI/Gui.cpp +++ b/Minecraft.Client/UI/Gui.cpp @@ -35,831 +35,911 @@ // #define RENDER_HUD 1 // #endif -float Gui::currentGuiBlendFactor = 1.0f; // 4J added -float Gui::currentGuiScaleFactor = 1.0f; // 4J added -ItemRenderer *Gui::itemRenderer = new ItemRenderer(); +float Gui::currentGuiBlendFactor = 1.0f; // 4J added +float Gui::currentGuiScaleFactor = 1.0f; // 4J added +ItemRenderer* Gui::itemRenderer = new ItemRenderer(); -Gui::Gui(Minecraft *minecraft) -{ - // 4J - initialisers added +Gui::Gui(Minecraft* minecraft) { + // 4J - initialisers added random = new Random(); - tickCount = 0; + tickCount = 0; overlayMessageTime = 0; animateOverlayMessageColor = false; - progress = 0.0f; - tbr = 1.0f; - fAlphaIncrementPerCent=255.0f/100.0f; + progress = 0.0f; + tbr = 1.0f; + fAlphaIncrementPerCent = 255.0f / 100.0f; - this->minecraft = minecraft; + this->minecraft = minecraft; - lastTickA = 0.0f; + lastTickA = 0.0f; } -void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) -{ - // 4J Stu - I have copied this code for XUI_BaseScene. If/when it gets changed it should be broken out - // 4J - altered to force full screen mode to 3X scaling, and any split screen modes to 2X scaling. This is so that the further scaling by 0.5 that - // happens in split screen modes results in a final scaling of 1 rather than 1.5. - int splitYOffset;// = 20; // This offset is applied when doing the 2X scaling above to move the gui out of the way of the tool tips - int guiScale;// = ( minecraft->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_FULLSCREEN ? 3 : 2 ); - int iPad=minecraft->player->GetXboxPad(); - int iWidthOffset=0,iHeightOffset=0; // used to get the interface looking right on a 2 player split screen game +void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) { + // 4J Stu - I have copied this code for XUI_BaseScene. If/when it gets + // changed it should be broken out 4J - altered to force full screen mode to + // 3X scaling, and any split screen modes to 2X scaling. This is so that the + // further scaling by 0.5 that happens in split screen modes results in a + // final scaling of 1 rather than 1.5. + int splitYOffset; // = 20; // This offset is applied when doing the 2X + // scaling above to move the gui out of the way of the + // tool tips + int guiScale; // = ( minecraft->player->m_iScreenSection == + // C4JRender::VIEWPORT_TYPE_FULLSCREEN ? 3 : 2 ); + int iPad = minecraft->player->GetXboxPad(); + int iWidthOffset = 0, + iHeightOffset = 0; // used to get the interface looking right on a 2 + // player split screen game - // 4J-PB - selected the gui scale based on the slider settings - if(minecraft->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_FULLSCREEN) - { - guiScale=app.GetGameSettings(iPad,eGameSetting_UISize) + 2; - } - else - { - guiScale=app.GetGameSettings(iPad,eGameSetting_UISizeSplitscreen) + 2; - } + // 4J-PB - selected the gui scale based on the slider settings + if (minecraft->player->m_iScreenSection == + C4JRender::VIEWPORT_TYPE_FULLSCREEN) { + guiScale = app.GetGameSettings(iPad, eGameSetting_UISize) + 2; + } else { + guiScale = + app.GetGameSettings(iPad, eGameSetting_UISizeSplitscreen) + 2; + } + ScreenSizeCalculator ssc(minecraft->options, minecraft->width, + minecraft->height, guiScale); + int screenWidth = ssc.getWidth(); + int screenHeight = ssc.getHeight(); + int iSafezoneXHalf = 0, iSafezoneYHalf = 0; + int iTooltipsYOffset = 0; + int quickSelectWidth = 182; + int quickSelectHeight = 22; + float fScaleFactorWidth = 1.0f, fScaleFactorHeight = 1.0f; + bool bTwoPlayerSplitscreen = false; + currentGuiScaleFactor = + (float)guiScale; // Keep static copy of scale so we know how gui + // coordinates map to physical pixels - this is also + // affected by the viewport - ScreenSizeCalculator ssc(minecraft->options, minecraft->width, minecraft->height, guiScale ); - int screenWidth = ssc.getWidth(); - int screenHeight = ssc.getHeight(); - int iSafezoneXHalf=0,iSafezoneYHalf=0; - int iTooltipsYOffset=0; - int quickSelectWidth=182; - int quickSelectHeight=22; - float fScaleFactorWidth=1.0f,fScaleFactorHeight=1.0f; - bool bTwoPlayerSplitscreen=false; - currentGuiScaleFactor = (float) guiScale; // Keep static copy of scale so we know how gui coordinates map to physical pixels - this is also affected by the viewport + switch (guiScale) { + case 3: + splitYOffset = 0; + break; + case 4: + splitYOffset = -5; + break; + default: // 2 + splitYOffset = 10; + break; + } - switch(guiScale) - { - case 3: - splitYOffset = 0; - break; - case 4: - splitYOffset = -5; - break; - default: // 2 - splitYOffset = 10; - break; - } + // Check which screen section this player is in + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + // single player + iSafezoneXHalf = screenWidth / 20; // 5% + iSafezoneYHalf = screenHeight / 20; // 5% + iTooltipsYOffset = 40 + splitYOffset; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + iSafezoneXHalf = + screenWidth / + 10; // 5% (need to treat the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset; + fScaleFactorWidth = 0.5f; + iWidthOffset = + (int)((float)screenWidth * (1.0f - fScaleFactorWidth)); + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + iSafezoneXHalf = + screenWidth / + 10; // 5% (need to treat the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset + + screenHeight / 10; // 5% (need to treat the whole + // screen is 2x this screen) + fScaleFactorWidth = 0.5f; + iWidthOffset = + (int)((float)screenWidth * (1.0f - fScaleFactorWidth)); + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + iSafezoneXHalf = + screenWidth / 10; // 5% (the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset + + screenHeight / 10; // 5% (need to treat the whole + // screen is 2x this screen) + fScaleFactorHeight = 0.5f; + iHeightOffset = screenHeight; + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + iSafezoneXHalf = 0; + iSafezoneYHalf = splitYOffset + + screenHeight / 10; // 5% (need to treat the whole + // screen is 2x this screen) + fScaleFactorHeight = 0.5f; + iHeightOffset = screenHeight; + iTooltipsYOffset = 44; + bTwoPlayerSplitscreen = true; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + iSafezoneXHalf = + screenWidth / 10; // 5% (the whole screen is 2x this screen) + iSafezoneYHalf = splitYOffset; + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + iSafezoneXHalf = 0; + iSafezoneYHalf = splitYOffset; // 5% + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + iSafezoneXHalf = + screenWidth / 10; // 5% (the whole screen is 2x this screen) + iSafezoneYHalf = + splitYOffset + + screenHeight / 10; // 5% (the whole screen is 2x this screen) + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + iSafezoneXHalf = 0; + iSafezoneYHalf = + splitYOffset + + screenHeight / 10; // 5% (the whole screen is 2x this screen) + iTooltipsYOffset = 44; + currentGuiScaleFactor *= 0.5f; + break; + } - // Check which screen section this player is in - switch(minecraft->player->m_iScreenSection) - { - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - // single player - iSafezoneXHalf = screenWidth/20; // 5% - iSafezoneYHalf = screenHeight/20; // 5% - iTooltipsYOffset=40+splitYOffset; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - iSafezoneXHalf = screenWidth/10; // 5% (need to treat the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset; - fScaleFactorWidth=0.5f; - iWidthOffset=(int)((float)screenWidth*(1.0f - fScaleFactorWidth)); - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - iSafezoneXHalf = screenWidth/10; // 5% (need to treat the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) - fScaleFactorWidth=0.5f; - iWidthOffset=(int)((float)screenWidth*(1.0f - fScaleFactorWidth)); - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - iSafezoneXHalf = screenWidth/10; // 5% (the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) - fScaleFactorHeight=0.5f; - iHeightOffset=screenHeight; - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - iSafezoneXHalf = 0; - iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) - fScaleFactorHeight=0.5f; - iHeightOffset=screenHeight; - iTooltipsYOffset=44; - bTwoPlayerSplitscreen=true; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - iSafezoneXHalf = screenWidth/10; // 5% (the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset; - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - iSafezoneXHalf = 0; - iSafezoneYHalf = splitYOffset; // 5% - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - iSafezoneXHalf = screenWidth/10; // 5% (the whole screen is 2x this screen) - iSafezoneYHalf = splitYOffset + screenHeight/10; // 5% (the whole screen is 2x this screen) - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - iSafezoneXHalf = 0; - iSafezoneYHalf = splitYOffset + screenHeight/10; // 5% (the whole screen is 2x this screen) - iTooltipsYOffset=44; - currentGuiScaleFactor *= 0.5f; - break; - - } + // 4J-PB - turn off the slot display if a xui menu is up, or if we're + // autosaving + bool bDisplayGui = !ui.GetMenuDisplayed(iPad) && + !(app.GetXuiAction(iPad) == + eAppAction_AutosaveSaveGameCapturedThumbnail); - // 4J-PB - turn off the slot display if a xui menu is up, or if we're autosaving - bool bDisplayGui=!ui.GetMenuDisplayed(iPad) && !(app.GetXuiAction(iPad)==eAppAction_AutosaveSaveGameCapturedThumbnail); + // if tooltips are off, set the y offset to zero + if (app.GetGameSettings(iPad, eGameSetting_Tooltips) == 0 && bDisplayGui) { + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + iTooltipsYOffset = screenHeight / 10; + break; + default: + // iTooltipsYOffset=screenHeight/10; + switch (guiScale) { + case 3: + iTooltipsYOffset = 28; // screenHeight/10; + break; + case 4: + iTooltipsYOffset = 28; // screenHeight/10; + break; + default: // 2 + iTooltipsYOffset = 14; // screenHeight/10; + break; + } + break; + } + } - // if tooltips are off, set the y offset to zero - if(app.GetGameSettings(iPad,eGameSetting_Tooltips)==0 && bDisplayGui) - { - switch(minecraft->player->m_iScreenSection) - { - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - iTooltipsYOffset=screenHeight/10; - break; - default: - //iTooltipsYOffset=screenHeight/10; - switch(guiScale) - { - case 3: - iTooltipsYOffset=28;//screenHeight/10; - break; - case 4: - iTooltipsYOffset=28;//screenHeight/10; - break; - default: // 2 - iTooltipsYOffset=14;//screenHeight/10; - break; - } - break; - } - } - - // 4J-PB - Turn off interface if eGameSetting_DisplayHUD is off - for screen shots/videos. - if ( app.GetGameSettings(iPad,eGameSetting_DisplayHUD)==0 ) - { - bDisplayGui = false; - } - - Font *font = minecraft->font; + // 4J-PB - Turn off interface if eGameSetting_DisplayHUD is off - for screen + // shots/videos. + if (app.GetGameSettings(iPad, eGameSetting_DisplayHUD) == 0) { + bDisplayGui = false; + } + Font* font = minecraft->font; minecraft->gameRenderer->setupGuiScreen(guiScale); - - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // 4J - added - this did actually get set in renderVignette but that code is currently commented out + glBlendFunc(GL_SRC_ALPHA, + GL_ONE_MINUS_SRC_ALPHA); // 4J - added - this did actually get + // set in renderVignette but that code + // is currently commented out - if (Minecraft::useFancyGraphics()) - { - renderVignette(minecraft->player->getBrightness(a), screenWidth, screenHeight); - } + if (Minecraft::useFancyGraphics()) { + renderVignette(minecraft->player->getBrightness(a), screenWidth, + screenHeight); + } - ///////////////////////////////////////////////////////////////////////////////////// - // Display the pumpkin screen effect - ///////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////// + // Display the pumpkin screen effect + ///////////////////////////////////////////////////////////////////////////////////// - std::shared_ptr headGear = minecraft->player->inventory->getArmor(3); + std::shared_ptr headGear = + minecraft->player->inventory->getArmor(3); - // 4J-PB - changing this to be per player - //if (!minecraft->options->thirdPersonView && headGear != NULL && headGear->id == Tile::pumpkin_Id) renderPumpkin(screenWidth, screenHeight); - if ((minecraft->player->ThirdPersonView()==0) && headGear != NULL && headGear->id == Tile::pumpkin_Id) renderPumpkin(screenWidth, screenHeight); - if (!minecraft->player->hasEffect(MobEffect::confusion)) - { - float pt = minecraft->player->oPortalTime + (minecraft->player->portalTime - minecraft->player->oPortalTime) * a; - if (pt > 0) - { - renderTp(pt, screenWidth, screenHeight); - } - } + // 4J-PB - changing this to be per player + // if (!minecraft->options->thirdPersonView && headGear != NULL && + // headGear->id == Tile::pumpkin_Id) renderPumpkin(screenWidth, + // screenHeight); + if ((minecraft->player->ThirdPersonView() == 0) && headGear != NULL && + headGear->id == Tile::pumpkin_Id) + renderPumpkin(screenWidth, screenHeight); + if (!minecraft->player->hasEffect(MobEffect::confusion)) { + float pt = + minecraft->player->oPortalTime + + (minecraft->player->portalTime - minecraft->player->oPortalTime) * + a; + if (pt > 0) { + renderTp(pt, screenWidth, screenHeight); + } + } - if (!minecraft->gameMode->isCutScene()) - { - if(bDisplayGui && bTwoPlayerSplitscreen) - { - // need to apply scale factors depending on the mode - glPushMatrix(); - glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); - } + if (!minecraft->gameMode->isCutScene()) { + if (bDisplayGui && bTwoPlayerSplitscreen) { + // need to apply scale factors depending on the mode + glPushMatrix(); + glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); + } #if RENDER_HUD - ///////////////////////////////////////////////////////////////////////////////////// - // Display the quick select background, the quick select selection, and the crosshair - ///////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////// + // Display the quick select background, the quick select selection, and + // the crosshair + ///////////////////////////////////////////////////////////////////////////////////// - glColor4f(1, 1, 1, 1); + glColor4f(1, 1, 1, 1); - // 4J - this is where to set the blend factor for gui things - // use the primary player's settings - unsigned char ucAlpha=app.GetGameSettings(ProfileManager.GetPrimaryPad(),eGameSetting_InterfaceOpacity); + // 4J - this is where to set the blend factor for gui things + // use the primary player's settings + unsigned char ucAlpha = app.GetGameSettings( + ProfileManager.GetPrimaryPad(), eGameSetting_InterfaceOpacity); - // If the user has started to navigate their quickselect bar, ignore the alpha setting, and display at default value - float fVal=fAlphaIncrementPerCent*(float)ucAlpha; - if(ucAlpha<80) - { - // check if we have the timer running for the opacity - unsigned int uiOpacityTimer=app.GetOpacityTimer(iPad); - if(uiOpacityTimer!=0) - { - if(uiOpacityTimer<10) - { - float fStep=(80.0f-(float)ucAlpha)/10.0f; - fVal=fAlphaIncrementPerCent*(80.0f-((10.0f-(float)uiOpacityTimer)*fStep)); - } - else - { - fVal=fAlphaIncrementPerCent*80.0f; - } - } - else - { - fVal=fAlphaIncrementPerCent*(float)ucAlpha; - } - } - else - { - fVal=fAlphaIncrementPerCent*(float)ucAlpha; - } + // If the user has started to navigate their quickselect bar, ignore the + // alpha setting, and display at default value + float fVal = fAlphaIncrementPerCent * (float)ucAlpha; + if (ucAlpha < 80) { + // check if we have the timer running for the opacity + unsigned int uiOpacityTimer = app.GetOpacityTimer(iPad); + if (uiOpacityTimer != 0) { + if (uiOpacityTimer < 10) { + float fStep = (80.0f - (float)ucAlpha) / 10.0f; + fVal = fAlphaIncrementPerCent * + (80.0f - ((10.0f - (float)uiOpacityTimer) * fStep)); + } else { + fVal = fAlphaIncrementPerCent * 80.0f; + } + } else { + fVal = fAlphaIncrementPerCent * (float)ucAlpha; + } + } else { + fVal = fAlphaIncrementPerCent * (float)ucAlpha; + } - RenderManager.StateSetBlendFactor(0xffffff |(((unsigned int)fVal)<<24)); - currentGuiBlendFactor = fVal / 255.0f; - // RenderManager.StateSetBlendFactor(0x40ffffff); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + RenderManager.StateSetBlendFactor(0xffffff | + (((unsigned int)fVal) << 24)); + currentGuiBlendFactor = fVal / 255.0f; + // RenderManager.StateSetBlendFactor(0x40ffffff); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - blitOffset = -90; + blitOffset = -90; - ///////////////////////////////////////////////////////////////////////////////////// - // Display the quick select background, the quick select selection, and the crosshair - ///////////////////////////////////////////////////////////////////////////////////// - if(bDisplayGui) - { - MemSect(31); - minecraft->textures->bindTexture(TN_GUI_GUI); // 4J was L"/gui/gui.png" - MemSect(0); + ///////////////////////////////////////////////////////////////////////////////////// + // Display the quick select background, the quick select selection, and + // the crosshair + ///////////////////////////////////////////////////////////////////////////////////// + if (bDisplayGui) { + MemSect(31); + minecraft->textures->bindTexture( + TN_GUI_GUI); // 4J was L"/gui/gui.png" + MemSect(0); - std::shared_ptr inventory = minecraft->player->inventory; - if(bTwoPlayerSplitscreen) - { - // need to apply scale factors depending on the mode + std::shared_ptr inventory = minecraft->player->inventory; + if (bTwoPlayerSplitscreen) { + // need to apply scale factors depending on the mode - // 4J Stu - Moved this push and scale further up as we still need to do it for the few HUD components not replaced by xui - //glPushMatrix(); - //glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); - - // 4J-PB - move into the safe zone, and account for 2 player splitscreen - blit(iWidthOffset + (screenWidth - quickSelectWidth)/2, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset , 0, 0, 182, 22); - blit(iWidthOffset + (screenWidth - quickSelectWidth)/2 - 1 + inventory->selected * 20, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 1, 0, 22, 24, 22); - } - else - { - blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset , 0, 0, 182, 22); - blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2 - 1 + inventory->selected * 20, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 1, 0, 22, 24, 22); - } + // 4J Stu - Moved this push and scale further up as we still + // need to do it for the few HUD components not replaced by xui + // glPushMatrix(); + // glScalef(fScaleFactorWidth, fScaleFactorHeight, + // fScaleFactorWidth); + // 4J-PB - move into the safe zone, and account for 2 player + // splitscreen + blit(iWidthOffset + (screenWidth - quickSelectWidth) / 2, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset, + 0, 0, 182, 22); + blit(iWidthOffset + (screenWidth - quickSelectWidth) / 2 - 1 + + inventory->selected * 20, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset - 1, + 0, 22, 24, 22); + } else { + blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset, + 0, 0, 182, 22); + blit(iWidthOffset + screenWidth / 2 - quickSelectWidth / 2 - 1 + + inventory->selected * 20, + iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset - 1, + 0, 22, 24, 22); + } - MemSect(31); - minecraft->textures->bindTexture(TN_GUI_ICONS);//L"/gui/icons.png")); - MemSect(0); - glEnable(GL_BLEND); - RenderManager.StateSetBlendFactor(0xffffff |(((unsigned int)fVal)<<24)); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - //glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR); - // 4J Stu - We don't want to adjust the cursor by the safezone, we want it centred - if(bTwoPlayerSplitscreen) - { - blit(iWidthOffset + screenWidth / 2 - 7, (iHeightOffset + screenHeight) / 2 - 7, 0, 0, 16, 16); - } - else - { - blit(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16); - } - glDisable(GL_BLEND); + MemSect(31); + minecraft->textures->bindTexture( + TN_GUI_ICONS); // L"/gui/icons.png")); + MemSect(0); + glEnable(GL_BLEND); + RenderManager.StateSetBlendFactor(0xffffff | + (((unsigned int)fVal) << 24)); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + // glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR); + // 4J Stu - We don't want to adjust the cursor by the safezone, we + // want it centred + if (bTwoPlayerSplitscreen) { + blit(iWidthOffset + screenWidth / 2 - 7, + (iHeightOffset + screenHeight) / 2 - 7, 0, 0, 16, 16); + } else { + blit(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16); + } + glDisable(GL_BLEND); - // if(bTwoPlayerSplitscreen) - // { - // glPopMatrix(); - // } + // if(bTwoPlayerSplitscreen) + // { + // glPopMatrix(); + // } + } - } + bool blink = minecraft->player->invulnerableTime / 3 % 2 == 1; + if (minecraft->player->invulnerableTime < 10) blink = false; + int iHealth = minecraft->player->getHealth(); + int iLastHealth = minecraft->player->lastHealth; + random->setSeed(tickCount * 312871); - bool blink = minecraft->player->invulnerableTime / 3 % 2 == 1; - if (minecraft->player->invulnerableTime < 10) blink = false; - int iHealth = minecraft->player->getHealth(); - int iLastHealth = minecraft->player->lastHealth; - random->setSeed(tickCount * 312871); + bool foodBlink = false; + FoodData* foodData = minecraft->player->getFoodData(); + int food = foodData->getFoodLevel(); + int oldFood = foodData->getLastFoodLevel(); - bool foodBlink = false; - FoodData *foodData = minecraft->player->getFoodData(); - int food = foodData->getFoodLevel(); - int oldFood = foodData->getLastFoodLevel(); + // if (false) //(true) + // { + // renderBossHealth(); + // } -// if (false) //(true) -// { -// renderBossHealth(); -// } + ///////////////////////////////////////////////////////////////////////////////////// + // Display the experience, food, armour, health and the air bubbles + ///////////////////////////////////////////////////////////////////////////////////// + if (bDisplayGui) { + // 4J - added blend for fading gui + glEnable(GL_BLEND); + glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - ///////////////////////////////////////////////////////////////////////////////////// - // Display the experience, food, armour, health and the air bubbles - ///////////////////////////////////////////////////////////////////////////////////// - if(bDisplayGui) - { - // 4J - added blend for fading gui - glEnable(GL_BLEND); - glBlendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + if (minecraft->gameMode->canHurtPlayer()) { + int xLeft, xRight; + // 4J Stu - TODO Work out proper positioning for splitscreen + if (bTwoPlayerSplitscreen) { + xLeft = iWidthOffset + (screenWidth - quickSelectWidth) / 2; + xRight = + iWidthOffset + (screenWidth + quickSelectWidth) / 2; + } else { + xLeft = (screenWidth - quickSelectWidth) / 2; + xRight = (screenWidth + quickSelectWidth) / 2; + } - if (minecraft->gameMode->canHurtPlayer()) - { - int xLeft, xRight; - // 4J Stu - TODO Work out proper positioning for splitscreen - if(bTwoPlayerSplitscreen) - { - xLeft = iWidthOffset + (screenWidth - quickSelectWidth)/2; - xRight = iWidthOffset + (screenWidth + quickSelectWidth)/2; - } - else - { - xLeft = (screenWidth - quickSelectWidth)/2; - xRight = (screenWidth + quickSelectWidth) / 2; - } + // render experience bar + int xpNeededForNextLevel = + minecraft->player->getXpNeededForNextLevel(); + if (xpNeededForNextLevel > 0) { + int w = 182; - // render experience bar - int xpNeededForNextLevel = minecraft->player->getXpNeededForNextLevel(); - if (xpNeededForNextLevel > 0) - { - int w = 182; + int progress = (int)(minecraft->player->experienceProgress * + (float)(w + 1)); - int progress = (int) (minecraft->player->experienceProgress * (float) (w + 1)); + int yo = + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 8; + if (bTwoPlayerSplitscreen) { + yo += iHeightOffset; + } + blit(xLeft, yo, 0, 64, w, 5); + if (progress > 0) { + blit(xLeft, yo, 0, 69, progress, 5); + } + } - int yo = screenHeight - iSafezoneYHalf - iTooltipsYOffset - 8; - if(bTwoPlayerSplitscreen) - { - yo+=iHeightOffset; - } - blit(xLeft, yo, 0, 64, w, 5); - if (progress > 0) - { - blit(xLeft, yo, 0, 69, progress, 5); - } - } + int yLine1, yLine2; + if (bTwoPlayerSplitscreen) { + // yo = iHeightOffset + screenHeight - 10 - iSafezoneYHalf - + // iTooltipsYOffset; + yLine1 = iHeightOffset + screenHeight - 18 - + iSafezoneYHalf - iTooltipsYOffset; + yLine2 = yLine1 - 10; + } else { + // yo = screenHeight - 10 - iSafezoneYHalf - + // iTooltipsYOffset; + yLine1 = + screenHeight - 18 - iSafezoneYHalf - iTooltipsYOffset; + yLine2 = yLine1 - 10; + } - int yLine1, yLine2; - if(bTwoPlayerSplitscreen) - { - //yo = iHeightOffset + screenHeight - 10 - iSafezoneYHalf - iTooltipsYOffset; - yLine1 = iHeightOffset + screenHeight - 18 - iSafezoneYHalf - iTooltipsYOffset; - yLine2 = yLine1 - 10; - } - else - { - //yo = screenHeight - 10 - iSafezoneYHalf - iTooltipsYOffset; - yLine1 = screenHeight - 18 - iSafezoneYHalf - iTooltipsYOffset; - yLine2 = yLine1 - 10; - } + int armor = minecraft->player->getArmorValue(); + int heartOffsetIndex = -1; + if (minecraft->player->hasEffect(MobEffect::regeneration)) { + heartOffsetIndex = tickCount % 25; + } - int armor = minecraft->player->getArmorValue(); - int heartOffsetIndex = -1; - if (minecraft->player->hasEffect(MobEffect::regeneration)) - { - heartOffsetIndex = tickCount % 25; - } + // render health and armor + for (int i = 0; i < Player::MAX_HEALTH / 2; i++) { + if (armor > 0) { + int xo = xLeft + i * 8; - // render health and armor - for (int i = 0; i < Player::MAX_HEALTH / 2; i++) - { - if (armor > 0) - { - int xo = xLeft + i * 8; + // HEALTH + if (i * 2 + 1 < armor) + blit(xo, yLine2, 16 + 2 * 9, 9 * 1, 9, 9); + if (i * 2 + 1 == armor) + blit(xo, yLine2, 16 + 1 * 9, 9 * 1, 9, 9); + if (i * 2 + 1 > armor) + blit(xo, yLine2, 16 + 0 * 9, 9 * 1, 9, 9); + } - // HEALTH - if (i * 2 + 1 < armor) blit(xo, yLine2, 16 + 2 * 9, 9 * 1, 9, 9); - if (i * 2 + 1 == armor) blit(xo, yLine2, 16 + 1 * 9, 9 * 1, 9, 9); - if (i * 2 + 1 > armor) blit(xo, yLine2, 16 + 0 * 9, 9 * 1, 9, 9); - } + int healthTexBaseX = 16; + if (minecraft->player->hasEffect(MobEffect::poison)) { + healthTexBaseX += 4 * 9; + } - int healthTexBaseX = 16; - if (minecraft->player->hasEffect(MobEffect::poison)) - { - healthTexBaseX += 4 * 9; - } + int bg = 0; + if (blink) bg = 1; + int xo = xLeft + i * 8; + int yo = yLine1; - int bg = 0; - if (blink) bg = 1; - int xo = xLeft + i * 8; - int yo = yLine1; - - if (iHealth <= 4) - { - yo += random->nextInt(2); - } - if (i == heartOffsetIndex) - { - yo -= 2; - } + if (iHealth <= 4) { + yo += random->nextInt(2); + } + if (i == heartOffsetIndex) { + yo -= 2; + } - int y0 = 0; - // 4J-PB - no hardcore in xbox -// if (minecraft.level.getLevelData().isHardcore()) { -// y0 = 5; -// } - blit(xo, yo, 16 + bg * 9, 9 * 0, 9, 9); - if (blink) - { - if (i * 2 + 1 < iLastHealth) blit(xo, yo, healthTexBaseX + 6 * 9, 9 * y0, 9, 9); - if (i * 2 + 1 == iLastHealth) blit(xo, yo, healthTexBaseX + 7 * 9, 9 * y0, 9, 9); - } - if (i * 2 + 1 < iHealth) blit(xo, yo, healthTexBaseX + 4 * 9, 9 * y0, 9, 9); - if (i * 2 + 1 == iHealth) blit(xo, yo, healthTexBaseX + 5 * 9, 9 * y0, 9, 9); - } + int y0 = 0; + // 4J-PB - no hardcore in xbox + // if + // (minecraft.level.getLevelData().isHardcore()) { y0 = 5; + // } + blit(xo, yo, 16 + bg * 9, 9 * 0, 9, 9); + if (blink) { + if (i * 2 + 1 < iLastHealth) + blit(xo, yo, healthTexBaseX + 6 * 9, 9 * y0, 9, 9); + if (i * 2 + 1 == iLastHealth) + blit(xo, yo, healthTexBaseX + 7 * 9, 9 * y0, 9, 9); + } + if (i * 2 + 1 < iHealth) + blit(xo, yo, healthTexBaseX + 4 * 9, 9 * y0, 9, 9); + if (i * 2 + 1 == iHealth) + blit(xo, yo, healthTexBaseX + 5 * 9, 9 * y0, 9, 9); + } - // render food - for (int i = 0; i < FoodConstants::MAX_FOOD / 2; i++) - { - int yo = yLine1; + // render food + for (int i = 0; i < FoodConstants::MAX_FOOD / 2; i++) { + int yo = yLine1; + int texBaseX = 16; + int bg = 0; + if (minecraft->player->hasEffect(MobEffect::hunger)) { + texBaseX += 4 * 9; + bg = 13; + } - int texBaseX = 16; - int bg = 0; - if (minecraft->player->hasEffect(MobEffect::hunger)) - { - texBaseX += 4 * 9; - bg = 13; - } + if (minecraft->player->getFoodData() + ->getSaturationLevel() <= 0) { + if ((tickCount % (food * 3 + 1)) == 0) { + yo += random->nextInt(3) - 1; + } + } - if (minecraft->player->getFoodData()->getSaturationLevel() <= 0) - { - if ((tickCount % (food * 3 + 1)) == 0) - { - yo += random->nextInt(3) - 1; - } - } + if (foodBlink) bg = 1; + int xo = xRight - i * 8 - 9; + blit(xo, yo, 16 + bg * 9, 9 * 3, 9, 9); + if (foodBlink) { + if (i * 2 + 1 < oldFood) + blit(xo, yo, texBaseX + 6 * 9, 9 * 3, 9, 9); + if (i * 2 + 1 == oldFood) + blit(xo, yo, texBaseX + 7 * 9, 9 * 3, 9, 9); + } + if (i * 2 + 1 < food) + blit(xo, yo, texBaseX + 4 * 9, 9 * 3, 9, 9); + if (i * 2 + 1 == food) + blit(xo, yo, texBaseX + 5 * 9, 9 * 3, 9, 9); + } - if (foodBlink) bg = 1; - int xo = xRight - i * 8 - 9; - blit(xo, yo, 16 + bg * 9, 9 * 3, 9, 9); - if (foodBlink) - { - if (i * 2 + 1 < oldFood) blit(xo, yo, texBaseX + 6 * 9, 9 * 3, 9, 9); - if (i * 2 + 1 == oldFood) blit(xo, yo, texBaseX + 7 * 9, 9 * 3, 9, 9); - } - if (i * 2 + 1 < food) blit(xo, yo, texBaseX + 4 * 9, 9 * 3, 9, 9); - if (i * 2 + 1 == food) blit(xo, yo, texBaseX + 5 * 9, 9 * 3, 9, 9); - } + // render air bubbles + if (minecraft->player->isUnderLiquid(Material::water)) { + int count = + (int)ceil((minecraft->player->getAirSupply() - 2) * + 10.0f / Player::TOTAL_AIR_SUPPLY); + int extra = (int)ceil((minecraft->player->getAirSupply()) * + 10.0f / Player::TOTAL_AIR_SUPPLY) - + count; + for (int i = 0; i < count + extra; i++) { + // Air bubbles + if (i < count) + blit(xRight - i * 8 - 9, yLine2, 16, 9 * 2, 9, 9); + else + blit(xRight - i * 8 - 9, yLine2, 16 + 9, 9 * 2, 9, + 9); + } + } + } + } - // render air bubbles - if (minecraft->player->isUnderLiquid(Material::water)) - { - int count = (int) ceil((minecraft->player->getAirSupply() - 2) * 10.0f / Player::TOTAL_AIR_SUPPLY); - int extra = (int) ceil((minecraft->player->getAirSupply()) * 10.0f / Player::TOTAL_AIR_SUPPLY) - count; - for (int i = 0; i < count + extra; i++) - { - // Air bubbles - if (i < count) blit(xRight - i * 8 - 9, yLine2, 16, 9 * 2, 9, 9); - else blit(xRight - i * 8 - 9, yLine2, 16 + 9, 9 * 2, 9, 9); - } - } - } + // 4J-PB - turn off the slot display if a xui menu is up - } + //////////////////////////// + // render the slot contents + //////////////////////////// + if (bDisplayGui) { + // glDisable(GL_BLEND); 4J - removed - we want + //to be able to fade our gui - // 4J-PB - turn off the slot display if a xui menu is up + glEnable(GL_RESCALE_NORMAL); - //////////////////////////// - // render the slot contents - //////////////////////////// - if(bDisplayGui) - { - // glDisable(GL_BLEND); 4J - removed - we want to be able to fade our gui + Lighting::turnOnGui(); - glEnable(GL_RESCALE_NORMAL); + int x, y; - Lighting::turnOnGui(); - + for (int i = 0; i < 9; i++) { + if (bTwoPlayerSplitscreen) { + x = iWidthOffset + screenWidth / 2 - 9 * 10 + i * 20 + 2; + y = iHeightOffset + screenHeight - iSafezoneYHalf - + iTooltipsYOffset - 16 - 3 + 22; + } else { + x = screenWidth / 2 - 9 * 10 + i * 20 + 2; + y = screenHeight - iSafezoneYHalf - iTooltipsYOffset - 16 - + 3 + 22; + } + this->renderSlot(i, x, y, a); + } + Lighting::turnOff(); + glDisable(GL_RESCALE_NORMAL); + } +#endif // RENDER_HUD - int x,y; + // 4J - do render of crouched player. This code is largely taken from + // the inventory render of the player, with some special hard-coded + // positions worked out by hand from the xui implementation of the + // crouch icon - for (int i = 0; i < 9; i++) - { - if(bTwoPlayerSplitscreen) - { - x = iWidthOffset + screenWidth / 2 - 9 * 10 + i * 20 + 2; - y = iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 16 - 3 + 22; - } - else - { - x = screenWidth / 2 - 9 * 10 + i * 20 + 2; - y = screenHeight - iSafezoneYHalf - iTooltipsYOffset - 16 - 3 + 22; - } - this->renderSlot(i, x, y, a); - } - Lighting::turnOff(); - glDisable(GL_RESCALE_NORMAL); - } -#endif // RENDER_HUD + if (app.GetGameSettings(iPad, eGameSetting_AnimatedCharacter)) { + // int playerIdx = minecraft->player->GetXboxPad(); - // 4J - do render of crouched player. This code is largely taken from the inventory render of the player, with some special hard-coded positions - // worked out by hand from the xui implementation of the crouch icon + static int characterDisplayTimer[4] = {0}; + if (!bDisplayGui) { + characterDisplayTimer[iPad] = 0; + } else if (minecraft->player->isSneaking()) { + characterDisplayTimer[iPad] = 30; + } else if (minecraft->player->isSprinting()) { + characterDisplayTimer[iPad] = 30; + } else if (minecraft->player->abilities.flying) { + characterDisplayTimer[iPad] = + 5; // quickly get rid of the player display if they stop + // flying + } else if (characterDisplayTimer[iPad] > 0) { + --characterDisplayTimer[iPad]; + } + bool displayCrouch = minecraft->player->isSneaking() || + (characterDisplayTimer[iPad] > 0); + bool displaySprint = minecraft->player->isSprinting() || + (characterDisplayTimer[iPad] > 0); + bool displayFlying = minecraft->player->abilities.flying || + (characterDisplayTimer[iPad] > 0); - if(app.GetGameSettings(iPad,eGameSetting_AnimatedCharacter)) - { - //int playerIdx = minecraft->player->GetXboxPad(); + if (bDisplayGui && + (displayCrouch || displaySprint || displayFlying)) { + EntityRenderDispatcher::instance->prepare( + minecraft->level, minecraft->textures, minecraft->font, + minecraft->cameraTargetPlayer, minecraft->options, a); + glEnable(GL_RESCALE_NORMAL); + glEnable(GL_COLOR_MATERIAL); - static int characterDisplayTimer[4] = {0}; - if( !bDisplayGui ) - { - characterDisplayTimer[iPad] = 0; - } - else if( minecraft->player->isSneaking() ) - { - characterDisplayTimer[iPad] = 30; - } - else if( minecraft->player->isSprinting() ) - { - characterDisplayTimer[iPad] = 30; - } - else if( minecraft->player->abilities.flying) - { - characterDisplayTimer[iPad] = 5; // quickly get rid of the player display if they stop flying - } - else if( characterDisplayTimer[iPad] > 0 ) - { - --characterDisplayTimer[iPad]; - } - bool displayCrouch = minecraft->player->isSneaking() || ( characterDisplayTimer[iPad] > 0 ); - bool displaySprint = minecraft->player->isSprinting() || ( characterDisplayTimer[iPad] > 0 ); - bool displayFlying = minecraft->player->abilities.flying || ( characterDisplayTimer[iPad] > 0 ); + int xo = 0; + int yo = 0; + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + default: + if (RenderManager.IsHiDef()) xo = -22; + yo = -36; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + xo = 0; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + xo = 0; + yo = -48; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: + xo = 0; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: + xo = -43; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: + xo = 0; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: + xo = -43; + yo = -25; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: + xo = 0; + yo = -48; + break; + case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: + xo = -43; + yo = -48; + break; + } + glPushMatrix(); + glTranslatef((float)xo + 51, (float)yo + 75, 50); + float ss = 12; + glScalef(-ss, ss, ss); + glRotatef(180, 0, 0, 1); - if( bDisplayGui && (displayCrouch || displaySprint || displayFlying) ) - { - EntityRenderDispatcher::instance->prepare(minecraft->level, minecraft->textures, minecraft->font, minecraft->cameraTargetPlayer, minecraft->options, a); - glEnable(GL_RESCALE_NORMAL); - glEnable(GL_COLOR_MATERIAL); + float oyr = minecraft->player->yRot; + float oyrO = minecraft->player->yRotO; + float oxr = minecraft->player->xRot; + int ofire = minecraft->player->onFire; + bool ofireflag = + minecraft->player->getSharedFlag(Entity::FLAG_ONFIRE); - int xo = 0; - int yo = 0; - switch( minecraft->player->m_iScreenSection ) - { - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - default: - if(RenderManager.IsHiDef()) xo = -22; - yo = -36; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - xo = 0; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - xo = 0; yo = -48; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: - xo = 0; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - xo = -43; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: - xo = 0; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - xo = -43; yo = -25; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT: - xo = 0; yo = -48; - break; - case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - xo = -43; yo = -48; - break; - } - glPushMatrix(); - glTranslatef((float)xo + 51, (float)yo + 75, 50); - float ss = 12; - glScalef(-ss, ss, ss); - glRotatef(180, 0, 0, 1); + float xd = -40; + float yd = 10; - float oyr = minecraft->player->yRot; - float oyrO = minecraft->player->yRotO; - float oxr = minecraft->player->xRot; - int ofire = minecraft->player->onFire; - bool ofireflag = minecraft->player->getSharedFlag(Entity::FLAG_ONFIRE); + // 4J Stu - This is all based on the inventory player renderer, + // with changes to ensure that capes render correctly by + // minimising the changes to member variables of the player + // which are all related - float xd = -40; - float yd = 10; + glRotatef(45 + 90, 0, 1, 0); + Lighting::turnOn(); + glRotatef(-45 - 90, 0, 1, 0); - // 4J Stu - This is all based on the inventory player renderer, with changes to ensure that capes render correctly - // by minimising the changes to member variables of the player which are all related + glRotatef(-(float)atan(yd / 40.0f) * 20, 1, 0, 0); + float bodyRot = (minecraft->player->yBodyRotO + + (minecraft->player->yBodyRot - + minecraft->player->yBodyRotO)); + // Fixed rotation angle of degrees, adjusted by bodyRot to + // negate the rotation that occurs in the renderer bodyRot in + // the rotation below is a simplification of "180 - (180 - + // bodyRot)" where the first 180 is + // EntityRenderDispatcher::instance->playerRotY that we set + // below and (180 - bodyRot) is the angle of rotation that is + // performed within the mob renderer + glRotatef(bodyRot - ((float)atan(xd / 40.0f) * 20), 0, 1, 0); + glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - glRotatef(45 + 90, 0, 1, 0); - Lighting::turnOn(); - glRotatef(-45 - 90, 0, 1, 0); + // Set head rotation to body rotation to make head static + minecraft->player->yRot = bodyRot; + minecraft->player->yRotO = minecraft->player->yRot; + minecraft->player->xRot = -(float)atan(yd / 40.0f) * 20; - glRotatef(-(float) atan(yd / 40.0f ) * 20, 1, 0, 0); - float bodyRot = (minecraft->player->yBodyRotO + (minecraft->player->yBodyRot - minecraft->player->yBodyRotO)); - // Fixed rotation angle of degrees, adjusted by bodyRot to negate the rotation that occurs in the renderer - // bodyRot in the rotation below is a simplification of "180 - (180 - bodyRot)" where the first 180 is EntityRenderDispatcher::instance->playerRotY that we set below - // and (180 - bodyRot) is the angle of rotation that is performed within the mob renderer - glRotatef( bodyRot - ( (float) atan(xd / 40.0f) * 20), 0, 1, 0); - glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + minecraft->player->onFire = 0; + minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, false); - // Set head rotation to body rotation to make head static - minecraft->player->yRot = bodyRot; - minecraft->player->yRotO = minecraft->player->yRot; - minecraft->player->xRot = -(float) atan(yd / 40.0f) * 20; + glTranslatef(0, minecraft->player->heightOffset, 0); + EntityRenderDispatcher::instance->playerRotY = 180; + EntityRenderDispatcher::instance->isGuiRender = true; + EntityRenderDispatcher::instance->render(minecraft->player, 0, + 0, 0, 0, 1); + EntityRenderDispatcher::instance->isGuiRender = false; - minecraft->player->onFire = 0; - minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, false); - - glTranslatef(0, minecraft->player->heightOffset, 0); - EntityRenderDispatcher::instance->playerRotY = 180; - EntityRenderDispatcher::instance->isGuiRender = true; - EntityRenderDispatcher::instance->render(minecraft->player, 0, 0, 0, 0, 1); - EntityRenderDispatcher::instance->isGuiRender = false; - - minecraft->player->yRot = oyr; - minecraft->player->yRotO = oyrO; - minecraft->player->xRot = oxr; - minecraft->player->onFire = ofire; - minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE,ofireflag); - glPopMatrix(); - Lighting::turnOff(); - glDisable(GL_RESCALE_NORMAL); - } - } - } + minecraft->player->yRot = oyr; + minecraft->player->yRotO = oyrO; + minecraft->player->xRot = oxr; + minecraft->player->onFire = ofire; + minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, + ofireflag); + glPopMatrix(); + Lighting::turnOff(); + glDisable(GL_RESCALE_NORMAL); + } + } + } #if RENDER_HUD - // Moved so the opacity blend is applied to it - if (bDisplayGui && minecraft->gameMode->hasExperience() && minecraft->player->experienceLevel > 0) - { - if (true) - { - bool blink = false; - int col = blink ? 0xffffff : 0x80ff20; - wchar_t formatted[10]; - swprintf(formatted, 10, L"%d",minecraft->player->experienceLevel); + // Moved so the opacity blend is applied to it + if (bDisplayGui && minecraft->gameMode->hasExperience() && + minecraft->player->experienceLevel > 0) { + if (true) { + bool blink = false; + int col = blink ? 0xffffff : 0x80ff20; + wchar_t formatted[10]; + swprintf(formatted, 10, L"%d", minecraft->player->experienceLevel); - std::wstring str = formatted; - int x = iWidthOffset + (screenWidth - font->width(str)) / 2; - int y = screenHeight - iSafezoneYHalf - iTooltipsYOffset; - // If we're in creative mode, we don't need to offset the XP display so much - if (minecraft->gameMode->canHurtPlayer()) - { - y-=18; - } - else - { - y-=13; - } - - if(bTwoPlayerSplitscreen) - { - y+=iHeightOffset; - } - //int y = screenHeight - 31 - 4; - font->draw(str, x + 1, y, 0x000000); - font->draw(str, x - 1, y, 0x000000); - font->draw(str, x, y + 1, 0x000000); - font->draw(str, x, y - 1, 0x000000); - // font->draw(str, x + 1, y + 1, 0x000000); - // font->draw(str, x - 1, y + 1, 0x000000); - // font->draw(str, x + 1, y - 1, 0x000000); - // font->draw(str, x - 1, y - 1, 0x000000); - font->draw(str, x, y, col); - } - } -#endif // RENDER_HUD + std::wstring str = formatted; + int x = iWidthOffset + (screenWidth - font->width(str)) / 2; + int y = screenHeight - iSafezoneYHalf - iTooltipsYOffset; + // If we're in creative mode, we don't need to offset the XP display + // so much + if (minecraft->gameMode->canHurtPlayer()) { + y -= 18; + } else { + y -= 13; + } - // 4J - added to disable blends, which we have enabled previously to allow gui fading - glDisable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + if (bTwoPlayerSplitscreen) { + y += iHeightOffset; + } + // int y = screenHeight - 31 - 4; + font->draw(str, x + 1, y, 0x000000); + font->draw(str, x - 1, y, 0x000000); + font->draw(str, x, y + 1, 0x000000); + font->draw(str, x, y - 1, 0x000000); + // font->draw(str, x + 1, y + 1, 0x000000); + // font->draw(str, x - 1, y + 1, 0x000000); + // font->draw(str, x + 1, y - 1, 0x000000); + // font->draw(str, x - 1, y - 1, 0x000000); + font->draw(str, x, y, col); + } + } +#endif // RENDER_HUD + + // 4J - added to disable blends, which we have enabled previously to allow + // gui fading + glDisable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // if the player is falling asleep we render a dark overlay - if (minecraft->player->getSleepTimer() > 0) - { + if (minecraft->player->getSleepTimer() > 0) { glDisable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); int timer = minecraft->player->getSleepTimer(); - float amount = (float) timer / (float) Player::SLEEP_DURATION; - if (amount > 1) - { + float amount = (float)timer / (float)Player::SLEEP_DURATION; + if (amount > 1) { // waking up - amount = 1.0f - ((float) (timer - Player::SLEEP_DURATION) / (float) Player::WAKE_UP_DURATION); + amount = 1.0f - ((float)(timer - Player::SLEEP_DURATION) / + (float)Player::WAKE_UP_DURATION); } - int color = (int) (220.0f * amount) << 24 | (0x101020); - fill(0, 0, screenWidth/fScaleFactorWidth, screenHeight/fScaleFactorHeight, color); + int color = (int)(220.0f * amount) << 24 | (0x101020); + fill(0, 0, screenWidth / fScaleFactorWidth, + screenHeight / fScaleFactorHeight, color); glEnable(GL_ALPHA_TEST); glEnable(GL_DEPTH_TEST); } - // 4J-PB - Request from Mojang to have a red death screen - if (!minecraft->player->isAlive()) - { - glDisable(GL_DEPTH_TEST); - glDisable(GL_ALPHA_TEST); - int timer = minecraft->player->getDeathFadeTimer(); - float amount = (float) timer / (float) Player::DEATHFADE_DURATION; + // 4J-PB - Request from Mojang to have a red death screen + if (!minecraft->player->isAlive()) { + glDisable(GL_DEPTH_TEST); + glDisable(GL_ALPHA_TEST); + int timer = minecraft->player->getDeathFadeTimer(); + float amount = (float)timer / (float)Player::DEATHFADE_DURATION; - int color = (int) (220.0f * amount) << 24 | (0x200000); - fill(0, 0, screenWidth/fScaleFactorWidth, screenHeight/fScaleFactorHeight, color); - glEnable(GL_ALPHA_TEST); - glEnable(GL_DEPTH_TEST); + int color = (int)(220.0f * amount) << 24 | (0x200000); + fill(0, 0, screenWidth / fScaleFactorWidth, + screenHeight / fScaleFactorHeight, color); + glEnable(GL_ALPHA_TEST); + glEnable(GL_DEPTH_TEST); + } - } - - - // { - // String str = "" + minecraft.player.getFoodData().getExhaustionLevel() + ", " + minecraft.player.getFoodData().getSaturationLevel(); - // int x = (screenWidth - font.width(str)) / 2; - // int y = screenHeight - 64; - // font.draw(str, x + 1, y, 0xffffff); - // } + // { + // String str = "" + + // minecraft.player.getFoodData().getExhaustionLevel() + ", " + + // minecraft.player.getFoodData().getSaturationLevel(); int x = + // (screenWidth - font.width(str)) / 2; int y = screenHeight - + // 64; font.draw(str, x + 1, y, 0xffffff); + // } #ifndef _FINAL_BUILD - MemSect(31); - if (minecraft->options->renderDebug) - { + MemSect(31); + if (minecraft->options->renderDebug) { glPushMatrix(); if (Minecraft::warezTime > 0) glTranslatef(0, 32, 0); - font->drawShadow(ClientConstants::VERSION_STRING + L" (" + minecraft->fpsString + L")", iSafezoneXHalf+2, 20, 0xffffff); - font->drawShadow(L"Seed: " + _toString<__int64>(minecraft->level->getLevelData()->getSeed() ), iSafezoneXHalf+2, 32 + 00, 0xffffff); - font->drawShadow(minecraft->gatherStats1(), iSafezoneXHalf+2, 32 + 10, 0xffffff); - font->drawShadow(minecraft->gatherStats2(), iSafezoneXHalf+2, 32 + 20, 0xffffff); - font->drawShadow(minecraft->gatherStats3(), iSafezoneXHalf+2, 32 + 30, 0xffffff); - font->drawShadow(minecraft->gatherStats4(), iSafezoneXHalf+2, 32 + 40, 0xffffff); + font->drawShadow(ClientConstants::VERSION_STRING + L" (" + + minecraft->fpsString + L")", + iSafezoneXHalf + 2, 20, 0xffffff); + font->drawShadow( + L"Seed: " + + _toString<__int64>(minecraft->level->getLevelData()->getSeed()), + iSafezoneXHalf + 2, 32 + 00, 0xffffff); + font->drawShadow(minecraft->gatherStats1(), iSafezoneXHalf + 2, 32 + 10, + 0xffffff); + font->drawShadow(minecraft->gatherStats2(), iSafezoneXHalf + 2, 32 + 20, + 0xffffff); + font->drawShadow(minecraft->gatherStats3(), iSafezoneXHalf + 2, 32 + 30, + 0xffffff); + font->drawShadow(minecraft->gatherStats4(), iSafezoneXHalf + 2, 32 + 40, + 0xffffff); - // TERRAIN FEATURES - int iYPos=82; + // TERRAIN FEATURES + int iYPos = 82; - if(minecraft->level->dimension->id==0) - { - std::wstring wfeature[eTerrainFeature_Count]; + if (minecraft->level->dimension->id == 0) { + std::wstring wfeature[eTerrainFeature_Count]; - wfeature[eTerrainFeature_Stronghold] = L"Stronghold: "; - wfeature[eTerrainFeature_Mineshaft] = L"Mineshaft: "; - wfeature[eTerrainFeature_Village] = L"Village: "; - wfeature[eTerrainFeature_Ravine] = L"Ravine: "; + wfeature[eTerrainFeature_Stronghold] = L"Stronghold: "; + wfeature[eTerrainFeature_Mineshaft] = L"Mineshaft: "; + wfeature[eTerrainFeature_Village] = L"Village: "; + wfeature[eTerrainFeature_Ravine] = L"Ravine: "; - for(int i=0;i( pFeatureData->x*16 ) + L", " + _toString( pFeatureData->z*16 ) + L"] "; - wfeature[pFeatureData->eTerrainFeature] += itemInfo; - } + std::wstring itemInfo = + L"[" + _toString(pFeatureData->x * 16) + L", " + + _toString(pFeatureData->z * 16) + L"] "; + wfeature[pFeatureData->eTerrainFeature] += itemInfo; + } - for( int i = eTerrainFeature_Stronghold; i < (int) eTerrainFeature_Count; i++ ) - { - font->drawShadow(wfeature[i], iSafezoneXHalf + 2, iYPos, 0xffffff); - iYPos+=10; - } - } - - //font->drawShadow(minecraft->gatherStats5(), iSafezoneXHalf+2, 32 + 10, 0xffffff); - { - /* 4J - removed - long max = Runtime.getRuntime().maxMemory(); - long total = Runtime.getRuntime().totalMemory(); - long free = Runtime.getRuntime().freeMemory(); - long used = total - free; - String msg = "Used memory: " + (used * 100 / max) + "% (" + (used / 1024 / 1024) + "MB) of " + (max / 1024 / 1024) + "MB"; - drawString(font, msg, screenWidth - font.width(msg) - 2, 2, 0xe0e0e0); - msg = "Allocated memory: " + (total * 100 / max) + "% (" + (total / 1024 / 1024) + "MB)"; - drawString(font, msg, screenWidth - font.width(msg) - 2, 12, 0xe0e0e0); - */ + for (int i = eTerrainFeature_Stronghold; + i < (int)eTerrainFeature_Count; i++) { + font->drawShadow(wfeature[i], iSafezoneXHalf + 2, iYPos, + 0xffffff); + iYPos += 10; + } } - // 4J Stu - Moved these so that they don't overlap - double xBlockPos = floor(minecraft->player->x); - double yBlockPos = floor(minecraft->player->y); - double zBlockPos = floor(minecraft->player->z); - drawString(font, L"x: " + _toString(minecraft->player->x) + L"/ Head: " + _toString(xBlockPos) + L"/ Chunk: " + _toString(minecraft->player->xChunk), iSafezoneXHalf+2, iYPos + 8 * 0, 0xe0e0e0); - drawString(font, L"y: " + _toString(minecraft->player->y) + L"/ Head: " + _toString(yBlockPos), iSafezoneXHalf+2, iYPos + 8 * 1, 0xe0e0e0); - drawString(font, L"z: " + _toString(minecraft->player->z) + L"/ Head: " + _toString(zBlockPos) + L"/ Chunk: " + _toString(minecraft->player->zChunk), iSafezoneXHalf+2, iYPos + 8 * 2, 0xe0e0e0); - drawString(font, L"f: " + _toString(Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & 0x3) + L"/ yRot: " + _toString(minecraft->player->yRot), iSafezoneXHalf+2, iYPos + 8 * 3, 0xe0e0e0); - iYPos += 8*4; - int px = Mth::floor(minecraft->player->x); - int py = Mth::floor(minecraft->player->y); - int pz = Mth::floor(minecraft->player->z); - if (minecraft->level != NULL && minecraft->level->hasChunkAt(px, py, pz)) - { - LevelChunk *chunkAt = minecraft->level->getChunkAt(px, pz); - Biome *biome = chunkAt->getBiome(px & 15, pz & 15, minecraft->level->getBiomeSource()); - drawString( - font, - L"b: " + biome->m_name + L" (" + _toString(biome->id) + L")", iSafezoneXHalf+2, iYPos, 0xe0e0e0); - } + // font->drawShadow(minecraft->gatherStats5(), iSafezoneXHalf+2, 32 + + // 10, 0xffffff); + { + /* 4J - removed +long max = Runtime.getRuntime().maxMemory(); +long total = Runtime.getRuntime().totalMemory(); +long free = Runtime.getRuntime().freeMemory(); +long used = total - free; +String msg = "Used memory: " + (used * 100 / max) + "% (" + (used / 1024 / 1024) ++ "MB) of " + (max / 1024 / 1024) + "MB"; drawString(font, msg, screenWidth - +font.width(msg) - 2, 2, 0xe0e0e0); msg = "Allocated memory: " + (total * 100 / +max) + "% (" + (total / 1024 / 1024) + "MB)"; drawString(font, msg, screenWidth +- font.width(msg) - 2, 12, 0xe0e0e0); + */ + } + // 4J Stu - Moved these so that they don't overlap + double xBlockPos = floor(minecraft->player->x); + double yBlockPos = floor(minecraft->player->y); + double zBlockPos = floor(minecraft->player->z); + drawString(font, + L"x: " + _toString(minecraft->player->x) + + L"/ Head: " + _toString(xBlockPos) + + L"/ Chunk: " + + _toString(minecraft->player->xChunk), + iSafezoneXHalf + 2, iYPos + 8 * 0, 0xe0e0e0); + drawString(font, + L"y: " + _toString(minecraft->player->y) + + L"/ Head: " + _toString(yBlockPos), + iSafezoneXHalf + 2, iYPos + 8 * 1, 0xe0e0e0); + drawString(font, + L"z: " + _toString(minecraft->player->z) + + L"/ Head: " + _toString(zBlockPos) + + L"/ Chunk: " + + _toString(minecraft->player->zChunk), + iSafezoneXHalf + 2, iYPos + 8 * 2, 0xe0e0e0); + drawString( + font, + L"f: " + + _toString( + Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & + 0x3) + + L"/ yRot: " + _toString(minecraft->player->yRot), + iSafezoneXHalf + 2, iYPos + 8 * 3, 0xe0e0e0); + iYPos += 8 * 4; + + int px = Mth::floor(minecraft->player->x); + int py = Mth::floor(minecraft->player->y); + int pz = Mth::floor(minecraft->player->z); + if (minecraft->level != NULL && + minecraft->level->hasChunkAt(px, py, pz)) { + LevelChunk* chunkAt = minecraft->level->getChunkAt(px, pz); + Biome* biome = chunkAt->getBiome( + px & 15, pz & 15, minecraft->level->getBiomeSource()); + drawString(font, + L"b: " + biome->m_name + L" (" + + _toString(biome->id) + L")", + iSafezoneXHalf + 2, iYPos, 0xe0e0e0); + } glPopMatrix(); } - MemSect(0); + MemSect(0); #endif - lastTickA = a; - // 4J Stu - This is now displayed in a xui scene + lastTickA = a; + // 4J Stu - This is now displayed in a xui scene #if 0 // Jukebox CD message if (overlayMessageTime > 0) @@ -894,11 +974,10 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) } } #endif - + unsigned int max = 10; bool isChatting = false; - if (dynamic_cast(minecraft->screen) != NULL) - { + if (dynamic_cast(minecraft->screen) != NULL) { max = 20; isChatting = true; } @@ -954,7 +1033,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) glPopMatrix(); #endif - // 4J Stu - Copied over but not used + // 4J Stu - Copied over but not used #if 0 if (minecraft.player instanceof MultiplayerLocalPlayer && minecraft.options.keyPlayerList.isDown) { @@ -1012,79 +1091,77 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) } #endif - if(bDisplayGui && bTwoPlayerSplitscreen) - { - // pop the scaled matrix - glPopMatrix(); - } + if (bDisplayGui && bTwoPlayerSplitscreen) { + // pop the scaled matrix + glPopMatrix(); + } - glColor4f(1, 1, 1, 1); + glColor4f(1, 1, 1, 1); glDisable(GL_BLEND); - glEnable(GL_ALPHA_TEST); + glEnable(GL_ALPHA_TEST); } // Moved to the xui base scene // void Gui::renderBossHealth(void) // { // if (EnderDragonRenderer::bossInstance == NULL) return; -// +// // std::shared_ptr boss = EnderDragonRenderer::bossInstance; // EnderDragonRenderer::bossInstance = NULL; -// +// // Minecraft *pMinecraft=Minecraft::GetInstance(); -// +// // Font *font = pMinecraft->font; -// -// ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); -// int screenWidth = ssc.getWidth(); -// +// +// ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, +// pMinecraft->height_phys); int screenWidth = ssc.getWidth(); +// // int w = 182; // int xLeft = screenWidth / 2 - w / 2; -// -// int progress = (int) (boss->getSynchedHealth() / (float) boss->getMaxHealth() * (float) (w + 1)); -// +// +// int progress = (int) (boss->getSynchedHealth() / (float) +// boss->getMaxHealth() * (float) (w + 1)); +// // int yo = 12; // blit(xLeft, yo, 0, 74, w, 5); // blit(xLeft, yo, 0, 74, w, 5); -// if (progress > 0) +// if (progress > 0) // { // blit(xLeft, yo, 0, 79, progress, 5); // } -// +// // std::wstring msg = L"Boss health - NON LOCALISED"; -// font->drawShadow(msg, screenWidth / 2 - font->width(msg) / 2, yo - 10, 0xff00ff); -// glColor4f(1, 1, 1, 1); -// glBindTexture(GL_TEXTURE_2D, pMinecraft->textures->loadTexture(TN_GUI_ICONS) );//"/gui/icons.png")); -// +// font->drawShadow(msg, screenWidth / 2 - font->width(msg) / 2, yo - 10, +// 0xff00ff); glColor4f(1, 1, 1, 1); glBindTexture(GL_TEXTURE_2D, +// pMinecraft->textures->loadTexture(TN_GUI_ICONS) );//"/gui/icons.png")); +// // } -void Gui::renderPumpkin(int w, int h) -{ +void Gui::renderPumpkin(int w, int h) { glDisable(GL_DEPTH_TEST); glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, 1); glDisable(GL_ALPHA_TEST); - MemSect(31); - minecraft->textures->bindTexture(TN__BLUR__MISC_PUMPKINBLUR);//L"%blur%/misc/pumpkinblur.png")); - MemSect(0); - Tesselator *t = Tesselator::getInstance(); + MemSect(31); + minecraft->textures->bindTexture( + TN__BLUR__MISC_PUMPKINBLUR); // L"%blur%/misc/pumpkinblur.png")); + MemSect(0); + Tesselator* t = Tesselator::getInstance(); t->begin(); - t->vertexUV((float)(0), (float)( h), (float)( -90), (float)( 0), (float)( 1)); - t->vertexUV((float)(w), (float)( h), (float)( -90), (float)( 1), (float)( 1)); - t->vertexUV((float)(w), (float)( 0), (float)( -90), (float)( 1), (float)( 0)); - t->vertexUV((float)(0), (float)( 0), (float)( -90), (float)( 0), (float)( 0)); + t->vertexUV((float)(0), (float)(h), (float)(-90), (float)(0), (float)(1)); + t->vertexUV((float)(w), (float)(h), (float)(-90), (float)(1), (float)(1)); + t->vertexUV((float)(w), (float)(0), (float)(-90), (float)(1), (float)(0)); + t->vertexUV((float)(0), (float)(0), (float)(-90), (float)(0), (float)(0)); t->end(); glDepthMask(true); glEnable(GL_DEPTH_TEST); glEnable(GL_ALPHA_TEST); glColor4f(1, 1, 1, 1); - } - -void Gui::renderVignette(float br, int w, int h) -{ + +void Gui::renderVignette(float br, int w, int h) { br = 1 - br; if (br < 0) br = 0; if (br > 1) br = 1; @@ -1110,10 +1187,8 @@ void Gui::renderVignette(float br, int w, int h) #endif } -void Gui::renderTp(float br, int w, int h) -{ - if (br < 1) - { +void Gui::renderTp(float br, int w, int h) { + if (br < 1) { br = br * br; br = br * br; br = br * 0.8f + 0.2f; @@ -1124,401 +1199,368 @@ void Gui::renderTp(float br, int w, int h) glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, br); - MemSect(31); - minecraft->textures->bindTexture(TN_TERRAIN);//L"/terrain.png")); - MemSect(0); - - Icon *slot = Tile::portalTile->getTexture(Facing::UP); + MemSect(31); + minecraft->textures->bindTexture(TN_TERRAIN); // L"/terrain.png")); + MemSect(0); + + Icon* slot = Tile::portalTile->getTexture(Facing::UP); float u0 = slot->getU0(); float v0 = slot->getV0(); float u1 = slot->getU1(); float v1 = slot->getV1(); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); - t->vertexUV((float)(0), (float)( h), (float)( -90), (float)( u0), (float)( v1)); - t->vertexUV((float)(w), (float)( h), (float)( -90), (float)( u1), (float)( v1)); - t->vertexUV((float)(w), (float)( 0), (float)( -90), (float)( u1), (float)( v0)); - t->vertexUV((float)(0), (float)( 0), (float)( -90), (float)( u0), (float)( v0)); + t->vertexUV((float)(0), (float)(h), (float)(-90), (float)(u0), (float)(v1)); + t->vertexUV((float)(w), (float)(h), (float)(-90), (float)(u1), (float)(v1)); + t->vertexUV((float)(w), (float)(0), (float)(-90), (float)(u1), (float)(v0)); + t->vertexUV((float)(0), (float)(0), (float)(-90), (float)(u0), (float)(v0)); t->end(); glDepthMask(true); glEnable(GL_DEPTH_TEST); glEnable(GL_ALPHA_TEST); glColor4f(1, 1, 1, 1); - } -void Gui::renderSlot(int slot, int x, int y, float a) -{ - std::shared_ptr item = minecraft->player->inventory->items[slot]; +void Gui::renderSlot(int slot, int x, int y, float a) { + std::shared_ptr item = + minecraft->player->inventory->items[slot]; if (item == NULL) return; float pop = item->popTime - a; - if (pop > 0) - { + if (pop > 0) { glPushMatrix(); - float squeeze = 1 + pop / (float) Inventory::POP_TIME_DURATION; + float squeeze = 1 + pop / (float)Inventory::POP_TIME_DURATION; glTranslatef((float)(x + 8), (float)(y + 12), 0); glScalef(1 / squeeze, (squeeze + 1) / 2, 1); glTranslatef((float)-(x + 8), (float)-(y + 12), 0); } - itemRenderer->renderAndDecorateItem(minecraft->font, minecraft->textures, item, x, y); + itemRenderer->renderAndDecorateItem(minecraft->font, minecraft->textures, + item, x, y); - if (pop > 0) - { + if (pop > 0) { glPopMatrix(); } - itemRenderer->renderGuiItemDecorations(minecraft->font, minecraft->textures, item, x, y); - + itemRenderer->renderGuiItemDecorations(minecraft->font, minecraft->textures, + item, x, y); } -void Gui::tick() -{ +void Gui::tick() { if (overlayMessageTime > 0) overlayMessageTime--; tickCount++; - for(int iPad=0;iPadlocalplayers[i]) - { - guiMessages[i].clear(); - } - } - } - else - { - guiMessages[iPad].clear(); - } -} - - -void Gui::addMessage(const std::wstring& _string,int iPad,bool bIsDeathMessage) -{ - std::wstring string = _string; // 4J - Take copy of input as it is const - //int iScale=1; - - //if((minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_TOP) || - // (minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM)) - //{ - // iScale=2; - //} - - // while (minecraft->font->width(string) > (m_iMaxMessageWidth*iScale)) - //{ - // unsigned int i = 1; - // while (i < string.length() && minecraft->font->width(string.substr(0, i + 1)) <= (m_iMaxMessageWidth*iScale)) - // { - // i++; - // } - // int iLast=string.find_last_of(L" ",i); - - // // if a space was found, include the space on this line - // if(iLast!=i) - // { - // iLast++; - // } - // addMessage(string.substr(0, iLast), iPad); - // string = string.substr(iLast); - // } - - int maximumChars; - - switch(minecraft->player->m_iScreenSection) - { - case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: - case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - if(RenderManager.IsHiDef()) - { - maximumChars = 105; - } - else - { - maximumChars = 55; - } -#ifdef __PSVITA__ - maximumChars = 90; -#endif - switch(XGetLanguage()) - { - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - case XC_LANGUAGE_KOREAN: - if(RenderManager.IsHiDef()) - { - maximumChars = 70; - } - else - { - maximumChars = 35; - } -#ifdef __PSVITA__ - maximumChars = 55; -#endif - break; - } - break; - default: - maximumChars = 55; - switch(XGetLanguage()) - { - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - case XC_LANGUAGE_KOREAN: - maximumChars = 35; - break; - } - break; - } - - - while (string.length() > maximumChars) - { - unsigned int i = 1; - while (i < string.length() && (i + 1) <= maximumChars) - { - i++; + for (int iPad = 0; iPad < XUSER_MAX_COUNT; iPad++) { + // 4J Stu - Fix for #10929 - MP LAB: Network Disconnects: Host does not + // receive an error message stating the client left the game when + // viewing the Pause Menu. We don't show the guiMessages when a menu is + // up, so don't fade them out + if (!ui.GetMenuDisplayed(iPad)) { + AUTO_VAR(itEnd, guiMessages[iPad].end()); + for (AUTO_VAR(it, guiMessages[iPad].begin()); it != itEnd; it++) { + (*it).ticks++; + } } - int iLast=(int)string.find_last_of(L" ",i); - switch(XGetLanguage()) - { - case XC_LANGUAGE_JAPANESE: - case XC_LANGUAGE_TCHINESE: - case XC_LANGUAGE_KOREAN: - iLast = maximumChars; - break; - default: - iLast=(int)string.find_last_of(L" ",i); - break; - } + } +} - // if a space was found, include the space on this line - if(iLast!=i) - { - iLast++; - } - addMessage(string.substr(0, iLast), iPad, bIsDeathMessage); - string = string.substr(iLast); +void Gui::clearMessages(int iPad) { + if (iPad == -1) { + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i]) { + guiMessages[i].clear(); + } + } + } else { + guiMessages[iPad].clear(); + } +} + +void Gui::addMessage(const std::wstring& _string, int iPad, + bool bIsDeathMessage) { + std::wstring string = _string; // 4J - Take copy of input as it is const + // int iScale=1; + + // if((minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_TOP) + // || + // (minecraft->player->m_iScreenSection==C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM)) + //{ + // iScale=2; + // } + + // while (minecraft->font->width(string) > (m_iMaxMessageWidth*iScale)) + //{ + // unsigned int i = 1; + // while (i < string.length() && + // minecraft->font->width(string.substr(0, i + 1)) <= + // (m_iMaxMessageWidth*iScale)) + // { + // i++; + // } + // int iLast=string.find_last_of(L" ",i); + + // // if a space was found, include the space on this line + // if(iLast!=i) + // { + // iLast++; + // } + // addMessage(string.substr(0, iLast), iPad); + // string = string.substr(iLast); + // } + + int maximumChars; + + switch (minecraft->player->m_iScreenSection) { + case C4JRender::VIEWPORT_TYPE_SPLIT_TOP: + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + case C4JRender::VIEWPORT_TYPE_FULLSCREEN: + if (RenderManager.IsHiDef()) { + maximumChars = 105; + } else { + maximumChars = 55; + } +#ifdef __PSVITA__ + maximumChars = 90; +#endif + switch (XGetLanguage()) { + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_KOREAN: + if (RenderManager.IsHiDef()) { + maximumChars = 70; + } else { + maximumChars = 35; + } +#ifdef __PSVITA__ + maximumChars = 55; +#endif + break; + } + break; + default: + maximumChars = 55; + switch (XGetLanguage()) { + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_KOREAN: + maximumChars = 35; + break; + } + break; } - if(iPad==-1) - { - // add to all - for(int i=0;ilocalplayers[i] && !(bIsDeathMessage && app.GetGameSettings(i,eGameSetting_DeathMessages)==0)) - { - guiMessages[i].insert(guiMessages[i].begin(), GuiMessage(string)); - while (guiMessages[i].size() > 50) - { - guiMessages[i].pop_back(); - } - } - } - } - else if(!(bIsDeathMessage && app.GetGameSettings(iPad,eGameSetting_DeathMessages)==0)) - { - guiMessages[iPad].insert(guiMessages[iPad].begin(), GuiMessage(string)); - while (guiMessages[iPad].size() > 50) - { - guiMessages[iPad].pop_back(); - } - } + while (string.length() > maximumChars) { + unsigned int i = 1; + while (i < string.length() && (i + 1) <= maximumChars) { + i++; + } + int iLast = (int)string.find_last_of(L" ", i); + switch (XGetLanguage()) { + case XC_LANGUAGE_JAPANESE: + case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_KOREAN: + iLast = maximumChars; + break; + default: + iLast = (int)string.find_last_of(L" ", i); + break; + } + // if a space was found, include the space on this line + if (iLast != i) { + iLast++; + } + addMessage(string.substr(0, iLast), iPad, bIsDeathMessage); + string = string.substr(iLast); + } + if (iPad == -1) { + // add to all + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + if (minecraft->localplayers[i] && + !(bIsDeathMessage && + app.GetGameSettings(i, eGameSetting_DeathMessages) == 0)) { + guiMessages[i].insert(guiMessages[i].begin(), + GuiMessage(string)); + while (guiMessages[i].size() > 50) { + guiMessages[i].pop_back(); + } + } + } + } else if (!(bIsDeathMessage && + app.GetGameSettings(iPad, eGameSetting_DeathMessages) == 0)) { + guiMessages[iPad].insert(guiMessages[iPad].begin(), GuiMessage(string)); + while (guiMessages[iPad].size() > 50) { + guiMessages[iPad].pop_back(); + } + } } // 4J Added -float Gui::getOpacity(int iPad, std::size_t index) -{ - float opacityPercentage = 0; - if (guiMessages[iPad].size() > index && guiMessages[iPad][index].ticks < 20 * 10) - { - double t = guiMessages[iPad][index].ticks / (20 * 10.0); - t = 1 - t; - t = t * 10; - if (t < 0) t = 0; - if (t > 1) t = 1; - t = t * t; - opacityPercentage = t; - } - return opacityPercentage; +float Gui::getOpacity(int iPad, std::size_t index) { + float opacityPercentage = 0; + if (guiMessages[iPad].size() > index && + guiMessages[iPad][index].ticks < 20 * 10) { + double t = guiMessages[iPad][index].ticks / (20 * 10.0); + t = 1 - t; + t = t * 10; + if (t < 0) t = 0; + if (t > 1) t = 1; + t = t * t; + opacityPercentage = t; + } + return opacityPercentage; } -float Gui::getJukeboxOpacity(int iPad) -{ - float t = overlayMessageTime - lastTickA; - int alpha = (int) (t * 256 / 20); +float Gui::getJukeboxOpacity(int iPad) { + float t = overlayMessageTime - lastTickA; + int alpha = (int)(t * 256 / 20); if (alpha > 255) alpha = 255; - alpha /= 255; + alpha /= 255; - return alpha; + return alpha; } -void Gui::setNowPlaying(const std::wstring& string) -{ -// overlayMessageString = L"Now playing: " + string; - overlayMessageString = app.GetString(IDS_NOWPLAYING) + string; +void Gui::setNowPlaying(const std::wstring& string) { + // overlayMessageString = L"Now playing: " + string; + overlayMessageString = app.GetString(IDS_NOWPLAYING) + string; overlayMessageTime = 20 * 3; animateOverlayMessageColor = true; } -void Gui::displayClientMessage(int messageId, int iPad) -{ - //Language *language = Language::getInstance(); - std::wstring languageString = app.GetString(messageId);//language->getElement(messageId); +void Gui::displayClientMessage(int messageId, int iPad) { + // Language *language = Language::getInstance(); + std::wstring languageString = + app.GetString(messageId); // language->getElement(messageId); addMessage(languageString, iPad); } // 4J Added -void Gui::renderGraph(int dataLength, int dataPos, __int64 *dataA, float dataAScale, int dataAWarning, __int64 *dataB, float dataBScale, int dataBWarning) -{ - int height = minecraft->height; - // This causes us to cover xScale*dataLength pixels in the horizontal - int xScale = 1; - if(dataA != NULL && dataB != NULL) xScale = 2; +void Gui::renderGraph(int dataLength, int dataPos, __int64* dataA, + float dataAScale, int dataAWarning, __int64* dataB, + float dataBScale, int dataBWarning) { + int height = minecraft->height; + // This causes us to cover xScale*dataLength pixels in the horizontal + int xScale = 1; + if (dataA != NULL && dataB != NULL) xScale = 2; - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); - glLineWidth(1); - glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + glLineWidth(1); + glDisable(GL_TEXTURE_2D); + Tesselator* t = Tesselator::getInstance(); - t->begin(GL_LINES); - for (int i = 0; i < dataLength; i++) - { - int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; - int cc = col * col / 255; - cc = cc * cc / 255; - int cc2 = cc * cc / 255; - cc2 = cc2 * cc2 / 255; + t->begin(GL_LINES); + for (int i = 0; i < dataLength; i++) { + int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; + int cc = col * col / 255; + cc = cc * cc / 255; + int cc2 = cc * cc / 255; + cc2 = cc2 * cc2 / 255; - if( dataA != NULL ) - { - if (dataA[i] > dataAWarning) - { - t->color(0xff000000 + cc * 65536); - } - else - { - t->color(0xff000000 + cc * 256); - } + if (dataA != NULL) { + if (dataA[i] > dataAWarning) { + t->color(0xff000000 + cc * 65536); + } else { + t->color(0xff000000 + cc * 256); + } - __int64 aVal = dataA[i] / dataAScale; + __int64 aVal = dataA[i] / dataAScale; - t->vertex((float)(xScale*i + 0.5f), (float)( height - aVal + 0.5f), (float)( 0)); - t->vertex((float)(xScale*i + 0.5f), (float)( height + 0.5f), (float)( 0)); - } - - if( dataB != NULL ) - { - if (dataB[i]>dataBWarning) - { - t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); - } - else - { - t->color(0xff808080 + cc/2 * 256); - } + t->vertex((float)(xScale * i + 0.5f), (float)(height - aVal + 0.5f), + (float)(0)); + t->vertex((float)(xScale * i + 0.5f), (float)(height + 0.5f), + (float)(0)); + } - __int64 bVal = dataB[i] / dataBScale; + if (dataB != NULL) { + if (dataB[i] > dataBWarning) { + t->color(0xff000000 + cc * 65536 + cc * 256 + cc * 1); + } else { + t->color(0xff808080 + cc / 2 * 256); + } - t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height - bVal + 0.5f), (float)( 0)); - t->vertex((float)(xScale*i + (xScale - 1) + 0.5f), (float)( height + 0.5f), (float)( 0)); - } - } - t->end(); + __int64 bVal = dataB[i] / dataBScale; - glEnable(GL_TEXTURE_2D); + t->vertex((float)(xScale * i + (xScale - 1) + 0.5f), + (float)(height - bVal + 0.5f), (float)(0)); + t->vertex((float)(xScale * i + (xScale - 1) + 0.5f), + (float)(height + 0.5f), (float)(0)); + } + } + t->end(); + + glEnable(GL_TEXTURE_2D); } -void Gui::renderStackedGraph(int dataPos, int dataLength, int dataSources, __int64 (*func)(unsigned int dataPos, unsigned int dataSource) ) -{ - int height = minecraft->height; +void Gui::renderStackedGraph(int dataPos, int dataLength, int dataSources, + __int64 (*func)(unsigned int dataPos, + unsigned int dataSource)) { + int height = minecraft->height; - glClear(GL_DEPTH_BUFFER_BIT); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glTranslatef(0, 0, -2000); + glClear(GL_DEPTH_BUFFER_BIT); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)minecraft->width, (float)height, 0, 1000, 3000); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0, 0, -2000); - glLineWidth(1); - glDisable(GL_TEXTURE_2D); - Tesselator *t = Tesselator::getInstance(); + glLineWidth(1); + glDisable(GL_TEXTURE_2D); + Tesselator* t = Tesselator::getInstance(); - t->begin(GL_LINES); - __int64 thisVal = 0; - __int64 topVal = 0; - for (int i = 0; i < dataLength; i++) - { - thisVal = 0; - topVal = 0; - int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; - int cc = col * col / 255; - cc = cc * cc / 255; - int cc2 = cc * cc / 255; - cc2 = cc2 * cc2 / 255; + t->begin(GL_LINES); + __int64 thisVal = 0; + __int64 topVal = 0; + for (int i = 0; i < dataLength; i++) { + thisVal = 0; + topVal = 0; + int col = ((i - dataPos) & (dataLength - 1)) * 255 / dataLength; + int cc = col * col / 255; + cc = cc * cc / 255; + int cc2 = cc * cc / 255; + cc2 = cc2 * cc2 / 255; + for (unsigned int source = 0; source < dataSources; ++source) { + thisVal = func(i, source); - for(unsigned int source = 0; source < dataSources; ++source ) - { - thisVal = func( i, source ); + if (thisVal > 0) { + float vary = (float)source / dataSources; + int fColour = floor(vary * 0xffffff); - if( thisVal > 0 ) - { - float vary = (float)source/dataSources; - int fColour = floor(vary * 0xffffff); + int colour = 0xff000000 + fColour; + // printf("Colour is %x\n", colour); + t->color(colour); - int colour = 0xff000000 + fColour; - //printf("Colour is %x\n", colour); - t->color(colour); + t->vertex((float)(i + 0.5f), + (float)(height - topVal - thisVal + 0.5f), + (float)(0)); + t->vertex((float)(i + 0.5f), (float)(height - topVal + 0.5f), + (float)(0)); - t->vertex((float)(i + 0.5f), (float)( height - topVal - thisVal + 0.5f), (float)( 0)); - t->vertex((float)(i + 0.5f), (float)( height - topVal + 0.5f), (float)( 0)); + topVal += thisVal; + } + } - topVal += thisVal; - } - } + // Draw some horizontals + for (unsigned int horiz = 1; horiz < 7; ++horiz) { + t->color(0xff000000); - // Draw some horizontals - for(unsigned int horiz = 1; horiz < 7; ++horiz ) - { - t->color(0xff000000); + t->vertex((float)(0 + 0.5f), (float)(height - (horiz * 100) + 0.5f), + (float)(0)); + t->vertex((float)(dataLength + 0.5f), + (float)(height - (horiz * 100) + 0.5f), (float)(0)); + } + } + t->end(); - t->vertex((float)(0 + 0.5f), (float)( height - (horiz*100) + 0.5f), (float)( 0)); - t->vertex((float)(dataLength + 0.5f), (float)( height - (horiz*100) + 0.5f), (float)( 0)); - } - } - t->end(); - - glEnable(GL_TEXTURE_2D); + glEnable(GL_TEXTURE_2D); } diff --git a/Minecraft.Client/UI/Gui.h b/Minecraft.Client/UI/Gui.h index 725a3b4c6..fc5767e1f 100644 --- a/Minecraft.Client/UI/Gui.h +++ b/Minecraft.Client/UI/Gui.h @@ -6,64 +6,75 @@ class Random; class Minecraft; class ItemRenderer; -class Gui : public GuiComponent -{ +class Gui : public GuiComponent { private: - // 4J-PB - this doesn't account for the safe zone, and the indent applied to messages - //static const int MAX_MESSAGE_WIDTH = 320; - static const int m_iMaxMessageWidth = 280; - static ItemRenderer *itemRenderer; + // 4J-PB - this doesn't account for the safe zone, and the indent applied to + // messages + // static const int MAX_MESSAGE_WIDTH = 320; + static const int m_iMaxMessageWidth = 280; + static ItemRenderer* itemRenderer; std::vector guiMessages[XUSER_MAX_COUNT]; - Random *random; + Random* random; + + Minecraft* minecraft; - Minecraft *minecraft; public: - std::wstring selectedName; + std::wstring selectedName; + private: - int tickCount; + int tickCount; std::wstring overlayMessageString; int overlayMessageTime; bool animateOverlayMessageColor; - // 4J Added - float lastTickA; - float fAlphaIncrementPerCent; -public: - static float currentGuiBlendFactor; // 4J added - static float currentGuiScaleFactor; // 4J added - - float progress; - -// private DecimalFormat df = new DecimalFormat("##.00"); + // 4J Added + float lastTickA; + float fAlphaIncrementPerCent; public: - Gui(Minecraft *minecraft); + static float currentGuiBlendFactor; // 4J added + static float currentGuiScaleFactor; // 4J added - void render(float a, bool mouseFree, int xMouse, int yMouse); + float progress; + + // private DecimalFormat df = new DecimalFormat("##.00"); + +public: + Gui(Minecraft* minecraft); + + void render(float a, bool mouseFree, int xMouse, int yMouse); float tbr; private: - //void renderBossHealth(void); - void renderPumpkin(int w, int h); + // void renderBossHealth(void); + void renderPumpkin(int w, int h); void renderVignette(float br, int w, int h); void renderTp(float br, int w, int h); void renderSlot(int slot, int x, int y, float a); + public: - void tick(); - void clearMessages(int iPad=-1); - void addMessage(const std::wstring& string, int iPad,bool bIsDeathMessage=false); + void tick(); + void clearMessages(int iPad = -1); + void addMessage(const std::wstring& string, int iPad, + bool bIsDeathMessage = false); void setNowPlaying(const std::wstring& string); void displayClientMessage(int messageId, int iPad); - // 4J Added - std::size_t getMessagesCount(int iPad) { return guiMessages[iPad].size(); } - std::wstring getMessage(int iPad, std::size_t index) { return guiMessages[iPad].at(index).string; } - float getOpacity(int iPad, std::size_t index); + // 4J Added + std::size_t getMessagesCount(int iPad) { return guiMessages[iPad].size(); } + std::wstring getMessage(int iPad, std::size_t index) { + return guiMessages[iPad].at(index).string; + } + float getOpacity(int iPad, std::size_t index); - std::wstring getJukeboxMessage(int iPad) { return overlayMessageString; } - float getJukeboxOpacity(int iPad); + std::wstring getJukeboxMessage(int iPad) { return overlayMessageString; } + float getJukeboxOpacity(int iPad); - // 4J Added - void renderGraph(int dataLength, int dataPos, __int64 *dataA, float dataAScale, int dataAWarning, __int64 *dataB, float dataBScale, int dataBWarning); - void renderStackedGraph(int dataPos, int dataLength, int dataSources, __int64 (*func)(unsigned int dataPos, unsigned int dataSource) ); + // 4J Added + void renderGraph(int dataLength, int dataPos, __int64* dataA, + float dataAScale, int dataAWarning, __int64* dataB, + float dataBScale, int dataBWarning); + void renderStackedGraph(int dataPos, int dataLength, int dataSources, + __int64 (*func)(unsigned int dataPos, + unsigned int dataSource)); }; diff --git a/Minecraft.Client/UI/GuiComponent.cpp b/Minecraft.Client/UI/GuiComponent.cpp index 460cf6fa1..d9149f2c8 100644 --- a/Minecraft.Client/UI/GuiComponent.cpp +++ b/Minecraft.Client/UI/GuiComponent.cpp @@ -2,10 +2,8 @@ #include "GuiComponent.h" #include "../Rendering/Tesselator.h" -void GuiComponent::hLine(int x0, int x1, int y, int col) -{ - if (x1 < x0) - { +void GuiComponent::hLine(int x0, int x1, int y, int col) { + if (x1 < x0) { int tmp = x0; x0 = x1; x1 = tmp; @@ -13,10 +11,8 @@ void GuiComponent::hLine(int x0, int x1, int y, int col) fill(x0, y, x1 + 1, y + 1, col); } -void GuiComponent::vLine(int x, int y0, int y1, int col) -{ - if (y1 < y0) - { +void GuiComponent::vLine(int x, int y0, int y1, int col) { + if (y1 < y0) { int tmp = y0; y0 = y1; y1 = tmp; @@ -24,16 +20,13 @@ void GuiComponent::vLine(int x, int y0, int y1, int col) fill(x, y0 + 1, x + 1, y1, col); } -void GuiComponent::fill(int x0, int y0, int x1, int y1, int col) -{ - if (x0 < x1) - { +void GuiComponent::fill(int x0, int y0, int x1, int y1, int col) { + if (x0 < x1) { int tmp = x0; x0 = x1; x1 = tmp; } - if (y0 < y1) - { + if (y0 < y1) { int tmp = y0; y0 = y1; y1 = tmp; @@ -42,23 +35,23 @@ void GuiComponent::fill(int x0, int y0, int x1, int y1, int col) float r = ((col >> 16) & 0xff) / 255.0f; float g = ((col >> 8) & 0xff) / 255.0f; float b = ((col) & 0xff) / 255.0f; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); glEnable(GL_BLEND); glDisable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(r, g, b, a); t->begin(); - t->vertex((float)(x0), (float)( y1), (float)( 0)); - t->vertex((float)(x1), (float)( y1), (float)( 0)); - t->vertex((float)(x1), (float)( y0), (float)( 0)); - t->vertex((float)(x0), (float)( y0), (float)( 0)); + t->vertex((float)(x0), (float)(y1), (float)(0)); + t->vertex((float)(x1), (float)(y1), (float)(0)); + t->vertex((float)(x1), (float)(y0), (float)(0)); + t->vertex((float)(x0), (float)(y0), (float)(0)); t->end(); glEnable(GL_TEXTURE_2D); glDisable(GL_BLEND); } -void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, int col2) -{ +void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, + int col2) { float a1 = ((col1 >> 24) & 0xff) / 255.0f; float r1 = ((col1 >> 16) & 0xff) / 255.0f; float g1 = ((col1 >> 8) & 0xff) / 255.0f; @@ -74,14 +67,14 @@ void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, int co glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_SMOOTH); - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); t->color(r1, g1, b1, a1); - t->vertex((float)(x1), (float)( y0), blitOffset); - t->vertex((float)(x0), (float)( y0), blitOffset); + t->vertex((float)(x1), (float)(y0), blitOffset); + t->vertex((float)(x0), (float)(y0), blitOffset); t->color(r2, g2, b2, a2); - t->vertex((float)(x0), (float)( y1), blitOffset); - t->vertex((float)(x1), (float)( y1), blitOffset); + t->vertex((float)(x0), (float)(y1), blitOffset); + t->vertex((float)(x1), (float)(y1), blitOffset); t->end(); glShadeModel(GL_FLAT); @@ -90,47 +83,62 @@ void GuiComponent::fillGradient(int x0, int y0, int x1, int y1, int col1, int co glEnable(GL_TEXTURE_2D); } -GuiComponent::GuiComponent() -{ - blitOffset = 0; +GuiComponent::GuiComponent() { blitOffset = 0; } + +void GuiComponent::drawCenteredString(Font* font, const std::wstring& str, + int x, int y, int color) { + font->drawShadow(str, x - (font->width(str)) / 2, y, color); } -void GuiComponent::drawCenteredString(Font *font, const std::wstring& str, int x, int y, int color) -{ - font->drawShadow(str, x - (font->width(str)) / 2, y, color); +void GuiComponent::drawString(Font* font, const std::wstring& str, int x, int y, + int color) { + font->drawShadow(str, x, y, color); } -void GuiComponent::drawString(Font *font, const std::wstring& str, int x, int y, int color) -{ - font->drawShadow(str, x, y, color); -} - -void GuiComponent::blit(int x, int y, int sx, int sy, int w, int h) -{ +void GuiComponent::blit(int x, int y, int sx, int sy, int w, int h) { float us = 1 / 256.0f; float vs = 1 / 256.0f; - Tesselator *t = Tesselator::getInstance(); + Tesselator* t = Tesselator::getInstance(); t->begin(); - // This is a bit of a mystery. In general this ought to be 0.5 to match the centre of texels & pixels in the DX9 version of things. However, when scaling the GUI by a factor of 1.5, I'm - // really not sure how exactly point sampled rasterisation works, but when shifting by 0.5 we get a discontinuity down the diagonal of quads. Setting this shift to 0.75 in all cases seems to work fine. - const float extraShift = 0.75f; + // This is a bit of a mystery. In general this ought to be 0.5 to match the + // centre of texels & pixels in the DX9 version of things. However, when + // scaling the GUI by a factor of 1.5, I'm really not sure how exactly point + // sampled rasterisation works, but when shifting by 0.5 we get a + // discontinuity down the diagonal of quads. Setting this shift to 0.75 in + // all cases seems to work fine. + const float extraShift = 0.75f; - // 4J - subtracting extraShift (actual screen pixels, so need to compensate for physical & game width) from each x & y coordinate to compensate for centre of pixels in directx vs openGL - float dx = ( extraShift * (float)Minecraft::GetInstance()->width ) / (float)Minecraft::GetInstance()->width_phys; - // 4J - Also factor in the scaling from gui coordinate space to the screen. This varies based on user-selected gui scale, and whether we are in a viewport mode or not - dx /= Gui::currentGuiScaleFactor; - float dy = extraShift / Gui::currentGuiScaleFactor; - // Ensure that the x/y, width and height are actually pixel aligned at our current scale factor - in particular, for split screen mode with the default (3X) - // scale, we have an overall scale factor of 3 * 0.5 = 1.5, and so any odd pixels won't align - float fx = (floorf((float)x * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; - float fy = (floorf((float)y * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; - float fw = (floorf((float)w * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; - float fh = (floorf((float)h * Gui::currentGuiScaleFactor)) / Gui::currentGuiScaleFactor; + // 4J - subtracting extraShift (actual screen pixels, so need to compensate + // for physical & game width) from each x & y coordinate to compensate for + // centre of pixels in directx vs openGL + float dx = (extraShift * (float)Minecraft::GetInstance()->width) / + (float)Minecraft::GetInstance()->width_phys; + // 4J - Also factor in the scaling from gui coordinate space to the screen. + // This varies based on user-selected gui scale, and whether we are in a + // viewport mode or not + dx /= Gui::currentGuiScaleFactor; + float dy = extraShift / Gui::currentGuiScaleFactor; + // Ensure that the x/y, width and height are actually pixel aligned at our + // current scale factor - in particular, for split screen mode with the + // default (3X) scale, we have an overall scale factor of 3 * 0.5 = 1.5, and + // so any odd pixels won't align + float fx = (floorf((float)x * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; + float fy = (floorf((float)y * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; + float fw = (floorf((float)w * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; + float fh = (floorf((float)h * Gui::currentGuiScaleFactor)) / + Gui::currentGuiScaleFactor; - t->vertexUV(fx + 0 - dx, fy + fh - dy, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + h) * vs)); - t->vertexUV(fx + fw - dx, fy + fh - dy, (float)( blitOffset), (float)( (sx + w) * us), (float)( (sy + h) * vs)); - t->vertexUV(fx + fw - dx, fy + 0 - dy, (float)( blitOffset), (float)( (sx + w) * us), (float)( (sy + 0) * vs)); - t->vertexUV(fx + 0 - dx, fy + 0 - dy, (float)( blitOffset), (float)( (sx + 0) * us), (float)( (sy + 0) * vs)); + t->vertexUV(fx + 0 - dx, fy + fh - dy, (float)(blitOffset), + (float)((sx + 0) * us), (float)((sy + h) * vs)); + t->vertexUV(fx + fw - dx, fy + fh - dy, (float)(blitOffset), + (float)((sx + w) * us), (float)((sy + h) * vs)); + t->vertexUV(fx + fw - dx, fy + 0 - dy, (float)(blitOffset), + (float)((sx + w) * us), (float)((sy + 0) * vs)); + t->vertexUV(fx + 0 - dx, fy + 0 - dy, (float)(blitOffset), + (float)((sx + 0) * us), (float)((sy + 0) * vs)); t->end(); } \ No newline at end of file diff --git a/Minecraft.Client/UI/GuiComponent.h b/Minecraft.Client/UI/GuiComponent.h index 71324d0e3..fe7ece730 100644 --- a/Minecraft.Client/UI/GuiComponent.h +++ b/Minecraft.Client/UI/GuiComponent.h @@ -1,19 +1,21 @@ #pragma once class Font; +class GuiComponent { +protected: + float blitOffset; -class GuiComponent -{ protected: - float blitOffset; -protected: - void hLine(int x0, int x1, int y, int col); + void hLine(int x0, int x1, int y, int col); void vLine(int x, int y0, int y1, int col); void fill(int x0, int y0, int x1, int y1, int col); void fillGradient(int x0, int y0, int x1, int y1, int col1, int col2); + public: - GuiComponent(); // 4J added - void drawCenteredString(Font *font, const std::wstring& str, int x, int y, int color); - void drawString(Font *font, const std::wstring& str, int x, int y, int color); + GuiComponent(); // 4J added + void drawCenteredString(Font* font, const std::wstring& str, int x, int y, + int color); + void drawString(Font* font, const std::wstring& str, int x, int y, + int color); void blit(int x, int y, int sx, int sy, int w, int h); }; diff --git a/Minecraft.Client/UI/GuiMessage.cpp b/Minecraft.Client/UI/GuiMessage.cpp index 6f62556a5..961c9e04b 100644 --- a/Minecraft.Client/UI/GuiMessage.cpp +++ b/Minecraft.Client/UI/GuiMessage.cpp @@ -1,8 +1,7 @@ #include "../Platform/stdafx.h" #include "GuiMessage.h" -GuiMessage::GuiMessage(const std::wstring& string) -{ - this->string = string; - ticks = 0; +GuiMessage::GuiMessage(const std::wstring& string) { + this->string = string; + ticks = 0; } \ No newline at end of file diff --git a/Minecraft.Client/UI/GuiMessage.h b/Minecraft.Client/UI/GuiMessage.h index ad1403084..84596a860 100644 --- a/Minecraft.Client/UI/GuiMessage.h +++ b/Minecraft.Client/UI/GuiMessage.h @@ -1,10 +1,8 @@ #pragma once - -class GuiMessage -{ +class GuiMessage { public: - std::wstring string; - int ticks; - GuiMessage(const std::wstring& string); + std::wstring string; + int ticks; + GuiMessage(const std::wstring& string); }; \ No newline at end of file diff --git a/Minecraft.Client/UI/Rect2i.cpp b/Minecraft.Client/UI/Rect2i.cpp index 6681adf15..e7d8e0f52 100644 --- a/Minecraft.Client/UI/Rect2i.cpp +++ b/Minecraft.Client/UI/Rect2i.cpp @@ -1,76 +1,49 @@ #include "../Platform/stdafx.h" #include "Rect2i.h" -Rect2i::Rect2i(int x, int y, int width, int height) -{ - xPos = x; - yPos = y; - this->width = width; - this->height = height; +Rect2i::Rect2i(int x, int y, int width, int height) { + xPos = x; + yPos = y; + this->width = width; + this->height = height; } -Rect2i *Rect2i::intersect(const Rect2i *other) -{ - int x0 = xPos; - int y0 = yPos; - int x1 = xPos + width; - int y1 = yPos + height; +Rect2i* Rect2i::intersect(const Rect2i* other) { + int x0 = xPos; + int y0 = yPos; + int x1 = xPos + width; + int y1 = yPos + height; - int x2 = other->getX(); - int y2 = other->getY(); - int x3 = x2 + other->getWidth(); - int y3 = y2 + other->getHeight(); + int x2 = other->getX(); + int y2 = other->getY(); + int x3 = x2 + other->getWidth(); + int y3 = y2 + other->getHeight(); - xPos = std::max(x0, x2); - yPos = std::max(y0, y2); - width = std::max(0, std::min(x1, x3) - xPos); - height = std::max(0, std::min(y1, y3) - yPos); + xPos = std::max(x0, x2); + yPos = std::max(y0, y2); + width = std::max(0, std::min(x1, x3) - xPos); + height = std::max(0, std::min(y1, y3) - yPos); - return this; + return this; } -int Rect2i::getX() const -{ - return xPos; -} +int Rect2i::getX() const { return xPos; } -int Rect2i::getY() const -{ - return yPos; -} +int Rect2i::getY() const { return yPos; } -void Rect2i::setX(int x) -{ - xPos = x; -} +void Rect2i::setX(int x) { xPos = x; } -void Rect2i::setY(int y) -{ - yPos = y; -} +void Rect2i::setY(int y) { yPos = y; } -int Rect2i::getWidth() const -{ - return width; -} +int Rect2i::getWidth() const { return width; } -int Rect2i::getHeight() const -{ - return height; -} +int Rect2i::getHeight() const { return height; } -void Rect2i::setWidth(int width) -{ - this->width = width; -} +void Rect2i::setWidth(int width) { this->width = width; } -void Rect2i::setHeight(int height) -{ - this->height = height; -} +void Rect2i::setHeight(int height) { this->height = height; } -void Rect2i::setPosition(int x, int y) -{ - xPos = x; - yPos = y; +void Rect2i::setPosition(int x, int y) { + xPos = x; + yPos = y; } \ No newline at end of file diff --git a/Minecraft.Client/UI/Rect2i.h b/Minecraft.Client/UI/Rect2i.h index cb9471a02..9f52a726f 100644 --- a/Minecraft.Client/UI/Rect2i.h +++ b/Minecraft.Client/UI/Rect2i.h @@ -1,24 +1,23 @@ #pragma once -class Rect2i -{ +class Rect2i { private: - int xPos; - int yPos; - int width; - int height; + int xPos; + int yPos; + int width; + int height; public: - Rect2i(int x, int y, int width, int height); + Rect2i(int x, int y, int width, int height); - Rect2i *intersect(const Rect2i *other); - int getX() const; - int getY() const; - void setX(int x); - void setY(int y); - int getWidth() const; - int getHeight() const; - void setWidth(int width); - void setHeight(int height); - void setPosition(int x, int y); + Rect2i* intersect(const Rect2i* other); + int getX() const; + int getY() const; + void setX(int x); + void setY(int y); + int getWidth() const; + int getHeight() const; + void setWidth(int width); + void setHeight(int height); + void setPosition(int x, int y); }; \ No newline at end of file diff --git a/Minecraft.Client/UI/Screen.cpp b/Minecraft.Client/UI/Screen.cpp index 3fe91d598..719e6c24c 100644 --- a/Minecraft.Client/UI/Screen.cpp +++ b/Minecraft.Client/UI/Screen.cpp @@ -6,59 +6,47 @@ #include "../Textures/Textures.h" #include "../../Minecraft.World/Util/SoundTypes.h" - - -Screen::Screen() // 4J added +Screen::Screen() // 4J added { - minecraft = NULL; - width = 0; + minecraft = NULL; + width = 0; height = 0; - passEvents = false; - font = NULL; - particles = NULL; - clickedButton = NULL; + passEvents = false; + font = NULL; + particles = NULL; + clickedButton = NULL; } -void Screen::render(int xm, int ym, float a) -{ - AUTO_VAR(itEnd, buttons.end()); - for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) - { - Button *button = *it; //buttons[i]; +void Screen::render(int xm, int ym, float a) { + AUTO_VAR(itEnd, buttons.end()); + for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) { + Button* button = *it; // buttons[i]; button->render(minecraft, xm, ym); } } -void Screen::keyPressed(wchar_t eventCharacter, int eventKey) -{ - if (eventKey == Keyboard::KEY_ESCAPE) - { - minecraft->setScreen(NULL); -// minecraft->grabMouse(); // 4J - removed - } +void Screen::keyPressed(wchar_t eventCharacter, int eventKey) { + if (eventKey == Keyboard::KEY_ESCAPE) { + minecraft->setScreen(NULL); + // minecraft->grabMouse(); // 4J - removed + } } -std::wstring Screen::getClipboard() -{ - // 4J - removed - return NULL; +std::wstring Screen::getClipboard() { + // 4J - removed + return NULL; } -void Screen::setClipboard(const std::wstring& str) -{ - // 4J - removed +void Screen::setClipboard(const std::wstring& str) { + // 4J - removed } -void Screen::mouseClicked(int x, int y, int buttonNum) -{ - if (buttonNum == 0) - { - AUTO_VAR(itEnd, buttons.end()); - for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) - { - Button *button = *it; //buttons[i]; - if (button->clicked(minecraft, x, y)) - { +void Screen::mouseClicked(int x, int y, int buttonNum) { + if (buttonNum == 0) { + AUTO_VAR(itEnd, buttons.end()); + for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) { + Button* button = *it; // buttons[i]; + if (button->clicked(minecraft, x, y)) { clickedButton = button; minecraft->soundEngine->playUI(eSoundType_RANDOM_CLICK, 1, 1); buttonClicked(button); @@ -67,21 +55,16 @@ void Screen::mouseClicked(int x, int y, int buttonNum) } } -void Screen::mouseReleased(int x, int y, int buttonNum) -{ - if (clickedButton!=NULL && buttonNum==0) - { +void Screen::mouseReleased(int x, int y, int buttonNum) { + if (clickedButton != NULL && buttonNum == 0) { clickedButton->released(x, y); clickedButton = NULL; } } -void Screen::buttonClicked(Button *button) -{ -} +void Screen::buttonClicked(Button* button) {} -void Screen::init(Minecraft *minecraft, int width, int height) -{ +void Screen::init(Minecraft* minecraft, int width, int height) { particles = new GuiParticles(minecraft); this->minecraft = minecraft; this->font = minecraft->font; @@ -91,97 +74,71 @@ void Screen::init(Minecraft *minecraft, int width, int height) init(); } -void Screen::setSize(int width, int height) -{ +void Screen::setSize(int width, int height) { this->width = width; this->height = height; } -void Screen::init() -{ +void Screen::init() {} + +void Screen::updateEvents() { + /* 4J - TODO +while (Mouse.next()) { + mouseEvent(); } -void Screen::updateEvents() -{ - /* 4J - TODO - while (Mouse.next()) { - mouseEvent(); - } - - while (Keyboard.next()) { - keyboardEvent(); - } - */ - +while (Keyboard.next()) { + keyboardEvent(); +} + */ } -void Screen::mouseEvent() -{ - /* 4J - TODO - if (Mouse.getEventButtonState()) { - int xm = Mouse.getEventX() * width / minecraft.width; - int ym = height - Mouse.getEventY() * height / minecraft.height - 1; - mouseClicked(xm, ym, Mouse.getEventButton()); +void Screen::mouseEvent() { + /* 4J - TODO +if (Mouse.getEventButtonState()) { + int xm = Mouse.getEventX() * width / minecraft.width; + int ym = height - Mouse.getEventY() * height / minecraft.height - 1; + mouseClicked(xm, ym, Mouse.getEventButton()); +} else { + int xm = Mouse.getEventX() * width / minecraft.width; + int ym = height - Mouse.getEventY() * height / minecraft.height - 1; + mouseReleased(xm, ym, Mouse.getEventButton()); +} + */ +} + +void Screen::keyboardEvent() { + /* 4J - TODO +if (Keyboard.getEventKeyState()) { + if (Keyboard.getEventKey() == Keyboard.KEY_F11) { + minecraft.toggleFullScreen(); + return; + } + keyPressed(Keyboard.getEventCharacter(), Keyboard.getEventKey()); +} + */ +} + +void Screen::tick() {} + +void Screen::removed() {} + +void Screen::renderBackground() { renderBackground(0); } + +void Screen::renderBackground(int vo) { + if (minecraft->level != NULL) { + fillGradient(0, 0, width, height, 0xc0101010, 0xd0101010); } else { - int xm = Mouse.getEventX() * width / minecraft.width; - int ym = height - Mouse.getEventY() * height / minecraft.height - 1; - mouseReleased(xm, ym, Mouse.getEventButton()); + renderDirtBackground(vo); } - */ } -void Screen::keyboardEvent() -{ - /* 4J - TODO - if (Keyboard.getEventKeyState()) { - if (Keyboard.getEventKey() == Keyboard.KEY_F11) { - minecraft.toggleFullScreen(); - return; - } - keyPressed(Keyboard.getEventCharacter(), Keyboard.getEventKey()); - } - */ -} - -void Screen::tick() -{ -} - -void Screen::removed() -{ -} - -void Screen::renderBackground() -{ - renderBackground(0); -} - -void Screen::renderBackground(int vo) -{ - if (minecraft->level != NULL) - { - fillGradient(0, 0, width, height, 0xc0101010, 0xd0101010); - } - else - { - renderDirtBackground(vo); - } -} - -void Screen::renderDirtBackground(int vo) -{ +void Screen::renderDirtBackground(int vo) { // 4J Unused - Iggy Flash UI renders the background on consoles } -bool Screen::isPauseScreen() -{ - return true; -} +bool Screen::isPauseScreen() { return true; } -void Screen::confirmResult(bool result, int id) -{ -} +void Screen::confirmResult(bool result, int id) {} -void Screen::tabPressed() -{ -} +void Screen::tabPressed() {} diff --git a/Minecraft.Client/UI/Screen.h b/Minecraft.Client/UI/Screen.h index 169b49f33..9395e9de9 100644 --- a/Minecraft.Client/UI/Screen.h +++ b/Minecraft.Client/UI/Screen.h @@ -4,39 +4,46 @@ class Button; class GuiParticles; class Minecraft; - -class Screen : public GuiComponent -{ +class Screen : public GuiComponent { protected: - Minecraft *minecraft; + Minecraft* minecraft; + public: - int width; + int width; int height; -protected: - std::vector