diff --git a/.clangd b/.clangd index 8a2174d..3542d83 100644 --- a/.clangd +++ b/.clangd @@ -1,3 +1,3 @@ CompileFlags: CompilationDatabase: build - Add: [-std=c++20] + Add: [-std=gnu++23] diff --git a/.gitmodules b/.gitmodules index 6d2aabf..ee92ef6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -13,9 +13,6 @@ [submodule "external/tinyxml2"] path = external/tinyxml2 url = https://github.com/leethomason/tinyxml2 -[submodule "external/libanm2"] - path = external/libanm2 - url = https://github.com/shweetsstuff/libanm2 [submodule "external/physfs"] path = external/physfs url = https://github.com/icculus/physfs diff --git a/CMakeLists.txt b/CMakeLists.txt index ee8e2ba..4e441f6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,9 +8,9 @@ set(BUILD_SHARED_LIBS OFF) if(NOT CMAKE_SYSTEM_NAME STREQUAL "Emscripten") set(CMAKE_C_FLAGS_DEBUG "-O0 -g" CACHE STRING "" FORCE) - set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g" CACHE STRING "" FORCE) + set(CMAKE_CXX_FLAGS_DEBUG "-Wall -Wpedantic -O0 -g" CACHE STRING "" FORCE) set(CMAKE_C_FLAGS_RELEASE "-O3 -DNDEBUG" CACHE STRING "" FORCE) - set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG" CACHE STRING "" FORCE) + set(CMAKE_CXX_FLAGS_RELEASE "-Wall -Wpedantic -O3 -DNDEBUG" CACHE STRING "" FORCE) endif() set(SDL_STATIC ON CACHE BOOL "" FORCE) @@ -56,12 +56,25 @@ set(SDLMIXER_TEST OFF CACHE BOOL "" FORCE) set(SDLMIXER_INSTALL OFF CACHE BOOL "" FORCE) add_subdirectory(external/SDL_mixer EXCLUDE_FROM_ALL) - - +set(PHYSFS_BUILD_SHARED OFF CACHE BOOL "" FORCE) +set(PHYSFS_BUILD_STATIC ON CACHE BOOL "" FORCE) +set(PHYSFS_BUILD_TEST OFF CACHE BOOL "" FORCE) +set(PHYSFS_BUILD_DOCS OFF CACHE BOOL "" FORCE) +set(PHYSFS_BUILD_WX_TEST OFF CACHE BOOL "" FORCE) +set(PHYSFS_ARCHIVE_ZIP ON CACHE BOOL "" FORCE) +set(PHYSFS_ARCHIVE_7Z OFF CACHE BOOL "" FORCE) +set(PHYSFS_ARCHIVE_GRP OFF CACHE BOOL "" FORCE) +set(PHYSFS_ARCHIVE_HOG OFF CACHE BOOL "" FORCE) +set(PHYSFS_ARCHIVE_PAK OFF CACHE BOOL "" FORCE) +set(PHYSFS_ARCHIVE_WAD OFF CACHE BOOL "" FORCE) +set(PHYSFS_ARCHIVE_DIR ON CACHE BOOL "" FORCE) +set(PHYSFS_DISABLE_INSTALL ON CACHE BOOL "" FORCE) +add_subdirectory(external/physfs) set(IMGUI_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external/imgui) set(TINYXML2_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external/tinyxml2) set(GLM_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external/glm) +set(PHYSFS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/external/physfs) set(IMGUI_SOURCES ${IMGUI_DIR}/imgui.cpp @@ -75,12 +88,17 @@ set(IMGUI_SOURCES set (TINYXML2_SOURCES ${TINYXML2_DIR}/tinyxml2.cpp) file(GLOB PROJECT_SRC CONFIGURE_DEPENDS - include/*.cpp - src/*.cpp - src/resource/*.cpp - src/window/*.cpp - src/util/*.cpp - src/util/*.h + include/*.cpp + src/*.cpp + src/resource/*.cpp + src/resource/xml/*.cpp + src/state/*.cpp + src/state/main/*.cpp + src/state/select/*.cpp + src/entity/*.cpp + src/window/*.cpp + src/util/*.cpp + src/util/imgui/*.cpp ) add_executable(${PROJECT_NAME} @@ -103,7 +121,7 @@ target_include_directories(${PROJECT_NAME} PRIVATE include ) -target_link_libraries(${PROJECT_NAME} PRIVATE SDL3::SDL3-static SDL3_mixer::SDL3_mixer-static) +target_link_libraries(${PROJECT_NAME} PRIVATE SDL3::SDL3-static SDL3_mixer::SDL3_mixer-static physfs-static) set(PROJECT_RESOURCES_DIR "${CMAKE_CURRENT_SOURCE_DIR}/resources") set(PROJECT_RESOURCES_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/resources") @@ -111,6 +129,7 @@ if(EXISTS "${PROJECT_RESOURCES_DIR}") file(GLOB_RECURSE PROJECT_RESOURCE_FILES CONFIGURE_DEPENDS "${PROJECT_RESOURCES_DIR}/*") add_custom_target(copy_resources ALL + COMMAND ${CMAKE_COMMAND} -E remove_directory "${PROJECT_RESOURCES_BINARY_DIR}" COMMAND ${CMAKE_COMMAND} -E copy_directory "${PROJECT_RESOURCES_DIR}" "${PROJECT_RESOURCES_BINARY_DIR}" DEPENDS ${PROJECT_RESOURCE_FILES} COMMENT "Copying resources directory") @@ -128,6 +147,9 @@ if (CMAKE_SYSTEM_NAME STREQUAL "Emscripten") "-sUSE_OGG=1" "-sUSE_VORBIS=1" "-sALLOW_MEMORY_GROWTH=1" + "-sFORCE_FILESYSTEM=1" + "-sASYNCIFY" + "-lidbfs.js" ) if(HAS_PROJECT_RESOURCES) target_link_options(${PROJECT_NAME} PRIVATE @@ -137,7 +159,7 @@ if (CMAKE_SYSTEM_NAME STREQUAL "Emscripten") endif() set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "index" - SUFFIX ".js") + SUFFIX ".html") else() find_package(OpenGL REQUIRED COMPONENTS OpenGL) target_link_libraries(${PROJECT_NAME} PRIVATE OpenGL::GL) diff --git a/external/libanm2 b/external/libanm2 deleted file mode 160000 index 623c67e..0000000 --- a/external/libanm2 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 623c67edbd80eb4aa4fcd5149a482f6e6440ef2a diff --git a/include/stb_image.h b/include/stb_image.h deleted file mode 100644 index 5eb262d..0000000 --- a/include/stb_image.h +++ /dev/null @@ -1,8881 +0,0 @@ -/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb - no warranty implied; use at your own risk - - Do this: - #define STB_IMAGE_IMPLEMENTATION - before you include this file in *one* C or C++ file to create the implementation. - - // i.e. it should look like this: - #include ... - #include ... - #include ... - #define STB_IMAGE_IMPLEMENTATION - #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 - - - 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 - - TGA (not sure what subset, if a subset) - BMP non-1bpp, non-RLE - PSD (composited view only, no extra channels, 8/16 bit-per-channel) - - GIF (*comp always reports as 4-channel) - HDR (radiance rgbE format) - PIC (Softimage PIC) - PNM (PPM and PGM binary only) - - Animated GIF still needs a proper API, but here's one way to do it: - http://gist.github.com/urraka/685d9a6340b26b830d49 - - - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - - decode from arbitrary I/O callbacks - - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) - - Full documentation under "DOCUMENTATION" below. - - -LICENSE - - See end of file for license information. - -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 - RGB-format JPEG; remove white matting in PSD; - allocate large structures on the stack; - correct channel count for PNG & BMP - 2.10 (2016-01-22) avoid warning introduced in 2.09 - 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED - - See end of file for full revision history. - - - ============================ Contributors ========================= - - Image formats Extensions, features - Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) - Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) - Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) - Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) - Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) - Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) - Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) - 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) - 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 - - 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. -*/ - -#ifndef STBI_INCLUDE_STB_IMAGE_H - #define STBI_INCLUDE_STB_IMAGE_H - -// DOCUMENTATION -// -// Limitations: -// - no 12-bit-per-channel JPEG -// - no JPEGs with arithmetic coding -// - GIF always returns *comp=4 -// -// Basic usage (see HDR discussion below for HDR usage): -// int x,y,n; -// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); -// // ... 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); -// -// 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 -// -// 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 -// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, -// with each pixel consisting of N interleaved 8-bit components; the first -// pixel pointed to is top-left-most in the image. There is no padding between -// image scanlines or between pixels, regardless of format. The number of -// components N is 'desired_channels' if desired_channels is non-zero, or -// *channels_in_file otherwise. If desired_channels is non-zero, -// *channels_in_file has the number of components that _would_ have been -// output otherwise. E.g. if you set desired_channels to 4, you will always -// get RGBA output, but you can check *channels_in_file to see if it's trivially -// opaque because e.g. there were only 3 channels in the source image. -// -// An output image with N components has the following components interleaved -// in this order in each pixel: -// -// N=#comp components -// 1 grey -// 2 grey, alpha -// 3 red, green, blue -// 4 red, green, blue, alpha -// -// If image loading fails for any reason, the return value will be NULL, -// 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. -// -// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. -// -// To query the width, height and component count of an image without having to -// decode the full file, you can use the stbi_info family of functions: -// -// int x,y,n,ok; -// ok = stbi_info(filename, &x, &y, &n); -// // returns ok=1 and sets x, y, n if image is a supported format, -// // 0 otherwise. -// -// Note that stb_image pervasively uses ints in its public API for sizes, -// including sizes of memory buffers. This is now part of the API and thus -// hard to change without causing breakage. As a result, the various image -// loaders all have certain limits on image size; these differ somewhat -// by format but generally boil down to either just under 2GB or just under -// 1GB. When the decoded image would be larger than this, stb_image decoding -// will fail. -// -// Additionally, stb_image will reject image files that have any of their -// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, -// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, -// the only way to have an image with such dimensions load correctly -// is for it to have a rather extreme aspect ratio. Either way, the -// assumption here is that such larger images are likely to be malformed -// or malicious. If you do need to load an image with individual dimensions -// larger than that, and it still fits in the overall size limit, you can -// #define STBI_MAX_DIMENSIONS on your own to be something larger. -// -// =========================================================================== -// -// UNICODE: -// -// If compiling for Windows and you wish to use Unicode filenames, compile -// with -// #define STBI_WINDOWS_UTF8 -// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert -// Windows wchar_t filenames to utf8. -// -// =========================================================================== -// -// Philosophy -// -// stb libraries are designed with the following priorities: -// -// 1. easy to use -// 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. -// -// Some secondary priorities arise directly from the first two, some of which -// provide more explicit reasons why performance can't be emphasized. -// -// - Portable ("ease of use") -// - Small source code footprint ("easy to maintain") -// - No dependencies ("ease of use") -// -// =========================================================================== -// -// I/O callbacks -// -// I/O callbacks allow you to read from arbitrary sources, like packaged -// files or some other source. Data read from callbacks are processed -// through a small internal buffer (currently 128 bytes) to try to reduce -// 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). -// -// =========================================================================== -// -// SIMD support -// -// The JPEG decoder will try to automatically use SIMD kernels on x86 when -// supported by the compiler. For ARM Neon support, you must explicitly -// request it. -// -// (The old do-it-yourself SIMD API is no longer supported in the current -// code.) -// -// On x86, SSE2 will automatically be used when available based on a run-time -// test; if not, the generic C versions are used as a fall-back. On ARM targets, -// the typical path is to have separate builds for NEON and non-NEON devices -// (at least this is true for iOS and Android). Therefore, the NEON support is -// toggled by a build flag: define STBI_NEON to get NEON loops. -// -// If for some reason you do not want to use any of SIMD code, or if -// you have issues compiling it, you can disable it entirely by -// defining STBI_NO_SIMD. -// -// =========================================================================== -// -// 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: -// -// stbi_hdr_to_ldr_gamma(2.2f); -// stbi_hdr_to_ldr_scale(1.0f); -// -// (note, do not use _inverse_ constants; stbi_image will invert them -// appropriately). -// -// Additionally, there is a new, parallel interface for loading files as -// (linear) floats to preserve the full dynamic range: -// -// float *data = stbi_loadf(filename, &x, &y, &n, 0); -// -// If you load LDR images through this interface, those images will -// be promoted to floating point values, run through the inverse of -// constants corresponding to the above: -// -// stbi_ldr_to_hdr_scale(1.0f); -// stbi_ldr_to_hdr_gamma(2.2f); -// -// Finally, given a filename (or an open file or memory block--see header -// file for details) containing image data, you can query for the "most -// appropriate" interface to use (that is, whether the image is HDR or -// not), using: -// -// stbi_is_hdr(char *filename); -// -// =========================================================================== -// -// iPhone PNG support: -// -// We optionally support converting iPhone-formatted PNGs (which store -// premultiplied BGRA) back to RGB, even though they're internally encoded -// differently. To enable this conversion, call -// stbi_convert_iphone_png_to_rgb(1). -// -// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per -// pixel to remove any premultiplied alpha *only* if the image file explicitly -// says there's premultiplied data (currently only happens in iPhone images, -// and only if iPhone convert-to-rgb processing is on). -// -// =========================================================================== -// -// ADDITIONAL CONFIGURATION -// -// - You can suppress implementation of any of the decoders to reduce -// your code footprint by #defining one or more of the following -// symbols before creating the implementation. -// -// STBI_NO_JPEG -// STBI_NO_PNG -// STBI_NO_BMP -// STBI_NO_PSD -// STBI_NO_TGA -// STBI_NO_GIF -// STBI_NO_HDR -// STBI_NO_PIC -// STBI_NO_PNM (.ppm and .pgm) -// -// - You can request *only* certain decoders and suppress all other ones -// (this will be more forward-compatible, as addition of new decoders -// doesn't require you to disable them explicitly): -// -// STBI_ONLY_JPEG -// STBI_ONLY_PNG -// STBI_ONLY_BMP -// STBI_ONLY_PSD -// STBI_ONLY_TGA -// STBI_ONLY_GIF -// STBI_ONLY_HDR -// STBI_ONLY_PIC -// STBI_ONLY_PNM (.ppm and .pgm) -// -// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still -// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB -// -// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater -// than that size (in either width or height) without further processing. -// This is to let programs in the wild set an upper bound to prevent -// denial-of-service attacks on untrusted data, as one could generate a -// valid image of gigantic dimensions and force stb_image to allocate a -// huge block of memory and spend disproportionate time decoding it. By -// default this is set to (1 << 24), which is 16777216, but that's still -// very big. - - #ifndef STBI_NO_STDIO - #include - #endif // STBI_NO_STDIO - - #define STBI_VERSION 1 - -enum -{ - STBI_default = 0, // only used for desired_channels - - STBI_grey = 1, - STBI_grey_alpha = 2, - STBI_rgb = 3, - STBI_rgb_alpha = 4 -}; - - #include -typedef unsigned char stbi_uc; -typedef unsigned short stbi_us; - - #ifdef __cplusplus -extern "C" -{ - #endif - - #ifndef STBIDEF - #ifdef STB_IMAGE_STATIC - #define STBIDEF static - #else - #define STBIDEF extern - #endif - #endif - - ////////////////////////////////////////////////////////////////////////////// - // - // PRIMARY API - works on images of any type - // - - // - // 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 - } stbi_io_callbacks; - - //////////////////////////////////// - // - // 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); - - #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 - #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); - #endif - - #ifdef STBI_WINDOWS_UTF8 - STBIDEF int stbi_convert_wchar_to_utf8(char* buffer, size_t bufferlen, const wchar_t* input); - #endif - - //////////////////////////////////// - // - // 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); - - #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); - #endif - - //////////////////////////////////// - // - // 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); - - #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 - - #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 - - // 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); - #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 - - // 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); - - // free the loaded image -- this is just free() - 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); - - #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); - #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); - - // 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 - 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); - - // 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); - - #ifdef __cplusplus -} - #endif - -// -// -//// end header file ///////////////////////////////////////////////////// -#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 - #endif - - #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) - #define STBI_NO_ZLIB - #endif - - #include - #include - #include // ptrdiff_t on osx - #include - #include - - #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) - #include // ldexp, pow - #endif - - #ifndef STBI_NO_STDIO - #include - #endif - - #ifndef STBI_ASSERT - #include - #define STBI_ASSERT(x) assert(x) - #endif - - #ifdef __cplusplus - #define STBI_EXTERN extern "C" - #else - #define STBI_EXTERN extern - #endif - - #ifndef _MSC_VER - #ifdef __cplusplus - #define stbi_inline inline - #else - #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 - - #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; - #else - #include -typedef uint16_t stbi__uint16; -typedef int16_t stbi__int16; -typedef uint32_t stbi__uint32; -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]; - - #ifdef _MSC_VER - #define STBI_NOTUSED(v) (void)(v) - #else - #define STBI_NOTUSED(v) (void)sizeof(v) - #endif - - #ifdef _MSC_VER - #define STBI_HAS_LROTL - #endif - - #ifdef STBI_HAS_LROTL - #define stbi_lrot(x, y) _lrotl(x, y) - #else - #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)) - // ok - #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)." - #endif - - #ifndef STBI_MALLOC - #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) - #endif - - // x86/x64 detection - #if defined(__x86_64__) || defined(_M_X64) - #define STBI__X64_TARGET - #elif defined(__i386) || defined(_M_IX86) - #define STBI__X86_TARGET - #endif - - #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 - // detection caused numerous issues. The way architecture extensions are - // exposed in GCC/Clang is, sadly, not really suited for one-file libs. - // New behavior: if compiled with -msse2, we use SSE2 without any - // detection; if not, we don't use it at all. - #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 - // - // 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. - // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not - // simultaneously enabling "-mstackrealign". - // - // 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. - #define STBI_NO_SIMD - #endif - - #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]; -} - #else -static int stbi__cpuid3(void) -{ - int res; - __asm { - mov eax,1 - cpuid - mov res,edx - } - 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; -} - #endif - - #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; -} - #endif - - #endif - #endif - - // ARM NEON - #if defined(STBI_NO_SIMD) && defined(STBI_NEON) - #undef STBI_NEON - #endif - - #ifdef STBI_NEON - #include - #ifdef _MSC_VER - #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name - #else - #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) - #endif - #endif - - #ifndef STBI_SIMD_ALIGN - #define STBI_SIMD_ALIGN(type, name) type name - #endif - - #ifndef STBI_MAX_DIMENSIONS - #define STBI_MAX_DIMENSIONS (1 << 24) - #endif - -/////////////////////////////////////////////// -// -// stbi__context struct and start_xxx functions - -// 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; - - stbi_io_callbacks io; - void* io_user_data; - - 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__context; - -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; -} - -// 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; -} - - #ifndef STBI_NO_STDIO - -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 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 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) { } - - #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; -} - -enum -{ - STBI_ORDER_RGB, - STBI_ORDER_BGR -}; - -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); - #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); - #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); - #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); - #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); - #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); - #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); - #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); - #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); - #endif - -static - #ifdef STBI_THREAD_LOCAL - STBI_THREAD_LOCAL - #endif - const char* 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; -} - #endif - -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 -// current code, even on 64-bit targets, is INT_MAX. this is not a -// significant limitation for the intended use case. -// -// we do, however, need to make sure our size calculations don't -// overflow. hence a few helper functions for size calculations that -// multiply integers together, making sure that they're non-negative -// and no overflow occurs. - -// 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; -} - -// 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; -} - - #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); -} - #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); -} - - // 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); -} - #endif - - #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); -} - #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); -} - - #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); -} - #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 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; -} - -// stbi__err - error -// stbi__errpf - error returning pointer to float -// stbi__errpuc - error returning pointer to unsigned char - - #ifdef STBI_NO_FAILURE_STRINGS - #define stbi__err(x, y) 0 - #elif defined(STBI_FAILURE_USERMSG) - #define stbi__err(x, y) stbi__err(y) - #else - #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)) - -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); - #endif - - #ifndef STBI_NO_HDR -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; -} - - #ifndef STBI_THREAD_LOCAL - #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; - -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 - -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 - - // 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_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"); -} - -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"); - - 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; -} - -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"); - - 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; -} - -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; - } - } -} - - #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; - - 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); - - 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); - - 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 - - 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; -} - -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; - - // 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; - } - - // @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)); - } - - 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)); - } -} - #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); - #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); -} - #endif - -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; - - 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; - #else - f = _wfopen(wFilename, wMode); - #endif - - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != fopen_s(&f, filename, mode)) f = 0; - #else - f = fopen(filename, mode); - #endif - 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_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_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 - -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_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); -} - - #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); - - 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; -} - #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"); -} - -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); -} - - #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_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_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 -} - - #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_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 - -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; - -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; } - -////////////////////////////////////////////////////////////////////////////// -// -// Common code used by all image loaders -// - -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; - } -} - -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) - // 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; - } - - 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) - // 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; -} - #endif - - #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; - - 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; - } - } - - 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) - // nothing - #else -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); -} - #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); -} - #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; -} - #endif - - #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) - // nothing - #else -////////////////////////////////////////////////////////////////////////////// -// -// generic converter from built-in img_n to req_comp -// individual types do this automatically as much as possible (e.g. jpeg -// does all cases internally since it needs to colorspace convert anyway, -// and it never has alpha, so very few cases ). png can automatically -// interleave an alpha=255 channel, but falls back to this for other cases -// -// 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); } - #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) - // 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; - - 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"); - } - - 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 - } - - 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); -} - #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; - - 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"); - } - - 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 - } - - 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; -} - #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; -} - #endif - -////////////////////////////////////////////////////////////////////////////// -// -// "baseline" JPEG/JFIF decoder -// -// simple implementation -// - doesn't support delayed output of y-dimension -// - simple interface (only one output format: 8-bit interleaved RGB) -// - doesn't try to recover corrupt jpegs -// - doesn't allow partial loading, loading multiple at once -// - still fast on x86 (copying globals into locals doesn't help x86) -// - allocates lots of intermediate memory (full size of all components) -// - non-interleaved case requires this anyway -// - allows good upsampling (see next) -// high-quality -// - upsampled channels are bilinearly interpolated, even across blocks -// - quality integer IDCT derived from IJG's 'slow' -// performance -// - fast huffman; reasonable integer IDCT -// - some SIMD kernels for common paths on targets with SSE2/NEON -// - uses a lot of intermediate memory, could cache poorly - - #ifndef STBI_NO_JPEG - - // huffman decoding acceleration - #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' -} 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]; - - // 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; - - 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 - - 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; - - // 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; - - // 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 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]; - - 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); -} - -// (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}; - -// 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; - - 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]; - } - - // 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; - - // 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]; -} - -// 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 - - 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_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}; - -// 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; - - 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])); - - 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 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"); - - 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 (!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"); - - if (j->succ_high == 0) - { - int shift = j->succ_low; - - 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; - } - 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 - - 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; - } - - // 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; -} - - #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; - -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; - } - } - - 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; - - // 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 = 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 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)); \ - } - - // 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) - - #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)); - - // 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)); - - // 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); - - // 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); - } - - // 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); - - // 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 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)); - } - - #undef dct_const - #undef dct_rot - #undef dct_widen - #undef dct_wadd - #undef dct_wsub - #undef dct_bfly32o - #undef dct_interleave8 - #undef dct_interleave16 - #undef dct_pass -} - - #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; - - 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_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) - - // 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) - - // 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) - - // 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_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); - - // add DC bias - row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); - - // column pass - dct_pass(vrshrn_n_s32, 10); - - // 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)); \ - } - - // 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 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); - - { - // 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]); \ - } - - // 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); - - // 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); - - // 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 - #undef dct_widen - #undef dct_wadd - #undef dct_wsub - #undef dct_bfly32o - #undef dct_pass -} - - #endif // STBI_NEON - - #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; -} - - // 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) - -// 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 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; - 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_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; - } - } -} - -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 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 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]; - } - 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; - } - 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; - - 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; - } - - 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; - } - - { - 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; -} - -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; - } - - 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"); - } - - 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"); - - 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"); - } - - // 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); - } - } - - 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__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 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)) 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); - - #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* 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; - - 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]; - - STBI_NOTUSED(in_far); - STBI_NOTUSED(hs); - - return out; -} - - #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; - } - - 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); - - 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; - - 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) - { - #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 - - // 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); - - // 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); - #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 - - // 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); - - // 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]; - } - - 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); - - STBI_NOTUSED(hs); - - 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; -} - - // 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; - } -} - - #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; - - #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 - - 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); - - // 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); - - // 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); - - // 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)); - - 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); - - // 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); - - // 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; - } -} - #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; - - #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; - } - #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; - #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); } - -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* 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"); - - // 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; - - 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; - - // 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}; - - stbi__resample res_comp[4]; - - 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; - } - } - 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; - } - } - 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; - } -} - -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_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; -} - #endif - -// public domain zlib decode v0.2 Sean Barrett 2006-11-18 -// simple implementation -// - all input must be provided in an upfront buffer -// - all output is written to a single output buffer (can malloc/realloc) -// performance -// - fast huffman - - #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 - -// 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]; -} 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__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]; - - // 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; -} - -// zlib-from-memory implementation for PNG reading -// because PNG allows splitting the zlib stream arbitrarily, -// and it's annoying structurally to have PNG call ZLIB call PNG, -// 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; - - char* zout; - char* zout_start; - char* zout_end; - int z_expandable; - - 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 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); -} - -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]; -} - -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 -{ - 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}; - -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_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"); - } - 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; - - 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; - - 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 - { - 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_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}; -/* -Init algorithm: -{ - int i; // use <= to match clearly with spec - for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; - for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; - for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; - for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; - - for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; -} -*/ - -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; - - 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(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 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 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 - -// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 -// simple implementation -// - only 8-bit samples -// - no CRC checking -// - allocates lots of intermediate memory -// - avoids problem of streaming data between subsystems -// - avoids explicit window management -// performance -// - uses stb_zlib, a PD zlib implementation with fast huffman decoding - - #ifndef STBI_NO_PNG -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 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; -} 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 -}; - -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 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]; - } - } -} - -// 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 - - 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"); - - // 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"); - - // 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; - } - - 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; - } - - // 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; - } - - 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 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; - } - } - 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(filter_buf); - if (!all_ok) return 0; - - 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); - } - } - STBI_FREE(a->out); - image_data += img_len; - image_data_len -= img_len; - } - } - a->out = final; - - 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; - - // 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 : 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__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; - - // 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); - - 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; -} - -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; - - p = (stbi_uc*)stbi__malloc_mad2(pixel_count, pal_img_n, 0); - if (p == NULL) return stbi__err("outofmem", "Out of memory"); - - // 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_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 - #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; - -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; -} - - #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; - - 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) - { - 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)) - -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; - - if (!stbi__check_png_header(s)) return 0; - - 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"); - } - // 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; - } - 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 - } - } - 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; - } - 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; - 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 - 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 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(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; -} - #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(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__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]; -} - -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; - - 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; - - 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; -} - -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 - - 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?)"); - - 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.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"); - - 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); - } - } - - // 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; - } - } - } - - 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; -} - #endif - - // Targa Truevision - TGA - // 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_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__rewind(s); - return 0; // only RGB or indexed allowed - } - 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__rewind(s); - return 0; - } - 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)) - { - stbi__rewind(s); - return 0; // only RGB or grey allowed, +/- RLE - } - 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) - { - stbi__rewind(s); - return 0; // test width - } - tga_h = stbi__get16le(s); - if (tga_h < 1) - { - stbi__rewind(s); - return 0; // test height - } - 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 - 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); - } - 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 -} - -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 - -errorEnd: - 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); - - // 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 - - 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); - - // 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"); - - // 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"); - - 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); - - 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; - } - } - 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_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); - } - 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]; - - // 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); - } - } - - // 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); - - // 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 - - #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_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--; - } - } - } - - 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); - - // 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"); - - // 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 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?)"); - - // 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"); - - // 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 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"); - - // Check size - if (!stbi__mad3sizes_valid(4, w, h, 0)) return stbi__errpuc("too large", "Corrupt PSD"); - - // 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 (!out) return stbi__errpuc("outofmem", "Out of memory"); - pixelCount = w * h; - - // 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 - - // 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; - - 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; - } - else - { - stbi_uc* p = out + channel; - stbi_uc val = channel == 3 ? 255 : 0; - for (i = 0; i < pixelCount; i++, p += 4) - *p = val; - } - } - 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 - { - 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); - } - } - } - 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 - } - - if (comp) *comp = 4; - *y = h; - *x = w; - - return out; -} - #endif - -// ************************************************************************************************* -// Softimage PIC loader -// by Tom Seddon -// -// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format -// 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; - - return 1; -} - -static int stbi__pic_test_core(stbi__context* s) -{ - int i; - - if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) return 0; - - for (i = 0; i < 84; ++i) - stbi__get8(s); - - if (!stbi__pic_is4(s, "PICT")) return 0; - - return 1; -} - -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; - - 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; -} - -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]; -} - -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 - // for the same channel in multiple packets. - do - { - stbi__pic_packet* packet; - - if (num_packets == sizeof(packets) / sizeof(packets[0])) return stbi__errpuc("bad format", "too many packets"); - - 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)) 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? - - for (y = 0; y < height; ++y) - { - int packet_idx; - - for (packet_idx = 0; packet_idx < num_packets; ++packet_idx) - { - stbi__pic_packet* packet = &packets[packet_idx]; - stbi_uc* dest = result + y * width * 4; - - switch (packet->type) - { - default: - return stbi__errpuc("bad format", "packet has bad compression type"); - - case 0: - { //uncompressed - int x; - - 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; - } - } - } - } - - 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); - - if (!comp) comp = &internal_comp; - - for (i = 0; i < 92; ++i) - stbi__get8(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 (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' - - // 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); - - return result; -} - -static int stbi__pic_test(stbi__context* s) -{ - int r = stbi__pic_test_core(s); - stbi__rewind(s); - return r; -} - #endif - -// ************************************************************************************************* -// 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; -} 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; -} 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(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 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"); - - 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 (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 (g->flags & 0x80) stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -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 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); - - if (g->cur_y >= g->max_y) return; - - 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; - - 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; - } - } -} - -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; - } - - // 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"); - } - - 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"); - - stbi__out_gif_code(g, (stbi__uint16)code); - - 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; - } - 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; - } - - 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); - - if (out) STBI_FREE(out); - if (delays && *delays) STBI_FREE(*delays); - 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; - - 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 - - // ************************************************************************************************* - // 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(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'; - - 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; -} - -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); - - // 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; - } - - 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); - - 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; - - 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"); - - // 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"); - } - } - - 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; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - 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; - } - - 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 - - #ifndef STBI_NO_BMP -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; -} - #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_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]; - - 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; - } - - 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; - } - - stbi__skip(s, 8); - - do - { - stbi__pic_packet* packet; - - 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; - - 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); - - return 1; -} - #endif - -// ************************************************************************************************* -// Portable Gray Map and Portable Pixel Map loader -// by Ken Miller -// -// PGM: http://netpbm.sourceforge.net/doc/pgm.html -// PPM: http://netpbm.sourceforge.net/doc/ppm.html -// -// Known limitations: -// Does not support comments in the header section -// Does not support ASCII image data (formats P2 and P3) - - #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 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; - - 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; - - 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"); - } - - 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 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; - - 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_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_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; -} - #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_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_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_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 - - // 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 - - #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_STDIO -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); - fclose(f); - 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_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); - fclose(f); - 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; -} - #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_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_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 - -/* - 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 - 1-bit BMP - *_is_16_bit api - avoid warnings - 2.16 (2017-07-23) all functions have 16-bit variants; - STBI_NO_STDIO works again; - compilation fixes; - fix rounding in unpremultiply; - optimize vertical flip; - disable raw_len validation; - documentation fixes - 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; - 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 - 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 - 2.09 (2016-01-16) allow comments in PNM files - 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 - limited 16-bpc PSD support - #ifdef unused functions - bug with < 92 byte PIC,PNM,HDR,TGA - 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value - 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning - 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit - 2.03 (2015-04-12) extra corruption checking (mmozeiko) - 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 - 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) - various warning fixes from Ronny Chevalier - 1.43 (2014-07-15) - fix MSVC-only compiler problem in code changed in 1.42 - 1.42 (2014-07-09) - don't define _CRT_SECURE_NO_WARNINGS (affects user code) - 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) - 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 - 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) - 1.13 threadsafe - 1.12 const qualifiers in the API - 1.11 Support installable IDCT, colorspace conversion routines - 1.10 Fixes for 64-bit (don't use "unsigned long") - optimized upsampling by Fabian "ryg" Giesen - 1.09 Fix format-conversion for PSD code (bad global variables!) - 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) - 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 - 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same - 0.93 handle jpegtran output; verbose errors - 0.92 read 4,8,16,24,32-bit BMP files of several formats - 0.91 output 24-bit Windows 3.0 BMP files - 0.90 fix a few more warnings; bump version number to approach 1.0 - 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd - 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.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 - 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments - 0.51 obey req_comp requests, 1-component jpegs return as 1-component, - on 'test' only check type, not whether we support this variant - 0.50 (2006-11-19) - first released version -*/ - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ \ No newline at end of file diff --git a/src/canvas.cpp b/src/canvas.cpp index ad10ef7..8384c50 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -1,8 +1,14 @@ -#include "canvas.h" +#include "canvas.hpp" #include +#include + +#include "util/imgui.hpp" +#include "util/math.hpp" + using namespace glm; using namespace game::resource; +using namespace game::util; namespace game { @@ -13,16 +19,16 @@ namespace game GLuint Canvas::rectVBO = 0; bool Canvas::isStaticInit = false; - Canvas::Canvas(vec2 size, bool isDefault) + Canvas::Canvas(ivec2 size, Flags flags) { this->size = size; + this->flags = flags; - if (isDefault) + if ((flags & DEFAULT) != 0) { fbo = 0; rbo = 0; texture = 0; - this->isDefault = true; } else { @@ -69,7 +75,6 @@ namespace game glBindVertexArray(0); - // Rect glGenVertexArrays(1, &rectVAO); glGenBuffers(1, &rectVBO); @@ -82,12 +87,47 @@ namespace game glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0); glBindVertexArray(0); + + isStaticInit = true; } } + Canvas::Canvas(const Canvas& other) : Canvas(other.size, other.flags) + { + pan = other.pan; + zoom = other.zoom; + + if ((flags & DEFAULT) == 0 && (other.flags & DEFAULT) == 0) + { + glBindFramebuffer(GL_READ_FRAMEBUFFER, other.fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); + glBlitFramebuffer(0, 0, other.size.x, other.size.y, 0, 0, size.x, size.y, GL_COLOR_BUFFER_BIT, GL_NEAREST); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + } + } + + Canvas::Canvas(Canvas&& other) noexcept + { + size = other.size; + pan = other.pan; + zoom = other.zoom; + flags = other.flags; + fbo = other.fbo; + rbo = other.rbo; + texture = other.texture; + + other.size = {}; + other.pan = {}; + other.zoom = 100.0f; + other.flags = FLIP; + other.fbo = 0; + other.rbo = 0; + other.texture = 0; + } + Canvas::~Canvas() { - if (!isDefault) + if ((flags & DEFAULT) == 0) { if (fbo) glDeleteFramebuffers(1, &fbo); if (rbo) glDeleteRenderbuffers(1, &rbo); @@ -95,15 +135,66 @@ namespace game } } - mat4 Canvas::view_get() const { return mat4{1.0f}; } - mat4 Canvas::projection_get() const + Canvas& Canvas::operator=(const Canvas& other) { - if (isDefault) return glm::ortho(0.0f, (float)size.x, (float)size.y, 0.0f, -1.0f, 1.0f); - return glm::ortho(0.0f, (float)size.x, 0.0f, (float)size.y, -1.0f, 1.0f); + if (this == &other) return *this; + Canvas tmp(other); + *this = std::move(tmp); + return *this; } - void Canvas::texture_render(Shader& shader, GLuint textureId, mat4& model, vec4 tint, vec3 colorOffset, - float* vertices) const + Canvas& Canvas::operator=(Canvas&& other) noexcept + { + if (this == &other) return *this; + + if ((flags & DEFAULT) == 0) + { + if (fbo) glDeleteFramebuffers(1, &fbo); + if (rbo) glDeleteRenderbuffers(1, &rbo); + if (texture) glDeleteTextures(1, &texture); + } + + size = other.size; + pan = other.pan; + zoom = other.zoom; + flags = other.flags; + fbo = other.fbo; + rbo = other.rbo; + texture = other.texture; + + other.size = {}; + other.pan = {}; + other.zoom = 100.0f; + other.flags = FLIP; + other.fbo = 0; + other.rbo = 0; + other.texture = 0; + + return *this; + } + + mat4 Canvas::view_get() const + { + auto view = mat4{1.0f}; + auto zoomFactor = math::to_unit(zoom); + auto panFactor = pan * zoomFactor; + + view = glm::translate(view, vec3(-panFactor, 0.0f)); + view = glm::scale(view, vec3(zoomFactor, zoomFactor, 1.0f)); + + return view; + } + mat4 Canvas::projection_get() const + { + if ((flags & FLIP) != 0) + { + return glm::ortho(0.0f, (float)size.x, 0.0f, (float)size.y, -1.0f, 1.0f); + } + return glm::ortho(0.0f, (float)size.x, (float)size.y, 0.0f, -1.0f, 1.0f); + } + + void Canvas::texture_render(Shader& shader, GLuint textureID, mat4 model, vec4 tint, vec3 colorOffset, + const float* vertices) const { glUseProgram(shader.id); @@ -122,7 +213,7 @@ namespace game glBufferData(GL_ARRAY_BUFFER, sizeof(TEXTURE_VERTICES), vertices, GL_DYNAMIC_DRAW); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, textureId); + glBindTexture(GL_TEXTURE_2D, textureID); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); @@ -156,14 +247,30 @@ namespace game texture_render(shader, texture, model, tint, colorOffset); } - void Canvas::bind() const + void Canvas::bind() { glBindFramebuffer(GL_FRAMEBUFFER, fbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); + } + + void Canvas::size_set(ivec2 size) + { + if ((flags & DEFAULT) == 0 && (size.x != this->size.x || size.y != this->size.y)) + { + glBindTexture(GL_TEXTURE_2D, texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); + glBindTexture(GL_TEXTURE_2D, 0); + + glBindRenderbuffer(GL_RENDERBUFFER, rbo); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, size.x, size.y); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + } + + this->size = size; glViewport(0, 0, size.x, size.y); } - void Canvas::clear(vec4 color) const + void Canvas::clear(vec4 color) { glClearColor(color.r, color.g, color.b, color.a); glClear(GL_COLOR_BUFFER_BIT); @@ -175,5 +282,14 @@ namespace game glBindFramebuffer(GL_FRAMEBUFFER, 0); } - bool Canvas::is_valid() const { return fbo != 0 || isDefault; }; + bool Canvas::is_valid() const { return (flags & DEFAULT) != 0 || fbo != 0; }; + + glm::vec2 Canvas::screen_position_convert(glm::vec2 position) const + { + auto viewport = ImGui::GetMainViewport(); + auto viewportPos = imgui::to_vec2(viewport->Pos); + auto localPosition = position - viewportPos; + auto zoomFactor = math::to_unit(zoom); + return pan + (localPosition / zoomFactor); + } } diff --git a/src/canvas.hpp b/src/canvas.hpp index 4707db6..8c4ef53 100644 --- a/src/canvas.hpp +++ b/src/canvas.hpp @@ -6,7 +6,7 @@ #include #endif -#include "resource/shader.h" +#include "resource/shader.hpp" #include #include #include @@ -30,27 +30,45 @@ namespace game static bool isStaticInit; public: + static constexpr glm::vec4 CLEAR_COLOR = {0, 0, 0, 0}; + + enum Flag + { + DEFAULT = (1 << 0), + FLIP = (1 << 1) + }; + + using Flags = int; + GLuint fbo{}; GLuint rbo{}; GLuint texture{}; - glm::vec2 size{}; - - bool isDefault{}; + glm::ivec2 size{}; + glm::vec2 pan{}; + float zoom{100.0f}; + Flags flags{FLIP}; Canvas() = default; - Canvas(glm::vec2, bool isDefault = false); + Canvas(glm::ivec2, Flags = FLIP); + Canvas(const Canvas&); + Canvas(Canvas&&) noexcept; ~Canvas(); + Canvas& operator=(const Canvas&); + Canvas& operator=(Canvas&&) noexcept; glm::mat4 transform_get() const; glm::mat4 view_get() const; glm::mat4 projection_get() const; - void texture_render(resource::Shader&, GLuint, glm::mat4&, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}, - float* = (float*)TEXTURE_VERTICES) const; + void texture_render(resource::Shader&, GLuint, glm::mat4, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}, + const float* = TEXTURE_VERTICES) const; + void texture_render(resource::Shader&, const Canvas&, glm::mat4, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}) const; void rect_render(resource::Shader&, glm::mat4&, glm::vec4 = glm::vec4(0, 0, 1, 1)) const; void render(resource::Shader&, glm::mat4&, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}) const; - void bind() const; + void bind(); + void size_set(glm::ivec2 size); + void clear(glm::vec4 color = CLEAR_COLOR); void unbind() const; - void clear(glm::vec4 color = glm::vec4(0, 0, 0, 1)) const; bool is_valid() const; + glm::vec2 screen_position_convert(glm::vec2 position) const; }; } diff --git a/src/character.cpp b/src/character.cpp deleted file mode 100644 index 657202c..0000000 --- a/src/character.cpp +++ /dev/null @@ -1,273 +0,0 @@ -#include "character.h" - -#include - -#include "types.h" -#include "util/math_.h" - -using namespace game::util; -using namespace game::anm2; -using namespace glm; - -namespace game -{ - float Character::max_capacity() { return capacity * CAPACITY_OVERSTUFFED_LIMIT_MULTIPLIER; } - - float Character::over_capacity_calories_get() - { - if (calories < capacity) return 0.0f; - return (calories - capacity); - } - float Character::over_capacity_percent_get() - { - if (calories < capacity) return 0.0f; - return (calories - capacity) / (max_capacity() - capacity); - } - - float Character::digestion_rate_second_get() { return digestionRate * 60; } - - bool Character::is_over_capacity() { return calories + 1 >= capacity; } - bool Character::is_max_capacity() { return calories >= max_capacity(); } - - void Character::talk() - { - if (auto talkItem = item_get(anm2::LAYER, talkLayerID)) - { - talkOverride = {.animationIndex = animationIndex, - .sourceID = talkLayerID, - .destinationID = mouthLayerID, - .length = (float)item_length(talkItem), - .isLoop = true}; - } - else - talkOverride.isEnabled = false; - } - - void Character::blink() - { - if (auto blinkItem = item_get(anm2::LAYER, blinkLayerID)) - { - blinkOverride = {.animationIndex = animationIndex, - .sourceID = blinkLayerID, - .destinationID = headLayerID, - .length = (float)item_length(blinkItem)}; - } - else - blinkOverride.isEnabled = false; - } - - float Character::weight_get(MeasurementSystem system) { return system == IMPERIAL ? weight * KG_TO_LB : weight; } - - float Character::weight_threshold_get(int stage, MeasurementSystem system) - { - stage = glm::clamp(stage, 0, WEIGHT_STAGE_MAX); - return system == IMPERIAL ? WEIGHT_THRESHOLDS[stage] * KG_TO_LB : WEIGHT_THRESHOLDS[stage]; - } - - float Character::weight_threshold_current_get(MeasurementSystem system) - { - return weight_threshold_get(weightStage, system); - } - - float Character::weight_threshold_next_get(MeasurementSystem system) - { - auto nextStage = glm::clamp(0, weightStage + 1, WEIGHT_STAGE_MAX); - return weight_threshold_get(nextStage, system); - } - - float Character::progress_to_next_weight_threshold_get() - { - if (weightStage >= WEIGHT_STAGE_MAX - 1) return 0.0f; - return (weight - weight_threshold_current_get()) / (weight_threshold_next_get() - weight_threshold_current_get()); - } - - vec4 Character::mouth_rect_get() { return null_frame_rect(mouthNullID); } - vec4 Character::head_rect_get() { return null_frame_rect(headNullID); } - vec4 Character::belly_rect_get() { return null_frame_rect(bellyNullID); } - vec4 Character::tail_rect_get() { return null_frame_rect(tailNullID); } - - Character::Character(Anm2* _anm2, glm::ivec2 _position) : Actor(_anm2, _position) - { - talkLayerID = item_id_get(LAYER_TALK); - blinkLayerID = item_id_get(LAYER_BLINK); - headLayerID = item_id_get(LAYER_HEAD); - mouthLayerID = item_id_get(LAYER_MOUTH); - torsoLayerID = item_id_get(LAYER_TORSO); - tailLayerID = item_id_get(LAYER_TAIL); - - mouthNullID = item_id_get(NULL_MOUTH, anm2::NULL_); - headNullID = item_id_get(NULL_HEAD, anm2::NULL_); - bellyNullID = item_id_get(NULL_BELLY, anm2::NULL_); - tailNullID = item_id_get(NULL_TAIL, anm2::NULL_); - - torsoCapacityScale = {.destinationID = torsoLayerID, .mode = Override::FRAME_ADD}; - tailCapacityScale = {.destinationID = tailLayerID, .mode = Override::FRAME_ADD}; - torsoCapacityScale.frame.scale = glm::vec2(); - tailCapacityScale.frame.scale = glm::vec2(); - - overrides.emplace_back(&talkOverride); - overrides.emplace_back(&blinkOverride); - overrides.emplace_back(&torsoCapacityScale); - overrides.emplace_back(&tailCapacityScale); - } - - void Character::digestion_start() - { - isDigesting = true; - digestionTimer = DIGESTION_TIMER_MAX; - isJustDigestionStart = true; - } - - void Character::digestion_end() - { - auto increment = calories * CALORIE_TO_KG; - weight += increment; - totalWeightGained += increment; - isForceStageUp = false; - - if (is_over_capacity()) capacity += over_capacity_percent_get() * capacity * CAPACITY_OVER_BONUS; - - calories = 0; - digestionProgress = 0; - digestionTimer = 0; - digestionCount++; - isDigesting = false; - isJustDigestionEnd = true; - } - - void Character::tick() - { - Actor::tick(); - - isJustDigestionStart = false; - isJustDigestionEnd = false; - isJustStageUp = false; - isJustFinalThreshold = false; - - auto animation = animation_get(); - if (animation && !animation->isLoop && !isPlaying) - { - if (state == APPEAR) isJustAppeared = true; - if (state == STAGE_UP && weightStage == WEIGHT_STAGE_MAX - 1 && !isForceStageUp) isJustFinalThreshold = true; - state_set(IDLE, true); - } - - if (isDigesting) - { - digestionTimer--; - if (digestionTimer <= 0) digestion_end(); - } - else if (calories > 0) - { - digestionProgress += digestionRate; - if (digestionProgress >= DIGESTION_MAX) digestion_start(); - } - - if (math::random_percent_roll(BLINK_CHANCE)) blink(); - - auto progress = calories / max_capacity(); - auto weightPercent = progress_to_next_weight_threshold_get(); - auto capacityPercent = isDigesting ? ((float)digestionTimer / DIGESTION_TIMER_MAX) * progress : progress; - auto scaleBonus = - vec2(glm::min(SCALE_BONUS_MAX * ((capacityPercent * 0.5f) + (weightPercent * 0.5f)), SCALE_BONUS_MAX)); - - torsoCapacityScale.frame.scale = glm::max(vec2(), scaleBonus); - tailCapacityScale.frame.scale = glm::max(vec2(), scaleBonus); - - if (!isForceStageUp) - { - for (int i = 0; i < WEIGHT_STAGE_MAX; i++) - { - if (weight >= WEIGHT_THRESHOLDS[i]) - { - if (i == previousWeightStage + 1) - { - state_set(STAGE_UP); - isJustStageUp = true; - weightStage = i; - break; - } - } - else if (weight < WEIGHT_THRESHOLDS[i]) - break; - } - } - - if (weight > highestWeight) highestWeight = weight; - - previousWeightStage = weightStage; - } - - std::string Character::animation_name_convert(const std::string& name) - { - return std::format("{}{}", name, weightStage); - } - - void Character::state_set(State state, bool isForce) - { - if (this->state == state && !isForce) return; - this->state = state; - AnimationType type{ANIMATION_NEUTRAL}; - auto speedMultiplier = 1.0f; - - switch (this->state) - { - case IDLE: - if (is_over_capacity()) - type = ANIMATION_NEUTRAL_FULL; - else - type = ANIMATION_NEUTRAL; - break; - case EAGER: - type = ANIMATION_EAGER; - break; - case CRY: - type = ANIMATION_CRY; - break; - case SHOCKED: - type = ANIMATION_SHOCKED; - break; - case EAT: - type = ANIMATION_EAT; - speedMultiplier = eatSpeedMultiplier; - break; - case ANGRY: - type = ANIMATION_ANGRY; - break; - case PAT: - type = ANIMATION_PAT; - break; - case BURP_SMALL: - type = ANIMATION_BURP_SMALL; - break; - case BURP_BIG: - type = ANIMATION_BURP_BIG; - break; - case HEAD_RUB: - if (is_over_capacity()) - type = ANIMATION_HEAD_RUB_FULL; - else - type = ANIMATION_HEAD_RUB; - break; - case BELLY_RUB: - if (is_over_capacity()) - type = ANIMATION_BELLY_RUB_FULL; - else - type = ANIMATION_BELLY_RUB; - break; - case TAIL_RUB: - if (is_over_capacity()) - type = ANIMATION_TAIL_RUB_FULL; - else - type = ANIMATION_TAIL_RUB; - break; - case STAGE_UP: - type = ANIMATION_STAGE_UP; - break; - default: - break; - }; - - play(animation_name_convert(ANIMATIONS[type]), PLAY, 0.0f, speedMultiplier); - } -} \ No newline at end of file diff --git a/src/character.hpp b/src/character.hpp deleted file mode 100644 index a1476d9..0000000 --- a/src/character.hpp +++ /dev/null @@ -1,185 +0,0 @@ -#pragma once - -#include "resource/actor.h" -#include "types.h" - -namespace game -{ - class Character : public resource::Actor - { - public: - static constexpr auto LAYER_TAIL = "Tail"; - static constexpr auto LAYER_TORSO = "Torso"; - static constexpr auto LAYER_HEAD = "Head"; - static constexpr auto LAYER_MOUTH = "Mouth"; - static constexpr auto LAYER_TALK = "Talk"; - static constexpr auto LAYER_BLINK = "Blink"; - - static constexpr auto NULL_MOUTH = "Mouth"; - static constexpr auto NULL_HEAD = "Head"; - static constexpr auto NULL_BELLY = "Belly"; - static constexpr auto NULL_TAIL = "Tail"; - - static constexpr auto EVENT_EAT = "Eat"; - - static constexpr auto BLINK_CHANCE = 0.5f; - - static constexpr auto PAT_CHANCE = 25.0f; - static constexpr auto BURP_SMALL_CHANCE = 20.0f; - static constexpr auto BURP_BIG_CHANCE = 10.0f; - - static constexpr auto GURGLE_CHANCE = 0.1f; - static constexpr auto GURGLE_CHANCE_BONUS = 0.3f; - - static constexpr auto CAPACITY_BASE = 500.0f; - - static constexpr auto CALORIE_TO_KG = 1.0 / 1000.0f; - static constexpr auto CAPACITY_OVERSTUFFED_LIMIT_MULTIPLIER = 1.5f; - - static constexpr auto SCALE_BONUS_MAX = 10.0f; - - static constexpr auto PAT_LENGTH = 5; - static constexpr auto PAT_SCALE_RANGE = 5; - - static constexpr auto EAT_SPEED_MULTIPLIER_MIN = 1.0f; - static constexpr auto EAT_SPEED_MULTIPLIER_MAX = 3.0f; - - static constexpr auto DIGESTION_RATE_MIN = 0.00f; - static constexpr auto DIGESTION_RATE_MAX = 0.25f; - static constexpr auto DIGESTION_RATE_BASE = 0.05f; - static constexpr auto DIGESTION_MAX = 100.0f; - static constexpr auto DIGESTION_TIMER_MAX = 60; - static constexpr auto DIGESTION_RUB_BONUS = 0.01f; - - static constexpr auto CAPACITY_OVER_BONUS = 0.1f; - - static constexpr auto WEIGHT_STAGE_MAX = 5; - - static constexpr float WEIGHT_THRESHOLDS[] = { - 8.1f, 15.0f, 30.0f, 50.0f, 75.0f, - }; - - static constexpr auto MOUTH_SIZE = glm::vec2(50.0f, 50.0f); - - enum State - { - APPEAR, - IDLE, - EAGER, - SHOCKED, - EAT, - CRY, - ANGRY, - BURP_SMALL, - BURP_BIG, - PAT, - HEAD_RUB, - BELLY_RUB, - TAIL_RUB, - STAGE_UP - }; - -#define ANIMATIONS_LIST \ - X(ANIMATION_NEUTRAL, "Neutral") \ - X(ANIMATION_NEUTRAL_FULL, "NeutralFull") \ - X(ANIMATION_SHOCKED, "Shocked") \ - X(ANIMATION_EAT, "Eat") \ - X(ANIMATION_ANGRY, "Angry") \ - X(ANIMATION_EAGER, "Eager") \ - X(ANIMATION_CRY, "Cry") \ - X(ANIMATION_PAT, "Pat") \ - X(ANIMATION_BURP_SMALL, "BurpSmall") \ - X(ANIMATION_BURP_BIG, "BurpBig") \ - X(ANIMATION_HEAD_RUB, "HeadRub") \ - X(ANIMATION_HEAD_RUB_FULL, "HeadRubFull") \ - X(ANIMATION_BELLY_RUB, "BellyRub") \ - X(ANIMATION_BELLY_RUB_FULL, "BellyRubFull") \ - X(ANIMATION_TAIL_RUB, "TailRub") \ - X(ANIMATION_TAIL_RUB_FULL, "TailRubFull") \ - X(ANIMATION_STAGE_UP, "StageUp") - - enum AnimationType - { -#define X(symbol, string) symbol, - ANIMATIONS_LIST -#undef X - }; - - static constexpr const char* ANIMATIONS[] = { -#define X(symbol, string) string, - ANIMATIONS_LIST -#undef X - }; - - float weight{WEIGHT_THRESHOLDS[0]}; - int weightStage{0}; - int previousWeightStage{0}; - float highestWeight{}; - float calories{}; - float capacity{CAPACITY_BASE}; - float digestionProgress{}; - float digestionRate{DIGESTION_RATE_BASE}; - - float totalWeightGained{}; - float totalCaloriesConsumed{}; - int foodItemsEaten{}; - int digestionCount{}; - - bool isJustDigestionStart{}; - bool isJustDigestionEnd{}; - bool isJustStageUp{}; - bool isForceStageUp{}; - bool isJustFinalThreshold{}; - bool isFinalThresholdReached{}; - bool isDigesting{}; - bool isJustAppeared{}; - int digestionTimer{}; - - int blinkLayerID{-1}; - int headLayerID{-1}; - int tailLayerID{-1}; - int talkLayerID{-1}; - int mouthLayerID{-1}; - int torsoLayerID{-1}; - - int mouthNullID{-1}; - int headNullID{-1}; - int bellyNullID{-1}; - int tailNullID{-1}; - - bool isFinishedFood{}; - - float eatSpeedMultiplier{EAT_SPEED_MULTIPLIER_MIN}; - - State state{APPEAR}; - - Override blinkOverride{}; - Override talkOverride{}; - Override torsoCapacityScale{}; - Override tailCapacityScale{}; - - Character(anm2::Anm2*, glm::ivec2); - void talk(); - void blink(); - void tick(); - void digestion_start(); - void digestion_end(); - void state_set(State, bool = false); - glm::vec4 mouth_rect_get(); - glm::vec4 belly_rect_get(); - glm::vec4 head_rect_get(); - glm::vec4 tail_rect_get(); - float weight_get(MeasurementSystem = METRIC); - float weight_threshold_get(int, MeasurementSystem = METRIC); - float weight_threshold_current_get(MeasurementSystem = METRIC); - float weight_threshold_next_get(MeasurementSystem = METRIC); - float progress_to_next_weight_threshold_get(); - float over_capacity_percent_get(); - float over_capacity_calories_get(); - float digestion_rate_second_get(); - bool is_max_capacity(); - bool is_over_capacity(); - float max_capacity(); - std::string animation_name_convert(const std::string&); - }; -} diff --git a/src/cursor.cpp b/src/cursor.cpp deleted file mode 100644 index fb5f82a..0000000 --- a/src/cursor.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "cursor.h" - -#include "util/imgui_.h" - -using namespace game::util; -using namespace game::anm2; -using namespace glm; - -namespace game -{ - Cursor::Cursor(Anm2* anm2) : Actor(anm2, glm::vec2()) {} - void Cursor::update() { position = imgui::to_vec2(ImGui::GetMousePos()); } -} \ No newline at end of file diff --git a/src/cursor.hpp b/src/cursor.hpp deleted file mode 100644 index be2bbed..0000000 --- a/src/cursor.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "resource/actor.h" - -namespace game -{ - class Cursor : public resource::Actor - { - - public: - static constexpr const char* ANIMATION_DEFAULT = "Default"; - static constexpr const char* ANIMATION_HOVER = "Hover"; - static constexpr const char* ANIMATION_GRAB = "Grab"; - static constexpr const char* ANIMATION_RUB = "Rub"; - - Cursor(anm2::Anm2* anm2); - void update(); - }; -} \ No newline at end of file diff --git a/src/entity/actor.cpp b/src/entity/actor.cpp new file mode 100644 index 0000000..b7b00e6 --- /dev/null +++ b/src/entity/actor.cpp @@ -0,0 +1,450 @@ +#include "actor.hpp" + +#include "../util/map.hpp" +#include "../util/math.hpp" +#include "../util/unordered_map.hpp" +#include "../util/vector.hpp" + +#include +#include + +#include "../log.hpp" + +#include + +using namespace glm; +using namespace game::util; +using namespace game::resource::xml; + +namespace game::entity +{ + Actor::Override::Override(int _id, Anm2::Type _type, Actor::Override::Mode _mode, FrameOptional _frame, + std::optional _time, Actor::Override::Function _function, float _cycles) + : id(_id), type(_type), mode(_mode), frame(_frame), time(_time), function(_function), cycles(_cycles) + { + frameBase = _frame; + timeStart = _time; + } + + Actor::Actor(const Actor&) = default; + Actor::Actor(Actor&&) noexcept = default; + Actor& Actor::operator=(const Actor&) = default; + Actor& Actor::operator=(Actor&&) noexcept = default; + + Actor::Actor(Anm2 _anm2, vec2 _position, Mode mode, float time, int animationIndex) : Anm2(_anm2), position(_position) + { + this->mode = mode; + this->startTime = time; + if (animationIndex != -1) + play(animationIndex, mode, time); + else + play_default_animation(mode, time); + } + + Anm2::Animation* Actor::animation_get(int index) + { + if (index == -1) index = animationIndex; + if (animationMapReverse.contains(index)) return &animations[index]; + return nullptr; + } + + Anm2::Animation* Actor::animation_get(const std::string& name) + { + if (animationMap.contains(name)) return &animations[animationMap[name]]; + return nullptr; + } + + bool Actor::is_playing(const std::string& name) + { + if (name.empty()) + return state == PLAYING; + else + return state == PLAYING && animationMap[name] == animationIndex; + } + + int Actor::animation_index_get(const std::string& name) + { + if (animationMap.contains(name)) return animationMap[name]; + return -1; + } + + Anm2::Item* Actor::item_get(Anm2::Type type, int id, int animationIndex) + { + if (animationIndex == -1) animationIndex = this->animationIndex; + if (auto animation = animation_get(animationIndex)) + { + switch (type) + { + case Anm2::ROOT: + return &animation->rootAnimation; + break; + case Anm2::LAYER: + return unordered_map::find(animation->layerAnimations, id); + case Anm2::NULL_: + return map::find(animation->nullAnimations, id); + break; + case Anm2::TRIGGER: + return &animation->triggers; + default: + return nullptr; + } + } + + return nullptr; + } + + int Actor::item_length(Anm2::Item* item) + { + if (!item) return -1; + + int duration{}; + for (auto& frame : item->frames) + duration += frame.duration; + return duration; + } + + Anm2::Frame Actor::frame_generate(Anm2::Item& item, float time, Anm2::Type type, int id) + { + Anm2::Frame frame{}; + frame.isVisible = false; + + if (item.frames.empty()) return frame; + + time = time < 0.0f ? 0.0f : time; + + Anm2::Frame* frameNext = nullptr; + Anm2::Frame frameNextCopy{}; + int durationCurrent = 0; + int durationNext = 0; + + for (int i = 0; i < (int)item.frames.size(); i++) + { + Anm2::Frame& checkFrame = item.frames[i]; + + frame = checkFrame; + + durationNext += frame.duration; + + if (time >= durationCurrent && time < durationNext) + { + if (i + 1 < (int)item.frames.size()) + { + frameNext = &item.frames[i + 1]; + frameNextCopy = *frameNext; + } + else + frameNext = nullptr; + break; + } + + durationCurrent += frame.duration; + } + + auto override_handle = [&](Anm2::Frame& overrideFrame) + { + for (auto& override : overrides) + { + if (override.type != type) continue; + if (override.id != id) continue; + + auto& source = override.frame; + + switch (override.mode) + { + case Override::SET: + if (source.position.has_value()) overrideFrame.position = *source.position; + if (source.pivot.has_value()) overrideFrame.pivot = *source.pivot; + if (source.size.has_value()) overrideFrame.size = *source.size; + if (source.scale.has_value()) overrideFrame.scale = *source.scale; + if (source.crop.has_value()) overrideFrame.crop = *source.crop; + if (source.rotation.has_value()) overrideFrame.rotation = *source.rotation; + if (source.tint.has_value()) overrideFrame.tint = *source.tint; + if (source.colorOffset.has_value()) overrideFrame.colorOffset = *source.colorOffset; + if (source.isInterpolated.has_value()) overrideFrame.isInterpolated = *source.isInterpolated; + if (source.isVisible.has_value()) overrideFrame.isVisible = *source.isVisible; + break; + case Override::ADD: + if (source.scale.has_value()) overrideFrame.scale += *source.scale; + break; + default: + break; + } + } + }; + + override_handle(frame); + if (frameNext) override_handle(frameNextCopy); + + if (frame.isInterpolated && frameNext && frame.duration > 1) + { + auto interpolation = (time - durationCurrent) / (durationNext - durationCurrent); + + frame.rotation = glm::mix(frame.rotation, frameNextCopy.rotation, interpolation); + frame.position = glm::mix(frame.position, frameNextCopy.position, interpolation); + frame.scale = glm::mix(frame.scale, frameNextCopy.scale, interpolation); + frame.colorOffset = glm::mix(frame.colorOffset, frameNextCopy.colorOffset, interpolation); + frame.tint = glm::mix(frame.tint, frameNextCopy.tint, interpolation); + } + + return frame; + } + + void Actor::play(int index, Mode mode, float time, float speedMultiplier) + { + if (!vector::in_bounds(animations, index)) return; + if (mode != PLAY_FORCE && index == animationIndex) return; + + this->playedEventID = -1; + this->playedTriggers.clear(); + + this->speedMultiplier = speedMultiplier; + this->animationIndex = index; + this->time = time; + if (mode == PLAY) state = PLAYING; + } + + void Actor::queue_play(QueuedPlay newQueuedPlay) { queuedPlay = newQueuedPlay; } + void Actor::queue_default_animation() { queue_play({defaultAnimation}); } + + void Actor::play(const std::string& name, Mode mode, float time, float speedMultiplier) + { + if (animationMap.contains(name)) + play(animationMap.at(name), mode, time, speedMultiplier); + else + logger.error(std::string("Animation \"" + name + "\" does not exist! Unable to play!")); + } + + void Actor::play_default_animation(Mode mode, float time, float speedMultiplier) + { + play(defaultAnimationID, mode, time, speedMultiplier); + } + + void Actor::tick() + { + if (state == Actor::STOPPED) + { + if (!nextQueuedPlay.empty()) + { + queuedPlay = nextQueuedPlay; + queuedPlay.isPlayAfterAnimation = false; + nextQueuedPlay = QueuedPlay{}; + } + currentQueuedPlay = QueuedPlay{}; + } + + if (auto animation = animation_get(); animation && animation->isLoop) currentQueuedPlay = QueuedPlay{}; + + if (!queuedPlay.empty()) + { + auto& index = animationMap.at(queuedPlay.animation); + if (queuedPlay.isPlayAfterAnimation) + nextQueuedPlay = queuedPlay; + else if (index != animationIndex && currentQueuedPlay.isInterruptible) + { + play(queuedPlay.animation, queuedPlay.mode, queuedPlay.time, queuedPlay.speedMultiplier); + currentQueuedPlay = queuedPlay; + } + queuedPlay = QueuedPlay{}; + } + + auto animation = animation_get(); + if (!animation || animation->frameNum == 1 || mode == SET || state == STOPPED) return; + + playedEventID = -1; + + for (auto& trigger : animation->triggers.frames) + { + if (!playedTriggers.contains(trigger.atFrame) && time >= trigger.atFrame) + { + auto id = trigger.soundIDs[(int)math::random_max(trigger.soundIDs.size())]; + if (auto sound = map::find(sounds, id)) sound->audio.play(); + playedTriggers.insert((int)trigger.atFrame); + playedEventID = trigger.eventID; + } + } + + auto increment = (fps / TICK_RATE) * speedMultiplier; + time += increment; + + if (time >= animation->frameNum) + { + if (animation->isLoop) + time = 0.0f; + else + state = STOPPED; + + playedTriggers.clear(); + } + + for (int i = 0; i < (int)overrides.size(); i++) + { + auto& override_ = overrides[i]; + + if (override_.function) override_.function(override_); + + if (override_.time.has_value()) + { + *override_.time -= 1.0f; + if (*override_.time <= 0.0f) overrides.erase(overrides.begin() + i++); + } + } + } + + glm::vec4 Actor::null_frame_rect(int nullID) + { + constexpr ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; + + if (nullID == -1) return glm::vec4(NAN); + auto item = item_get(Anm2::NULL_, nullID); + if (!item) return glm::vec4(NAN); + + auto animation = animation_get(); + if (!animation) return glm::vec4(NAN); + + auto root = frame_generate(animation->rootAnimation, time, Anm2::ROOT); + + auto frame = frame_generate(*item, time, Anm2::NULL_, nullID); + if (!frame.isVisible) return glm::vec4(NAN); + + auto rootModel = + math::quad_model_no_size_get(root.position + position, root.pivot, math::to_unit(root.scale), root.rotation); + auto frameModel = math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), frame.rotation); + auto model = rootModel * frameModel; + + float minX = std::numeric_limits::infinity(); + float minY = std::numeric_limits::infinity(); + float maxX = -std::numeric_limits::infinity(); + float maxY = -std::numeric_limits::infinity(); + + for (auto& corner : CORNERS) + { + vec4 world = model * vec4(corner, 0.0f, 1.0f); + minX = std::min(minX, world.x); + minY = std::min(minY, world.y); + maxX = std::max(maxX, world.x); + maxY = std::max(maxY, world.y); + } + + return glm::vec4(minX, minY, maxX - minX, maxY - minY); + } + + void Actor::render(resource::Shader& textureShader, resource::Shader& rectShader, Canvas& canvas) + { + auto animation = animation_get(); + if (!animation) return; + + auto root = frame_generate(animation->rootAnimation, time, Anm2::ROOT); + + auto rootModel = + math::quad_model_no_size_get(root.position + position, root.pivot, math::to_unit(root.scale), root.rotation); + + for (auto& i : animation->layerOrder) + { + auto& layerAnimation = animation->layerAnimations[i]; + if (!layerAnimation.isVisible) continue; + + auto layer = map::find(layers, i); + if (!layer) continue; + + auto spritesheet = map::find(spritesheets, layer->spritesheetID); + if (!spritesheet) continue; + + auto frame = frame_generate(layerAnimation, time, Anm2::LAYER, i); + if (!frame.isVisible) continue; + + auto model = + math::quad_model_get(frame.size, frame.position, frame.pivot, math::to_unit(frame.scale), frame.rotation); + model = rootModel * model; + + auto& texture = spritesheet->texture; + if (!texture.is_valid()) return; + + auto tint = frame.tint * root.tint; + auto colorOffset = frame.colorOffset + root.colorOffset; + + auto inset = vec2(0); + auto uvMin = (frame.crop + inset) / vec2(texture.size); + auto uvMax = (frame.crop + frame.size - inset) / vec2(texture.size); + auto uvVertices = math::uv_vertices_get(uvMin, uvMax); + + canvas.texture_render(textureShader, texture.id, model, tint, colorOffset, uvVertices.data()); + } + + if (isShowNulls) + { + for (int i = 0; i < (int)animation->nullAnimations.size(); i++) + { + auto& nullAnimation = animation->nullAnimations[i]; + if (!nullAnimation.isVisible) continue; + + auto frame = frame_generate(nullAnimation, time, Anm2::NULL_, i); + if (!frame.isVisible) continue; + + auto model = math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), frame.rotation); + model = rootModel * model; + + canvas.rect_render(rectShader, model); + } + } + } + + vec4 Actor::rect() + { + constexpr ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; + + auto animation = animation_get(); + + float minX = std::numeric_limits::infinity(); + float minY = std::numeric_limits::infinity(); + float maxX = -std::numeric_limits::infinity(); + float maxY = -std::numeric_limits::infinity(); + bool any = false; + + if (!animation) return vec4(-NAN); + + for (float t = 0.0f; t < (float)animation->frameNum; t += 1.0f) + { + mat4 transform(1.0f); + + auto root = frame_generate(animation->rootAnimation, t, Anm2::ROOT); + transform *= + math::quad_model_no_size_get(root.position + position, root.pivot, math::to_unit(root.scale), root.rotation); + + for (auto& [id, layerAnimation] : animation->layerAnimations) + { + if (!layerAnimation.isVisible) continue; + + auto frame = frame_generate(layerAnimation, t, Anm2::LAYER, id); + + if (frame.size == vec2() || !frame.isVisible) continue; + + auto layerTransform = transform * math::quad_model_get(frame.size, frame.position, frame.pivot, + math::to_unit(frame.scale), frame.rotation); + for (auto& corner : CORNERS) + { + vec4 world = layerTransform * vec4(corner, 0.0f, 1.0f); + minX = std::min(minX, world.x); + minY = std::min(minY, world.y); + maxX = std::max(maxX, world.x); + maxY = std::max(maxY, world.y); + any = true; + } + } + } + + if (!any) return vec4(-NAN); + return {minX, minY, maxX - minX, maxY - minY}; + } + + bool Actor::is_animation_finished() + { + if (auto animation = animation_get()) + { + if (animation->isLoop) return true; + if (time > animation->frameNum) return true; + } + return false; + } + + void Actor::consume_played_event() { playedEventID = -1; } +}; diff --git a/src/entity/actor.hpp b/src/entity/actor.hpp new file mode 100644 index 0000000..f30455c --- /dev/null +++ b/src/entity/actor.hpp @@ -0,0 +1,113 @@ +#pragma once + +#include + +#include "../canvas.hpp" +#include "../resource/xml/anm2.hpp" + +namespace game::entity +{ + class Actor : public resource::xml::Anm2 + { + public: + static constexpr auto TICK_RATE = 30.0f; + + enum Mode + { + PLAY, + PLAY_FORCE, + SET, + }; + + enum State + { + STOPPED, + PLAYING + }; + + class Override + { + private: + public: + enum Mode + { + SET, + ADD + }; + + using Function = void (*)(Override&); + + int id{-1}; + Anm2::Type type{Anm2::NONE}; + Mode mode{SET}; + FrameOptional frame{}; + std::optional time{}; + Function function{nullptr}; + + FrameOptional frameBase{}; + std::optional timeStart{}; + + float cycles{}; + + Override() = default; + Override(int, Anm2::Type, Mode, FrameOptional = {}, std::optional = std::nullopt, Function = nullptr, + float = 0); + }; + + struct QueuedPlay + { + std::string animation{}; + float time{}; + float speedMultiplier{1.0f}; + Mode mode{PLAY}; + bool isInterruptible{true}; + bool isPlayAfterAnimation{false}; + + inline bool empty() { return animation.empty(); }; + }; + + State state{STOPPED}; + Mode mode{PLAY}; + + glm::vec2 position{}; + float time{}; + bool isShowNulls{}; + int animationIndex{-1}; + int playedEventID{-1}; + float startTime{}; + float speedMultiplier{}; + + QueuedPlay queuedPlay{}; + QueuedPlay currentQueuedPlay{}; + QueuedPlay nextQueuedPlay{}; + + std::unordered_set playedTriggers{}; + std::vector overrides{}; + + Actor() = default; + Actor(const Actor&); + Actor(Actor&&) noexcept; + Actor& operator=(const Actor&); + Actor& operator=(Actor&&) noexcept; + Actor(resource::xml::Anm2, glm::vec2 position = {}, Mode = PLAY, float time = 0.0f, int animationIndex = -1); + bool is_playing(const std::string& name = {}); + glm::vec4 null_frame_rect(int = -1); + glm::vec4 rect(); + int animation_index_get(const std::string&); + int item_length(resource::xml::Anm2::Item*); + resource::xml::Anm2::Animation* animation_get(const std::string&); + resource::xml::Anm2::Animation* animation_get(int = -1); + resource::xml::Anm2::Frame frame_generate(resource::xml::Anm2::Item&, float, resource::xml::Anm2::Type, + int id = -1); + resource::xml::Anm2::Item* item_get(resource::xml::Anm2::Type, int = -1, int = -1); + void consume_played_event(); + void play(const std::string& animation, Mode = PLAY, float time = 0.0f, float speedMultiplier = 1.0f); + void play(int index, Mode = PLAY, float time = 0.0f, float speedMultiplier = 1.0f); + void play_default_animation(Mode = PLAY, float = 0.0f, float = 1.0f); + void queue_default_animation(); + void queue_play(QueuedPlay); + bool is_animation_finished(); + void render(resource::Shader& textureShader, resource::Shader& rectShader, Canvas&); + void tick(); + }; +} diff --git a/src/entity/character.cpp b/src/entity/character.cpp new file mode 100644 index 0000000..ee419eb --- /dev/null +++ b/src/entity/character.cpp @@ -0,0 +1,372 @@ +#include "character.hpp" + +#include + +#include "../util/math.hpp" +#include "../util/vector.hpp" + +using namespace game::util; +using namespace glm; + +namespace game::entity +{ + Character::Character(const Character&) = default; + Character::Character(Character&&) noexcept = default; + Character& Character::operator=(const Character&) = default; + Character& Character::operator=(Character&&) noexcept = default; + + Character::Character(resource::xml::Character& _data, glm::ivec2 _position) : Actor(_data.anm2, _position) + { + data = _data; + + auto& save = data.save; + auto saveIsValid = save.is_valid(); + + capacity = saveIsValid ? save.capacity : data.capacity; + weight = saveIsValid ? save.weight : data.weight; + digestionRate = saveIsValid ? save.digestionRate : data.digestionRate; + eatSpeed = saveIsValid ? save.eatSpeed : data.eatSpeed; + + calories = saveIsValid ? save.calories : 0; + + isDigesting = saveIsValid ? save.isDigesting : false; + digestionProgress = saveIsValid ? save.digestionProgress : 0; + digestionTimer = saveIsValid ? save.digestionTimer : 0; + + auto& talkSource = data.talkOverride.layerSource; + auto& talkDestination = data.talkOverride.layerDestination; + talkOverrideID = vector::push_index(overrides, Actor::Override(talkDestination, Anm2::LAYER, Override::SET)); + for (auto& animation : animations) + { + if (!animation.layerAnimations.contains(talkSource)) + animationTalkDurations.emplace_back(-1); + else + animationTalkDurations.emplace_back(item_length(&animation.layerAnimations.at(talkSource))); + } + + auto& blinkSource = data.blinkOverride.layerSource; + auto& blinkDestination = data.blinkOverride.layerDestination; + blinkOverrideID = vector::push_index(overrides, Actor::Override(blinkDestination, Anm2::LAYER, Override::SET)); + for (auto& animation : animations) + { + if (!animation.layerAnimations.contains(blinkSource)) + animationBlinkDurations.emplace_back(-1); + else + animationBlinkDurations.emplace_back(item_length(&animation.layerAnimations.at(blinkSource))); + } + + for (int i = 0; i < (int)data.expandAreas.size(); i++) + { + auto& expandArea = data.expandAreas[i]; + expandAreaOverrideLayerIDs[i] = + vector::push_index(overrides, Actor::Override(expandArea.layerID, Anm2::LAYER, Override::ADD)); + expandAreaOverrideNullIDs[i] = + vector::push_index(overrides, Actor::Override(expandArea.nullID, Anm2::NULL_, Override::ADD)); + } + + for (int i = 0; i < (int)data.interactAreas.size(); i++) + { + auto& interactArea = data.interactAreas[i]; + if (interactArea.layerID != -1) + interactAreaOverrides[i] = Actor::Override(interactArea.layerID, Anm2::LAYER, Override::ADD); + } + + stage = stage_get(); + expand_areas_apply(); + } + + float Character::weight_get(measurement::System system) + { + return system == measurement::IMPERIAL ? weight * measurement::KG_TO_LB : weight; + } + + int Character::stage_from_weight_get(float checkWeight) const + { + if (data.stages.empty()) return 0; + if (checkWeight <= data.weight) return 0; + + for (int i = 0; i < (int)data.stages.size(); i++) + if (checkWeight < data.stages[i].threshold) return i; + + return stage_max_get(); + } + + int Character::stage_get() const { return stage_from_weight_get(weight); } + + int Character::stage_max_get() const { return data.stages.size(); } + + float Character::stage_threshold_get(int stage, measurement::System system) const + { + if (stage == -1) stage = this->stage; + + float threshold = data.weight; + + if (!data.stages.empty()) + { + if (stage <= 0) + threshold = data.weight; + else if (stage >= stage_max_get()) + threshold = data.stages.back().threshold; + else + threshold = data.stages[stage - 1].threshold; + } + + return system == measurement::IMPERIAL ? threshold * measurement::KG_TO_LB : threshold; + } + + float Character::stage_threshold_next_get(measurement::System system) const + { + return stage_threshold_get(stage + 1, system); + } + + float Character::stage_progress_get() + { + auto currentStage = stage_get(); + if (currentStage >= stage_max_get()) return 1.0f; + + auto currentThreshold = stage_threshold_get(currentStage); + auto nextThreshold = stage_threshold_get(currentStage + 1); + if (nextThreshold <= currentThreshold) return 1.0f; + + return (weight - currentThreshold) / (nextThreshold - currentThreshold); + } + + float Character::digestion_rate_get() { return digestionRate * 60; } + + float Character::max_capacity() const { return capacity * data.capacityMaxMultiplier; } + bool Character::is_over_capacity() const { return calories > capacity; } + bool Character::is_max_capacity() const { return calories >= max_capacity(); } + float Character::capacity_percent_get() const { return calories / max_capacity(); } + + std::string Character::animation_name_convert(const std::string& name) { return std::format("{}{}", name, stage); } + void Character::play_convert(const std::string& animation, Mode mode, float time, float speedMultiplier) + { + play(animation_name_convert(animation), mode, time, speedMultiplier); + } + + void Character::expand_areas_apply() + { + auto stageProgress = stage_progress_get(); + auto capacityProgress = isDigesting + ? (float)calories / max_capacity() * (float)digestionTimer / data.digestionTimerMax + : calories / max_capacity(); + + for (int i = 0; i < (int)data.expandAreas.size(); i++) + { + auto& expandArea = data.expandAreas[i]; + auto& overrideLayer = overrides[expandAreaOverrideLayerIDs[i]]; + auto& overrideNull = overrides[expandAreaOverrideNullIDs[i]]; + + auto stageScaleAdd = ((expandArea.scaleAdd * stageProgress) * 0.5f); + auto capacityScaleAdd = ((expandArea.scaleAdd * capacityProgress) * 0.5f); + + auto scaleAdd = + glm::clamp(glm::vec2(), glm::vec2(stageScaleAdd + capacityScaleAdd), glm::vec2(expandArea.scaleAdd)); + overrideLayer.frame.scale = scaleAdd; + overrideNull.frame.scale = scaleAdd; + } + } + + void Character::update() + { + isJustStageUp = false; + isJustStageFinal = false; + isJustDigested = false; + } + + void Character::tick() + { + if (state == Actor::STOPPED) + { + if (isStageUp) + { + if (stage >= (int)data.stages.size()) + isJustStageFinal = true; + else + isJustStageUp = true; + + isStageUp = false; + } + + if (nextQueuedPlay.empty()) queue_idle_animation(); + } + + Actor::tick(); + + if (isDigesting) + { + digestionTimer--; + + if (digestionTimer <= 0) + { + auto increment = calories * data.caloriesToKilogram; + + if (is_over_capacity()) + { + auto capacityMaxCalorieDifference = (calories - capacity); + auto overCapacityPercent = capacityMaxCalorieDifference / (max_capacity() - capacity); + auto capacityIncrement = + (overCapacityPercent * data.capacityIfOverStuffedOnDigestBonus) * capacityMaxCalorieDifference; + capacity = glm::clamp(data.capacityMin, capacity + capacityIncrement, data.capacityMax); + } + + totalCaloriesConsumed += calories; + calories = 0; + + if (auto nextStage = stage_from_weight_get(weight + increment); nextStage > stage_from_weight_get(weight)) + { + queuedPlay = QueuedPlay{}; + nextQueuedPlay = QueuedPlay{}; + currentQueuedPlay = QueuedPlay{}; + play_convert(data.animations.stageUp); + stage = nextStage; + isStageUp = true; + } + else + isJustDigested = true; + + weight = glm::clamp(data.weightMin, weight + increment, data.weightMax); + + isDigesting = false; + digestionTimer = data.digestionTimerMax; + digestionProgress = 0; + } + } + else + { + if (calories > 0) digestionProgress += digestionRate; + if (digestionProgress >= DIGESTION_MAX) + { + isDigesting = true; + digestionTimer = data.digestionTimerMax; + data.sounds.digest.play(); + } + } + + if (math::random_percent_roll( + math::to_percent(data.gurgleChance * (capacity_percent_get() * data.gurgleCapacityMultiplier)))) + data.sounds.gurgle.play(); + + stage = stage_get(); + expand_areas_apply(); + + auto& talkOverride = overrides[talkOverrideID]; + + if (isTalking) + { + auto talk_reset = [&]() + { + isTalking = false; + talkTimer = 0.0f; + talkOverride.frame = FrameOptional(); + }; + + auto& id = data.talkOverride.layerSource; + auto& layerAnimations = animation_get()->layerAnimations; + + if (layerAnimations.contains(id) && animationTalkDurations.at(animationIndex) > -1) + { + auto& layerAnimation = layerAnimations.at(data.talkOverride.layerSource); + + if (!layerAnimation.frames.empty()) + { + auto frame = frame_generate(layerAnimation, talkTimer, Anm2::LAYER, id); + + talkOverride.frame.crop = frame.crop; + talkOverride.frame.size = frame.size; + talkOverride.frame.pivot = frame.pivot; + + talkTimer += 1.0f; + + if (talkTimer > animationTalkDurations.at(animationIndex)) talkTimer = 0.0f; + } + else + talk_reset(); + } + else + talk_reset(); + } + else + talkOverride.frame = {}; + + auto& blinkOverride = overrides[blinkOverrideID]; + + if (auto blinkDuration = animationBlinkDurations[animationIndex]; blinkDuration != 1) + { + if (math::random_percent_roll(data.blinkChance)) isBlinking = true; + + if (isBlinking) + { + auto blink_reset = [&]() + { + isBlinking = false; + blinkTimer = 0.0f; + blinkOverride.frame = FrameOptional(); + }; + + auto& id = data.blinkOverride.layerSource; + auto& layerAnimations = animation_get()->layerAnimations; + + if (layerAnimations.contains(id)) + { + auto& layerAnimation = layerAnimations.at(data.blinkOverride.layerSource); + + if (!layerAnimation.frames.empty()) + { + auto frame = frame_generate(layerAnimation, blinkTimer, Anm2::LAYER, id); + + blinkOverride.frame.crop = frame.crop; + blinkOverride.frame.size = frame.size; + blinkOverride.frame.pivot = frame.pivot; + + blinkTimer += 1.0f; + + if (blinkTimer >= blinkDuration) blink_reset(); + } + else + blink_reset(); + } + else + blink_reset(); + } + } + } + + void Character::queue_play(QueuedPlay play) + { + queuedPlay = play; + queuedPlay.animation = animation_name_convert(queuedPlay.animation); + } + + void Character::queue_idle_animation() + { + if (data.animations.idle.empty()) return; + queue_play( + {is_over_capacity() && !data.animations.idleFull.empty() ? data.animations.idleFull : data.animations.idle}); + } + + void Character::queue_interact_area_animation(resource::xml::Character::InteractArea& interactArea) + { + if (interactArea.animation.empty()) return; + queue_play({is_over_capacity() && !interactArea.animationFull.empty() ? interactArea.animationFull + : interactArea.animation}); + } + + void Character::spritesheet_set(SpritesheetType type) + { + switch (type) + { + case NORMAL: + spritesheets.at(data.alternateSpritesheet.id).texture = + data.anm2.spritesheets.at(data.alternateSpritesheet.id).texture; + break; + case ALTERNATE: + spritesheets.at(data.alternateSpritesheet.id).texture = data.alternateSpritesheet.texture; + break; + default: + break; + } + + spritesheetType = type; + } +} diff --git a/src/entity/character.hpp b/src/entity/character.hpp new file mode 100644 index 0000000..76b8c77 --- /dev/null +++ b/src/entity/character.hpp @@ -0,0 +1,92 @@ +#pragma once + +#include "../resource/xml/character.hpp" +#include "../util/measurement.hpp" + +#include "actor.hpp" + +namespace game::entity +{ + class Character : public Actor + { + public: + static constexpr auto DIGESTION_MAX = 100.0f; + + enum SpritesheetType + { + NORMAL, + ALTERNATE + }; + + resource::xml::Character data; + + float weight{}; + int stage{0}; + float calories{}; + float capacity{}; + + float digestionProgress{}; + float digestionRate{0.05f}; + int digestionTimer{}; + bool isDigesting{}; + bool isJustDigested{}; + + float eatSpeed{1.0f}; + + float totalCaloriesConsumed{}; + int totalFoodItemsEaten{}; + + int talkOverrideID{}; + float talkTimer{}; + bool isTalking{}; + std::vector animationTalkDurations{}; + + int blinkOverrideID{}; + float blinkTimer{}; + bool isBlinking{}; + std::vector animationBlinkDurations{}; + + bool isStageUp{}; + bool isJustStageUp{}; + bool isJustStageFinal{}; + + SpritesheetType spritesheetType{}; + + std::map interactAreaOverrides{}; + + std::unordered_map expandAreaOverrideLayerIDs{}; + std::unordered_map expandAreaOverrideNullIDs{}; + + Character() = default; + Character(const Character&); + Character(Character&&) noexcept; + Character& operator=(const Character&); + Character& operator=(Character&&) noexcept; + Character(resource::xml::Character&, glm::ivec2); + + float weight_get(util::measurement::System = util::measurement::METRIC); + float digestion_rate_get(); + float capacity_percent_get() const; + float max_capacity() const; + bool is_over_capacity() const; + bool is_max_capacity() const; + + int stage_get() const; + int stage_from_weight_get(float weight) const; + int stage_max_get() const; + float stage_progress_get(); + float stage_threshold_get(int stage = -1, util::measurement::System = util::measurement::METRIC) const; + float stage_threshold_next_get(util::measurement::System = util::measurement::METRIC) const; + + void expand_areas_apply(); + void spritesheet_set(SpritesheetType); + void update(); + void tick(); + void play_convert(const std::string&, Mode = PLAY, float time = 0.0f, float speedMultiplier = 1.0f); + void queue_idle_animation(); + void queue_interact_area_animation(resource::xml::Character::InteractArea&); + void queue_play(QueuedPlay); + + std::string animation_name_convert(const std::string& name); + }; +} diff --git a/src/entity/cursor.cpp b/src/entity/cursor.cpp new file mode 100644 index 0000000..5784e46 --- /dev/null +++ b/src/entity/cursor.cpp @@ -0,0 +1,22 @@ +#include "cursor.hpp" + +#include "../util/imgui.hpp" + +using namespace game::util; +using namespace glm; + +namespace game::entity +{ + Cursor::Cursor(Anm2& anm2) : Actor(anm2, imgui::to_vec2(ImGui::GetMousePos())) {} + void Cursor::tick() + { + Actor::tick(); + queue_default_animation(); + } + + void Cursor::update() + { + state = DEFAULT; + position = imgui::to_vec2(ImGui::GetMousePos()); + } +} diff --git a/src/entity/cursor.hpp b/src/entity/cursor.hpp new file mode 100644 index 0000000..a7fec19 --- /dev/null +++ b/src/entity/cursor.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "../util/interact_type.hpp" +#include "actor.hpp" + +namespace game::entity +{ + class Cursor : public Actor + { + public: + enum State + { + DEFAULT, + HOVER, + ACTION + }; + + State state{DEFAULT}; + InteractType mode{InteractType::RUB}; + + Cursor() = default; + Cursor(resource::xml::Anm2&); + void tick(); + void update(); + }; +} \ No newline at end of file diff --git a/src/entity/item.cpp b/src/entity/item.cpp new file mode 100644 index 0000000..6a78f3d --- /dev/null +++ b/src/entity/item.cpp @@ -0,0 +1,31 @@ +#include "item.hpp" + +#include + +#include "../util/vector.hpp" + +using game::resource::xml::Anm2; +using namespace game::util; +using namespace glm; + +namespace game::entity +{ + Item::Item(Anm2 _anm2, glm::ivec2 _position, int _schemaID, int _chewCount, int _animationIndex, glm::vec2 _velocity, + float _rotation) + : Actor(_anm2, _position, SET, 0.0f, _animationIndex), schemaID(_schemaID), chewCount(_chewCount), + velocity(_velocity) + { + + rotationOverrideID = + vector::push_index(overrides, Override(-1, Anm2::ROOT, Override::SET, Anm2::FrameOptional{.rotation = _rotation})); + } + + void Item::update() + { + auto& rotationOverride = overrides[rotationOverrideID]; + + position += velocity; + + *rotationOverride.frame.rotation += angularVelocity; + } +} diff --git a/src/entity/item.hpp b/src/entity/item.hpp new file mode 100644 index 0000000..21b24b1 --- /dev/null +++ b/src/entity/item.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "../resource/xml/item.hpp" + +#include "actor.hpp" + +namespace game::entity +{ + class Item : public Actor + { + public: + bool isToBeDeleted{}; + bool isHeld{}; + + int schemaID{}; + int rotationOverrideID{}; + int chewCount{}; + + glm::vec2 velocity{}; + float angularVelocity{}; + + Item(resource::xml::Anm2, glm::ivec2 position, int id, int chewCount = 0, int animationIndex = -1, + glm::vec2 velocity = {}, float rotation = 0.0f); + void update(); + }; +} diff --git a/src/game_data.hpp b/src/game_data.hpp deleted file mode 100644 index db2639a..0000000 --- a/src/game_data.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include "types.h" - -namespace game -{ - class GameData - { - public: - MeasurementSystem measurementSystem{MeasurementSystem::METRIC}; - int volume{100}; - }; -} \ No newline at end of file diff --git a/src/item.cpp b/src/item.cpp deleted file mode 100644 index e7e5de3..0000000 --- a/src/item.cpp +++ /dev/null @@ -1,129 +0,0 @@ -#include "item.h" -#include "imgui.h" -#include "util/math_.h" - -using namespace game::anm2; -using namespace game::util; -using namespace glm; - -namespace game -{ - Item* Item::heldItem = nullptr; - Item* Item::heldItemPrevious = nullptr; - Item* Item::hoveredItem = nullptr; - Item* Item::hoveredItemPrevious = nullptr; - Item* Item::queuedReturnItem = nullptr; - - std::array rarity_pools_get() - { - std::array newPools{}; - for (auto& pool : newPools) - pool.clear(); - - for (int i = 0; i < Item::ITEM_COUNT; i++) - { - auto& rarity = Item::RARITIES[i]; - newPools[rarity].emplace_back((Item::Type)i); - } - - return newPools; - } - - const std::array Item::pools = rarity_pools_get(); - - Item::Item(Anm2* _anm2, glm::ivec2 _position, Type _type) : Actor(_anm2, _position, SET, (float)_type) - { - this->type = _type; - } - - void Item::tick() { Actor::tick(); } - - void Item::update(Resources& resources) - { - auto bounds = ivec4(position.x - SIZE * 0.5f, position.y - SIZE * 0.5f, SIZE, SIZE); - auto mousePos = ivec2(ImGui::GetMousePos().x, ImGui::GetMousePos().y); - - if (isHeld) - { - position = mousePos - ivec2(holdOffset); - delta = previousPosition - position; - - velocity *= VELOCITY_HOLD_MULTIPLIER; - - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) - { - auto power = fabs(delta.x) + fabs(delta.y); - - heldItem = nullptr; - - if (power > THROW_THRESHOLD) - resources.sound_play(audio::THROW); - else - resources.sound_play(audio::RELEASE); - - velocity += delta; - isHeld = false; - } - } - else if (math::is_point_in_rect(bounds, mousePos)) - { - hoveredItem = this; - - if (ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !heldItem) - { - heldItem = this; - - resources.sound_play(audio::GRAB); - - isHeld = true; - holdOffset = mousePos - ivec2(position); - } - else if (ImGui::IsMouseClicked(ImGuiMouseButton_Right)) - { - queuedReturnItem = this; - } - } - - if (!isHeld) velocity.y += GRAVITY; - position += velocity; - - if (position.x < BOUNDS.x || position.x > BOUNDS.z) - { - velocity.x = -velocity.x; - velocity.x *= FRICTION; - - if (fabs(velocity.x) > BOUNCE_SOUND_THRESHOLD) resources.sound_play(audio::BOUNCE); - } - if (position.y < BOUNDS.y || position.y > BOUNDS.w) - { - velocity.y = -velocity.y; - velocity *= FRICTION; - - if (fabs(velocity.y) > BOUNCE_SOUND_THRESHOLD) resources.sound_play(audio::BOUNCE); - } - - position = glm::clamp(vec2(BOUNDS.x, BOUNDS.y), position, vec2(BOUNDS.z, BOUNDS.w)); - - previousPosition = position; - } - - void Item::state_set(State state) - { - this->state = state; - - switch (this->state) - { - case DEFAULT: - play("Default", SET, (float)type); - break; - case CHEW_1: - play("Chew1", SET, (float)type); - break; - case CHEW_2: - play("Chew2", SET, (float)type); - break; - default: - break; - }; - } -} diff --git a/src/item.hpp b/src/item.hpp deleted file mode 100644 index 7b80e50..0000000 --- a/src/item.hpp +++ /dev/null @@ -1,241 +0,0 @@ -#pragma once - -#include "resource/actor.h" -#include "resources.h" - -namespace game -{ - class Item : public resource::Actor - { - public: - static constexpr auto VELOCITY_HOLD_MULTIPLIER = 0.50f; - static constexpr auto VELOCITY_HOLD_BOOST = 2.5f; - static constexpr auto BOUNCE_SOUND_THRESHOLD = 2.5f; - static constexpr auto THROW_MULTIPLIER = 1.0f; - static constexpr auto THROW_THRESHOLD = 50.0f; - static constexpr auto FRICTION = 0.75f; - static constexpr auto GRAVITY = 0.50f; - static constexpr auto SIZE = 72.0f; - static constexpr auto CHEW_COUNT_MAX = 2; - - static constexpr auto DEPLOYED_MAX = 10; - - static constexpr auto ANIMATION_STATE = "State"; - - static constexpr glm::vec4 BOUNDS = {50, 100, 475, 500}; - static constexpr auto SPAWN_X_MIN = BOUNDS.x; - static constexpr auto SPAWN_X_MAX = BOUNDS.z + BOUNDS.x; - static constexpr auto SPAWN_Y_MIN = BOUNDS.y; - static constexpr auto SPAWN_Y_MAX = BOUNDS.w + BOUNDS.y; - -#define CATEGORIES \ - X(INVALID, "Invalid") \ - X(FOOD, "Food") \ - X(UTILITY, "Utility") - - enum Category - { -#define X(symbol, name) symbol, - CATEGORIES -#undef X - }; - - static constexpr const char* CATEGORY_NAMES[] = { -#define X(symbol, name) name, - CATEGORIES -#undef X - }; - -#undef CATEGORIES - -#define RARITIES \ - X(NO_RARITY, "No Rarity", 0.0f) \ - X(COMMON, "Common", 1.0f) \ - X(UNCOMMON, "Uncommon", 0.75f) \ - X(RARE, "Rare", 0.5f) \ - X(EPIC, "Epic", 0.25f) \ - X(LEGENDARY, "Legendary", 0.125f) \ - X(IMPOSSIBLE, "???", 0.001f) \ - X(SPECIAL, "Special", 0.0f) - - enum Rarity - { -#define X(symbol, name, chance) symbol, - RARITIES -#undef X - RARITY_COUNT - }; - - static constexpr const char* RARITY_NAMES[] = { -#define X(symbol, name, chance) name, - RARITIES -#undef X - }; - - static constexpr float RARITY_CHANCES[] = { -#define X(symbol, name, chance) chance, - RARITIES -#undef X - }; - -#undef RARITIES - -#define FLAVORS \ - X(FLAVORLESS, "None") \ - X(SWEET, "Sweet") \ - X(BITTER, "Bitter") \ - X(SPICY, "Spicy") \ - X(MINT, "Mint") \ - X(CITRUS, "Citrus") \ - X(MOCHA, "Mocha") \ - X(SPICE, "Spice") - - enum Flavor - { -#define X(symbol, name) symbol, - FLAVORS -#undef X - FLAVOR_COUNT - }; - - static constexpr const char* FLAVOR_NAMES[] = { -#define X(symbol, name) name, - FLAVORS -#undef X - }; - -#undef FLAVORS - - // clang-format off -#define ITEMS \ - X(NONE, INVALID, FLAVORLESS, NO_RARITY, "", "", 0, 0, 0) \ - X(POKE_PUFF_BASIC_SWEET, FOOD, SWEET, COMMON, "Poké Puff (Basic, Sweet)", "A basic sweet Poké Puff.", 100.0f, 0, 0) \ - X(POKE_PUFF_BASIC_MINT, FOOD, MINT, COMMON, "Poké Puff (Basic, Mint)", "A basic minty Poké Puff.", 100.0f, 0, 0) \ - X(POKE_PUFF_BASIC_CITRUS, FOOD, CITRUS, COMMON, "Poké Puff (Basic, Citrus)", "A basic citrusy Poké Puff.", 100.0f, 0, 0) \ - X(POKE_PUFF_BASIC_MOCHA, FOOD, MOCHA, COMMON, "Poké Puff (Basic, Mocha)", "A basic mocha Poké Puff.", 100.0f, 0, 0) \ - X(POKE_PUFF_BASIC_SPICE, FOOD, SPICE, COMMON, "Poké Puff (Basic, Spice)", "A basic spice Poké Puff.", 100.0f, 0, 0) \ - X(POKE_PUFF_FROSTED_SWEET, FOOD, SWEET, UNCOMMON, "Poké Puff (Frosted, Sweet)", "A frosted sweet Poké Puff.", 250.0f, 0, 0) \ - X(POKE_PUFF_FROSTED_MINT, FOOD, MINT, UNCOMMON, "Poké Puff (Frosted, Mint)", "A frosted minty Poké Puff.", 250.0f, 0, 0) \ - X(POKE_PUFF_FROSTED_CITRUS, FOOD, MINT, UNCOMMON, "Poké Puff (Frosted, Citrus)", "A frosted citrusy Poké Puff.", 250.0f, 0, 0) \ - X(POKE_PUFF_FROSTED_MOCHA, FOOD, MOCHA, UNCOMMON, "Poké Puff (Frosted, Mocha)", "A frosted mocha Poké Puff.", 250.0f, 0, 0) \ - X(POKE_PUFF_FROSTED_SPICE, FOOD, SPICE, UNCOMMON, "Poké Puff (Frosted, Spice)", "A frosted spice Poké Puff.", 250.0f, 0, 0) \ - X(POKE_PUFF_FANCY_SWEET, FOOD, SWEET, RARE, "Poké Puff (Fancy, Sweet)", "A fancy sweet Poké Puff, adorned with a cherry.", 500.0f, 0, 0) \ - X(POKE_PUFF_FANCY_MINT, FOOD, MINT, RARE, "Poké Puff (Fancy, Mint)", "A fancy minty Poké Puff, adorned with a crescent moon-shaped candy.", 500.0f, 0, 0) \ - X(POKE_PUFF_FANCY_CITRUS, FOOD, CITRUS, RARE, "Poké Puff (Fancy, Citrus)", "A fancy citrus Poké Puff, adorned with an orange slice.", 500.0f, 0, 0) \ - X(POKE_PUFF_FANCY_MOCHA, FOOD, MOCHA, RARE, "Poké Puff (Fancy, Mocha)", "A fancy mocha Poké Puff, adorned with a morsel of white chocolate.", 500.0f, 0, 0) \ - X(POKE_PUFF_FANCY_SPICE, FOOD, SPICE, RARE, "Poké Puff (Fancy, Spice)", "A fancy spice Poké Puff, adorned with a morsel of dark chocolate.", 500.0f, 0, 0) \ - X(POKE_PUFF_DELUXE_SWEET, FOOD, SWEET, EPIC, "Poké Puff (Deluxe, Sweet)", "A deluxe sweet Poké Puff; frosted and adorned with a cherry.", 1000.0f, 0, 0) \ - X(POKE_PUFF_DELUXE_MINT, FOOD, MINT, EPIC, "Poké Puff (Deluxe, Mint)", "A deluxe minty Poké Puff; frosted and adorned with a crescent moon-shapedd candy.", 1000.0f, 0, 0) \ - X(POKE_PUFF_DELUXE_CITRUS, FOOD, CITRUS, EPIC, "Poké Puff (Deluxe, Citrus)", "A deluxe citrusy Poké Puff; frosted and adorned with an orange slice.", 1000.0f, 0, 0) \ - X(POKE_PUFF_DELUXE_MOCHA, FOOD, MOCHA, EPIC, "Poké Puff (Deluxe, Mocha)", "A deluxe mocha Poké Puff; frosted and adorned with a morsel of white chocolate.", 1000.0f, 0, 0) \ - X(POKE_PUFF_DELUXE_SPICE, FOOD, SPICE, EPIC, "Poké Puff (Deluxe, Spice)", "A deluxe spice Poké Puff; frosted and adorned with a morsel of dark chocolate.", 1000.0f, 0, 0) \ - X(POKE_PUFF_SUPREME_SPRING, FOOD, SWEET, LEGENDARY, "Poké Puff (Supreme Spring)", "A supreme Poké Puff that tastes like the sweet cherry blossoms of spring.", 2500.0f, 0, 0) \ - X(POKE_PUFF_SUPREME_SUMMER, FOOD, CITRUS, LEGENDARY, "Poké Puff (Supreme Summer)", "A supreme Poké Puff that tastes like a tropical summer vacation.", 2500.0f, 0, 0) \ - X(POKE_PUFF_SUPREME_AUTUMN, FOOD, CITRUS, LEGENDARY, "Poké Puff (Supreme Autumn)", "A supreme Poké Puff that tastes like a bountiful autumn harvest.", 2500.0f, 0, 0) \ - X(POKE_PUFF_SUPREME_WINTER, FOOD, SPICE, LEGENDARY, "Poké Puff (Supreme Winter)", "A supreme Poké Puff that tastes like a frosty winter wonderland.", 2500.0f, 0, 0) \ - X(POKE_PUFF_SUPREME_WISH, FOOD, SPICE, IMPOSSIBLE, "Poké Puff (Supreme Wish)", "A supreme Poké Puff that tastes like a cherished birthday celebration.\nIt also is the biggest calorie nuke ever.\nCan Snivy eat it!?\nAlso, statistically, it might be your birthday today, right?", 10000.0f, 0, 0) \ - X(POKE_PUFF_SUPREME_HONOR, FOOD, MOCHA, SPECIAL, "Poké Puff (Supreme Honor)", "A supreme Poké Puff that tastes like a monumental victory.\nAwarded for achieving a superb Play score.\nYou've earned it...if Snivy can eat it!", 2500.0f, 0.025f, 1.0f) \ - X(BERRY_CHERI, FOOD, SPICY, UNCOMMON, "Cheri Berry", "A spherical red berry that cures paralysis\n...oh, and it also excites one's stomach.", 25.0f, 0.000833f, 0) \ - X(BERRY_TAMATO, FOOD, SPICY, RARE, "Tamato Berry", "A spiny crimson berry that lowers speed and raises friendship.\n...oh, and it also greatly excites one's stomach.", 50.0f, 0.0025f, 0) \ - X(BERRY_TOUGA, FOOD, SPICY, EPIC, "Touga Berry", "An obscure, searing-red berry from faraway lands.\nIt cures confusion...and it'll make one's stomach a burning inferno.", 100.0f, 0.00833f, 0) \ - X(BERRY_PECHA, FOOD, SWEET, UNCOMMON, "Pecha Berry", "A plump and juicy pink berry that cures poison.\n...oh, and its sugars will stir appetite.", 25.0f, 0, 0.05f) \ - X(BERRY_MAGOST, FOOD, SWEET, RARE, "Magost Berry", "A spherical, shining berry that packs a punch with a fibrious inside.\n...oh, and its sugars will greatly stir appetite.", 50.0f, 0, 0.15f) \ - X(BERRY_WATMEL, FOOD, SWEET, EPIC, "Watmel Berry", "A truly bountiful berry with a brilliant green and pink pattern.\nWhispering tales say that if one eats such a berry,\ntheir appetite will increase to a point that they will soon bare the berry's shape.", 100.0f, 0, 0.50f) \ - X(BERRY_AGUAV, FOOD, BITTER, RARE, "Aguav Berry", "A bitter berry that will restore health for hurt eaters who enjoy the flavor.\n...oh, also its taste will soothe an upset stomach.\n(Only use this if you really want to decrease Snivy's digestion.)", 50.0f, -0.01666f, 0) \ - X(BERRY_POMEG, FOOD, FLAVORLESS, IMPOSSIBLE, "Pomeg Berry", "cG9tZWcgYmVycnkgcG9tZWcgYmVycnkgcG9tZWcgYmVycnk=", -2500.0f, 0.2, 2.0f) - // clang-format on - - enum Type - { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) symbol, - ITEMS -#undef X - ITEM_COUNT - }; - - static constexpr Category CATEGORIES[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) category, - ITEMS -#undef X - }; - - static constexpr Flavor FLAVORS[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) flavor, - ITEMS -#undef X - }; - - static constexpr Rarity RARITIES[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) rarity, - ITEMS -#undef X - }; - - static constexpr const char* NAMES[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) name, - ITEMS -#undef X - }; - - static constexpr const char* DESCRIPTIONS[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) description, - ITEMS -#undef X - }; - - static constexpr float CALORIES[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) calories, - ITEMS -#undef X - }; - - static constexpr float DIGESTION_RATE_BONUSES[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) \ - digestionRateBonus, - ITEMS -#undef X - }; - - static constexpr float EAT_SPEED_BONUSES[] = { -#define X(symbol, category, flavor, rarity, name, description, calories, digestionRateBonus, eatSpeedBonus) \ - eatSpeedBonus, - ITEMS -#undef X - }; - -#undef ITEMS - - enum State - { - DEFAULT, - CHEW_1, - CHEW_2 - }; - - static Item* heldItem; - static Item* heldItemPrevious; - static Item* hoveredItem; - static Item* hoveredItemPrevious; - static Item* queuedReturnItem; - - using Pool = std::vector; - static const std::array pools; - - Type type{NONE}; - State state{DEFAULT}; - int chewCount{0}; - bool isToBeDeleted{}; - - glm::vec2 delta{}; - glm::vec2 previousPosition{}; - glm::vec2 velocity{}; - glm::vec2 holdOffset{}; - - bool isHeld{}; - - Item(anm2::Anm2*, glm::ivec2, Type); - void state_set(State); - void tick(); - void update(Resources& resources); - }; -} diff --git a/src/loader.cpp b/src/loader.cpp index 6003b50..e8f203f 100644 --- a/src/loader.cpp +++ b/src/loader.cpp @@ -1,4 +1,5 @@ -#include "loader.h" +#include "loader.hpp" +#include "util/imgui/widget.hpp" #ifdef __EMSCRIPTEN__ #include @@ -8,45 +9,69 @@ #include #include +#include #include -#include -#include "util/math_.h" +#include "log.hpp" +#include "util/math.hpp" #include +#include + +#include "resource/audio.hpp" +#include "resource/xml/settings.hpp" +#include "util/imgui/style.hpp" +#include "util/preferences.hpp" + #ifdef __EMSCRIPTEN__ + + #include "util/web_filesystem.hpp" + constexpr auto GL_VERSION_MAJOR = 3; constexpr auto GL_VERSION_MINOR = 0; constexpr auto GLSL_VERSION = "#version 300 es"; + #else constexpr auto GL_VERSION_MAJOR = 3; constexpr auto GL_VERSION_MINOR = 3; constexpr auto GLSL_VERSION = "#version 330"; #endif -constexpr auto WINDOW_ROUNDING = 6.0f; -constexpr auto WINDOW_COLOR = ImVec4(0.03f, 0.25f, 0.06f, 1.0f); -constexpr auto WINDOW_BACKGROUND_COLOR = ImVec4(0.02f, 0.08f, 0.03f, 0.96f); -constexpr auto ACCENT_COLOR = ImVec4(0.05f, 0.32f, 0.12f, 1.0f); -constexpr auto ACCENT_COLOR_HOVERED = ImVec4(0.07f, 0.4f, 0.15f, 1.0f); -constexpr auto ACCENT_COLOR_ACTIVE = ImVec4(0.09f, 0.5f, 0.2f, 1.0f); -constexpr auto TAB_UNFOCUSED_COLOR = ImVec4(0.03f, 0.2f, 0.07f, 0.9f); - using namespace game::util; namespace game { - Loader::Loader() + + Loader::Loader(int argc, const char** argv) { - if (!SDL_Init(SDL_INIT_VIDEO)) +#ifdef __EMSCRIPTEN__ + util::web_filesystem::init_and_wait(); +#endif + + settings = resource::xml::Settings(preferences::path() / "settings.xml"); + + logger.info("Initializing..."); + + if (!PHYSFS_init((argc > 0 && argv && argv[0]) ? argv[0] : "snivy")) { - std::cout << "Failed to initialize SDL: " << SDL_GetError(); + logger.fatal(std::format("Failed to initialize PhysicsFS: {}", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()))); isError = true; return; } - std::cout << "Initialized SDL" << "\n"; + PHYSFS_setWriteDir(nullptr); + + logger.info("Initialized PhysFS"); + + if (!SDL_Init(SDL_INIT_VIDEO)) + { + logger.fatal(std::format("Failed to initialize SDL: {}", SDL_GetError())); + isError = true; + return; + } + + logger.info("Initialized SDL"); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, GL_VERSION_MAJOR); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, GL_VERSION_MINOR); @@ -57,30 +82,49 @@ namespace game #endif SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); +#ifdef __EMSCRIPTEN__ window = SDL_CreateWindow("Snivy", SIZE.x, SIZE.y, SDL_WINDOW_OPENGL); +#else + + SDL_PropertiesID windowProperties = SDL_CreateProperties(); + + SDL_SetStringProperty(windowProperties, SDL_PROP_WINDOW_CREATE_TITLE_STRING, "Snivy"); + SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, settings.windowSize.x); + SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, settings.windowSize.y); + + SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_X_NUMBER, + settings.windowPosition.x == 0 ? SDL_WINDOWPOS_CENTERED : settings.windowPosition.x); + SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_Y_NUMBER, + settings.windowPosition.y == 0 ? SDL_WINDOWPOS_CENTERED : settings.windowPosition.y); + + SDL_SetBooleanProperty(windowProperties, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true); + SDL_SetBooleanProperty(windowProperties, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true); + SDL_SetBooleanProperty(windowProperties, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true); + + window = SDL_CreateWindowWithProperties(windowProperties); +#endif if (!window) { - std::cout << "Failed to initialize window: " << SDL_GetError(); - ; + logger.fatal(std::format("Failed to initialize window: {}", SDL_GetError())); isError = true; return; } - std::cout << "Initialized window" << "\n"; + logger.info("Initialized window"); context = SDL_GL_CreateContext(window); if (!context) { - std::cout << "Failed to initialize GL context: " << SDL_GetError(); + logger.fatal(std::format("Failed to initialize GL context: {}", SDL_GetError())); isError = true; return; } if (!SDL_GL_MakeCurrent(window, context)) { - std::cout << "Failed to make GL context current: " << SDL_GetError(); + logger.fatal(std::format("Failed to make GL context current: {}", SDL_GetError())); isError = true; return; } @@ -88,12 +132,12 @@ namespace game #ifndef __EMSCRIPTEN__ if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { - std::cout << "Failed to initialize GLAD" << "\n"; + logger.fatal("Failed to initialize GLAD"); isError = true; return; } - std::cout << "Initialized GLAD" << "\n"; + logger.info("Initialized GLAD"); #endif glEnable(GL_BLEND); @@ -101,90 +145,68 @@ namespace game glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); - std::cout << "Initialized GL context: " << glGetString(GL_VERSION) << "\n"; + logger.info(std::format("Initialized GL context: {}", (const char*)glGetString(GL_VERSION))); SDL_GL_SetSwapInterval(1); + SDL_GL_MakeCurrent(window, context); if (!MIX_Init()) { - std::cout << "Failed to initialize SDL mixer: " << SDL_GetError(); + logger.fatal(std::format("Failed to initialize SDL mixer: {}", SDL_GetError())); isError = true; return; } - std::cout << "Initialized SDL mixer" << "\n"; + logger.info("Initialized SDL mixer"); IMGUI_CHECKVERSION(); ImGuiContext* imguiContext = ImGui::CreateContext(); if (!imguiContext) { - std::cout << "Failed to initialize Dear ImGui" << "\n"; + logger.fatal("Failed to initialize Dear ImGui"); isError = true; return; } - std::cout << "Initialized Dear ImGui" << "\n"; + logger.info("Initialized Dear ImGui"); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); - style.Colors[ImGuiCol_TitleBg] = WINDOW_COLOR; - style.Colors[ImGuiCol_TitleBgActive] = WINDOW_COLOR; - style.Colors[ImGuiCol_TitleBgCollapsed] = WINDOW_COLOR; - style.Colors[ImGuiCol_Header] = ACCENT_COLOR; - style.Colors[ImGuiCol_HeaderHovered] = ACCENT_COLOR_HOVERED; - style.Colors[ImGuiCol_HeaderActive] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_FrameBg] = ACCENT_COLOR; - style.Colors[ImGuiCol_FrameBgActive] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_FrameBgHovered] = ACCENT_COLOR_HOVERED; - style.Colors[ImGuiCol_Button] = ACCENT_COLOR; - style.Colors[ImGuiCol_ButtonHovered] = ACCENT_COLOR_HOVERED; - style.Colors[ImGuiCol_ButtonActive] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_CheckMark] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_SliderGrab] = ACCENT_COLOR; - style.Colors[ImGuiCol_SliderGrabActive] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_ResizeGrip] = ACCENT_COLOR; - style.Colors[ImGuiCol_ResizeGripHovered] = ACCENT_COLOR_HOVERED; - style.Colors[ImGuiCol_ResizeGripActive] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_PlotLines] = ACCENT_COLOR; - style.Colors[ImGuiCol_PlotLinesHovered] = ACCENT_COLOR_HOVERED; - style.Colors[ImGuiCol_PlotHistogram] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_PlotHistogramHovered] = ACCENT_COLOR_HOVERED; - style.Colors[ImGuiCol_Tab] = ACCENT_COLOR; - style.Colors[ImGuiCol_TabHovered] = ACCENT_COLOR_HOVERED; - style.Colors[ImGuiCol_TabActive] = ACCENT_COLOR_ACTIVE; - style.Colors[ImGuiCol_TabUnfocused] = TAB_UNFOCUSED_COLOR; - style.Colors[ImGuiCol_TabUnfocusedActive] = ACCENT_COLOR; if (!ImGui_ImplSDL3_InitForOpenGL(window, context)) { - std::cout << "Failed to initialize Dear ImGui SDL3 backend" << "\n"; + logger.fatal("Failed to initialize Dear ImGui SDL3 backend"); ImGui::DestroyContext(imguiContext); isError = true; return; } - std::cout << "Initialize Dear ImGui SDL3 backend" << "\n"; + logger.info("Initialized Dear ImGui SDL3 backend"); if (!ImGui_ImplOpenGL3_Init(GLSL_VERSION)) { - std::cout << "Failed to initialize Dear ImGui OpenGL backend" << "\n"; + logger.fatal("Failed to initialize Dear ImGui OpenGL backend"); ImGui_ImplSDL3_Shutdown(); ImGui::DestroyContext(imguiContext); isError = true; return; } - std::cout << "Initialize Dear ImGui OpenGL backend" << "\n"; + logger.info("Initialized Dear ImGui OpenGL backend"); + imgui::style::color_set(settings.color); + imgui::style::rounding_set(); math::random_seed_set(); + resource::Audio::volume_set((float)settings.volume / 100); } Loader::~Loader() { + PHYSFS_deinit(); + if (ImGui::GetCurrentContext()) { ImGui_ImplOpenGL3_Shutdown(); @@ -196,6 +218,6 @@ namespace game if (window) SDL_DestroyWindow(window); SDL_Quit(); - std::cout << "Exiting..." << "\n"; + logger.info("Exiting..."); } }; diff --git a/src/loader.hpp b/src/loader.hpp index aa212fa..912733d 100644 --- a/src/loader.hpp +++ b/src/loader.hpp @@ -1,20 +1,22 @@ #pragma once -#include "glm/ext/vector_float2.hpp" +#include "resource/xml/settings.hpp" #include +#include namespace game { class Loader { public: - static constexpr glm::vec2 SIZE = {1080, 720}; + static constexpr glm::vec2 SIZE = {1280, 720}; SDL_Window* window{}; SDL_GLContext context{}; bool isError{}; + resource::xml::Settings settings; - Loader(); + Loader(int argc, const char** argv); ~Loader(); }; diff --git a/src/log.cpp b/src/log.cpp new file mode 100644 index 0000000..910f57e --- /dev/null +++ b/src/log.cpp @@ -0,0 +1,114 @@ +#include "log.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) + #include + #include + #include +#endif + +#include "util/preferences.hpp" +#include "util/time.hpp" + +using namespace game::util; + +namespace game +{ + class StderrToLoggerBuf final : public std::streambuf + { + Logger* logger{}; + std::string buffer; + std::mutex mutex; + + public: + explicit StderrToLoggerBuf(Logger* target) : logger(target) {} + + protected: + int overflow(int ch) override + { + if (ch == traits_type::eof()) return traits_type::not_eof(ch); + std::lock_guard lock(mutex); + if (ch == '\n') + { + if (logger && !buffer.empty()) + { + logger->error(buffer); + buffer.clear(); + } + } + else + { + buffer.push_back(static_cast(ch)); + } + return ch; + } + + int sync() override + { + std::lock_guard lock(mutex); + if (logger && !buffer.empty()) + { + logger->error(buffer); + buffer.clear(); + } + return 0; + } + }; + + std::streambuf* old_stderr_buf = nullptr; + + void Logger::write_raw(const std::string& message) + { + std::println("{}", message); + if (file.is_open()) file << message << '\n' << std::flush; + } + + void Logger::write(const Level level, const std::string& message) + { + std::string formatted = std::format("{} {} {}", LEVEL_STRINGS[level], time::get("(%d-%B-%Y %I:%M:%S)"), message); + write_raw(formatted); + } + + void Logger::info(const std::string& message) { write(LEVEL_INFO, message); } + void Logger::warning(const std::string& message) { write(LEVEL_WARNING, message); } + void Logger::error(const std::string& message) { write(LEVEL_ERROR, message); } + void Logger::fatal(const std::string& message) { write(LEVEL_FATAL, message); } + void Logger::open(const std::filesystem::path& path) { file.open(path, std::ios::out | std::ios::app); } + + std::filesystem::path Logger::path() { return preferences::path() / "log.txt"; } + + Logger::Logger() + { + open(path()); + static StderrToLoggerBuf stderr_buf(this); + old_stderr_buf = std::cerr.rdbuf(&stderr_buf); + std::cerr.setf(std::ios::unitbuf); + std::set_terminate( + [] + { + try + { + if (auto eptr = std::current_exception()) std::rethrow_exception(eptr); + } + catch (const std::exception& ex) + { + logger.fatal(std::string("Unhandled exception: ") + ex.what()); + } + catch (...) + { + logger.fatal("Unhandled exception: "); + } + std::abort(); + }); + } +} + +game::Logger logger; diff --git a/src/log.hpp b/src/log.hpp new file mode 100644 index 0000000..5eaf652 --- /dev/null +++ b/src/log.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include +#include +#include +#include + +namespace game +{ +#define LEVELS \ + X(LEVEL_INFO, "[INFO]") \ + X(LEVEL_WARNING, "[WARNING]") \ + X(LEVEL_ERROR, "[ERROR]") \ + X(LEVEL_FATAL, "[FATAL]") + + enum Level + { +#define X(symbol, string) symbol, + LEVELS +#undef X + }; + + constexpr std::string_view LEVEL_STRINGS[] = { +#define X(symbol, string) string, + LEVELS +#undef X + }; +#undef LEVELS + + class Logger + { + std::ofstream file{}; + + public: + static std::filesystem::path path(); + void write_raw(const std::string&); + void write(const Level, const std::string&); + void info(const std::string&); + void warning(const std::string&); + void error(const std::string&); + void fatal(const std::string&); + void open(const std::filesystem::path&); + Logger(); + }; + +} + +extern game::Logger logger; \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index c1d710b..a80dddd 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,8 +4,8 @@ #include #endif -#include "loader.h" -#include "state.h" +#include "loader.hpp" +#include "state.hpp" using namespace game; @@ -19,13 +19,13 @@ static void emscripten_loop(void* arg) } #endif -int main() +int main(int argc, const char** argv) { - Loader loader; + Loader loader(argc, argv); if (loader.isError) return EXIT_FAILURE; - State state(loader.window, loader.context, Loader::SIZE); + State state(loader.window, loader.context, loader.settings); #ifdef __EMSCRIPTEN__ emscripten_set_main_loop_arg(emscripten_loop, &state, 0, true); diff --git a/src/resource/actor.cpp b/src/resource/actor.cpp deleted file mode 100644 index 9e6ef98..0000000 --- a/src/resource/actor.cpp +++ /dev/null @@ -1,421 +0,0 @@ -#include "actor.h" - -#include "../util/map_.h" -#include "../util/math_.h" -#include "../util/unordered_map_.h" -#include "../util/vector_.h" - -#include "../resource/audio.h" -#include "../resource/texture.h" - -#include -#include - -using namespace glm; -using namespace game::util; -using namespace game::anm2; - -namespace game::resource -{ - Actor::Actor(Anm2* _anm2, vec2 _position, Mode mode, float time) : anm2(_anm2), position(_position) - { - if (anm2) - { - this->mode = mode; - this->startTime = time; - play(anm2->animations.defaultAnimation, mode, time); - } - } - - anm2::Animation* Actor::animation_get(int index) - { - if (!anm2) return nullptr; - if (index == -1) index = animationIndex; - if (anm2->animations.mapReverse.contains(index)) return &anm2->animations.items[index]; - return nullptr; - } - - anm2::Animation* Actor::animation_get(const std::string& name) - { - if (!anm2) return nullptr; - if (anm2->animations.map.contains(name)) return &anm2->animations.items[anm2->animations.map[name]]; - return nullptr; - } - - bool Actor::is_playing(const std::string& name) - { - if (!anm2) return false; - if (name.empty()) - return isPlaying; - else - return isPlaying && anm2->animations.map[name] == animationIndex; - } - - int Actor::animation_index_get(const std::string& name) - { - if (!anm2) return -1; - if (anm2->animations.map.contains(name)) return anm2->animations.map[name]; - return -1; - } - - int Actor::item_id_get(const std::string& name, anm2::Type type) - { - if (!anm2 || (type != anm2::LAYER && type != anm2::NULL_)) return -1; - - if (type == anm2::LAYER) - { - for (int i = 0; i < anm2->content.layers.size(); i++) - if (anm2->content.layers.at(i).name == name) return i; - } - else if (type == anm2::NULL_) - { - for (int i = 0; i < anm2->content.nulls.size(); i++) - if (anm2->content.nulls.at(i).name == name) return i; - } - - return -1; - } - - anm2::Item* Actor::item_get(anm2::Type type, int id, int animationIndex) - { - if (!anm2) return nullptr; - if (animationIndex == -1) animationIndex = this->animationIndex; - if (auto animation = animation_get(animationIndex)) - { - switch (type) - { - case anm2::ROOT: - return &animation->rootAnimation; - break; - case anm2::LAYER: - return unordered_map::find(animation->layerAnimations, id); - case anm2::NULL_: - return map::find(animation->nullAnimations, id); - break; - case anm2::TRIGGER: - return &animation->triggers; - default: - return nullptr; - } - } - - return nullptr; - } - - int Actor::item_length(anm2::Item* item) - { - if (!item) return -1; - - int duration{}; - for (auto& frame : item->frames) - duration += frame.duration; - return duration; - } - - anm2::Frame* Actor::trigger_get(int atFrame) - { - if (auto item = item_get(anm2::TRIGGER)) - for (auto& trigger : item->frames) - if (trigger.atFrame == atFrame) return &trigger; - - return nullptr; - } - - anm2::Frame* Actor::frame_get(int index, anm2::Type type, int id) - { - if (auto item = item_get(type, id)) return vector::find(item->frames, index); - return nullptr; - } - - bool Actor::is_event(const std::string& event) - { - if (!anm2) return false; - if (playedEventID == -1) return false; - return event == anm2->content.events.at(playedEventID).name; - } - - anm2::Frame Actor::frame_generate(anm2::Item& item, float time, anm2::Type type, int id) - { - anm2::Frame frame{}; - frame.isVisible = false; - - if (item.frames.empty()) return frame; - - time = time < 0.0f ? 0.0f : time; - - anm2::Frame* frameNext = nullptr; - anm2::Frame frameNextCopy{}; - int durationCurrent = 0; - int durationNext = 0; - - for (int i = 0; i < item.frames.size(); i++) - { - anm2::Frame& checkFrame = item.frames[i]; - - frame = checkFrame; - - durationNext += frame.duration; - - if (time >= durationCurrent && time < durationNext) - { - if (i + 1 < (int)item.frames.size()) - { - frameNext = &item.frames[i + 1]; - frameNextCopy = *frameNext; - } - else - frameNext = nullptr; - break; - } - - durationCurrent += frame.duration; - } - - for (auto& override : overrides) - { - if (!override || !override->isEnabled) continue; - - if (id == override->destinationID) - { - switch (override->mode) - { - case Override::FRAME_ADD: - if (override->frame.scale.has_value()) - { - frame.scale += *override->frame.scale; - if (frameNext) frameNextCopy.scale += *override->frame.scale; - } - if (override->frame.rotation.has_value()) - { - frame.rotation += *override->frame.rotation; - if (frameNext) frameNextCopy.rotation += *override->frame.rotation; - } - break; - case Override::FRAME_SET: - if (override->frame.scale.has_value()) - { - frame.scale = *override->frame.scale; - if (frameNext) frameNextCopy.scale = *override->frame.scale; - } - if (override->frame.rotation.has_value()) - { - frame.rotation = *override->frame.rotation; - if (frameNext) frameNextCopy.rotation = *override->frame.rotation; - } - break; - case Override::ITEM_SET: - default: - if (override->animationIndex == -1) break; - auto& animation = anm2->animations.items[override->animationIndex]; - auto overrideFrame = frame_generate(animation.layerAnimations[override->sourceID], override->time, - anm2::LAYER, override->sourceID); - frame.crop = overrideFrame.crop; - break; - } - } - } - - if (frame.isInterpolated && frameNext && frame.duration > 1) - { - auto interpolation = (time - durationCurrent) / (durationNext - durationCurrent); - - frame.rotation = glm::mix(frame.rotation, frameNextCopy.rotation, interpolation); - frame.position = glm::mix(frame.position, frameNextCopy.position, interpolation); - frame.scale = glm::mix(frame.scale, frameNextCopy.scale, interpolation); - frame.colorOffset = glm::mix(frame.colorOffset, frameNextCopy.colorOffset, interpolation); - frame.tint = glm::mix(frame.tint, frameNextCopy.tint, interpolation); - } - - return frame; - } - - void Actor::play(int index, Mode mode, float time, float speedMultiplier) - { - this->playedEventID = -1; - this->playedTriggers.clear(); - - if (!anm2) return; - if (mode != FORCE_PLAY && this->animationIndex == index) return; - if (!vector::in_bounds(anm2->animations.items, index)) return; - this->speedMultiplier = speedMultiplier; - this->previousAnimationIndex = animationIndex; - this->animationIndex = index; - this->time = time; - if (mode == PLAY || mode == FORCE_PLAY) isPlaying = true; - } - - void Actor::play(const std::string& name, Mode mode, float time, float speedMultiplier) - { - if (!anm2) return; - if (anm2->animations.map.contains(name)) - play(anm2->animations.map.at(name), mode, time, speedMultiplier); - else - std::cout << "Animation \"" << name << "\" does not exist! Unable to play!\n"; - } - - void Actor::tick() - { - if (!anm2) return; - if (!isPlaying) return; - auto animation = animation_get(); - if (!animation) return; - - playedEventID = -1; - - for (auto& trigger : animation->triggers.frames) - { - if (!playedTriggers.contains(trigger.atFrame) && time >= trigger.atFrame) - { - if (auto sound = map::find(anm2->content.sounds, trigger.soundID)) sound->audio.play(); - playedTriggers.insert((int)trigger.atFrame); - playedEventID = trigger.eventID; - } - } - - auto increment = (anm2->info.fps / 30.0f) * speedMultiplier; - time += increment; - - if (time >= animation->frameNum) - { - if (animation->isLoop) - time = 0.0f; - else - isPlaying = false; - - playedTriggers.clear(); - } - - for (auto& override : overrides) - { - if (!override->isEnabled || override->length < 0) continue; - override->time += increment; - if (override->time > override->length) override->isLoop ? override->time = 0.0f : override->isEnabled = false; - } - } - - glm::vec4 Actor::null_frame_rect(int nullID) - { - auto invalidRect = glm::vec4(0.0f / 0.0f); - if (!anm2 || nullID == -1) return invalidRect; - auto item = item_get(anm2::NULL_, nullID); - if (!item) return invalidRect; - - auto animation = animation_get(); - if (!animation) return invalidRect; - - auto root = frame_generate(animation->rootAnimation, time, anm2::ROOT); - - for (auto& override : overrides) - { - if (!override || !override->isEnabled || override->type != anm2::ROOT) continue; - - switch (override->mode) - { - case Override::FRAME_ADD: - if (override->frame.scale.has_value()) root.scale += *override->frame.scale; - if (override->frame.rotation.has_value()) root.rotation += *override->frame.rotation; - break; - case Override::FRAME_SET: - if (override->frame.scale.has_value()) root.scale = *override->frame.scale; - if (override->frame.rotation.has_value()) root.rotation = *override->frame.rotation; - break; - default: - break; - } - } - - auto frame = frame_generate(*item, time, anm2::NULL_, nullID); - if (!frame.isVisible) return invalidRect; - - auto rootScale = math::to_unit(root.scale); - auto frameScale = math::to_unit(frame.scale); - auto combinedScale = rootScale * frameScale; - auto scaledSize = NULL_SIZE * glm::abs(combinedScale); - - auto worldPosition = position + root.position + frame.position * rootScale; - auto halfSize = scaledSize * 0.5f; - - return glm::vec4(worldPosition - halfSize, scaledSize); - } - - void Actor::render(Shader& textureShader, Shader& rectShader, Canvas& canvas) - { - if (!anm2) return; - auto animation = animation_get(); - if (!animation) return; - - auto root = frame_generate(animation->rootAnimation, time, anm2::ROOT); - - for (auto& override : overrides) - { - if (!override || !override->isEnabled || override->type != anm2::ROOT) continue; - - switch (override->mode) - { - case Override::FRAME_ADD: - if (override->frame.scale.has_value()) root.scale += *override->frame.scale; - if (override->frame.rotation.has_value()) root.rotation += *override->frame.rotation; - break; - case Override::FRAME_SET: - if (override->frame.scale.has_value()) root.scale = *override->frame.scale; - if (override->frame.rotation.has_value()) root.rotation = *override->frame.rotation; - break; - default: - break; - } - } - - auto rootModel = - math::quad_model_parent_get(root.position + position, root.pivot, math::to_unit(root.scale), root.rotation); - - for (auto& i : animation->layerOrder) - { - auto& layerAnimation = animation->layerAnimations[i]; - if (!layerAnimation.isVisible) continue; - - auto layer = map::find(anm2->content.layers, i); - if (!layer) continue; - - auto spritesheet = map::find(anm2->content.spritesheets, layer->spritesheetID); - if (!spritesheet) continue; - - auto frame = frame_generate(layerAnimation, time, anm2::LAYER, i); - if (!frame.isVisible) continue; - - auto model = - math::quad_model_get(frame.size, frame.position, frame.pivot, math::to_unit(frame.scale), frame.rotation); - model = rootModel * model; - - auto& texture = spritesheet->texture; - if (!texture.is_valid()) return; - - auto tint = frame.tint * root.tint; - auto colorOffset = frame.colorOffset + root.colorOffset; - - auto uvMin = frame.crop / vec2(texture.size); - auto uvMax = (frame.crop + frame.size) / vec2(texture.size); - auto uvVertices = math::uv_vertices_get(uvMin, uvMax); - - canvas.texture_render(textureShader, texture.id, model, tint, colorOffset, uvVertices.data()); - } - - if (isShowNulls) - { - for (int i = 0; i < animation->nullAnimations.size(); i++) - { - auto& nullAnimation = animation->nullAnimations[i]; - if (!nullAnimation.isVisible) continue; - - auto frame = frame_generate(nullAnimation, time, anm2::NULL_, i); - if (!frame.isVisible) continue; - - auto model = math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), frame.rotation); - model = rootModel * model; - - canvas.rect_render(rectShader, model); - } - } - } - - void Actor::consume_played_event() { playedEventID = -1; } -}; diff --git a/src/resource/actor.h b/src/resource/actor.h deleted file mode 100644 index 0a5a4a5..0000000 --- a/src/resource/actor.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once - -#include - -#include "../canvas.h" -#include "anm2.h" - -namespace game::resource -{ - class Actor - { - - public: - static constexpr auto NULL_SIZE = glm::vec2(100, 100); - - enum Mode - { - PLAY, - SET, - FORCE_PLAY - }; - - struct Override - { - enum Mode - { - ITEM_SET, - FRAME_ADD, - FRAME_SET - }; - - anm2::FrameOptional frame{}; - int animationIndex{-1}; - int sourceID{-1}; - int destinationID{-1}; - float length{-1.0f}; - bool isLoop{false}; - Mode mode{ITEM_SET}; - anm2::Type type{anm2::LAYER}; - - bool isEnabled{true}; - float time{}; - }; - - anm2::Anm2* anm2{}; - glm::vec2 position{}; - float time{}; - bool isPlaying{}; - bool isShowNulls{}; - int animationIndex{-1}; - int previousAnimationIndex{-1}; - int lastPlayedAnimationIndex{-1}; - int playedEventID{-1}; - Mode mode{PLAY}; - float startTime{}; - float speedMultiplier{}; - - std::unordered_set playedTriggers{}; - std::vector overrides{}; - - Actor(anm2::Anm2*, glm::vec2, Mode = PLAY, float = 0.0f); - anm2::Animation* animation_get(int = -1); - anm2::Animation* animation_get(const std::string&); - int animation_index_get(const std::string&); - anm2::Item* item_get(anm2::Type, int = -1, int = -1); - int item_length(anm2::Item*); - anm2::Frame* trigger_get(int); - anm2::Frame* frame_get(int, anm2::Type, int = -1); - int item_id_get(const std::string&, anm2::Type = anm2::LAYER); - anm2::Frame frame_generate(anm2::Item&, float, anm2::Type, int = -1); - void play(const std::string&, Mode = PLAY, float = 0.0f, float = 1.0f); - void play(int, Mode = PLAY, float = 0.0f, float = 1.0f); - bool is_event(const std::string& event); - void tick(); - bool is_playing(const std::string& name = {}); - void render(Shader& textureShader, Shader& rectShader, Canvas&); - glm::vec4 null_frame_rect(int = -1); - void consume_played_event(); - }; -} \ No newline at end of file diff --git a/src/resource/anm2.cpp b/src/resource/anm2.cpp deleted file mode 100644 index 608a201..0000000 --- a/src/resource/anm2.cpp +++ /dev/null @@ -1,234 +0,0 @@ -#include "anm2.h" - -#include - -#include "../util/xml_.h" - -using namespace tinyxml2; -using namespace game::resource; -using namespace game::util; - -namespace game::anm2 -{ - Info::Info(XMLElement* element) - { - if (!element) return; - element->QueryIntAttribute("Fps", &fps); - } - - Spritesheet::Spritesheet(XMLElement* element, int& id) - { - if (!element) return; - element->QueryIntAttribute("Id", &id); - xml::query_path_attribute(element, "Path", &path); - texture = Texture(path); - } - - Layer::Layer(XMLElement* element, int& id) - { - if (!element) return; - element->QueryIntAttribute("Id", &id); - xml::query_string_attribute(element, "Name", &name); - element->QueryIntAttribute("SpritesheetId", &spritesheetID); - } - - Null::Null(XMLElement* element, int& id) - { - if (!element) return; - element->QueryIntAttribute("Id", &id); - xml::query_string_attribute(element, "Name", &name); - element->QueryBoolAttribute("ShowRect", &isShowRect); - } - - Event::Event(XMLElement* element, int& id) - { - if (!element) return; - element->QueryIntAttribute("Id", &id); - xml::query_string_attribute(element, "Name", &name); - } - - Sound::Sound(XMLElement* element, int& id) - { - if (!element) return; - element->QueryIntAttribute("Id", &id); - xml::query_path_attribute(element, "Path", &path); - audio = Audio(path); - } - - Content::Content(XMLElement* element) - { - if (auto spritesheetsElement = element->FirstChildElement("Spritesheets")) - { - for (auto child = spritesheetsElement->FirstChildElement("Spritesheet"); child; - child = child->NextSiblingElement("Spritesheet")) - { - int spritesheetId{}; - Spritesheet spritesheet(child, spritesheetId); - spritesheets.emplace(spritesheetId, std::move(spritesheet)); - } - } - - if (auto layersElement = element->FirstChildElement("Layers")) - { - for (auto child = layersElement->FirstChildElement("Layer"); child; child = child->NextSiblingElement("Layer")) - { - int layerId{}; - Layer layer(child, layerId); - layers.emplace(layerId, std::move(layer)); - } - } - - if (auto nullsElement = element->FirstChildElement("Nulls")) - { - for (auto child = nullsElement->FirstChildElement("Null"); child; child = child->NextSiblingElement("Null")) - { - int nullId{}; - Null null(child, nullId); - nulls.emplace(nullId, std::move(null)); - } - } - - if (auto eventsElement = element->FirstChildElement("Events")) - { - for (auto child = eventsElement->FirstChildElement("Event"); child; child = child->NextSiblingElement("Event")) - { - int eventId{}; - Event event(child, eventId); - events.emplace(eventId, std::move(event)); - } - } - - if (auto soundsElement = element->FirstChildElement("Sounds")) - { - for (auto child = soundsElement->FirstChildElement("Sound"); child; child = child->NextSiblingElement("Sound")) - { - int soundId{}; - Sound sound(child, soundId); - sounds.emplace(soundId, std::move(sound)); - } - } - } - - Frame::Frame(XMLElement* element, Type type) - { - if (type != TRIGGER) - { - element->QueryFloatAttribute("XPosition", &position.x); - element->QueryFloatAttribute("YPosition", &position.y); - if (type == LAYER) - { - element->QueryFloatAttribute("XPivot", &pivot.x); - element->QueryFloatAttribute("YPivot", &pivot.y); - element->QueryFloatAttribute("XCrop", &crop.x); - element->QueryFloatAttribute("YCrop", &crop.y); - element->QueryFloatAttribute("Width", &size.x); - element->QueryFloatAttribute("Height", &size.y); - } - element->QueryFloatAttribute("XScale", &scale.x); - element->QueryFloatAttribute("YScale", &scale.y); - element->QueryIntAttribute("Delay", &duration); - element->QueryBoolAttribute("Visible", &isVisible); - xml::query_color_attribute(element, "RedTint", &tint.r); - xml::query_color_attribute(element, "GreenTint", &tint.g); - xml::query_color_attribute(element, "BlueTint", &tint.b); - xml::query_color_attribute(element, "AlphaTint", &tint.a); - xml::query_color_attribute(element, "RedOffset", &colorOffset.r); - xml::query_color_attribute(element, "GreenOffset", &colorOffset.g); - xml::query_color_attribute(element, "BlueOffset", &colorOffset.b); - element->QueryFloatAttribute("Rotation", &rotation); - element->QueryBoolAttribute("Interpolated", &isInterpolated); - } - else - { - element->QueryIntAttribute("EventId", &eventID); - element->QueryIntAttribute("SoundId", &soundID); - element->QueryIntAttribute("AtFrame", &atFrame); - } - } - - Item::Item(XMLElement* element, Type type, int& id) - { - if (type == LAYER) element->QueryIntAttribute("LayerId", &id); - if (type == NULL_) element->QueryIntAttribute("NullId", &id); - - element->QueryBoolAttribute("Visible", &isVisible); - - for (auto child = type == TRIGGER ? element->FirstChildElement("Trigger") : element->FirstChildElement("Frame"); - child; child = type == TRIGGER ? child->NextSiblingElement("Trigger") : child->NextSiblingElement("Frame")) - frames.emplace_back(Frame(child, type)); - } - - Animation::Animation(XMLElement* element) - { - xml::query_string_attribute(element, "Name", &name); - element->QueryIntAttribute("FrameNum", &frameNum); - element->QueryBoolAttribute("Loop", &isLoop); - - int id{-1}; - - if (auto rootAnimationElement = element->FirstChildElement("RootAnimation")) - rootAnimation = Item(rootAnimationElement, ROOT, id); - - if (auto layerAnimationsElement = element->FirstChildElement("LayerAnimations")) - { - for (auto child = layerAnimationsElement->FirstChildElement("LayerAnimation"); child; - child = child->NextSiblingElement("LayerAnimation")) - { - Item layerAnimation(child, LAYER, id); - layerOrder.push_back(id); - layerAnimations.emplace(id, std::move(layerAnimation)); - } - } - - if (auto nullAnimationsElement = element->FirstChildElement("NullAnimations")) - { - for (auto child = nullAnimationsElement->FirstChildElement("NullAnimation"); child; - child = child->NextSiblingElement("NullAnimation")) - { - Item nullAnimation(child, NULL_, id); - nullAnimations.emplace(id, std::move(nullAnimation)); - } - } - - if (auto triggersElement = element->FirstChildElement("Triggers")) triggers = Item(triggersElement, TRIGGER, id); - } - - Animations::Animations(XMLElement* element) - { - xml::query_string_attribute(element, "DefaultAnimation", &defaultAnimation); - - for (auto child = element->FirstChildElement("Animation"); child; child = child->NextSiblingElement("Animation")) - items.emplace_back(Animation(child)); - - for (int i = 0; i < items.size(); i++) - { - auto& item = items.at(i); - map[item.name] = i; - mapReverse[i] = item.name; - } - } - - Anm2::Anm2(const std::filesystem::path& path) - { - XMLDocument document; - - if (document.LoadFile(path.c_str()) != XML_SUCCESS) - { - std::cout << "Failed to initialize anm2: " << document.ErrorStr() << "\n"; - return; - } - - auto previousPath = std::filesystem::current_path(); - std::filesystem::current_path(path.parent_path()); - - auto element = document.RootElement(); - - if (auto infoElement = element->FirstChildElement("Info")) info = Info(infoElement); - if (auto contentElement = element->FirstChildElement("Content")) content = Content(contentElement); - if (auto animationsElement = element->FirstChildElement("Animations")) animations = Animations(animationsElement); - - std::filesystem::current_path(previousPath); - - std::cout << "Initialzed anm2: " << path.string() << "\n"; - } -} diff --git a/src/resource/anm2.hpp b/src/resource/anm2.hpp deleted file mode 100644 index 6ed65af..0000000 --- a/src/resource/anm2.hpp +++ /dev/null @@ -1,176 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include - -#include - -#include "audio.h" -#include "texture.h" - -namespace game::anm2 -{ - enum Type - { - NONE, - ROOT, - LAYER, - NULL_, - TRIGGER - }; - - class Info - { - public: - int fps = 30; - - Info() = default; - Info(tinyxml2::XMLElement*); - }; - - class Spritesheet - { - public: - std::filesystem::path path{}; - resource::Texture texture{}; - - Spritesheet(tinyxml2::XMLElement*, int&); - }; - - class Layer - { - public: - std::string name{"New Layer"}; - int spritesheetID{-1}; - Layer(tinyxml2::XMLElement*, int&); - }; - - class Null - { - public: - std::string name{"New Null"}; - bool isShowRect{}; - Null(tinyxml2::XMLElement*, int&); - }; - - class Event - { - public: - std::string name{"New Event"}; - Event(tinyxml2::XMLElement*, int&); - }; - - class Sound - { - public: - std::filesystem::path path{}; - resource::Audio audio{}; - - Sound(tinyxml2::XMLElement*, int&); - }; - - class Content - { - public: - std::map spritesheets{}; - std::map layers{}; - std::map nulls{}; - std::map events{}; - std::map sounds{}; - - Content() = default; - Content(tinyxml2::XMLElement*); - }; - - struct Frame - { - glm::vec2 crop{}; - glm::vec2 position{}; - glm::vec2 pivot{}; - glm::vec2 size{}; - glm::vec2 scale{100, 100}; - float rotation{}; - int duration{}; - glm::vec4 tint{1.0f, 1.0f, 1.0f, 1.0f}; - glm::vec3 colorOffset{}; - bool isInterpolated{}; - int eventID{-1}; - int soundID{-1}; - int atFrame{-1}; - - bool isVisible{true}; - - Frame() = default; - Frame(tinyxml2::XMLElement*, Type); - }; - - struct FrameOptional - { - std::optional crop{}; - std::optional position{}; - std::optional pivot{}; - std::optional size{}; - std::optional scale{}; - std::optional rotation{}; - std::optional tint{}; - std::optional colorOffset{}; - std::optional isInterpolated{}; - std::optional isVisible{}; - }; - - class Item - { - public: - std::vector frames{}; - bool isVisible{}; - - Item() = default; - Item(tinyxml2::XMLElement*, Type, int&); - }; - - class Animation - { - public: - std::string name{"New Animation"}; - int frameNum{}; - bool isLoop{}; - - Item rootAnimation{}; - std::unordered_map layerAnimations{}; - std::vector layerOrder{}; - std::map nullAnimations{}; - Item triggers{}; - - Animation() = default; - Animation(tinyxml2::XMLElement*); - }; - - class Animations - { - public: - std::string defaultAnimation{}; - std::vector items{}; - std::unordered_map map{}; - std::unordered_map mapReverse{}; - - Animations() = default; - Animations(tinyxml2::XMLElement*); - }; - - class Anm2 - { - public: - Info info; - Content content{}; - Animations animations{}; - - Anm2() = default; - Anm2(const std::filesystem::path&); - }; -} diff --git a/src/resource/audio.cpp b/src/resource/audio.cpp index cbec0b6..1c608d2 100644 --- a/src/resource/audio.cpp +++ b/src/resource/audio.cpp @@ -1,73 +1,119 @@ -#include "audio.h" +#include "audio.hpp" #include -#include +#include "../log.hpp" +#include +#include + +using namespace game::util; namespace game::resource { + static std::shared_ptr audio_make(MIX_Audio* audio) + { + return std::shared_ptr(audio, + [](MIX_Audio* a) + { + if (a) MIX_DestroyAudio(a); + }); + } + + static std::unordered_map> audioCache{}; + + static std::shared_ptr cache_get(const std::string& key) + { + auto it = audioCache.find(key); + if (it == audioCache.end()) return {}; + + auto cached = it->second.lock(); + if (!cached) audioCache.erase(it); + return cached; + } + + static void cache_set(const std::string& key, const std::shared_ptr& audio) + { + if (!audio) return; + audioCache[key] = audio; + } + MIX_Mixer* Audio::mixer_get() { static auto mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr); return mixer; } - void Audio::set_gain(float gain) + void Audio::volume_set(float volume) { auto mixer = mixer_get(); - MIX_SetMasterGain(mixer, gain); - } - - void Audio::retain() - { - if (refCount) ++(*refCount); - } - - void Audio::release() - { - if (refCount) - { - if (--(*refCount) == 0) - { - if (internal) MIX_DestroyAudio(internal); - delete refCount; - } - refCount = nullptr; - } - internal = nullptr; + MIX_SetMasterGain(mixer, volume); } Audio::Audio(const std::filesystem::path& path) { - internal = MIX_LoadAudio(mixer_get(), path.c_str(), true); + auto key = std::string("fs:") + path.string(); + internal = cache_get(key); if (internal) { - refCount = new int(1); - std::cout << "Initialized audio: '" << path.string() << "'\n"; + logger.info(std::format("Using cached audio: {}", path.string())); + return; } - else + + internal = audio_make(MIX_LoadAudio(mixer_get(), path.c_str(), true)); + cache_set(key, internal); + if (internal) logger.info(std::format("Initialized audio: {}", path.string())); + + if (!internal) logger.info(std::format("Failed to intialize audio: {} ({})", path.string(), SDL_GetError())); + } + + Audio::Audio(const physfs::Path& path) + { + if (!path.is_valid()) { - std::cout << "Failed to initialize audio: '" << path.string() << "'\n"; + logger.error( + std::format("Failed to initialize audio from PhysicsFS path: {}", path.c_str(), physfs::error_get())); + return; } + + auto key = std::string("physfs:") + path.c_str(); + internal = cache_get(key); + if (internal) + { + logger.info(std::format("Using cached audio: {}", path.c_str())); + return; + } + + auto buffer = path.read(); + + if (buffer.empty()) + { + logger.error( + std::format("Failed to initialize audio from PhysicsFS path: {} ({})", path.c_str(), physfs::error_get())); + return; + } + + auto ioStream = SDL_IOFromConstMem(buffer.data(), buffer.size()); + + internal = audio_make(MIX_LoadAudio_IO(mixer_get(), ioStream, false, true)); + cache_set(key, internal); + if (internal) + logger.info(std::format("Initialized audio: {}", path.c_str())); + else + logger.info(std::format("Failed to intialize audio: {} ({})", path.c_str(), SDL_GetError())); } Audio::Audio(const Audio& other) { internal = other.internal; - refCount = other.refCount; - retain(); track = nullptr; } Audio::Audio(Audio&& other) noexcept { - internal = other.internal; + internal = std::move(other.internal); track = other.track; - refCount = other.refCount; - other.internal = nullptr; other.track = nullptr; - other.refCount = nullptr; } Audio& Audio::operator=(const Audio& other) @@ -76,8 +122,7 @@ namespace game::resource { unload(); internal = other.internal; - refCount = other.refCount; - retain(); + track = nullptr; } return *this; } @@ -87,13 +132,10 @@ namespace game::resource if (this != &other) { unload(); - internal = other.internal; + internal = std::move(other.internal); track = other.track; - refCount = other.refCount; - other.internal = nullptr; other.track = nullptr; - other.refCount = nullptr; } return *this; } @@ -105,7 +147,7 @@ namespace game::resource MIX_DestroyTrack(track); track = nullptr; } - release(); + internal.reset(); } void Audio::play(bool isLoop) @@ -126,7 +168,7 @@ namespace game::resource if (!track) return; } - MIX_SetTrackAudio(track, internal); + MIX_SetTrackAudio(track, internal.get()); SDL_PropertiesID options = 0; @@ -149,5 +191,5 @@ namespace game::resource bool Audio::is_playing() const { return track && MIX_TrackPlaying(track); } Audio::~Audio() { unload(); } - bool Audio::is_valid() const { return internal != nullptr; } + bool Audio::is_valid() const { return (bool)internal; } } diff --git a/src/resource/audio.hpp b/src/resource/audio.hpp index 400a4a7..84106c2 100644 --- a/src/resource/audio.hpp +++ b/src/resource/audio.hpp @@ -2,22 +2,24 @@ #include #include +#include + +#include "../util/physfs.hpp" namespace game::resource { class Audio { - MIX_Audio* internal{nullptr}; - MIX_Track* track{nullptr}; - int* refCount{nullptr}; static MIX_Mixer* mixer_get(); void unload(); - void retain(); - void release(); + + std::shared_ptr internal{}; + MIX_Track* track{nullptr}; public: Audio() = default; Audio(const std::filesystem::path&); + Audio(const util::physfs::Path&); Audio(const Audio&); Audio(Audio&&) noexcept; Audio& operator=(const Audio&); @@ -27,6 +29,6 @@ namespace game::resource void play(bool isLoop = false); void stop(); bool is_playing() const; - static void set_gain(float vol); + static void volume_set(float volume); }; } diff --git a/src/resource/dialogue.cpp b/src/resource/dialogue.cpp deleted file mode 100644 index 8f4d772..0000000 --- a/src/resource/dialogue.cpp +++ /dev/null @@ -1,137 +0,0 @@ -#include "dialogue.h" - -#include - -#include "../util/map_.h" -#include "../util/xml_.h" - -using namespace tinyxml2; -using namespace game::util; - -namespace game::resource -{ - void label_map_query(XMLElement* element, std::map& labelMap, const char* attribute, int& id) - { - std::string label{}; - xml::query_string_attribute(element, attribute, &label); - if (auto foundID = map::find(labelMap, label)) - id = *foundID; - else - id = -1; - } - - Dialogue::Color::Color(XMLElement* element) - { - if (!element) return; - element->QueryIntAttribute("Start", &start); - element->QueryIntAttribute("End", &end); - xml::query_color_attribute(element, "R", &value.r); - xml::query_color_attribute(element, "G", &value.g); - xml::query_color_attribute(element, "B", &value.b); - xml::query_color_attribute(element, "A", &value.a); - } - - Dialogue::Animation::Animation(XMLElement* element) - { - if (!element) return; - element->QueryIntAttribute("At", &at); - xml::query_string_attribute(element, "Name", &name); - } - - Dialogue::Branch::Branch(XMLElement* element, std::map& labelMap) - { - if (!element) return; - label_map_query(element, labelMap, "Label", nextID); - xml::query_string_attribute(element, "Content", &content); - } - - Dialogue::Entry::Entry(XMLElement* element, std::map& labelMap) - { - if (!element) return; - - xml::query_string_attribute(element, "Content", &content); - label_map_query(element, labelMap, "Next", nextID); - - std::string flagString{}; - xml::query_string_attribute(element, "Flag", &flagString); - - for (int i = 0; i < std::size(FLAG_STRINGS); i++) - { - if (flagString == FLAG_STRINGS[i]) - { - flag = (Flag)i; - break; - } - } - - for (auto child = element->FirstChildElement("Color"); child; child = child->NextSiblingElement("Color")) - colors.emplace_back(child); - - for (auto child = element->FirstChildElement("Animation"); child; child = child->NextSiblingElement("Animation")) - animations.emplace_back(child); - - for (auto child = element->FirstChildElement("Branch"); child; child = child->NextSiblingElement("Branch")) - branches.emplace_back(child, labelMap); - } - - Dialogue::Dialogue(const std::string& path) - { - XMLDocument document; - - if (document.LoadFile(path.c_str()) != XML_SUCCESS) - { - std::cout << "Failed to initialize dialogue: " << document.ErrorStr() << "\n"; - return; - } - - auto element = document.RootElement(); - int id{}; - - for (auto child = element->FirstChildElement("Entry"); child; child = child->NextSiblingElement("Entry")) - { - std::string label{}; - xml::query_string_attribute(child, "Label", &label); - labelMap.emplace(label, id++); - } - - id = 0; - - for (auto child = element->FirstChildElement("Entry"); child; child = child->NextSiblingElement("Entry")) - entryMap.emplace(id++, Entry(child, labelMap)); - - for (auto& [label, id] : labelMap) - { - if (label.starts_with(BURP_SMALL_LABEL)) burpSmallIDs.emplace_back(id); - if (label.starts_with(BURP_BIG_LABEL)) burpBigIDs.emplace_back(id); - if (label.starts_with(EAT_HUNGRY_LABEL)) eatHungryIDs.emplace_back(id); - if (label.starts_with(EAT_FULL_LABEL)) eatFullIDs.emplace_back(id); - if (label.starts_with(FULL_LABEL)) fullIDs.emplace_back(id); - if (label.starts_with(CAPACITY_LOW_LABEL)) capacityLowIDs.emplace_back(id); - if (label.starts_with(FEED_HUNGRY_LABEL)) feedHungryIDs.emplace_back(id); - if (label.starts_with(FEED_FULL_LABEL)) feedFullIDs.emplace_back(id); - if (label.starts_with(FOOD_STOLEN_LABEL)) foodStolenIDs.emplace_back(id); - if (label.starts_with(FOOD_EASED_LABEL)) foodEasedIDs.emplace_back(id); - if (label.starts_with(PERFECT_LABEL)) perfectIDs.emplace_back(id); - if (label.starts_with(MISS_LABEL)) missIDs.emplace_back(id); - if (label.starts_with(POST_DIGEST_LABEL)) postDigestIDs.emplace_back(id); - if (label.starts_with(RANDOM_LABEL)) randomIDs.emplace_back(id); - } - - std::cout << "Initialzed dialogue: " << path << "\n"; - } - - Dialogue::Entry* Dialogue::get(int id) - { - if (id == -1) return nullptr; - return map::find(entryMap, id); - } - - Dialogue::Entry* Dialogue::get(const std::string& label) - { - auto id = map::find(labelMap, label); - if (!id) return nullptr; - return get(*id); - } - - Dialogue::Entry* Dialogue::next(Dialogue::Entry* entry) { return get(entry->nextID); } -} \ No newline at end of file diff --git a/src/resource/dialogue.hpp b/src/resource/dialogue.hpp deleted file mode 100644 index 9cfe3be..0000000 --- a/src/resource/dialogue.hpp +++ /dev/null @@ -1,118 +0,0 @@ -#pragma once - -#include "glm/ext/vector_float4.hpp" - -#include - -#include - -#include - -namespace game::resource -{ - class Dialogue - { - public: - static constexpr auto FULL_LABEL = "Full"; - static constexpr auto POST_DIGEST_LABEL = "PostDigest"; - static constexpr auto BURP_SMALL_LABEL = "BurpSmall"; - static constexpr auto BURP_BIG_LABEL = "BurpBig"; - static constexpr auto FEED_HUNGRY_LABEL = "FeedHungry"; - static constexpr auto FEED_FULL_LABEL = "FeedFull"; - static constexpr auto EAT_HUNGRY_LABEL = "EatHungry"; - static constexpr auto EAT_FULL_LABEL = "EatFull"; - static constexpr auto FOOD_STOLEN_LABEL = "FoodStolen"; - static constexpr auto FOOD_EASED_LABEL = "FoodEased"; - static constexpr auto CAPACITY_LOW_LABEL = "CapacityLow"; - static constexpr auto PERFECT_LABEL = "Perfect"; - static constexpr auto MISS_LABEL = "Miss"; - static constexpr auto RANDOM_LABEL = "StartRandom"; - ; - - class Color - { - public: - int start{}; - int end{}; - glm::vec4 value{}; - - Color(tinyxml2::XMLElement*); - }; - - class Animation - { - public: - int at{-1}; - std::string name{}; - - Animation(tinyxml2::XMLElement*); - }; - - class Branch - { - public: - std::string content{}; - int nextID{-1}; - - Branch(tinyxml2::XMLElement*, std::map&); - }; - - class Entry - { - public: -#define FLAGS \ - X(NONE, "None") \ - X(ACTIVATE_WINDOWS, "ActivateWindows") \ - X(DEACTIVATE_WINDOWS, "DeactivateWindows") \ - X(ONLY_INFO, "OnlyInfo") \ - X(ACTIVATE_CHEATS, "ActivateCheats") - - enum Flag - { -#define X(symbol, name) symbol, - FLAGS -#undef X - }; - - static constexpr const char* FLAG_STRINGS[] = { -#define X(symbol, name) name, - FLAGS -#undef X - }; - -#undef FLAGS - - std::string content{}; - std::vector colors{}; - std::vector animations{}; - std::vector branches{}; - int nextID{-1}; - Flag flag{Flag::NONE}; - - Entry(tinyxml2::XMLElement*, std::map&); - }; - - std::map labelMap; - std::map entryMap{}; - - std::vector eatHungryIDs{}; - std::vector eatFullIDs{}; - std::vector feedHungryIDs{}; - std::vector feedFullIDs{}; - std::vector burpSmallIDs{}; - std::vector burpBigIDs{}; - std::vector fullIDs{}; - std::vector foodStolenIDs{}; - std::vector foodEasedIDs{}; - std::vector perfectIDs{}; - std::vector postDigestIDs{}; - std::vector missIDs{}; - std::vector capacityLowIDs{}; - std::vector randomIDs{}; - - Dialogue(const std::string&); - Entry* get(const std::string&); - Entry* get(int = -1); - Entry* next(Entry*); - }; -} \ No newline at end of file diff --git a/src/resource/font.cpp b/src/resource/font.cpp index e13c8cb..a10a817 100644 --- a/src/resource/font.cpp +++ b/src/resource/font.cpp @@ -1,10 +1,52 @@ -#include "font.h" +#include "font.hpp" + +#include "../log.hpp" + +using namespace game::util; namespace game::resource { - Font::Font(const std::string& path, float size) + Font::Font(const std::filesystem::path& path, float size) { - internal = ImGui::GetIO().Fonts->AddFontFromFileTTF(path.c_str(), size); + ImFontConfig config; + config.FontDataOwnedByAtlas = false; + + internal = ImGui::GetIO().Fonts->AddFontFromFileTTF(path.c_str(), size, &config); + + if (internal) + logger.info(std::format("Initialized font: {}", path.c_str())); + else + logger.error(std::format("Failed to initialize font: {}", path.c_str())); } + + Font::Font(const physfs::Path& path, float size) + { + if (!path.is_valid()) + { + logger.error( + std::format("Failed to initialize font from PhysicsFS path: {} ({})", path.c_str(), physfs::error_get())); + return; + } + + auto buffer = path.read(); + + if (buffer.empty()) + { + logger.error( + std::format("Failed to initialize font from PhysicsFS path: {} ({})", path.c_str(), physfs::error_get())); + return; + } + + ImFontConfig config; + config.FontDataOwnedByAtlas = false; + + internal = ImGui::GetIO().Fonts->AddFontFromMemoryTTF(buffer.data(), (int)buffer.size(), size, &config); + + if (internal) + logger.info(std::format("Initialized font: {}", path.c_str())); + else + logger.error(std::format("Failed to initialize font: {}", path.c_str())); + } + ImFont* Font::get() { return internal; }; -} \ No newline at end of file +} diff --git a/src/resource/font.hpp b/src/resource/font.hpp index 51bd832..d4e7dfe 100644 --- a/src/resource/font.hpp +++ b/src/resource/font.hpp @@ -1,20 +1,28 @@ #pragma once -#include "imgui.h" -#include +#include + +#include + +#include "../util/physfs.hpp" namespace game::resource { class Font { + ImFont* internal{}; + public: - ImFont* internal; + static constexpr auto NORMAL = 20; + static constexpr auto ABOVE_AVERAGE = 24; + static constexpr auto BIG = 30; + static constexpr auto HEADER_3 = 40; + static constexpr auto HEADER_2 = 50; + static constexpr auto HEADER_1 = 60; - static constexpr auto NORMAL = 12; - static constexpr auto BIG = 16; - static constexpr auto LARGE = 24; - - Font(const std::string&, float = NORMAL); + Font() = default; + Font(const std::filesystem::path&, float = NORMAL); + Font(const util::physfs::Path&, float = NORMAL); ImFont* get(); }; -} \ No newline at end of file +} diff --git a/src/resource/shader.cpp b/src/resource/shader.cpp index df9c2b6..af5d695 100644 --- a/src/resource/shader.cpp +++ b/src/resource/shader.cpp @@ -1,6 +1,6 @@ -#include "shader.h" +#include "shader.hpp" -#include +#include "../log.hpp" namespace game::resource { @@ -20,7 +20,7 @@ namespace game::resource glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &logLength); std::string log(logLength, '\0'); if (logLength > 0) glGetShaderInfoLog(shaderHandle, logLength, nullptr, log.data()); - std::cout << "Failed to compile shader: " << log << '\n'; + logger.error(std::format("Failed to compile shader: {}", log)); return false; } return true; @@ -49,11 +49,11 @@ namespace game::resource if (!isLinked) { glDeleteProgram(id); + logger.error(std::format("Failed to link shader: {}", id)); id = 0; - std::cout << "Failed to link shader: " << id << "\n"; } else - std::cout << "Initialized shader: " << id << "\n"; + logger.info(std::format("Initialized shader: {}", id)); glDeleteShader(vertexHandle); glDeleteShader(fragmentHandle); diff --git a/src/resource/texture.cpp b/src/resource/texture.cpp index 18e1d7a..02c72db 100644 --- a/src/resource/texture.cpp +++ b/src/resource/texture.cpp @@ -1,60 +1,75 @@ -#include "texture.h" +#include "texture.hpp" -#if defined(__clang__) || defined(__GNUC__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wmissing-field-initializers" - #pragma GCC diagnostic ignored "-Wunused-function" -#endif +#include +#include +#include -#define STBI_ONLY_PNG -#define STB_IMAGE_IMPLEMENTATION -#include - -#if defined(__clang__) || defined(__GNUC__) - #pragma GCC diagnostic pop -#endif - -#include +#include "../log.hpp" using namespace glm; +using namespace game::util; namespace game::resource { + struct CachedTexture + { + std::weak_ptr idShared{}; + glm::ivec2 size{}; + int channels{}; + }; + + static std::unordered_map textureCache{}; + + static bool cache_get(const std::string& key, std::shared_ptr& idShared, GLuint& id, ivec2& size, int& channels) + { + auto it = textureCache.find(key); + if (it == textureCache.end()) return false; + + auto shared = it->second.idShared.lock(); + if (!shared) + { + textureCache.erase(it); + return false; + } + + idShared = shared; + id = *shared; + size = it->second.size; + channels = it->second.channels; + return true; + } + + static void cache_set(const std::string& key, const std::shared_ptr& idShared, ivec2 size, int channels) + { + if (!idShared) return; + textureCache[key] = CachedTexture{.idShared = idShared, .size = size, .channels = channels}; + } + + static std::shared_ptr texture_id_make(GLuint id) + { + return std::shared_ptr(new GLuint(id), + [](GLuint* p) + { + if (!p) return; + if (*p != 0) glDeleteTextures(1, p); + delete p; + }); + } + bool Texture::is_valid() const { return id != 0; } - void Texture::retain() + Texture::~Texture() { - if (refCount) ++(*refCount); - } - - void Texture::release() - { - if (refCount) - { - if (--(*refCount) == 0) - { - if (is_valid()) glDeleteTextures(1, &id); - delete refCount; - } - refCount = nullptr; - } - else if (is_valid()) - { - glDeleteTextures(1, &id); - } - + idShared.reset(); id = 0; } - Texture::~Texture() { release(); } - Texture::Texture(const Texture& other) { id = other.id; size = other.size; channels = other.channels; - refCount = other.refCount; - retain(); + idShared = other.idShared; } Texture::Texture(Texture&& other) noexcept @@ -62,24 +77,21 @@ namespace game::resource id = other.id; size = other.size; channels = other.channels; - refCount = other.refCount; + idShared = std::move(other.idShared); other.id = 0; other.size = {}; other.channels = 0; - other.refCount = nullptr; } Texture& Texture::operator=(const Texture& other) { if (this != &other) { - release(); + idShared = other.idShared; id = other.id; size = other.size; channels = other.channels; - refCount = other.refCount; - retain(); } return *this; } @@ -88,45 +100,103 @@ namespace game::resource { if (this != &other) { - release(); + idShared.reset(); id = other.id; size = other.size; channels = other.channels; - refCount = other.refCount; + idShared = std::move(other.idShared); other.id = 0; other.size = {}; other.channels = 0; - other.refCount = nullptr; } return *this; } + void Texture::init(const uint8_t* data) + { + idShared.reset(); + id = 0; + + GLuint newId{}; + glGenTextures(1, &newId); + glBindTexture(GL_TEXTURE_2D, newId); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_2D, 0); + channels = CHANNELS; + + idShared = texture_id_make(newId); + id = newId; + } + Texture::Texture(const std::filesystem::path& path) { - if (auto data = stbi_load(path.c_str(), &size.x, &size.y, nullptr, CHANNELS); data) + auto key = std::string("fs:") + path.string(); + if (cache_get(key, idShared, id, size, channels)) { - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_2D, id); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - glBindTexture(GL_TEXTURE_2D, 0); - stbi_image_free(data); - channels = CHANNELS; - refCount = new int(1); - std::cout << "Initialized texture: '" << path.string() << "\n"; + logger.info(std::format("Using cached texture: {}", path.string())); + return; + } + + if (auto surface = SDL_LoadPNG(path.c_str())) + { + auto rgbaSurface = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_RGBA32); + SDL_DestroySurface(surface); + surface = rgbaSurface; + this->size = ivec2(surface->w, surface->h); + init((const uint8_t*)surface->pixels); + SDL_DestroySurface(surface); + cache_set(key, idShared, this->size, channels); + logger.info(std::format("Initialized texture: {}", path.string())); } else + logger.error(std::format("Failed to initialize texture: {} ({})", path.string(), SDL_GetError())); + } + + Texture::Texture(const physfs::Path& path) + { + if (!path.is_valid()) { - id = 0; - size = {}; - channels = 0; - refCount = nullptr; - std::cout << "Failed to initialize texture: '" << path.string() << "'\n"; + logger.error( + std::format("Failed to initialize texture from PhysicsFS path: {}", path.c_str(), physfs::error_get())); + return; } + + auto key = std::string("physfs:") + path.c_str(); + if (cache_get(key, idShared, id, size, channels)) + { + logger.info(std::format("Using cached texture: {}", path.c_str())); + return; + } + + auto buffer = path.read(); + + if (buffer.empty()) + { + logger.error( + std::format("Failed to initialize texture from PhysicsFS path: {} ({})", path.c_str(), physfs::error_get())); + return; + } + + auto ioStream = SDL_IOFromConstMem(buffer.data(), buffer.size()); + + if (auto surface = SDL_LoadPNG_IO(ioStream, true)) + { + auto rgbaSurface = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_RGBA32); + SDL_DestroySurface(surface); + surface = rgbaSurface; + this->size = ivec2(surface->w, surface->h); + init((const uint8_t*)surface->pixels); + SDL_DestroySurface(surface); + cache_set(key, idShared, this->size, channels); + logger.info(std::format("Initialized texture: {}", path.c_str())); + } + else + logger.error(std::format("Failed to initialize texture: {} ({})", path.c_str(), SDL_GetError())); } } diff --git a/src/resource/texture.hpp b/src/resource/texture.hpp index 813a347..c3155d2 100644 --- a/src/resource/texture.hpp +++ b/src/resource/texture.hpp @@ -6,8 +6,12 @@ #include #endif +#include #include #include +#include + +#include "../util/physfs.hpp" namespace game::resource { @@ -29,10 +33,10 @@ namespace game::resource Texture& operator=(const Texture&); Texture& operator=(Texture&&) noexcept; Texture(const std::filesystem::path&); + Texture(const util::physfs::Path&); + void init(const uint8_t*); private: - int* refCount{nullptr}; - void retain(); - void release(); + std::shared_ptr idShared{}; }; } diff --git a/src/resource/xml/animation_entry.cpp b/src/resource/xml/animation_entry.cpp new file mode 100644 index 0000000..598248c --- /dev/null +++ b/src/resource/xml/animation_entry.cpp @@ -0,0 +1,11 @@ +#include "animation_entry.hpp" + +#include "../../util/vector.hpp" + +namespace game::resource::xml +{ + const std::string& AnimationEntryCollection::get() + { + return at(util::vector::random_index_weighted(*this, [](const auto& entry) { return entry.weight; })).animation; + } +} diff --git a/src/resource/xml/animation_entry.hpp b/src/resource/xml/animation_entry.hpp new file mode 100644 index 0000000..a816114 --- /dev/null +++ b/src/resource/xml/animation_entry.hpp @@ -0,0 +1,23 @@ +// Handles animation entries in .xml files. "Weight" value determines weight of being randomly selected. + +#pragma once + +#include +#include + +namespace game::resource::xml +{ + class AnimationEntry + { + public: + std::string animation{}; + float weight{1.0f}; + }; + + class AnimationEntryCollection : public std::vector + { + public: + const std::string& get(); + }; + +} diff --git a/src/resource/xml/anm2.cpp b/src/resource/xml/anm2.cpp new file mode 100644 index 0000000..6cea45d --- /dev/null +++ b/src/resource/xml/anm2.cpp @@ -0,0 +1,338 @@ +#include "anm2.hpp" +#include "util.hpp" + +#include "../../util/working_directory.hpp" + +#include "../../log.hpp" + +#include + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Anm2::Anm2(const Anm2&) = default; + Anm2::Anm2(Anm2&&) = default; + Anm2& Anm2::operator=(const Anm2&) = default; + Anm2& Anm2::operator=(Anm2&&) = default; + + void Anm2::init(XMLDocument& document, Flags flags, const physfs::Path& archive) + { + this->flags = flags; + + auto element = document.RootElement(); + if (!element) return; + + auto parse_frame = [&](XMLElement* element, Type type, int spritesheetID = -1) + { + Frame frame{}; + if (!element) return frame; + + if (type != TRIGGER) + { + element->QueryFloatAttribute("XPosition", &frame.position.x); + element->QueryFloatAttribute("YPosition", &frame.position.y); + if (type == LAYER) + { + if (element->FindAttribute("RegionId") && spritesheets.contains(spritesheetID)) + { + auto& spritesheet = spritesheets.at(spritesheetID); + element->QueryIntAttribute("RegionId", &frame.regionID); + auto& region = spritesheet.regions.at(frame.regionID); + frame.crop = region.crop; + frame.size = region.size; + frame.pivot = region.origin == Spritesheet::Region::Origin::CENTER + ? glm::vec2(glm::ivec2(frame.size * 0.5f)) + : region.origin == Spritesheet::Region::Origin::TOP_LEFT ? glm::vec2{} + : region.pivot; + } + else + { + element->QueryFloatAttribute("XPivot", &frame.pivot.x); + element->QueryFloatAttribute("YPivot", &frame.pivot.y); + element->QueryFloatAttribute("XCrop", &frame.crop.x); + element->QueryFloatAttribute("YCrop", &frame.crop.y); + element->QueryFloatAttribute("Width", &frame.size.x); + element->QueryFloatAttribute("Height", &frame.size.y); + } + } + element->QueryFloatAttribute("XScale", &frame.scale.x); + element->QueryFloatAttribute("YScale", &frame.scale.y); + element->QueryIntAttribute("Delay", &frame.duration); + element->QueryBoolAttribute("Visible", &frame.isVisible); + xml::query_color_attribute(element, "RedTint", &frame.tint.r); + xml::query_color_attribute(element, "GreenTint", &frame.tint.g); + xml::query_color_attribute(element, "BlueTint", &frame.tint.b); + xml::query_color_attribute(element, "AlphaTint", &frame.tint.a); + xml::query_color_attribute(element, "RedOffset", &frame.colorOffset.r); + xml::query_color_attribute(element, "GreenOffset", &frame.colorOffset.g); + xml::query_color_attribute(element, "BlueOffset", &frame.colorOffset.b); + element->QueryFloatAttribute("Rotation", &frame.rotation); + element->QueryBoolAttribute("Interpolated", &frame.isInterpolated); + } + else + { + for (auto child = element->FirstChildElement("Sound"); child; child = child->NextSiblingElement("Sound")) + { + int soundID{}; + child->QueryIntAttribute("Id", &soundID); + frame.soundIDs.emplace_back(soundID); + } + + element->QueryIntAttribute("EventId", &frame.eventID); + element->QueryIntAttribute("AtFrame", &frame.atFrame); + } + + return frame; + }; + + auto parse_item = [&](XMLElement* element, Type type, int& id) + { + Item item{}; + if (!element) return item; + + if (type == LAYER) element->QueryIntAttribute("LayerId", &id); + if (type == NULL_) element->QueryIntAttribute("NullId", &id); + + element->QueryBoolAttribute("Visible", &item.isVisible); + + for (auto child = type == TRIGGER ? element->FirstChildElement("Trigger") : element->FirstChildElement("Frame"); + child; child = type == TRIGGER ? child->NextSiblingElement("Trigger") : child->NextSiblingElement("Frame")) + item.frames.emplace_back(parse_frame(child, type, type == LAYER ? layers.at(id).spritesheetID : -1)); + + return item; + }; + + auto parse_animation = [&](XMLElement* element) + { + Animation animation{}; + if (!element) return animation; + + xml::query_string_attribute(element, "Name", &animation.name); + element->QueryIntAttribute("FrameNum", &animation.frameNum); + element->QueryBoolAttribute("Loop", &animation.isLoop); + + int id{-1}; + + if (auto rootAnimationElement = element->FirstChildElement("RootAnimation")) + animation.rootAnimation = parse_item(rootAnimationElement, ROOT, id); + + if (auto layerAnimationsElement = element->FirstChildElement("LayerAnimations")) + { + for (auto child = layerAnimationsElement->FirstChildElement("LayerAnimation"); child; + child = child->NextSiblingElement("LayerAnimation")) + { + auto layerAnimation = parse_item(child, LAYER, id); + animation.layerOrder.push_back(id); + animation.layerAnimations.emplace(id, std::move(layerAnimation)); + } + } + + if (auto nullAnimationsElement = element->FirstChildElement("NullAnimations")) + { + for (auto child = nullAnimationsElement->FirstChildElement("NullAnimation"); child; + child = child->NextSiblingElement("NullAnimation")) + { + auto nullAnimation = parse_item(child, NULL_, id); + animation.nullAnimations.emplace(id, std::move(nullAnimation)); + } + } + + if (auto triggersElement = element->FirstChildElement("Triggers")) + animation.triggers = parse_item(triggersElement, TRIGGER, id); + + return animation; + }; + + if (auto infoElement = element->FirstChildElement("Info")) infoElement->QueryIntAttribute("Fps", &fps); + + if (auto contentElement = element->FirstChildElement("Content")) + { + if (auto spritesheetsElement = contentElement->FirstChildElement("Spritesheets")) + { + for (auto child = spritesheetsElement->FirstChildElement("Spritesheet"); child; + child = child->NextSiblingElement("Spritesheet")) + { + int spritesheetId{}; + Spritesheet spritesheet{}; + child->QueryIntAttribute("Id", &spritesheetId); + xml::query_string_attribute(child, "Path", &spritesheet.path); + + if ((this->flags & NO_SPRITESHEETS) != 0) + spritesheet.texture = Texture(); + else if (!archive.empty()) + spritesheet.texture = Texture(physfs::Path(archive + "/" + spritesheet.path)); + else + spritesheet.texture = Texture(std::filesystem::path(spritesheet.path)); + + for (auto regionChild = child->FirstChildElement("Region"); regionChild; + regionChild = regionChild->NextSiblingElement("Region")) + { + Spritesheet::Region region{}; + int regionID{}; + + regionChild->QueryIntAttribute("Id", ®ionID); + xml::query_string_attribute(regionChild, "Name", ®ion.name); + regionChild->QueryFloatAttribute("XCrop", ®ion.crop.x); + regionChild->QueryFloatAttribute("YCrop", ®ion.crop.y); + regionChild->QueryFloatAttribute("Width", ®ion.size.x); + regionChild->QueryFloatAttribute("Height", ®ion.size.y); + + if (regionChild->FindAttribute("Origin")) + { + std::string origin{}; + xml::query_string_attribute(regionChild, "Origin", &origin); + region.origin = origin == "Center" ? Spritesheet::Region::CENTER + : origin == "TopLeft" ? Spritesheet::Region::TOP_LEFT + : Spritesheet::Region::CUSTOM; + } + else + { + regionChild->QueryFloatAttribute("XPivot", ®ion.pivot.x); + regionChild->QueryFloatAttribute("YPivot", ®ion.pivot.y); + } + + spritesheet.regions.emplace(regionID, std::move(region)); + spritesheet.regionOrder.emplace_back(regionID); + } + + spritesheets.emplace(spritesheetId, std::move(spritesheet)); + } + } + + if (auto layersElement = contentElement->FirstChildElement("Layers")) + { + for (auto child = layersElement->FirstChildElement("Layer"); child; child = child->NextSiblingElement("Layer")) + { + int layerId{}; + Layer layer{}; + child->QueryIntAttribute("Id", &layerId); + xml::query_string_attribute(child, "Name", &layer.name); + child->QueryIntAttribute("SpritesheetId", &layer.spritesheetID); + layerMap[layer.name] = layerId; + layers.emplace(layerId, std::move(layer)); + } + } + + if (auto nullsElement = contentElement->FirstChildElement("Nulls")) + { + for (auto child = nullsElement->FirstChildElement("Null"); child; child = child->NextSiblingElement("Null")) + { + int nullId{}; + Null null{}; + child->QueryIntAttribute("Id", &nullId); + xml::query_string_attribute(child, "Name", &null.name); + child->QueryBoolAttribute("ShowRect", &null.isShowRect); + nullMap[null.name] = nullId; + nulls.emplace(nullId, std::move(null)); + } + } + + if (auto eventsElement = contentElement->FirstChildElement("Events")) + { + for (auto child = eventsElement->FirstChildElement("Event"); child; child = child->NextSiblingElement("Event")) + { + int eventId{}; + Event event{}; + child->QueryIntAttribute("Id", &eventId); + xml::query_string_attribute(child, "Name", &event.name); + eventMap[event.name] = eventId; + events.emplace(eventId, std::move(event)); + } + } + + if (auto soundsElement = contentElement->FirstChildElement("Sounds")) + { + for (auto child = soundsElement->FirstChildElement("Sound"); child; child = child->NextSiblingElement("Sound")) + { + int soundId{}; + Sound sound{}; + child->QueryIntAttribute("Id", &soundId); + xml::query_string_attribute(child, "Path", &sound.path); + if ((this->flags & NO_SOUNDS) != 0) + sound.audio = Audio(); + else if (!archive.empty()) + sound.audio = Audio(physfs::Path(archive + "/" + sound.path)); + else + sound.audio = Audio(std::filesystem::path(sound.path)); + sounds.emplace(soundId, std::move(sound)); + } + } + } + + if (auto animationsElement = element->FirstChildElement("Animations")) + { + xml::query_string_attribute(animationsElement, "DefaultAnimation", &defaultAnimation); + + for (auto child = animationsElement->FirstChildElement("Animation"); child; + child = child->NextSiblingElement("Animation")) + { + if ((this->flags & DEFAULT_ANIMATION_ONLY) != 0) + { + std::string name{}; + xml::query_string_attribute(child, "Name", &name); + if (name == defaultAnimation) + { + animations.emplace_back(parse_animation(child)); + break; + } + } + else + animations.emplace_back(parse_animation(child)); + } + + for (int i = 0; i < (int)animations.size(); i++) + { + auto& animation = animations[i]; + animationMap[animation.name] = i; + animationMapReverse[i] = animation.name; + } + + if (animationMap.contains(defaultAnimation)) + defaultAnimationID = animationMap[defaultAnimation]; + else + defaultAnimationID = -1; + } + + isValid = true; + } + + Anm2::Anm2(const std::filesystem::path& path, Flags flags) + { + XMLDocument document; + + if (document.LoadFile(path.c_str()) != XML_SUCCESS) + { + logger.error(std::format("Failed to initialize anm2: {} ({})", path.string(), document.ErrorStr())); + isValid = false; + return; + } + + WorkingDirectory workingDirectory(path, WorkingDirectory::FILE); + + this->path = path.string(); + + init(document, flags); + + logger.info(std::format("Initialized anm2: {}", path.string())); + } + + Anm2::Anm2(const physfs::Path& path, Flags flags) + { + XMLDocument document; + + if (xml::document_load(path, document) != XML_SUCCESS) + { + isValid = false; + return; + } + + this->path = path; + init(document, flags, path.directory_get()); + + logger.info(std::format("Initialized anm2: {}", path.c_str())); + } + + bool Anm2::is_valid() const { return isValid; } +} diff --git a/src/resource/xml/anm2.hpp b/src/resource/xml/anm2.hpp new file mode 100644 index 0000000..c467247 --- /dev/null +++ b/src/resource/xml/anm2.hpp @@ -0,0 +1,177 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "../audio.hpp" +#include "../texture.hpp" + +#include "../../util/physfs.hpp" + +namespace game::resource::xml +{ + class Anm2 + { + public: + enum Type + { + NONE, + ROOT, + LAYER, + NULL_, + TRIGGER + }; + + enum Flag + { + NO_SPRITESHEETS = (1 << 0), + NO_SOUNDS = (1 << 1), + DEFAULT_ANIMATION_ONLY = (1 << 2) + }; + + using Flags = int; + + struct Spritesheet + { + struct Region + { + enum Origin + { + TOP_LEFT, + CENTER, + CUSTOM + }; + + std::string name{}; + glm::vec2 crop{}; + glm::vec2 pivot{}; + glm::vec2 size{}; + Origin origin{CUSTOM}; + }; + + std::string path{}; + resource::Texture texture{}; + + std::map regions{}; + std::vector regionOrder{}; + }; + + struct Sound + { + std::string path{}; + resource::Audio audio{}; + }; + + struct Layer + { + std::string name{"New Layer"}; + int spritesheetID{-1}; + }; + + struct Null + { + std::string name{"New Null"}; + bool isShowRect{}; + }; + + struct Event + { + std::string name{"New Event"}; + }; + + struct Frame + { + glm::vec2 crop{}; + glm::vec2 position{}; + glm::vec2 pivot{}; + glm::vec2 size{}; + glm::vec2 scale{100, 100}; + float rotation{}; + int duration{}; + glm::vec4 tint{1.0f, 1.0f, 1.0f, 1.0f}; + glm::vec3 colorOffset{}; + bool isInterpolated{}; + int eventID{-1}; + int regionID{-1}; + std::vector soundIDs{}; + int atFrame{-1}; + + bool isVisible{true}; + }; + + struct FrameOptional + { + std::optional crop{}; + std::optional position{}; + std::optional pivot{}; + std::optional size{}; + std::optional scale{}; + std::optional rotation{}; + std::optional tint{}; + std::optional colorOffset{}; + std::optional isInterpolated{}; + std::optional isVisible{}; + }; + + struct Item + { + std::vector frames{}; + bool isVisible{}; + }; + + struct Animation + { + std::string name{"New Animation"}; + int frameNum{}; + bool isLoop{}; + + Item rootAnimation{}; + std::unordered_map layerAnimations{}; + std::vector layerOrder{}; + std::map nullAnimations{}; + Item triggers{}; + }; + + int fps{30}; + + std::map spritesheets{}; + std::map layers{}; + std::map nulls{}; + std::map events{}; + std::map sounds{}; + + std::unordered_map layerMap{}; + std::unordered_map nullMap{}; + std::unordered_map eventMap{}; + + std::string defaultAnimation{}; + int defaultAnimationID{-1}; + std::vector animations{}; + std::unordered_map animationMap{}; + std::unordered_map animationMapReverse{}; + std::string path{}; + bool isValid{}; + Flags flags{}; + + Anm2() = default; + Anm2(const Anm2&); + Anm2(Anm2&&); + Anm2& operator=(const Anm2&); + Anm2& operator=(Anm2&&); + Anm2(const std::filesystem::path&, Flags = 0); + Anm2(const util::physfs::Path&, Flags = 0); + + bool is_valid() const; + + private: + void init(tinyxml2::XMLDocument& document, Flags flags, const util::physfs::Path& archive = {}); + }; +} diff --git a/src/resource/xml/area.cpp b/src/resource/xml/area.cpp new file mode 100644 index 0000000..12d3d43 --- /dev/null +++ b/src/resource/xml/area.cpp @@ -0,0 +1,45 @@ +#include "area.hpp" + +#include "../../log.hpp" + +#include "util.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Area::Area(const physfs::Path& path) + { + XMLDocument document; + + if (document_load(path, document) != XML_SUCCESS) return; + + auto archive = path.directory_get(); + + if (auto root = document.RootElement()) + { + std::string textureRootPath{}; + query_string_attribute(root, "TextureRootPath", &textureRootPath); + + for (auto child = root->FirstChildElement("Area"); child; child = child->NextSiblingElement("Area")) + { + Entry area{}; + + query_texture(child, "Texture", archive, textureRootPath, area.texture); + child->QueryFloatAttribute("Gravity", &area.gravity); + child->QueryFloatAttribute("Friction", &area.friction); + + areas.emplace_back(std::move(area)); + } + } + + if (areas.empty()) areas.emplace_back(Entry()); + + isValid = true; + + logger.info(std::format("Initialized area schema: {}", path.c_str())); + } + + bool Area::is_valid() const { return isValid; }; +} diff --git a/src/resource/xml/area.hpp b/src/resource/xml/area.hpp new file mode 100644 index 0000000..862517d --- /dev/null +++ b/src/resource/xml/area.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include "../texture.hpp" +#include "../../util/physfs.hpp" + +namespace game::resource::xml +{ + class Area + { + public: + struct Entry + { + Texture texture{}; + float gravity{0.95f}; + float friction{0.80f}; + float airResistance{0.975f}; + }; + + std::vector areas{}; + bool isValid{}; + + Area() = default; + Area(const util::physfs::Path&); + + bool is_valid() const; + }; +} diff --git a/src/resource/xml/character.cpp b/src/resource/xml/character.cpp new file mode 100644 index 0000000..de51d88 --- /dev/null +++ b/src/resource/xml/character.cpp @@ -0,0 +1,233 @@ +#include "character.hpp" + +#include + +#include "../../log.hpp" +#include "../../util/preferences.hpp" +#include "util.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Character::Character(const std::filesystem::path& path) + { + XMLDocument document; + + physfs::Archive archive(path, path.filename().string()); + + if (!archive.is_valid()) + { + logger.error(std::format("Failed to initialize character from PhysicsFS archive: {} ({})", path.string(), + physfs::error_get())); + return; + } + + physfs::Path characterPath(archive + "/" + "character.xml"); + + if (document_load(characterPath, document) != XML_SUCCESS) return; + + if (auto root = document.RootElement()) + { + std::string textureRootPath{}; + query_string_attribute(root, "TextureRootPath", &textureRootPath); + + std::string soundRootPath{}; + query_string_attribute(root, "SoundRootPath", &soundRootPath); + + query_anm2(root, "Anm2", archive, textureRootPath, anm2); + query_string_attribute(root, "Name", &name); + + root->QueryFloatAttribute("Weight", &weight); + root->QueryFloatAttribute("WeightMin", &weightMin); + root->QueryFloatAttribute("WeightMax", &weightMax); + + root->QueryFloatAttribute("Capacity", &capacity); + root->QueryFloatAttribute("CapacityMin", &capacityMin); + root->QueryFloatAttribute("CapacityMax", &capacityMax); + root->QueryFloatAttribute("CapacityMaxMultiplier", &capacityMaxMultiplier); + root->QueryFloatAttribute("CapacityIfOverStuffedOnDigestBonus", &capacityIfOverStuffedOnDigestBonus); + + root->QueryFloatAttribute("CaloriesToKilogram", &caloriesToKilogram); + + root->QueryFloatAttribute("DigestionRate", &digestionRate); + root->QueryFloatAttribute("DigestionRateMin", &digestionRateMin); + root->QueryFloatAttribute("DigestionRateMax", &digestionRateMax); + root->QueryIntAttribute("DigestionTimerMax", &digestionTimerMax); + + root->QueryFloatAttribute("EatSpeed", &eatSpeed); + root->QueryFloatAttribute("EatSpeedMin", &eatSpeedMin); + root->QueryFloatAttribute("EatSpeedMax", &eatSpeedMax); + + root->QueryFloatAttribute("BlinkChance", &blinkChance); + root->QueryFloatAttribute("GurgleChance", &gurgleChance); + root->QueryFloatAttribute("GurgleCapacityMultiplier", &gurgleCapacityMultiplier); + + auto dialoguePath = physfs::Path(archive + "/" + "dialogue.xml"); + + if (!dialoguePath.is_valid()) + logger.warning(std::format("No character dialogue.xml file found: {}", path.string())); + else + dialogue = Dialogue(dialoguePath); + + dialogue.query_pool_id(root, "DialoguePoolID", pool.id); + + if (auto element = root->FirstChildElement("AlternateSpritesheet")) + { + query_texture(element, "Texture", archive, textureRootPath, alternateSpritesheet.texture); + query_sound(element, "Sound", archive, soundRootPath, alternateSpritesheet.sound); + element->QueryIntAttribute("ID", &alternateSpritesheet.id); + element->QueryFloatAttribute("ChanceOnNewGame", &alternateSpritesheet.chanceOnNewGame); + } + + if (auto element = root->FirstChildElement("Animations")) + { + query_animation_entry_collection(element, "FinishFood", animations.finishFood); + query_animation_entry_collection(element, "PostDigest", animations.postDigest); + + if (auto child = element->FirstChildElement("Idle")) + query_string_attribute(child, "Animation", &animations.idle); + + if (auto child = element->FirstChildElement("IdleFull")) + query_string_attribute(child, "Animation", &animations.idleFull); + + if (auto child = element->FirstChildElement("StageUp")) + query_string_attribute(child, "Animation", &animations.stageUp); + } + + if (auto element = root->FirstChildElement("Sounds")) + { + query_sound_entry_collection(element, "Digest", archive, soundRootPath, sounds.digest); + query_sound_entry_collection(element, "Gurgle", archive, soundRootPath, sounds.gurgle); + } + + if (auto element = root->FirstChildElement("Overrides")) + { + if (auto child = element->FirstChildElement("Talk")) + { + query_layer_id(child, "LayerSource", anm2, talkOverride.layerSource); + query_layer_id(child, "LayerDestination", anm2, talkOverride.layerDestination); + } + + if (auto child = element->FirstChildElement("Blink")) + { + query_layer_id(child, "LayerSource", anm2, blinkOverride.layerSource); + query_layer_id(child, "LayerDestination", anm2, blinkOverride.layerDestination); + } + } + + if (auto element = root->FirstChildElement("Stages")) + { + for (auto child = element->FirstChildElement("Stage"); child; child = child->NextSiblingElement("Stage")) + { + Stage stage{}; + child->QueryFloatAttribute("Threshold", &stage.threshold); + child->QueryIntAttribute("AreaID", &stage.areaID); + dialogue.query_pool_id(child, "DialoguePoolID", stage.pool.id); + stages.emplace_back(std::move(stage)); + } + } + + if (auto element = root->FirstChildElement("EatAreas")) + { + for (auto child = element->FirstChildElement("EatArea"); child; child = child->NextSiblingElement("EatArea")) + { + EatArea eatArea{}; + query_null_id(child, "Null", anm2, eatArea.nullID); + query_event_id(child, "Event", anm2, eatArea.eventID); + query_string_attribute(child, "Animation", &eatArea.animation); + + eatAreas.emplace_back(std::move(eatArea)); + } + } + + if (auto element = root->FirstChildElement("ExpandAreas")) + { + for (auto child = element->FirstChildElement("ExpandArea"); child; + child = child->NextSiblingElement("ExpandArea")) + { + ExpandArea expandArea{}; + + query_layer_id(child, "Layer", anm2, expandArea.layerID); + query_null_id(child, "Null", anm2, expandArea.nullID); + child->QueryFloatAttribute("ScaleAdd", &expandArea.scaleAdd); + + expandAreas.emplace_back(std::move(expandArea)); + } + } + + if (auto element = root->FirstChildElement("InteractAreas")) + { + for (auto child = element->FirstChildElement("InteractArea"); child; + child = child->NextSiblingElement("InteractArea")) + { + InteractArea interactArea{}; + + if (child->FindAttribute("Layer")) query_layer_id(child, "Layer", anm2, interactArea.layerID); + + query_null_id(child, "Null", anm2, interactArea.nullID); + query_string_attribute(child, "Animation", &interactArea.animation); + query_string_attribute(child, "AnimationFull", &interactArea.animationFull); + query_string_attribute(child, "AnimationCursorHover", &interactArea.animationCursorHover); + query_string_attribute(child, "AnimationCursorActive", &interactArea.animationCursorActive); + query_sound_entry_collection(child, "Sound", archive, soundRootPath, interactArea.sound, "Path"); + dialogue.query_pool_id(child, "DialoguePoolID", interactArea.pool.id); + child->QueryFloatAttribute("DigestionBonusRub", &interactArea.digestionBonusRub); + child->QueryFloatAttribute("DigestionBonusClick", &interactArea.digestionBonusClick); + child->QueryFloatAttribute("Time", &interactArea.time); + child->QueryFloatAttribute("ScaleEffectAmplitude", &interactArea.scaleEffectAmplitude); + child->QueryFloatAttribute("ScaleEffectCycles", &interactArea.scaleEffectCycles); + + std::string typeString{}; + query_string_attribute(child, "Type", &typeString); + + for (int i = 0; i < (int)std::size(INTERACT_TYPE_STRINGS); i++) + if (typeString == INTERACT_TYPE_STRINGS[i]) interactArea.type = (InteractType)i; + + interactAreas.emplace_back(std::move(interactArea)); + } + } + } + + auto itemSchemaPath = physfs::Path(archive + "/" + "items.xml"); + + if (auto itemSchemaPath = physfs::Path(archive + "/" + "items.xml"); itemSchemaPath.is_valid()) + itemSchema = Item(itemSchemaPath); + else + logger.warning(std::format("No character items.xml file found: {}", path.string())); + + if (auto areaSchemaPath = physfs::Path(archive + "/" + "areas.xml"); areaSchemaPath.is_valid()) + areaSchema = Area(areaSchemaPath); + else + logger.warning(std::format("No character areas.xml file found: {}", path.string())); + + if (auto menuSchemaPath = physfs::Path(archive + "/" + "menu.xml"); menuSchemaPath.is_valid()) + menuSchema = Menu(menuSchemaPath); + else + logger.warning(std::format("No character menu.xml file found: {}", path.string())); + + if (auto cursorSchemaPath = physfs::Path(archive + "/" + "cursor.xml"); cursorSchemaPath.is_valid()) + cursorSchema = Cursor(cursorSchemaPath); + else + logger.warning(std::format("No character cursor.xml file found: {}", path.string())); + + if (auto playSchemaPath = physfs::Path(archive + "/" + "play.xml"); playSchemaPath.is_valid()) + playSchema = Play(playSchemaPath, dialogue); + else + logger.warning(std::format("No character play.xml file found: {}", path.string())); + + logger.info(std::format("Initialized character: {}", name)); + + this->path = path; + save = Save(save_path_get()); + } + + std::filesystem::path Character::save_path_get() + { + auto savePath = path.stem(); + savePath = preferences::path() / "saves" / savePath.replace_extension(".save"); + std::filesystem::create_directories(savePath.parent_path()); + return savePath; + } +} diff --git a/src/resource/xml/character.hpp b/src/resource/xml/character.hpp new file mode 100644 index 0000000..3d10558 --- /dev/null +++ b/src/resource/xml/character.hpp @@ -0,0 +1,144 @@ +#pragma once + +#include +#include + +#include "../../util/interact_type.hpp" +#include "../audio.hpp" +#include "animation_entry.hpp" +#include "anm2.hpp" +#include "area.hpp" +#include "cursor.hpp" +#include "dialogue.hpp" +#include "item.hpp" +#include "menu.hpp" +#include "play.hpp" +#include "save.hpp" + +namespace game::resource::xml +{ + class Character + { + public: + struct Stage + { + float threshold{}; + int areaID{}; + Dialogue::PoolReference pool{-1}; + }; + + struct EatArea + { + int nullID{-1}; + int eventID{-1}; + std::string animation{}; + }; + + struct ExpandArea + { + int layerID{-1}; + int nullID{-1}; + float scaleAdd{}; + }; + + struct InteractArea + { + std::string animation{}; + std::string animationFull{}; + std::string animationCursorActive{}; + std::string animationCursorHover{}; + SoundEntryCollection sound{}; + + int nullID{-1}; + int layerID{-1}; + InteractType type{(InteractType)-1}; + Dialogue::PoolReference pool{-1}; + + float digestionBonusRub{}; + float digestionBonusClick{}; + float time{}; + float scaleEffectAmplitude{}; + float scaleEffectCycles{}; + }; + + struct Animations + { + AnimationEntryCollection finishFood{}; + AnimationEntryCollection postDigest{}; + + std::string idle{}; + std::string idleFull{}; + std::string stageUp{}; + }; + + struct Sounds + { + SoundEntryCollection gurgle{}; + SoundEntryCollection digest{}; + }; + + struct Override + { + int layerSource{}; + int layerDestination{}; + }; + + struct AlternateSpritesheet + { + Texture texture{}; + Audio sound{}; + int id{-1}; + float chanceOnNewGame{0.001}; + }; + + Anm2 anm2{}; + Area areaSchema{}; + Dialogue dialogue{}; + Item itemSchema{}; + Menu menuSchema{}; + Cursor cursorSchema{}; + Play playSchema{}; + + Save save{}; + + Animations animations{}; + Override talkOverride{}; + Override blinkOverride{}; + + Sounds sounds{}; + + std::vector stages{}; + std::vector expandAreas{}; + std::vector eatAreas{}; + std::vector interactAreas{}; + + AlternateSpritesheet alternateSpritesheet{}; + + std::string name{}; + std::filesystem::path path{}; + float weight{50}; + float weightMin{}; + float weightMax{999}; + float capacity{2000.0f}; + float capacityMin{2000.0f}; + float capacityMax{99999.0f}; + float capacityMaxMultiplier{1.5f}; + float capacityIfOverStuffedOnDigestBonus{0.25f}; + float caloriesToKilogram{1000.0f}; + float digestionRate{0.05f}; + float digestionRateMin{0.0f}; + float digestionRateMax{0.25f}; + int digestionTimerMax{60}; + float eatSpeed{1.0f}; + float eatSpeedMin{1.0f}; + float eatSpeedMax{3.0f}; + float blinkChance{1.0f}; + float gurgleChance{1.0f}; + float gurgleCapacityMultiplier{1.0f}; + Dialogue::PoolReference pool{-1}; + + Character() = default; + Character(const std::filesystem::path&); + std::filesystem::path save_path_get(); + }; +} diff --git a/src/resource/xml/character_preview.cpp b/src/resource/xml/character_preview.cpp new file mode 100644 index 0000000..3781c82 --- /dev/null +++ b/src/resource/xml/character_preview.cpp @@ -0,0 +1,66 @@ +#include "character_preview.hpp" + +#include + +#include "../../log.hpp" +#include "../../util/preferences.hpp" +#include "util.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + CharacterPreview::CharacterPreview(const std::filesystem::path& path) + { + XMLDocument document; + + physfs::Archive archive(path, path.filename().string()); + + if (!archive.is_valid()) + { + logger.error(std::format("Failed to initialize character preview from PhysicsFS archive: {} ({})", path.string(), + physfs::error_get())); + return; + } + + physfs::Path characterPath(archive + "/" + "character.xml"); + + if (document_load(characterPath, document) != XML_SUCCESS) return; + + if (auto root = document.RootElement()) + { + std::string textureRootPath{}; + query_string_attribute(root, "TextureRootPath", &textureRootPath); + + query_anm2(root, "Anm2", archive, textureRootPath, anm2, Anm2::NO_SOUNDS | Anm2::DEFAULT_ANIMATION_ONLY); + query_texture(root, "Render", archive, textureRootPath, render); + query_texture(root, "Portrait", archive, textureRootPath, portrait); + + query_string_attribute(root, "Name", &name); + query_string_attribute(root, "Description", &description); + query_string_attribute(root, "Author", &author); + root->QueryFloatAttribute("Weight", &weight); + + if (auto element = root->FirstChildElement("Stages")) + for (auto child = element->FirstChildElement("Stage"); child; child = child->NextSiblingElement("Stage")) + stages++; + } + + this->path = path; + save = Save(save_path_get()); + isValid = true; + + logger.info(std::format("Initialized character preview: {}", name)); + } + + std::filesystem::path CharacterPreview::save_path_get() + { + auto savePath = path.stem(); + savePath = preferences::path() / "saves" / savePath.replace_extension(".save"); + std::filesystem::create_directories(savePath.parent_path()); + return savePath; + } + + bool CharacterPreview::is_valid() const { return isValid; } +} diff --git a/src/resource/xml/character_preview.hpp b/src/resource/xml/character_preview.hpp new file mode 100644 index 0000000..b3de36d --- /dev/null +++ b/src/resource/xml/character_preview.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include + +#include "anm2.hpp" +#include "save.hpp" + +namespace game::resource::xml +{ + class CharacterPreview + { + public: + struct Stage + { + float threshold{}; + int dialoguePoolID{-1}; + }; + + Anm2 anm2{}; + Texture portrait{}; + Texture render{}; + Save save{}; + + int stages{1}; + + std::string name{}; + std::string author{}; + std::string description{}; + std::filesystem::path path{}; + float weight{50}; + + bool isValid{}; + + CharacterPreview() = default; + CharacterPreview(const std::filesystem::path&); + + std::filesystem::path save_path_get(); + bool is_valid() const; + }; +} diff --git a/src/resource/xml/cursor.cpp b/src/resource/xml/cursor.cpp new file mode 100644 index 0000000..4868fff --- /dev/null +++ b/src/resource/xml/cursor.cpp @@ -0,0 +1,52 @@ +#include "cursor.hpp" + +#include "../../log.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Cursor::Cursor(const physfs::Path& path) + { + XMLDocument document; + + if (document_load(path, document) != XML_SUCCESS) return; + + auto archive = path.directory_get(); + + if (auto root = document.RootElement()) + { + std::string textureRootPath{}; + query_string_attribute(root, "TextureRootPath", &textureRootPath); + + std::string soundRootPath{}; + query_string_attribute(root, "SoundRootPath", &soundRootPath); + + query_anm2(root, "Anm2", archive, textureRootPath, anm2); + + if (auto element = root->FirstChildElement("Animations")) + { + query_animation_entry_collection(element, "Idle", animations.idle); + query_animation_entry_collection(element, "Hover", animations.hover); + query_animation_entry_collection(element, "Grab", animations.grab); + query_animation_entry_collection(element, "Pan", animations.pan); + query_animation_entry_collection(element, "Zoom", animations.zoom); + query_animation_entry_collection(element, "Return", animations.return_); + } + + if (auto element = root->FirstChildElement("Sounds")) + { + query_sound_entry_collection(element, "Grab", archive, soundRootPath, sounds.grab); + query_sound_entry_collection(element, "Release", archive, soundRootPath, sounds.release); + query_sound_entry_collection(element, "Throw", archive, soundRootPath, sounds.throw_); + } + } + + isValid = true; + + logger.info(std::format("Initialized area schema: {}", path.c_str())); + } + + bool Cursor::is_valid() const { return isValid; }; +} \ No newline at end of file diff --git a/src/resource/xml/cursor.hpp b/src/resource/xml/cursor.hpp new file mode 100644 index 0000000..1e759d9 --- /dev/null +++ b/src/resource/xml/cursor.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include "util.hpp" + +namespace game::resource::xml +{ + class Cursor + { + public: + struct Animations + { + AnimationEntryCollection idle{}; + AnimationEntryCollection hover{}; + AnimationEntryCollection grab{}; + AnimationEntryCollection pan{}; + AnimationEntryCollection zoom{}; + AnimationEntryCollection return_{}; + }; + + struct Sounds + { + SoundEntryCollection grab{}; + SoundEntryCollection release{}; + SoundEntryCollection throw_{}; + }; + + Animations animations{}; + Sounds sounds{}; + Anm2 anm2{}; + + bool isValid{}; + + Cursor() = default; + Cursor(const util::physfs::Path&); + + bool is_valid() const; + }; +} diff --git a/src/resource/xml/dialogue.cpp b/src/resource/xml/dialogue.cpp new file mode 100644 index 0000000..e010a94 --- /dev/null +++ b/src/resource/xml/dialogue.cpp @@ -0,0 +1,165 @@ +#include "dialogue.hpp" +#include "util.hpp" + +#include "../../log.hpp" +#include "../../util/math.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + void Dialogue::query_entry_id(XMLElement* element, const char* name, int& id) + { + std::string entryID{}; + query_string_attribute(element, name, &entryID); + if (entryIDMap.contains(entryID)) + id = entryIDMap.at(entryID); + else if (entryID.empty()) + entryID = -1; + else + { + logger.warning("Dialogue entries does not contain: " + entryID); + id = -1; + } + } + + void Dialogue::query_pool_id(XMLElement* element, const char* name, int& id) + { + std::string poolID{}; + query_string_attribute(element, name, &poolID); + if (poolMap.contains(poolID)) + id = poolMap.at(poolID); + else if (poolID.empty()) + poolID = -1; + else + { + logger.warning("Dialogue pools does not contain: " + poolID); + id = -1; + } + } + + Dialogue::Dialogue(const physfs::Path& path) + { + + XMLDocument document; + + if (document_load(path, document) != XML_SUCCESS) return; + + if (auto root = document.RootElement()) + { + if (auto element = root->FirstChildElement("Entries")) + { + int id{}; + + for (auto child = element->FirstChildElement("Entry"); child; child = child->NextSiblingElement("Entry")) + { + std::string stringID{}; + query_string_attribute(child, "ID", &stringID); + entryIDMap.emplace(stringID, id); + entryIDMapReverse.emplace(id, stringID); + id++; + } + + id = 0; + + for (auto child = element->FirstChildElement("Entry"); child; child = child->NextSiblingElement("Entry")) + { + Entry entry{}; + + entry.name = entryIDMapReverse.at(id); + + query_string_attribute(child, "Text", &entry.text); + + query_string_attribute(child, "Animation", &entry.animation); + + if (child->FindAttribute("Next")) + { + std::string nextID{}; + query_string_attribute(child, "Next", &nextID); + if (!entryIDMap.contains(nextID)) + logger.warning(std::format("Dialogue: next ID does not point to a valid Entry! ({})", nextID)); + else + entry.nextID = entryIDMap.at(nextID); + } + + for (auto choiceChild = child->FirstChildElement("Choice"); choiceChild; + choiceChild = choiceChild->NextSiblingElement("Choice")) + { + Choice choice{}; + query_entry_id(choiceChild, "Next", choice.nextID); + query_string_attribute(choiceChild, "Text", &choice.text); + entry.choices.emplace_back(std::move(choice)); + } + + entries.emplace_back(std::move(entry)); + + id++; + } + } + + if (auto element = root->FirstChildElement("Pools")) + { + int id{}; + + for (auto child = element->FirstChildElement("Pool"); child; child = child->NextSiblingElement("Pool")) + { + Pool pool{}; + std::string stringID{}; + query_string_attribute(child, "ID", &stringID); + poolMap[stringID] = id; + pools.emplace_back(pool); + id++; + } + + id = 0; + + for (auto child = element->FirstChildElement("Pool"); child; child = child->NextSiblingElement("Pool")) + { + auto& pool = pools.at(id); + + for (auto entryChild = child->FirstChildElement("PoolEntry"); entryChild; + entryChild = entryChild->NextSiblingElement("PoolEntry")) + { + int entryID{}; + query_entry_id(entryChild, "ID", entryID); + pool.emplace_back(entryID); + } + + id++; + } + + logger.info(std::format("Initialized dialogue: {}", path.c_str())); + isValid = true; + } + + if (auto element = root->FirstChildElement("Start")) + { + query_entry_id(element, "ID", start.id); + query_string_attribute(element, "Animation", &start.animation); + } + if (auto element = root->FirstChildElement("End")) query_entry_id(element, "ID", end.id); + if (auto element = root->FirstChildElement("Help")) query_entry_id(element, "ID", help.id); + + if (auto element = root->FirstChildElement("Digest")) query_pool_id(element, "PoolID", digest.id); + if (auto element = root->FirstChildElement("Eat")) query_pool_id(element, "PoolID", eat.id); + if (auto element = root->FirstChildElement("EatFull")) query_pool_id(element, "PoolID", eatFull.id); + if (auto element = root->FirstChildElement("Feed")) query_pool_id(element, "PoolID", feed.id); + if (auto element = root->FirstChildElement("FeedFull")) query_pool_id(element, "PoolID", feedFull.id); + if (auto element = root->FirstChildElement("FoodTaken")) query_pool_id(element, "PoolID", foodTaken.id); + if (auto element = root->FirstChildElement("FoodTakenFull")) query_pool_id(element, "PoolID", foodTakenFull.id); + if (auto element = root->FirstChildElement("Full")) query_pool_id(element, "PoolID", full.id); + if (auto element = root->FirstChildElement("LowCapacity")) query_pool_id(element, "PoolID", lowCapacity.id); + if (auto element = root->FirstChildElement("Random")) query_pool_id(element, "PoolID", random.id); + if (auto element = root->FirstChildElement("Throw")) query_pool_id(element, "PoolID", throw_.id); + if (auto element = root->FirstChildElement("StageUp")) query_pool_id(element, "PoolID", stageUp.id); + } + } + + int Dialogue::Pool::get() const { return this->at(math::random_max(this->size())); } + Dialogue::Entry* Dialogue::get(int id) { return &entries.at(id); } + Dialogue::Entry* Dialogue::get(Dialogue::EntryReference& entry) { return &entries.at(entry.id); } + Dialogue::Entry* Dialogue::get(const std::string& string) { return &entries.at(entryIDMap.at(string)); } + Dialogue::Entry* Dialogue::get(Dialogue::PoolReference& pool) { return &entries.at(pools.at(pool.id).get()); } + Dialogue::Entry* Dialogue::get(Dialogue::Pool& pool) { return &entries.at(pool.get()); } +} diff --git a/src/resource/xml/dialogue.hpp b/src/resource/xml/dialogue.hpp new file mode 100644 index 0000000..285e6c1 --- /dev/null +++ b/src/resource/xml/dialogue.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include + +#include + +#include + +#include "../../util/physfs.hpp" + +namespace game::resource::xml +{ + class Dialogue + { + public: + struct Choice + { + std::string text{}; + int nextID{-1}; + }; + + struct Entry + { + std::string name{}; + std::string animation{}; + std::string text{}; + std::vector choices{}; + int nextID{-1}; + + inline bool is_last() const { return choices.empty() && nextID == -1; }; + }; + + struct EntryReference + { + int id{-1}; + std::string animation{}; + + inline bool is_valid() const { return id != -1; }; + }; + + class PoolReference + { + public: + int id{-1}; + inline bool is_valid() const { return id != -1; }; + }; + + class Pool : public std::vector + { + public: + int get() const; + }; + + std::map entryIDMap; + std::map entryIDMapReverse; + std::vector entries{}; + + std::vector pools{}; + std::map poolMap{}; + + EntryReference start{-1}; + EntryReference end{-1}; + EntryReference help{-1}; + PoolReference digest{-1}; + PoolReference eatFull{-1}; + PoolReference eat{-1}; + PoolReference feedFull{-1}; + PoolReference feed{-1}; + PoolReference foodTakenFull{-1}; + PoolReference foodTaken{-1}; + PoolReference full{-1}; + PoolReference random{-1}; + PoolReference lowCapacity{-1}; + PoolReference throw_{-1}; + PoolReference stageUp{-1}; + + bool isValid{}; + + Dialogue() = default; + Dialogue(const util::physfs::Path&); + Entry* get(const std::string&); + Entry* get(int id); + Entry* get(Dialogue::EntryReference&); + Entry* get(Dialogue::Pool&); + Entry* get(Dialogue::PoolReference&); + void query_entry_id(tinyxml2::XMLElement* element, const char* name, int& id); + void query_pool_id(tinyxml2::XMLElement* element, const char* name, int& id); + inline bool is_valid() const { return isValid; }; + }; +} \ No newline at end of file diff --git a/src/resource/xml/item.cpp b/src/resource/xml/item.cpp new file mode 100644 index 0000000..ebe171d --- /dev/null +++ b/src/resource/xml/item.cpp @@ -0,0 +1,156 @@ +#include "item.hpp" + +#include +#include + +#include +#include + +#include "../../log.hpp" + +#include "util.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Item::Item(const physfs::Path& path) + { + XMLDocument document; + + if (document_load(path, document) != XML_SUCCESS) return; + + auto archive = path.directory_get(); + + if (auto root = document.RootElement()) + { + std::string textureRootPath{}; + query_string_attribute(root, "TextureRootPath", &textureRootPath); + + std::string soundRootPath{}; + query_string_attribute(root, "SoundRootPath", &soundRootPath); + + query_anm2(root, "BaseAnm2", archive, textureRootPath, baseAnm2, Anm2::NO_SPRITESHEETS); + + if (auto element = root->FirstChildElement("Categories")) + { + for (auto child = element->FirstChildElement("Category"); child; child = child->NextSiblingElement("Category")) + { + Category category{}; + query_string_attribute(child, "Name", &category.name); + query_bool_attribute(child, "IsEdible", &category.isEdible); + categoryMap[category.name] = (int)categories.size(); + categories.push_back(category); + } + } + + if (auto element = root->FirstChildElement("Rarities")) + { + for (auto child = element->FirstChildElement("Rarity"); child; child = child->NextSiblingElement("Rarity")) + { + Rarity rarity{}; + + query_string_attribute(child, "Name", &rarity.name); + child->QueryFloatAttribute("Chance", &rarity.chance); + query_bool_attribute(child, "IsHidden", &rarity.isHidden); + + query_sound(child, "Sound", archive, soundRootPath, rarity.sound); + + rarityMap[rarity.name] = (int)rarities.size(); + rarities.emplace_back(std::move(rarity)); + } + } + + if (auto element = root->FirstChildElement("Flavors")) + { + for (auto child = element->FirstChildElement("Flavor"); child; child = child->NextSiblingElement("Flavor")) + { + Flavor flavor{}; + query_string_attribute(child, "Name", &flavor.name); + flavorMap[flavor.name] = (int)flavors.size(); + flavors.push_back(flavor); + } + } + + if (auto element = root->FirstChildElement("Animations")) + { + if (auto child = element->FirstChildElement("Chew")) + query_string_attribute(child, "Animation", &animations.chew); + } + + if (auto element = root->FirstChildElement("Sounds")) + { + query_sound_entry_collection(element, "Bounce", archive, soundRootPath, sounds.bounce); + query_sound_entry_collection(element, "Dispose", archive, soundRootPath, sounds.dispose); + query_sound_entry_collection(element, "Return", archive, soundRootPath, sounds.return_); + query_sound_entry_collection(element, "Summon", archive, soundRootPath, sounds.summon); + } + + if (auto element = root->FirstChildElement("Items")) + { + std::string itemTextureRootPath{}; + query_string_attribute(element, "TextureRootPath", &itemTextureRootPath); + + element->QueryIntAttribute("ChewCount", &chewCount); + element->QueryIntAttribute("QuantityMax", &quantityMax); + + for (auto child = element->FirstChildElement("Item"); child; child = child->NextSiblingElement("Item")) + { + Entry item{}; + + query_string_attribute(child, "Name", &item.name); + query_string_attribute(child, "Description", &item.description); + + query_float_optional_attribute(child, "Calories", item.calories); + query_float_optional_attribute(child, "DigestionBonus", item.digestionBonus); + query_float_optional_attribute(child, "EatSpeedBonus", item.eatSpeedBonus); + query_float_optional_attribute(child, "Gravity", item.gravity); + query_int_optional_attribute(child, "ChewCount", item.chewCount); + query_bool_attribute(child, "IsPlayReward", &item.isPlayReward); + query_bool_attribute(child, "IsToggleSpritesheet", &item.isToggleSpritesheet); + + std::string categoryString{}; + query_string_attribute(child, "Category", &categoryString); + item.categoryID = categoryMap.contains(categoryString) ? categoryMap[categoryString] : -1; + + std::string rarityString{}; + query_string_attribute(child, "Rarity", &rarityString); + item.rarityID = rarityMap.contains(rarityString) ? rarityMap[rarityString] : -1; + + std::string flavorString{}; + query_string_attribute(child, "Flavor", &flavorString); + if (flavorMap.contains(flavorString)) item.flavorID = flavorMap[flavorString]; + + Texture texture{}; + query_texture(child, "Texture", archive, itemTextureRootPath, texture); + + Anm2 anm2{baseAnm2}; + if (child->FindAttribute("Anm2")) query_anm2(child, "Anm2", archive, textureRootPath, anm2); + anm2.spritesheets.at(0).texture = std::move(texture); + anm2s.emplace_back(std::move(anm2)); + items.emplace_back(std::move(item)); + } + } + } + + for (int i = 0; i < (int)items.size(); i++) + { + auto& item = items[i]; + pools[item.rarityID].emplace_back(i); + if (item.isPlayReward) rewardItemPool.emplace_back(i); + } + + for (int i = 0; i < (int)rarities.size(); i++) + { + rarityIDsSortedByChance.emplace_back(i); + } + std::stable_sort(rarityIDsSortedByChance.begin(), rarityIDsSortedByChance.end(), + [&](int a, int b) { return rarities[a].chance > rarities[b].chance; }); + + isValid = true; + logger.info(std::format("Initialized item schema: {}", path.c_str())); + } + + bool Item::is_valid() const { return isValid; }; +} diff --git a/src/resource/xml/item.hpp b/src/resource/xml/item.hpp new file mode 100644 index 0000000..1f8d752 --- /dev/null +++ b/src/resource/xml/item.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "../audio.hpp" +#include "anm2.hpp" +#include "sound_entry.hpp" + +namespace game::resource::xml +{ + class Item + { + public: + static constexpr auto UNDEFINED = "???"; + + struct Category + { + std::string name{}; + bool isEdible{}; + }; + + struct Rarity + { + std::string name{UNDEFINED}; + float chance{}; + bool isHidden{}; + Audio sound{}; + }; + + struct Flavor + { + std::string name{UNDEFINED}; + }; + + struct Entry + { + std::string name{UNDEFINED}; + std::string description{UNDEFINED}; + int categoryID{}; + int rarityID{}; + std::optional flavorID; + std::optional calories{}; + std::optional eatSpeedBonus{}; + std::optional digestionBonus{}; + std::optional gravity{}; + std::optional chewCount{}; + bool isPlayReward{}; + bool isToggleSpritesheet{}; + }; + + struct Animations + { + std::string chew{}; + }; + + struct Sounds + { + SoundEntryCollection bounce{}; + SoundEntryCollection return_{}; + SoundEntryCollection dispose{}; + SoundEntryCollection summon{}; + }; + + std::unordered_map categoryMap{}; + std::unordered_map rarityMap{}; + std::unordered_map flavorMap{}; + + using Pool = std::vector; + + std::vector categories{}; + std::vector rarities{}; + std::vector flavors{}; + std::vector items{}; + std::vector anm2s{}; + + std::vector rarityIDsSortedByChance{}; + std::unordered_map pools{}; + Pool rewardItemPool{}; + + Animations animations{}; + Sounds sounds{}; + Anm2 baseAnm2{}; + int chewCount{2}; + int quantityMax{99}; + + bool isValid{}; + + Item() = default; + Item(const std::filesystem::path&); + Item(const util::physfs::Path&); + + bool is_valid() const; + }; +} diff --git a/src/resource/xml/menu.cpp b/src/resource/xml/menu.cpp new file mode 100644 index 0000000..0eff25d --- /dev/null +++ b/src/resource/xml/menu.cpp @@ -0,0 +1,46 @@ +#include "menu.hpp" + +#include "../../log.hpp" + +#include "util.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Menu::Menu(const physfs::Path& path) + { + XMLDocument document; + + if (document_load(path, document) != XML_SUCCESS) return; + + auto archive = path.directory_get(); + + if (auto root = document.RootElement()) + { + std::string soundRootPath{}; + query_string_attribute(root, "SoundRootPath", &soundRootPath); + + std::string fontRootPath{}; + query_string_attribute(root, "FontRootPath", &fontRootPath); + + query_font(root, "Font", archive, fontRootPath, font); + root->QueryFloatAttribute("Rounding", &rounding); + + if (auto element = root->FirstChildElement("Sounds")) + { + query_sound_entry_collection(element, "Open", archive, soundRootPath, sounds.open); + query_sound_entry_collection(element, "Close", archive, soundRootPath, sounds.close); + query_sound_entry_collection(element, "Hover", archive, soundRootPath, sounds.hover); + query_sound_entry_collection(element, "Select", archive, soundRootPath, sounds.select); + } + } + + isValid = true; + + logger.info(std::format("Initialized menu schema: {}", path.c_str())); + } + + bool Menu::is_valid() const { return isValid; }; +} diff --git a/src/resource/xml/menu.hpp b/src/resource/xml/menu.hpp new file mode 100644 index 0000000..6f4712d --- /dev/null +++ b/src/resource/xml/menu.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include "../../util/physfs.hpp" +#include "../font.hpp" +#include "sound_entry.hpp" + +namespace game::resource::xml +{ + class Menu + { + public: + struct Sounds + { + SoundEntryCollection open{}; + SoundEntryCollection close{}; + SoundEntryCollection hover{}; + SoundEntryCollection select{}; + }; + + Sounds sounds{}; + Font font{}; + float rounding{}; + + bool isValid{}; + + Menu() = default; + Menu(const util::physfs::Path&); + + bool is_valid() const; + }; +} diff --git a/src/resource/xml/play.cpp b/src/resource/xml/play.cpp new file mode 100644 index 0000000..e735ee1 --- /dev/null +++ b/src/resource/xml/play.cpp @@ -0,0 +1,67 @@ +#include "play.hpp" + +#include "../../log.hpp" +#include "util.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Play::Play(const physfs::Path& path, Dialogue& dialogue) + { + XMLDocument document; + + if (document_load(path, document) != XML_SUCCESS) return; + + auto archive = path.directory_get(); + + if (auto root = document.RootElement()) + { + std::string soundRootPath{}; + query_string_attribute(root, "SoundRootPath", &soundRootPath); + + root->QueryIntAttribute("RewardScore", &rewardScore); + root->QueryFloatAttribute("RewardScoreBonus", &rewardScoreBonus); + root->QueryFloatAttribute("RewardGradeBonus", &rewardGradeBonus); + root->QueryFloatAttribute("RangeBase", &rangeBase); + root->QueryFloatAttribute("RangeMin", &rangeMin); + root->QueryFloatAttribute("RangeScoreBonus", &rangeScoreBonus); + root->QueryFloatAttribute("SpeedMin", &speedMin); + root->QueryFloatAttribute("SpeedMax", &speedMax); + root->QueryFloatAttribute("SpeedScoreBonus", &speedScoreBonus); + root->QueryIntAttribute("EndTimerMax", &endTimerMax); + root->QueryIntAttribute("EndTimerFailureMax", &endTimerFailureMax); + + if (auto element = root->FirstChildElement("Sounds")) + { + query_sound_entry_collection(element, "Fall", archive, soundRootPath, sounds.fall); + query_sound_entry_collection(element, "ScoreLoss", archive, soundRootPath, sounds.scoreLoss); + query_sound_entry_collection(element, "HighScore", archive, soundRootPath, sounds.highScore); + query_sound_entry_collection(element, "HighScoreLoss", archive, soundRootPath, sounds.highScoreLoss); + query_sound_entry_collection(element, "RewardScore", archive, soundRootPath, sounds.rewardScore); + } + + if (auto element = root->FirstChildElement("Grades")) + { + for (auto child = element->FirstChildElement("Grade"); child; child = child->NextSiblingElement("Grade")) + { + Grade grade{}; + query_string_attribute(child, "Name", &grade.name); + query_string_attribute(child, "NamePlural", &grade.namePlural); + child->QueryIntAttribute("Value", &grade.value); + child->QueryFloatAttribute("Weight", &grade.weight); + query_bool_attribute(child, "IsFailure", &grade.isFailure); + query_sound(child, "Sound", archive, soundRootPath, grade.sound); + dialogue.query_pool_id(child, "DialoguePoolID", grade.pool.id); + grades.emplace_back(std::move(grade)); + } + } + } + + isValid = true; + logger.info(std::format("Initialized play schema: {}", path.c_str())); + } + + bool Play::is_valid() const { return isValid; }; +} \ No newline at end of file diff --git a/src/resource/xml/play.hpp b/src/resource/xml/play.hpp new file mode 100644 index 0000000..a8e3923 --- /dev/null +++ b/src/resource/xml/play.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include + +#include "util.hpp" + +#include "dialogue.hpp" + +namespace game::resource::xml +{ + class Play + { + public: + struct Grade + { + std::string name{}; + std::string namePlural{}; + int value{}; + float weight{}; + bool isFailure{}; + Audio sound{}; + Dialogue::PoolReference pool{}; + }; + + struct Sounds + { + SoundEntryCollection fall{}; + SoundEntryCollection highScore{}; + SoundEntryCollection highScoreLoss{}; + SoundEntryCollection rewardScore{}; + SoundEntryCollection scoreLoss{}; + }; + + Sounds sounds{}; + std::vector grades{}; + + float rewardScoreBonus{0.01}; + float rewardGradeBonus{0.05}; + float speedMin{0.005}; + float speedMax{0.075}; + float speedScoreBonus{0.000025f}; + float rangeBase{0.75}; + float rangeMin{0.10}; + float rangeScoreBonus{0.0005}; + int endTimerMax{20}; + int endTimerFailureMax{60}; + int rewardScore{999}; + + bool isValid{}; + + Play() = default; + Play(const util::physfs::Path&, Dialogue&); + + bool is_valid() const; + }; +} diff --git a/src/resource/xml/save.cpp b/src/resource/xml/save.cpp new file mode 100644 index 0000000..7159ad9 --- /dev/null +++ b/src/resource/xml/save.cpp @@ -0,0 +1,183 @@ +#include "save.hpp" +#include "util.hpp" + +#include + +#include "../../log.hpp" + +#ifdef __EMSCRIPTEN__ + #include "../../util/web_filesystem.hpp" +#endif + +using namespace game::util; + +using namespace tinyxml2; + +namespace game::resource::xml +{ + Save::Save(const std::filesystem::path& path) + { + XMLDocument document; + + // Fail silently if there's no save. + auto result = document.LoadFile(path.c_str()); + + if (result == XML_ERROR_FILE_NOT_FOUND || result == XML_ERROR_FILE_COULD_NOT_BE_OPENED) return; + + if (result != XML_SUCCESS) + { + logger.error( + std::format("Could not initialize character save file: {} ({})", path.string(), document.ErrorStr())); + return; + } + + if (auto root = document.RootElement()) + { + query_bool_attribute(root, "IsPostgame", &isPostgame); + query_bool_attribute(root, "IsAlternateSpritesheet", &isAlternateSpritesheet); + + if (auto element = root->FirstChildElement("Character")) + { + + element->QueryFloatAttribute("Weight", &weight); + element->QueryFloatAttribute("Calories", &calories); + element->QueryFloatAttribute("Capacity", &capacity); + element->QueryFloatAttribute("DigestionRate", &digestionRate); + element->QueryFloatAttribute("EatSpeed", &eatSpeed); + query_bool_attribute(element, "IsDigesting", &isDigesting); + element->QueryFloatAttribute("DigestionProgress", &digestionProgress); + element->QueryIntAttribute("DigestionTimer", &digestionTimer); + element->QueryFloatAttribute("TotalCaloriesConsumed", &totalCaloriesConsumed); + element->QueryIntAttribute("TotalFoodItemsEaten", &totalFoodItemsEaten); + } + + if (auto element = root->FirstChildElement("Play")) + { + element->QueryIntAttribute("TotalPlays", &totalPlays); + element->QueryIntAttribute("HighScore", &highScore); + element->QueryIntAttribute("BestCombo", &bestCombo); + + if (auto child = element->FirstChildElement("Grades")) + { + for (auto gradeChild = child->FirstChildElement("Grade"); gradeChild; + gradeChild = gradeChild->NextSiblingElement("Grade")) + { + int id{}; + gradeChild->QueryIntAttribute("ID", &id); + gradeChild->QueryIntAttribute("Count", &gradeCounts[id]); + } + } + } + + if (auto element = root->FirstChildElement("Inventory")) + { + for (auto child = element->FirstChildElement("Item"); child; child = child->NextSiblingElement("Item")) + { + int id{}; + int quantity{}; + child->QueryIntAttribute("ID", &id); + child->QueryIntAttribute("Quantity", &quantity); + + inventory[id] = quantity; + } + } + + if (auto element = root->FirstChildElement("Items")) + { + for (auto child = element->FirstChildElement("Item"); child; child = child->NextSiblingElement("Item")) + { + Item item{}; + child->QueryIntAttribute("ID", &item.id); + child->QueryIntAttribute("ChewCount", &item.chewCount); + child->QueryFloatAttribute("PositionX", &item.position.x); + child->QueryFloatAttribute("PositionY", &item.position.y); + child->QueryFloatAttribute("VelocityX", &item.velocity.x); + child->QueryFloatAttribute("VelocityY", &item.velocity.y); + child->QueryFloatAttribute("Rotation", &item.rotation); + items.emplace_back(std::move(item)); + } + } + } + + logger.info(std::format("Initialized character save file: {}", path.string())); + + isValid = true; + } + + bool Save::is_valid() const { return isValid; } + + void Save::serialize(const std::filesystem::path& path) + { + XMLDocument document; + + auto element = document.NewElement("Save"); + element->SetAttribute("IsPostgame", isPostgame ? "true" : "false"); + element->SetAttribute("IsAlternateSpritesheet", isAlternateSpritesheet ? "true" : "false"); + + auto characterElement = element->InsertNewChildElement("Character"); + characterElement->SetAttribute("Weight", weight); + characterElement->SetAttribute("Calories", calories); + characterElement->SetAttribute("Capacity", capacity); + characterElement->SetAttribute("DigestionRate", digestionRate); + characterElement->SetAttribute("EatSpeed", eatSpeed); + characterElement->SetAttribute("IsDigesting", isDigesting ? "true" : "false"); + characterElement->SetAttribute("DigestionProgress", digestionProgress); + characterElement->SetAttribute("DigestionTimer", digestionTimer); + characterElement->SetAttribute("TotalCaloriesConsumed", totalCaloriesConsumed); + characterElement->SetAttribute("TotalFoodItemsEaten", totalFoodItemsEaten); + + auto playElement = element->InsertNewChildElement("Play"); + + playElement->SetAttribute("TotalPlays", totalPlays); + playElement->SetAttribute("HighScore", highScore); + playElement->SetAttribute("BestCombo", bestCombo); + + auto gradesElement = playElement->InsertNewChildElement("Grades"); + + for (auto& [i, count] : gradeCounts) + { + auto gradeElement = gradesElement->InsertNewChildElement("Grade"); + gradeElement->SetAttribute("ID", i); + gradeElement->SetAttribute("Count", count); + } + + auto inventoryElement = element->InsertNewChildElement("Inventory"); + + for (auto& [id, quantity] : inventory) + { + auto itemElement = inventoryElement->InsertNewChildElement("Item"); + + itemElement->SetAttribute("ID", id); + itemElement->SetAttribute("Quantity", quantity); + } + + auto itemsElement = element->InsertNewChildElement("Items"); + + for (auto& item : items) + { + auto itemElement = itemsElement->InsertNewChildElement("Item"); + + itemElement->SetAttribute("ID", item.id); + itemElement->SetAttribute("ChewCount", item.chewCount); + itemElement->SetAttribute("PositionX", item.position.x); + itemElement->SetAttribute("PositionY", item.position.y); + itemElement->SetAttribute("VelocityX", item.velocity.x); + itemElement->SetAttribute("VelocityY", item.velocity.y); + itemElement->SetAttribute("Rotation", item.rotation); + } + + document.InsertFirstChild(element); + + if (document.SaveFile(path.c_str()) != XML_SUCCESS) + { + logger.error(std::format("Failed to save character save file: {} ({})", path.string(), document.ErrorStr())); + return; + } + + logger.info(std::format("Saved character save file: {}", path.string())); + +#ifdef __EMSCRIPTEN__ + web_filesystem::flush_async(); +#endif + } +} diff --git a/src/resource/xml/save.hpp b/src/resource/xml/save.hpp new file mode 100644 index 0000000..62c9f37 --- /dev/null +++ b/src/resource/xml/save.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include + +#include +#include + +#include + +namespace game::resource::xml +{ + class Save + { + public: + struct Item + { + int id{}; + int chewCount{}; + glm::vec2 position{}; + glm::vec2 velocity{}; + float rotation{}; + }; + + float weight{}; + float calories{}; + float capacity{}; + float eatSpeed{}; + float digestionRate{}; + float digestionProgress{}; + int digestionTimer{}; + bool isDigesting{}; + + bool isAlternateSpritesheet{}; + + float totalCaloriesConsumed{}; + int totalFoodItemsEaten{}; + int totalPlays{}; + int highScore{}; + int bestCombo{}; + std::map gradeCounts{}; + + std::map inventory; + std::vector items; + + bool isPostgame{}; + + bool isValid{}; + + Save() = default; + Save(const std::filesystem::path&); + void serialize(const std::filesystem::path&); + bool is_valid() const; + }; +} diff --git a/src/resource/xml/settings.cpp b/src/resource/xml/settings.cpp new file mode 100644 index 0000000..00bd82f --- /dev/null +++ b/src/resource/xml/settings.cpp @@ -0,0 +1,80 @@ +#include "settings.hpp" +#include "util.hpp" + +#include + +#include "../../log.hpp" + +#ifdef __EMSCRIPTEN__ + #include "../../util/web_filesystem.hpp" +#endif + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + Settings::Settings(const std::filesystem::path& path) + { + XMLDocument document; + + if (document.LoadFile(path.c_str()) != XML_SUCCESS) + { + logger.error( + std::format("Could not initialize character save file: {} ({})", path.string(), document.ErrorStr())); + return; + } + + if (auto root = document.RootElement()) + { + std::string measurementSystemString{}; + query_string_attribute(root, "MeasurementSystem", &measurementSystemString); + measurementSystem = measurementSystemString == "Imperial" ? measurement::IMPERIAL : measurement::METRIC; + root->QueryIntAttribute("Volume", &volume); + root->QueryFloatAttribute("ColorR", &color.r); + root->QueryFloatAttribute("ColorG", &color.g); + root->QueryFloatAttribute("ColorB", &color.b); + root->QueryFloatAttribute("WindowX", &windowPosition.x); + root->QueryFloatAttribute("WindowY", &windowPosition.y); + root->QueryIntAttribute("WindowW", &windowSize.x); + root->QueryIntAttribute("WindowH", &windowSize.y); + } + + logger.info(std::format("Initialized settings: {}", path.string())); + + isValid = true; + } + + bool Settings::is_valid() const { return isValid; } + + void Settings::serialize(const std::filesystem::path& path) + { + XMLDocument document; + + auto element = document.NewElement("Settings"); + + element->SetAttribute("MeasurementSystem", measurementSystem == measurement::IMPERIAL ? "Imperial" : "Metric"); + element->SetAttribute("Volume", volume); + element->SetAttribute("ColorR", color.r); + element->SetAttribute("ColorG", color.g); + element->SetAttribute("ColorB", color.b); + element->SetAttribute("WindowX", windowPosition.x); + element->SetAttribute("WindowY", windowPosition.y); + element->SetAttribute("WindowW", windowSize.x); + element->SetAttribute("WindowH", windowSize.y); + + document.InsertFirstChild(element); + + if (document.SaveFile(path.c_str()) != XML_SUCCESS) + { + logger.info(std::format("Failed to initialize settings: {} ({})", path.string(), document.ErrorStr())); + return; + } + + logger.info(std::format("Saved settings: {}", path.string())); + +#ifdef __EMSCRIPTEN__ + web_filesystem::flush_async(); +#endif + } +} diff --git a/src/resource/xml/settings.hpp b/src/resource/xml/settings.hpp new file mode 100644 index 0000000..a98efa9 --- /dev/null +++ b/src/resource/xml/settings.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include "../../util/measurement.hpp" +#include + +#include + +namespace game::resource::xml +{ + class Settings + { + public: + static constexpr auto VOLUME_MIN = 0; + static constexpr auto VOLUME_MAX = 100; + + enum Mode + { + LOADER, + IMGUI + }; + + util::measurement::System measurementSystem{util::measurement::METRIC}; + int volume{VOLUME_MAX}; + + glm::vec3 color{0.09, 0.2196, 0.37}; + glm::ivec2 windowSize{1280, 720}; + glm::vec2 windowPosition{}; + + bool isValid{}; + + Settings() = default; + Settings(const std::filesystem::path&); + void serialize(const std::filesystem::path&); + bool is_valid() const; + }; +} diff --git a/src/resource/xml/sound_entry.cpp b/src/resource/xml/sound_entry.cpp new file mode 100644 index 0000000..946019f --- /dev/null +++ b/src/resource/xml/sound_entry.cpp @@ -0,0 +1,16 @@ +#include "sound_entry.hpp" + +#include "../../util/vector.hpp" + +namespace game::resource::xml +{ + Audio& SoundEntryCollection::get() + { + return at(util::vector::random_index_weighted(*this, [](const auto& entry) { return entry.weight; })).sound; + } + + void SoundEntryCollection::play() + { + at(util::vector::random_index_weighted(*this, [](const auto& entry) { return entry.weight; })).play(); + } +} diff --git a/src/resource/xml/sound_entry.hpp b/src/resource/xml/sound_entry.hpp new file mode 100644 index 0000000..0a356a9 --- /dev/null +++ b/src/resource/xml/sound_entry.hpp @@ -0,0 +1,24 @@ +// Handles sound entries in .xml files. "Weight" value determines weight of being randomly selected. + +#pragma once + +#include "../audio.hpp" + +namespace game::resource::xml +{ + class SoundEntry + { + public: + Audio sound{}; + float weight{1.0f}; + + inline void play() { sound.play(); }; + }; + + class SoundEntryCollection : public std::vector + { + public: + Audio& get(); + void play(); + }; +} diff --git a/src/resource/xml/util.cpp b/src/resource/xml/util.cpp new file mode 100644 index 0000000..3f56643 --- /dev/null +++ b/src/resource/xml/util.cpp @@ -0,0 +1,185 @@ +#include "util.hpp" + +#include + +#include "../../util/physfs.hpp" +#include "../../util/string.hpp" + +#include "../../log.hpp" + +using namespace tinyxml2; +using namespace game::util; + +namespace game::resource::xml +{ + XMLError query_string_attribute(XMLElement* element, const char* attribute, std::string* value) + { + const char* temp = nullptr; + auto result = element->QueryStringAttribute(attribute, &temp); + if (result == XML_SUCCESS && temp && value) *value = temp; + return result; + } + + XMLError query_bool_attribute(XMLElement* element, const char* attribute, bool* value) + { + std::string temp{}; + auto result = query_string_attribute(element, attribute, &temp); + temp = string::to_lower(temp); + if (value) *value = temp == "true" || temp == "1" ? true : false; + return result; + } + + XMLError query_path_attribute(XMLElement* element, const char* attribute, std::filesystem::path* value) + { + std::string temp{}; + auto result = query_string_attribute(element, attribute, &temp); + if (value) *value = std::filesystem::path(temp); + return result; + } + + XMLError query_color_attribute(XMLElement* element, const char* attribute, float* value) + { + int temp{}; + auto result = element->QueryIntAttribute(attribute, &temp); + if (result == XML_SUCCESS && value) *value = (temp / 255.0f); + return result; + } + + XMLError query_float_optional_attribute(XMLElement* element, const char* attribute, std::optional& value) + { + value.emplace(); + auto result = element->QueryFloatAttribute(attribute, &*value); + if (result == XML_NO_ATTRIBUTE) value.reset(); + return result; + } + + XMLError query_int_optional_attribute(XMLElement* element, const char* attribute, std::optional& value) + { + value.emplace(); + auto result = element->QueryIntAttribute(attribute, &*value); + if (result == XML_NO_ATTRIBUTE) value.reset(); + return result; + } + + XMLError document_load(const physfs::Path& path, XMLDocument& document) + { + if (!path.is_valid()) + { + logger.error(std::format("Failed to open XML document: {} ({})", path.c_str(), physfs::error_get())); + return XML_ERROR_FILE_NOT_FOUND; + } + + auto buffer = path.read(); + + if (buffer.empty()) + { + logger.error(std::format("Failed to read XML document: {} ({})", path.c_str(), physfs::error_get())); + return XML_ERROR_FILE_COULD_NOT_BE_OPENED; + } + + auto result = document.Parse((const char*)buffer.data(), buffer.size()); + if (result != XML_SUCCESS) + logger.error(std::format("Failed to parse XML document: {} ({})", path.c_str(), document.ErrorStr())); + + return result; + } + + void query_event_id(XMLElement* element, const char* name, const Anm2& anm2, int& eventID) + { + std::string string{}; + query_string_attribute(element, name, &string); + if (anm2.eventMap.contains(string)) + eventID = anm2.eventMap.at(string); + else + { + logger.error(std::format("Could not query anm2 event ID: {} ({})", string, anm2.path)); + eventID = -1; + } + } + + void query_layer_id(XMLElement* element, const char* name, const Anm2& anm2, int& layerID) + { + std::string string{}; + query_string_attribute(element, name, &string); + if (anm2.layerMap.contains(string)) + layerID = anm2.layerMap.at(string); + else + { + logger.error(std::format("Could not query anm2 layer ID: {} ({})", string, anm2.path)); + layerID = -1; + } + } + + void query_null_id(XMLElement* element, const char* name, const Anm2& anm2, int& nullID) + { + std::string string{}; + query_string_attribute(element, name, &string); + if (anm2.nullMap.contains(string)) + nullID = anm2.nullMap.at(string); + else + { + logger.error(std::format("Could not query anm2 null ID: {} ({})", string, anm2.path)); + nullID = -1; + } + } + + void query_anm2(XMLElement* element, const char* name, const std::string& archive, const std::string& rootPath, + Anm2& anm2, Anm2::Flags flags) + { + std::string string{}; + query_string_attribute(element, name, &string); + anm2 = Anm2(physfs::Path(archive + "/" + rootPath + "/" + string), flags); + } + + void query_texture(XMLElement* element, const char* name, const std::string& archive, const std::string& rootPath, + Texture& texture) + { + std::string string{}; + query_string_attribute(element, name, &string); + texture = Texture(physfs::Path(archive + "/" + rootPath + "/" + string)); + } + + void query_sound(XMLElement* element, const char* name, const std::string& archive, const std::string& rootPath, + Audio& sound) + { + std::string string{}; + query_string_attribute(element, name, &string); + sound = Audio(physfs::Path(archive + "/" + rootPath + "/" + string)); + } + + void query_font(XMLElement* element, const char* name, const std::string& archive, const std::string& rootPath, + Font& font) + { + std::string string{}; + query_string_attribute(element, name, &string); + font = Font(physfs::Path(archive + "/" + rootPath + "/" + string)); + } + + void query_animation_entry(XMLElement* element, AnimationEntry& animationEntry) + { + query_string_attribute(element, "Animation", &animationEntry.animation); + element->QueryFloatAttribute("Weight", &animationEntry.weight); + } + + void query_animation_entry_collection(XMLElement* element, const char* name, + AnimationEntryCollection& animationEntryCollection) + { + for (auto child = element->FirstChildElement(name); child; child = child->NextSiblingElement(name)) + query_animation_entry(child, animationEntryCollection.emplace_back()); + } + + void query_sound_entry(XMLElement* element, const std::string& archive, const std::string& rootPath, + SoundEntry& soundEntry, const std::string& attributeName) + { + query_sound(element, attributeName.c_str(), archive, rootPath, soundEntry.sound); + element->QueryFloatAttribute("Weight", &soundEntry.weight); + } + + void query_sound_entry_collection(XMLElement* element, const char* name, const std::string& archive, + const std::string& rootPath, SoundEntryCollection& soundEntryCollection, + const std::string& attributeName) + { + for (auto child = element->FirstChildElement(name); child; child = child->NextSiblingElement(name)) + query_sound_entry(child, archive, rootPath, soundEntryCollection.emplace_back(), attributeName); + } +} diff --git a/src/resource/xml/util.hpp b/src/resource/xml/util.hpp new file mode 100644 index 0000000..361ae07 --- /dev/null +++ b/src/resource/xml/util.hpp @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include + +#include + +#include "animation_entry.hpp" +#include "sound_entry.hpp" + +#include "../../util/physfs.hpp" +#include "../font.hpp" +#include "anm2.hpp" + +namespace game::resource::xml +{ + tinyxml2::XMLError query_string_attribute(tinyxml2::XMLElement*, const char*, std::string*); + tinyxml2::XMLError query_bool_attribute(tinyxml2::XMLElement*, const char*, bool*); + tinyxml2::XMLError query_path_attribute(tinyxml2::XMLElement*, const char*, std::filesystem::path*); + tinyxml2::XMLError query_color_attribute(tinyxml2::XMLElement*, const char*, float*); + tinyxml2::XMLError query_float_optional_attribute(tinyxml2::XMLElement* element, const char* attribute, + std::optional& value); + tinyxml2::XMLError query_int_optional_attribute(tinyxml2::XMLElement* element, const char* attribute, + std::optional& value); + + void query_event_id(tinyxml2::XMLElement* element, const char* name, const Anm2& anm2, int& eventID); + void query_layer_id(tinyxml2::XMLElement* element, const char* name, const Anm2& anm2, int& layerID); + void query_null_id(tinyxml2::XMLElement* element, const char* name, const Anm2& anm2, int& nullID); + + void query_anm2(tinyxml2::XMLElement* element, const char* name, const std::string& archive, + const std::string& rootPath, Anm2& anm2, Anm2::Flags flags = {}); + void query_texture(tinyxml2::XMLElement* element, const char* name, const std::string& archive, + const std::string& rootPath, Texture& texture); + void query_sound(tinyxml2::XMLElement* element, const char* name, const std::string& archive, + const std::string& rootPath, Audio& sound); + void query_font(tinyxml2::XMLElement* element, const char* name, const std::string& archive, + const std::string& rootPath, Font& font); + + void query_animation_entry(tinyxml2::XMLElement* element, AnimationEntry& animationEntry); + void query_animation_entry_collection(tinyxml2::XMLElement* element, const char* name, + AnimationEntryCollection& animationEntryCollection); + + void query_sound_entry(tinyxml2::XMLElement* element, const std::string& archive, const std::string& rootPath, + SoundEntry& soundEntry, const std::string& attributeName = "Sound"); + void query_sound_entry_collection(tinyxml2::XMLElement* element, const char* name, const std::string& archive, + const std::string& rootPath, SoundEntryCollection& soundEntryCollection, + const std::string& attributeName = "Sound"); + + tinyxml2::XMLError document_load(const util::physfs::Path&, tinyxml2::XMLDocument&); +} diff --git a/src/resources.cpp b/src/resources.cpp index bb3a930..d877023 100644 --- a/src/resources.cpp +++ b/src/resources.cpp @@ -1,7 +1,9 @@ -#include "resources.h" +#include "resources.hpp" + +#include "util/preferences.hpp" using namespace game::resource; -using namespace game::anm2; +using namespace game::util; namespace game { @@ -10,19 +12,30 @@ namespace game for (int i = 0; i < shader::COUNT; i++) shaders[i] = Shader(shader::INFO[i].vertex, shader::INFO[i].fragment); - for (int i = 0; i < audio::COUNT; i++) - audio[i] = Audio(audio::PATHS[i]); - - for (int i = 0; i < texture::COUNT; i++) - textures[i] = Texture(texture::PATHS[i]); - - for (int i = 0; i < anm2::COUNT; i++) - anm2s[i] = Anm2(anm2::PATHS[i]); + for (auto& entry : std::filesystem::recursive_directory_iterator("resources/characters")) + if (entry.is_regular_file() && entry.path().extension() == ".zip") characterPreviews.emplace_back(entry.path()); + characters.resize(characterPreviews.size()); } - void Resources::sound_play(audio::Type type) { audio[type].play(); } + void Resources::volume_set(float vol) { Audio::volume_set(vol); } - void Resources::set_audio_gain(float vol) { - Audio::set_gain(vol); + resource::xml::Character& Resources::character_get(int index) + { + if (!characters.at(index).has_value()) + { + characters[index].emplace(characterPreviews.at(index).path); + characters[index]->save = characterPreviews.at(index).save; + } + return *characters[index]; } -} \ No newline at end of file + + resource::xml::CharacterPreview& Resources::character_preview_get(int index) { return characterPreviews.at(index); } + + void Resources::character_save_set(int index, const resource::xml::Save& save) + { + characterPreviews.at(index).save = save; + if (characters.at(index).has_value()) characters[index]->save = save; + } + + Resources::~Resources() { settings.serialize(preferences::path() / "settings.xml"); } +} diff --git a/src/resources.hpp b/src/resources.hpp index 8e88c6f..5d77975 100644 --- a/src/resources.hpp +++ b/src/resources.hpp @@ -1,129 +1,32 @@ #pragma once -#include "resource/anm2.h" -#include "resource/audio.h" -#include "resource/dialogue.h" -#include "resource/font.h" -#include "resource/shader.h" +#include -namespace game::audio -{ -#define AUDIO \ - X(BLIP, "resources/sfx/blip.ogg") \ - X(ADVANCE, "resources/sfx/advance.ogg") \ - X(BOUNCE, "resources/sfx/bounce.ogg") \ - X(BURP_1, "resources/sfx/burp1.ogg") \ - X(BURP_2, "resources/sfx/burp2.ogg") \ - X(BURP_3, "resources/sfx/burp3.ogg") \ - X(GRAB, "resources/sfx/grab.ogg") \ - X(MISS, "resources/sfx/miss.ogg") \ - X(OK, "resources/sfx/ok.ogg") \ - X(GOOD, "resources/sfx/good.ogg") \ - X(GREAT, "resources/sfx/great.ogg") \ - X(EXCELLENT, "resources/sfx/excellent.ogg") \ - X(PERFECT, "resources/sfx/perfect.ogg") \ - X(FALL, "resources/sfx/fall.ogg") \ - X(COMMON, "resources/sfx/common.ogg") \ - X(UNCOMMON, "resources/sfx/uncommon.ogg") \ - X(RARE, "resources/sfx/rare.ogg") \ - X(EPIC, "resources/sfx/epic.ogg") \ - X(LEGENDARY, "resources/sfx/legendary.ogg") \ - X(SPECIAL, "resources/sfx/special.ogg") \ - X(IMPOSSIBLE, "resources/sfx/impossible.ogg") \ - X(SCORE_LOSS, "resources/sfx/scoreLoss.ogg") \ - X(HIGH_SCORE, "resources/sfx/highScore.ogg") \ - X(HIGH_SCORE_BIG, "resources/sfx/highScoreBig.ogg") \ - X(HIGH_SCORE_LOSS, "resources/sfx/highScoreLoss.ogg") \ - X(GURGLE_1, "resources/sfx/gurgle1.ogg") \ - X(GURGLE_2, "resources/sfx/gurgle2.ogg") \ - X(GURGLE_3, "resources/sfx/gurgle3.ogg") \ - X(RELEASE, "resources/sfx/release.ogg") \ - X(SUMMON, "resources/sfx/summon.ogg") \ - X(RETURN, "resources/sfx/return.ogg") \ - X(DISPOSE, "resources/sfx/dispose.ogg") \ - X(RUB, "resources/sfx/rub.ogg") \ - X(THROW, "resources/sfx/throw.ogg") - - enum Type - { -#define X(symbol, path) symbol, - AUDIO -#undef X - COUNT - }; - - static constexpr const char* PATHS[] = { -#define X(symbol, path) path, - AUDIO -#undef X - }; - -#undef AUDIO - - static constexpr Type BURPS[] = {BURP_1, BURP_2, BURP_3}; - static constexpr Type GURGLES[] = {GURGLE_1, GURGLE_2, GURGLE_3}; -} - -namespace game::texture -{ -#define TEXTURES X(BG, "resources/gfx/bg.png") - - enum Type - { -#define X(symbol, path) symbol, - TEXTURES -#undef X - COUNT - }; - - static constexpr const char* PATHS[] = { -#define X(symbol, path) path, - TEXTURES -#undef X - }; - -#undef TEXTURES -} - -namespace game::anm2 -{ -#define ANM2 \ - X(CHARACTER, "resources/anm2/snivy.anm2") \ - X(ITEMS, "resources/anm2/items.anm2") \ - X(CURSOR, "resources/anm2/cursor.anm2") - - enum Anm2Type - { -#define X(symbol, path) symbol, - ANM2 -#undef X - COUNT - }; - - static constexpr const char* PATHS[] = { -#define X(symbol, path) path, - ANM2 -#undef X - }; - -#undef ANM2 -} +#include "resource/font.hpp" +#include "resource/shader.hpp" +#include "resource/xml/character.hpp" +#include "resource/xml/character_preview.hpp" +#include "resource/xml/settings.hpp" namespace game { class Resources { - public: resource::Shader shaders[resource::shader::COUNT]; - resource::Audio audio[audio::COUNT]; - resource::Texture textures[texture::COUNT]; - anm2::Anm2 anm2s[anm2::COUNT]; resource::Font font{"resources/font/font.ttf"}; - resource::Dialogue dialogue{"resources/dialogue.xml"}; + resource::xml::Settings settings; + + std::vector characterPreviews{}; + std::vector> characters{}; Resources(); - void sound_play(audio::Type); - void set_audio_gain(float vol); + ~Resources(); + + resource::xml::Character& character_get(int index); + resource::xml::CharacterPreview& character_preview_get(int index); + void character_save_set(int index, const resource::xml::Save& save); + + void volume_set(float volume); }; -} \ No newline at end of file +} diff --git a/src/state.cpp b/src/state.cpp index 40d7168..c6b4dfc 100644 --- a/src/state.cpp +++ b/src/state.cpp @@ -1,14 +1,14 @@ -#include "state.h" +#include "state.hpp" #include #include #include -#include "util/math_.h" +#include "util/math.hpp" using namespace glm; -using namespace game::resource; using namespace game::util; +using namespace game::state; namespace game { @@ -17,402 +17,101 @@ namespace game constexpr auto UPDATE_RATE = 60; constexpr auto UPDATE_INTERVAL = (1000 / UPDATE_RATE); - State::State(SDL_Window* inWindow, SDL_GLContext inContext, vec2 size) - : window(inWindow), context(inContext), canvas(size, true) + State::State(SDL_Window* _window, SDL_GLContext _context, resource::xml::Settings settings) + : window(_window), context(_context), canvas(settings.windowSize, Canvas::DEFAULT) { + resources.settings = settings; + SDL_SetWindowSize(window, resources.settings.windowSize.x, resources.settings.windowSize.y); } void State::tick() { - for (auto& item : items) - item.tick(); - - character.tick(); - - if (character.isJustDigestionStart) - resources.sound_play(audio::GURGLES[(int)math::random_roll(std::size(audio::GURGLES))]); - if (character.is_event("Burp")) resources.sound_play(audio::BURPS[(int)math::random_roll(std::size(audio::BURPS))]); - if (character.isJustDigestionEnd && !character.isJustStageUp) + switch (type) { - character.state_set(Character::PAT, true); - textWindow.set_random(resources.dialogue.postDigestIDs, resources, character); + case SELECT: + select.tick(); + break; + case MAIN: + main.tick(resources); + break; + default: + break; } - - cursor.tick(); - - textWindow.tick(resources, character); } void State::update() { - static bool isRubbing{}; - auto& inventory = mainMenuWindow.inventory; - auto& dialogue = resources.dialogue; - - int width{}; - int height{}; - SDL_GetWindowSize(window, &width, &height); + SDL_GetWindowSize(window, &resources.settings.windowSize.x, &resources.settings.windowSize.y); SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSDL3_ProcessEvent(&event); - if (event.type == SDL_EVENT_QUIT) isRunning = false; + if (event.type == SDL_EVENT_QUIT) + { + if (type == MAIN) main.exit(resources); + isRunning = false; + } + if (!isRunning) return; } - if (!isRunning) return; - ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); - auto style = ImGui::GetStyle(); - - if (textWindow.isFlagActivated) + switch (type) { - switch (textWindow.flag) - { - case Dialogue::Entry::ACTIVATE_WINDOWS: - isInfo = true; - isMainMenu = true; - break; - case Dialogue::Entry::DEACTIVATE_WINDOWS: - isInfo = false; - isMainMenu = false; - break; - case Dialogue::Entry::ONLY_INFO: - isInfo = true; - isMainMenu = false; - break; - case Dialogue::Entry::ACTIVATE_CHEATS: - mainMenuWindow.isCheats = true; - break; - default: - break; - } - } - - auto infoSize = ImVec2(width * 0.5f, ImGui::GetTextLineHeightWithSpacing() * 3.5); - auto infoPos = style.WindowPadding; - if (isInfo) infoWindow.update(resources, gameData, character, infoSize, infoPos); - - auto textSize = ImVec2(width - style.WindowPadding.x * 2, ImGui::GetTextLineHeightWithSpacing() * 8); - auto textPos = ImVec2(style.WindowPadding.x, height - textSize.y - style.WindowPadding.y); - if (isText) textWindow.update(resources, character, textSize, textPos); - - auto mainSize = - ImVec2((width * 0.5f) - style.WindowPadding.x * 3, height - textSize.y - (style.WindowPadding.y * 3)); - auto mainPos = ImVec2(infoPos.x + infoSize.x + style.WindowPadding.x, style.WindowPadding.y); - if (isMainMenu) mainMenuWindow.update(resources, character, gameData, textWindow, mainSize, mainPos); - - /* Inventory */ - - if (inventory.isQueued) - { - if (items.size() > Item::DEPLOYED_MAX) - { - inventory.isQueued = false; - inventory.queuedItemType = Item::NONE; - resources.sound_play(audio::MISS); - } - else - { - auto& type = inventory.queuedItemType; - - auto position = glm::vec2(((Item::SPAWN_X_MAX - Item::SPAWN_X_MIN) * math::random()) + Item::SPAWN_X_MIN, - ((Item::SPAWN_Y_MAX - Item::SPAWN_Y_MIN) * math::random()) + Item::SPAWN_Y_MIN); - items.emplace_back(&resources.anm2s[anm2::ITEMS], position, type); - - inventory.adjust_item(type, -1); - type = Item::NONE; - inventory.isQueued = false; - } - } - - /* Item */ - Item::hoveredItem = nullptr; - Item::heldItemPrevious = Item::heldItem; - bool isSpeak{}; - std::vector* dialogueIDs{}; - - for (int i = 0; i < items.size(); i++) - { - auto& item = items[i]; - - item.update(resources); - - if (&item == Item::heldItem && &item != &items.back()) - { - std::swap(items[i], items.back()); - Item::heldItem = &items.back(); - continue; - } - - if (item.isToBeDeleted) - { - items.erase(items.begin() + i--); - continue; - } - - if (Item::queuedReturnItem == &item) - { - if (Item::queuedReturnItem->state == Item::DEFAULT) + case SELECT: + select.update(resources); + if (select.info.isNewGame || select.info.isContinue) { - inventory.adjust_item(item.type); - resources.sound_play(audio::RETURN); + Main::Game game = select.info.isNewGame ? Main::NEW_GAME : Main::CONTINUE; + if (game == Main::NEW_GAME) resources.character_save_set(select.characterIndex, resource::xml::Save()); + + main.set(resources, select.characterIndex, game); + type = MAIN; + + select.info.isNewGame = false; + select.info.isContinue = false; } - else - resources.sound_play(audio::DISPOSE); - - items.erase(items.begin() + i--); - Item::queuedReturnItem = nullptr; - continue; - } - } - - auto& item = Item::heldItem; - auto isHeldItemChanged = item != Item::heldItemPrevious; - - if (item && character.state != Character::STAGE_UP) - { - auto& type = item->type; - auto& calories = Item::CALORIES[type]; - auto& category = Item::CATEGORIES[type]; - auto& position = item->position; - auto caloriesChew = Item::CALORIES[type] / (Item::CHEW_COUNT_MAX + 1); - auto digestionRateBonusChew = Item::DIGESTION_RATE_BONUSES[type] / (Item::CHEW_COUNT_MAX + 1); - auto eatSpeedBonusChew = Item::EAT_SPEED_BONUSES[type] / (Item::CHEW_COUNT_MAX + 1); - auto isAbleToEat = character.calories + caloriesChew <= character.max_capacity(); - - if (category == Item::FOOD) - { - auto isByMouth = math::is_point_in_rectf(character.mouth_rect_get(), position); - - if (character.state == Character::EAT && !isHeldItemChanged) + break; + case MAIN: + main.update(resources); + if (main.menu.configuration.isGoToSelect) { - if (!isByMouth) - { - if (character.is_over_capacity()) - { - dialogueIDs = &dialogue.foodEasedIDs; - character.state_set(Character::IDLE); - } - else - { - dialogueIDs = &dialogue.foodStolenIDs; - character.state_set(Character::ANGRY); - } - isSpeak = true; - } - - if (character.is_event(Character::EVENT_EAT)) - { - item->chewCount++; - - if (digestionRateBonusChew > 0 || digestionRateBonusChew < 0) - { - character.digestionRate = - glm::clamp(Character::DIGESTION_RATE_MIN, character.digestionRate + digestionRateBonusChew, - Character::DIGESTION_RATE_MAX); - } - - if (eatSpeedBonusChew > 0) - { - character.eatSpeedMultiplier = - glm::clamp(Character::EAT_SPEED_MULTIPLIER_MIN, character.eatSpeedMultiplier + eatSpeedBonusChew, - Character::EAT_SPEED_MULTIPLIER_MAX); - } - - character.calories += caloriesChew; - character.totalCaloriesConsumed += caloriesChew; - character.consume_played_event(); - - if (item->chewCount > Item::CHEW_COUNT_MAX) - { - character.isFinishedFood = true; - character.foodItemsEaten++; - - item->isToBeDeleted = true; - Item::heldItem = nullptr; - cursor.play(Cursor::ANIMATION_DEFAULT); - } - else - item->state_set(item->chewCount == 1 ? Item::CHEW_1 - : item->chewCount == 2 ? Item::CHEW_2 - : Item::DEFAULT); - - if (character.calories + caloriesChew >= character.max_capacity() && Item::heldItem) - { - character.state_set(Character::SHOCKED); - dialogueIDs = &dialogue.fullIDs; - isSpeak = true; - } - } + main.exit(resources); + type = SELECT; + main.menu.configuration.isGoToSelect = false; } - else if (character.state == Character::ANGRY) - { - } - else - { - - cursor.play(Cursor::ANIMATION_GRAB); - - if (!isAbleToEat) - { - character.state_set(Character::SHOCKED); - if (caloriesChew > character.max_capacity()) - dialogueIDs = &dialogue.capacityLowIDs; - else - dialogueIDs = &dialogue.fullIDs; - } - else if (character.is_over_capacity()) - dialogueIDs = &dialogue.feedFullIDs; - else - { - character.state_set(Character::EAGER); - dialogueIDs = &dialogue.feedHungryIDs; - } - - if (isHeldItemChanged) isSpeak = true; - - if (isAbleToEat && isByMouth) - if (character.state != Character::EAT) character.state_set(Character::EAT); - - isRubbing = false; - } - } + break; + default: + break; } - else if (isHeldItemChanged && character.state != Character::ANGRY && character.state != Character::STAGE_UP) - character.state_set(Character::IDLE); - - /* Character */ - if (character.isFinishedFood && character.state == Character::IDLE) - { - if (!character.is_over_capacity()) dialogueIDs = &dialogue.eatHungryIDs; - - if (math::random_percent_roll(Character::BURP_BIG_CHANCE)) - { - character.state_set(Character::BURP_BIG); - dialogueIDs = &dialogue.burpBigIDs; - } - else if (math::random_percent_roll(Character::BURP_SMALL_CHANCE)) - { - character.state_set(Character::BURP_SMALL); - dialogueIDs = &dialogue.burpSmallIDs; - } - else if (!character.is_over_capacity() && math::random_percent_roll(Character::PAT_CHANCE)) - character.state_set(Character::PAT); - - character.isFinishedFood = false; - isSpeak = true; - } - - /* Character */ - if (character.isJustAppeared) - { - textWindow.set(dialogue.get("Start"), character); - isText = true; - character.isJustAppeared = false; - } - - if (character.isJustFinalThreshold && !character.isFinalThresholdReached) - { - Item::heldItem = nullptr; - Item::heldItemPrevious = nullptr; - textWindow.set(dialogue.get("End"), character); - items.clear(); - character.isFinalThresholdReached = true; - } - - /* Dialogue */ - if (isSpeak && dialogueIDs) textWindow.set_random(*dialogueIDs, resources, character); - - /* Rubbing/Grabbing */ - bool isHeadRubPossible = math::is_point_in_rectf(character.head_rect_get(), cursor.position) && !Item::heldItem; - bool isBellyRubPossible = math::is_point_in_rectf(character.belly_rect_get(), cursor.position) && !Item::heldItem; - bool isTailRubPossible = math::is_point_in_rectf(character.tail_rect_get(), cursor.position) && !Item::heldItem; - auto isRubPossible = isHeadRubPossible || isBellyRubPossible || isTailRubPossible; - - if (isRubPossible) - { - if (!isRubbing) cursor.play(Cursor::ANIMATION_HOVER); - - if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) - { - isRubbing = true; - resources.sound_play(audio::RUB); - if (isHeadRubPossible) - { - character.state_set(Character::HEAD_RUB); - cursor.play(Cursor::ANIMATION_RUB); - } - else if (isBellyRubPossible) - { - character.state_set(Character::BELLY_RUB); - cursor.play(Cursor::ANIMATION_GRAB); - } - else if (isTailRubPossible) - { - character.state_set(Character::TAIL_RUB); - cursor.play(Cursor::ANIMATION_GRAB); - } - } - } - else if (Item::hoveredItem) - cursor.play(Cursor::ANIMATION_HOVER); - else if (!Item::heldItem) - cursor.play(Cursor::ANIMATION_DEFAULT); - - if (isRubbing) - { - if (isBellyRubPossible && !character.isDigesting) - { - auto delta = ImGui::GetIO().MouseDelta; - auto power = fabs(delta.x) + fabs(delta.y); - - if (character.calories > 0) character.digestionProgress += power * Character::DIGESTION_RUB_BONUS; - } - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || !isRubPossible) - { - isRubbing = false; - character.state_set(Character::IDLE); - } - } - - SDL_HideCursor(); - cursor.update(); } void State::render() { - SDL_GL_MakeCurrent(window, context); - - int width{}; - int height{}; - SDL_GetWindowSize(window, &width, &height); - - auto& textureShader = resources.shaders[shader::TEXTURE]; - auto& rectShader = resources.shaders[shader::RECT]; + ivec2 windowSize{}; + SDL_GetWindowSize(window, &windowSize.x, &windowSize.y); canvas.bind(); - - canvas.clear(glm::vec4(0, 0, 0, 1)); - - auto bgModel = math::quad_model_get(vec2(width, height)); - canvas.texture_render(textureShader, resources.textures[texture::BG].id, bgModel); - - ImGui::Render(); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - - character.render(textureShader, rectShader, canvas); - - for (auto& item : items) - item.render(textureShader, rectShader, canvas); - - cursor.render(textureShader, rectShader, canvas); - + canvas.size_set(windowSize); + canvas.clear(vec4(resources.settings.color, 1.0f)); canvas.unbind(); + switch (type) + { + case SELECT: + select.render(resources, canvas); + break; + case MAIN: + main.render(resources, canvas); + break; + default: + break; + } + SDL_GL_SwapWindow(window); } diff --git a/src/state.hpp b/src/state.hpp index e7c9260..9e0175e 100644 --- a/src/state.hpp +++ b/src/state.hpp @@ -2,53 +2,47 @@ #include -#include "character.h" -#include "cursor.h" -#include "item.h" +#include "canvas.hpp" +#include "resources.hpp" -#include "canvas.h" -#include "resources.h" +#include "state/main.hpp" +#include "state/select.hpp" -#include "window/info.h" -#include "window/main_menu.h" -#include "window/text.h" +#include "entity/cursor.hpp" namespace game { - class State { + public: SDL_Window* window{}; SDL_GLContext context{}; long previousUpdate{}; long previousTick{}; + enum Type + { + MAIN, + SELECT + }; + + Type type{SELECT}; + Resources resources; - Character character{&resources.anm2s[anm2::CHARACTER], glm::vec2(300, 500)}; - Cursor cursor{&resources.anm2s[anm2::CURSOR]}; - - std::vector items{}; - - window::Info infoWindow; - window::MainMenu mainMenuWindow; - window::Text textWindow; - - bool isMainMenu{false}; - bool isInfo{false}; - bool isText{false}; - - GameData gameData; + state::Main main; + state::Select select; void tick(); + void tick_60(); void update(); void render(); - public: bool isRunning{true}; + Canvas canvas{}; - State(SDL_Window*, SDL_GLContext, glm::vec2); + State(SDL_Window*, SDL_GLContext, resource::xml::Settings); void loop(); }; }; diff --git a/src/state/configuration.cpp b/src/state/configuration.cpp new file mode 100644 index 0000000..361bbb5 --- /dev/null +++ b/src/state/configuration.cpp @@ -0,0 +1,56 @@ +#include "configuration.hpp" + +#include +#include + +#include "../util/math.hpp" +#include "../util/imgui/style.hpp" +#include "../util/imgui/widget.hpp" +#include "../util/measurement.hpp" + +using namespace game::util; +using namespace game::util::imgui; + +namespace game::state +{ + void Configuration::update(Resources& resources, Mode mode) + { + auto& settings = resources.settings; + auto& measurementSystem = settings.measurementSystem; + auto& volume = settings.volume; + auto& color = settings.color; + + ImGui::SeparatorText("Measurement System"); + WIDGET_FX(ImGui::RadioButton("Metric", (int*)&measurementSystem, measurement::METRIC)); + ImGui::SetItemTooltip("%s", "Use kilograms (kg)."); + ImGui::SameLine(); + WIDGET_FX(ImGui::RadioButton("Imperial", (int*)&measurementSystem, measurement::IMPERIAL)); + ImGui::SetItemTooltip("%s", "Use pounds (lbs)."); + + ImGui::SeparatorText("Sound"); + if (WIDGET_FX(ImGui::SliderInt("Volume", &volume, 0, 100, "%d%%"))) + resources.volume_set(math::to_unit((float)volume)); + ImGui::SetItemTooltip("%s", "Adjust master volume."); + + ImGui::SeparatorText("Appearance"); + + if (WIDGET_FX( + ImGui::ColorEdit3("Color", value_ptr(color), ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoTooltip))) + style::color_set(color); + ImGui::SetItemTooltip("%s", "Change the UI color."); + + ImGui::Separator(); + if (WIDGET_FX(ImGui::Button("Reset to Default", ImVec2(-FLT_MIN, 0)))) settings = resource::xml::Settings(); + + if (mode == MAIN) + { + ImGui::Separator(); + + if (WIDGET_FX(ImGui::Button("Save", ImVec2(-FLT_MIN, 0)))) isSave = true; + ImGui::SetItemTooltip("%s", "Save the game.\n(Note: the game autosaves frequently.)"); + + if (WIDGET_FX(ImGui::Button("Return to Characters", ImVec2(-FLT_MIN, 0)))) isGoToSelect = true; + ImGui::SetItemTooltip("%s", "Go back to the character selection screen.\nProgress will be saved."); + } + } +} diff --git a/src/state/configuration.hpp b/src/state/configuration.hpp new file mode 100644 index 0000000..8eaaf75 --- /dev/null +++ b/src/state/configuration.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include "../resources.hpp" + +namespace game::state +{ + class Configuration + { + public: + enum Mode + { + SELECT, + MAIN + }; + + bool isGoToSelect{}; + bool isSave{}; + + void update(Resources&, Mode = SELECT); + }; +} \ No newline at end of file diff --git a/src/state/main.cpp b/src/state/main.cpp new file mode 100644 index 0000000..123f33d --- /dev/null +++ b/src/state/main.cpp @@ -0,0 +1,294 @@ +#include "main.hpp" + +#include +#include +#include + +#include "../util/imgui.hpp" +#include "../util/imgui/style.hpp" +#include "../util/imgui/widget.hpp" +#include "../util/math.hpp" + +using namespace game::resource; +using namespace game::util; +using namespace game::state::main; +using namespace glm; + +namespace game::state +{ + World::Focus Main::focus_get() + { + return menu.isOpen && tools.isOpen ? World::MENU_TOOLS + : menu.isOpen ? World::MENU + : tools.isOpen ? World::TOOLS + : World::CENTER; + } + + void Main::set(Resources& resources, int characterIndex, enum Game game) + { + auto& data = resources.character_get(characterIndex); + auto& saveData = data.save; + auto& itemSchema = data.itemSchema; + auto& dialogue = data.dialogue; + auto& menuSchema = data.menuSchema; + this->characterIndex = characterIndex; + + character = + entity::Character(data, vec2(World::BOUNDS.x + World::BOUNDS.z * 0.5f, World::BOUNDS.w - World::BOUNDS.y)); + + auto isAlternateSpritesheet = + (game == NEW_GAME && math::random_percent_roll(data.alternateSpritesheet.chanceOnNewGame)); + + if (isAlternateSpritesheet || saveData.isAlternateSpritesheet) + { + character.spritesheet_set(entity::Character::ALTERNATE); + if (game == NEW_GAME) character.data.alternateSpritesheet.sound.play(); + } + + character.totalCaloriesConsumed = saveData.totalCaloriesConsumed; + character.totalFoodItemsEaten = saveData.totalFoodItemsEaten; + characterManager = CharacterManager{}; + + cursor = entity::Cursor(character.data.cursorSchema.anm2); + + menu.inventory = Inventory{}; + for (auto& [id, quantity] : saveData.inventory) + { + if (quantity == 0) continue; + menu.inventory.values[id] = quantity; + } + + itemManager = ItemManager{}; + for (auto& item : saveData.items) + { + auto& anm2 = itemSchema.anm2s.at(item.id); + auto chewAnimation = itemSchema.animations.chew + std::to_string(item.chewCount); + auto animationIndex = item.chewCount > 0 ? anm2.animationMap[chewAnimation] : -1; + auto& saveItem = itemSchema.anm2s.at(item.id); + itemManager.items.emplace_back(saveItem, item.position, item.id, item.chewCount, animationIndex, item.velocity, + item.rotation); + } + + imgui::style::rounding_set(menuSchema.rounding); + imgui::widget::sounds_set(&menuSchema.sounds.hover, &menuSchema.sounds.select); + + menu.play = Play(character); + menu.play.totalPlays = saveData.totalPlays; + menu.play.highScore = saveData.highScore; + menu.play.bestCombo = saveData.bestCombo; + menu.play.gradeCounts = saveData.gradeCounts; + menu.play.isHighScoreAchieved = saveData.highScore > 0 ? true : false; + + menu.isChat = character.data.dialogue.help.is_valid() || character.data.dialogue.random.is_valid(); + + text.entry = nullptr; + text.isEnabled = false; + + if (auto font = character.data.menuSchema.font.get()) ImGui::GetIO().FontDefault = font; + + if (game == NEW_GAME && dialogue.start.is_valid()) + { + character.queue_play({.animation = dialogue.start.animation, .isInterruptible = false}); + character.tick(); + isWindows = false; + isStart = true; + } + + isPostgame = saveData.isPostgame; + + if (isPostgame) + menu.isCheats = true; + else + menu.isCheats = true; //false; + + worldCanvas.size_set(imgui::to_vec2(ImGui::GetMainViewport()->Size)); + + world.set(character, worldCanvas, focus_get()); + } + + void Main::exit(Resources& resources) + { + imgui::style::rounding_set(); + imgui::widget::sounds_set(nullptr, nullptr); + ImGui::GetIO().FontDefault = resources.font.get(); + save(resources); + } + + void Main::tick(Resources& resources) + { + character.tick(); + cursor.tick(); + menu.tick(); + toasts.tick(); + text.tick(character); + + for (auto& item : itemManager.items) + item.tick(); + } + + void Main::update(Resources& resources) + { + auto focus = focus_get(); + auto& dialogue = character.data.dialogue; + + if (isWindows) + { + menu.update(resources, itemManager, character, cursor, text, worldCanvas); + tools.update(character, cursor, world, focus, worldCanvas); + info.update(resources, character); + toasts.update(); + } + + if (text.isEnabled) text.update(character); + + if (isStart) + { + if (!isStartBegin) + { + if (auto animation = character.animation_get()) + { + if (animation->isLoop || character.state == entity::Actor::STOPPED) + { + text.set(dialogue.get(dialogue.start.id), character); + isStartBegin = true; + } + } + } + else if (!isStartEnd) + { + if (text.entry->is_last()) + { + isWindows = true; + isStartEnd = true; + isStart = false; + world.character_focus(character, worldCanvas, focus_get()); + } + } + } + + if (character.isJustStageFinal && !isEnd && !isPostgame) isEnd = true; + + if (isEnd) + { + if (!isEndBegin) + { + if (character.is_animation_finished()) + { + text.set(dialogue.get(dialogue.end.id), character); + isEndBegin = true; + isWindows = false; + tools.isOpen = false; + menu.isOpen = false; + character.calories = 0; + character.digestionProgress = 0; + itemManager.items.clear(); + itemManager.heldItemIndex = -1; + world.character_focus(character, worldCanvas, focus_get()); + } + } + else if (!isEndEnd) + { + if (text.entry->is_last()) + { + menu.isOpen = true; + isWindows = true; + isEndEnd = true; + isEnd = false; + isPostgame = true; + } + } + } + + itemManager.update(character, cursor, areaManager, text, World::BOUNDS, worldCanvas); + characterManager.update(character, cursor, text, worldCanvas); + + character.update(); + cursor.update(); + world.update(character, cursor, worldCanvas, focus); + + if (autosaveTime += ImGui::GetIO().DeltaTime; autosaveTime > AUTOSAVE_TIME || menu.configuration.isSave) + { + save(resources); + autosaveTime = 0; + menu.configuration.isSave = false; + } + } + + void Main::render(Resources& resources, Canvas& canvas) + { + auto& textureShader = resources.shaders[shader::TEXTURE]; + auto& rectShader = resources.shaders[shader::RECT]; + auto size = imgui::to_ivec2(ImGui::GetMainViewport()->Size); + + auto& bgTexture = character.data.areaSchema.areas.at(areaManager.get(character)).texture; + + auto windowModel = math::quad_model_get(vec2(size)); + auto worldModel = math::quad_model_get(bgTexture.size); + worldCanvas.bind(); + worldCanvas.size_set(size); + worldCanvas.clear(); + worldCanvas.texture_render(textureShader, bgTexture.id, worldModel); + + character.render(textureShader, rectShader, worldCanvas); + + for (auto& item : itemManager.items) + item.render(textureShader, rectShader, worldCanvas); + + if (menu.debug.isBoundsDisplay) + { + auto boundsModel = + math::quad_model_get(glm::vec2(World::BOUNDS.z, World::BOUNDS.w), glm::vec2(World::BOUNDS.x, World::BOUNDS.y), + glm::vec2(World::BOUNDS.x, World::BOUNDS.y) * 0.5f); + worldCanvas.rect_render(rectShader, boundsModel); + } + worldCanvas.unbind(); + + canvas.bind(); + canvas.texture_render(textureShader, worldCanvas.texture, windowModel); + ImGui::Render(); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + cursor.render(textureShader, rectShader, canvas); + canvas.unbind(); + + SDL_HideCursor(); + } + + void Main::save(Resources& resources) + { + resource::xml::Save save; + + save.weight = character.weight; + save.calories = character.calories; + save.capacity = character.capacity; + save.digestionRate = character.digestionRate; + save.eatSpeed = character.eatSpeed; + save.digestionProgress = character.digestionProgress; + save.isDigesting = character.isDigesting; + save.digestionTimer = character.digestionTimer; + save.totalCaloriesConsumed = character.totalCaloriesConsumed; + save.totalFoodItemsEaten = character.totalFoodItemsEaten; + save.totalPlays = menu.play.totalPlays; + save.highScore = menu.play.highScore; + save.bestCombo = menu.play.bestCombo; + save.gradeCounts = menu.play.gradeCounts; + save.isPostgame = isPostgame; + save.isAlternateSpritesheet = character.spritesheetType == entity::Character::ALTERNATE; + + for (auto& [id, quantity] : menu.inventory.values) + { + if (quantity == 0) continue; + save.inventory[id] = quantity; + } + + for (auto& item : itemManager.items) + save.items.emplace_back(item.schemaID, item.chewCount, item.position, item.velocity, + *item.overrides[item.rotationOverrideID].frame.rotation); + + save.isValid = true; + + resources.character_save_set(characterIndex, save); + save.serialize(character.data.save_path_get()); + + toasts.push("Saving..."); + } +}; diff --git a/src/state/main.hpp b/src/state/main.hpp new file mode 100644 index 0000000..3de806c --- /dev/null +++ b/src/state/main.hpp @@ -0,0 +1,69 @@ +#pragma once + +#include "../resources.hpp" + +#include "main/area_manager.hpp" +#include "main/character_manager.hpp" +#include "main/info.hpp" +#include "main/item_manager.hpp" +#include "main/menu.hpp" +#include "main/text.hpp" +#include "main/toasts.hpp" +#include "main/tools.hpp" +#include "main/world.hpp" + +namespace game::state +{ + class Main + { + public: + static constexpr auto AUTOSAVE_TIME = 30.0f; + + enum Game + { + NEW_GAME, + CONTINUE + }; + + entity::Character character; + entity::Cursor cursor; + + main::Info info; + main::Menu menu; + main::Tools tools; + main::Text text; + main::World world; + main::Toasts toasts; + main::ItemManager itemManager{}; + main::CharacterManager characterManager{}; + main::AreaManager areaManager{}; + + int characterIndex{}; + int areaIndex{}; + + float autosaveTime{}; + + bool isWindows{true}; + + bool isStartBegin{}; + bool isStart{}; + bool isStartEnd{}; + + bool isEndBegin{}; + bool isEnd{}; + bool isEndEnd{}; + + bool isPostgame{}; + + Canvas worldCanvas{main::World::SIZE}; + + Main() = default; + void set(Resources&, int characterIndex, Game = CONTINUE); + void exit(Resources& resources); + void update(Resources&); + void tick(Resources&); + void render(Resources&, Canvas&); + void save(Resources&); + main::World::Focus focus_get(); + }; +}; diff --git a/src/state/main/area_manager.cpp b/src/state/main/area_manager.cpp new file mode 100644 index 0000000..d177f66 --- /dev/null +++ b/src/state/main/area_manager.cpp @@ -0,0 +1,26 @@ +#include "area_manager.hpp" + +#include + +using namespace game::resource; +using namespace game::util; + +namespace game::state::main +{ + int AreaManager::get(entity::Character& character) + { + auto& data = character.data; + auto& schema = data.areaSchema; + if (schema.areas.empty()) return -1; + + auto size = (int)data.stages.size(); + + for (int i = 0; i < size; i++) + { + auto& stage = data.stages[size - i - 1]; + if (stage.areaID != -1) return stage.areaID; + } + + return -1; + } +} diff --git a/src/state/main/area_manager.hpp b/src/state/main/area_manager.hpp new file mode 100644 index 0000000..1c2757a --- /dev/null +++ b/src/state/main/area_manager.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include "../../entity/character.hpp" + +namespace game::state::main +{ + class AreaManager + { + public: + int get(entity::Character&); + }; +} diff --git a/src/state/main/character_manager.cpp b/src/state/main/character_manager.cpp new file mode 100644 index 0000000..e5408ae --- /dev/null +++ b/src/state/main/character_manager.cpp @@ -0,0 +1,120 @@ +#include "character_manager.hpp" + +#include "../../util/math.hpp" + +#include +#include + +using namespace game::resource::xml; +using namespace game::util; + +namespace game::state::main +{ + void CharacterManager::update(entity::Character& character, entity::Cursor& cursor, Text& text, Canvas& canvas) + { + auto interact_area_override_tick = [](entity::Actor::Override& override_) + { + if (override_.frame.scale.has_value() && override_.frameBase.scale.has_value() && override_.time.has_value() && + override_.timeStart.has_value()) + { + auto percent = glm::clamp(*override_.time / *override_.timeStart, 0.0f, 1.0f); + auto elapsed = 1.0f - percent; + + auto oscillation = cosf(elapsed * glm::tau() * override_.cycles); + auto envelope = percent; + auto amplitude = glm::abs(*override_.frameBase.scale); + + *override_.frame.scale = amplitude * (oscillation * envelope); + } + }; + + auto& dialogue = character.data.dialogue; + auto cursorWorldPosition = canvas.screen_position_convert(cursor.position); + auto isMouseLeftClick = ImGui::IsMouseClicked(ImGuiMouseButton_Left); + auto isMouseLeftReleased = ImGui::IsMouseReleased(ImGuiMouseButton_Left); + auto isImguiCaptureMouse = ImGui::GetIO().WantCaptureMouse; + + isInteractingPrevious = isInteracting; + isHoveringPrevious = isHovering; + isHovering = false; + + if (isJustStoppedInteracting) + { + cursor.queue_play({cursor.defaultAnimation}); + if (cursor.mode == RUB) character.queue_idle_animation(); + isJustStoppedInteracting = false; + } + + if (isJustStoppedHovering) + { + cursor.queue_play({cursor.defaultAnimation}); + isJustStoppedHovering = false; + } + + for (int i = 0; i < (int)character.data.interactAreas.size(); i++) + { + auto& interactArea = character.data.interactAreas.at(i); + if (interactArea.nullID == -1) continue; + auto rect = character.null_frame_rect(interactArea.nullID); + + if (cursor.state == entity::Cursor::DEFAULT && math::is_point_in_rectf(rect, cursorWorldPosition) && + !isImguiCaptureMouse && interactArea.type == cursor.mode) + { + cursor.state = entity::Cursor::HOVER; + cursor.queue_play({interactArea.animationCursorHover}); + isHovering = true; + interactAreaID = i; + + if (isMouseLeftClick) + { + isInteracting = true; + interactArea.sound.play(); + lastInteractType = cursor.mode; + + if (interactArea.digestionBonusClick > 0 && character.calories > 0 && !character.isDigesting) + character.digestionProgress += interactArea.digestionBonusClick; + + if (interactArea.layerID != -1) + { + character.overrides.emplace_back(entity::Actor::Override( + interactArea.layerID, Anm2::LAYER, entity::Actor::Override::ADD, + {.scale = glm::vec2(interactArea.scaleEffectAmplitude)}, std::optional(interactArea.time), + interact_area_override_tick, interactArea.scaleEffectCycles)); + } + + if (interactArea.pool.is_valid() && text.is_interruptible()) + text.set(dialogue.get(interactArea.pool), character); + } + + if (isInteracting) + { + cursor.state = entity::Cursor::ACTION; + character.queue_interact_area_animation(interactArea); + cursor.queue_play({interactArea.animationCursorActive}); + + if (interactArea.digestionBonusRub > 0 && character.calories > 0 && !character.isDigesting) + { + auto mouseDelta = cursorWorldPosition - cursorWorldPositionPrevious; + auto digestionBonus = (fabs(mouseDelta.x) + fabs(mouseDelta.y)) * interactArea.digestionBonusRub; + character.digestionProgress += digestionBonus; + } + } + } + + if ((i == interactAreaID && !math::is_point_in_rectf(rect, cursorWorldPosition)) || isMouseLeftReleased || + isImguiCaptureMouse) + { + isInteracting = false; + interactAreaID = -1; + } + } + + if (isInteracting != isInteractingPrevious && !isInteracting) isJustStoppedInteracting = true; + if (isHovering != isHoveringPrevious && !isHovering) isJustStoppedHovering = true; + + cursorWorldPositionPrevious = cursorWorldPosition; + + if (character.isJustDigested && text.is_interruptible()) text.set(dialogue.get(dialogue.digest), character); + if (character.isJustStageUp) text.set(dialogue.get(dialogue.stageUp), character); + } +} diff --git a/src/state/main/character_manager.hpp b/src/state/main/character_manager.hpp new file mode 100644 index 0000000..8818d08 --- /dev/null +++ b/src/state/main/character_manager.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "../../entity/character.hpp" +#include "../../entity/cursor.hpp" +#include "text.hpp" + +namespace game::state::main +{ + class CharacterManager + { + public: + bool isInteracting{}; + bool isHovering{}; + bool isInteractingPrevious{}; + bool isHoveringPrevious{}; + bool isJustStoppedInteracting{}; + bool isJustStoppedHovering{}; + int interactAreaID{-1}; + InteractType lastInteractType{(InteractType)-1}; + + glm::vec2 cursorWorldPositionPrevious{}; + std::string queuedAnimation{}; + + void update(entity::Character&, entity::Cursor&, Text&, Canvas&); + }; +} diff --git a/src/state/main/chat.cpp b/src/state/main/chat.cpp new file mode 100644 index 0000000..c51c55a --- /dev/null +++ b/src/state/main/chat.cpp @@ -0,0 +1,32 @@ +#include "chat.hpp" + +#include "../../util/imgui/widget.hpp" + +using namespace game::resource; +using namespace game::util::imgui; + +namespace game::state::main +{ + void Chat::update(Resources& resources, Text& text, entity::Character& character) + { + auto& dialogue = character.data.dialogue; + auto size = ImGui::GetContentRegionAvail(); + + ImGui::PushFont(ImGui::GetFont(), Font::HEADER_2); + + if (dialogue.random.is_valid()) + if (WIDGET_FX(ImGui::Button("Let's chat!", ImVec2(size.x, 0)))) + text.set(dialogue.get(dialogue.random), character); + + ImGui::PopFont(); + + if (dialogue.help.is_valid()) + if (WIDGET_FX(ImGui::Button("Help", ImVec2(size.x, 0)))) text.set(dialogue.get(dialogue.help), character); + + auto stage = glm::clamp(0, character.stage_get(), character.stage_max_get()); + auto& pool = stage > 0 ? character.data.stages.at(stage - 1).pool : character.data.pool; + + if (pool.is_valid()) + if (WIDGET_FX(ImGui::Button("How are you feeling?", ImVec2(size.x, 0)))) text.set(dialogue.get(pool), character); + } +} diff --git a/src/state/main/chat.hpp b/src/state/main/chat.hpp new file mode 100644 index 0000000..bf3ff2f --- /dev/null +++ b/src/state/main/chat.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include "text.hpp" + +#include + +namespace game::state::main +{ + class Chat + { + public: + void update(Resources&, Text&, entity::Character&); + }; +} diff --git a/src/state/main/cheats.cpp b/src/state/main/cheats.cpp new file mode 100644 index 0000000..9b982d7 --- /dev/null +++ b/src/state/main/cheats.cpp @@ -0,0 +1,114 @@ +#include "cheats.hpp" + +#include +#include + +#include "../../util/imgui/input_int_ex.hpp" +#include "../../util/imgui/widget.hpp" + +using namespace game::util::imgui; +using namespace game::util; + +namespace game::state::main +{ + void Cheats::update(Resources& resources, entity::Character& character, Inventory& inventory, Text& text) + { + static constexpr auto FEED_INCREMENT = 100.0f; + + if (ImGui::BeginChild("##Cheats")) + { + + if (WIDGET_FX(ImGui::Button("Feed"))) + { + character.calories = std::min(character.calories + FEED_INCREMENT, character.max_capacity()); + character.queue_idle_animation(); + } + ImGui::SameLine(); + if (WIDGET_FX(ImGui::Button("Starve"))) + { + character.calories = std::max(0.0f, character.calories - FEED_INCREMENT); + character.queue_idle_animation(); + } + ImGui::SameLine(); + if (WIDGET_FX(ImGui::Button("Digest"))) character.digestionProgress = entity::Character::DIGESTION_MAX; + + if (WIDGET_FX(ImGui::SliderFloat("Weight", &character.weight, character.data.weightMin, character.data.weightMax, + "%0.2f kg"))) + { + character.stage = character.stage_get(); + character.queue_idle_animation(); + } + + auto stage = character.stage + 1; + if (WIDGET_FX(ImGui::SliderInt("Stage", &stage, 1, character.data.stages.size() + 1))) + { + character.stage = glm::clamp(0, stage - 1, (int)character.data.stages.size()); + character.weight = + character.stage == 0 ? character.data.weight : character.data.stages.at(character.stage - 1).threshold; + character.queue_idle_animation(); + } + + WIDGET_FX(ImGui::SliderFloat("Capacity", &character.capacity, character.data.capacityMin, + character.data.capacityMax, "%0.0f kcal")); + + WIDGET_FX(ImGui::SliderFloat("Digestion Rate", &character.digestionRate, character.data.digestionRateMin, + character.data.digestionRateMax, "%0.2f% / tick")); + WIDGET_FX(ImGui::SliderFloat("Eat Speed", &character.eatSpeed, character.data.eatSpeedMin, + character.data.eatSpeedMax, "%0.2fx")); + + ImGui::SeparatorText("Animations"); + ImGui::Text("Now Playing: %s", character.animationMapReverse.at(character.animationIndex).c_str()); + + auto childSize = ImVec2(0, ImGui::GetContentRegionAvail().y / 3); + + if (ImGui::BeginChild("##Animations", childSize, ImGuiChildFlags_Borders)) + { + for (int i = 0; i < (int)character.animations.size(); i++) + { + auto& animation = character.animations[i]; + ImGui::PushID(i); + if (WIDGET_FX(ImGui::Selectable(animation.name.c_str()))) + character.play(animation.name.c_str(), entity::Actor::PLAY_FORCE); + ImGui::SetItemTooltip("%s", animation.name.c_str()); + ImGui::PopID(); + } + } + ImGui::EndChild(); + + ImGui::SeparatorText("Dialogue"); + + if (ImGui::BeginChild("##Dialogue", childSize, ImGuiChildFlags_Borders)) + { + for (int i = 0; i < (int)character.data.dialogue.entries.size(); i++) + { + auto& entry = character.data.dialogue.entries[i]; + ImGui::PushID(i); + if (WIDGET_FX(ImGui::Selectable(entry.name.c_str()))) text.set(&entry, character); + ImGui::SetItemTooltip("%s", entry.name.c_str()); + ImGui::PopID(); + } + } + ImGui::EndChild(); + + ImGui::SeparatorText("Inventory"); + + if (ImGui::BeginChild("##Inventory", ImGui::GetContentRegionAvail(), ImGuiChildFlags_Borders)) + { + auto& schema = character.data.itemSchema; + + ImGui::PushItemWidth(100); + for (int i = 0; i < (int)schema.items.size(); i++) + { + auto& item = schema.items[i]; + ImGui::PushID(i); + WIDGET_FX(input_int_range(item.name.c_str(), &inventory.values[i], 0, schema.quantityMax, 1, 5)); + ImGui::SetItemTooltip("%s", item.name.c_str()); + ImGui::PopID(); + } + ImGui::PopItemWidth(); + } + ImGui::EndChild(); + } + ImGui::EndChild(); + } +} diff --git a/src/state/main/cheats.hpp b/src/state/main/cheats.hpp new file mode 100644 index 0000000..5def3cf --- /dev/null +++ b/src/state/main/cheats.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include "inventory.hpp" +#include "text.hpp" + +#include + +namespace game::state::main +{ + class Cheats + { + public: + void update(Resources&, entity::Character&, Inventory&, Text&); + }; +} diff --git a/src/state/main/debug.cpp b/src/state/main/debug.cpp new file mode 100644 index 0000000..6d81ca7 --- /dev/null +++ b/src/state/main/debug.cpp @@ -0,0 +1,37 @@ +#include "debug.hpp" + +#include "../../util/imgui/widget.hpp" + +#include + +using namespace game::util::imgui; + +namespace game::state::main +{ + void Debug::update(entity::Character& character, entity::Cursor& cursor, ItemManager& itemManager, Canvas& canvas) + { + auto cursorPosition = canvas.screen_position_convert(cursor.position); + + ImGui::Text("Cursor Pos (Screen): %0.0f, %0.0f", cursor.position.x, cursor.position.y); + ImGui::Text("Cursor Pos (World): %0.0f, %0.0f", cursorPosition.x, cursorPosition.y); + + WIDGET_FX(ImGui::Checkbox("Show Nulls (Hitboxes)", &character.isShowNulls)); + WIDGET_FX(ImGui::Checkbox("Show World Bounds", &isBoundsDisplay)); + + if (!itemManager.items.empty()) + { + ImGui::SeparatorText("Item"); + + for (int i = 0; i < (int)itemManager.items.size(); i++) + { + auto& item = itemManager.items[i]; + if (itemManager.heldItemIndex == i) ImGui::Text("Held"); + ImGui::Text("Type: %i", item.schemaID); + ImGui::Text("Position: %0.0f, %0.0f", item.position.x, item.position.y); + ImGui::Text("Velocity: %0.0f, %0.0f", item.velocity.x, item.velocity.y); + ImGui::Text("Chew Count: %i", item.chewCount); + ImGui::Separator(); + } + } + } +} diff --git a/src/state/main/debug.hpp b/src/state/main/debug.hpp new file mode 100644 index 0000000..1214fb9 --- /dev/null +++ b/src/state/main/debug.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include "../../entity/character.hpp" +#include "../../entity/cursor.hpp" + +#include "item_manager.hpp" + +#include + +namespace game::state::main +{ + class Debug + { + public: + bool isBoundsDisplay{}; + + void update(entity::Character&, entity::Cursor& cursor, ItemManager&, Canvas& canvas); + }; +} diff --git a/src/state/main/info.cpp b/src/state/main/info.cpp new file mode 100644 index 0000000..9f51cfd --- /dev/null +++ b/src/state/main/info.cpp @@ -0,0 +1,125 @@ +#include "info.hpp" + +#include "../../util/color.hpp" +#include "../../util/imgui.hpp" +#include "../../util/math.hpp" +#include "../../util/string.hpp" + +#include +#include + +using namespace game::resource; +using namespace game::util; + +namespace game::state::main +{ + void Info::update(Resources& resources, entity::Character& character) + { + static constexpr auto WIDTH_MULTIPLIER = 0.30f; + static constexpr auto HEIGHT_MULTIPLIER = 4.0f; + + auto& style = ImGui::GetStyle(); + auto windowSize = imgui::to_ivec2(ImGui::GetMainViewport()->Size); + + auto size = ImVec2(windowSize.x * WIDTH_MULTIPLIER - (style.WindowPadding.x * 2.0f), + ImGui::GetTextLineHeightWithSpacing() * HEIGHT_MULTIPLIER); + auto pos = ImVec2((windowSize.x * 0.5f) - (size.x * 0.5f), style.WindowPadding.y); + + ImGui::SetNextWindowSize(size); + ImGui::SetNextWindowPos(pos); + + if (ImGui::Begin("##Info", nullptr, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + auto childSize = ImVec2(ImGui::GetContentRegionAvail().x / 2, ImGui::GetContentRegionAvail().y); + + if (ImGui::BeginChild("##Weight", childSize)) + { + auto& system = resources.settings.measurementSystem; + auto weight = character.weight_get(system); + auto stage = character.stage_get(); + auto stageMax = character.stage_max_get(); + auto stageWeight = character.stage_threshold_get(stage, system); + auto stageNextWeight = character.stage_threshold_next_get(system); + auto unitString = (system == measurement::IMPERIAL ? "lbs" : "kg"); + + auto weightString = util::string::format_commas(weight, 2) + " " + unitString; + ImGui::PushFont(ImGui::GetFont(), Font::ABOVE_AVERAGE); + ImGui::TextUnformatted(weightString.c_str()); + ImGui::SetItemTooltip("%s", weightString.c_str()); + ImGui::PopFont(); + + auto stageProgress = character.stage_progress_get(); + ImGui::ProgressBar(stageProgress, ImVec2(ImGui::GetContentRegionAvail().x, 0), + stage >= stageMax ? "MAX" : "To Next Stage"); + if (ImGui::BeginItemTooltip()) + { + ImGui::Text("Stage: %i/%i (%0.1f%%)", stage + 1, stageMax + 1, math::to_percent(stageProgress)); + ImGui::Separator(); + ImGui::PushStyleColor(ImGuiCol_Text, imgui::to_imvec4(color::GRAY)); + if (stage >= stageMax) + ImGui::Text("Maxed out!"); + else + { + ImGui::Text("Start: %0.2f %s", stageWeight, unitString); + ImGui::Text("Current: %0.2f %s", weight, unitString); + ImGui::Text("Next: %0.2f %s", stageNextWeight, unitString); + } + ImGui::PopStyleColor(); + ImGui::EndTooltip(); + } + } + ImGui::EndChild(); + + ImGui::SameLine(); + + if (ImGui::BeginChild("##Calories and Capacity", childSize)) + { + auto& calories = character.calories; + auto& capacity = character.capacity; + + auto overstuffedPercent = std::max(0.0f, (calories - capacity) / (character.max_capacity() - capacity)); + auto caloriesColor = ImVec4(1.0f, 1.0f - overstuffedPercent, 1.0f - overstuffedPercent, 1.0f); + + ImGui::PushFont(ImGui::GetFont(), Font::ABOVE_AVERAGE); + ImGui::PushStyleColor(ImGuiCol_Text, caloriesColor); + auto caloriesString = std::format("{:.0f} kcal / {:.0f} kcal", calories, + character.is_over_capacity() ? character.max_capacity() : character.capacity); + ImGui::TextUnformatted(caloriesString.c_str()); + ImGui::SetItemTooltip("%s", caloriesString.c_str()); + ImGui::PopStyleColor(); + ImGui::PopFont(); + + auto digestionProgress = character.isDigesting + ? (float)character.digestionTimer / character.data.digestionTimerMax + : character.digestionProgress / entity::Character::DIGESTION_MAX; + ImGui::ProgressBar(digestionProgress, ImVec2(ImGui::GetContentRegionAvail().x, 0), + character.isDigesting ? "Digesting..." : "Digestion"); + + if (ImGui::BeginItemTooltip()) + { + if (character.isDigesting) + ImGui::TextUnformatted("Digestion in progress..."); + else if (digestionProgress <= 0.0f) + ImGui::TextUnformatted("Give food to start digesting!"); + else + ImGui::Text("%0.2f%%", math::to_percent(digestionProgress)); + + ImGui::Separator(); + + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(imgui::to_imvec4(color::GRAY))); + + ImGui::Text("Rate: %0.2f%% / sec", character.digestion_rate_get()); + ImGui::Text("Eating Speed: %0.2fx", character.eatSpeed); + + ImGui::PopStyleColor(); + + ImGui::EndTooltip(); + } + } + ImGui::EndChild(); + } + ImGui::End(); + } +} diff --git a/src/state/main/info.hpp b/src/state/main/info.hpp new file mode 100644 index 0000000..322c193 --- /dev/null +++ b/src/state/main/info.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include "../../entity/character.hpp" +#include "../../resources.hpp" + +#include + +namespace game::state::main +{ + class Info + { + public: + void update(Resources&, entity::Character&); + }; +} diff --git a/src/state/main/inventory.cpp b/src/state/main/inventory.cpp new file mode 100644 index 0000000..01f6ed9 --- /dev/null +++ b/src/state/main/inventory.cpp @@ -0,0 +1,194 @@ +#include "inventory.hpp" + +#include +#include +#include + +#include "../../util/color.hpp" +#include "../../util/imgui.hpp" +#include "../../util/imgui/widget.hpp" +#include "../../util/math.hpp" + +using namespace game::util; +using namespace game::util::imgui; +using namespace game::entity; +using namespace game::resource; +using namespace glm; + +namespace game::state::main +{ + void Inventory::tick() + { + for (auto& [i, actor] : actors) + actor.tick(); + } + + void Inventory::update(Resources& resources, ItemManager& itemManager, entity::Character& character) + { + auto& schema = character.data.itemSchema; + + if (!itemManager.returnItemIDs.empty()) + { + for (auto& id : itemManager.returnItemIDs) + values[id]++; + itemManager.returnItemIDs.clear(); + } + + if (ImGui::BeginChild("##Inventory Child")) + { + auto cursorPos = ImGui::GetCursorPos(); + auto cursorStartX = ImGui::GetCursorPosX(); + + auto size = ImVec2(SIZE, SIZE); + + for (int i = 0; i < (int)schema.items.size(); i++) + { + auto& item = schema.items[i]; + auto& quantity = values[i]; + auto& category = schema.categories[item.categoryID]; + auto& calories = item.calories; + auto& digestionBonus = item.digestionBonus; + auto& eatSpeedBonus = item.eatSpeedBonus; + auto& rarity = schema.rarities[item.rarityID]; + + quantity = glm::clamp(0, quantity, schema.quantityMax); + if (rarity.isHidden && quantity <= 0) continue; + + ImGui::PushID(i); + + ImGui::SetCursorPos(cursorPos); + auto cursorScreenPos = ImGui::GetCursorScreenPos(); + + if (!actors.contains(i)) + { + actors[i] = Actor(schema.anm2s[i], {}, Actor::SET); + rects[i] = actors[i].rect(); + } + auto& rect = rects[i]; + auto rectSize = vec2(rect.z, rect.w); + + auto previewScale = (size.x <= 0.0f || size.y <= 0.0f || rectSize.x <= 0.0f || rectSize.y <= 0.0f || + !std::isfinite(rectSize.x) || !std::isfinite(rectSize.y)) + ? 0.0f + : std::min(size.x / rectSize.x, size.y / rectSize.y); + + auto previewSize = rectSize * previewScale; + auto canvasSize = ivec2(std::max(1.0f, previewSize.x), std::max(1.0f, previewSize.y)); + if (!canvases.contains(i)) canvases.emplace((int)i, Canvas(canvasSize, Canvas::FLIP)); + auto& canvas = canvases[i]; + canvas.zoom = math::to_percent(previewScale); + canvas.pan = vec2(rect.x, rect.y); + canvas.bind(); + canvas.size_set(canvasSize); + canvas.clear(); + + actors[i].render(resources.shaders[shader::TEXTURE], resources.shaders[shader::RECT], canvas); + canvas.unbind(); + + ImGui::BeginDisabled(quantity < 1); + if (WIDGET_FX(ImGui::ImageButton("##Image Button", canvas.texture, size, ImVec2(), ImVec2(1, 1), ImVec4(), + quantity <= 0 ? ImVec4(0, 0, 0, 1) : ImVec4(1, 1, 1, 1))) && + quantity > 0) + { + if (category.isEdible) + { + if (itemManager.items.size() + 1 >= ItemManager::LIMIT) + character.data.itemSchema.sounds.dispose.play(); + else + { + character.data.itemSchema.sounds.summon.play(); + itemManager.queuedItemIDs.emplace_back(i); + quantity--; + } + } + else if (item.isToggleSpritesheet) + { + character.spritesheet_set(character.spritesheetType == Character::NORMAL ? Character::ALTERNATE + : Character::NORMAL); + character.data.alternateSpritesheet.sound.play(); + quantity--; + } + } + + ImGui::EndDisabled(); + + if (ImGui::BeginItemTooltip()) + { + if (quantity > 0) + { + ImGui::PushFont(ImGui::GetFont(), Font::BIG); + + ImGui::Text("%s (x%i)", item.name.c_str(), quantity); + + ImGui::Separator(); + + ImGui::PopFont(); + + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(imgui::to_imvec4(color::GRAY))); + + ImGui::Text("-- %s (%s) --", category.name.c_str(), rarity.name.c_str()); + if (item.flavorID.has_value()) ImGui::Text("Flavor: %s", schema.flavors[*item.flavorID].name.c_str()); + if (calories.has_value()) ImGui::Text("%0.0f kcal", *calories); + if (digestionBonus.has_value()) + { + if (*digestionBonus > 0) + ImGui::Text("Digestion Rate Bonus: +%0.2f%% / sec", *digestionBonus * 60.0f); + else if (digestionBonus < 0) + ImGui::Text("Digestion Rate Penalty: %0.2f%% / sec", *digestionBonus * 60.0f); + } + if (eatSpeedBonus.has_value()) + { + if (*eatSpeedBonus > 0) + ImGui::Text("Eat Speed Bonus: +%0.2f%% / sec", *eatSpeedBonus); + else if (eatSpeedBonus < 0) + ImGui::Text("Eat Speed Penalty: %0.2f%% / sec", *eatSpeedBonus); + } + ImGui::PopStyleColor(); + + ImGui::Separator(); + ImGui::TextUnformatted(item.description.c_str()); + } + else + { + ImGui::PushFont(ImGui::GetFont(), Font::BIG); + ImGui::TextUnformatted("???"); + ImGui::PopFont(); + } + + ImGui::EndTooltip(); + } + + ImGui::PushFont(ImGui::GetFont(), Font::BIG); + + auto text = std::format("x{}", quantity); + auto textPos = ImVec2(cursorScreenPos.x + size.x - ImGui::CalcTextSize(text.c_str()).x, + cursorScreenPos.y + size.y - ImGui::GetTextLineHeightWithSpacing()); + ImGui::GetWindowDrawList()->AddText(textPos, ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Text)), + text.c_str()); + ImGui::PopFont(); + + auto increment = ImGui::GetItemRectSize().x + ImGui::GetStyle().ItemSpacing.x; + cursorPos.x += increment; + + if (cursorPos.x + increment > ImGui::GetContentRegionAvail().x) + { + cursorPos.x = cursorStartX; + cursorPos.y += increment; + } + + ImGui::PopID(); + } + + if (count() == 0) ImGui::Text("Check the \"Play\" tab to earn rewards!"); + } + ImGui::EndChild(); + } + + int Inventory::count() + { + int count{}; + for (auto& [type, quantity] : values) + count += quantity; + return count; + } +} diff --git a/src/state/main/inventory.hpp b/src/state/main/inventory.hpp new file mode 100644 index 0000000..2901e64 --- /dev/null +++ b/src/state/main/inventory.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include "../../entity/character.hpp" + +#include "../../resources.hpp" + +#include "item_manager.hpp" + +#include + +namespace game::state::main +{ + class Inventory + { + public: + static constexpr auto SIZE = 96.0f; + + std::map values{}; + std::unordered_map actors{}; + std::unordered_map rects{}; + std::unordered_map canvases{}; + + void tick(); + void update(Resources&, ItemManager&, entity::Character&); + int count(); + }; +} diff --git a/src/state/main/item_manager.cpp b/src/state/main/item_manager.cpp new file mode 100644 index 0000000..4021be6 --- /dev/null +++ b/src/state/main/item_manager.cpp @@ -0,0 +1,315 @@ +#include "item_manager.hpp" + +#include +#include +#include + +#include "../../util/math.hpp" +#include "../../util/vector.hpp" + +#include + +using namespace game::resource; +using namespace game::util; +using namespace glm; + +namespace game::state::main +{ + void ItemManager::update(entity::Character& character, entity::Cursor& cursor, AreaManager& areaManager, Text& text, + const glm::vec4& bounds, Canvas& canvas) + { + static constexpr float ROTATION_MAX = 90.0f; + static constexpr float ROTATION_RETURN_SPEED = 120.0f; + static constexpr float ROTATION_GROUND_DAMPING = 0.85f; + static constexpr float ROTATION_HOLD_DELTA_ANGULAR_VELOCITY_MULTIPLIER = 0.1f; + static constexpr float THROW_THRESHOLD = 10.0f; + + auto& schema = character.data.itemSchema; + auto& cursorSchema = character.data.cursorSchema; + auto& area = character.data.areaSchema.areas.at(areaManager.get(character)); + auto& friction = area.friction; + auto& airResistance = area.airResistance; + auto& dialogue = character.data.dialogue; + auto isOverCapacity = character.is_over_capacity(); + + auto cursorPosition = canvas.screen_position_convert(cursor.position); + auto cursorDelta = cursorPosition - cursorPositionPrevious; + + auto isImguiCaptureMouse = ImGui::GetIO().WantCaptureMouse; + + auto isMouseLeftClicked = ImGui::IsMouseClicked(ImGuiMouseButton_Left); + auto isMouseLeftDown = ImGui::IsMouseDown(ImGuiMouseButton_Left); + auto isMouseLeftReleased = ImGui::IsMouseReleased(ImGuiMouseButton_Left); + auto isMouseRightClicked = ImGui::IsMouseClicked(ImGuiMouseButton_Right); + auto isMouseRightDown = ImGui::IsMouseDown(ImGuiMouseButton_Right); + + auto& io = ImGui::GetIO(); + + if (isJustItemHoveredStopped) + { + cursor.queue_default_animation(); + isJustItemHoveredStopped = false; + } + + if (isJustItemHeldStopped || isJustItemThrown) + { + cursor.queue_default_animation(); + if (!isJustItemThrown) character.queue_idle_animation(); + isJustItemHeldStopped = false; + isJustItemThrown = false; + } + + isItemHoveredPrevious = isItemHovered; + isItemHovered = false; + if (isItemHovered != isItemHoveredPrevious && !isItemHovered) isJustItemHoveredStopped = true; + + for (auto& id : queuedItemIDs) + { + auto spawnBounds = character.rect(); + auto position = glm::vec2(math::random_in_range(spawnBounds.x, spawnBounds.x + spawnBounds.z), + math::random_in_range(spawnBounds.y, spawnBounds.y + spawnBounds.w)); + + auto& itemSchema = character.data.itemSchema; + items.emplace_back(itemSchema.anm2s.at(id), position, id); + } + queuedItemIDs.clear(); + + if (isMouseRightDown) cursor.queue_play({cursorSchema.animations.return_.get()}); + + if (auto heldItem = vector::find(items, heldItemIndex)) + { + auto& item = schema.items[heldItem->schemaID]; + auto& rotationOverride = heldItem->overrides[heldItem->rotationOverrideID]; + auto& rotation = *rotationOverride.frame.rotation; + + auto delta = cursorPositionPrevious - cursorPosition; + heldItem->position = cursorPosition; + heldItem->velocity = vec2(); + + heldItem->angularVelocity -= delta.x * ROTATION_HOLD_DELTA_ANGULAR_VELOCITY_MULTIPLIER; + heldItem->angularVelocity *= friction; + rotation *= friction; + rotation = glm::clamp(-ROTATION_MAX, rotation, ROTATION_MAX); + + if (schema.categories[item.categoryID].isEdible) + { + auto& chewCountMax = item.chewCount.has_value() ? *item.chewCount : schema.chewCount; + auto caloriesChew = item.calories.has_value() ? *item.calories / (chewCountMax + 1) : 0; + auto isCanEat = character.calories + caloriesChew <= character.max_capacity(); + + if (isJustItemHeld) + { + if (isCanEat) + text.set(dialogue.get(isOverCapacity ? dialogue.feedFull : dialogue.feed), character); + else if (caloriesChew > character.capacity) + text.set(dialogue.get(dialogue.lowCapacity), character); + else + text.set(dialogue.get(dialogue.full), character); + isJustItemHeld = false; + } + + for (auto& eatArea : character.data.eatAreas) + { + heldItem = vector::find(items, heldItemIndex); + if (!heldItem) break; + + auto rect = character.null_frame_rect(eatArea.nullID); + + if (isCanEat && math::is_point_in_rectf(rect, heldItem->position)) + { + character.queue_play( + {.animation = eatArea.animation, .speedMultiplier = character.eatSpeed, .isInterruptible = false}); + + if (character.playedEventID == eatArea.eventID) + { + heldItem->chewCount++; + character.consume_played_event(); + + auto chewAnimation = schema.animations.chew + std::to_string(heldItem->chewCount); + auto animationIndex = heldItem->chewCount > 0 ? heldItem->animationMap[chewAnimation] : -1; + + heldItem->play(animationIndex, entity::Actor::SET); + + character.calories += caloriesChew; + character.totalCaloriesConsumed += caloriesChew; + + if (item.eatSpeedBonus.has_value()) + { + character.eatSpeed += *item.eatSpeedBonus / (chewCountMax + 1); + character.eatSpeed = + glm::clamp(character.data.eatSpeedMin, character.eatSpeed, character.data.eatSpeedMax); + } + if (item.digestionBonus.has_value()) + { + character.digestionRate += *item.digestionBonus / (chewCountMax + 1); + character.digestionRate = glm::clamp(character.data.digestionRateMin, character.digestionRate, + character.data.digestionRateMax); + } + + if (heldItem->chewCount > chewCountMax) + { + isQueueFinishFood = true; + character.totalFoodItemsEaten++; + queuedRemoveItemIndex = heldItemIndex; + heldItemIndex = -1; + } + } + } + + if (isMouseLeftReleased) + { + if (fabs(delta.x) >= THROW_THRESHOLD || fabs(delta.y) >= THROW_THRESHOLD) + { + cursorSchema.sounds.throw_.play(); + text.set(dialogue.get(dialogue.throw_), character); + isJustItemThrown = true; + } + else + cursorSchema.sounds.release.play(); + + heldItem->velocity -= delta; + heldItemIndex = -1; + isJustItemHeldStopped = true; + } + + // Food stolen + if (auto animation = character.animation_get(character.animation_name_convert(eatArea.animation)); + character.is_playing(animation->name) && !isOverCapacity) + { + if (!math::is_point_in_rectf(rect, heldItem->position)) + text.set(dialogue.get(isOverCapacity ? dialogue.foodTakenFull : dialogue.foodTaken), character); + } + } + } + } + + if (auto animation = character.animation_get(); character.time >= animation->frameNum && isQueueFinishFood) + { + text.set(dialogue.get(isOverCapacity ? dialogue.eatFull : dialogue.eat), character); + isQueueFinishFood = false; + } + + if (queuedRemoveItemIndex > -1) + { + items.erase(items.begin() + queuedRemoveItemIndex); + queuedRemoveItemIndex = -1; + } + + int heldItemMoveIndex = -1; + for (int i = 0; i < (int)items.size(); i++) + { + auto& item = items[i]; + auto& schemaItem = schema.items[item.schemaID]; + auto& rotationOverride = item.overrides[item.rotationOverrideID]; + auto& rotation = *rotationOverride.frame.rotation; + auto& gravity = schemaItem.gravity.has_value() ? *schemaItem.gravity : area.gravity; + + item.update(); + + if (math::is_point_in_rectf(item.rect(), cursorPosition) && !isImguiCaptureMouse) + { + isItemHovered = true; + cursor.queue_play({cursorSchema.animations.hover.get()}); + cursor.state = entity::Cursor::HOVER; + + if (isMouseLeftClicked) + { + cursorSchema.sounds.grab.play(); + isJustItemHeld = true; + } + + if (isMouseLeftDown) + { + isItemHeld = true; + cursor.queue_play({cursorSchema.animations.grab.get()}); + cursor.state = entity::Cursor::ACTION; + heldItemIndex = i; + heldItemMoveIndex = i; + } + + if (isMouseRightClicked) + { + if (item.chewCount > 0) + schema.sounds.dispose.play(); + else + { + schema.sounds.return_.play(); + returnItemIDs.emplace_back(item.schemaID); + } + + if (heldItemIndex == i) heldItemIndex = -1; + if (heldItemMoveIndex == i) heldItemMoveIndex = -1; + if (heldItemIndex > i) heldItemIndex--; + if (heldItemMoveIndex > i) heldItemMoveIndex--; + items.erase(items.begin() + i); + continue; + } + } + + if (i != heldItemIndex) + { + + if (item.position.x <= bounds.x || item.position.x >= bounds.z) + { + if (item.position.x <= bounds.x) item.position.x = bounds.x + 1.0f; + if (item.position.x >= bounds.z) item.position.x = bounds.z - 1.0f; + + item.velocity.x *= friction; + item.velocity.x = -item.velocity.x; + item.angularVelocity *= friction; + item.angularVelocity = -item.angularVelocity; + rotation = -rotation; + schema.sounds.bounce.play(); + } + + if (item.position.y <= bounds.y || item.position.y >= bounds.w) + { + + if (item.position.y >= bounds.w && item.velocity.y <= gravity) + { + item.position.y = bounds.w; + item.velocity.y = 0; + item.velocity.x *= friction; + + rotation = std::fmod(rotation, 360.0f); + if (rotation < 0.0f) rotation += 360.0f; + if (rotation > 180.0f) rotation -= 360.0f; + + auto returnStep = ROTATION_RETURN_SPEED * io.DeltaTime; + if (std::abs(rotation) <= returnStep) + rotation = 0.0f; + else + rotation += (rotation > 0.0f) ? -returnStep : returnStep; + + item.angularVelocity *= ROTATION_GROUND_DAMPING; + } + else + { + item.velocity.y = -item.velocity.y; + item.angularVelocity *= friction; + schema.sounds.bounce.play(); + } + + item.velocity.y *= friction; + } + + item.velocity.x *= airResistance; + item.velocity.y += gravity; + } + + item.position.x = glm::clamp(bounds.x, item.position.x, bounds.z); + item.position.y = glm::clamp(bounds.y, item.position.y, bounds.w); + } + + if (heldItemMoveIndex != -1 && heldItemMoveIndex < (int)items.size() - 1) + { + auto heldItem = std::move(items[heldItemMoveIndex]); + items.erase(items.begin() + heldItemMoveIndex); + items.push_back(std::move(heldItem)); + heldItemIndex = (int)items.size() - 1; + } + + cursorPositionPrevious = cursorPosition; + cursorDeltaPrevious = cursorDelta; + } +} diff --git a/src/state/main/item_manager.hpp b/src/state/main/item_manager.hpp new file mode 100644 index 0000000..2664693 --- /dev/null +++ b/src/state/main/item_manager.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include "../../entity/character.hpp" +#include "../../entity/cursor.hpp" +#include "../../entity/item.hpp" + +#include "area_manager.hpp" +#include "text.hpp" + +namespace game::state::main +{ + class ItemManager + { + public: + static constexpr auto LIMIT = 100; + + std::vector items{}; + int heldItemIndex{-1}; + int queuedRemoveItemIndex{-1}; + + bool isItemHovered{}; + bool isItemHoveredPrevious{}; + bool isJustItemHoveredStopped{}; + + bool isItemHeld{}; + bool isItemHeldPrevious{}; + bool isJustItemHeldStopped{}; + bool isJustItemHeld{}; + bool isJustItemThrown{}; + + bool isQueueFinishFood{}; + + bool isItemFinished{}; + + glm::vec2 cursorPositionPrevious{}; + glm::vec2 cursorDeltaPrevious{}; + + std::vector queuedItemIDs{}; + std::vector returnItemIDs{}; + + void update(entity::Character&, entity::Cursor&, AreaManager&, Text&, const glm::vec4& bounds, Canvas&); + }; +} diff --git a/src/state/main/menu.cpp b/src/state/main/menu.cpp new file mode 100644 index 0000000..267c671 --- /dev/null +++ b/src/state/main/menu.cpp @@ -0,0 +1,165 @@ +#include "menu.hpp" + +#include "../../util/imgui.hpp" +#include "../../util/imgui/widget.hpp" + +#include + +using namespace game::util; +using namespace game::util::imgui; + +namespace game::state::main +{ + void Menu::tick() + { + inventory.tick(); + play.tick(); + } + + void Menu::update(Resources& resources, ItemManager& itemManager, entity::Character& character, + entity::Cursor& cursor, Text& text, Canvas& canvas) + { + static constexpr auto WIDTH_MULTIPLIER = 0.30f; + + auto& schema = character.data.menuSchema; + + auto style = ImGui::GetStyle(); + auto& io = ImGui::GetIO(); + + slide.update(isOpen, io.DeltaTime); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); + ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); + + auto windowSize = imgui::to_ivec2(ImGui::GetMainViewport()->Size); + + auto size = ImVec2(windowSize.x * WIDTH_MULTIPLIER, windowSize.y - style.WindowPadding.y * 2); + auto targetX = windowSize.x - size.x; + auto t = slide.value_get(); + auto eased = slide.eased_get(); + auto posX = windowSize.x + (targetX - windowSize.x) * eased; + + auto pos = ImVec2(posX, style.WindowPadding.y); + auto barSize = ImVec2(ImGui::GetTextLineHeightWithSpacing(), windowSize.y - style.WindowPadding.y * 2); + auto barPos = ImVec2(pos.x - barSize.x - style.WindowPadding.x, style.WindowPadding.y); + + if (slide.is_visible()) + { + ImGui::SetNextWindowSize(size); + ImGui::SetNextWindowPos(pos); + + if (ImGui::Begin("##Menu", nullptr, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + if (ImGui::BeginTabBar("##Options")) + { + + if (isChat && WIDGET_FX(ImGui::BeginTabItem("Chat"))) + { + chat.update(resources, text, character); + ImGui::EndTabItem(); + } + + if (WIDGET_FX(ImGui::BeginTabItem("Play"))) + { + play.update(resources, character, inventory, text); + ImGui::EndTabItem(); + } + + if (WIDGET_FX(ImGui::BeginTabItem("Items"))) + { + inventory.update(resources, itemManager, character); + ImGui::EndTabItem(); + } + + if (WIDGET_FX(ImGui::BeginTabItem("Stats"))) + { + stats.update(resources, play, character); + ImGui::EndTabItem(); + } + + if (WIDGET_FX(ImGui::BeginTabItem("Settings"))) + { + configuration.update(resources, Configuration::MAIN); + ImGui::EndTabItem(); + } + + if (isCheats && WIDGET_FX(ImGui::BeginTabItem("Cheats"))) + { + cheats.update(resources, character, inventory, text); + ImGui::EndTabItem(); + } + + if (isDebug && WIDGET_FX(ImGui::BeginTabItem("Debug"))) + { + debug.update(character, cursor, itemManager, canvas); + ImGui::EndTabItem(); + } + } + ImGui::EndTabBar(); + } + ImGui::End(); + } + + ImGui::SetNextWindowSize(barSize); + ImGui::SetNextWindowPos(barPos); + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + if (ImGui::Begin("##Menu Open Bar", nullptr, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + auto buttonSize = ImGui::GetContentRegionAvail(); + auto cursorPos = ImGui::GetCursorScreenPos(); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + auto result = WIDGET_FX(ImGui::Button("##MenuToggle", buttonSize)); + + if (t <= 0.0f || t >= 1.0f) + { + ImGui::SetItemTooltip(isOpen ? "Close Main Menu" : "Open Main Menu"); + if (result) + { + isOpen = !isOpen; + + if (isOpen) + schema.sounds.open.play(); + else + schema.sounds.close.play(); + } + if (!isOpen && t <= 0.0f && ImGui::IsItemHovered()) + { + isOpen = true; + schema.sounds.open.play(); + } + } + ImGui::PopStyleVar(); + + auto center = ImVec2(cursorPos.x + (buttonSize.x * 0.5f), cursorPos.y + (buttonSize.y * 0.5f)); + auto half = std::min(buttonSize.x, buttonSize.y) * 0.22f; + ImVec2 tip; + ImVec2 baseA; + ImVec2 baseB; + if (isOpen) + { + tip = ImVec2(center.x + half, center.y); + baseA = ImVec2(center.x - half, center.y - half); + baseB = ImVec2(center.x - half, center.y + half); + } + else + { + tip = ImVec2(center.x - half, center.y); + baseA = ImVec2(center.x + half, center.y - half); + baseB = ImVec2(center.x + half, center.y + half); + } + + auto color = ImGui::GetColorU32(ImGuiCol_Text); + ImGui::GetWindowDrawList()->AddTriangleFilled(tip, baseA, baseB, color); + } + ImGui::End(); + ImGui::PopStyleVar(2); + ImGui::PopStyleVar(2); + } +} diff --git a/src/state/main/menu.hpp b/src/state/main/menu.hpp new file mode 100644 index 0000000..376f790 --- /dev/null +++ b/src/state/main/menu.hpp @@ -0,0 +1,39 @@ +#pragma once + +#include + +#include "../configuration.hpp" + +#include "chat.hpp" +#include "cheats.hpp" +#include "debug.hpp" +#include "play.hpp" +#include "stats.hpp" +#include "text.hpp" + +#include "../../util/imgui/window_slide.hpp" + +namespace game::state::main +{ + class Menu + { + public: + Play play; + Chat chat; + Cheats cheats; + Debug debug; + Stats stats; + Inventory inventory; + + state::Configuration configuration; + + bool isCheats{true}; + bool isDebug{true}; + bool isOpen{true}; + bool isChat{true}; + util::imgui::WindowSlide slide{}; + + void tick(); + void update(Resources&, ItemManager&, entity::Character&, entity::Cursor&, Text&, Canvas&); + }; +} diff --git a/src/state/main/play.cpp b/src/state/main/play.cpp new file mode 100644 index 0000000..ce093cf --- /dev/null +++ b/src/state/main/play.cpp @@ -0,0 +1,433 @@ +#include "play.hpp" + +#include + +#include "../../util/imgui.hpp" +#include "../../util/imgui/widget.hpp" +#include "../../util/math.hpp" + +#include +#include +#include + +using namespace game::util; +using namespace game::entity; +using namespace game::resource; +using namespace glm; + +namespace game::state::main +{ + float Play::accuracy_score_get(entity::Character& character) + { + if (totalPlays == 0) return 0.0f; + + auto& schema = character.data.playSchema; + + float combinedWeight{}; + + for (int i = 0; i < (int)schema.grades.size(); i++) + { + auto& grade = schema.grades[i]; + combinedWeight += gradeCounts[i] * grade.weight; + } + + return glm::clamp(0.0f, math::to_percent(combinedWeight / totalPlays), 100.0f); + } + + Play::Challenge Play::challenge_generate(entity::Character& character) + { + auto& schema = character.data.playSchema; + + Challenge newChallenge; + + Range newRange{}; + + auto rangeSize = std::max(schema.rangeMin, schema.rangeBase - (schema.rangeScoreBonus * score)); + newRange.min = math::random_max(1.0f - rangeSize); + newRange.max = newRange.min + rangeSize; + + newChallenge.range = newRange; + newChallenge.tryValue = 0.0f; + + newChallenge.speed = + glm::clamp(schema.speedMin, schema.speedMin + (schema.speedScoreBonus * score), schema.speedMax); + + if (math::random_bool()) + { + newChallenge.tryValue = 1.0f; + newChallenge.speed *= -1; + } + + return newChallenge; + } + + Play::Play(entity::Character& character) { challenge = challenge_generate(character); } + + void Play::tick() + { + for (auto& [i, actor] : itemActors) + actor.tick(); + } + + void Play::update(Resources& resources, entity::Character& character, Inventory& inventory, Text& text) + { + static constexpr auto BG_COLOR_MULTIPLIER = 0.5f; + static constexpr ImVec4 LINE_COLOR = ImVec4(1, 1, 1, 1); + static constexpr ImVec4 PERFECT_COLOR = ImVec4(1, 1, 1, 0.50); + static constexpr auto LINE_HEIGHT = 2.0f; + static constexpr auto LINE_WIDTH_BONUS = 10.0f; + static constexpr auto TOAST_MESSAGE_SPEED = 1.0f; + static constexpr auto ITEM_FALL_GRAVITY = 2400.0f; + + auto& dialogue = character.data.dialogue; + auto& schema = character.data.playSchema; + auto& itemSchema = character.data.itemSchema; + auto& style = ImGui::GetStyle(); + auto drawList = ImGui::GetWindowDrawList(); + auto position = ImGui::GetCursorScreenPos(); + auto size = ImGui::GetContentRegionAvail(); + auto spacing = ImGui::GetTextLineHeightWithSpacing(); + auto& io = ImGui::GetIO(); + + auto cursorPos = ImGui::GetCursorPos(); + + ImGui::Text("Score: %i pts (%ix)", score, combo); + auto bestString = std::format("Best: {} pts({}x)", highScore, bestCombo); + ImGui::SetCursorPos(ImVec2(size.x - ImGui::CalcTextSize(bestString.c_str()).x, cursorPos.y)); + + ImGui::Text("Best: %i pts (%ix)", highScore, bestCombo); + + if (score == 0 && isActive) + { + ImGui::SetCursorPos(ImVec2(style.WindowPadding.x, size.y - style.WindowPadding.y)); + ImGui::TextWrapped("Match the line to the colored areas with Space/click! Better performance, better rewards!"); + } + + auto barMin = ImVec2(position.x + (size.x * 0.5f) - (spacing * 0.5f), position.y + (spacing * 2.0f)); + auto barMax = ImVec2(barMin.x + (spacing * 2.0f), barMin.y + size.y - (spacing * 4.0f)); + auto endTimerProgress = (float)endTimer / endTimerMax; + + auto bgColor = ImGui::GetStyleColorVec4(ImGuiCol_FrameBg); + bgColor = imgui::to_imvec4(imgui::to_vec4(bgColor) * BG_COLOR_MULTIPLIER); + drawList->AddRectFilled(barMin, barMax, ImGui::GetColorU32(bgColor)); + + auto barWidth = barMax.x - barMin.x; + auto barHeight = barMax.y - barMin.y; + + auto sub_ranges_get = [&](Range& range) + { + auto& min = range.min; + auto& max = range.max; + std::vector ranges{}; + + auto baseHeight = max - min; + auto center = (min + max) * 0.5f; + + int rangeCount{}; + + for (auto& grade : schema.grades) + { + if (grade.isFailure) continue; + + auto scale = powf(0.5f, rangeCount); + auto halfHeight = baseHeight * scale * 0.5f; + + rangeCount++; + + ranges.push_back({center - halfHeight, center + halfHeight}); + } + + return ranges; + }; + + auto range_draw = [&](Range& range, float alpha = 1.0f) + { + auto subRanges = sub_ranges_get(range); + + for (int i = 0; i < (int)subRanges.size(); i++) + { + auto& subRange = subRanges[i]; + int layer = (int)subRanges.size() - 1 - i; + + ImVec2 rectMin = {barMin.x, barMin.y + subRange.min * barHeight}; + + ImVec2 rectMax = {barMax.x, barMin.y + subRange.max * barHeight}; + + ImVec4 color = + i == (int)subRanges.size() - 1 ? PERFECT_COLOR : ImGui::GetStyleColorVec4(ImGuiCol_FrameBgHovered); + color.w = (color.w - (float)layer / subRanges.size()) * alpha; + + drawList->AddRectFilled(rectMin, rectMax, ImGui::GetColorU32(color)); + } + }; + + range_draw(challenge.range, isActive ? 1.0f : 0.0f); + + auto lineMin = ImVec2(barMin.x - LINE_WIDTH_BONUS, barMin.y + (barHeight * tryValue)); + auto lineMax = ImVec2(barMin.x + barWidth + LINE_WIDTH_BONUS, lineMin.y + LINE_HEIGHT); + auto color = LINE_COLOR; + color.w = isActive ? 1.0f : endTimerProgress; + drawList->AddRectFilled(lineMin, lineMax, ImGui::GetColorU32(color)); + + if (!isActive && !isGameOver) + { + range_draw(queuedChallenge.range, 1.0f - endTimerProgress); + + auto lineMin = ImVec2(barMin.x - LINE_WIDTH_BONUS, barMin.y + (barHeight * queuedChallenge.tryValue)); + auto lineMax = ImVec2(barMin.x + barWidth + LINE_WIDTH_BONUS, lineMin.y + LINE_HEIGHT); + auto color = LINE_COLOR; + color.w = 1.0f - endTimerProgress; + drawList->AddRectFilled(lineMin, lineMax, ImGui::GetColorU32(color)); + } + + if (isActive) + { + tryValue += challenge.speed; + + if (tryValue > 1.0f || tryValue < 0.0f) + { + tryValue = tryValue > 1.0f ? 0.0f : tryValue < 0.0f ? 1.0f : tryValue; + + if (score > 0) + { + score--; + schema.sounds.scoreLoss.play(); + auto toastMessagePosition = + ImVec2(barMin.x - ImGui::CalcTextSize("-1").x - ImGui::GetTextLineHeightWithSpacing(), lineMin.y); + toasts.emplace_back("-1", toastMessagePosition, schema.endTimerMax, schema.endTimerMax); + } + } + + ImGui::SetCursorScreenPos(barMin); + auto barButtonSize = ImVec2(barMax.x - barMin.x, barMax.y - barMin.y); + + if (ImGui::IsKeyPressed(ImGuiKey_Space) || + WIDGET_FX(ImGui::InvisibleButton("##PlayBar", barButtonSize, ImGuiButtonFlags_PressedOnClick))) + { + int gradeID{}; + + auto subRanges = sub_ranges_get(challenge.range); + + for (int i = 0; i < (int)subRanges.size(); i++) + { + auto& subRange = subRanges[i]; + + if (tryValue >= subRange.min && tryValue <= subRange.max) + gradeID = std::min((int)gradeID + 1, (int)schema.grades.size() - 1); + } + + gradeCounts[gradeID]++; + totalPlays++; + + auto& grade = schema.grades.at(gradeID); + grade.sound.play(); + + if (text.is_interruptible() && grade.pool.is_valid()) text.set(dialogue.get(grade.pool), character); + + if (!grade.isFailure) + { + combo++; + score += grade.value; + + if (score >= schema.rewardScore && !isRewardScoreAchieved) + { + schema.sounds.rewardScore.play(); + isRewardScoreAchieved = true; + + for (auto& itemID : itemSchema.rewardItemPool) + { + inventory.values[itemID]++; + if (!itemActors.contains(itemID)) + { + itemActors[itemID] = Actor(itemSchema.anm2s[itemID], {}, Actor::SET); + itemRects[itemID] = itemActors[itemID].rect(); + } + auto rect = itemRects[itemID]; + auto rectSize = vec2(rect.z, rect.w); + auto previewScale = (rectSize.x <= 0.0f || rectSize.y <= 0.0f || size.x <= 0.0f || size.y <= 0.0f || + !std::isfinite(rectSize.x) || !std::isfinite(rectSize.y)) + ? 0.0f + : std::min(size.x / rectSize.x, size.y / rectSize.y); + previewScale = std::min(1.0f, previewScale); + auto previewSize = rectSize * previewScale; + auto minX = position.x; + auto maxX = position.x + size.x - previewSize.x; + auto spawnX = minX >= maxX ? position.x : math::random_in_range(minX, maxX); + auto spawnY = position.y - previewSize.y - math::random_in_range(0.0f, size.y); + items.push_back({itemID, ImVec2(spawnX, spawnY), 0.0f}); + } + + auto toastMessagePosition = + ImVec2(barMin.x - ImGui::CalcTextSize("Fantastic score!\nCongratulations!").x - + ImGui::GetTextLineHeightWithSpacing(), + lineMin.y + (ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().ItemSpacing.y)); + toasts.emplace_back("Fantastic score! Congratulations!", toastMessagePosition, schema.endTimerMax, + schema.endTimerMax); + } + + if (score > highScore) + { + highScore = score; + + if (isHighScoreAchieved && !isHighScoreAchievedThisRun) + { + isHighScoreAchievedThisRun = true; + schema.sounds.highScore.play(); + auto toastMessagePosition = + ImVec2(barMin.x - ImGui::CalcTextSize("High Score!").x - ImGui::GetTextLineHeightWithSpacing(), + lineMin.y + ImGui::GetTextLineHeightWithSpacing()); + toasts.emplace_back("High Score!", toastMessagePosition, schema.endTimerMax, schema.endTimerMax); + } + } + + if (combo > bestCombo) bestCombo = combo; + + auto rewardBonus = (schema.rewardGradeBonus * score) + (schema.rewardGradeBonus * grade.value); + while (rewardBonus > 0.0f) + { + const resource::xml::Item::Pool* pool{}; + int rewardID{-1}; + int rarityID{-1}; + auto chanceBonus = std::max(1.0f, (float)grade.value); + + for (auto& id : itemSchema.rarityIDsSortedByChance) + { + auto& rarity = itemSchema.rarities[id]; + if (rarity.chance <= 0.0f) continue; + + if (math::random_percent_roll(rarity.chance * chanceBonus)) + { + pool = &itemSchema.pools[id]; + rarityID = id; + break; + } + } + + if (pool && !pool->empty()) + { + rewardID = (*pool)[(int)math::random_roll((float)pool->size())]; + auto& rarity = itemSchema.rarities.at(rarityID); + + rarity.sound.play(); + inventory.values[rewardID]++; + if (!itemActors.contains(rewardID)) + { + itemActors[rewardID] = Actor(itemSchema.anm2s[rewardID], {}, Actor::SET); + itemRects[rewardID] = itemActors[rewardID].rect(); + } + auto rect = itemRects[rewardID]; + auto rectSize = vec2(rect.z, rect.w); + auto previewScale = (rectSize.x <= 0.0f || rectSize.y <= 0.0f || size.x <= 0.0f || size.y <= 0.0f || + !std::isfinite(rectSize.x) || !std::isfinite(rectSize.y)) + ? 0.0f + : std::min(size.x / rectSize.x, size.y / rectSize.y); + previewScale = std::min(1.0f, previewScale); + auto previewSize = rectSize * previewScale; + auto minX = position.x; + auto maxX = position.x + size.x - previewSize.x; + auto spawnX = minX >= maxX ? position.x : math::random_in_range(minX, maxX); + auto spawnY = position.y - previewSize.y - math::random_in_range(0.0f, size.y); + items.push_back({rewardID, ImVec2(spawnX, spawnY), 0.0f}); + } + + rewardBonus -= 1.0f; + } + } + else + { + + score = 0; + if (isHighScoreAchieved) schema.sounds.highScoreLoss.play(); + if (highScore > 0) isHighScoreAchieved = true; + isRewardScoreAchieved = false; + isHighScoreAchievedThisRun = true; + highScoreStart = highScore; + isGameOver = true; + } + + endTimerMax = grade.isFailure ? schema.endTimerFailureMax : schema.endTimerMax; + isActive = false; + endTimer = endTimerMax; + + queuedChallenge = challenge_generate(character); + + auto string = grade.isFailure ? grade.name : std::format("{} (+{})", grade.name, grade.value); + auto toastMessagePosition = + ImVec2(barMin.x - ImGui::CalcTextSize(string.c_str()).x - ImGui::GetTextLineHeightWithSpacing(), lineMin.y); + toasts.emplace_back(string, toastMessagePosition, endTimerMax, endTimerMax); + } + } + else + { + endTimer--; + if (endTimer <= 0) + { + challenge = queuedChallenge; + tryValue = challenge.tryValue; + isActive = true; + isGameOver = false; + } + } + + for (int i = 0; i < (int)toasts.size(); i++) + { + auto& toastMessage = toasts[i]; + + toastMessage.position.y -= TOAST_MESSAGE_SPEED; + + auto color = ImGui::GetStyleColorVec4(ImGuiCol_Text); + color.w = ((float)toastMessage.time / toastMessage.timeMax); + + drawList->AddText(toastMessage.position, ImGui::GetColorU32(color), toastMessage.message.c_str()); + + toastMessage.time--; + + if (toastMessage.time <= 0) toasts.erase(toasts.begin() + i--); + } + + auto gravity = ITEM_FALL_GRAVITY; + auto windowMin = position; + auto windowMax = ImVec2(position.x + size.x, position.y + size.y); + ImGui::PushClipRect(windowMin, windowMax, true); + for (int i = 0; i < (int)items.size(); i++) + { + auto& fallingItem = items[i]; + if (!itemActors.contains(fallingItem.id)) + { + items.erase(items.begin() + i--); + continue; + } + + auto rect = itemRects[fallingItem.id]; + auto rectSize = vec2(rect.z, rect.w); + auto previewScale = (rectSize.x <= 0.0f || rectSize.y <= 0.0f || size.x <= 0.0f || size.y <= 0.0f || + !std::isfinite(rectSize.x) || !std::isfinite(rectSize.y)) + ? 0.0f + : std::min(size.x / rectSize.x, size.y / rectSize.y); + previewScale = std::min(1.0f, previewScale); + auto previewSize = rectSize * previewScale; + auto canvasSize = ivec2(std::max(1.0f, previewSize.x), std::max(1.0f, previewSize.y)); + + if (!itemCanvases.contains(fallingItem.id)) + itemCanvases.emplace(fallingItem.id, Canvas(canvasSize, Canvas::FLIP)); + auto& canvas = itemCanvases[fallingItem.id]; + canvas.zoom = math::to_percent(previewScale); + canvas.pan = vec2(rect.x, rect.y); + canvas.bind(); + canvas.size_set(canvasSize); + canvas.clear(); + + itemActors[fallingItem.id].render(resources.shaders[shader::TEXTURE], resources.shaders[shader::RECT], canvas); + canvas.unbind(); + + auto min = fallingItem.position; + auto max = ImVec2(fallingItem.position.x + previewSize.x, fallingItem.position.y + previewSize.y); + drawList->AddImage(canvas.texture, min, max); + + fallingItem.velocity += gravity * io.DeltaTime; + fallingItem.position.y += fallingItem.velocity * io.DeltaTime; + if (fallingItem.position.y > position.y + size.y) items.erase(items.begin() + i--); + } + ImGui::PopClipRect(); + } +} diff --git a/src/state/main/play.hpp b/src/state/main/play.hpp new file mode 100644 index 0000000..46ffbad --- /dev/null +++ b/src/state/main/play.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include "../../canvas.hpp" +#include "../../entity/actor.hpp" +#include "../../entity/character.hpp" +#include "../../resources.hpp" + +#include "inventory.hpp" +#include "text.hpp" + +#include +#include +#include +#include + +namespace game::state::main +{ + class Play + { + + public: + struct Range + { + float min{}; + float max{}; + }; + + struct Challenge + { + Range range{}; + float speed{}; + float tryValue{}; + int level{}; + }; + + struct Toast + { + std::string message{}; + ImVec2 position; + int time{}; + int timeMax{}; + }; + + struct Item + { + int id{-1}; + ImVec2 position{}; + float velocity{}; + }; + + Challenge challenge{}; + Challenge queuedChallenge{}; + float tryValue{}; + + int score{}; + int combo{}; + + int endTimer{}; + int endTimerMax{}; + + int highScoreStart{}; + + int bestCombo{}; + int highScore{}; + int totalPlays{}; + std::map gradeCounts{}; + + bool isActive{true}; + bool isRewardScoreAchieved{false}; + bool isHighScoreAchieved{false}; + bool isHighScoreAchievedThisRun{false}; + bool isGameOver{}; + + std::vector toasts{}; + std::vector items{}; + std::unordered_map itemActors{}; + std::unordered_map itemRects{}; + std::unordered_map itemCanvases{}; + + Play() = default; + Play(entity::Character&); + Challenge challenge_generate(entity::Character&); + void tick(); + void update(Resources&, entity::Character&, Inventory&, Text&); + float accuracy_score_get(entity::Character&); + }; +} diff --git a/src/state/main/stats.cpp b/src/state/main/stats.cpp new file mode 100644 index 0000000..3a76b92 --- /dev/null +++ b/src/state/main/stats.cpp @@ -0,0 +1,48 @@ +#include "stats.hpp" + +#include + +#include "../../util/measurement.hpp" + +using namespace game::resource; +using namespace game::util; + +namespace game::state::main +{ + void Stats::update(Resources& resources, Play& play, entity::Character& character) + { + ImGui::PushFont(ImGui::GetFont(), Font::BIG); + ImGui::TextUnformatted(character.data.name.c_str()); + ImGui::PopFont(); + + ImGui::Separator(); + + auto& playSchema = character.data.playSchema; + auto& system = resources.settings.measurementSystem; + auto weight = character.weight_get(system); + auto weightUnit = system == measurement::IMPERIAL ? "lbs" : "kg"; + + ImGui::Text("Weight: %0.2f %s (Stage: %i)", weight, weightUnit, character.stage_get() + 1); + ImGui::Text("Capacity: %0.0f kcal (Max: %0.0f kcal)", character.capacity, character.max_capacity()); + ImGui::Text("Digestion Rate: %0.2f%%/sec", character.digestion_rate_get()); + ImGui::Text("Eating Speed: %0.2fx", character.eatSpeed); + + ImGui::SeparatorText("Totals"); + + ImGui::Text("Total Calories Consumed: %0.0f kcal", character.totalCaloriesConsumed); + ImGui::Text("Total Food Items Eaten: %i", character.totalFoodItemsEaten); + + ImGui::SeparatorText("Play"); + + ImGui::Text("Best: %i pts (%ix)", play.highScore, play.bestCombo); + ImGui::Text("Total Plays: %i", play.totalPlays); + + for (int i = 0; i < (int)playSchema.grades.size(); i++) + { + auto& grade = playSchema.grades[i]; + ImGui::Text("%s: %i", grade.namePlural.c_str(), play.gradeCounts[i]); + } + + ImGui::Text("Accuracy: %0.2f%%", play.accuracy_score_get(character)); + } +} diff --git a/src/state/main/stats.hpp b/src/state/main/stats.hpp new file mode 100644 index 0000000..cd561a4 --- /dev/null +++ b/src/state/main/stats.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "../../entity/character.hpp" +#include "../../resources.hpp" + +#include "play.hpp" + +#include + +namespace game::state::main +{ + class Stats + { + public: + void update(Resources&, Play&, entity::Character&); + }; +} diff --git a/src/state/main/text.cpp b/src/state/main/text.cpp new file mode 100644 index 0000000..8c97355 --- /dev/null +++ b/src/state/main/text.cpp @@ -0,0 +1,205 @@ +#include "text.hpp" + +#include +#include + +#include +#include + +#include "../../util/imgui.hpp" +#include "../../util/imgui/widget.hpp" +#include "../../util/math.hpp" + +using namespace game::util; + +namespace game::state::main +{ + const char* utf8_advance_chars(const char* text, const char* end, int count) + { + const char* it = text; + while (it < end && count > 0) + { + unsigned int codepoint = 0; + int step = ImTextCharFromUtf8(&codepoint, it, end); + if (step <= 0) break; + it += step; + --count; + } + return it; + } + + void Text::set(resource::xml::Dialogue::Entry* entry, entity::Character& character) + { + if (!entry) return; + this->entry = entry; + + isFinished = false; + index = 0; + time = 0.0f; + isEnabled = true; + character.isTalking = true; + if (!entry->animation.empty()) character.play_convert(entry->animation); + if (entry->text.empty()) isEnabled = false; + } + + void Text::tick(entity::Character& character) + { + if (!entry || isFinished) return; + + index++; + + if (index >= ImTextCountCharsFromUtf8(entry->text.c_str(), entry->text.c_str() + entry->text.size())) + { + isFinished = true; + character.isTalking = false; + } + } + + void Text::update(entity::Character& character) + { + static constexpr auto WIDTH_MULTIPLIER = 0.30f; + static constexpr auto HEIGHT_MULTIPLIER = 6.0f; + + if (!entry) return; + auto& dialogue = character.data.dialogue; + auto& menuSchema = character.data.menuSchema; + + auto& style = ImGui::GetStyle(); + auto windowSize = imgui::to_ivec2(ImGui::GetMainViewport()->Size); + + auto size = ImVec2(windowSize.x * WIDTH_MULTIPLIER - (style.WindowPadding.x * 2.0f), + ImGui::GetTextLineHeightWithSpacing() * HEIGHT_MULTIPLIER); + auto pos = ImVec2((windowSize.x * 0.5f) - (size.x * 0.5f), windowSize.y - size.y - style.WindowPadding.y); + + ImGui::SetNextWindowSize(size); + ImGui::SetNextWindowPos(pos); + + if (!entry) return; + + if (ImGui::Begin("##Text", nullptr, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + auto isHovered = ImGui::IsWindowHovered(); + auto isMouse = ImGui::IsMouseReleased(ImGuiMouseButton_Left); + auto isSpace = ImGui::IsKeyReleased(ImGuiKey_Space); + auto isAdvance = (isHovered && (isMouse || isSpace)); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, 0)); + + if (ImGui::BeginTabBar("##Name")) + { + if (ImGui::BeginTabItem(character.data.name.c_str())) ImGui::EndTabItem(); + ImGui::EndTabBar(); + } + + auto available = ImGui::GetContentRegionAvail(); + + auto font = ImGui::GetFont(); + auto fontSize = resource::Font::NORMAL; + + ImGui::PushFont(font, fontSize); + + auto text = [&]() + { + auto text = entry ? std::string_view(entry->text) : "null"; + auto length = std::clamp(index, 0, ImTextCountCharsFromUtf8(text.data(), text.data() + text.size())); + + if (length <= 0) + { + ImGui::Dummy(ImVec2(1.0f, ImGui::GetTextLineHeight())); + return; + } + + const char* textStart = text.data(); + const char* textEnd = textStart + text.size(); + const char* textLimit = utf8_advance_chars(textStart, textEnd, length); + + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + available.x); + ImGui::TextUnformatted(textStart, textLimit); + ImGui::PopTextWrapPos(); + }; + + text(); + + if (entry) + { + if (isFinished) + { + if (!entry->choices.empty()) + { + ImGui::SetCursorPos(ImVec2(ImGui::GetStyle().WindowPadding.x, available.y)); + auto buttonSize = imgui::row_widget_size_get(entry->choices.size()); + + for (auto& branch : entry->choices) + { + if (WIDGET_FX(ImGui::Button(branch.text.c_str(), buttonSize))) + set(dialogue.get(branch.nextID), character); + + ImGui::SetItemTooltip("%s", branch.text.c_str()); + ImGui::SameLine(); + } + + if (isHovered && isSpace) + { + set(dialogue.get(entry->choices.front().nextID), character); + menuSchema.sounds.select.play(); + } + } + else + { + if (entry->nextID != -1) + { + ImGui::SetCursorPos(ImVec2(available.x - ImGui::GetTextLineHeightWithSpacing(), available.y)); + auto indicatorSize = ImVec2(ImGui::GetTextLineHeightWithSpacing(), ImGui::GetTextLineHeightWithSpacing()); + auto cursorPos = ImGui::GetCursorScreenPos(); + auto center = ImVec2(cursorPos.x + (indicatorSize.x * 0.5f), cursorPos.y + (indicatorSize.y * 0.5f)); + auto half = std::min(indicatorSize.x, indicatorSize.y) * 0.35f; + auto tip = ImVec2(center.x + half, center.y); + auto baseA = ImVec2(center.x - half, center.y - half); + auto baseB = ImVec2(center.x - half, center.y + half); + auto color = ImGui::GetColorU32(ImGuiCol_Text); + ImGui::GetWindowDrawList()->AddTriangleFilled(tip, baseA, baseB, color); + ImGui::Dummy(indicatorSize); + + if (isAdvance) + { + menuSchema.sounds.select.play(); + set(dialogue.get(entry->nextID), character); + } + } + else if (isAdvance) + { + isEnabled = false; + entry = nullptr; + } + } + } + else + { + if (isAdvance) + { + index = ImTextCountCharsFromUtf8(entry->text.c_str(), entry->text.c_str() + entry->text.size()); + isFinished = true; + character.isTalking = false; + } + } + } + + ImGui::PopFont(); + ImGui::PopStyleVar(); + }; + ImGui::End(); + + if (isEnabled && isFinished && entry && entry->is_last()) + { + if (time += ImGui::GetIO().DeltaTime; time > LIFETIME) + { + isEnabled = false; + entry = nullptr; + } + } + } + + bool Text::is_interruptible() const { return !entry || (entry && entry->is_last()); } +} diff --git a/src/state/main/text.hpp b/src/state/main/text.hpp new file mode 100644 index 0000000..6155560 --- /dev/null +++ b/src/state/main/text.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include "../../entity/character.hpp" + +#include "../../resources.hpp" + +namespace game::state::main +{ + class Text + { + int index{}; + bool isFinished{}; + + public: + static constexpr auto LIFETIME = 10.0f; + + resource::xml::Dialogue::Entry* entry{}; + + bool isEnabled{true}; + float time{}; + + void set(resource::xml::Dialogue::Entry*, entity::Character&); + void tick(entity::Character&); + void update(entity::Character&); + bool is_interruptible() const; + }; +} \ No newline at end of file diff --git a/src/state/main/toasts.cpp b/src/state/main/toasts.cpp new file mode 100644 index 0000000..fc687ae --- /dev/null +++ b/src/state/main/toasts.cpp @@ -0,0 +1,68 @@ +#include "toasts.hpp" + +#include +#include + +namespace game::state::main +{ + void Toasts::tick() + { + for (int i = 0; i < (int)items.size(); i++) + { + auto& item = items[i]; + + item.lifetime--; + + if (item.lifetime <= 0) + { + items.erase(items.begin() + i--); + continue; + } + } + } + + void Toasts::update() + { + if (items.empty()) return; + + auto viewport = ImGui::GetMainViewport(); + auto& style = ImGui::GetStyle(); + + auto windowBgColor = ImGui::GetStyleColorVec4(ImGuiCol_WindowBg); + auto borderColor = ImGui::GetStyleColorVec4(ImGuiCol_Border); + auto textColor = ImGui::GetStyleColorVec4(ImGuiCol_Text); + + for (int i = 0; i < (int)items.size(); i++) + { + auto& item = items[i]; + auto posY = viewport->Size.y - style.WindowPadding.y - + (((ImGui::GetTextLineHeightWithSpacing() + style.WindowPadding.y * 2)) * (items.size() - i)); + + ImGui::SetNextWindowPos(ImVec2(style.WindowPadding.x, posY)); + + ImGui::SetNextWindowSize(ImVec2(ImGui::CalcTextSize(item.message.c_str()).x + (style.WindowPadding.x * 2), + ImGui::GetTextLineHeightWithSpacing())); + + auto alpha = (float)item.lifetime / Item::LIFETIME; + + windowBgColor.w = alpha; + borderColor.w = alpha; + textColor.w = alpha; + + ImGui::PushStyleColor(ImGuiCol_WindowBg, windowBgColor); + ImGui::PushStyleColor(ImGuiCol_Border, borderColor); + ImGui::PushStyleColor(ImGuiCol_Text, textColor); + + auto name = "##Toast " + std::to_string(i); + if (ImGui::Begin(name.c_str(), nullptr, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar)) + ImGui::TextUnformatted(item.message.c_str()); + ImGui::End(); + + ImGui::PopStyleColor(3); + } + } + + void Toasts::push(const std::string& message) { items.push_back({message, Item::LIFETIME}); } +} diff --git a/src/state/main/toasts.hpp b/src/state/main/toasts.hpp new file mode 100644 index 0000000..07a112a --- /dev/null +++ b/src/state/main/toasts.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +namespace game::state::main +{ + class Toasts + { + public: + struct Item + { + static constexpr auto LIFETIME = 30; + + std::string message{}; + int lifetime{}; + }; + + std::vector items{}; + + void update(); + void tick(); + void push(const std::string&); + }; +}; \ No newline at end of file diff --git a/src/state/main/tools.cpp b/src/state/main/tools.cpp new file mode 100644 index 0000000..6c01bb5 --- /dev/null +++ b/src/state/main/tools.cpp @@ -0,0 +1,129 @@ +#include "tools.hpp" + +#include "../../util/imgui.hpp" +#include "../../util/imgui/widget.hpp" + +#include + +using namespace game::util; +using namespace game::util::imgui; + +namespace game::state::main +{ + void Tools::update(entity::Character& character, entity::Cursor& cursor, World& world, World::Focus focus, + Canvas& canvas) + { + static constexpr auto WIDTH_MULTIPLIER = 0.05f; + + auto style = ImGui::GetStyle(); + auto& io = ImGui::GetIO(); + auto& schema = character.data.menuSchema; + + slide.update(isOpen, io.DeltaTime); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); + ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); + + auto windowSize = imgui::to_ivec2(ImGui::GetMainViewport()->Size); + + auto size = ImVec2(windowSize.x * WIDTH_MULTIPLIER, windowSize.y - style.WindowPadding.y * 2); + auto targetX = 0; + auto t = slide.value_get(); + auto eased = slide.eased_get(); + auto closedX = -size.x; + auto posX = closedX + (targetX - closedX) * eased; + auto pos = ImVec2(posX, style.WindowPadding.y); + auto barSize = ImVec2(ImGui::GetTextLineHeightWithSpacing(), windowSize.y - style.WindowPadding.y * 2); + auto barPos = ImVec2(pos.x + size.x, style.WindowPadding.y); + + if (slide.is_visible()) + { + ImGui::SetNextWindowSize(size); + ImGui::SetNextWindowPos(pos); + + if (ImGui::Begin("##Tools", nullptr, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + auto buttonSize = imgui::to_imvec2(vec2(ImGui::GetContentRegionAvail().x)); + + auto cursor_mode_button = [&](const char* name, InteractType mode) + { + auto isMode = cursor.mode == mode; + ImGui::PushStyleColor(ImGuiCol_Button, + ImGui::GetStyleColorVec4(isMode ? ImGuiCol_ButtonHovered : ImGuiCol_Button)); + if (WIDGET_FX(ImGui::Button(name, buttonSize))) cursor.mode = mode; + ImGui::PopStyleColor(); + }; + + if (WIDGET_FX(ImGui::Button("Home", buttonSize))) world.character_focus(character, canvas, focus); + ImGui::SetItemTooltip("%s", "Reset camera view.\n(Shortcut: Home)"); + + cursor_mode_button("Rub", InteractType::RUB); + cursor_mode_button("Kiss", InteractType::KISS); + cursor_mode_button("Smack", InteractType::SMACK); + } + ImGui::End(); + } + + ImGui::SetNextWindowSize(barSize); + ImGui::SetNextWindowPos(barPos); + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + if (ImGui::Begin("##Tools Open Bar", nullptr, + ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + auto buttonSize = ImGui::GetContentRegionAvail(); + auto cursorPos = ImGui::GetCursorScreenPos(); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + auto result = WIDGET_FX(ImGui::Button("##ToolsToggle", buttonSize)); + + if (t <= 0.0f || t >= 1.0f) + { + ImGui::SetItemTooltip(isOpen ? "Close Tools" : "Open Tools"); + if (result) + { + isOpen = !isOpen; + if (isOpen) + schema.sounds.open.play(); + else + schema.sounds.close.play(); + } + if (!isOpen && t <= 0.0f && ImGui::IsItemHovered()) + { + isOpen = true; + schema.sounds.open.play(); + } + } + ImGui::PopStyleVar(); + + auto center = ImVec2(cursorPos.x + (buttonSize.x * 0.5f), cursorPos.y + (buttonSize.y * 0.5f)); + auto half = std::min(buttonSize.x, buttonSize.y) * 0.22f; + ImVec2 tip; + ImVec2 baseA; + ImVec2 baseB; + if (isOpen) + { + tip = ImVec2(center.x - half, center.y); + baseA = ImVec2(center.x + half, center.y - half); + baseB = ImVec2(center.x + half, center.y + half); + } + else + { + tip = ImVec2(center.x + half, center.y); + baseA = ImVec2(center.x - half, center.y - half); + baseB = ImVec2(center.x - half, center.y + half); + } + + auto color = ImGui::GetColorU32(ImGuiCol_Text); + ImGui::GetWindowDrawList()->AddTriangleFilled(tip, baseA, baseB, color); + } + ImGui::End(); + ImGui::PopStyleVar(2); + + ImGui::PopStyleVar(2); + } +} diff --git a/src/state/main/tools.hpp b/src/state/main/tools.hpp new file mode 100644 index 0000000..308d67a --- /dev/null +++ b/src/state/main/tools.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include + +#include "../../util/imgui/window_slide.hpp" +#include "world.hpp" + +namespace game::state::main +{ + class Tools + { + public: + bool isOpen{}; + util::imgui::WindowSlide slide{0.125f, 0.0f}; + + void update(entity::Character&, entity::Cursor&, World&, World::Focus, Canvas&); + }; +} diff --git a/src/state/main/world.cpp b/src/state/main/world.cpp new file mode 100644 index 0000000..69620cb --- /dev/null +++ b/src/state/main/world.cpp @@ -0,0 +1,92 @@ +#include "world.hpp" + +#include "../../util/imgui.hpp" +#include "../../util/math.hpp" + +#include +#include + +using namespace game::util; + +namespace game::state::main +{ + void World::set(entity::Character& character, Canvas& canvas, Focus focus) + { + character.stage = character.stage_get(); + character.queue_idle_animation(); + character_focus(character, canvas, focus); + } + + void World::update(entity::Character& character, entity::Cursor& cursor, Canvas& canvas, Focus focus) + { + auto& cursorSchema = character.data.cursorSchema; + auto& pan = canvas.pan; + auto& zoom = canvas.zoom; + auto& io = ImGui::GetIO(); + bool isPan{true}; + auto isMouseMiddleDown = ImGui::IsMouseDown(ImGuiMouseButton_Middle); + auto panMultiplier = ZOOM_BASE / zoom; + + if (!ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) && !ImGui::IsAnyItemActive()) + { + if ((isMouseMiddleDown) && isPan) + { + cursor.queue_play({cursorSchema.animations.pan.get()}); + pan -= imgui::to_vec2(io.MouseDelta) * panMultiplier; + } + + if (io.MouseWheel != 0) + { + auto viewport = ImGui::GetMainViewport(); + auto mousePos = io.MousePos; + auto cursorPos = imgui::to_vec2(ImVec2(mousePos.x - viewport->Pos.x, mousePos.y - viewport->Pos.y)); + auto zoomBefore = zoom; + auto zoomFactorBefore = math::to_unit(zoomBefore); + auto cursorWorld = pan + (cursorPos / zoomFactorBefore); + + cursor.queue_play({cursorSchema.animations.zoom.get()}); + + zoom = glm::clamp(ZOOM_MIN, zoom + (io.MouseWheel * ZOOM_STEP), ZOOM_MAX); + + auto zoomFactorAfter = math::to_unit(zoom); + pan = cursorWorld - (cursorPos / zoomFactorAfter); + } + } + + zoom = glm::clamp(ZOOM_MIN, zoom, ZOOM_MAX); + + if (ImGui::IsKeyPressed(ImGuiKey_Home)) character_focus(character, canvas, focus); + } + + void World::character_focus(entity::Character& character, Canvas& canvas, Focus focus) + { + static constexpr float MENU_WIDTH_MULTIPLIER = 0.30f; + static constexpr float TOOLS_WIDTH_MULTIPLIER = 0.10f; + static constexpr float PADDING = 100.0f; + + auto rect = character.rect(); + + if (!std::isfinite(rect.x) || !std::isfinite(rect.y) || !std::isfinite(rect.z) || !std::isfinite(rect.w) || + rect.z <= 0.0f || rect.w <= 0.0f) + return; + + rect = {rect.x - PADDING * 0.5f, rect.y - PADDING * 0.5f, rect.z + PADDING, rect.w + PADDING}; + + auto zoomFactor = std::min((float)canvas.size.x / rect.z, (float)canvas.size.y / rect.w); + canvas.zoom = glm::clamp(ZOOM_MIN, math::to_percent(zoomFactor), ZOOM_MAX); + zoomFactor = math::to_unit(canvas.zoom); + + auto rectCenter = glm::vec2(rect.x + rect.z * 0.5f, rect.y + rect.w * 0.5f); + auto viewSizeWorld = glm::vec2(canvas.size) / zoomFactor; + canvas.pan = rectCenter - (vec2(viewSizeWorld.x, viewSizeWorld.y) * 0.5f); + auto menuWidthWorld = (canvas.size.x * MENU_WIDTH_MULTIPLIER) / zoomFactor; + auto toolsWidthWorld = (canvas.size.x * TOOLS_WIDTH_MULTIPLIER) / zoomFactor; + + if (focus == Focus::MENU || focus == Focus::MENU_TOOLS) canvas.pan.x += menuWidthWorld * 0.5f; + if (focus == Focus::TOOLS || focus == Focus::MENU_TOOLS) canvas.pan.x -= toolsWidthWorld * 0.5f; + + auto panMin = glm::vec2(0.0f, 0.0f); + auto panMax = glm::max(glm::vec2(0.0f), SIZE - viewSizeWorld); + canvas.pan = glm::clamp(panMin, canvas.pan, panMax); + } +} diff --git a/src/state/main/world.hpp b/src/state/main/world.hpp new file mode 100644 index 0000000..f958306 --- /dev/null +++ b/src/state/main/world.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include "../../canvas.hpp" +#include "../../entity/character.hpp" + +#include "character_manager.hpp" +#include "item_manager.hpp" + +namespace game::state::main +{ + class World + { + public: + static constexpr auto ZOOM_MIN = 50.0f; + static constexpr auto ZOOM_BASE = 100.0f; + static constexpr auto ZOOM_STEP = 25.0f; + static constexpr auto ZOOM_MAX = 400.0f; + static constexpr auto SIZE = glm::vec2{1920, 1080}; + static constexpr auto BOUNDS = + glm::vec4(SIZE.x * 0.05, SIZE.y * 0.05, SIZE.x - (SIZE.x * 0.05f), SIZE.y - (SIZE.y * 0.05f)); + + enum Focus + { + CENTER, + MENU, + MENU_TOOLS, + TOOLS + }; + + void update(entity::Character& character, entity::Cursor& cursor, Canvas& canvas, Focus = CENTER); + void character_focus(entity::Character& character, Canvas& canvas, Focus = CENTER); + void set(entity::Character& character, Canvas& canvas, Focus = CENTER); + glm::vec2 screen_to_world(glm::vec2 screenPosition, const Canvas& canvas) const; + }; +} diff --git a/src/state/select.cpp b/src/state/select.cpp new file mode 100644 index 0000000..55c38c3 --- /dev/null +++ b/src/state/select.cpp @@ -0,0 +1,25 @@ +#include "select.hpp" + +#include + +using namespace game::util; + +namespace game::state +{ + void Select::tick() { preview.tick(characterIndex); } + + void Select::update(Resources& resources) + { + preview.update(resources, characterIndex); + info.update(resources, characterIndex); + characters.update(resources, characterIndex); + } + + void Select::render(Resources& resources, Canvas& canvas) + { + canvas.bind(); + ImGui::Render(); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + canvas.unbind(); + } +}; diff --git a/src/state/select.hpp b/src/state/select.hpp new file mode 100644 index 0000000..066f83d --- /dev/null +++ b/src/state/select.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "../canvas.hpp" + +#include "select/characters.hpp" +#include "select/info.hpp" +#include "select/preview.hpp" + +namespace game::state +{ + class Select + { + public: + select::Characters characters{}; + select::Info info{}; + select::Preview preview{}; + + int characterIndex{-1}; + + void tick(); + void update(Resources&); + void render(Resources&, Canvas&); + }; +}; \ No newline at end of file diff --git a/src/state/select/characters.cpp b/src/state/select/characters.cpp new file mode 100644 index 0000000..d7ac6c2 --- /dev/null +++ b/src/state/select/characters.cpp @@ -0,0 +1,81 @@ +#include "characters.hpp" + +#include + +#include "../../util/imgui/widget.hpp" + +using namespace game::util::imgui; + +namespace game::state::select +{ + void Characters::update(Resources& resources, int& characterIndex) + { + auto& style = ImGui::GetStyle(); + auto viewport = ImGui::GetMainViewport(); + + auto size = + ImVec2(viewport->Size.x / 2.0f - style.WindowPadding.x, viewport->Size.y - (style.WindowPadding.y * 2.0f)); + auto pos = ImVec2(viewport->Size.x / 2.0f, style.WindowPadding.y); + + ImGui::SetNextWindowSize(size); + ImGui::SetNextWindowPos(pos); + + if (ImGui::Begin("##Main Menu", nullptr, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoTitleBar)) + { + if (ImGui::BeginTabBar("##Main Menu Bar")) + { + if (WIDGET_FX(ImGui::BeginTabItem("Characters"))) + { + auto cursorPos = ImGui::GetCursorPos(); + auto cursorStartX = ImGui::GetCursorPosX(); + + auto buttonSize = ImVec2(ImGui::GetContentRegionAvail().x / 4, ImGui::GetContentRegionAvail().x / 4); + + for (int i = 0; i < (int)resources.characterPreviews.size(); i++) + { + auto& character = resources.characterPreviews[i]; + ImGui::PushID(i); + + ImGui::SetCursorPos(cursorPos); + + auto isSelected = i == characterIndex; + + if (isSelected) ImGui::PushStyleColor(ImGuiCol_FrameBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBgHovered)); + + if (character.portrait.is_valid()) + { + if (WIDGET_FX(ImGui::ImageButton(character.name.c_str(), character.portrait.id, buttonSize))) + characterIndex = i; + } + else if (WIDGET_FX(ImGui::Button(character.name.c_str(), buttonSize))) + characterIndex = i; + if (isSelected) ImGui::PopStyleColor(); + ImGui::SetItemTooltip("%s", character.name.c_str()); + + auto increment = ImGui::GetItemRectSize().x + ImGui::GetStyle().ItemSpacing.x; + cursorPos.x += increment; + + if (cursorPos.x + increment > ImGui::GetContentRegionAvail().x) + { + cursorPos.x = cursorStartX; + cursorPos.y += increment; + } + + ImGui::PopID(); + } + ImGui::EndTabItem(); + } + + if (WIDGET_FX(ImGui::BeginTabItem("Configuration"))) + { + configuration.update(resources); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::End(); + } + } +} diff --git a/src/state/select/characters.hpp b/src/state/select/characters.hpp new file mode 100644 index 0000000..38b3e06 --- /dev/null +++ b/src/state/select/characters.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include "../../resources.hpp" +#include "../configuration.hpp" + +namespace game::state::select +{ + class Characters + { + public: + Configuration configuration; + + void update(Resources&, int& characterIndex); + }; +} \ No newline at end of file diff --git a/src/state/select/info.cpp b/src/state/select/info.cpp new file mode 100644 index 0000000..5ee8136 --- /dev/null +++ b/src/state/select/info.cpp @@ -0,0 +1,127 @@ +#include "info.hpp" + +#include "../../util/color.hpp" +#include "../../util/imgui.hpp" +#include "../../util/imgui/widget.hpp" +#include "../../util/vector.hpp" + +using namespace game::util; +using namespace game::util::imgui; +using namespace game::util::measurement; +using namespace game::resource; + +namespace game::state::select +{ + void Info::update(Resources& resources, int characterIndex) + { + if (!vector::in_bounds(resources.characterPreviews, characterIndex)) return; + + auto& style = ImGui::GetStyle(); + auto viewport = ImGui::GetMainViewport(); + + auto size = ImVec2(viewport->Size.x / 2.0f - (style.WindowPadding.x * 2.0f), + (viewport->Size.y / 2.0f) - (style.WindowPadding.y * 2.0f)); + auto pos = ImVec2(style.WindowPadding.x, (viewport->Size.y / 2.0f) + style.WindowPadding.y); + + ImGui::SetNextWindowSize(size); + ImGui::SetNextWindowPos(pos); + + if (ImGui::Begin("##Info", nullptr, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoTitleBar)) + { + auto& character = resources.characterPreviews[characterIndex]; + auto& save = character.save; + auto& system = resources.settings.measurementSystem; + auto& weight = save.is_valid() ? save.weight : character.weight; + + ImGui::PushFont(ImGui::GetFont(), Font::HEADER_3); + + auto childSize = imgui::size_without_footer_get(); + + if (ImGui::BeginChild("##Info Child", childSize)) + { + ImGui::PushFont(ImGui::GetFont(), Font::HEADER_3); + ImGui::TextUnformatted(character.name.c_str()); + ImGui::PopFont(); + + if (!character.description.empty()) + { + ImGui::Separator(); + + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(imgui::to_imvec4(color::GRAY))); + ImGui::PushFont(ImGui::GetFont(), Font::BIG); + ImGui::TextWrapped("%s", character.description.c_str()); + ImGui::PopFont(); + + ImGui::PopStyleColor(); + } + + ImGui::Separator(); + + ImGui::PushFont(ImGui::GetFont(), Font::BIG); + + ImGui::Text("Weight: %0.2f %s", system == IMPERIAL ? weight * KG_TO_LB : weight, + system == IMPERIAL ? "lbs" : "kg"); + ImGui::Text("Stages: %i", character.stages); + + ImGui::Separator(); + + ImGui::PopFont(); + + ImGui::PushFont(ImGui::GetFont(), Font::NORMAL); + + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(imgui::to_imvec4(color::GRAY))); + + if (!character.author.empty()) ImGui::TextWrapped("Author: %s", character.author.c_str()); + + ImGui::PopStyleColor(); + + ImGui::PopFont(); + } + ImGui::EndChild(); + + auto widgetSize = row_widget_size_get(save.is_valid() ? 2 : 1); + + if (save.is_valid()) + { + if (WIDGET_FX(ImGui::Button("Continue", widgetSize))) isContinue = true; + ImGui::PushFont(ImGui::GetFont(), Font::NORMAL); + ImGui::SetItemTooltip("%s", "Continue from a saved game."); + ImGui::PopFont(); + ImGui::SameLine(); + } + + if (WIDGET_FX(ImGui::Button("New Game", widgetSize))) + { + if (save.is_valid()) + { + ImGui::OpenPopup("New Game Warning"); + isNewGameWarning = true; + } + else + isNewGame = true; + } + ImGui::PushFont(ImGui::GetFont(), Font::NORMAL); + ImGui::SetItemTooltip("%s", "Start a new game.\nThis will delete progress!"); + ImGui::PopFont(); + + ImGui::PopFont(); + + ImGui::SetNextWindowSize(ImVec2(viewport->Size.x * 0.5f, 0), ImGuiCond_Always); + ImGui::SetNextWindowPos(ImVec2(viewport->GetCenter()), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + + if (ImGui::BeginPopupModal("New Game Warning", &isNewGameWarning, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize)) + { + auto widgetSize = row_widget_size_get(save.is_valid() ? 2 : 1); + ImGui::TextWrapped("This will delete saved progress! Are you sure?"); + if (WIDGET_FX(ImGui::Button("Yes", widgetSize))) isNewGame = true; + ImGui::SameLine(); + if (WIDGET_FX(ImGui::Button("No", widgetSize))) isNewGameWarning = false; + ImGui::EndPopup(); + } + } + ImGui::End(); + } +} diff --git a/src/state/select/info.hpp b/src/state/select/info.hpp new file mode 100644 index 0000000..36cc4c8 --- /dev/null +++ b/src/state/select/info.hpp @@ -0,0 +1,16 @@ +#pragma once + +#include "../../resources.hpp" + +namespace game::state::select +{ + class Info + { + public: + bool isContinue{}; + bool isNewGame{}; + bool isNewGameWarning{}; + + void update(Resources&, int characterIndex); + }; +} \ No newline at end of file diff --git a/src/state/select/preview.cpp b/src/state/select/preview.cpp new file mode 100644 index 0000000..d251182 --- /dev/null +++ b/src/state/select/preview.cpp @@ -0,0 +1,110 @@ +#include "preview.hpp" + +#include +#include + +#include "../../util/imgui.hpp" +#include "../../util/imgui/widget.hpp" +#include "../../util/vector.hpp" + +using namespace game::entity; +using namespace game::resource; +using namespace game::util; +using namespace game::util::imgui; + +namespace game::state::select +{ + void Preview::tick(int characterIndex) + { + if (characterIndex != -1 && isInGame) actor.tick(); + } + + void Preview::update(Resources& resources, int characterIndex) + { + if (!vector::in_bounds(resources.characterPreviews, characterIndex)) return; + + auto& style = ImGui::GetStyle(); + auto viewport = ImGui::GetMainViewport(); + + auto size = ImVec2(viewport->Size.x / 2.0f - (style.WindowPadding.x * 2.0f), + (viewport->Size.y / 2.0f) - (style.WindowPadding.y * 2.0f)); + auto pos = ImVec2(style.WindowPadding.x, style.WindowPadding.y); + + ImGui::SetNextWindowSize(size); + ImGui::SetNextWindowPos(pos); + + if (ImGui::Begin("##Preview", nullptr, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | + ImGuiWindowFlags_NoTitleBar)) + { + if (ImGui::BeginTabBar("##Preview Tab Bar")) + { + auto& character = resources.characterPreviews[characterIndex]; + + auto available = ImGui::GetContentRegionAvail(); + auto availableSize = imgui::to_vec2(available); + auto textureSize = vec2(character.render.size); + + if (WIDGET_FX(ImGui::BeginTabItem("Render"))) + { + auto scale = + (availableSize.x <= 0.0f || availableSize.y <= 0.0f || textureSize.x <= 0.0f || textureSize.y <= 0.0f) + ? 0.0f + : std::min(availableSize.x / textureSize.x, availableSize.y / textureSize.y); + + auto size = ImVec2(textureSize.x * scale, textureSize.y * scale); + + ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + (availableSize.x * 0.5f) - (size.y * 0.5f), + ImGui::GetCursorPosY() + (availableSize.y * 0.5f) - (size.y * 0.5f))); + + ImGui::Image(character.render.id, size); + + ImGui::EndTabItem(); + } + + if (WIDGET_FX(ImGui::BeginTabItem("In Game"))) + { + isInGame = true; + + if (previousCharacterIndex != characterIndex) + { + actor = Actor(resources.characterPreviews[characterIndex].anm2); + rect = actor.rect(); + previousCharacterIndex = characterIndex; + } + + auto rectSize = vec2(rect.z, rect.w); + auto previewScale = (availableSize.x <= 0.0f || availableSize.y <= 0.0f || rectSize.x <= 0.0f || + rectSize.y <= 0.0f || !std::isfinite(rectSize.x) || !std::isfinite(rectSize.y)) + ? 0.0f + : std::min(availableSize.x / rectSize.x, availableSize.y / rectSize.y); + + auto previewSize = rectSize * previewScale; + auto canvasSize = ivec2(std::max(1.0f, previewSize.x), std::max(1.0f, previewSize.y)); + + canvas.zoom = previewScale * 100.0f; + canvas.pan = vec2(rect.x, rect.y); + + auto cursorPos = ImGui::GetCursorPos(); + ImGui::SetCursorPos(ImVec2(cursorPos.x + (availableSize.x * 0.5f) - ((float)canvasSize.x * 0.5f), + cursorPos.y + (availableSize.y * 0.5f) - ((float)canvasSize.y * 0.5f))); + + canvas.bind(); + canvas.size_set(canvasSize); + canvas.clear(); + actor.render(resources.shaders[shader::TEXTURE], resources.shaders[shader::RECT], canvas); + canvas.unbind(); + + ImGui::Image(canvas.texture, imgui::to_imvec2(canvasSize)); + + ImGui::EndTabItem(); + } + else + isInGame = false; + + ImGui::EndTabBar(); + } + } + ImGui::End(); + } +} diff --git a/src/state/select/preview.hpp b/src/state/select/preview.hpp new file mode 100644 index 0000000..1d2c8cd --- /dev/null +++ b/src/state/select/preview.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include "../../entity/actor.hpp" +#include "../../resources.hpp" + +namespace game::state::select +{ + class Preview + { + public: + int previousCharacterIndex{-1}; + entity::Actor actor{}; + glm::vec4 rect{}; + bool isInGame{}; + + Canvas canvas{glm::vec2(), Canvas::FLIP}; + + void update(Resources& resources, int characterIndex); + void tick(int characterIndex); + }; +} diff --git a/src/types.hpp b/src/types.hpp deleted file mode 100644 index e92f118..0000000 --- a/src/types.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "glm/ext/vector_float4.hpp" - -namespace game -{ - enum MeasurementSystem - { - METRIC, - IMPERIAL - }; - - constexpr auto KG_TO_LB = 2.20462; - constexpr auto WHITE = glm::vec4(); - constexpr auto GRAY = glm::vec4(0.5f, 0.5f, 0.5f, 1.0f); -} diff --git a/src/util/color.hpp b/src/util/color.hpp new file mode 100644 index 0000000..d87aa7d --- /dev/null +++ b/src/util/color.hpp @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace game::util::color +{ + constexpr auto WHITE = glm::vec4(1.0f); + constexpr auto GRAY = glm::vec4(0.5f, 0.5f, 0.5f, 1.0f); +} \ No newline at end of file diff --git a/src/util/imgui.cpp b/src/util/imgui.cpp new file mode 100644 index 0000000..8364a5d --- /dev/null +++ b/src/util/imgui.cpp @@ -0,0 +1,27 @@ +#include "imgui.hpp" + +namespace game::util::imgui +{ + float row_widget_width_get(int count, float width) + { + return (width - (ImGui::GetStyle().ItemSpacing.x * (float)(count - 1))) / (float)count; + } + + ImVec2 row_widget_size_get(int count, float width) { return ImVec2(row_widget_width_get(count, width), 0); } + + float footer_height_get(int itemCount) + { + return ImGui::GetTextLineHeightWithSpacing() * itemCount + ImGui::GetStyle().WindowPadding.y + + ImGui::GetStyle().ItemSpacing.y * (itemCount); + } + + ImVec2 footer_size_get(int itemCount) + { + return ImVec2(ImGui::GetContentRegionAvail().x, footer_height_get(itemCount)); + } + + ImVec2 size_without_footer_get(int rowCount) + { + return ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - footer_height_get(rowCount)); + } +} diff --git a/src/util/imgui_.hpp b/src/util/imgui.hpp similarity index 50% rename from src/util/imgui_.hpp rename to src/util/imgui.hpp index b79594f..62aa90d 100644 --- a/src/util/imgui_.hpp +++ b/src/util/imgui.hpp @@ -8,12 +8,18 @@ using namespace glm; namespace game::util::imgui { - float widget_width_with_row_get(int = 1, float = ImGui::GetContentRegionAvail().x); - ImVec2 widget_size_with_row_get(int = 1, float = ImGui::GetContentRegionAvail().x); + float row_widget_width_get(int = 1, float = ImGui::GetContentRegionAvail().x); + ImVec2 row_widget_size_get(int = 1, float = ImGui::GetContentRegionAvail().x); + + float footer_height_get(int = 1); + ImVec2 footer_size_get(int = 1); + ImVec2 size_without_footer_get(int = 1); inline ImVec2 to_imvec2(vec2 value) { return ImVec2(value.x, value.y); } + inline ImVec2 to_imvec2(ivec2 value) { return ImVec2(value.x, value.y); } inline vec2 to_vec2(ImVec2 value) { return vec2(value.x, value.y); } + inline ivec2 to_ivec2(ImVec2 value) { return ivec2(value.x, value.y); } inline ImVec4 to_imvec4(vec4 value) { return ImVec4(value.r, value.g, value.b, value.a); } inline vec4 to_vec4(ImVec4 value) { return vec4(value.x, value.y, value.z, value.w); } -} \ No newline at end of file +} diff --git a/src/util/imgui/input_int_ex.cpp b/src/util/imgui/input_int_ex.cpp new file mode 100644 index 0000000..bf7ecb3 --- /dev/null +++ b/src/util/imgui/input_int_ex.cpp @@ -0,0 +1,23 @@ +#include "input_int_ex.hpp" + +#include + +namespace game::util::imgui +{ + bool input_int_range(const char* label, int* value, int min, int max, int step, int stepFast, + ImGuiInputTextFlags flags) + { + auto isChanged = ImGui::InputInt(label, value, step, stepFast, flags); + + auto minMax = std::minmax(min, max); + auto clamped = std::clamp(*value, minMax.first, minMax.second); + + if (clamped != *value) + { + *value = clamped; + isChanged = true; + } + + return isChanged; + } +} diff --git a/src/util/imgui/input_int_ex.hpp b/src/util/imgui/input_int_ex.hpp new file mode 100644 index 0000000..c79f50c --- /dev/null +++ b/src/util/imgui/input_int_ex.hpp @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace game::util::imgui +{ + bool input_int_range(const char* label, int* value, int min, int max, int step = 1, int stepFast = 100, + ImGuiInputTextFlags flags = 0); +} diff --git a/src/util/imgui/style.cpp b/src/util/imgui/style.cpp new file mode 100644 index 0000000..2a90f41 --- /dev/null +++ b/src/util/imgui/style.cpp @@ -0,0 +1,67 @@ +#include "style.hpp" + +#include "../imgui.hpp" + +namespace game::util::imgui::style +{ + void rounding_set(float rounding) + { + auto& style = ImGui::GetStyle(); + style.WindowRounding = rounding; + style.FrameRounding = rounding; + style.GrabRounding = rounding; + } + + void color_set(glm::vec3 color) + { + static constexpr auto COLOR_BG_MULTIPLIER = 0.25f; + static constexpr auto COLOR_BG_ALPHA = 0.90f; + static constexpr auto COLOR_ACTIVE_MULTIPLIER = 1.30f; + static constexpr auto COLOR_HOVERED_MULTIPLIER = 1.60f; + static constexpr auto COLOR_ACCENT_MULTIPLIER = 2.0f; + static constexpr auto COLOR_ACCENT_ACTIVE_MULTIPLIER = 2.25f; + + auto& colors = ImGui::GetStyle().Colors; + + auto colorNew = to_imvec4(glm::vec4(color, 1.0f)); + auto colorBg = to_imvec4(glm::vec4(color * COLOR_BG_MULTIPLIER, COLOR_BG_ALPHA)); + auto colorChildBg = to_imvec4(glm::vec4(color * COLOR_BG_MULTIPLIER, 0.0f)); + auto colorActive = to_imvec4(glm::vec4(color * COLOR_ACTIVE_MULTIPLIER, 1.0f)); + auto colorHovered = to_imvec4(glm::vec4(color * COLOR_HOVERED_MULTIPLIER, 1.0f)); + auto colorAccent = to_imvec4(glm::vec4(color * COLOR_ACCENT_MULTIPLIER, 1.0f)); + auto colorAccentActive = to_imvec4(glm::vec4(color * COLOR_ACCENT_ACTIVE_MULTIPLIER, 1.0f)); + + colors[ImGuiCol_Button] = colorNew; + colors[ImGuiCol_FrameBg] = colorNew; + colors[ImGuiCol_FrameBgHovered] = colorHovered; + colors[ImGuiCol_FrameBgActive] = colorActive; + colors[ImGuiCol_Header] = colorNew; + colors[ImGuiCol_HeaderHovered] = colorHovered; + colors[ImGuiCol_HeaderActive] = colorActive; + colors[ImGuiCol_Tab] = colorNew; + colors[ImGuiCol_TitleBg] = colorNew; + colors[ImGuiCol_TitleBgCollapsed] = colorNew; + colors[ImGuiCol_TitleBgActive] = colorNew; + colors[ImGuiCol_WindowBg] = colorBg; + colors[ImGuiCol_ChildBg] = colorChildBg; + colors[ImGuiCol_PopupBg] = colorBg; + + colors[ImGuiCol_ScrollbarBg] = colorNew; + colors[ImGuiCol_ScrollbarGrab] = colorHovered; + colors[ImGuiCol_ScrollbarGrabHovered] = colorHovered; + colors[ImGuiCol_ScrollbarGrabActive] = colorAccent; + + colors[ImGuiCol_ButtonHovered] = colorHovered; + colors[ImGuiCol_FrameBgHovered] = colorHovered; + colors[ImGuiCol_TabHovered] = colorHovered; + + colors[ImGuiCol_ButtonActive] = colorActive; + colors[ImGuiCol_FrameBgActive] = colorActive; + colors[ImGuiCol_TabActive] = colorActive; + + colors[ImGuiCol_PlotHistogram] = colorAccent; + colors[ImGuiCol_CheckMark] = colorAccent; + colors[ImGuiCol_SliderGrab] = colorAccent; + colors[ImGuiCol_SliderGrabActive] = colorAccentActive; + } +} diff --git a/src/util/imgui/style.hpp b/src/util/imgui/style.hpp new file mode 100644 index 0000000..5822716 --- /dev/null +++ b/src/util/imgui/style.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include +#include + +namespace game::util::imgui::style +{ + void rounding_set(float rounding = 10.0f); + void color_set(glm::vec3 color); +} \ No newline at end of file diff --git a/src/util/imgui/widget.cpp b/src/util/imgui/widget.cpp new file mode 100644 index 0000000..172fadd --- /dev/null +++ b/src/util/imgui/widget.cpp @@ -0,0 +1,61 @@ +#include "widget.hpp" + +#include + +using game::resource::xml::SoundEntryCollection; + +namespace game::util::imgui::widget +{ + static SoundEntryCollection* hover{}; + static SoundEntryCollection* select{}; + + void sounds_set(SoundEntryCollection* _hover, SoundEntryCollection* _select) + { + hover = _hover; + select = _select; + } + + void fx() + { + static constexpr auto FREQUENCY = 10.0f; + static constexpr auto ALPHA_MIN = 1.0f; + static constexpr auto ALPHA_MAX = 1.0f; + static constexpr auto THICKNESS_MIN = 2.0f; + static constexpr auto THICKNESS_MAX = 3.0f; + + if (ImGui::IsItemActivated()) + if (select && !select->empty()) select->play(); + + if (ImGui::IsItemHovered()) + { + auto storage = ImGui::GetStateStorage(); + auto id = ImGui::GetItemID(); + if (id == 0) return; + bool wasHovered = storage->GetBool(id, false); + + if (!wasHovered) + { + if (hover && !hover->empty()) hover->play(); + storage->SetBool(id, true); + } + + auto& style = ImGui::GetStyle(); + auto min = ImGui::GetItemRectMin(); + auto max = ImGui::GetItemRectMax(); + auto time = ImGui::GetTime(); + auto period = sinf(time * FREQUENCY); + auto thickness = THICKNESS_MIN + (THICKNESS_MAX * period); + auto colorBorder = ImGui::GetStyleColorVec4(ImGuiCol_CheckMark); + colorBorder.w = ALPHA_MIN + (ALPHA_MAX * period); + + ImGui::GetWindowDrawList()->AddRect(min, max, ImGui::GetColorU32(colorBorder), style.FrameRounding, 0, thickness); + } + else + { + auto storage = ImGui::GetStateStorage(); + auto id = ImGui::GetItemID(); + if (id == 0) return; + storage->SetBool(id, false); + } + } +} diff --git a/src/util/imgui/widget.hpp b/src/util/imgui/widget.hpp new file mode 100644 index 0000000..8359ee4 --- /dev/null +++ b/src/util/imgui/widget.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include "../../resource/xml/sound_entry.hpp" +#include + +namespace game::util::imgui::widget +{ + void sounds_set(resource::xml::SoundEntryCollection* _hover, resource::xml::SoundEntryCollection* _select); + void fx(); +} + +#define WIDGET_FX_LAST_ITEM() ::game::util::imgui::widget::fx() +#define WIDGET_FX(expr) \ + ( \ + [&]() \ + { \ + const auto _widget_result = (expr); \ + WIDGET_FX_LAST_ITEM(); \ + return _widget_result; \ + }()) diff --git a/src/util/imgui/window_slide.cpp b/src/util/imgui/window_slide.cpp new file mode 100644 index 0000000..4c07b89 --- /dev/null +++ b/src/util/imgui/window_slide.cpp @@ -0,0 +1,30 @@ +#include "window_slide.hpp" + +#include +#include + +namespace game::util::imgui +{ + WindowSlide::WindowSlide(float duration, float initial) : value_(initial), duration_(duration) {} + + void WindowSlide::update(bool isOpen, float deltaTime) + { + auto target = isOpen ? 1.0f : 0.0f; + if (duration_ <= 0.0f) + { + value_ = target; + return; + } + + auto step = deltaTime / duration_; + if (value_ < target) value_ = std::min(target, value_ + step); + if (value_ > target) value_ = std::max(target, value_ - step); + value_ = std::clamp(value_, 0.0f, 1.0f); + } + + float WindowSlide::value_get() const { return value_; } + + float WindowSlide::eased_get(float power) const { return std::pow(value_, power); } + + bool WindowSlide::is_visible() const { return value_ > 0.0f; } +} diff --git a/src/util/imgui/window_slide.hpp b/src/util/imgui/window_slide.hpp new file mode 100644 index 0000000..62becbf --- /dev/null +++ b/src/util/imgui/window_slide.hpp @@ -0,0 +1,19 @@ +#pragma once + +namespace game::util::imgui +{ + class WindowSlide + { + public: + explicit WindowSlide(float duration = 0.125f, float initial = 1.0f); + + void update(bool isOpen, float deltaTime); + float value_get() const; + float eased_get(float power = 2.0f) const; + bool is_visible() const; + + private: + float value_{1.0f}; + float duration_{0.125f}; + }; +} diff --git a/src/util/imgui_.cpp b/src/util/imgui_.cpp deleted file mode 100644 index 4cc7abc..0000000 --- a/src/util/imgui_.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "imgui_.h" - -namespace game::util::imgui -{ - float row_widget_width_get(int count, float width) - { - return (width - (ImGui::GetStyle().ItemSpacing.x * (float)(count - 1))) / (float)count; - } - - ImVec2 widget_size_with_row_get(int count, float width) { return ImVec2(row_widget_width_get(count, width), 0); } -} diff --git a/src/util/interact_type.hpp b/src/util/interact_type.hpp new file mode 100644 index 0000000..a44bace --- /dev/null +++ b/src/util/interact_type.hpp @@ -0,0 +1,24 @@ +#pragma once + +namespace game +{ +#define LIST \ + X(RUB, "Rub") \ + X(KISS, "Kiss") \ + X(SMACK, "Smack") + + enum InteractType + { +#define X(symbol, string) symbol, + LIST +#undef X + }; + + static constexpr const char* INTERACT_TYPE_STRINGS[] = { +#define X(symbol, string) string, + LIST +#undef X + }; + +#undef LIST +} \ No newline at end of file diff --git a/src/util/map_.hpp b/src/util/map.hpp similarity index 100% rename from src/util/map_.hpp rename to src/util/map.hpp diff --git a/src/util/math_.cpp b/src/util/math.cpp similarity index 67% rename from src/util/math_.cpp rename to src/util/math.cpp index 7a33640..21db904 100644 --- a/src/util/math_.cpp +++ b/src/util/math.cpp @@ -1,4 +1,4 @@ -#include "math_.h" +#include "math.hpp" #include "SDL3/SDL_rect.h" #include "glm/ext/matrix_transform.hpp" #include @@ -7,25 +7,7 @@ using namespace glm; namespace game::util::math { - mat4 quad_model_get(vec2 size, vec2 position, vec2 pivot, vec2 scale, float rotation) - { - vec2 scaleAbsolute = glm::abs(scale); - vec2 scaleSign = glm::sign(scale); - vec2 pivotScaled = pivot * scaleAbsolute; - vec2 sizeScaled = size * scaleAbsolute; - float handedness = (scaleSign.x * scaleSign.y) < 0.0f ? -1.0f : 1.0f; - - mat4 model(1.0f); - model = glm::translate(model, vec3(position - pivotScaled, 0.0f)); - model = glm::translate(model, vec3(pivotScaled, 0.0f)); - model = glm::scale(model, vec3(scaleSign, 1.0f)); - model = glm::rotate(model, glm::radians(rotation) * handedness, vec3(0, 0, 1)); - model = glm::translate(model, vec3(-pivotScaled, 0.0f)); - model = glm::scale(model, vec3(sizeScaled, 1.0f)); - return model; - } - - mat4 quad_model_parent_get(vec2 position, vec2 pivot, vec2 scale, float rotation) + static mat4 quad_model_local_get(vec2 pivot, vec2 scale, float rotation) { vec2 scaleSign = glm::sign(scale); vec2 scaleAbsolute = glm::abs(scale); @@ -37,17 +19,33 @@ namespace game::util::math local = glm::rotate(local, glm::radians(rotation) * handedness, vec3(0, 0, 1)); local = glm::translate(local, vec3(-pivot, 0.0f)); local = glm::scale(local, vec3(scaleAbsolute, 1.0f)); + return local; + } - return glm::translate(mat4(1.0f), vec3(position, 0.0f)) * local; + mat4 quad_model_get(vec2 size, vec2 position, vec2 pivot, vec2 scale, float rotation) + { + vec2 scaleAbsolute = glm::abs(scale); + vec2 scaleSign = glm::sign(scale); + vec2 pivotScaled = pivot * scaleAbsolute; + vec2 sizeScaled = size * scaleAbsolute; + + return glm::translate(mat4(1.0f), vec3(position - pivotScaled, 0.0f)) * + quad_model_local_get(pivotScaled, scaleSign, rotation) * glm::scale(mat4(1.0f), vec3(sizeScaled, 1.0f)); + } + + mat4 quad_model_no_size_get(vec2 position, vec2 pivot, vec2 scale, float rotation) + { + return glm::translate(mat4(1.0f), vec3(position, 0.0f)) * quad_model_local_get(pivot, scale, rotation); } bool is_point_in_rect(ivec4 rect, ivec2 point) { return SDL_PointInRect((SDL_Point*)&point, (SDL_Rect*)&rect); } bool is_point_in_rectf(vec4 rect, vec2 point) { return SDL_PointInRectFloat((SDL_FPoint*)&point, (SDL_FRect*)&rect); } - float random() { return (float)rand() / RAND_MAX; } + float random() { return (float)rand() / (float)RAND_MAX; } bool random_percent_roll(float percent) { return to_percent(random()) < percent; } float random_in_range(float min, float max) { return min + random() * (max - min); } + float random_max(float max) { return random_in_range(0, max); } float random_roll(float value) { return random() * value; } bool random_bool() { return random() < 0.5f; }; void random_seed_set() { srand(std::time(nullptr)); } -} \ No newline at end of file +} diff --git a/src/util/math_.hpp b/src/util/math.hpp similarity index 82% rename from src/util/math_.hpp rename to src/util/math.hpp index f4dcccf..8711e0f 100644 --- a/src/util/math_.hpp +++ b/src/util/math.hpp @@ -7,8 +7,8 @@ namespace game::util::math { glm::mat4 quad_model_get(glm::vec2 size, glm::vec2 position = {}, glm::vec2 pivot = {}, glm::vec2 scale = glm::vec2(1.0f), float rotation = {}); - glm::mat4 quad_model_parent_get(glm::vec2 position = {}, glm::vec2 pivot = {}, glm::vec2 scale = glm::vec2(1.0f), - float rotation = {}); + glm::mat4 quad_model_no_size_get(glm::vec2 position = {}, glm::vec2 pivot = {}, glm::vec2 scale = glm::vec2(1.0f), + float rotation = {}); template constexpr T to_percent(T value) { return value * 100.0f; } template constexpr T to_unit(T value) { return value / 100.0f; } @@ -26,6 +26,7 @@ namespace game::util::math bool random_percent_roll(float percent); float random_roll(float value); float random_in_range(float min, float max); + float random_max(float max); bool random_bool(); void random_seed_set(); -} \ No newline at end of file +} diff --git a/src/util/measurement.hpp b/src/util/measurement.hpp new file mode 100644 index 0000000..def202e --- /dev/null +++ b/src/util/measurement.hpp @@ -0,0 +1,12 @@ +#pragma once + +namespace game::util::measurement +{ + enum System + { + METRIC, + IMPERIAL + }; + + constexpr auto KG_TO_LB = 2.20462; +} \ No newline at end of file diff --git a/src/util/physfs.cpp b/src/util/physfs.cpp new file mode 100644 index 0000000..acde594 --- /dev/null +++ b/src/util/physfs.cpp @@ -0,0 +1,131 @@ +#include "physfs.hpp" + +#include + +#include +#include + +#include "../log.hpp" + +namespace game::util::physfs +{ + std::string path_normalize(std::string_view path) + { + const bool absolute = !path.empty() && path.front() == '/'; + std::vector parts{}; + std::string segment{}; + + auto flush_segment = [&]() + { + if (segment.empty() || segment == ".") + { + segment.clear(); + return; + } + + if (segment == "..") + { + if (!parts.empty() && parts.back() != "..") + parts.pop_back(); + else if (!absolute) + parts.emplace_back(".."); + } + else + { + parts.emplace_back(std::move(segment)); + } + + segment.clear(); + }; + + for (char ch : path) + { + if (ch == '/') + { + flush_segment(); + continue; + } + + segment.push_back(ch); + } + + flush_segment(); + + std::string pathNormalized{}; + if (absolute) pathNormalized.push_back('/'); + for (size_t i = 0; i < parts.size(); ++i) + { + if (i > 0) pathNormalized.push_back('/'); + pathNormalized.append(parts[i]); + } + + if (pathNormalized.empty() && absolute) return "/"; + return pathNormalized; + } + + std::string error_get() { return PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()); } + + Archive::Archive(const std::filesystem::path& path, const std::string& mount) + { + if (!PHYSFS_mount(path.c_str(), mount.c_str(), 0)) + { + logger.error(std::format("Failed to mount archive: {} ({})", path.c_str(), error_get())); + return; + } + + *this = std::string(mount); + } + + Archive::~Archive() { PHYSFS_unmount(c_str()); } + + bool Archive::is_valid() { return !empty(); } + + std::vector Path::read() const + { + auto pathNormalized = path_normalize(*this); + auto file = PHYSFS_openRead(pathNormalized.c_str()); + + if (!file) + { + logger.error( + std::format("Failed to read PhysicsFS file (PHYFSFS_openRead): {} ({})", pathNormalized, error_get())); + return {}; + } + + auto size = PHYSFS_fileLength(file); + if (size < 0) + { + logger.error( + std::format("Failed to get PhysicsFS file length (PHYSFS_fileLength): {} ({})", pathNormalized, error_get())); + return {}; + } + + std::vector buffer((size_t)size); + + auto read = PHYSFS_readBytes(file, buffer.data(), size); + + PHYSFS_close(file); + + if (read != size) + { + logger.error(std::format("Invalid PhysicsFS file read size: {} ({})", pathNormalized, error_get())); + return {}; + } + + return buffer; + } + + physfs::Path Path::directory_get() const + { + auto pos = find_last_of('/'); + if (pos == std::string_view::npos) return physfs::Path(""); + if (pos == 0) return physfs::Path("/"); + return physfs::Path(substr(0, pos)); + } + + bool Path::is_valid() const + { + auto pathNormalized = path_normalize(*this); + return PHYSFS_exists(pathNormalized.c_str()); + } +} diff --git a/src/util/physfs.hpp b/src/util/physfs.hpp new file mode 100644 index 0000000..005d5ca --- /dev/null +++ b/src/util/physfs.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include + +namespace game::util::physfs +{ + class Archive : public std::string + { + public: + using std::string::operator=; + + Archive(const std::filesystem::path&, const std::string& mount); + ~Archive(); + + bool is_valid(); + }; + + class Path : public std::string + { + public: + bool is_valid() const; + + Path directory_get() const; + std::vector read() const; + }; + + std::string error_get(); +} diff --git a/src/util/preferences.cpp b/src/util/preferences.cpp new file mode 100644 index 0000000..a135b83 --- /dev/null +++ b/src/util/preferences.cpp @@ -0,0 +1,22 @@ +#include "preferences.hpp" + +#include + +namespace game::util::preferences +{ + std::filesystem::path path() + { +#ifdef __EMSCRIPTEN__ + static constexpr auto filePath = "/snivy"; + std::filesystem::create_directories(filePath); + return filePath; +#else + auto sdlPath = SDL_GetPrefPath(nullptr, "snivy"); + if (!sdlPath) return {}; + auto filePath = std::filesystem::path(sdlPath); + std::filesystem::create_directories(filePath); + SDL_free(sdlPath); + return filePath; +#endif + } +} \ No newline at end of file diff --git a/src/util/preferences.hpp b/src/util/preferences.hpp new file mode 100644 index 0000000..40dd028 --- /dev/null +++ b/src/util/preferences.hpp @@ -0,0 +1,8 @@ +#pragma once + +#include + +namespace game::util::preferences +{ + std::filesystem::path path(); +} \ No newline at end of file diff --git a/src/util/string.cpp b/src/util/string.cpp new file mode 100644 index 0000000..da73b23 --- /dev/null +++ b/src/util/string.cpp @@ -0,0 +1,11 @@ +#include "string.hpp" + +namespace game::util::string +{ + std::string to_lower(const std::string& string) + { + std::string transformed = string; + std::ranges::transform(transformed, transformed.begin(), [](const unsigned char c) { return std::tolower(c); }); + return transformed; + } +} \ No newline at end of file diff --git a/src/util/string_.hpp b/src/util/string.hpp similarity index 91% rename from src/util/string_.hpp rename to src/util/string.hpp index 5ca90c3..b14657c 100644 --- a/src/util/string_.hpp +++ b/src/util/string.hpp @@ -8,8 +8,7 @@ namespace game::util::string { - template - std::string format_commas(Number value, int decimalDigits = -1) + template std::string format_commas(Number value, int decimalDigits = -1) { static_assert(std::is_arithmetic_v, "format_commas requires numeric types"); @@ -59,4 +58,6 @@ namespace game::util::string return formattedInteger + fraction + exponent; } + + std::string to_lower(const std::string&); } diff --git a/src/util/time.cpp b/src/util/time.cpp new file mode 100644 index 0000000..465be36 --- /dev/null +++ b/src/util/time.cpp @@ -0,0 +1,17 @@ +#include "time.hpp" + +#include +#include + +namespace game::util::time +{ + std::string get(const char* format) + { + auto now = std::chrono::system_clock::now(); + auto time = std::chrono::system_clock::to_time_t(now); + auto localTime = *std::localtime(&time); + std::ostringstream timeString; + timeString << std::put_time(&localTime, format); + return timeString.str(); + } +} diff --git a/src/util/time.hpp b/src/util/time.hpp new file mode 100644 index 0000000..e74e722 --- /dev/null +++ b/src/util/time.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include + +namespace game::util::time +{ + constexpr auto SECOND_M = 60; + + std::string get(const char*); +} diff --git a/src/util/unordered_map_.hpp b/src/util/unordered_map.hpp similarity index 99% rename from src/util/unordered_map_.hpp rename to src/util/unordered_map.hpp index 331e5ea..cbcb9db 100644 --- a/src/util/unordered_map_.hpp +++ b/src/util/unordered_map.hpp @@ -10,4 +10,4 @@ namespace game::util::unordered_map if (it != map.end()) return &it->second; return nullptr; } -} \ No newline at end of file +} diff --git a/src/util/vector.hpp b/src/util/vector.hpp new file mode 100644 index 0000000..255ea5c --- /dev/null +++ b/src/util/vector.hpp @@ -0,0 +1,86 @@ +#pragma once + +#include +#include + +#include "math.hpp" + +namespace game::util::vector +{ + template bool in_bounds(std::vector& vector, int index) + { + return (index >= 0 && index < (int)vector.size()); + } + + template T* find(std::vector& vector, int index) + { + if (!in_bounds(vector, index)) return nullptr; + return &vector[index]; + } + + template T* find(std::vector& vector, T& value) + { + auto it = find(vector.begin(), vector.end(), value); + return (it == vector.end()) ? nullptr : std::addressof(*it); + } + + template int index_get(std::vector& vector, T& value) + { + auto it = find(vector.begin(), vector.end(), value); + return (it == vector.end()) ? -1 : (int)std::distance(vector.begin(), it); + } + + template int emplace_index(std::vector& vector, Args&&... args) + { + auto index = (int)vector.size(); + vector.emplace_back(std::forward(args)...); + return index; + } + + template int push_index(std::vector& vector, const T& value) + { + auto index = (int)vector.size(); + vector.push_back(value); + return index; + } + + template int push_index(std::vector& vector, T&& value) + { + auto index = (int)vector.size(); + vector.push_back(std::move(value)); + return index; + } + + template + int random_index_weighted(const std::vector& vector, WeightFunction weightFunction) + { + if (vector.empty()) return -1; + if (vector.size() == 1) return 0; + + float total{}; + float accumulator{}; + + for (auto& item : vector) + { + auto weight = (float)(weightFunction(item)); + if (weight > 0.0f) total += weight; + } + + if (total <= 0.0f) return -1; + + float randomValue = math::random_max(total); + int lastIndex = -1; + + for (int i = 0; i < (int)vector.size(); i++) + { + auto weight = (float)(weightFunction(vector[i])); + if (weight <= 0.0f) continue; + + lastIndex = i; + accumulator += weight; + if (randomValue < accumulator) return i; + } + + return lastIndex; + } +} diff --git a/src/util/vector_.hpp b/src/util/vector_.hpp deleted file mode 100644 index 1b5e372..0000000 --- a/src/util/vector_.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -namespace game::util::vector -{ - template bool in_bounds(std::vector& vector, int index) - { - return (index >= 0 && index < vector.size()); - } - - template T* find(std::vector& vector, int index) - { - if (!in_bounds(vector, index)) return nullptr; - return &vector[index]; - } -} diff --git a/src/util/web_filesystem.cpp b/src/util/web_filesystem.cpp new file mode 100644 index 0000000..ead4fe1 --- /dev/null +++ b/src/util/web_filesystem.cpp @@ -0,0 +1,53 @@ +#include "web_filesystem.hpp" + +#ifdef __EMSCRIPTEN__ + #include + #include +#endif + +namespace game::util::web_filesystem +{ +#ifdef __EMSCRIPTEN__ + EM_JS(void, idbfs_init_async, (), { + Module.filesystemReady = 0; + try + { + FS.mkdir('/snivy'); + } + catch (e) + { + } + FS.mount(IDBFS, {}, '/snivy'); + FS.syncfs( + true, function(err) { + if (err) console.error('IDBFS init sync failed', err); + Module.filesystemReady = 1; + }); + }); + + EM_JS(int, idbfs_ready, (), { return Module.filesystemReady ? 1 : 0; }); + + EM_JS(void, idbfs_flush_async, (), { + FS.syncfs( + false, function(err) { + if (err) console.error('IDBFS flush failed', err); + }); + }); +#endif + + void init_and_wait() + { +#ifdef __EMSCRIPTEN__ + idbfs_init_async(); + while (!idbfs_ready()) + emscripten_sleep(16); +#endif + } + + void flush_async() + { +#ifdef __EMSCRIPTEN__ + idbfs_flush_async(); +#endif + } +} \ No newline at end of file diff --git a/src/util/web_filesystem.hpp b/src/util/web_filesystem.hpp new file mode 100644 index 0000000..2c3f4f6 --- /dev/null +++ b/src/util/web_filesystem.hpp @@ -0,0 +1,7 @@ +#pragma once + +namespace game::util::web_filesystem +{ + void init_and_wait(); + void flush_async(); +}; \ No newline at end of file diff --git a/src/util/working_directory.cpp b/src/util/working_directory.cpp new file mode 100644 index 0000000..79ba7d0 --- /dev/null +++ b/src/util/working_directory.cpp @@ -0,0 +1,49 @@ +#include "working_directory.hpp" + +#include +#include + +namespace game::util +{ + WorkingDirectory::WorkingDirectory(const std::filesystem::path& path, Type type) + { + std::error_code ec{}; + previous = std::filesystem::current_path(ec); + if (ec) + { + std::cout << std::format("Could not query current directory: {}", ec.message()) << "\n"; + previous.clear(); + ec.clear(); + } + + if (type == FILE && path.has_parent_path()) + { + std::filesystem::path parentPath = path.parent_path(); + std::filesystem::current_path(parentPath, ec); + if (ec) + std::cout << std::format("Could not set current directory to {}: {}", parentPath.string(), ec.message()) + << "\n"; + } + else if (std::filesystem::is_directory(path)) + { + std::filesystem::current_path(path, ec); + if (ec) + std::cout << std::format("Could not set current directory to {}: {}", path.string(), ec.message()) << "\n"; + } + + isValid = true; + } + + WorkingDirectory::~WorkingDirectory() + { + if (previous.empty() || !isValid) return; + + std::error_code ec{}; + std::filesystem::current_path(previous, ec); + if (ec) + std::cout << std::format("Could not restore current directory to {}: {}", previous.string(), ec.message()) + << "\n"; + } + + bool WorkingDirectory::is_valid() const { return isValid; } +} \ No newline at end of file diff --git a/src/util/working_directory.hpp b/src/util/working_directory.hpp new file mode 100644 index 0000000..e5a4102 --- /dev/null +++ b/src/util/working_directory.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include + +namespace game::util +{ + class WorkingDirectory + { + public: + enum Type + { + DIRECTORY, + FILE + }; + + std::filesystem::path previous{}; + bool isValid{}; + + WorkingDirectory() = default; + WorkingDirectory(const std::filesystem::path&, Type type = DIRECTORY); + ~WorkingDirectory(); + bool is_valid() const; + }; +} \ No newline at end of file diff --git a/src/util/xml_.cpp b/src/util/xml_.cpp deleted file mode 100644 index e8d34dd..0000000 --- a/src/util/xml_.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "xml_.h" - -using namespace tinyxml2; - -namespace game::util::xml -{ - XMLError query_string_attribute(XMLElement* element, const char* attribute, std::string* value) - { - const char* temp = nullptr; - auto result = element->QueryStringAttribute(attribute, &temp); - if (result == XML_SUCCESS && temp && value) *value = temp; - return result; - } - - XMLError query_path_attribute(XMLElement* element, const char* attribute, std::filesystem::path* value) - { - std::string temp{}; - auto result = query_string_attribute(element, attribute, &temp); - if (value) *value = std::filesystem::path(temp); - return result; - } - - XMLError query_color_attribute(XMLElement* element, const char* attribute, float* value) - { - int temp{}; - auto result = element->QueryIntAttribute(attribute, &temp); - if (result == XML_SUCCESS && value) *value = (temp / 255.0f); - return result; - } -} \ No newline at end of file diff --git a/src/util/xml_.hpp b/src/util/xml_.hpp deleted file mode 100644 index db7f6db..0000000 --- a/src/util/xml_.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -#include -#include - -namespace game::util::xml -{ - tinyxml2::XMLError query_string_attribute(tinyxml2::XMLElement*, const char*, std::string*); - tinyxml2::XMLError query_path_attribute(tinyxml2::XMLElement*, const char*, std::filesystem::path*); - tinyxml2::XMLError query_color_attribute(tinyxml2::XMLElement*, const char*, float*); -} \ No newline at end of file diff --git a/src/window/chat.cpp b/src/window/chat.cpp deleted file mode 100644 index 055f1cd..0000000 --- a/src/window/chat.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "chat.h" - -using namespace game::resource; - -namespace game::window -{ - void Chat::update(Resources& resources, GameData& gameData, Text& text, Character& character) - { - - auto size = ImGui::GetContentRegionAvail(); - - ImGui::PushFont(resources.font.get(), Font::LARGE); - if (ImGui::Button("Let's chat!", ImVec2(size.x, 0))) - { - resources.sound_play(audio::ADVANCE); - text.set_random(resources.dialogue.randomIDs, resources, character); - } - ImGui::PopFont(); - ImGui::SetItemTooltip("Snivy will bring up a random conversation topic."); - - if (ImGui::Button("Help", ImVec2(size.x, 0))) - { - resources.sound_play(audio::ADVANCE); - text.set(resources.dialogue.get("Help"), character); - } - ImGui::SetItemTooltip("Ask Snivy for help on this whole shebang."); - } -} diff --git a/src/window/chat.hpp b/src/window/chat.hpp deleted file mode 100644 index 9bc4e54..0000000 --- a/src/window/chat.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "../character.h" -#include "../game_data.h" -#include "../resources.h" - -#include "text.h" - -#include - -namespace game::window -{ - class Chat - { - public: - void update(Resources&, GameData&, Text&, Character&); - }; -} diff --git a/src/window/info.cpp b/src/window/info.cpp deleted file mode 100644 index 846f0ca..0000000 --- a/src/window/info.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include "info.h" - -#include "../util/math_.h" -#include "../util/string_.h" - -#include -#include - -namespace game::window -{ - - void Info::update(Resources& resources, GameData& gameData, Character& character, ImVec2 size, ImVec2 pos) - { - ImGui::SetNextWindowSize(size); - ImGui::SetNextWindowPos(pos); - - if (ImGui::Begin("##Info", nullptr, - ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove)) - { - auto childSize = ImVec2(ImGui::GetContentRegionAvail().x / 2, ImGui::GetContentRegionAvail().y); - - if (ImGui::BeginChild("##Weight", childSize)) - { - auto& system = gameData.measurementSystem; - auto weight = character.weight_get(system); - - ImGui::TextUnformatted( - std::format("{} {}", util::string::format_commas(weight, 2), system == IMPERIAL ? "lbs" : "kg").c_str()); - - if (character.weightStage >= character.WEIGHT_STAGE_MAX - 1) - { - ImGui::ProgressBar(1.0f, ImVec2(), "MAX"); - ImGui::SetItemTooltip("Maxed out!"); - } - else - { - auto weightCurrent = character.weight_threshold_current_get(system); - auto weightNext = character.weight_threshold_next_get(system); - auto weightProgress = character.progress_to_next_weight_threshold_get(); - - ImGui::ProgressBar(weightProgress, ImVec2(), "To Next Stage"); - auto format = system == IMPERIAL ? "Start: %0.2flbs | Current: %0.2flbs | Goal: %0.2flbs | (%0.2f%%)" - : "Start: %0.2fkg | Current: %0.2fkg | Goal: %0.2fkg | (%0.2f%%)"; - ImGui::SetItemTooltip(format, weightCurrent, weight, weightNext, util::math::to_percent(weightProgress)); - } - } - ImGui::EndChild(); - - ImGui::SameLine(); - - if (ImGui::BeginChild("##Calories and Capacity", childSize)) - { - auto& calories = character.calories; - auto& capacity = character.capacity; - - auto overstuffedPercent = std::max(0.0f, (calories - capacity) / (character.max_capacity() - capacity)); - auto caloriesColor = ImVec4(1.0f, 1.0f - overstuffedPercent, 1.0f - overstuffedPercent, 1.0f); - - ImGui::PushStyleColor(ImGuiCol_Text, caloriesColor); - ImGui::Text("%0.0lf kcal", calories); - ImGui::PopStyleColor(); - ImGui::SameLine(); - if (character.is_over_capacity()) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 0, 0, 1)); - ImGui::Text("/ %0.0lf kcal", character.is_over_capacity() ? character.max_capacity() : character.capacity); - if (character.is_over_capacity()) ImGui::PopStyleColor(); - - auto digestionProgress = character.isDigesting - ? (float)character.digestionTimer / Character::DIGESTION_TIMER_MAX - : character.digestionProgress / character.DIGESTION_MAX; - ImGui::ProgressBar(digestionProgress, ImVec2(), character.isDigesting ? "Digesting..." : "Digestion"); - - if (ImGui::BeginItemTooltip()) - { - if (character.isDigesting) - ImGui::TextUnformatted("Digestion in progress..."); - else if (digestionProgress <= 0.0f) - ImGui::TextUnformatted("Give food to start digesting!"); - - ImGui::Text("%0.2f%%", util::math::to_percent(digestionProgress)); - - ImGui::Text("Rate: %0.2f%% / sec", character.digestion_rate_second_get()); - - ImGui::Text("Eating Speed: %0.2fx", character.eatSpeedMultiplier); - - ImGui::EndTooltip(); - } - } - ImGui::EndChild(); - } - ImGui::End(); - } -} diff --git a/src/window/info.hpp b/src/window/info.hpp deleted file mode 100644 index 7fa10a1..0000000 --- a/src/window/info.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "../character.h" -#include "../game_data.h" -#include "../resources.h" - -#include - -namespace game::window -{ - class Info - { - public: - void update(Resources&, GameData&, Character&, ImVec2, ImVec2); - }; -} diff --git a/src/window/inventory.cpp b/src/window/inventory.cpp deleted file mode 100644 index f0ddfbe..0000000 --- a/src/window/inventory.cpp +++ /dev/null @@ -1,157 +0,0 @@ -#include "inventory.h" - -#include "../util/imgui_.h" -#include - -using namespace game::util; -using namespace game::resource; -using namespace glm; - -namespace game::window -{ - Inventory::Inventory() - { - count = 0; - - for (auto& [type, quantity] : values) - { - count += quantity; - } - } - - void Inventory::adjust_item(Item::Type type, int quantity) - { - values[type] += quantity; - count += quantity; - } - - void Inventory::set_item(Item::Type type, int value) - { - count -= values[type]; - values[type] = value; - count += value; - } - - int Inventory::get_item(Item::Type type) { return values.contains(type) ? values[type] : 0; } - - void Inventory::update(Resources& resources, Character& character, GameData& gameData) - { - auto& texture = resources.anm2s[anm2::ITEMS].content.spritesheets.at(0).texture; - - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, BUTTON_ROUNDING); - - auto cursorPos = ImGui::GetCursorPos(); - auto cursorStartX = ImGui::GetCursorPosX(); - - for (int index = 0; index < Item::ITEM_COUNT; index++) - { - auto type = (Item::Type)index; - auto seen = values.contains(type); - - //Hide invalid items and impossible-to-obtain items when not seen. - if (!seen && (Item::CATEGORIES[type] == Item::INVALID || Item::RARITIES[type] == Item::IMPOSSIBLE)) continue; - - auto columns = (int)(texture.size.x / ITEM_SIZE.x); - auto crop = vec2(type % columns, type / columns) * ITEM_SIZE; - auto uvMin = crop / vec2(texture.size); - auto uvMax = (crop + ITEM_SIZE) / vec2(texture.size); - - ImGui::PushID(type); - ImGui::SetCursorPos(cursorPos); - auto cursorScreenPos = ImGui::GetCursorScreenPos(); - - auto quantity = 0; - - if (seen) - { - quantity = values[type]; - - ImGui::BeginDisabled(quantity < 1); - if (ImGui::ImageButton("##Image Button", texture.id, IMAGE_SIZE, imgui::to_imvec2(uvMin), - imgui::to_imvec2(uvMax)) && - quantity > 0) - { - queuedItemType = type; - isQueued = true; - - resources.sound_play(audio::SUMMON); - } - ImGui::EndDisabled(); - - if (ImGui::BeginItemTooltip()) - { - auto& category = Item::CATEGORIES[type]; - auto& rarity = Item::RARITIES[type]; - auto& flavor = Item::FLAVORS[type]; - auto& calories = Item::CALORIES[type]; - auto& digestionRateBonus = Item::DIGESTION_RATE_BONUSES[type]; - auto& eatSpeedBonus = Item::EAT_SPEED_BONUSES[type]; - - ImGui::Text("%s (x%i)", Item::NAMES[type], quantity); - - ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(imgui::to_imvec4(GRAY))); - ImGui::Text("-- %s (%s) --", Item::CATEGORY_NAMES[category], Item::RARITY_NAMES[rarity]); - if (category == Item::FOOD) - { - ImGui::Separator(); - if (flavor != Item::FLAVORLESS) ImGui::Text("Flavor: %s", Item::FLAVOR_NAMES[flavor]); - if (calories != 0) ImGui::Text("%0.0f kcal", calories); - if (digestionRateBonus > 0) - ImGui::Text("Digestion Rate Bonus: +%0.2f%% / sec", digestionRateBonus * 60.0f); - else if (digestionRateBonus < 0) - ImGui::Text("Digestion Rate Penalty: %0.2f%% / sec", digestionRateBonus * 60.0f); - if (eatSpeedBonus > 0) ImGui::Text("Eat Speed Bonus: +%0.2fx ", eatSpeedBonus); - } - ImGui::Separator(); - ImGui::TextUnformatted(Item::DESCRIPTIONS[type]); - ImGui::PopStyleColor(); - ImGui::EndTooltip(); - } - - ImGui::PushFont(resources.font.get(), Font::BIG); - auto text = std::format("x{}", quantity); - auto textPos = ImVec2(cursorScreenPos.x + IMAGE_SIZE.x - ImGui::CalcTextSize(text.c_str()).x, - cursorScreenPos.y + IMAGE_SIZE.y - ImGui::GetTextLineHeight()); - ImGui::GetWindowDrawList()->AddText(textPos, ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Text)), - text.c_str()); - ImGui::PopFont(); - } - else - { - ImGui::BeginDisabled(true); - ImGui::ImageButton("##Image Button", texture.id, IMAGE_SIZE, imgui::to_imvec2(uvMin), imgui::to_imvec2(uvMax), - ImVec4(0, 0, 0, 0), ImVec4(0, 0, 0, 1)); - ImGui::EndDisabled(); - - if (ImGui::BeginItemTooltip()) - { - ImGui::TextUnformatted("??? (x0)"); - - ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetColorU32(imgui::to_imvec4(GRAY))); - ImGui::TextUnformatted("-- ??? (\?\?\?) --"); - - ImGui::Separator(); - ImGui::TextUnformatted("???"); - - ImGui::PopStyleColor(); - ImGui::EndTooltip(); - } - } - - auto increment = ImGui::GetItemRectSize().x + ImGui::GetStyle().ItemSpacing.x; - cursorPos.x += increment; - - if (cursorPos.x + increment > ImGui::GetContentRegionAvail().x) - { - cursorPos.x = cursorStartX; - cursorPos.y += increment; - } - - ImGui::PopID(); - } - - if (count == 0) ImGui::Text("Check the \"Play\" tab to earn rewards!"); - - ImGui::PopStyleVar(); - } -} diff --git a/src/window/inventory.hpp b/src/window/inventory.hpp deleted file mode 100644 index 40c8510..0000000 --- a/src/window/inventory.hpp +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include "../character.h" -#include "../game_data.h" -#include "../item.h" -#include "../resources.h" - -#include - -namespace game::window -{ - class Inventory - { - private: - std::map values = {{Item::POKE_PUFF_BASIC_SWEET, 1}, - {Item::POKE_PUFF_BASIC_CITRUS, 1}, - {Item::POKE_PUFF_BASIC_MINT, 1}, - {Item::POKE_PUFF_BASIC_MOCHA, 1}, - {Item::POKE_PUFF_BASIC_SPICE, 1}}; - - public: - static constexpr auto ITEM_SIZE = glm::vec2(48, 48); - static constexpr auto IMAGE_SIZE = ImVec2(48, 48); - static constexpr auto BUTTON_ROUNDING = 32.0f; - int count; - - bool isQueued{}; - Item::Type queuedItemType{}; - - Inventory(); - void update(Resources&, Character&, GameData&); - void adjust_item(Item::Type, int = 1); - void set_item(Item::Type, int); - int get_item(Item::Type); - }; -} diff --git a/src/window/main_menu.cpp b/src/window/main_menu.cpp deleted file mode 100644 index 73c547f..0000000 --- a/src/window/main_menu.cpp +++ /dev/null @@ -1,150 +0,0 @@ -#include "main_menu.h" - -namespace game::window -{ - void MainMenu::update(Resources& resources, Character& character, GameData& gameData, Text& text, ImVec2 size, - ImVec2 pos) - { - MeasurementSystem& measurementSystem = gameData.measurementSystem; - int& volume = gameData.volume; - - ImGui::SetNextWindowSize(size); - ImGui::SetNextWindowPos(pos); - - if (ImGui::Begin("##Main", nullptr, - ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove)) - { - - if (ImGui::BeginTabBar("##Options", ImGuiTabBarFlags_FittingPolicyResizeDown)) - { - - if (ImGui::BeginTabItem("Chat")) - { - chat.update(resources, gameData, text, character); - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem("Play")) - { - play.update(resources, character, inventory, gameData, text); - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem("Inventory")) - { - inventory.update(resources, character, gameData); - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem("Stats")) - { - stats.update(resources, gameData, play, character); - ImGui::EndTabItem(); - } - - if (ImGui::BeginTabItem("Settings")) - { - ImGui::SeparatorText("Measurement System"); - ImGui::RadioButton("Metric", (int*)&measurementSystem, MeasurementSystem::METRIC); - ImGui::SameLine(); - ImGui::RadioButton("Imperial", (int*)&measurementSystem, MeasurementSystem::IMPERIAL); - - ImGui::SeparatorText("Sound"); - if (ImGui::SliderInt("Volume", (int*)&volume, 0, 100)) - { - resources.set_audio_gain((float)volume / 100); - } - - ImGui::EndTabItem(); - } - - if (isCheats && ImGui::BeginTabItem("Cheats")) - { - if (ImGui::Button("Feed")) - character.calories = std::min(character.calories + 100.0f, character.max_capacity()); - ImGui::SameLine(); - if (ImGui::Button("Starve")) character.calories = std::max(0.0f, character.calories - 100.0f); - ImGui::SameLine(); - if (ImGui::Button("Digest")) - { - character.digestionProgress = Character::DIGESTION_MAX; - if (character.calories == 0.0f) character.calories = 0.001f; - } - ImGui::SameLine(); - ImGui::Checkbox("Show Nulls (Hitboxes)", &character.isShowNulls); - - if (ImGui::DragInt("Stage", &character.weightStage, 0.1f, 0, Character::WEIGHT_STAGE_MAX - 1)) - { - character.weight = Character::WEIGHT_THRESHOLDS[character.weightStage]; - character.weight = character.weight < character.highestWeight ? character.highestWeight : character.weight; - character.state_set(Character::IDLE, true); - character.isForceStageUp = true; - } - - ImGui::DragFloat("Digestion Rate", &character.digestionRate, 0.005f, Character::DIGESTION_RATE_MIN, - Character::DIGESTION_RATE_MAX); - ImGui::DragFloat("Eat Speed", &character.eatSpeedMultiplier, 0.1f, Character::EAT_SPEED_MULTIPLIER_MIN, - Character::EAT_SPEED_MULTIPLIER_MAX); - - ImGui::SeparatorText("Animations"); - ImGui::Text("Now Playing: %s", character.anm2->animations.mapReverse.at(character.animationIndex).c_str()); - - if (ImGui::BeginChild("## Animations", {0, 100}, ImGuiChildFlags_Borders)) - { - for (int i = 0; i < character.anm2->animations.items.size(); i++) - { - auto& animation = character.anm2->animations.items[i]; - ImGui::PushID(i); - if (ImGui::Selectable(animation.name.c_str())) - character.play(animation.name.c_str(), Character::FORCE_PLAY); - ImGui::PopID(); - } - } - ImGui::EndChild(); - - ImGui::SeparatorText("Dialogue"); - - if (ImGui::BeginChild("## Dialogue", {0, 100}, ImGuiChildFlags_Borders)) - { - for (auto& [label, i] : resources.dialogue.labelMap) - { - ImGui::PushID(i); - if (ImGui::Selectable(label.c_str())) text.set(&resources.dialogue.entryMap.at(i), character); - ImGui::PopID(); - } - } - ImGui::EndChild(); - - ImGui::SeparatorText("Inventory"); - - if (ImGui::BeginChild("## Inventory", ImGui::GetContentRegionAvail(), ImGuiChildFlags_Borders)) - { - ImGui::PushItemWidth(100); - for (int i = 0; i < Item::ITEM_COUNT; i++) - { - if (Item::CATEGORIES[i] == Item::INVALID) continue; - ImGui::PushID(i); - - //TODO: Probably a cleaner way to do this, maybe - int value = inventory.get_item((Item::Type)i); - if (ImGui::DragInt(Item::NAMES[i], &value, 0.1f, 0, 999)) - { - inventory.set_item((Item::Type)i, value); - } - - ImGui::PopID(); - } - ImGui::PopItemWidth(); - } - ImGui::EndChild(); - - ImGui::EndTabItem(); - } - } - - ImGui::EndTabBar(); - } - ImGui::End(); - } -} \ No newline at end of file diff --git a/src/window/main_menu.hpp b/src/window/main_menu.hpp deleted file mode 100644 index ae7f356..0000000 --- a/src/window/main_menu.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -#include "chat.h" -#include "play.h" -#include "stats.h" -#include "text.h" - -namespace game::window -{ - class MainMenu - { - public: - Play play; - Chat chat; - Stats stats; - Inventory inventory; - - bool isCheats{}; - - void update(Resources&, Character&, GameData&, Text& text, ImVec2 size, ImVec2 pos); - }; -} diff --git a/src/window/play.cpp b/src/window/play.cpp deleted file mode 100644 index 19ecb86..0000000 --- a/src/window/play.cpp +++ /dev/null @@ -1,361 +0,0 @@ -#include "play.h" - -#include "../util/imgui_.h" -#include "../util/math_.h" -#include - -using namespace game::util; -using namespace glm; - -namespace game::window -{ - const std::unordered_map GRADE_SOUNDS = { - {Play::MISS, audio::MISS}, {Play::OK, audio::OK}, - {Play::GOOD, audio::GOOD}, {Play::GREAT, audio::GREAT}, - {Play::EXCELLENT, audio::EXCELLENT}, {Play::PERFECT, audio::PERFECT}}; - - const std::unordered_map RARITY_SOUNDS = {{Item::COMMON, audio::COMMON}, - {Item::UNCOMMON, audio::UNCOMMON}, - {Item::RARE, audio::RARE}, - {Item::EPIC, audio::EPIC}, - {Item::LEGENDARY, audio::LEGENDARY}, - {Item::SPECIAL, audio::SPECIAL}, - {Item::IMPOSSIBLE, audio::IMPOSSIBLE}}; - - float Play::accuracy_score_get() - { - if (totalPlays == 0) return 0.0f; - float combinedWeight{}; - for (int i = 0; i < Play::GRADE_COUNT; i++) - combinedWeight += (GRADE_WEIGHTS[(Play::Grade)i] * gradeCounts[(Play::Grade)i]); - - return glm::clamp(0.0f, math::to_percent(combinedWeight / totalPlays), 100.0f); - } - - Play::Challenge Play::challenge_generate(int level) - { - level = std::max(1, level); - - Challenge newChallenge; - - newChallenge.level = level; - - Range newRange{}; - - auto rangeSize = std::max(RANGE_MIN, RANGE_BASE - (RANGE_SCORE_BONUS * score)); - newRange.min = math::random_in_range(0.0, 1.0f - rangeSize); - newRange.max = newRange.min + rangeSize; - - newChallenge.range = newRange; - newChallenge.tryValue = 0.0f; - - newChallenge.speed = glm::clamp(SPEED_BASE, SPEED_BASE + (SPEED_SCORE_BONUS * score), SPEED_MAX); - - if (math::random_bool()) - { - newChallenge.tryValue = 1.0f; - newChallenge.speed *= -1; - } - - return newChallenge; - } - - Play::Play() - { - challenge = challenge_generate(1); - - for (int i = 0; i < Play::GRADE_COUNT; i++) - gradeCounts[(Play::Grade)i] = 0; - } - - void Play::update(Resources& resources, Character& character, Inventory& inventory, GameData& gameData, Text& text) - { - auto drawList = ImGui::GetWindowDrawList(); - - auto size = ImGui::GetContentRegionAvail(); - auto position = ImGui::GetCursorScreenPos(); - auto spacing = ImGui::GetTextLineHeightWithSpacing(); - auto level = character.weightStage + 1; - - ImGui::Text("Score: %i pts (%ix)", score, combo); - ImGui::Text("Best: %i pts (%ix)", highScore, comboBest); - if (score == 0 && isActive) - ImGui::Text("Match the line to the\ncolored areas with Space/click!\nBetter performance, better rewards!"); - - auto barMin = ImVec2(position.x + (size.x * 0.5f) - (spacing * 0.5f), position.y + (spacing * 2.0f)); - auto barMax = ImVec2(barMin.x + (spacing * 2.0f), barMin.y + size.y - (spacing * 4.0f)); - - bool mouseHovering = ImGui::IsMouseHoveringRect(barMin, barMax); - auto endTimerProgress = (float)endTimer / endTimerMax; - - if (mouseHovering) - { - auto color = RECT_COLOR; - //Ease out and back in again - color.w = isActive ? 1.0f : (4 * pow(endTimerProgress, 2) - 4 * endTimerProgress + 1); - drawList->AddRect(ImVec2(barMin.x - 1, barMin.y - 1), ImVec2(barMax.x + 1, barMax.y + 1), - ImGui::GetColorU32(color)); - } - - drawList->AddRectFilled(barMin, barMax, ImGui::GetColorU32(BG_COLOR)); - - auto barWidth = barMax.x - barMin.x; - auto barHeight = barMax.y - barMin.y; - - auto sub_ranges_get = [&](Range& range) - { - auto& min = range.min; - auto& max = range.max; - auto baseMinY = min; - auto baseMaxY = max; - std::vector ranges{}; - - auto baseHeight = max - min; - auto center = (min + max) * 0.5f; - - for (int i = 0; i < RANGE_AREA_COUNT; ++i) - { - auto scale = powf(0.5f, i); - auto halfHeight = baseHeight * scale * 0.5f; - - ranges.push_back({center - halfHeight, center + halfHeight}); - } - - return ranges; - }; - - auto range_draw = [&](Range& range, float alpha = 1.0f) - { - auto subRanges = sub_ranges_get(range); - - for (int i = 0; i < (int)subRanges.size(); i++) - { - auto& subRange = subRanges[i]; - int layer = (int)subRanges.size() - 1 - i; - - ImVec2 rectMin = {barMin.x, barMin.y + subRange.min * barHeight}; - - ImVec2 rectMax = {barMax.x, barMin.y + subRange.max * barHeight}; - - ImVec4 color = i == subRanges.size() - 1 ? PERFECT_COLOR : RECT_COLOR; - color.w = (color.w - (float)layer / subRanges.size()) * alpha; - - drawList->AddRectFilled(rectMin, rectMax, ImGui::GetColorU32(color)); - } - }; - - range_draw(challenge.range, isActive ? 1.0f : 0.0f); - - auto lineMin = ImVec2(barMin.x - LINE_WIDTH_BONUS, barMin.y + (barHeight * tryValue)); - auto lineMax = ImVec2(barMin.x + barWidth + LINE_WIDTH_BONUS, lineMin.y + LINE_HEIGHT); - auto color = LINE_COLOR; - color.w = isActive ? 1.0f : endTimerProgress; - drawList->AddRectFilled(lineMin, lineMax, ImGui::GetColorU32(color)); - - if (!isActive && !isGameOver) - { - range_draw(queuedChallenge.range, 1.0f - endTimerProgress); - - auto lineMin = ImVec2(barMin.x - LINE_WIDTH_BONUS, barMin.y + (barHeight * queuedChallenge.tryValue)); - auto lineMax = ImVec2(barMin.x + barWidth + LINE_WIDTH_BONUS, lineMin.y + LINE_HEIGHT); - auto color = LINE_COLOR; - color.w = 1.0f - endTimerProgress; - drawList->AddRectFilled(lineMin, lineMax, ImGui::GetColorU32(color)); - } - - if (isActive) - { - tryValue += challenge.speed; - - if (tryValue > 1.0f || tryValue < 0.0f) - { - tryValue = tryValue > 1.0f ? 0.0f : tryValue < 0.0f ? 1.0f : tryValue; - - if (score > 0) - { - score--; - resources.sound_play(audio::SCORE_LOSS); - auto toastMessagePosition = - ImVec2(barMin.x - ImGui::CalcTextSize("-1").x - ImGui::GetTextLineHeightWithSpacing(), lineMin.y); - toastMessages.emplace_back("-1", toastMessagePosition, END_TIMER_MAX, END_TIMER_MAX); - } - } - - if (ImGui::IsKeyPressed(ImGuiKey_Space) || (mouseHovering && ImGui::IsMouseClicked(ImGuiMouseButton_Left))) - { - Grade grade{MISS}; - auto subRanges = sub_ranges_get(challenge.range); - - for (int i = 0; i < (int)subRanges.size(); i++) - { - auto& subRange = subRanges[i]; - - if (tryValue >= subRange.min && tryValue <= subRange.max) - grade = (Grade)std::min((int)(grade + 1), (int)PERFECT); - } - - gradeCounts[grade]++; - totalPlays++; - - if (grade != MISS) - { - if (grade == PERFECT) text.set_random(resources.dialogue.perfectIDs, resources, character); - - combo++; - score += (int)grade; - if (score > highScore) - { - highScore = score; - - if (highScore >= HIGH_SCORE_BIG && !isHighScoreBigAchieved) - { - resources.sound_play(audio::HIGH_SCORE_BIG); - isHighScoreBigAchieved = true; - - inventory.adjust_item(Item::POKE_PUFF_SUPREME_HONOR); - - auto toastItemPosition = - ImVec2(math::random_in_range(barMax.x + ITEM_SIZE.x, barMax.x + (size.x * 0.5f) - ITEM_SIZE.x), - position.y - math::random_in_range(ITEM_SIZE.y, ITEM_SIZE.y * 2.0f)); - toastItems.emplace_back(Item::POKE_PUFF_SUPREME_HONOR, toastItemPosition); - - auto toastMessagePosition = - ImVec2(barMin.x - ImGui::CalcTextSize("Fantastic score! Congratulations!").x - - ImGui::GetTextLineHeightWithSpacing(), - lineMin.y + (ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().ItemSpacing.y)); - toastMessages.emplace_back("Fantastic score! Congratulations!", toastMessagePosition, END_TIMER_MAX, - END_TIMER_MAX); - } - - if (highScoreStart > 0) - { - if (!isHighScoreAchieved) - { - resources.sound_play(audio::HIGH_SCORE); - isHighScoreAchieved = true; - auto toastMessagePosition = - ImVec2(barMin.x - ImGui::CalcTextSize("High Score!").x - ImGui::GetTextLineHeightWithSpacing(), - lineMin.y + ImGui::GetTextLineHeightWithSpacing()); - toastMessages.emplace_back("High Score!", toastMessagePosition, END_TIMER_MAX, END_TIMER_MAX); - } - } - } - - if (combo > comboBest) comboBest = combo; - - auto rewardBonus = - (REWARD_SCORE_BONUS * score) + (REWARD_LEVEL_BONUS * level) + (REWARD_GRADE_BONUS * (int)grade); - while (rewardBonus > 0.0f) - { - const Item::Pool* pool{}; - auto rewardType = Item::NONE; - auto gradeChanceBonus = REWARD_GRADE_CHANCE_BONUS * (int)grade; - auto levelChanceBonus = REWARD_LEVEL_CHANCE_BONUS * (int)level; - auto chanceBonus = std::max(1.0f, gradeChanceBonus + levelChanceBonus); - if (math::random_percent_roll(Item::RARITY_CHANCES[Item::IMPOSSIBLE] * chanceBonus)) - pool = &Item::pools[Item::IMPOSSIBLE]; - else if (math::random_percent_roll(Item::RARITY_CHANCES[Item::LEGENDARY] * chanceBonus)) - pool = &Item::pools[Item::LEGENDARY]; - else if (math::random_percent_roll(Item::RARITY_CHANCES[Item::EPIC] * chanceBonus)) - pool = &Item::pools[Item::EPIC]; - else if (math::random_percent_roll(Item::RARITY_CHANCES[Item::RARE] * chanceBonus)) - pool = &Item::pools[Item::RARE]; - else if (math::random_percent_roll(Item::RARITY_CHANCES[Item::UNCOMMON] * chanceBonus)) - pool = &Item::pools[Item::UNCOMMON]; - else if (math::random_percent_roll(Item::RARITY_CHANCES[Item::COMMON] * chanceBonus)) - pool = &Item::pools[Item::COMMON]; - - if (pool && !pool->empty()) - { - rewardType = (*pool)[(int)math::random_roll((float)pool->size())]; - - auto& rarity = Item::RARITIES[rewardType]; - - resources.sound_play(audio::FALL); - resources.sound_play(RARITY_SOUNDS.at(rarity)); - - inventory.adjust_item(rewardType); - - auto toastItemPosition = - ImVec2(math::random_in_range(barMax.x + ITEM_SIZE.x, barMax.x + (size.x * 0.5f) - ITEM_SIZE.x), - position.y - math::random_in_range(ITEM_SIZE.y, ITEM_SIZE.y * 2.0f)); - toastItems.emplace_back(rewardType, toastItemPosition); - } - - rewardBonus -= 1.0f; - } - } - else - { - text.set_random(resources.dialogue.missIDs, resources, character); - score = 0; - if (isHighScoreAchieved) resources.sound_play(audio::HIGH_SCORE_LOSS); - isHighScoreAchieved = false; - highScoreStart = highScore; - isGameOver = true; - } - resources.sound_play(GRADE_SOUNDS.at(grade)); - - endTimerMax = grade == MISS ? END_TIMER_MISS_MAX : END_TIMER_MAX; - isActive = false; - endTimer = endTimerMax; - - queuedChallenge = challenge_generate(level); - - auto string = - grade == MISS ? GRADE_STRINGS[grade] : std::format("{} (+{})", GRADE_STRINGS[grade], GRADE_VALUES[grade]); - auto toastMessagePosition = - ImVec2(barMin.x - ImGui::CalcTextSize(string.c_str()).x - ImGui::GetTextLineHeightWithSpacing(), lineMin.y); - toastMessages.emplace_back(string, toastMessagePosition, endTimerMax, endTimerMax); - } - } - else - { - endTimer--; - if (endTimer <= 0) - { - challenge = queuedChallenge; - tryValue = challenge.tryValue; - isActive = true; - isGameOver = false; - } - } - - for (int i = 0; i < (int)toastMessages.size(); i++) - { - auto& toastMessage = toastMessages[i]; - - toastMessage.position.y -= TOAST_MESSAGE_SPEED; - - auto color = ImGui::GetStyleColorVec4(ImGuiCol_Text); - color.w = ((float)toastMessage.time / toastMessage.timeMax); - - drawList->AddText(toastMessage.position, ImGui::GetColorU32(color), toastMessage.message.c_str()); - - toastMessage.time--; - - if (toastMessage.time <= 0) toastMessages.erase(toastMessages.begin() + i--); - } - - for (int i = 0; i < (int)toastItems.size(); i++) - { - auto& texture = resources.anm2s[anm2::ITEMS].content.spritesheets.at(0).texture; - auto& toastItem = toastItems[i]; - auto& type = toastItem.type; - - auto columns = (int)(texture.size.x / ITEM_SIZE.x); - auto crop = vec2(type % columns, type / columns) * ITEM_SIZE; - auto uvMin = imgui::to_imvec2(crop / vec2(texture.size)); - auto uvMax = imgui::to_imvec2((crop + ITEM_SIZE) / vec2(texture.size)); - - auto min = ImVec2(toastItem.position.x - (ITEM_SIZE.x * 0.5f), toastItem.position.y - (ITEM_SIZE.y * 0.5f)); - auto max = ImVec2(toastItem.position.x + (ITEM_SIZE.x * 0.5f), toastItem.position.y + (ITEM_SIZE.y * 0.5f)); - - drawList->AddImage(texture.id, min, max, uvMin, uvMax); - - toastItem.velocityY += Item::GRAVITY; - toastItem.position.y += toastItem.velocityY; - if (toastItem.position.y > position.y + size.y + ITEM_SIZE.y) toastItems.erase(toastItems.begin() + i--); - } - } -} \ No newline at end of file diff --git a/src/window/play.hpp b/src/window/play.hpp deleted file mode 100644 index adc9f52..0000000 --- a/src/window/play.hpp +++ /dev/null @@ -1,153 +0,0 @@ -#pragma once - -#include "../character.h" -#include "../game_data.h" -#include "../resources.h" - -#include "inventory.h" -#include "text.h" - -#include - -namespace game::window -{ - class Play - { - - static constexpr ImVec4 LINE_COLOR = ImVec4(1, 1, 1, 1); - static constexpr ImVec4 RECT_COLOR = ImVec4(0, 1, 0, 1); - static constexpr ImVec4 BG_COLOR = ImVec4(0, 1, 0, 0.1); - static constexpr ImVec4 PERFECT_COLOR = ImVec4(1, 1, 1, 0.75); - static constexpr auto LINE_HEIGHT = 2.0f; - static constexpr auto LINE_WIDTH_BONUS = 10.0f; - - static constexpr auto RANGE_BASE = 0.75f; - static constexpr auto RANGE_MIN = 0.10f; - static constexpr auto RANGE_SCORE_BONUS = 0.0005f; - - static constexpr auto SPEED_BASE = 0.005f; - static constexpr auto SPEED_MAX = 0.075f; - static constexpr auto SPEED_SCORE_BONUS = 0.000025f; - - static constexpr auto EXPONENTIAL_LEVEL_MIN = 3; - static constexpr auto EXPONENTIAL_CHANCE_BASE = 0.25f; - static constexpr auto RANGE_AREA_COUNT = 5; - static constexpr auto BONUS_RANGE_CHANCE_BASE = 25.0f; - - static constexpr auto END_TIMER_MAX = 30; - static constexpr auto END_TIMER_MISS_MAX = 90; - - static constexpr auto HIGH_SCORE_BIG = 999; - - static constexpr auto TOAST_MESSAGE_SPEED = 1.0f; - - static constexpr auto REWARD_SCORE_BONUS = 0.01f; - static constexpr auto REWARD_GRADE_BONUS = 0.05f; - static constexpr auto REWARD_LEVEL_BONUS = 0.25f; - - static constexpr auto REWARD_GRADE_CHANCE_BONUS = 1.0f; - static constexpr auto REWARD_LEVEL_CHANCE_BONUS = 1.0f; - - static constexpr auto ITEM_SIZE = glm::vec2(48.0f, 48.0f); - - public: -#define GRADES \ - X(MISS, "Miss!", "Misses", 0, -0.05f) \ - X(OK, "OK", "OKs", 1, 0.40f) \ - X(GOOD, "Good", "Goods", 2, 0.65f) \ - X(GREAT, "Great", "Greats", 3, 0.85f) \ - X(EXCELLENT, "Excellent!", "Excellents", 4, 0.95f) \ - X(PERFECT, "PERFECT!", "Perfects", 5, 1.00f) - - enum Grade - { -#define X(symbol, name, nameStats, value, weight) symbol, - GRADES -#undef X - GRADE_COUNT - }; - - static constexpr const char* GRADE_STRINGS[] = { -#define X(symbol, name, nameStats, value, weight) name, - GRADES -#undef X - }; - - static constexpr const char* GRADE_STATS_STRINGS[] = { -#define X(symbol, name, nameStats, value, weight) nameStats, - GRADES -#undef X - }; - - static constexpr float GRADE_WEIGHTS[] = { -#define X(symbol, name, nameStats, value, weight) weight, - GRADES -#undef X - }; - - static constexpr int GRADE_VALUES[] = { -#define X(symbol, name, nameStats, value, weight) value, - GRADES -#undef X - }; - -#undef GRADES - - struct Range - { - float min{}; - float max{}; - }; - - struct Challenge - { - Range range{}; - float speed{}; - float tryValue{}; - int level{}; - }; - - struct ToastMessage - { - std::string message{}; - ImVec2 position; - int time{}; - int timeMax{}; - }; - - struct ToastItem - { - Item::Type type{}; - ImVec2 position; - float velocityY; - }; - - Challenge challenge{}; - Challenge queuedChallenge{}; - float tryValue{}; - - int score{}; - int combo{}; - int comboBest{}; - int highScore{}; - int highScoreStart{}; - int endTimer{}; - int endTimerMax{}; - bool isActive{true}; - bool isHighScoreBigAchieved{false}; - bool isHighScoreAchieved{false}; - bool isGameOver{}; - - int totalPlays{}; - - std::unordered_map gradeCounts{}; - - std::vector toastMessages{}; - std::vector toastItems{}; - - Play(); - Challenge challenge_generate(int); - void update(Resources&, Character&, Inventory&, GameData&, Text&); - float accuracy_score_get(); - }; -} diff --git a/src/window/stats.cpp b/src/window/stats.cpp deleted file mode 100644 index 6a4c034..0000000 --- a/src/window/stats.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "stats.h" -#include - -using namespace game::resource; - -namespace game::window -{ - void Stats::update(Resources& resources, GameData& gameData, Play& play, Character& character) - { - ImGui::PushFont(resources.font.get(), Font::BIG); - ImGui::Text("Snivy"); - ImGui::PopFont(); - - ImGui::Separator(); - - auto& system = gameData.measurementSystem; - auto weight = character.weight_get(system); - auto weightUnit = system == MeasurementSystem::IMPERIAL ? "lbs" : "kg"; - - ImGui::Text("Weight: %0.2f %s (Stage: %i)", weight, weightUnit, character.weightStage + 1); - ImGui::Text("Capacity: %0.0f (Max: %0.0f)", character.capacity, character.max_capacity()); - ImGui::Text("Digestion Rate: %0.2f%%/sec", character.digestion_rate_second_get()); - ImGui::Text("Eating Speed: %0.2fx", character.eatSpeedMultiplier); - - ImGui::SeparatorText("Totals"); - - ImGui::Text("Total Calories Consumed: %0.0f", character.totalCaloriesConsumed); - - ImGui::Text("Total Weight Gained: %0.2f %s", - system == MeasurementSystem::IMPERIAL ? character.totalWeightGained * KG_TO_LB - : character.totalWeightGained, - weightUnit); - ImGui::Text("Food Items Eaten: %i", character.foodItemsEaten); - - ImGui::SeparatorText("Play"); - - ImGui::Text("Best: %i pts (%ix)", play.highScore, play.comboBest); - ImGui::Text("Total Plays: %i", play.totalPlays); - - for (int i = 0; i < Play::GRADE_COUNT; i++) - { - auto& value = play.gradeCounts[(Play::Grade)i]; - auto string = std::format("{}", Play::GRADE_STATS_STRINGS[i]); - ImGui::Text("%s: %i", string.c_str(), value); - } - - ImGui::Text("Score: %0.2f%%", play.accuracy_score_get()); - } -} diff --git a/src/window/stats.hpp b/src/window/stats.hpp deleted file mode 100644 index e9b7cae..0000000 --- a/src/window/stats.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include "../character.h" -#include "../game_data.h" -#include "../resources.h" - -#include "play.h" - -#include - -namespace game::window -{ - class Stats - { - public: - void update(Resources&, GameData&, Play&, Character&); - }; -} diff --git a/src/window/text.cpp b/src/window/text.cpp deleted file mode 100644 index db5b43c..0000000 --- a/src/window/text.cpp +++ /dev/null @@ -1,351 +0,0 @@ -#include "text.h" - -#include - -#include -#include -#include - -#include "../util/imgui_.h" - -#include "../util/math_.h" - -using namespace game::util; - -namespace game::window -{ - constexpr auto TEXT_COLOR_DEFAULT = ImVec4(1, 1, 1, 1); - namespace - { - int utf8_next_len(const char* text, const char* end) - { - if (text >= end) return 0; - - const unsigned char lead = static_cast(*text); - int length = 1; - if (lead < 0x80) - length = 1; - else if ((lead >> 5) == 0x6) - length = 2; - else if ((lead >> 4) == 0xE) - length = 3; - else if ((lead >> 3) == 0x1E) - length = 4; - - if (text + length > end) return 1; - - for (int i = 1; i < length; ++i) - { - const unsigned char byte = static_cast(text[i]); - if ((byte & 0xC0) != 0x80) return 1; - } - - return length; - } - - int utf8_count_chars(std::string_view text) - { - const char* it = text.data(); - const char* end = it + text.size(); - int count = 0; - while (it < end) - { - int step = utf8_next_len(it, end); - if (step <= 0) break; - it += step; - ++count; - } - return count; - } - - const char* utf8_advance_chars(const char* text, const char* end, int count) - { - const char* it = text; - while (it < end && count > 0) - { - int step = utf8_next_len(it, end); - if (step <= 0) break; - it += step; - --count; - } - return it; - } - } - - void Text::set(resource::Dialogue::Entry* entry, Character& character) - { - if (!entry) return; - this->entry = entry; - this->flag = entry->flag; - - if (this->flag != resource::Dialogue::Entry::Flag::NONE) this->isFlagActivated = true; - isFinished = false; - index = 0; - - if (!entry->animations.empty()) - { - for (auto& animation : entry->animations) - { - if (animation.at == -1) - { - character.play(character.animation_name_convert(animation.name)); - character.blink(); - break; - } - } - } - - character.talk(); - } - - void Text::set_random(std::vector& dialogueIDs, Resources& resources, Character& character) - { - if (dialogueIDs.empty()) return; - set(resources.dialogue.get((dialogueIDs)[math::random_roll(dialogueIDs.size())]), character); - } - - void Text::tick(Resources& resources, Character& character) - { - if (!entry || isFinished) return; - - index++; - - if (!entry->animations.empty()) - { - for (auto& animation : entry->animations) - { - if (animation.at == index) - { - character.play(character.animation_name_convert(animation.name)); - character.blink(); - break; - } - } - } - - if (index >= utf8_count_chars(entry->content)) isFinished = true; - } - - void Text::update(Resources& resources, Character& character, ImVec2 size, ImVec2 pos) - { - if (!entry) return; - auto& dialogue = resources.dialogue; - ImGui::SetNextWindowSize(size); - ImGui::SetNextWindowPos(pos); - - this->isFlagActivated = false; - - if (!entry) return; - - if (ImGui::Begin("##Text", nullptr, - ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove)) - { - auto isHovered = ImGui::IsWindowHovered(); - auto isMouse = ImGui::IsMouseReleased(ImGuiMouseButton_Left); - auto isSpace = ImGui::IsKeyReleased(ImGuiKey_Space); - auto isAdvance = (isHovered && (isMouse || isSpace)); - - if (ImGui::BeginTabBar("##Name")) - { - if (ImGui::BeginTabItem("Snivy")) ImGui::EndTabItem(); - ImGui::EndTabBar(); - } - - auto available = ImGui::GetContentRegionAvail(); - - auto font = resources.font.get(); - auto fontSize = resource::Font::BIG; - - ImGui::PushFont(font, fontSize); - - auto text = [&]() - { - auto content = entry ? std::string_view(entry->content) : "null"; - auto length = std::clamp(index, 0, utf8_count_chars(content)); - - if (length <= 0) - { - ImGui::Dummy(ImVec2(1.0f, ImGui::GetTextLineHeight())); - return; - } - - auto drawList = ImGui::GetWindowDrawList(); - auto startPos = ImGui::GetCursorScreenPos(); - auto wrapWidth = available.x <= 0.0f ? FLT_MAX : available.x; - auto lineHeight = ImGui::GetTextLineHeightWithSpacing(); - auto cursor = startPos; - auto maxX = startPos.x + wrapWidth; - - auto color_get = [&](int i) - { - if (!entry || entry->colors.empty()) return TEXT_COLOR_DEFAULT; - - for (auto& color : entry->colors) - if (i >= color.start && i <= color.end) - return ImVec4(color.value.r, color.value.g, color.value.b, color.value.a); - - return TEXT_COLOR_DEFAULT; - }; - - const char* textStart = content.data(); - const char* textEnd = textStart + content.size(); - const char* textLimit = utf8_advance_chars(textStart, textEnd, length); - - int i = 0; - for (const char* it = textStart; it < textLimit;) - { - int step = utf8_next_len(it, textLimit); - if (step <= 0) break; - - if (*it == '\n') - { - cursor.x = startPos.x; - cursor.y += lineHeight; - it += step; - ++i; - continue; - } - - if (*it == ' ') - { - auto glyphSize = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, it, it + step); - if (cursor.x != startPos.x && cursor.x + glyphSize.x > maxX) - { - cursor.x = startPos.x; - cursor.y += lineHeight; - it += step; - ++i; - continue; - } - - if (cursor.x == startPos.x) - { - it += step; - ++i; - continue; - } - - drawList->AddText(font, fontSize, cursor, ImGui::GetColorU32(color_get(i)), it, it + step); - cursor.x += glyphSize.x; - it += step; - ++i; - continue; - } - - const char* wordStart = it; - const char* wordEnd = it; - float wordWidth = 0.0f; - int wordChars = 0; - - for (const char* wordIt = it; wordIt < textLimit;) - { - int wordStep = utf8_next_len(wordIt, textLimit); - if (wordStep <= 0) break; - if (*wordIt == '\n' || *wordIt == ' ') break; - - auto glyphSize = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, wordIt, wordIt + wordStep); - wordWidth += glyphSize.x; - wordIt += wordStep; - ++wordChars; - wordEnd = wordIt; - } - - if (cursor.x != startPos.x && cursor.x + wordWidth > maxX) - { - cursor.x = startPos.x; - cursor.y += lineHeight; - } - - for (const char* wordIt = wordStart; wordIt < wordEnd;) - { - int wordStep = utf8_next_len(wordIt, wordEnd); - if (wordStep <= 0) break; - - auto glyphSize = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, wordIt, wordIt + wordStep); - drawList->AddText(font, fontSize, cursor, ImGui::GetColorU32(color_get(i)), wordIt, wordIt + wordStep); - cursor.x += glyphSize.x; - wordIt += wordStep; - ++i; - } - - it = wordEnd; - } - - float layoutWidth = wrapWidth == FLT_MAX ? (cursor.x - startPos.x) : wrapWidth; - if (layoutWidth <= 0.0f) layoutWidth = 1.0f; - auto totalHeight = (cursor.y - startPos.y) + lineHeight; - ImGui::Dummy(ImVec2(layoutWidth, totalHeight)); - }; - - text(); - - if (entry) - { - if (isFinished) - { - character.talkOverride.isLoop = false; - - if (!entry->branches.empty()) - { - ImGui::SetCursorPos(ImVec2(ImGui::GetStyle().WindowPadding.x, available.y)); - auto buttonSize = imgui::widget_size_with_row_get(entry->branches.size()); - - for (auto& branch : entry->branches) - { - if (ImGui::Button(branch.content.c_str(), buttonSize)) - { - set(dialogue.get(branch.nextID), character); - resources.sound_play(audio::ADVANCE); - } - ImGui::SameLine(); - } - - if (isHovered && isSpace) - { - set(dialogue.get(entry->branches.front().nextID), character); - resources.sound_play(audio::ADVANCE); - } - } - else - { - if (entry->nextID != -1) - { - ImGui::SetCursorPos(ImVec2(available.x - ImGui::GetTextLineHeightWithSpacing(), - available.y - ImGui::GetStyle().WindowPadding.y)); - ImGui::Text("▶"); - - if (isAdvance) - { - resources.sound_play(audio::ADVANCE); - set(dialogue.get(entry->nextID), character); - } - } - } - } - else - { - if (isAdvance) - { - index = utf8_count_chars(entry->content); - isFinished = true; - - if (!entry->animations.empty()) - { - auto& animation = entry->animations.back(); - auto name = character.animation_name_convert(animation.name); - if (auto animationIndex = character.animation_index_get(name); animationIndex != character.animationIndex) - { - character.play(name); - character.blink(); - } - } - } - } - } - - ImGui::PopFont(); - }; - ImGui::End(); - } -} diff --git a/src/window/text.hpp b/src/window/text.hpp deleted file mode 100644 index 0c096b0..0000000 --- a/src/window/text.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include "../character.h" -#include "../resources.h" -#include "imgui.h" - -namespace game::window -{ - class Text - { - resource::Dialogue::Entry* entry{}; - int index{}; - bool isFinished{}; - - public: - resource::Dialogue::Entry::Flag flag{}; - - bool isFlagActivated{}; - - void set(resource::Dialogue::Entry*, Character&); - void set_random(std::vector&, Resources&, Character&); - void tick(Resources&, Character&); - void update(Resources&, Character&, ImVec2, ImVec2); - }; -} \ No newline at end of file