From 7bffcded09b9574f54710b2198eb243531229a52 Mon Sep 17 00:00:00 2001 From: Alexis Maiquez Date: Sat, 10 May 2025 19:34:59 +0200 Subject: [PATCH] feat: make custom version of glslang to improve shader compatibility + random improvements (#291) * feat: added glslang and spirv-core for handling shaders, should provide better results than current systems * fix: brought back proper include placement, should fix some shaders not working * chore: dial down required version to 330 * fix: crash when taking screenshot * fix: use glReadnPixels for X11 copying to be more memory safe * chore: reverted part of last commit * chore: delay initialization of browser until it's used once * chore: do not initialize web browser unless explicitly needed * chore: cleanup filesystem functions to use containers directly * chore: memory cleanup fixes * chore: fix glReadPixels for older opengl versions * chore: remove shader patches as they shouldn't be needed anymore * chore: initialise variables * chore: update deps, actions and readme * chore: make use of custon glslang and SPIRV-Cross * Revert "chore: update deps, actions and readme" This reverts commit c3fbc9340b73bf705884b7e37c35727ba02cd7f1. * chore: update actions to include submodules * chore: do not depend on SPIRV-Tools * fix: added log10 macro * feat: update to latest glslang (swizzle and vec2/vec3/vec4 implicit casting to float) * revert: delayed initialization of cef was causing issues, reverted * chore: re-organized web wallpaper support to use custom scheme and better handle multiprocessing * chore: make use of external repos for all deps instead of copying things manually and more cleanup work * chore: wrong include file used in CGLSLContext.cpp * chore: fix wayland generation folder not being present * feat: somewhat support TEXB0004 * chore: improve function call matching and fallback to more lax method if no function is found * chore: changed shader compilation slightly so they're passed onto glsl just once * feat: swap android's fft implementation (which wasn't right) with kissfft's and fix update frequency issues * chore: added missing dependency * chore: added missing dep to PKGBUILD * feat: add testing tools to run over all backgrounds and getting output data * chore: jail CDirectory to the basepath and prevent accessing data outside of the main directory * chore: process script now scales the previews so the html file is not too big * chore: add showcase gallery to the README.md * chore: update README * chore: some readability improvements on code * chore: fix segfault after code cleanup * chore: make use of std::filesystem::canonical instead of basepath and slight typing changes on texture objects * chore: fix path detection being wrong, make use of std::filesystem::path on CContainers * chore: cleanup of the core part of the project * chore: bring back std::move and make some methods const where it makes sense * feat: added a pretty printer for easier debug and comparison between different versions of linux-wallpaperengine * chore: refactored shader compilation code once more to be easier to follow and fixed the longstanding bug of #include not being added in the right place * chore: more debug info for the pretty printer * fix: some textures applied were not the right ones * chore: properly set combos based on textures * feat: take into account project properties for shader values feat: proper parsing of combo values in shaders fix: shader units weren't linked as they should chore: more support for detecting shader things automatically * fix: blending mode for passes using the wrong value fix: shader uniforms from project properties should now be taken into account * chore: use ubuntu 22 and ubuntu 24 as builders, ubuntu 20 is retired * chore: use ubuntu 22 and ubuntu 24 as builders, ubuntu 20 is retired * chore: hopefully fix github actions build * refactor: simplified working with properties, constants and shader variables * chore: remove a couple of todos that aren't needed anymore * chore: simplify the texture detection a little bit, still work left to do * fix: regression on texture setup not working properly * fix: filenames with dots were not being handled properly * chore: remove some uselesss messages * chore: fixed std::string json values not casting anything to it as it was assumed * fix: null user value for constants means it cannot be modified by the user * chore: remove exception when a shader constant uses a non-existant property * fix: angles can be an user setting too, also added detection for animation frames to show a warning * fix: ensure variable information is not commented out by a line comment * fix: shader includes weren't being processed properly * chore: update to latest glslang and SPIRV-Cross to support non-integer array indices * chore: make use of auto where it made sense * feat: make use of in/out promotion on glslang-WallpaperEngine feat: use glslang-WallpaperEngine linkin process as an extra validation * chore: improve scripts for running the app * chore: hide background structure dump behind a command-line switch * chore: rewritten bloom effect as a json object inside C++ so it's easier to follow * chore: removed deprecated parameters and switched to argparse instead of getopt fix: clamping mode wasn't applied by background properly, only globally * chore: removed help prompt from the output unless actually required * fix: web subprocesses weren't launching due to parameter's parsing, temporal fix * feat: added material command copy support * feat: do not initialize some subsystems if they're disabled or not used by backgrounds * chore: ignore type in combos as only seems to be used in the editor * chore: update to latest glslang-WallpaperEngine changes * chore: delete uniforms if they already exist before setting * chore: more cleanup and fixes * chore: more cleanup and fixes * chore: more cleanup and fixes * chore: update file functions to make use of shared_ptr/unique_ptr instead of copying things around * chore: more changes to unique_ptr and shared_ptr * chore: more changes to unique_ptr and shared_ptr * chore: more changes to unique_ptr and shared_ptr feat: improved render initialization process to make it easier and simpler to add new drivers (no more #ifdef in CWallpaperApplication.cpp) * chore: change all is/as castings to use typeid so no string comparison takes place * chore: more cleanup, default initialization of values wherever possible * chore: moved more things to std::unique_ptr and std::shared_ptr * chore: moved more things to std::unique_ptr and std::shared_ptr * fix: browser context usage crashed the app * chore: the setting controls fullscreen detection creation the same way audio works * fix: ensure that at least one frame is rendered before detecting fullscreen windows * chore: slight changes to output and documentation to properly reflect current build configuration * chore: fix mipmap texture creation * chore: fix pass uniforms not taking into account fragment shader's uniforms chore: keep processed code in the shader sent to opengl so it appears on RenderDoc * chore: formating issues by codefactor * chore: do not use new to allocate the pretty printer * fix: strchr wasn't properly done for window geometry * chore: add recording mode for status page generation * chore: update .gitignore * chore: update script to make use of video generation instead of the old python scripts * chore: also copy project.json so it can be used on the site too * fix: regression on invisible images not being rendered * feat: add option to disable camera parallax * chore: add the reversing tools I have locally * chore: mention some of the common issues in the README.md * chore: take submodules into account for archlinux * chore: missed cd "$pkgname" in arch's prepare step --- .github/workflows/arch.yml | 4 +- .github/workflows/cmake.yml | 32 +- .gitignore | 2 +- .gitmodules | 28 + CMakeLists.txt | 298 +- CMakeModules/DownloadCEF.cmake | 80 + CMakeModules/FindCEF.cmake | 39 - CMakeModules/cef_macros.cmake | 387 - CMakeModules/cef_variables.cmake | 582 -- README.md | 290 +- docs/images/screenshot_folder.png | Bin 34650 -> 0 bytes docs/images/zip.png | Bin 118882 -> 0 bytes include/nlohmann/adl_serializer.hpp | 45 - .../nlohmann/detail/conversions/from_json.hpp | 378 - .../nlohmann/detail/conversions/to_chars.hpp | 1095 --- .../nlohmann/detail/conversions/to_json.hpp | 357 - include/nlohmann/detail/exceptions.hpp | 330 - .../nlohmann/detail/input/binary_reader.hpp | 1693 ---- .../nlohmann/detail/input/input_adapters.hpp | 374 - include/nlohmann/detail/input/json_sax.hpp | 687 -- include/nlohmann/detail/input/lexer.hpp | 1329 --- include/nlohmann/detail/input/parser.hpp | 486 - .../detail/iterators/internal_iterator.hpp | 25 - .../nlohmann/detail/iterators/iter_impl.hpp | 614 -- .../detail/iterators/iteration_proxy.hpp | 128 - .../iterators/json_reverse_iterator.hpp | 119 - .../detail/iterators/primitive_iterator.hpp | 120 - include/nlohmann/detail/json_pointer.hpp | 696 -- include/nlohmann/detail/json_ref.hpp | 63 - include/nlohmann/detail/macro_scope.hpp | 117 - include/nlohmann/detail/macro_unscope.hpp | 22 - include/nlohmann/detail/meta.hpp | 278 - .../nlohmann/detail/output/binary_writer.hpp | 949 -- .../detail/output/output_adapters.hpp | 113 - include/nlohmann/detail/output/serializer.hpp | 631 -- include/nlohmann/detail/value_t.hpp | 76 - include/nlohmann/json.hpp | 7723 ---------------- include/nlohmann/json_fwd.hpp | 64 - include/stb_image.h | 7988 ----------------- include/stb_image_write.h | 1724 ---- main.cpp | 47 - packaging/archlinux/PKGBUILD | 6 + share/patches/lens_flare_sun.frag.json | 14 - share/patches/vhstest.vert.json | 13 - share/patches/water_caustics.frag.json | 16 - src/External/Android/fft.cpp | 162 - src/External/Android/fft.h | 11 - src/External/MimeTypes | 1 + src/External/SPIRV-Cross-WallpaperEngine | 1 + src/External/argparse | 1 + src/External/glslang-WallpaperEngine | 1 + src/External/json | 1 + src/External/kissfft | 1 + src/External/stb | 1 + src/Steam/FileSystem/FileSystem.cpp | 17 +- .../Application/CApplicationContext.cpp | 488 +- .../Application/CApplicationContext.h | 63 +- .../Application/CApplicationState.cpp | 1 - .../Application/CWallpaperApplication.cpp | 541 +- .../Application/CWallpaperApplication.h | 64 +- .../Assets/CAssetLoadException.h | 2 +- .../Assets/CCombinedContainer.cpp | 14 +- .../Assets/CCombinedContainer.h | 10 +- src/WallpaperEngine/Assets/CContainer.cpp | 55 +- src/WallpaperEngine/Assets/CContainer.h | 18 +- src/WallpaperEngine/Assets/CDirectory.cpp | 114 +- src/WallpaperEngine/Assets/CDirectory.h | 12 +- src/WallpaperEngine/Assets/CFileEntry.h | 14 +- src/WallpaperEngine/Assets/CPackage.cpp | 21 +- src/WallpaperEngine/Assets/CPackage.h | 6 +- .../Assets/CPackageLoadException.h | 2 +- src/WallpaperEngine/Assets/CTexture.cpp | 292 +- src/WallpaperEngine/Assets/CTexture.h | 100 +- .../Assets/CVirtualContainer.cpp | 29 +- .../Assets/CVirtualContainer.h | 27 +- src/WallpaperEngine/Assets/ITexture.h | 38 +- src/WallpaperEngine/Audio/CAudioStream.cpp | 40 +- src/WallpaperEngine/Audio/CAudioStream.h | 38 +- .../Audio/Drivers/CAudioDriver.cpp | 6 +- .../Audio/Drivers/CAudioDriver.h | 5 +- .../Audio/Drivers/CSDLAudioDriver.cpp | 28 +- .../Audio/Drivers/CSDLAudioDriver.h | 13 +- .../Detectors/CAudioPlayingDetector.cpp | 6 +- .../Drivers/Detectors/CAudioPlayingDetector.h | 11 +- .../Detectors/CPulseAudioPlayingDetector.cpp | 7 +- .../Detectors/CPulseAudioPlayingDetector.h | 10 +- .../Recorders/CPulseAudioPlaybackRecorder.cpp | 157 +- .../Recorders/CPulseAudioPlaybackRecorder.h | 42 +- src/WallpaperEngine/Core/CObject.cpp | 116 +- src/WallpaperEngine/Core/CObject.h | 64 +- src/WallpaperEngine/Core/CProject.cpp | 128 +- src/WallpaperEngine/Core/CProject.h | 42 +- src/WallpaperEngine/Core/CWallpaper.cpp | 5 +- src/WallpaperEngine/Core/CWallpaper.h | 34 +- src/WallpaperEngine/Core/Core.cpp | 465 +- src/WallpaperEngine/Core/Core.h | 32 +- .../Core/DynamicValues/CDynamicValue.cpp | 205 + .../Core/DynamicValues/CDynamicValue.h | 68 + src/WallpaperEngine/Core/Objects/CEffect.cpp | 385 +- src/WallpaperEngine/Core/Objects/CEffect.h | 64 +- src/WallpaperEngine/Core/Objects/CImage.cpp | 115 +- src/WallpaperEngine/Core/Objects/CImage.h | 54 +- .../Core/Objects/CParticle.cpp | 77 +- src/WallpaperEngine/Core/Objects/CParticle.h | 51 +- src/WallpaperEngine/Core/Objects/CSound.cpp | 53 +- src/WallpaperEngine/Core/Objects/CSound.h | 31 +- .../Core/Objects/Effects/CBind.cpp | 14 +- .../Core/Objects/Effects/CBind.h | 11 +- .../Core/Objects/Effects/CFBO.cpp | 16 +- .../Core/Objects/Effects/CFBO.h | 13 +- .../Effects/Constants/CShaderConstant.cpp | 8 +- .../Effects/Constants/CShaderConstant.h | 35 +- .../Constants/CShaderConstantFloat.cpp | 10 +- .../Effects/Constants/CShaderConstantFloat.h | 14 +- .../Constants/CShaderConstantInteger.cpp | 10 +- .../Constants/CShaderConstantInteger.h | 14 +- .../Constants/CShaderConstantProperty.cpp | 12 + .../Constants/CShaderConstantProperty.h | 20 + .../Constants/CShaderConstantVector2.cpp | 17 +- .../Constants/CShaderConstantVector2.h | 14 +- .../Constants/CShaderConstantVector3.cpp | 19 +- .../Constants/CShaderConstantVector3.h | 14 +- .../Constants/CShaderConstantVector4.cpp | 21 +- .../Constants/CShaderConstantVector4.h | 14 +- .../Core/Objects/Images/CMaterial.cpp | 108 +- .../Core/Objects/Images/CMaterial.h | 67 +- .../Core/Objects/Images/Materials/CPass.cpp | 99 +- .../Core/Objects/Images/Materials/CPass.h | 66 +- .../Core/Objects/Particles/CControlPoint.cpp | 33 +- .../Core/Objects/Particles/CControlPoint.h | 19 +- .../Core/Objects/Particles/CEmitter.cpp | 33 +- .../Core/Objects/Particles/CEmitter.h | 21 +- .../Core/Objects/Particles/CInitializer.cpp | 33 +- .../Core/Objects/Particles/CInitializer.h | 28 +- .../Particles/Initializers/CAlphaRandom.cpp | 15 +- .../Particles/Initializers/CAlphaRandom.h | 6 +- .../Initializers/CAngularVelocityRandom.cpp | 16 +- .../Initializers/CAngularVelocityRandom.h | 6 +- .../Particles/Initializers/CColorRandom.cpp | 16 +- .../Particles/Initializers/CColorRandom.h | 6 +- .../Initializers/CLifeTimeRandom.cpp | 15 +- .../Particles/Initializers/CLifeTimeRandom.h | 6 +- .../Initializers/CRotationRandom.cpp | 6 +- .../Particles/Initializers/CRotationRandom.h | 14 +- .../Particles/Initializers/CSizeRandom.cpp | 15 +- .../Particles/Initializers/CSizeRandom.h | 6 +- .../Initializers/CTurbulentVelocityRandom.cpp | 40 +- .../Initializers/CTurbulentVelocityRandom.h | 22 +- .../Initializers/CVelocityRandom.cpp | 16 +- .../Particles/Initializers/CVelocityRandom.h | 6 +- .../Core/Projects/CProperty.cpp | 38 +- src/WallpaperEngine/Core/Projects/CProperty.h | 57 +- .../Core/Projects/CPropertyBoolean.cpp | 30 +- .../Core/Projects/CPropertyBoolean.h | 19 +- .../Core/Projects/CPropertyColor.cpp | 30 +- .../Core/Projects/CPropertyColor.h | 16 +- .../Core/Projects/CPropertyCombo.cpp | 91 +- .../Core/Projects/CPropertyCombo.h | 35 +- .../Core/Projects/CPropertySlider.cpp | 47 +- .../Core/Projects/CPropertySlider.h | 28 +- .../Core/Projects/CPropertyText.cpp | 17 +- .../Core/Projects/CPropertyText.h | 10 +- src/WallpaperEngine/Core/Scenes/CCamera.cpp | 18 +- src/WallpaperEngine/Core/Scenes/CCamera.h | 8 +- .../Core/Scenes/CProjection.cpp | 16 +- src/WallpaperEngine/Core/Scenes/CProjection.h | 13 +- .../Core/UserSettings/CUserSettingBoolean.cpp | 98 +- .../Core/UserSettings/CUserSettingBoolean.h | 21 +- .../Core/UserSettings/CUserSettingFloat.cpp | 97 +- .../Core/UserSettings/CUserSettingFloat.h | 24 +- .../Core/UserSettings/CUserSettingValue.cpp | 2 - .../Core/UserSettings/CUserSettingValue.h | 33 +- .../Core/UserSettings/CUserSettingVector3.cpp | 94 +- .../Core/UserSettings/CUserSettingVector3.h | 22 +- .../Core/Wallpapers/CScene.cpp | 129 +- src/WallpaperEngine/Core/Wallpapers/CScene.h | 114 +- .../Core/Wallpapers/CVideo.cpp | 11 +- src/WallpaperEngine/Core/Wallpapers/CVideo.h | 8 +- src/WallpaperEngine/Core/Wallpapers/CWeb.cpp | 10 +- src/WallpaperEngine/Core/Wallpapers/CWeb.h | 24 +- src/WallpaperEngine/FileSystem/FileSystem.cpp | 24 - src/WallpaperEngine/FileSystem/FileSystem.h | 21 - src/WallpaperEngine/Input/CInputContext.cpp | 6 +- src/WallpaperEngine/Input/CInputContext.h | 4 +- .../Input/Drivers/CGLFWMouseInput.cpp | 12 +- .../Input/Drivers/CGLFWMouseInput.h | 12 +- .../Input/Drivers/CWaylandMouseInput.cpp | 22 +- .../Input/Drivers/CWaylandMouseInput.h | 12 +- src/WallpaperEngine/Logging/CLog.cpp | 8 +- src/WallpaperEngine/Logging/CLog.h | 60 +- .../PrettyPrinter/CPrettyPrinter.cpp | 403 + .../PrettyPrinter/CPrettyPrinter.h | 108 + src/WallpaperEngine/Render/CCamera.cpp | 9 +- src/WallpaperEngine/Render/CCamera.h | 28 +- src/WallpaperEngine/Render/CFBO.cpp | 34 +- src/WallpaperEngine/Render/CFBO.h | 46 +- src/WallpaperEngine/Render/CObject.cpp | 10 +- src/WallpaperEngine/Render/CObject.h | 42 +- src/WallpaperEngine/Render/CRenderContext.cpp | 16 +- src/WallpaperEngine/Render/CRenderContext.h | 14 +- src/WallpaperEngine/Render/CTextureCache.cpp | 6 +- src/WallpaperEngine/Render/CTextureCache.h | 7 +- src/WallpaperEngine/Render/CWallpaper.cpp | 82 +- src/WallpaperEngine/Render/CWallpaper.h | 85 +- .../Render/CWallpaperState.cpp | 41 + src/WallpaperEngine/Render/CWallpaperState.h | 106 +- .../Render/Drivers/CGLFWOpenGLDriver.cpp | 63 +- .../Render/Drivers/CGLFWOpenGLDriver.h | 10 +- .../Render/Drivers/CVideoDriver.cpp | 11 +- .../Render/Drivers/CVideoDriver.h | 17 +- .../Render/Drivers/CVideoFactories.cpp | 93 + .../Render/Drivers/CVideoFactories.h | 72 + .../Render/Drivers/CWaylandOpenGLDriver.cpp | 23 +- .../Render/Drivers/CWaylandOpenGLDriver.h | 10 +- .../Detectors/CWaylandFullScreenDetector.cpp | 11 + .../Detectors/CWaylandFullScreenDetector.h | 4 +- .../Detectors/CX11FullScreenDetector.cpp | 36 +- .../Detectors/CX11FullScreenDetector.h | 14 +- .../Drivers/Output/CGLFWWindowOutput.cpp | 4 + .../Render/Drivers/Output/CGLFWWindowOutput.h | 1 + .../Render/Drivers/Output/COutput.cpp | 2 - .../Render/Drivers/Output/COutput.h | 7 +- .../Render/Drivers/Output/COutputViewport.cpp | 2 - .../Render/Drivers/Output/COutputViewport.h | 2 +- .../Render/Drivers/Output/CWaylandOutput.cpp | 7 +- .../Render/Drivers/Output/CWaylandOutput.h | 3 +- .../Drivers/Output/CWaylandOutputViewport.cpp | 9 +- .../Drivers/Output/CWaylandOutputViewport.h | 6 +- .../Render/Drivers/Output/CX11Output.cpp | 20 +- .../Render/Drivers/Output/CX11Output.h | 10 +- .../Render/Objects/CEffect.cpp | 39 +- src/WallpaperEngine/Render/Objects/CEffect.h | 29 +- src/WallpaperEngine/Render/Objects/CImage.cpp | 128 +- src/WallpaperEngine/Render/Objects/CImage.h | 71 +- src/WallpaperEngine/Render/Objects/CSound.cpp | 17 +- src/WallpaperEngine/Render/Objects/CSound.h | 15 +- .../Render/Objects/Effects/CMaterial.h | 2 +- .../Render/Objects/Effects/CPass.cpp | 545 +- .../Render/Objects/Effects/CPass.h | 61 +- .../Render/Shaders/CGLSLContext.cpp | 198 + .../Render/Shaders/CGLSLContext.h | 30 + .../Render/Shaders/CShader.cpp | 82 + src/WallpaperEngine/Render/Shaders/CShader.h | 102 + .../Render/Shaders/CShaderUnit.cpp | 570 ++ .../Render/Shaders/CShaderUnit.h | 156 + .../Render/Shaders/Compiler.cpp | 771 -- src/WallpaperEngine/Render/Shaders/Compiler.h | 267 - .../Shaders/Variables/CShaderVariable.cpp | 19 - .../Shaders/Variables/CShaderVariable.h | 45 +- .../Variables/CShaderVariableFloat.cpp | 23 +- .../Shaders/Variables/CShaderVariableFloat.h | 10 - .../Variables/CShaderVariableInteger.cpp | 24 +- .../Variables/CShaderVariableInteger.h | 12 +- .../Variables/CShaderVariableVector2.cpp | 25 +- .../Variables/CShaderVariableVector2.h | 12 +- .../Variables/CShaderVariableVector3.cpp | 22 +- .../Variables/CShaderVariableVector3.h | 10 - .../Variables/CShaderVariableVector4.cpp | 22 +- .../Variables/CShaderVariableVector4.h | 10 - .../Render/Wallpapers/CScene.cpp | 34 +- .../Render/Wallpapers/CScene.h | 44 +- .../Render/Wallpapers/CVideo.cpp | 24 +- .../Render/Wallpapers/CVideo.h | 24 +- .../Render/Wallpapers/CWeb.cpp | 70 +- src/WallpaperEngine/Render/Wallpapers/CWeb.h | 147 +- .../WebBrowser/CEF/CBrowserApp.cpp | 56 + .../WebBrowser/CEF/CBrowserApp.h | 30 + .../WebBrowser/CEF/CBrowserClient.cpp | 11 + .../WebBrowser/CEF/CBrowserClient.h | 21 + .../WebBrowser/CEF/CRenderHandler.cpp | 32 + .../WebBrowser/CEF/CRenderHandler.h | 41 + .../WebBrowser/CEF/CSubprocessApp.cpp | 29 + .../WebBrowser/CEF/CSubprocessApp.h | 28 + .../WebBrowser/CEF/CWPSchemeHandler.cpp | 101 + .../WebBrowser/CEF/CWPSchemeHandler.h | 47 + .../CEF/CWPSchemeHandlerFactory.cpp | 20 + .../WebBrowser/CEF/CWPSchemeHandlerFactory.h | 26 + .../WebBrowser/CWebBrowserContext.cpp | 97 +- .../WebBrowser/CWebBrowserContext.h | 23 +- src/common.h | 4 - src/main.cpp | 66 + src/recording.cpp | 193 + src/recording.h | 16 + tools/reversing/README.md | 14 + .../d3dcompiler_47/d3dcompiler_47_shim.sln | 31 + .../d3dcompiler_47_shim/Source.def | 4 + .../d3dcompiler_47_shim.vcxproj | 177 + .../d3dcompiler_47_shim/dllmain.cpp | 137 + .../d3dcompiler_47_shim/framework.h | 5 + .../d3dcompiler_47_shim/pch.cpp | 5 + .../d3dcompiler_47/d3dcompiler_47_shim/pch.h | 13 + tools/reversing/renderdoc.cap | 28 + tools/run-over-all-backgrounds.sh | 25 + 293 files changed, 8553 insertions(+), 34718 deletions(-) create mode 100644 .gitmodules delete mode 100644 CMakeModules/FindCEF.cmake delete mode 100644 CMakeModules/cef_macros.cmake delete mode 100644 CMakeModules/cef_variables.cmake delete mode 100644 docs/images/screenshot_folder.png delete mode 100644 docs/images/zip.png delete mode 100644 include/nlohmann/adl_serializer.hpp delete mode 100644 include/nlohmann/detail/conversions/from_json.hpp delete mode 100644 include/nlohmann/detail/conversions/to_chars.hpp delete mode 100644 include/nlohmann/detail/conversions/to_json.hpp delete mode 100644 include/nlohmann/detail/exceptions.hpp delete mode 100644 include/nlohmann/detail/input/binary_reader.hpp delete mode 100644 include/nlohmann/detail/input/input_adapters.hpp delete mode 100644 include/nlohmann/detail/input/json_sax.hpp delete mode 100644 include/nlohmann/detail/input/lexer.hpp delete mode 100644 include/nlohmann/detail/input/parser.hpp delete mode 100644 include/nlohmann/detail/iterators/internal_iterator.hpp delete mode 100644 include/nlohmann/detail/iterators/iter_impl.hpp delete mode 100644 include/nlohmann/detail/iterators/iteration_proxy.hpp delete mode 100644 include/nlohmann/detail/iterators/json_reverse_iterator.hpp delete mode 100644 include/nlohmann/detail/iterators/primitive_iterator.hpp delete mode 100644 include/nlohmann/detail/json_pointer.hpp delete mode 100644 include/nlohmann/detail/json_ref.hpp delete mode 100644 include/nlohmann/detail/macro_scope.hpp delete mode 100644 include/nlohmann/detail/macro_unscope.hpp delete mode 100644 include/nlohmann/detail/meta.hpp delete mode 100644 include/nlohmann/detail/output/binary_writer.hpp delete mode 100644 include/nlohmann/detail/output/output_adapters.hpp delete mode 100644 include/nlohmann/detail/output/serializer.hpp delete mode 100644 include/nlohmann/detail/value_t.hpp delete mode 100644 include/nlohmann/json.hpp delete mode 100644 include/nlohmann/json_fwd.hpp delete mode 100644 include/stb_image.h delete mode 100644 include/stb_image_write.h delete mode 100644 main.cpp delete mode 100644 share/patches/lens_flare_sun.frag.json delete mode 100644 share/patches/vhstest.vert.json delete mode 100644 share/patches/water_caustics.frag.json delete mode 100644 src/External/Android/fft.cpp delete mode 100644 src/External/Android/fft.h create mode 160000 src/External/MimeTypes create mode 160000 src/External/SPIRV-Cross-WallpaperEngine create mode 160000 src/External/argparse create mode 160000 src/External/glslang-WallpaperEngine create mode 160000 src/External/json create mode 160000 src/External/kissfft create mode 160000 src/External/stb delete mode 100644 src/WallpaperEngine/Application/CApplicationState.cpp create mode 100644 src/WallpaperEngine/Core/DynamicValues/CDynamicValue.cpp create mode 100644 src/WallpaperEngine/Core/DynamicValues/CDynamicValue.h create mode 100644 src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.cpp create mode 100644 src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.h delete mode 100644 src/WallpaperEngine/FileSystem/FileSystem.cpp delete mode 100644 src/WallpaperEngine/FileSystem/FileSystem.h create mode 100644 src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.cpp create mode 100644 src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.h create mode 100644 src/WallpaperEngine/Render/Drivers/CVideoFactories.cpp create mode 100644 src/WallpaperEngine/Render/Drivers/CVideoFactories.h create mode 100644 src/WallpaperEngine/Render/Shaders/CGLSLContext.cpp create mode 100644 src/WallpaperEngine/Render/Shaders/CGLSLContext.h create mode 100644 src/WallpaperEngine/Render/Shaders/CShader.cpp create mode 100644 src/WallpaperEngine/Render/Shaders/CShader.h create mode 100644 src/WallpaperEngine/Render/Shaders/CShaderUnit.cpp create mode 100644 src/WallpaperEngine/Render/Shaders/CShaderUnit.h delete mode 100644 src/WallpaperEngine/Render/Shaders/Compiler.cpp delete mode 100644 src/WallpaperEngine/Render/Shaders/Compiler.h create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.cpp create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.h create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.cpp create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.h create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.cpp create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.h create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.cpp create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.h create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.cpp create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.h create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.cpp create mode 100644 src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.h delete mode 100644 src/common.h create mode 100644 src/main.cpp create mode 100644 src/recording.cpp create mode 100644 src/recording.h create mode 100644 tools/reversing/README.md create mode 100644 tools/reversing/d3dcompiler_47/d3dcompiler_47_shim.sln create mode 100644 tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/Source.def create mode 100644 tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/d3dcompiler_47_shim.vcxproj create mode 100644 tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/dllmain.cpp create mode 100644 tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/framework.h create mode 100644 tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.cpp create mode 100644 tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.h create mode 100644 tools/reversing/renderdoc.cap create mode 100755 tools/run-over-all-backgrounds.sh diff --git a/.github/workflows/arch.yml b/.github/workflows/arch.yml index d57ed7e..f9d7ec6 100644 --- a/.github/workflows/arch.yml +++ b/.github/workflows/arch.yml @@ -14,8 +14,10 @@ jobs: - name: Checkout uses: actions/checkout@v2 + with: + submodules: true - - name: Publish parallel-disk-usage to the AUR + - name: Publish linux-wallpaperengine-git to the AUR uses: KSXGitHub/github-actions-deploy-aur@v2.7.2 with: pkgname: linux-wallpaperengine-git diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 63dd698..2f6fdb0 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -14,7 +14,7 @@ jobs: build-x11: strategy: matrix: - os: [ubuntu-22.04, ubuntu-20.04] + os: [ubuntu-22.04, ubuntu-24.04] # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. # You can convert this to a matrix build if you need cross-platform coverage. # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix @@ -22,9 +22,15 @@ jobs: steps: - uses: actions/checkout@v3 + with: + submodules: true - name: Install dependencies - run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 + if: matrix.os == 'ubuntu-22.04' + run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 libfftw3-dev + - name: Install dependencies + if: matrix.os == 'ubuntu-24.04' + run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev - name: Configure CMake # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. @@ -38,7 +44,7 @@ jobs: build-x11-wayland: strategy: matrix: - os: [ubuntu-22.04] + os: [ubuntu-22.04, ubuntu-24.04] # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. # You can convert this to a matrix build if you need cross-platform coverage. # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix @@ -46,9 +52,16 @@ jobs: steps: - uses: actions/checkout@v3 + with: + submodules: true - name: Install dependencies - run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 wayland-scanner++ wayland-protocols libwayland-dev + if: matrix.os == 'ubuntu-22.04' + run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 libfftw3-dev wayland-scanner++ wayland-protocols libwayland-dev + + - name: Install dependencies + if: matrix.os == 'ubuntu-24.04' + run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev wayland-scanner++ wayland-protocols libwayland-dev - name: Configure CMake # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. @@ -62,7 +75,7 @@ jobs: build-wayland: strategy: matrix: - os: [ubuntu-22.04] + os: [ubuntu-22.04, ubuntu-24.04] # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. # You can convert this to a matrix build if you need cross-platform coverage. # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix @@ -70,9 +83,16 @@ jobs: steps: - uses: actions/checkout@v3 + with: + submodules: true - name: Install dependencies - run: sudo apt-get update && sudo apt-get -y install wayland-scanner++ wayland-protocols libwayland-dev libwayland-egl-backend-dev libglfw3-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libglm-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 + if: matrix.os == 'ubuntu-22.04' + run: sudo apt-get update && sudo apt-get -y install wayland-scanner++ wayland-protocols libwayland-dev libwayland-egl-backend-dev libglfw3-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libglm-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 libfftw3-dev + + - name: Install dependencies + if: matrix.os == 'ubuntu-24.04' + run: sudo apt-get update && sudo apt-get -y install wayland-scanner++ wayland-protocols libwayland-dev libwayland-egl-backend-dev libglfw3-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libglm-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev - name: Configure CMake # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. diff --git a/.gitignore b/.gitignore index 77b25b8..153df4b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -cmake-build-debug* +cmake-build-* .idea build/ .vscode/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..54a51c2 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,28 @@ +[submodule "src/External/glslang-WallpaperEngine"] + path = src/External/glslang-WallpaperEngine + url = https://github.com/Almamu/glslang-WallpaperEngine.git + branch = main +[submodule "src/External/SPIRV-Cross-WallpaperEngine"] + path = src/External/SPIRV-Cross-WallpaperEngine + url = https://github.com/Almamu/SPIRV-Cross-WallpaperEngine.git + branch = main +[submodule "src/External/stb"] + path = src/External/stb + url = https://github.com/nothings/stb.git + branch = master +[submodule "src/External/json"] + path = src/External/json + url = https://github.com/nlohmann/json.git + branch = develop +[submodule "src/External/MimeTypes"] + path = src/External/MimeTypes + url = https://github.com/lasselukkari/MimeTypes.git + branch = master +[submodule "src/External/kissfft"] + path = src/External/kissfft + url = https://github.com/mborgerding/kissfft.git + branch = master +[submodule "src/External/argparse"] + path = src/External/argparse + url = https://github.com/p-ranav/argparse.git + branch = master diff --git a/CMakeLists.txt b/CMakeLists.txt index 79dbaf2..d999b35 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,10 +10,12 @@ set_property(GLOBAL PROPERTY OS_FOLDERS ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules") set(OpenGL_GL_PREFERENCE "LEGACY") -set(DATADIR ${CMAKE_INSTALL_PREFIX}/share/${PROJECT_NAME}) -set(PATCHESDIR ${DATADIR}/patches/) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +if(NOT DEMOMODE) + set(DEMOMODE 0) +endif() + if(NOT ERRORONLY) set(ERRORONLY 0) endif() @@ -22,7 +24,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-narrowing") # if you're developing you might find this debug option useful for shader output, although RenderDoc is encouraged add_compile_definitions(ERRORONLY=${ERRORONLY}) -add_compile_definitions(DATADIR="${DATADIR}") +add_compile_definitions(DEMOMODE=${DEMOMODE}) find_package(X11) find_package(OpenGL REQUIRED) @@ -35,9 +37,14 @@ find_package(LZ4 REQUIRED) find_package(FFMPEG REQUIRED) find_package(PulseAudio REQUIRED) +set(ENABLE_OPT OFF) +set(SPIRV_CROSS_FORCE_PIC ON) +set(KISSFFT_TEST OFF) +set(KISSFFT_TOOLS OFF) + # Download CEF of specified version for current platform # Specify the CEF distribution version. -set(CEF_VERSION "120.1.10+g3ce3184+chromium-120.0.6099.129") +set(CEF_VERSION "135.0.17+gcbc1c5b+chromium-135.0.7049.52") # Determine the platform. if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin") if("${PROJECT_ARCH}" STREQUAL "arm64") @@ -87,47 +94,28 @@ elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") endif() message(STATUS "Using CEF for ${CMAKE_SYSTEM_NAME} - ${CEF_PLATFORM} (${CEF_ARCH_DETECTION})") include(DownloadCEF) -DownloadCEF("${CEF_PLATFORM}" "${CEF_VERSION}" "${CMAKE_SOURCE_DIR}/third_party/cef") +DownloadCEF("${CEF_PLATFORM}" "${CEF_VERSION}" "${CMAKE_CURRENT_BINARY_DIR}/cef") + +# add cef's cmake files to the lookup so we can use those directly +list(APPEND CMAKE_MODULE_PATH "${CEF_ROOT}/cmake") find_package(CEF REQUIRED) -set( - CMAKE_RUNTIME_OUTPUT_DIRECTORY - ${CMAKE_CURRENT_BINARY_DIR}/build - ) +# remove some switches that forbid us from using things that are commonplace in our codebase +list(REMOVE_ITEM CEF_CXX_COMPILER_FLAGS -fno-exceptions) +list(REMOVE_ITEM CEF_CXX_COMPILER_FLAGS -fno-rtti) +# remove the vulkan library from the files to copy so it doesn't fail after removing it +list(REMOVE_ITEM CEF_BINARY_FILES libvulkan.so.1) -set( - CMAKE_LIBRARY_OUTPUT_DIRECTORY - ${CMAKE_CURRENT_BINARY_DIR}/lib - ) - -set( - TARGET_OUTPUT_DIRECTORY - ${CMAKE_CURRENT_BINARY_DIR}/build - ) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/output) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib) +set(TARGET_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/output) add_subdirectory(${CEF_LIBCEF_DLL_WRAPPER_PATH} libcef_dll_wrapper) - -include_directories( - ${MPV_INCLUDE_DIR} - ${GLEW_INCLUDE_DIR} - ${LZ4_INCLUDE_DIR} - ${SDL2_INCLUDE_DIRS} - ${FFMPEG_INCLUDE_DIR} - ${PULSEAUDIO_INCLUDE_DIR} - src - ${CEF_INCLUDE_PATH} - ${CMAKE_SOURCE_DIR} - include) - - -add_library(ceflib SHARED IMPORTED) -set_target_properties(ceflib - PROPERTIES IMPORTED_LOCATION ${TARGET_OUTPUT_DIRECTORY}/libcef.so) - -ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}") -# SET_CEF_TARGET_OUT_DIR() -include_directories(${_CEF_ROOT}) +add_subdirectory(src/External/glslang-WallpaperEngine glslang) +add_subdirectory(src/External/SPIRV-Cross-WallpaperEngine spirv-cross) +add_subdirectory(src/External/kissfft kissfft) +add_subdirectory(src/External/argparse argparse) # try to enable wayland builds when possible pkg_check_modules(WAYLAND_SUPPORT wayland-cursor wayland-protocols egl wayland-egl) @@ -141,54 +129,61 @@ if(WAYLAND_SUPPORT_FOUND) OUTPUT_VARIABLE WAYLAND_PROTOCOLS_DIR OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "Found wayland-protocols at ${WAYLAND_PROTOCOLS_DIR}") + set(WAYLAND_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/wayland) + + file(MAKE_DIRECTORY ${WAYLAND_OUTPUT_DIR}) message(STATUS "Building protocols...") - execute_process( - COMMAND ${WaylandScanner} client-header ${CMAKE_SOURCE_DIR}/protocols/wlr-foreign-toplevel-management-unstable-v1.xml wlr-foreign-toplevel-management-unstable-v1-protocol.h - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) - execute_process( - COMMAND ${WaylandScanner} private-code ${CMAKE_SOURCE_DIR}/protocols/wlr-foreign-toplevel-management-unstable-v1.xml wlr-foreign-toplevel-management-unstable-v1-protocol.c - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) - execute_process( - COMMAND ${WaylandScanner} client-header ${CMAKE_SOURCE_DIR}/protocols/wlr-layer-shell-unstable-v1.xml wlr-layer-shell-unstable-v1-protocol.h - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) - execute_process( - COMMAND ${WaylandScanner} private-code ${CMAKE_SOURCE_DIR}/protocols/wlr-layer-shell-unstable-v1.xml wlr-layer-shell-unstable-v1-protocol.c - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) - execute_process( - COMMAND ${WaylandScanner} client-header ${WAYLAND_PROTOCOLS_DIR}/stable/xdg-shell/xdg-shell.xml xdg-shell-protocol.h - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) - execute_process( - COMMAND ${WaylandScanner} private-code ${WAYLAND_PROTOCOLS_DIR}/stable/xdg-shell/xdg-shell.xml xdg-shell-protocol.c - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) + add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/wlr-foreign-toplevel-management-unstable-v1-protocol.h + COMMAND ${WaylandScanner} client-header ${CMAKE_SOURCE_DIR}/protocols/wlr-foreign-toplevel-management-unstable-v1.xml ${WAYLAND_OUTPUT_DIR}/wlr-foreign-toplevel-management-unstable-v1-protocol.h) + add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/wlr-foreign-toplevel-management-unstable-v1-protocol.c + COMMAND ${WaylandScanner} private-code ${CMAKE_SOURCE_DIR}/protocols/wlr-foreign-toplevel-management-unstable-v1.xml ${WAYLAND_OUTPUT_DIR}/wlr-foreign-toplevel-management-unstable-v1-protocol.c) + add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/wlr-layer-shell-unstable-v1-protocol.h + COMMAND ${WaylandScanner} client-header ${CMAKE_SOURCE_DIR}/protocols/wlr-layer-shell-unstable-v1.xml ${WAYLAND_OUTPUT_DIR}/wlr-layer-shell-unstable-v1-protocol.h) + add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/wlr-layer-shell-unstable-v1-protocol.c + COMMAND ${WaylandScanner} private-code ${CMAKE_SOURCE_DIR}/protocols/wlr-layer-shell-unstable-v1.xml ${WAYLAND_OUTPUT_DIR}/wlr-layer-shell-unstable-v1-protocol.c) + add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.h + COMMAND ${WaylandScanner} client-header ${WAYLAND_PROTOCOLS_DIR}/stable/xdg-shell/xdg-shell.xml ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.h) + add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.c + COMMAND ${WaylandScanner} private-code ${WAYLAND_PROTOCOLS_DIR}/stable/xdg-shell/xdg-shell.xml ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.c) add_compile_definitions(ENABLE_WAYLAND) + include_directories(${WAYLAND_OUTPUT_DIR}) + set(WAYLAND_LIBRARIES + pthread + wayland-cursor + wayland-client + wayland-egl + ${OPENGL_egl_LIBRARY}) set(WAYLAND_SOURCES - "src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" - "src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp" - "src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp" - "src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h" - "src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp" - "src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h" - "src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp" - "src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h" - "src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp" - "src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h" - "xdg-shell-protocol.c" - "wlr-foreign-toplevel-management-unstable-v1-protocol.c" - "wlr-layer-shell-unstable-v1-protocol.c") + src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h + src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp + src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp + src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h + src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp + src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h + src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp + src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h + src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp + src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h + ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.c + ${WAYLAND_OUTPUT_DIR}/xdg-shell-protocol.h + ${WAYLAND_OUTPUT_DIR}/wlr-foreign-toplevel-management-unstable-v1-protocol.c + ${WAYLAND_OUTPUT_DIR}/wlr-foreign-toplevel-management-unstable-v1-protocol.h + ${WAYLAND_OUTPUT_DIR}/wlr-layer-shell-unstable-v1-protocol.c + ${WAYLAND_OUTPUT_DIR}/wlr-layer-shell-unstable-v1-protocol.h) endif() if(X11_FOUND) - set(X11_SUPPORT_FOUND TRUE) - if(NOT X11_Xrandr_FOUND) message(WARNING "X11 support disabled. Xrandr package is missing") set(X11_SUPPORT_FOUND FALSE) - endif() - if(NOT X11_xf86vmode_FOUND) + elseif(NOT X11_xf86vmode_FOUND) message(WARNING "X11 support disabled. Xxf86vm package is missing") set(X11_SUPPORT_FOUND FALSE) + else() + message("X11 support enabled") + set(X11_SUPPORT_FOUND TRUE) endif() endif() @@ -196,26 +191,78 @@ if(X11_SUPPORT_FOUND) include_directories(${X11_INCLUDE_DIR} ${XRANDR_INCLUDE_DIR}) add_compile_definitions(ENABLE_X11) + set(X11_LIBRARIES + ${X11_LIBRARIES} + ${X11_Xrandr_LIB}) set(X11_SOURCES - "src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp" - "src/WallpaperEngine/Render/Drivers/Output/CX11Output.h" - "src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp" - "src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h") + src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp + src/WallpaperEngine/Render/Drivers/Output/CX11Output.h + src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp + src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h) + SET(X11_INCLUDES + ${X11_INCLUDE_DIR} + ${XRANDR_INCLUDE_DIR}) + set(CMAKE_REQUIRED_LIBRARIES ${X11_LIBRARIES}) + + # make sure some of the X11 functions we'll use are available + check_function_exists(XSetIOErrorExitHandler HAVE_XSETIOERROREXITHANDLER) + + if(HAVE_XSETIOERROREXITHANDLER) + add_compile_definitions(HAVE_XSETIOERROREXITHANDLER=1) + endif() endif() +if(DEMOMODE) + set(DEMOMODE_SOURCES + src/recording.cpp + src/recording.h) + message(WARNING "Enabling demo mode will automatically record 5 seconds and stop the software. This is used internally to produce the video seen on the website as a sort of status report") +endif() +if(NOT WAYLAND_SUPPORT_FOUND AND NOT X11_SUPPORT_FOUND) + message(WARNING "No window server detected at build time. You will only be able to preview backgrounds") +endif() + +add_library(ceflib SHARED IMPORTED) +set_target_properties(ceflib + PROPERTIES IMPORTED_LOCATION ${TARGET_OUTPUT_DIRECTORY}/libcef.so) + +ADD_LOGICAL_TARGET(libcef_lib "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}") +PRINT_CEF_CONFIG() + +include_directories( + src + src/External/glslang-WallpaperEngine + src/External/SPIRV-Cross-WallpaperEngine + src/External/MimeTypes + src/External/json/include + src/External/stb + src/External/kissfft + ${MPV_INCLUDE_DIR} + ${GLEW_INCLUDE_DIR} + ${LZ4_INCLUDE_DIR} + ${SDL2_INCLUDE_DIRS} + ${FFMPEG_INCLUDE_DIR} + ${PULSEAUDIO_INCLUDE_DIR} + ${CEF_INCLUDE_PATH} + ${CMAKE_SOURCE_DIR} + ${X11_INCLUDES}) + add_executable( linux-wallpaperengine - main.cpp + src/main.cpp - src/External/Android/fft.cpp - src/External/Android/fft.h + src/External/MimeTypes/MimeTypes.cpp + src/External/MimeTypes/MimeTypes.h - src/Steam/FileSystem/FileSystem.h src/Steam/FileSystem/FileSystem.cpp + src/Steam/FileSystem/FileSystem.h src/WallpaperEngine/Logging/CLog.cpp src/WallpaperEngine/Logging/CLog.h + src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.cpp + src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.h + src/WallpaperEngine/Application/CApplicationContext.cpp src/WallpaperEngine/Application/CApplicationContext.h src/WallpaperEngine/Application/CWallpaperApplication.cpp @@ -281,12 +328,19 @@ add_executable( src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp - src/WallpaperEngine/Render/Shaders/Compiler.h - src/WallpaperEngine/Render/Shaders/Compiler.cpp + src/WallpaperEngine/Render/Shaders/CShader.h + src/WallpaperEngine/Render/Shaders/CShader.cpp + src/WallpaperEngine/Render/Shaders/CShaderUnit.cpp + src/WallpaperEngine/Render/Shaders/CShaderUnit.h + src/WallpaperEngine/Render/Shaders/CGLSLContext.cpp + src/WallpaperEngine/Render/Shaders/CGLSLContext.h src/WallpaperEngine/Render/Helpers/CContextAware.cpp src/WallpaperEngine/Render/Helpers/CContextAware.h + src/WallpaperEngine/Render/Drivers/CVideoFactories.cpp + src/WallpaperEngine/Render/Drivers/CVideoFactories.h + src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.cpp src/WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h @@ -339,11 +393,23 @@ add_executable( src/WallpaperEngine/Render/Objects/Effects/CMaterial.h src/WallpaperEngine/Render/Objects/Effects/CMaterial.cpp + src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.cpp + src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.h + src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.cpp + src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.h + src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.cpp + src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.h + src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.cpp + src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.h + src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.cpp + src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.h + src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.cpp + src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.h src/WallpaperEngine/WebBrowser/CWebBrowserContext.cpp src/WallpaperEngine/WebBrowser/CWebBrowserContext.h - src/WallpaperEngine/FileSystem/FileSystem.cpp - src/WallpaperEngine/FileSystem/FileSystem.h + src/WallpaperEngine/Core/DynamicValues/CDynamicValue.cpp + src/WallpaperEngine/Core/DynamicValues/CDynamicValue.h src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h @@ -403,12 +469,16 @@ add_executable( src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp + src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h + src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp + src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.h + src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.cpp src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h @@ -442,17 +512,8 @@ add_executable( ${WAYLAND_SOURCES} ${X11_SOURCES} -) + ${DEMOMODE_SOURCES}) -COPY_FILES(linux-wallpaperengine "${CEF_BINARY_FILES}" "${CEF_BINARY_DIR}" "${TARGET_OUTPUT_DIRECTORY}") -COPY_FILES(linux-wallpaperengine "${CEF_RESOURCE_FILES}" "${CEF_RESOURCE_DIR}" "${TARGET_OUTPUT_DIRECTORY}") - -SET_EXECUTABLE_TARGET_PROPERTIES(linux-wallpaperengine) -add_dependencies(linux-wallpaperengine libcef_dll_wrapper) - -# Need to remove libvulkan, otherwise will get error on linking: -# /usr/bin/ld: /usr/lib/libmpv.so: undefined reference to `vkCreateXlibSurfaceKHR' -file(REMOVE "${CEF_BINARY_DIR_DEBUG}/libvulkan.so.1" "${CEF_BINARY_DIR_RELEASE}/libvulkan.so.1") target_link_libraries (linux-wallpaperengine PUBLIC ${OPENGL_LIBRARIES} ${GLEW_LIBRARIES} @@ -463,39 +524,26 @@ target_link_libraries (linux-wallpaperengine PUBLIC ${FFMPEG_LIBRARIES} ${MPV_LIBRARY} ${PULSEAUDIO_LIBRARY} + ${WAYLAND_LIBRARIES} + ${X11_LIBRARIES} + kissfft + glslang + spirv-cross-core + spirv-cross-glsl glfw - libcef_lib libcef_dll_wrapper) + libcef_lib + libcef_dll_wrapper + argparse) +COPY_FILES(linux-wallpaperengine "${CEF_BINARY_FILES}" "${CEF_BINARY_DIR}" "${TARGET_OUTPUT_DIRECTORY}") +COPY_FILES(linux-wallpaperengine "${CEF_RESOURCE_FILES}" "${CEF_RESOURCE_DIR}" "${TARGET_OUTPUT_DIRECTORY}") +# remove the vulkan lib as chromium includes a broken libvulkan.so.1 with it +file(REMOVE "${CEF_BINARY_DIR}/libvulkan.so.1") -if (WAYLAND_SUPPORT_FOUND) - target_link_libraries(linux-wallpaperengine PUBLIC - pthread - wayland-cursor - wayland-client - wayland-egl - ${OPENGL_egl_LIBRARY}) -endif() - -if(X11_SUPPORT_FOUND) - target_link_libraries (linux-wallpaperengine PUBLIC - ${X11_LIBRARIES} ${X11_Xrandr_LIB}) - - - set(CMAKE_REQUIRED_LIBRARIES ${X11_LIBRARIES}) - - # make sure some of the X11 functions we'll use are available - check_function_exists(XSetIOErrorExitHandler HAVE_XSETIOERROREXITHANDLER) - - if(HAVE_XSETIOERROREXITHANDLER) - add_compile_definitions(HAVE_XSETIOERROREXITHANDLER=1) - endif() -endif() - -if(NOT WAYLAND_SUPPORT_FOUND AND NOT X11_SUPPORT_FOUND) - message(WARNING "No window server detected at build time. You will only be able to preview backgrounds") -endif() +add_dependencies(linux-wallpaperengine libcef_dll_wrapper glslang spirv-cross-core spirv-cross-glsl) +# custom version of cef's SET_EXECUTABLE_TARGET_PROPERTIES that fixes C files being compiled with the wrong parameters +REPLACED_SET_EXECUTABLE_TARGET_PROPERTIES(linux-wallpaperengine) # set some install parameters if not in debug mode install(DIRECTORY ${TARGET_OUTPUT_DIRECTORY}/ DESTINATION .) install(FILES ${TARGET_OUTPUT_DIRECTORY}/${PROJECT_NAME} PERMISSIONS OWNER_READ OWNER_WRITE WORLD_EXECUTE WORLD_READ GROUP_READ DESTINATION .) -install(DIRECTORY share/ DESTINATION ./share) diff --git a/CMakeModules/DownloadCEF.cmake b/CMakeModules/DownloadCEF.cmake index 2a40437..b780121 100644 --- a/CMakeModules/DownloadCEF.cmake +++ b/CMakeModules/DownloadCEF.cmake @@ -46,3 +46,83 @@ function(DownloadCEF platform version download_dir) ) endif() endfunction() + + +# Set common target properties. Use SET_LIBRARY_TARGET_PROPERTIES() or +# SET_EXECUTABLE_TARGET_PROPERTIES() instead of calling this macro directly. +macro(REPLACED_SET_COMMON_TARGET_PROPERTIES target) + # Compile flags. (MODIFIED FOR C/C++ SEPARATION) + target_compile_options(${target} PRIVATE $<$:${CEF_COMPILER_FLAGS}>) + target_compile_options(${target} PRIVATE $<$:${CEF_CXX_COMPILER_FLAGS}>) + target_compile_options(${target} PRIVATE $<$:${CEF_COMPILER_FLAGS_DEBUG} ${CEF_CXX_COMPILER_FLAGS_DEBUG}>) + target_compile_options(${target} PRIVATE $<$:${CEF_COMPILER_FLAGS_RELEASE} ${CEF_CXX_COMPILER_FLAGS_RELEASE}>) + + # Compile definitions. + target_compile_definitions(${target} PRIVATE ${CEF_COMPILER_DEFINES}) + target_compile_definitions(${target} PRIVATE $<$:${CEF_COMPILER_DEFINES_DEBUG}>) + target_compile_definitions(${target} PRIVATE $<$:${CEF_COMPILER_DEFINES_RELEASE}>) + + # Include directories. + target_include_directories(${target} PRIVATE ${CEF_INCLUDE_PATH}) + + # Linker flags. + if(CEF_LINKER_FLAGS) + string(REPLACE ";" " " _flags_str "${CEF_LINKER_FLAGS}") + set_property(TARGET ${target} PROPERTY LINK_FLAGS ${_flags_str}) + endif() + if(CEF_LINKER_FLAGS_DEBUG) + string(REPLACE ";" " " _flags_str "${CEF_LINKER_FLAGS_DEBUG}") + set_property(TARGET ${target} PROPERTY LINK_FLAGS_DEBUG ${_flags_str}) + endif() + if(CEF_LINKER_FLAGS_RELEASE) + string(REPLACE ";" " " _flags_str "${CEF_LINKER_FLAGS_RELEASE}") + set_property(TARGET ${target} PROPERTY LINK_FLAGS_RELEASE ${_flags_str}) + endif() + + if(OS_MAC) + # Set Xcode target properties. + set_target_properties(${target} PROPERTIES + XCODE_ATTRIBUTE_ALWAYS_SEARCH_USER_PATHS NO + XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "gnu++11" # -std=gnu++11 + XCODE_ATTRIBUTE_CLANG_LINK_OBJC_RUNTIME NO # -fno-objc-link-runtime + XCODE_ATTRIBUTE_CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS YES # -Wobjc-missing-property-synthesis + XCODE_ATTRIBUTE_COPY_PHASE_STRIP NO + XCODE_ATTRIBUTE_DEAD_CODE_STRIPPING[variant=Release] YES # -Wl,-dead_strip + XCODE_ATTRIBUTE_GCC_C_LANGUAGE_STANDARD "c99" # -std=c99 + XCODE_ATTRIBUTE_GCC_CW_ASM_SYNTAX NO # No -fasm-blocks + XCODE_ATTRIBUTE_GCC_DYNAMIC_NO_PIC NO + XCODE_ATTRIBUTE_GCC_ENABLE_CPP_EXCEPTIONS NO # -fno-exceptions + XCODE_ATTRIBUTE_GCC_ENABLE_CPP_RTTI NO # -fno-rtti + XCODE_ATTRIBUTE_GCC_ENABLE_PASCAL_STRINGS NO # No -mpascal-strings + XCODE_ATTRIBUTE_GCC_INLINES_ARE_PRIVATE_EXTERN YES # -fvisibility-inlines-hidden + XCODE_ATTRIBUTE_GCC_OBJC_CALL_CXX_CDTORS YES # -fobjc-call-cxx-cdtors + XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN YES # -fvisibility=hidden + XCODE_ATTRIBUTE_GCC_THREADSAFE_STATICS NO # -fno-threadsafe-statics + XCODE_ATTRIBUTE_GCC_TREAT_WARNINGS_AS_ERRORS YES # -Werror + XCODE_ATTRIBUTE_GCC_VERSION "com.apple.compilers.llvm.clang.1_0" + XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE YES # -Wnewline-eof + XCODE_ATTRIBUTE_USE_HEADERMAP NO + OSX_ARCHITECTURES_DEBUG "${CMAKE_OSX_ARCHITECTURES}" + OSX_ARCHITECTURES_RELEASE "${CMAKE_OSX_ARCHITECTURES}" + ) + endif() +endmacro() + +# Set executable-specific properties. +macro(REPLACED_SET_EXECUTABLE_TARGET_PROPERTIES target) + REPLACED_SET_COMMON_TARGET_PROPERTIES(${target}) + + # Executable linker flags. + if(CEF_EXE_LINKER_FLAGS) + string(REPLACE ";" " " _flags_str "${CEF_EXE_LINKER_FLAGS}") + set_property(TARGET ${target} PROPERTY LINK_FLAGS ${_flags_str}) + endif() + if(CEF_EXE_LINKER_FLAGS_DEBUG) + string(REPLACE ";" " " _flags_str "${CEF_EXE_LINKER_FLAGS_DEBUG}") + set_property(TARGET ${target} PROPERTY LINK_FLAGS_DEBUG ${_flags_str}) + endif() + if(CEF_EXE_LINKER_FLAGS_RELEASE) + string(REPLACE ";" " " _flags_str "${CEF_EXE_LINKER_FLAGS_RELEASE}") + set_property(TARGET ${target} PROPERTY LINK_FLAGS_RELEASE ${_flags_str}) + endif() +endmacro() diff --git a/CMakeModules/FindCEF.cmake b/CMakeModules/FindCEF.cmake deleted file mode 100644 index cd33a7d..0000000 --- a/CMakeModules/FindCEF.cmake +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights -# reserved. Use of this source code is governed by a BSD-style license that -# can be found in the LICENSE file. - -# -# This file is the CEF CMake configuration entry point and should be loaded -# using `find_package(CEF REQUIRED)`. See the top-level CMakeLists.txt file -# included with the CEF binary distribution for usage information. -# - -# Find the CEF binary distribution root directory. -set(_CEF_ROOT "") -if(CEF_ROOT AND IS_DIRECTORY "${CEF_ROOT}") - set(_CEF_ROOT "${CEF_ROOT}") - set(_CEF_ROOT_EXPLICIT 1) -else() - set(_ENV_CEF_ROOT "") - if(DEFINED ENV{CEF_ROOT}) - file(TO_CMAKE_PATH "$ENV{CEF_ROOT}" _ENV_CEF_ROOT) - endif() - if(_ENV_CEF_ROOT AND IS_DIRECTORY "${_ENV_CEF_ROOT}") - set(_CEF_ROOT "${_ENV_CEF_ROOT}") - set(_CEF_ROOT_EXPLICIT 1) - endif() - unset(_ENV_CEF_ROOT) -endif() - -if(NOT DEFINED _CEF_ROOT_EXPLICIT) - message(FATAL_ERROR "Must specify a CEF_ROOT value via CMake or environment variable.") -endif() - -if(NOT IS_DIRECTORY "${_CEF_ROOT}/cmake") - message(FATAL_ERROR "No CMake bootstrap found for CEF binary distribution at: ${CEF_ROOT}.") -endif() - -# Execute additional cmake files from the CEF binary distribution. -set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${_CEF_ROOT}/cmake") -include("cef_variables") -include("cef_macros") diff --git a/CMakeModules/cef_macros.cmake b/CMakeModules/cef_macros.cmake deleted file mode 100644 index f357d06..0000000 --- a/CMakeModules/cef_macros.cmake +++ /dev/null @@ -1,387 +0,0 @@ -# Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights -# reserved. Use of this source code is governed by a BSD-style license that -# can be found in the LICENSE file. - -# Must be loaded via FindCEF.cmake. -if(NOT DEFINED _CEF_ROOT_EXPLICIT) - message(FATAL_ERROR "Use find_package(CEF) to load this file.") -endif() - - -# -# Shared macros. -# - -# Print the current CEF configuration. -macro(PRINT_CEF_CONFIG) - message(STATUS "*** CEF CONFIGURATION SETTINGS ***") - message(STATUS "Generator: ${CMAKE_GENERATOR}") - message(STATUS "Platform: ${CMAKE_SYSTEM_NAME}") - message(STATUS "Project architecture: ${PROJECT_ARCH}") - - if(GEN_NINJA OR GEN_MAKEFILES) - message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") - endif() - - message(STATUS "Binary distribution root: ${_CEF_ROOT}") - - if(OS_MAC) - message(STATUS "Base SDK: ${CMAKE_OSX_SYSROOT}") - message(STATUS "Target SDK: ${CEF_TARGET_SDK}") - endif() - - if(OS_WINDOWS) - message(STATUS "Visual Studio ATL support: ${USE_ATL}") - endif() - - message(STATUS "CEF sandbox: ${USE_SANDBOX}") - - set(_libraries ${CEF_STANDARD_LIBS}) - if(OS_WINDOWS AND USE_SANDBOX) - list(APPEND _libraries ${CEF_SANDBOX_STANDARD_LIBS}) - endif() - message(STATUS "Standard libraries: ${_libraries}") - - message(STATUS "Compile defines: ${CEF_COMPILER_DEFINES}") - message(STATUS "Compile defines (Debug): ${CEF_COMPILER_DEFINES_DEBUG}") - message(STATUS "Compile defines (Release): ${CEF_COMPILER_DEFINES_RELEASE}") - message(STATUS "C compile flags: ${CEF_COMPILER_FLAGS} ${CEF_C_COMPILER_FLAGS}") - message(STATUS "C compile flags (Debug): ${CEF_COMPILER_FLAGS_DEBUG} ${CEF_C_COMPILER_FLAGS_DEBUG}") - message(STATUS "C compile flags (Release): ${CEF_COMPILER_FLAGS_RELEASE} ${CEF_C_COMPILER_FLAGS_RELEASE}") - message(STATUS "C++ compile flags: ${CEF_COMPILER_FLAGS} ${CEF_CXX_COMPILER_FLAGS}") - message(STATUS "C++ compile flags (Debug): ${CEF_COMPILER_FLAGS_DEBUG} ${CEF_CXX_COMPILER_FLAGS_DEBUG}") - message(STATUS "C++ compile flags (Release): ${CEF_COMPILER_FLAGS_RELEASE} ${CEF_CXX_COMPILER_FLAGS_RELEASE}") - message(STATUS "Exe link flags: ${CEF_LINKER_FLAGS} ${CEF_EXE_LINKER_FLAGS}") - message(STATUS "Exe link flags (Debug): ${CEF_LINKER_FLAGS_DEBUG} ${CEF_EXE_LINKER_FLAGS_DEBUG}") - message(STATUS "Exe link flags (Release): ${CEF_LINKER_FLAGS_RELEASE} ${CEF_EXE_LINKER_FLAGS_RELEASE}") - message(STATUS "Shared link flags: ${CEF_LINKER_FLAGS} ${CEF_SHARED_LINKER_FLAGS}") - message(STATUS "Shared link flags (Debug): ${CEF_LINKER_FLAGS_DEBUG} ${CEF_SHARED_LINKER_FLAGS_DEBUG}") - message(STATUS "Shared link flags (Release): ${CEF_LINKER_FLAGS_RELEASE} ${CEF_SHARED_LINKER_FLAGS_RELEASE}") - - if(OS_LINUX OR OS_WINDOWS) - message(STATUS "CEF Binary files: ${CEF_BINARY_FILES}") - message(STATUS "CEF Resource files: ${CEF_RESOURCE_FILES}") - endif() -endmacro() - -# Append platform specific sources to a list of sources. -macro(APPEND_PLATFORM_SOURCES name_of_list) - if(OS_LINUX AND ${name_of_list}_LINUX) - list(APPEND ${name_of_list} ${${name_of_list}_LINUX}) - endif() - if(OS_POSIX AND ${name_of_list}_POSIX) - list(APPEND ${name_of_list} ${${name_of_list}_POSIX}) - endif() - if(OS_WINDOWS AND ${name_of_list}_WINDOWS) - list(APPEND ${name_of_list} ${${name_of_list}_WINDOWS}) - endif() - if(OS_MAC AND ${name_of_list}_MAC) - list(APPEND ${name_of_list} ${${name_of_list}_MAC}) - endif() -endmacro() - -# Determine the target output directory based on platform and generator. -macro(SET_CEF_TARGET_OUT_DIR) - if(GEN_NINJA OR GEN_MAKEFILES) - # By default Ninja and Make builds don't create a subdirectory named after - # the configuration. - set(CEF_TARGET_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}") - - # Output binaries (executables, libraries) to the correct directory. - set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CEF_TARGET_OUT_DIR}) - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CEF_TARGET_OUT_DIR}) - else() - set(CEF_TARGET_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/$") - endif() -endmacro() - -# Copy a list of files from one directory to another. Relative file paths are maintained. -macro(COPY_FILES target file_list source_dir target_dir) - foreach(FILENAME ${file_list}) - set(source_file ${source_dir}/${FILENAME}) - - # Remove the target file path component. - get_filename_component(target_name ${FILENAME} NAME) - set(target_file ${target_dir}/${target_name}) - - COPY_SINGLE_FILE(${target} ${source_file} ${target_file}) - endforeach() -endmacro() - -# Copy a list of files from one directory to another. Relative file paths are maintained. -macro(COPY_RESOURCES target file_list prefix_list source_dir target_dir) - foreach(FILENAME ${file_list}) - set(source_file ${source_dir}/${FILENAME}) - - # Remove one or more prefixes from the source paths. - set(TARGET_FILENAME "${FILENAME}") - foreach(PREFIX ${prefix_list}) - string(REGEX REPLACE "^.*${PREFIX}" "" TARGET_FILENAME ${TARGET_FILENAME}) - endforeach() - set(target_file ${target_dir}/${TARGET_FILENAME}) - - COPY_SINGLE_FILE(${target} ${source_file} ${target_file}) - endforeach() -endmacro() - -macro(COPY_SINGLE_FILE target source_file target_file) - string(FIND ${source_file} "$" _pos) - if(NOT ${_pos} EQUAL -1) - # Must test with an actual configuration directory. - string(REPLACE "$" "Release" existing_source_file ${source_file}) - if(NOT EXISTS ${existing_source_file}) - string(REPLACE "$" "Debug" existing_source_file ${source_file}) - endif() - else() - set(existing_source_file ${source_file}) - endif() - - if(IS_DIRECTORY ${existing_source_file}) - add_custom_command( - TARGET ${target} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_directory "${source_file}" "${target_file}" - VERBATIM - ) - else() - add_custom_command( - TARGET ${target} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${source_file}" "${target_file}" - VERBATIM - ) - endif() -endmacro() - - -# -# Linux macros. -# - -if(OS_LINUX) - -# Use pkg-config to find Linux libraries and update compiler/linker variables. -macro(FIND_LINUX_LIBRARIES libraries) - # Read pkg-config info into variables. - execute_process(COMMAND pkg-config --cflags ${libraries} OUTPUT_VARIABLE FLL_CFLAGS) - execute_process(COMMAND pkg-config --libs-only-L --libs-only-other ${libraries} OUTPUT_VARIABLE FLL_LDFLAGS) - execute_process(COMMAND pkg-config --libs-only-l ${libraries} OUTPUT_VARIABLE FLL_LIBS) - - # Strip leading and trailing whitepspace. - STRING(STRIP "${FLL_CFLAGS}" FLL_CFLAGS) - STRING(STRIP "${FLL_LDFLAGS}" FLL_LDFLAGS) - STRING(STRIP "${FLL_LIBS}" FLL_LIBS) - - # Convert to a list. - separate_arguments(FLL_CFLAGS) - separate_arguments(FLL_LDFLAGS) - separate_arguments(FLL_LIBS) - - # Update build variables. - list(APPEND CEF_C_COMPILER_FLAGS ${FLL_CFLAGS}) - list(APPEND CEF_CXX_COMPILER_FLAGS ${FLL_CFLAGS}) - list(APPEND CEF_EXE_LINKER_FLAGS ${FLL_LDFLAGS}) - list(APPEND CEF_SHARED_LINKER_FLAGS ${FLL_LDFLAGS}) - list(APPEND CEF_STANDARD_LIBS ${FLL_LIBS}) -endmacro() - -# Set SUID permissions on the specified executable. -macro(SET_LINUX_SUID_PERMISSIONS target executable) - add_custom_command( - TARGET ${target} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E echo "" - COMMAND ${CMAKE_COMMAND} -E echo "*** Run the following command manually to set SUID permissions ***" - COMMAND ${CMAKE_COMMAND} -E echo "EXE=\"${executable}\" && sudo -- chown root:root $EXE && sudo -- chmod 4755 $EXE" - COMMAND ${CMAKE_COMMAND} -E echo "" - VERBATIM - ) -endmacro() - -endif(OS_LINUX) - - -# -# Mac OS X macros. -# - -if(OS_MAC) - -# Manually process and copy over resource files. -macro(COPY_MAC_RESOURCES resource_list prefix_list target source_dir app_path) - foreach(FILENAME ${resource_list}) - # Remove one or more prefixes from the source paths. - set(TARGET_FILENAME "${FILENAME}") - foreach(PREFIX ${prefix_list}) - string(REGEX REPLACE "^.*${PREFIX}" "" TARGET_FILENAME ${TARGET_FILENAME}) - endforeach() - - # Determine the absolute source and target paths. - set(TARGET_PATH "${app_path}/Contents/Resources/${TARGET_FILENAME}") - if(IS_ABSOLUTE ${FILENAME}) - set(SOURCE_PATH ${FILENAME}) - else() - set(SOURCE_PATH "${source_dir}/${FILENAME}") - endif() - - if(${FILENAME} MATCHES ".xib$") - # Change the target file extension. - string(REGEX REPLACE ".xib$" ".nib" TARGET_PATH ${TARGET_PATH}) - - get_filename_component(TARGET_DIRECTORY ${TARGET_PATH} PATH) - add_custom_command( - TARGET ${target} - POST_BUILD - # Create the target directory. - COMMAND ${CMAKE_COMMAND} -E make_directory "${TARGET_DIRECTORY}" - # Compile the XIB file to a NIB. - COMMAND /usr/bin/ibtool --output-format binary1 --compile "${TARGET_PATH}" "${SOURCE_PATH}" - VERBATIM - ) - elseif(NOT ${TARGET_FILENAME} STREQUAL "Info.plist") - # Copy the file as-is. - add_custom_command( - TARGET ${target} - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy "${SOURCE_PATH}" "${TARGET_PATH}" - VERBATIM - ) - endif() - endforeach() -endmacro() - -endif(OS_MAC) - - -# -# Windows macros. -# - -if(OS_WINDOWS) - -# Add custom manifest files to an executable target. -macro(ADD_WINDOWS_MANIFEST manifest_path target extension) - add_custom_command( - TARGET ${target} - POST_BUILD - COMMAND "mt.exe" -nologo - -manifest \"${manifest_path}/${target}.${extension}.manifest\" \"${manifest_path}/compatibility.manifest\" - -outputresource:"${CEF_TARGET_OUT_DIR}/${target}.${extension}"\;\#1 - COMMENT "Adding manifest..." - ) -endmacro() - -endif(OS_WINDOWS) - - -# -# Target configuration macros. -# - -# Add a logical target that can be used to link the specified libraries into an -# executable target. -macro(ADD_LOGICAL_TARGET target debug_lib release_lib) - add_library(${target} ${CEF_LIBTYPE} IMPORTED) - set_target_properties(${target} PROPERTIES - IMPORTED_LOCATION "${release_lib}" - IMPORTED_LOCATION_DEBUG "${debug_lib}" - IMPORTED_LOCATION_RELEASE "${release_lib}" - ) -endmacro() - -# Set common target properties. Use SET_LIBRARY_TARGET_PROPERTIES() or -# SET_EXECUTABLE_TARGET_PROPERTIES() instead of calling this macro directly. -macro(SET_COMMON_TARGET_PROPERTIES target) - # Compile flags. - target_compile_options(${target} PRIVATE ${CEF_COMPILER_FLAGS} ${CEF_CXX_COMPILER_FLAGS}) - target_compile_options(${target} PRIVATE $<$:${CEF_COMPILER_FLAGS_DEBUG} ${CEF_CXX_COMPILER_FLAGS_DEBUG}>) - target_compile_options(${target} PRIVATE $<$:${CEF_COMPILER_FLAGS_RELEASE} ${CEF_CXX_COMPILER_FLAGS_RELEASE}>) - - # Compile definitions. - target_compile_definitions(${target} PRIVATE ${CEF_COMPILER_DEFINES}) - target_compile_definitions(${target} PRIVATE $<$:${CEF_COMPILER_DEFINES_DEBUG}>) - target_compile_definitions(${target} PRIVATE $<$:${CEF_COMPILER_DEFINES_RELEASE}>) - - # Include directories. - target_include_directories(${target} PRIVATE ${CEF_INCLUDE_PATH}) - - # Linker flags. - if(CEF_LINKER_FLAGS) - string(REPLACE ";" " " _flags_str "${CEF_LINKER_FLAGS}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS ${_flags_str}) - endif() - if(CEF_LINKER_FLAGS_DEBUG) - string(REPLACE ";" " " _flags_str "${CEF_LINKER_FLAGS_DEBUG}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS_DEBUG ${_flags_str}) - endif() - if(CEF_LINKER_FLAGS_RELEASE) - string(REPLACE ";" " " _flags_str "${CEF_LINKER_FLAGS_RELEASE}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS_RELEASE ${_flags_str}) - endif() - - if(OS_MAC) - # Set Xcode target properties. - set_target_properties(${target} PROPERTIES - XCODE_ATTRIBUTE_ALWAYS_SEARCH_USER_PATHS NO - XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "gnu++11" # -std=gnu++11 - XCODE_ATTRIBUTE_CLANG_LINK_OBJC_RUNTIME NO # -fno-objc-link-runtime - XCODE_ATTRIBUTE_CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS YES # -Wobjc-missing-property-synthesis - XCODE_ATTRIBUTE_COPY_PHASE_STRIP NO - XCODE_ATTRIBUTE_DEAD_CODE_STRIPPING[variant=Release] YES # -Wl,-dead_strip - XCODE_ATTRIBUTE_GCC_C_LANGUAGE_STANDARD "c99" # -std=c99 - XCODE_ATTRIBUTE_GCC_CW_ASM_SYNTAX NO # No -fasm-blocks - XCODE_ATTRIBUTE_GCC_DYNAMIC_NO_PIC NO - XCODE_ATTRIBUTE_GCC_ENABLE_CPP_EXCEPTIONS NO # -fno-exceptions - XCODE_ATTRIBUTE_GCC_ENABLE_CPP_RTTI NO # -fno-rtti - XCODE_ATTRIBUTE_GCC_ENABLE_PASCAL_STRINGS NO # No -mpascal-strings - XCODE_ATTRIBUTE_GCC_INLINES_ARE_PRIVATE_EXTERN YES # -fvisibility-inlines-hidden - XCODE_ATTRIBUTE_GCC_OBJC_CALL_CXX_CDTORS YES # -fobjc-call-cxx-cdtors - XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN YES # -fvisibility=hidden - XCODE_ATTRIBUTE_GCC_THREADSAFE_STATICS NO # -fno-threadsafe-statics - XCODE_ATTRIBUTE_GCC_TREAT_WARNINGS_AS_ERRORS YES # -Werror - XCODE_ATTRIBUTE_GCC_VERSION "com.apple.compilers.llvm.clang.1_0" - XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE YES # -Wnewline-eof - XCODE_ATTRIBUTE_USE_HEADERMAP NO - OSX_ARCHITECTURES_DEBUG "${CMAKE_OSX_ARCHITECTURES}" - OSX_ARCHITECTURES_RELEASE "${CMAKE_OSX_ARCHITECTURES}" - ) - endif() -endmacro() - -# Set library-specific properties. -macro(SET_LIBRARY_TARGET_PROPERTIES target) - SET_COMMON_TARGET_PROPERTIES(${target}) - - # Shared library linker flags. - if(CEF_SHARED_LINKER_FLAGS) - string(REPLACE ";" " " _flags_str "${CEF_SHARED_LINKER_FLAGS}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS ${_flags_str}) - endif() - if(CEF_SHARED_LINKER_FLAGS_DEBUG) - string(REPLACE ";" " " _flags_str "${CEF_SHARED_LINKER_FLAGS_DEBUG}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS_DEBUG ${_flags_str}) - endif() - if(CEF_SHARED_LINKER_FLAGS_RELEASE) - string(REPLACE ";" " " _flags_str "${CEF_SHARED_LINKER_FLAGS_RELEASE}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS_RELEASE ${_flags_str}) - endif() -endmacro() - -# Set executable-specific properties. -macro(SET_EXECUTABLE_TARGET_PROPERTIES target) - SET_COMMON_TARGET_PROPERTIES(${target}) - - # Executable linker flags. - if(CEF_EXE_LINKER_FLAGS) - string(REPLACE ";" " " _flags_str "${CEF_EXE_LINKER_FLAGS}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS ${_flags_str}) - endif() - if(CEF_EXE_LINKER_FLAGS_DEBUG) - string(REPLACE ";" " " _flags_str "${CEF_EXE_LINKER_FLAGS_DEBUG}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS_DEBUG ${_flags_str}) - endif() - if(CEF_EXE_LINKER_FLAGS_RELEASE) - string(REPLACE ";" " " _flags_str "${CEF_EXE_LINKER_FLAGS_RELEASE}") - set_property(TARGET ${target} PROPERTY LINK_FLAGS_RELEASE ${_flags_str}) - endif() -endmacro() diff --git a/CMakeModules/cef_variables.cmake b/CMakeModules/cef_variables.cmake deleted file mode 100644 index a3d78fb..0000000 --- a/CMakeModules/cef_variables.cmake +++ /dev/null @@ -1,582 +0,0 @@ -# Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights -# reserved. Use of this source code is governed by a BSD-style license that -# can be found in the LICENSE file. - -# Must be loaded via FindCEF.cmake. -if(NOT DEFINED _CEF_ROOT_EXPLICIT) - message(FATAL_ERROR "Use find_package(CEF) to load this file.") -endif() - - -# -# Shared configuration. -# - -# Determine the platform. -if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin") - set(OS_MAC 1) - set(OS_MACOSX 1) # For backwards compatibility. - set(OS_POSIX 1) -elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") - set(OS_LINUX 1) - set(OS_POSIX 1) -elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") - set(OS_WINDOWS 1) -endif() - -# Determine the project architecture. -if(NOT DEFINED PROJECT_ARCH) - if(("${CMAKE_HOST_SYSTEM_PROCESSOR}" STREQUAL "arm64") OR - ("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM64")) - set(PROJECT_ARCH "arm64") - elseif(CMAKE_SIZEOF_VOID_P MATCHES 8) - set(PROJECT_ARCH "x86_64") - else() - set(PROJECT_ARCH "x86") - endif() -endif() - -if(${CMAKE_GENERATOR} STREQUAL "Ninja") - set(GEN_NINJA 1) -elseif(${CMAKE_GENERATOR} STREQUAL "Unix Makefiles") - set(GEN_MAKEFILES 1) -endif() - -# Determine the build type. -if(NOT CMAKE_BUILD_TYPE AND (GEN_NINJA OR GEN_MAKEFILES)) - # CMAKE_BUILD_TYPE should be specified when using Ninja or Unix Makefiles. - set(CMAKE_BUILD_TYPE Release) - message(WARNING "No CMAKE_BUILD_TYPE value selected, using ${CMAKE_BUILD_TYPE}") -endif() - - -# Path to the include directory. -set(CEF_INCLUDE_PATH "${_CEF_ROOT}") - -# Path to the libcef_dll_wrapper target. -set(CEF_LIBCEF_DLL_WRAPPER_PATH "${_CEF_ROOT}/libcef_dll") - - -# Shared compiler/linker flags. -list(APPEND CEF_COMPILER_DEFINES - # Allow C++ programs to use stdint.h macros specified in the C99 standard that aren't - # in the C++ standard (e.g. UINT8_MAX, INT64_MIN, etc) - __STDC_CONSTANT_MACROS __STDC_FORMAT_MACROS - ) - - -# Configure use of the sandbox. -option(USE_SANDBOX "Enable or disable use of the sandbox." ON) - - -# -# Linux configuration. -# - -if(OS_LINUX) - # Platform-specific compiler/linker flags. - set(CEF_LIBTYPE SHARED) - list(APPEND CEF_COMPILER_FLAGS - -fno-strict-aliasing # Avoid assumptions regarding non-aliasing of objects of different types - -fPIC # Generate position-independent code for shared libraries - -fstack-protector # Protect some vulnerable functions from stack-smashing (security feature) - -funwind-tables # Support stack unwinding for backtrace() - -fvisibility=hidden # Give hidden visibility to declarations that are not explicitly marked as visible - --param=ssp-buffer-size=4 # Set the minimum buffer size protected by SSP (security feature, related to stack-protector) - -pipe # Use pipes rather than temporary files for communication between build stages - -pthread # Use the pthread library - # -Wall # Enable all warnings - # -Werror # Treat warnings as errors - # -Wno-missing-field-initializers # Don't warn about missing field initializers - # -Wno-unused-parameter # Don't warn about unused parameters - # -Wno-error=comment # Don't warn about code in comments - # -Wno-comment # Don't warn about code in comments - # -Wno-deprecated-declarations # Don't warn about using deprecated methods - ) - list(APPEND CEF_C_COMPILER_FLAGS - -std=c99 # Use the C99 language standard - ) - list(APPEND CEF_CXX_COMPILER_FLAGS - # -fno-exceptions # Disable exceptions - # -fno-rtti # Disable real-time type information - -fno-threadsafe-statics # Don't generate thread-safe statics - -fvisibility-inlines-hidden # Give hidden visibility to inlined class member functions - -std=c++17 # Use the C++17 language standard - -Wsign-compare # Warn about mixed signed/unsigned type comparisons - ) - list(APPEND CEF_COMPILER_FLAGS_DEBUG - -O0 # Disable optimizations - -g # Generate debug information - ) - list(APPEND CEF_COMPILER_FLAGS_RELEASE - -O2 # Optimize for maximum speed - -fdata-sections # Enable linker optimizations to improve locality of reference for data sections - -ffunction-sections # Enable linker optimizations to improve locality of reference for function sections - -fno-ident # Ignore the #ident directive - -U_FORTIFY_SOURCE # Undefine _FORTIFY_SOURCE in case it was previously defined - -D_FORTIFY_SOURCE=2 # Add memory and string function protection (security feature, related to stack-protector) - ) - list(APPEND CEF_LINKER_FLAGS - -fPIC # Generate position-independent code for shared libraries - -pthread # Use the pthread library - -Wl,--disable-new-dtags # Don't generate new-style dynamic tags in ELF - -Wl,--fatal-warnings # Treat warnings as errors - -Wl,-rpath,. # Set rpath so that libraries can be placed next to the executable - -Wl,-z,noexecstack # Mark the stack as non-executable (security feature) - -Wl,-z,now # Resolve symbols on program start instead of on first use (security feature) - -Wl,-z,relro # Mark relocation sections as read-only (security feature) - ) - list(APPEND CEF_LINKER_FLAGS_RELEASE - -Wl,-O1 # Enable linker optimizations - -Wl,--as-needed # Only link libraries that export symbols used by the binary - -Wl,--gc-sections # Remove unused code resulting from -fdata-sections and -function-sections - ) - list(APPEND CEF_COMPILER_DEFINES - _FILE_OFFSET_BITS=64 # Allow the Large File Support (LFS) interface to replace the old interface - ) - list(APPEND CEF_COMPILER_DEFINES_RELEASE - NDEBUG # Not a debug build - ) - - include(CheckCCompilerFlag) - include(CheckCXXCompilerFlag) - - CHECK_CXX_COMPILER_FLAG(-Wno-undefined-var-template COMPILER_SUPPORTS_NO_UNDEFINED_VAR_TEMPLATE) - if(COMPILER_SUPPORTS_NO_UNDEFINED_VAR_TEMPLATE) - list(APPEND CEF_CXX_COMPILER_FLAGS - -Wno-undefined-var-template # Don't warn about potentially uninstantiated static members - ) - endif() - - CHECK_C_COMPILER_FLAG(-Wno-unused-local-typedefs COMPILER_SUPPORTS_NO_UNUSED_LOCAL_TYPEDEFS) - if(COMPILER_SUPPORTS_NO_UNUSED_LOCAL_TYPEDEFS) - list(APPEND CEF_C_COMPILER_FLAGS - -Wno-unused-local-typedefs # Don't warn about unused local typedefs - ) - endif() - - CHECK_CXX_COMPILER_FLAG(-Wno-literal-suffix COMPILER_SUPPORTS_NO_LITERAL_SUFFIX) - if(COMPILER_SUPPORTS_NO_LITERAL_SUFFIX) - list(APPEND CEF_CXX_COMPILER_FLAGS - -Wno-literal-suffix # Don't warn about invalid suffixes on literals - ) - endif() - - CHECK_CXX_COMPILER_FLAG(-Wno-narrowing COMPILER_SUPPORTS_NO_NARROWING) - if(COMPILER_SUPPORTS_NO_NARROWING) - list(APPEND CEF_CXX_COMPILER_FLAGS - -Wno-narrowing # Don't warn about type narrowing - ) - endif() - - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - list(APPEND CEF_CXX_COMPILER_FLAGS - -Wno-attributes # The cfi-icall attribute is not supported by the GNU C++ compiler - ) - endif() - - if(PROJECT_ARCH STREQUAL "x86_64") - # 64-bit architecture. - list(APPEND CEF_COMPILER_FLAGS - -m64 - -march=x86-64 - ) - list(APPEND CEF_LINKER_FLAGS - -m64 - ) - elseif(PROJECT_ARCH STREQUAL "x86") - # 32-bit architecture. - list(APPEND CEF_COMPILER_FLAGS - -msse2 - -mfpmath=sse - -mmmx - -m32 - ) - list(APPEND CEF_LINKER_FLAGS - -m32 - ) - endif() - - # Standard libraries. - set(CEF_STANDARD_LIBS - X11 - ) - - # CEF directory paths. - set(CEF_RESOURCE_DIR "${_CEF_ROOT}/Resources") - set(CEF_BINARY_DIR "${_CEF_ROOT}/${CMAKE_BUILD_TYPE}") - set(CEF_BINARY_DIR_DEBUG "${_CEF_ROOT}/Debug") - set(CEF_BINARY_DIR_RELEASE "${_CEF_ROOT}/Release") - - # CEF library paths. - set(CEF_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/libcef.so") - set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.so") - - # List of CEF binary files. - set(CEF_BINARY_FILES - chrome-sandbox - libcef.so - libEGL.so - libGLESv2.so - libvk_swiftshader.so - # libvulkan.so.1 - snapshot_blob.bin - v8_context_snapshot.bin - vk_swiftshader_icd.json - ) - - # List of CEF resource files. - set(CEF_RESOURCE_FILES - chrome_100_percent.pak - chrome_200_percent.pak - resources.pak - icudtl.dat - locales - ) - - if(USE_SANDBOX) - list(APPEND CEF_COMPILER_DEFINES - CEF_USE_SANDBOX # Used by apps to test if the sandbox is enabled - ) - endif() -endif() - - -# -# Mac OS X configuration. -# - -if(OS_MAC) - # Platform-specific compiler/linker flags. - # See also Xcode target properties in cef_macros.cmake. - set(CEF_LIBTYPE SHARED) - list(APPEND CEF_COMPILER_FLAGS - -fno-strict-aliasing # Avoid assumptions regarding non-aliasing of objects of different types - -fstack-protector # Protect some vulnerable functions from stack-smashing (security feature) - -funwind-tables # Support stack unwinding for backtrace() - -fvisibility=hidden # Give hidden visibility to declarations that are not explicitly marked as visible - -Wall # Enable all warnings - -Werror # Treat warnings as errors - -Wextra # Enable additional warnings - -Wendif-labels # Warn whenever an #else or an #endif is followed by text - -Wnewline-eof # Warn about no newline at end of file - -Wno-missing-field-initializers # Don't warn about missing field initializers - -Wno-unused-parameter # Don't warn about unused parameters - ) - list(APPEND CEF_C_COMPILER_FLAGS - -std=c99 # Use the C99 language standard - ) - list(APPEND CEF_CXX_COMPILER_FLAGS - # -fno-exceptions # Disable exceptions - # -fno-rtti # Disable real-time type information - -fno-threadsafe-statics # Don't generate thread-safe statics - -fobjc-call-cxx-cdtors # Call the constructor/destructor of C++ instance variables in ObjC objects - -fvisibility-inlines-hidden # Give hidden visibility to inlined class member functions - -std=c++17 # Use the C++17 language standard - -Wno-narrowing # Don't warn about type narrowing - -Wsign-compare # Warn about mixed signed/unsigned type comparisons - ) - list(APPEND CEF_COMPILER_FLAGS_DEBUG - -O0 # Disable optimizations - -g # Generate debug information - ) - list(APPEND CEF_COMPILER_FLAGS_RELEASE - -O3 # Optimize for maximum speed plus a few extras - ) - list(APPEND CEF_LINKER_FLAGS - -Wl,-search_paths_first # Search for static or shared library versions in the same pass - -Wl,-ObjC # Support creation of ObjC static libraries - -Wl,-pie # Generate position-independent code suitable for executables only - ) - list(APPEND CEF_LINKER_FLAGS_RELEASE - -Wl,-dead_strip # Strip dead code - ) - - include(CheckCXXCompilerFlag) - - CHECK_CXX_COMPILER_FLAG(-Wno-undefined-var-template COMPILER_SUPPORTS_NO_UNDEFINED_VAR_TEMPLATE) - if(COMPILER_SUPPORTS_NO_UNDEFINED_VAR_TEMPLATE) - list(APPEND CEF_CXX_COMPILER_FLAGS - -Wno-undefined-var-template # Don't warn about potentially uninstantiated static members - ) - endif() - - # Standard libraries. - set(CEF_STANDARD_LIBS - -lpthread - "-framework Cocoa" - "-framework AppKit" - ) - - # Find the newest available base SDK. - execute_process(COMMAND xcode-select --print-path OUTPUT_VARIABLE XCODE_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) - foreach(OS_VERSION 10.15 10.14 10.13) - set(SDK "${XCODE_PATH}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${OS_VERSION}.sdk") - if(NOT "${CMAKE_OSX_SYSROOT}" AND EXISTS "${SDK}" AND IS_DIRECTORY "${SDK}") - set(CMAKE_OSX_SYSROOT ${SDK}) - endif() - endforeach() - - # Target SDK. - set(CEF_TARGET_SDK "10.13") - list(APPEND CEF_COMPILER_FLAGS - -mmacosx-version-min=${CEF_TARGET_SDK} - ) - set(CMAKE_OSX_DEPLOYMENT_TARGET ${CEF_TARGET_SDK}) - - # Target architecture. - if(PROJECT_ARCH STREQUAL "x86_64") - set(CMAKE_OSX_ARCHITECTURES "x86_64") - elseif(PROJECT_ARCH STREQUAL "arm64") - set(CMAKE_OSX_ARCHITECTURES "arm64") - else() - set(CMAKE_OSX_ARCHITECTURES "i386") - endif() - - # Prevent Xcode 11 from doing automatic codesigning. - set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "") - - # CEF directory paths. - set(CEF_BINARY_DIR "${_CEF_ROOT}/$") - set(CEF_BINARY_DIR_DEBUG "${_CEF_ROOT}/Debug") - set(CEF_BINARY_DIR_RELEASE "${_CEF_ROOT}/Release") - - if(USE_SANDBOX) - list(APPEND CEF_COMPILER_DEFINES - CEF_USE_SANDBOX # Used by apps to test if the sandbox is enabled - ) - - list(APPEND CEF_STANDARD_LIBS - -lsandbox - ) - - # CEF sandbox library paths. - set(CEF_SANDBOX_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/cef_sandbox.a") - set(CEF_SANDBOX_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/cef_sandbox.a") - endif() - - # CEF Helper app suffixes. - # Format is "::". - set(CEF_HELPER_APP_SUFFIXES - "::" - " (Alerts):_alerts:.alerts" - " (GPU):_gpu:.gpu" - " (Plugin):_plugin:.plugin" - " (Renderer):_renderer:.renderer" - ) -endif() - - -# -# Windows configuration. -# - -if(OS_WINDOWS) - if (GEN_NINJA) - # When using the Ninja generator clear the CMake defaults to avoid excessive - # console warnings (see issue #2120). - set(CMAKE_CXX_FLAGS "") - set(CMAKE_CXX_FLAGS_DEBUG "") - set(CMAKE_CXX_FLAGS_RELEASE "") - endif() - - if(USE_SANDBOX) - # Check if the current MSVC version is compatible with the cef_sandbox.lib - # static library. We require VS2015 or newer. - if(MSVC_VERSION LESS 1900) - message(WARNING "CEF sandbox is not compatible with the current MSVC version (${MSVC_VERSION})") - set(USE_SANDBOX OFF) - endif() - endif() - - # Consumers who run into LNK4099 warnings can pass /Z7 instead (see issue #385). - set(CEF_DEBUG_INFO_FLAG "/Zi" CACHE STRING "Optional flag specifying specific /Z flag to use") - - # Consumers using different runtime types may want to pass different flags - set(CEF_RUNTIME_LIBRARY_FLAG "/MT" CACHE STRING "Optional flag specifying which runtime to use") - if (CEF_RUNTIME_LIBRARY_FLAG) - list(APPEND CEF_COMPILER_FLAGS_DEBUG ${CEF_RUNTIME_LIBRARY_FLAG}d) - list(APPEND CEF_COMPILER_FLAGS_RELEASE ${CEF_RUNTIME_LIBRARY_FLAG}) - endif() - - # Platform-specific compiler/linker flags. - set(CEF_LIBTYPE STATIC) - list(APPEND CEF_COMPILER_FLAGS - /MP # Multiprocess compilation - /Gy # Enable function-level linking - /GR- # Disable run-time type information - /W4 # Warning level 4 - /WX # Treat warnings as errors - /wd4100 # Ignore "unreferenced formal parameter" warning - /wd4127 # Ignore "conditional expression is constant" warning - /wd4244 # Ignore "conversion possible loss of data" warning - /wd4324 # Ignore "structure was padded due to alignment specifier" warning - /wd4481 # Ignore "nonstandard extension used: override" warning - /wd4512 # Ignore "assignment operator could not be generated" warning - /wd4701 # Ignore "potentially uninitialized local variable" warning - /wd4702 # Ignore "unreachable code" warning - /wd4996 # Ignore "function or variable may be unsafe" warning - ${CEF_DEBUG_INFO_FLAG} - ) - list(APPEND CEF_COMPILER_FLAGS_DEBUG - /RTC1 # Disable optimizations - /Od # Enable basic run-time checks - ) - list(APPEND CEF_COMPILER_FLAGS_RELEASE - /O2 # Optimize for maximum speed - /Ob2 # Inline any suitable function - /GF # Enable string pooling - ) - list(APPEND CEF_CXX_COMPILER_FLAGS - /std:c++17 # Use the C++17 language standard - ) - list(APPEND CEF_LINKER_FLAGS_DEBUG - /DEBUG # Generate debug information - ) - list(APPEND CEF_EXE_LINKER_FLAGS - /MANIFEST:NO # No default manifest (see ADD_WINDOWS_MANIFEST macro usage) - /LARGEADDRESSAWARE # Allow 32-bit processes to access 3GB of RAM - ) - list(APPEND CEF_COMPILER_DEFINES - WIN32 _WIN32 _WINDOWS # Windows platform - UNICODE _UNICODE # Unicode build - # Targeting Windows 10. We can't say `=_WIN32_WINNT_WIN10` here because - # some files do `#if WINVER < 0x0600` without including windows.h before, - # and then _WIN32_WINNT_WIN10 isn't yet known to be 0x0A00. - WINVER=0x0A00 - _WIN32_WINNT=0x0A00 - NTDDI_VERSION=NTDDI_WIN10_FE - NOMINMAX # Use the standard's templated min/max - WIN32_LEAN_AND_MEAN # Exclude less common API declarations - _HAS_EXCEPTIONS=0 # Disable exceptions - ) - list(APPEND CEF_COMPILER_DEFINES_RELEASE - NDEBUG _NDEBUG # Not a debug build - ) - - if(PROJECT_ARCH STREQUAL "x86") - # Set the initial stack size to 0.5MiB, instead of the 1.5MiB minimum - # needed by CEF's main thread. This saves significant memory on threads - # (like those in the Windows thread pool, and others) whose stack size we - # can only control through this setting. The main thread (in 32-bit builds - # only) uses fibers to switch to a 4MiB stack at runtime via - # CefRunWinMainWithPreferredStackSize(). - list(APPEND CEF_EXE_LINKER_FLAGS - /STACK:0x80000 - ) - else() - # Increase the initial stack size to 8MiB from the default 1MiB. - list(APPEND CEF_EXE_LINKER_FLAGS - /STACK:0x800000 - ) - endif() - - # Standard libraries. - set(CEF_STANDARD_LIBS - comctl32.lib - gdi32.lib - rpcrt4.lib - shlwapi.lib - ws2_32.lib - ) - - # CEF directory paths. - set(CEF_RESOURCE_DIR "${_CEF_ROOT}/Resources") - set(CEF_BINARY_DIR "${_CEF_ROOT}/$") - set(CEF_BINARY_DIR_DEBUG "${_CEF_ROOT}/Debug") - set(CEF_BINARY_DIR_RELEASE "${_CEF_ROOT}/Release") - - # CEF library paths. - set(CEF_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/libcef.lib") - set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.lib") - - # List of CEF binary files. - set(CEF_BINARY_FILES - chrome_elf.dll - d3dcompiler_47.dll - libcef.dll - libEGL.dll - libGLESv2.dll - snapshot_blob.bin - v8_context_snapshot.bin - vk_swiftshader.dll - vk_swiftshader_icd.json - vulkan-1.dll - ) - - # List of CEF resource files. - set(CEF_RESOURCE_FILES - chrome_100_percent.pak - chrome_200_percent.pak - resources.pak - icudtl.dat - locales - ) - - if(USE_SANDBOX) - list(APPEND CEF_COMPILER_DEFINES - PSAPI_VERSION=1 # Required by cef_sandbox.lib - CEF_USE_SANDBOX # Used by apps to test if the sandbox is enabled - ) - list(APPEND CEF_COMPILER_DEFINES_DEBUG - _HAS_ITERATOR_DEBUGGING=0 # Disable iterator debugging - ) - - # Libraries required by cef_sandbox.lib. - set(CEF_SANDBOX_STANDARD_LIBS - Advapi32.lib - dbghelp.lib - Delayimp.lib - ntdll.lib - OleAut32.lib - PowrProf.lib - Propsys.lib - psapi.lib - SetupAPI.lib - Shell32.lib - Shcore.lib - Userenv.lib - version.lib - wbemuuid.lib - WindowsApp.lib - winmm.lib - ) - - # CEF sandbox library paths. - set(CEF_SANDBOX_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/cef_sandbox.lib") - set(CEF_SANDBOX_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/cef_sandbox.lib") - endif() - - # Configure use of ATL. - option(USE_ATL "Enable or disable use of ATL." ON) - if(USE_ATL) - # Locate the atlmfc directory if it exists. It may be at any depth inside - # the VC directory. The cl.exe path returned by CMAKE_CXX_COMPILER may also - # be at different depths depending on the toolchain version - # (e.g. "VC/bin/cl.exe", "VC/bin/amd64_x86/cl.exe", - # "VC/Tools/MSVC/14.10.25017/bin/HostX86/x86/cl.exe", etc). - set(HAS_ATLMFC 0) - get_filename_component(VC_DIR ${CMAKE_CXX_COMPILER} DIRECTORY) - get_filename_component(VC_DIR_NAME ${VC_DIR} NAME) - while(NOT ${VC_DIR_NAME} STREQUAL "VC") - get_filename_component(VC_DIR ${VC_DIR} DIRECTORY) - if(IS_DIRECTORY "${VC_DIR}/atlmfc") - set(HAS_ATLMFC 1) - break() - endif() - get_filename_component(VC_DIR_NAME ${VC_DIR} NAME) - endwhile() - - # Determine if the Visual Studio install supports ATL. - if(NOT HAS_ATLMFC) - message(WARNING "ATL is not supported by your VC installation.") - set(USE_ATL OFF) - endif() - endif() - - if(USE_ATL) - list(APPEND CEF_COMPILER_DEFINES - CEF_USE_ATL # Used by apps to test if ATL support is enabled - ) - endif() -endif() diff --git a/README.md b/README.md index 3c7bb11..4b4b7cf 100644 --- a/README.md +++ b/README.md @@ -7,160 +7,193 @@ help wanted + Compatibility gallery

-# 1. Disclaimer -**This is an educational project**. Although the project started as a learning exercise on the Irrlicht Engine, it has kind of turned into an OpenGL one instead due to limitations and issues with Irrlicht (most likely caused by my limited experience with graphics programming). As it turns out, working directly with OpenGL is not as hard as I thought. For more information on the project's license, check [LICENSE](LICENSE). +# 🖼️ Linux Wallpaper Engine -# 2. What is this project all about? -This project aims to reproduce the background functionality of Wallpaper Engine on Linux systems. Simple as that. +Bring **Wallpaper Engine**-style live wallpapers to Linux! This project allows you to run animated wallpapers from Steam’s Wallpaper Engine right on your desktop. -# 3. What is Wallpaper Engine? -Wallpaper Engine is a software designed by [Kristjan Skutta](https://store.steampowered.com/search/?developer=Kristjan%20Skutta&snr=1_5_9__400) that provides live wallpaper functionality to Windows Systems, allowing its users to animate their own backgrounds and share their own creations. You can find more about it on their [Steam page](https://store.steampowered.com/app/431960/Wallpaper_Engine/). +> ⚠️ This is an educational project that evolved into a functional OpenGL-based wallpaper engine for Linux. Expect some limitations and quirks! + +--- + +## 📦 System Requirements + +To compile and run this, you'll need: -# 4. Compilation requirements -## linux-wallpaperengine - OpenGL 3.3 support - CMake -- LZ4 -- ZLIB +- LZ4, Zlib - SDL2 - FFmpeg -- X11 (with libxxf86vm) or Wayland -- Xrandr (for X11 support) -- GLFW3 -- GLM -- GLEW -- GLUT +- X11 or Wayland +- Xrandr (for X11) +- GLFW3, GLEW, GLUT, GLM - MPV - PulseAudio +- FFTW3 -## Commands -``` +Install the required dependencies on Ubuntu/Debian-based systems: + +### Ubuntu 22.04 +```bash sudo apt-get update -sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 +sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv1 libpulse-dev libpulse0 libfftw3-dev ``` -# 5. How to use -## 5.1. Pre-requirements -In order to properly use this software you'll need to own an actual copy of the Windows version of Wallpaper Engine (which you can buy on the [Steam Page](https://store.steampowered.com/app/431960/Wallpaper_Engine/)), as it contains some basic assets on which most of the backgrounds are based on. - -The only way to get those assets is to install the Windows version through Steam. Luckily you don't really need a Windows installation for that. Using the Linux Steam client is enough to download the files we need. Note you may need to check "Enable Steam Play for all other titles" in the Steam Play section of Steam's settings if you haven't already. Also note that the software cannot actually be launched through Steam Play (Proton), but the setting is required for Steam to download the software. - -## 5.2. Extracting the assets -The automatic way doesn't require anything extra, as long as Wallpaper Engine is installed in Steam the software should automatically detect where the assets are. - -### 5.2.1. Extracting the assets manually -In the off-case where the software doesn't automatically detect the correct path, the assets can be extracted manually. Once Wallpaper Engine is downloaded, open the installation folder (Right-Click the application in Steam -> Manage -> Browse local files). Here you'll see the main folders of Wallpaper Engine. The folder we're interested in is the one named "assets". - -![folder](docs/images/screenshot_folder.png) - -The assets folder itself **must** be copied to the same folder where the binary lives. - -## 5.3. Getting the sources -You can download a zipped version of the repository here: https://github.com/Almamu/linux-wallpaperengine/archive/refs/heads/main.zip - -You can also clone the repository using git like this: -``` -git clone git@github.com:Almamu/linux-wallpaperengine.git +### Ubuntu 24.04 +```bash +sudo apt-get update +sudo apt-get install build-essential cmake libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev ``` -Or using the HTTPS method if you haven't set up SSH: -``` -https://github.com/Almamu/linux-wallpaperengine.git +--- + +## 🐧 Arch Linux Users + +You can install this directly from the AUR using your favorite AUR helper: + +```bash +yay -S linux-wallpaperengine-git ``` -## 5.4. Compilation steps -The project is built on CMake as the build engine. First we need to create the directory where the build will be stored and get into it: +> This installs the latest development version. + +**Note:** You’ll still need assets from the official Wallpaper Engine (via Steam). See below for details. + +--- + +## 🚀 Getting Started + +### 1. Get Wallpaper Engine Assets + +You **must own and install Wallpaper Engine** via Steam. This provides the required assets used by many backgrounds. + +Good news: **you usually don’t need to copy anything manually.** The app will automatically look in these common install paths: ``` -mkdir build -cd build +~/.steam/steam/steamapps/common +~/.local/share/Steam/steamapps/common +~/.var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/common +~/snap/steam/common/.local/share/Steam/steamapps/common ``` -Once the folder is created and we're in it, CMake has to generate the actual Makefiles. This can be done this way: +> ✅ If Wallpaper Engine is installed in one of these paths, the assets will be detected automatically! + +--- + +#### ❗ If Assets Aren’t Found Automatically + +You can copy the `assets` folder manually: + +1. In Steam, right-click **Wallpaper Engine** → **Manage** → **Browse local files** +2. Copy the `assets` folder +3. Paste it into the same folder where the `linux-wallpaperengine` binary is located + +--- + +### 2. Build from Source + +Clone the repo: + +```bash +git clone --recurse-submodules https://github.com/Almamu/linux-wallpaperengine.git +cd linux-wallpaperengine ``` + +Build it: + +```bash +mkdir build && cd build cmake .. -``` -Take a closer look at the CMake output, if you miss any library, CMake will report the missing libraries so you can install them either trough your package manager or manually in your system. - -Finally we can compile the project to generate the actual executable. -``` make ``` -**REMEMBER: The assets folder has to be in the same folder as the executable** +Once the build process is finished, this should create a new `output` folder containing the app and all the required +support files to run. -## 5.5. Running a background -### 5.5.1. Running a background from Steam -Just like with the assets, the software can automatically detect where the subscribed backgrounds are stored. To get started, search in the workshop for whatever background you want to use and click the "+Subscribe" button. This should download the background in the steam directory. +> ✅ Remember: Place the `assets` folder next to the built binary if it isn’t detected automatically. -To actually use the background you'll need to know the workshop's ID. This can be obtained right-clicking anywhere in the background's page -> "Copy Page URL". You can paste this URL anywhere, it will look something like this: +--- -``` -https://steamcommunity.com/sharedfiles/filedetails/?id=1845706469&searchtext=portal+3 +## 🧪 Usage + +Basic syntax: + +```bash +./linux-wallpaperengine [options] ``` -Where 1845706469 is the wallpaper's ID. You can use this ID to run wallpaperengine: -``` +You can use either: +- A Steam Workshop ID (e.g. `1845706469`) +- A path to a background folder + +--- + +### 🔧 Common Options + +| Option | Description | +|--------|-------------| +| `--silent` | Mute background audio | +| `--volume ` | Set audio volume | +| `--noautomute` | Don't mute when other apps play audio | +| `--no-audio-processing` | Disable audio reactive features | +| `--fps ` | Limit frame rate | +| `--window ` | Run in windowed mode with custom size/position | +| `--screen-root ` | Set as background for specific screen | +| `--bg ` | Assign a background to a specific screen (use after `--screen-root`) | +| `--scaling ` | Wallpaper scaling: `stretch`, `fit`, `fill`, or `default` | +| `--clamping ` | Set texture clamping: `clamp`, `border`, `repeat` | +| `--assets-dir ` | Set custom path for assets | +| `--screenshot ` | Save screenshot (PNG, JPEG, BMP) | +| `--list-properties` | Show customizable properties of a wallpaper | +| `--set-property name=value` | Override a specific property | +| `--disable-mouse` | Disable mouse interaction | +| `--disable-parallax` | Disable parallax effect on backgrounds that support it | +| `--no-fullscreen-pause` | Prevent pausing while fullscreen apps are running | + +--- + +### 💡 Examples + +#### Run a background by ID +```bash ./linux-wallpaperengine 1845706469 ``` -### 5.5.2. Running a background in a different folder -For the situations where the software cannot detect where the backgrounds are stored, you can specify a full path to it, like so: -``` -./linux-wallpaperengine /home/almamu/Development/backgrounds/1845706469/ +#### Run a background from a folder +```bash +./linux-wallpaperengine ~/backgrounds/1845706469/ ``` -### 5.5.2. Running in a window (Default) -By default the app will load the backgrounds in a window so you can preview them: -``` -./linux-wallpaperengine /home/almamu/Development/backgrounds/1845706469/ +#### Assign backgrounds to screens with scaling +```bash +./linux-wallpaperengine \ + --scaling stretch --screen-root eDP-1 --bg 2667198601 \ + --scaling fill --screen-root HDMI-1 --bg 2667198602 ``` -Where `/home/almamu/Development/backgrounds/1845706469/` is the background's path. - -### 5.5.3. Running as a screen's background -The app supports running as background in X11 and Wayland. Use the --screen-root switch and the screen name, like so: - -``` -./linux-wallpaperengine --screen-root HDMI-1 --screen-root DVI-D-1 1845706469 +#### Run in a window +```bash +./linux-wallpaperengine --window 0x0x1280x720 1845706469 ``` -#### Wayland -Has only been tested under wlroots but should work on any flavour as long as wlr-layer-shell-unstable is supported. - -#### X11 -Only screens configured with the XRandr extension are supported. To specify the screen names (as reported from xrandr tool) just use the ```--screen-root``` switch. You can specify multiple screens at the same time, for example: - -**IMPORTANT: Right now this doesn't work if there is anything drawing to the background (like a compositor, gnome, kde, nautilus, etc)** - - -### 5.5.4. Limiting FPS -To reduce the performance hit to your system you can reduce (or increase) the FPS limit with the switch ```--fps```, especially useful for laptops: -``` -./linux-wallpaperengine --fps 30 +#### Limit FPS to save power +```bash +./linux-wallpaperengine --fps 30 1845706469 ``` -## 5.6. Audio -### 5.6.1. Disable audio -It's possible to disable the audio of the background with the silent argument -``` -./linux-wallpaperengine --silent +#### Take a screenshot +```bash +./linux-wallpaperengine --screenshot ~/wallpaper.png 1845706469 ``` -## 5.7. Taking a screenshot -It is possible to take a screenshot of the screen's content at the moment a background is loaded up and rendered. Useful for tools like pywal to further customize your environment: -``` -./linux-wallpaperengine --screenshot /path/to/screenshot/name.png -``` +This can be useful as output for pywal or other color systems that use images as basis to generate a set of colors +to apply to your system. -PNG, BMP and JPEG are supported. - -## 5.8. Properties -Some backgrounds have a list of properties that the user can customize. These properties modify how parts of the background behave or look like. Support for these is present. -First, list all the available properties in a background, you can do that with the --list-properties switch: -``` +#### View and change properties +```bash ./linux-wallpaperengine --list-properties 2370927443 ``` @@ -219,18 +252,43 @@ Any of these values can be modified with the --set-property switch. Say you want ./linux-wallpaperengine --set-property bloom=1 2370927443 ``` -If you keep --list-properties in the commandline you can see how the values change to confirm that it applied properly. +--- -## 6. Example background -This was the first background to even be compatible with the software. And it's not 100% compatible yet. Both textures and shaders are properly loaded, but there are still particles missing. +## 🧪 Wayland & X11 Support -![example](docs/images/example.gif) +- **Wayland**: Works with compositors that support `wlr-layer-shell-unstable`. +- **X11**: Requires XRandr. Use `--screen-root ` (as shown in `xrandr`). -###### 1845706469 -In similar fashion to the example background, this one represents the progress of the program. It leverages FBOs (targets), and multiple-effects over objects. +> ⚠ For X11 users: Currently doesn't work if a compositor or desktop environment (e.g. GNOME, KDE, Nautilus) is drawing the background. +--- + +## 🌈 Example Backgrounds + +![example1](docs/images/example.gif) ![example2](docs/images/example2.gif) -# 7. Special thanks -- [RePKG](https://github.com/notscuffed/repkg) for the information on texture flags -- [RenderDoc](https://github.com/baldurk/renderdoc) for the so helpful OpenGL debugging tool that simplified finding issues on the new OpenGL code. Seriously this tool ROCKS +## 🪲 Common issues +### Black screen when setting as screen's background +This can be caused by a few different things depending on your environment and setup. + +### X11 +Common symptom of a compositor drawing to the background which prevents Wallpaper Engine from being properly visible. +The only solution currently is disabling the compositor so Wallpaper Engine can properly draw on the screen + +### NVIDIA +Some users have had issues with GLFW initialization and other OpenGL errors. These are generally something that's +worth reporting in the issues. Sometimes adding this variable when running Wallpaper Engine helps and/or solves +the issue: +```bash +__GL_THREADED_OPTIMIZATIONS=0 linux-wallpaperengine +``` + +We'll be looking at improving this in the future, but for now it can be a useful workaround. + +--- + +## 🙏 Special Thanks + +- [RePKG](https://github.com/notscuffed/repkg) – for texture flag insights +- [RenderDoc](https://github.com/baldurk/renderdoc) – the best OpenGL debugger out there! diff --git a/docs/images/screenshot_folder.png b/docs/images/screenshot_folder.png deleted file mode 100644 index 8387e34b2528be44c83575e3b6f147ff3c40ac98..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 34650 zcmd42Wmp|sw3%?Esyyw<{H58GpwW4uXwsfn2qtMZB^pu9BRooa=6E$b4sU+EqFv6*|3 zd+xj+U3NXUxK#p2^_ zx~KHEV(~cnrH+N33UP?B%!X2$5^nG0@%Sz;KmVQSVCAsTyTIrv=|Z;mD7_`B`&oJk zgsDn-FsSBJVkQGt`7@N|^{e=~ri^Va2jzDa-q*!qrJ)=rB|J`%dXz#*GT{F>EW2iTr`RMoOE3AN?L6F3s&hW| z!bpSN>U1{bUB1LvVtVx@{t{!LaKaIH7<%5uNHHXC-JQ<}+)UR<)Qh}sIpeCN@G!cM zGF~NsA;0*KXbu5Qk~5-M-%LFRB&CJrozw22JxxfaayCBfbMS=|0)Rey8Z$;{%@`p1KYse`RkZr5Tu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A9wyA>b#Kw0x$@Cq~eriIPQXL4+Qz3 zfjhz77=+@NSaVYKn|heYe8GpAyTd;$MR3AsGAf`1@1{|Ibv`G;o|8GaoVmE@9(eGc z=ptpRIjID=9)%I+(>K5C)u9bDZ!jLQlr~UdBkx1(=kcWwDE29uru%epNv?$(3a;xD>ozXpGWx4o4`OLaCf-0 zzZsHJzTg8Tu`5K--ihPCjrL~r{C%;)bdWa8iE3dsk%kK|&H%G|(UyPM{!I<$?qDrQ zh=R7yi5nyUSN6#Pz4G7|YYJXIaSZXuh+3G7iy+95tt=69rn=k`q`;0UD3IjPD9)aGo$!6 z$D3K=?aeF^j{U0-I)3@PIcA}YzU$KK6t>INBXI4c z+xA|*Gb#f8Be01%X6Jna!w%H z#VCBen%cHXxw2L4Od;s=Ug}C2%i^)Ps(7`By|=3PU1i9>y(xB05bI_V=T6ZYncc9bzZ5+ zWz?&)ef&x9%Z97-t!1v1vq3ZA^B*fB`x|5R7d^I~o2}q!bD_ByBKJdXyav}ukGI31 z2RxhL$A0d^EApkTzIF1i$KDNR-%wL7yUnt*vxQGYz|#sY!VIn=y-zUO#6^|J?^eMq zIPp{9H0nt%+l8L|y6#EK@Ig7g{>4RhiszOs`1Rh4R1`Tp7y>{3f`@Eb_Eeyc8zU^$OXRp$+$3jZ+ftAi}2%Th|?p?q5B9bzv-`Jig85}q|zuFJ0T|vV2;>j@r+0qDw zzqsgXfSe;Cc)Pb7vUTfKH%iBi*Xiw*^**Z$`--tB0yDJ-u#(+a`%cFDz<8{iIkR!~ hth{hGF{Ssyd%_=EPFi3q0bB=8T3i8A^u+M>{{rQdsaXI3 diff --git a/docs/images/zip.png b/docs/images/zip.png deleted file mode 100644 index 51d6db970f7a25699360900d30fc8660204e7c21..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 118882 zcmV)0K+eC3P) zaB^>EX>4U6ba`-PAZ2)IW&i+q+O3;cb|gEtWdAXW9s;x&4&+*I20i@Vh7b&rnN_!5 z7n#W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^5tKHyJ$Ma4@B9AH~>pn z9DoB*8~~~Tv=VL>^ZOy-va!IQt1~0U{R30h BQVRe8 diff --git a/include/nlohmann/adl_serializer.hpp b/include/nlohmann/adl_serializer.hpp deleted file mode 100644 index 53c9009..0000000 --- a/include/nlohmann/adl_serializer.hpp +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include - -#include -#include - -namespace nlohmann -{ -template -struct adl_serializer -{ - /*! - @brief convert a JSON value to any value type - - This function is usually called by the `get()` function of the - @ref basic_json class (either explicit or via conversion operators). - - @param[in] j JSON value to read from - @param[in,out] val value to write to - */ - template - static void from_json(BasicJsonType&& j, ValueType& val) noexcept( - noexcept(::nlohmann::from_json(std::forward(j), val))) - { - ::nlohmann::from_json(std::forward(j), val); - } - - /*! - @brief convert any value type to a JSON value - - This function is usually called by the constructors of the @ref basic_json - class. - - @param[in,out] j JSON value to write to - @param[in] val value to read from - */ - template - static void to_json(BasicJsonType& j, ValueType&& val) noexcept( - noexcept(::nlohmann::to_json(j, std::forward(val)))) - { - ::nlohmann::to_json(j, std::forward(val)); - } -}; -} diff --git a/include/nlohmann/detail/conversions/from_json.hpp b/include/nlohmann/detail/conversions/from_json.hpp deleted file mode 100644 index cd6bfd1..0000000 --- a/include/nlohmann/detail/conversions/from_json.hpp +++ /dev/null @@ -1,378 +0,0 @@ -#pragma once - -#include // transform -#include // array -#include // and, not -#include // forward_list -#include // inserter, front_inserter, end -#include // map -#include // string -#include // tuple, make_tuple -#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible -#include // unordered_map -#include // pair, declval -#include // valarray - -#include -#include -#include -#include - -namespace nlohmann -{ -namespace detail -{ -// overloads for basic_json template parameters -template::value and - not std::is_same::value, - int> = 0> -void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) -{ - switch (static_cast(j)) - { - case value_t::number_unsigned: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_integer: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_float: - { - val = static_cast(*j.template get_ptr()); - break; - } - - default: - JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); - } -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) -{ - if (JSON_UNLIKELY(not j.is_boolean())) - { - JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()))); - } - b = *j.template get_ptr(); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) -{ - if (JSON_UNLIKELY(not j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); - } - s = *j.template get_ptr(); -} - -template < - typename BasicJsonType, typename CompatibleStringType, - enable_if_t < - is_compatible_string_type::value and - not std::is_same::value, - int > = 0 > -void from_json(const BasicJsonType& j, CompatibleStringType& s) -{ - if (JSON_UNLIKELY(not j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); - } - - s = *j.template get_ptr(); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) -{ - get_arithmetic_value(j, val); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) -{ - get_arithmetic_value(j, val); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) -{ - get_arithmetic_value(j, val); -} - -template::value, int> = 0> -void from_json(const BasicJsonType& j, EnumType& e) -{ - typename std::underlying_type::type val; - get_arithmetic_value(j, val); - e = static_cast(val); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) -{ - if (JSON_UNLIKELY(not j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); - } - arr = *j.template get_ptr(); -} - -// forward_list doesn't have an insert method -template::value, int> = 0> -void from_json(const BasicJsonType& j, std::forward_list& l) -{ - if (JSON_UNLIKELY(not j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); - } - std::transform(j.rbegin(), j.rend(), - std::front_inserter(l), [](const BasicJsonType & i) - { - return i.template get(); - }); -} - -// valarray doesn't have an insert method -template::value, int> = 0> -void from_json(const BasicJsonType& j, std::valarray& l) -{ - if (JSON_UNLIKELY(not j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); - } - l.resize(j.size()); - std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l)); -} - -template -void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/) -{ - using std::end; - - std::transform(j.begin(), j.end(), - std::inserter(arr, end(arr)), [](const BasicJsonType & i) - { - // get() returns *this, this won't call a from_json - // method when value_type is BasicJsonType - return i.template get(); - }); -} - -template -auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/) --> decltype( - arr.reserve(std::declval()), - void()) -{ - using std::end; - - arr.reserve(j.size()); - std::transform(j.begin(), j.end(), - std::inserter(arr, end(arr)), [](const BasicJsonType & i) - { - // get() returns *this, this won't call a from_json - // method when value_type is BasicJsonType - return i.template get(); - }); -} - -template -void from_json_array_impl(const BasicJsonType& j, std::array& arr, priority_tag<2> /*unused*/) -{ - for (std::size_t i = 0; i < N; ++i) - { - arr[i] = j.at(i).template get(); - } -} - -template < - typename BasicJsonType, typename CompatibleArrayType, - enable_if_t < - is_compatible_array_type::value and - not std::is_same::value and - std::is_constructible < - BasicJsonType, typename CompatibleArrayType::value_type >::value, - int > = 0 > -void from_json(const BasicJsonType& j, CompatibleArrayType& arr) -{ - if (JSON_UNLIKELY(not j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + - std::string(j.type_name()))); - } - - from_json_array_impl(j, arr, priority_tag<2> {}); -} - -template::value, int> = 0> -void from_json(const BasicJsonType& j, CompatibleObjectType& obj) -{ - if (JSON_UNLIKELY(not j.is_object())) - { - JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()))); - } - - auto inner_object = j.template get_ptr(); - using value_type = typename CompatibleObjectType::value_type; - std::transform( - inner_object->begin(), inner_object->end(), - std::inserter(obj, obj.begin()), - [](typename BasicJsonType::object_t::value_type const & p) - { - return value_type(p.first, p.second.template get()); - }); -} - -// overload for arithmetic types, not chosen for basic_json template arguments -// (BooleanType, etc..); note: Is it really necessary to provide explicit -// overloads for boolean_t etc. in case of a custom BooleanType which is not -// an arithmetic type? -template::value and - not std::is_same::value and - not std::is_same::value and - not std::is_same::value and - not std::is_same::value, - int> = 0> -void from_json(const BasicJsonType& j, ArithmeticType& val) -{ - switch (static_cast(j)) - { - case value_t::number_unsigned: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_integer: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_float: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::boolean: - { - val = static_cast(*j.template get_ptr()); - break; - } - - default: - JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); - } -} - -template -void from_json(const BasicJsonType& j, std::pair& p) -{ - p = {j.at(0).template get(), j.at(1).template get()}; -} - -template -void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence) -{ - t = std::make_tuple(j.at(Idx).template get::type>()...); -} - -template -void from_json(const BasicJsonType& j, std::tuple& t) -{ - from_json_tuple_impl(j, t, index_sequence_for {}); -} - -template ::value>> -void from_json(const BasicJsonType& j, std::map& m) -{ - if (JSON_UNLIKELY(not j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); - } - for (const auto& p : j) - { - if (JSON_UNLIKELY(not p.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); - } - m.emplace(p.at(0).template get(), p.at(1).template get()); - } -} - -template ::value>> -void from_json(const BasicJsonType& j, std::unordered_map& m) -{ - if (JSON_UNLIKELY(not j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); - } - for (const auto& p : j) - { - if (JSON_UNLIKELY(not p.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); - } - m.emplace(p.at(0).template get(), p.at(1).template get()); - } -} - -struct from_json_fn -{ - private: - template - auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const - noexcept(noexcept(from_json(j, val))) - -> decltype(from_json(j, val), void()) - { - return from_json(j, val); - } - - template - void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept - { - static_assert(sizeof(BasicJsonType) == 0, - "could not find from_json() method in T's namespace"); -#ifdef _MSC_VER - // MSVC does not show a stacktrace for the above assert - using decayed = uncvref_t; - static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0, - "forcing MSVC stacktrace to show which T we're talking about."); -#endif - } - - public: - template - void operator()(const BasicJsonType& j, T& val) const - noexcept(noexcept(std::declval().call(j, val, priority_tag<1> {}))) - { - return call(j, val, priority_tag<1> {}); - } -}; -} - -/// namespace to hold default `from_json` function -/// to see why this is required: -/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html -namespace -{ -constexpr const auto& from_json = detail::static_const::value; -} -} diff --git a/include/nlohmann/detail/conversions/to_chars.hpp b/include/nlohmann/detail/conversions/to_chars.hpp deleted file mode 100644 index a13d258..0000000 --- a/include/nlohmann/detail/conversions/to_chars.hpp +++ /dev/null @@ -1,1095 +0,0 @@ -#pragma once - -#include // assert -#include // or, and, not -#include // signbit, isfinite -#include // intN_t, uintN_t -#include // memcpy, memmove - -namespace nlohmann -{ -namespace detail -{ - -/*! -@brief implements the Grisu2 algorithm for binary to decimal floating-point -conversion. - -This implementation is a slightly modified version of the reference -implementation which may be obtained from -http://florian.loitsch.com/publications (bench.tar.gz). - -The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. - -For a detailed description of the algorithm see: - -[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with - Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming - Language Design and Implementation, PLDI 2010 -[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", - Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language - Design and Implementation, PLDI 1996 -*/ -namespace dtoa_impl -{ - -template -Target reinterpret_bits(const Source source) -{ - static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); - - Target target; - std::memcpy(&target, &source, sizeof(Source)); - return target; -} - -struct diyfp // f * 2^e -{ - static constexpr int kPrecision = 64; // = q - - uint64_t f; - int e; - - constexpr diyfp() noexcept : f(0), e(0) {} - constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {} - - /*! - @brief returns x - y - @pre x.e == y.e and x.f >= y.f - */ - static diyfp sub(const diyfp& x, const diyfp& y) noexcept - { - assert(x.e == y.e); - assert(x.f >= y.f); - - return diyfp(x.f - y.f, x.e); - } - - /*! - @brief returns x * y - @note The result is rounded. (Only the upper q bits are returned.) - */ - static diyfp mul(const diyfp& x, const diyfp& y) noexcept - { - static_assert(kPrecision == 64, "internal error"); - - // Computes: - // f = round((x.f * y.f) / 2^q) - // e = x.e + y.e + q - - // Emulate the 64-bit * 64-bit multiplication: - // - // p = u * v - // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) - // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) - // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) - // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) - // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) - // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) - // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) - // - // (Since Q might be larger than 2^32 - 1) - // - // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) - // - // (Q_hi + H does not overflow a 64-bit int) - // - // = p_lo + 2^64 p_hi - - const uint64_t u_lo = x.f & 0xFFFFFFFF; - const uint64_t u_hi = x.f >> 32; - const uint64_t v_lo = y.f & 0xFFFFFFFF; - const uint64_t v_hi = y.f >> 32; - - const uint64_t p0 = u_lo * v_lo; - const uint64_t p1 = u_lo * v_hi; - const uint64_t p2 = u_hi * v_lo; - const uint64_t p3 = u_hi * v_hi; - - const uint64_t p0_hi = p0 >> 32; - const uint64_t p1_lo = p1 & 0xFFFFFFFF; - const uint64_t p1_hi = p1 >> 32; - const uint64_t p2_lo = p2 & 0xFFFFFFFF; - const uint64_t p2_hi = p2 >> 32; - - uint64_t Q = p0_hi + p1_lo + p2_lo; - - // The full product might now be computed as - // - // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) - // p_lo = p0_lo + (Q << 32) - // - // But in this particular case here, the full p_lo is not required. - // Effectively we only need to add the highest bit in p_lo to p_hi (and - // Q_hi + 1 does not overflow). - - Q += uint64_t{1} << (64 - 32 - 1); // round, ties up - - const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32); - - return diyfp(h, x.e + y.e + 64); - } - - /*! - @brief normalize x such that the significand is >= 2^(q-1) - @pre x.f != 0 - */ - static diyfp normalize(diyfp x) noexcept - { - assert(x.f != 0); - - while ((x.f >> 63) == 0) - { - x.f <<= 1; - x.e--; - } - - return x; - } - - /*! - @brief normalize x such that the result has the exponent E - @pre e >= x.e and the upper e - x.e bits of x.f must be zero. - */ - static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept - { - const int delta = x.e - target_exponent; - - assert(delta >= 0); - assert(((x.f << delta) >> delta) == x.f); - - return diyfp(x.f << delta, target_exponent); - } -}; - -struct boundaries -{ - diyfp w; - diyfp minus; - diyfp plus; -}; - -/*! -Compute the (normalized) diyfp representing the input number 'value' and its -boundaries. - -@pre value must be finite and positive -*/ -template -boundaries compute_boundaries(FloatType value) -{ - assert(std::isfinite(value)); - assert(value > 0); - - // Convert the IEEE representation into a diyfp. - // - // If v is denormal: - // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) - // If v is normalized: - // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) - - static_assert(std::numeric_limits::is_iec559, - "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); - - constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) - constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); - constexpr int kMinExp = 1 - kBias; - constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1) - - using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type; - - const uint64_t bits = reinterpret_bits(value); - const uint64_t E = bits >> (kPrecision - 1); - const uint64_t F = bits & (kHiddenBit - 1); - - const bool is_denormal = (E == 0); - const diyfp v = is_denormal - ? diyfp(F, kMinExp) - : diyfp(F + kHiddenBit, static_cast(E) - kBias); - - // Compute the boundaries m- and m+ of the floating-point value - // v = f * 2^e. - // - // Determine v- and v+, the floating-point predecessor and successor if v, - // respectively. - // - // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) - // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) - // - // v+ = v + 2^e - // - // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ - // between m- and m+ round to v, regardless of how the input rounding - // algorithm breaks ties. - // - // ---+-------------+-------------+-------------+-------------+--- (A) - // v- m- v m+ v+ - // - // -----------------+------+------+-------------+-------------+--- (B) - // v- m- v m+ v+ - - const bool lower_boundary_is_closer = (F == 0 and E > 1); - const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); - const diyfp m_minus = lower_boundary_is_closer - ? diyfp(4 * v.f - 1, v.e - 2) // (B) - : diyfp(2 * v.f - 1, v.e - 1); // (A) - - // Determine the normalized w+ = m+. - const diyfp w_plus = diyfp::normalize(m_plus); - - // Determine w- = m- such that e_(w-) = e_(w+). - const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); - - return {diyfp::normalize(v), w_minus, w_plus}; -} - -// Given normalized diyfp w, Grisu needs to find a (normalized) cached -// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies -// within a certain range [alpha, gamma] (Definition 3.2 from [1]) -// -// alpha <= e = e_c + e_w + q <= gamma -// -// or -// -// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q -// <= f_c * f_w * 2^gamma -// -// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies -// -// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma -// -// or -// -// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) -// -// The choice of (alpha,gamma) determines the size of the table and the form of -// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well -// in practice: -// -// The idea is to cut the number c * w = f * 2^e into two parts, which can be -// processed independently: An integral part p1, and a fractional part p2: -// -// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e -// = (f div 2^-e) + (f mod 2^-e) * 2^e -// = p1 + p2 * 2^e -// -// The conversion of p1 into decimal form requires a series of divisions and -// modulos by (a power of) 10. These operations are faster for 32-bit than for -// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be -// achieved by choosing -// -// -e >= 32 or e <= -32 := gamma -// -// In order to convert the fractional part -// -// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... -// -// into decimal form, the fraction is repeatedly multiplied by 10 and the digits -// d[-i] are extracted in order: -// -// (10 * p2) div 2^-e = d[-1] -// (10 * p2) mod 2^-e = d[-2] / 10^1 + ... -// -// The multiplication by 10 must not overflow. It is sufficient to choose -// -// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. -// -// Since p2 = f mod 2^-e < 2^-e, -// -// -e <= 60 or e >= -60 := alpha - -constexpr int kAlpha = -60; -constexpr int kGamma = -32; - -struct cached_power // c = f * 2^e ~= 10^k -{ - uint64_t f; - int e; - int k; -}; - -/*! -For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached -power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c -satisfies (Definition 3.2 from [1]) - - alpha <= e_c + e + q <= gamma. -*/ -inline cached_power get_cached_power_for_binary_exponent(int e) -{ - // Now - // - // alpha <= e_c + e + q <= gamma (1) - // ==> f_c * 2^alpha <= c * 2^e * 2^q - // - // and since the c's are normalized, 2^(q-1) <= f_c, - // - // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) - // ==> 2^(alpha - e - 1) <= c - // - // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as - // - // k = ceil( log_10( 2^(alpha - e - 1) ) ) - // = ceil( (alpha - e - 1) * log_10(2) ) - // - // From the paper: - // "In theory the result of the procedure could be wrong since c is rounded, - // and the computation itself is approximated [...]. In practice, however, - // this simple function is sufficient." - // - // For IEEE double precision floating-point numbers converted into - // normalized diyfp's w = f * 2^e, with q = 64, - // - // e >= -1022 (min IEEE exponent) - // -52 (p - 1) - // -52 (p - 1, possibly normalize denormal IEEE numbers) - // -11 (normalize the diyfp) - // = -1137 - // - // and - // - // e <= +1023 (max IEEE exponent) - // -52 (p - 1) - // -11 (normalize the diyfp) - // = 960 - // - // This binary exponent range [-1137,960] results in a decimal exponent - // range [-307,324]. One does not need to store a cached power for each - // k in this range. For each such k it suffices to find a cached power - // such that the exponent of the product lies in [alpha,gamma]. - // This implies that the difference of the decimal exponents of adjacent - // table entries must be less than or equal to - // - // floor( (gamma - alpha) * log_10(2) ) = 8. - // - // (A smaller distance gamma-alpha would require a larger table.) - - // NB: - // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. - - constexpr int kCachedPowersSize = 79; - constexpr int kCachedPowersMinDecExp = -300; - constexpr int kCachedPowersDecStep = 8; - - static constexpr cached_power kCachedPowers[] = - { - { 0xAB70FE17C79AC6CA, -1060, -300 }, - { 0xFF77B1FCBEBCDC4F, -1034, -292 }, - { 0xBE5691EF416BD60C, -1007, -284 }, - { 0x8DD01FAD907FFC3C, -980, -276 }, - { 0xD3515C2831559A83, -954, -268 }, - { 0x9D71AC8FADA6C9B5, -927, -260 }, - { 0xEA9C227723EE8BCB, -901, -252 }, - { 0xAECC49914078536D, -874, -244 }, - { 0x823C12795DB6CE57, -847, -236 }, - { 0xC21094364DFB5637, -821, -228 }, - { 0x9096EA6F3848984F, -794, -220 }, - { 0xD77485CB25823AC7, -768, -212 }, - { 0xA086CFCD97BF97F4, -741, -204 }, - { 0xEF340A98172AACE5, -715, -196 }, - { 0xB23867FB2A35B28E, -688, -188 }, - { 0x84C8D4DFD2C63F3B, -661, -180 }, - { 0xC5DD44271AD3CDBA, -635, -172 }, - { 0x936B9FCEBB25C996, -608, -164 }, - { 0xDBAC6C247D62A584, -582, -156 }, - { 0xA3AB66580D5FDAF6, -555, -148 }, - { 0xF3E2F893DEC3F126, -529, -140 }, - { 0xB5B5ADA8AAFF80B8, -502, -132 }, - { 0x87625F056C7C4A8B, -475, -124 }, - { 0xC9BCFF6034C13053, -449, -116 }, - { 0x964E858C91BA2655, -422, -108 }, - { 0xDFF9772470297EBD, -396, -100 }, - { 0xA6DFBD9FB8E5B88F, -369, -92 }, - { 0xF8A95FCF88747D94, -343, -84 }, - { 0xB94470938FA89BCF, -316, -76 }, - { 0x8A08F0F8BF0F156B, -289, -68 }, - { 0xCDB02555653131B6, -263, -60 }, - { 0x993FE2C6D07B7FAC, -236, -52 }, - { 0xE45C10C42A2B3B06, -210, -44 }, - { 0xAA242499697392D3, -183, -36 }, - { 0xFD87B5F28300CA0E, -157, -28 }, - { 0xBCE5086492111AEB, -130, -20 }, - { 0x8CBCCC096F5088CC, -103, -12 }, - { 0xD1B71758E219652C, -77, -4 }, - { 0x9C40000000000000, -50, 4 }, - { 0xE8D4A51000000000, -24, 12 }, - { 0xAD78EBC5AC620000, 3, 20 }, - { 0x813F3978F8940984, 30, 28 }, - { 0xC097CE7BC90715B3, 56, 36 }, - { 0x8F7E32CE7BEA5C70, 83, 44 }, - { 0xD5D238A4ABE98068, 109, 52 }, - { 0x9F4F2726179A2245, 136, 60 }, - { 0xED63A231D4C4FB27, 162, 68 }, - { 0xB0DE65388CC8ADA8, 189, 76 }, - { 0x83C7088E1AAB65DB, 216, 84 }, - { 0xC45D1DF942711D9A, 242, 92 }, - { 0x924D692CA61BE758, 269, 100 }, - { 0xDA01EE641A708DEA, 295, 108 }, - { 0xA26DA3999AEF774A, 322, 116 }, - { 0xF209787BB47D6B85, 348, 124 }, - { 0xB454E4A179DD1877, 375, 132 }, - { 0x865B86925B9BC5C2, 402, 140 }, - { 0xC83553C5C8965D3D, 428, 148 }, - { 0x952AB45CFA97A0B3, 455, 156 }, - { 0xDE469FBD99A05FE3, 481, 164 }, - { 0xA59BC234DB398C25, 508, 172 }, - { 0xF6C69A72A3989F5C, 534, 180 }, - { 0xB7DCBF5354E9BECE, 561, 188 }, - { 0x88FCF317F22241E2, 588, 196 }, - { 0xCC20CE9BD35C78A5, 614, 204 }, - { 0x98165AF37B2153DF, 641, 212 }, - { 0xE2A0B5DC971F303A, 667, 220 }, - { 0xA8D9D1535CE3B396, 694, 228 }, - { 0xFB9B7CD9A4A7443C, 720, 236 }, - { 0xBB764C4CA7A44410, 747, 244 }, - { 0x8BAB8EEFB6409C1A, 774, 252 }, - { 0xD01FEF10A657842C, 800, 260 }, - { 0x9B10A4E5E9913129, 827, 268 }, - { 0xE7109BFBA19C0C9D, 853, 276 }, - { 0xAC2820D9623BF429, 880, 284 }, - { 0x80444B5E7AA7CF85, 907, 292 }, - { 0xBF21E44003ACDD2D, 933, 300 }, - { 0x8E679C2F5E44FF8F, 960, 308 }, - { 0xD433179D9C8CB841, 986, 316 }, - { 0x9E19DB92B4E31BA9, 1013, 324 }, - }; - - // This computation gives exactly the same results for k as - // k = ceil((kAlpha - e - 1) * 0.30102999566398114) - // for |e| <= 1500, but doesn't require floating-point operations. - // NB: log_10(2) ~= 78913 / 2^18 - assert(e >= -1500); - assert(e <= 1500); - const int f = kAlpha - e - 1; - const int k = (f * 78913) / (1 << 18) + (f > 0); - - const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; - assert(index >= 0); - assert(index < kCachedPowersSize); - static_cast(kCachedPowersSize); // Fix warning. - - const cached_power cached = kCachedPowers[index]; - assert(kAlpha <= cached.e + e + 64); - assert(kGamma >= cached.e + e + 64); - - return cached; -} - -/*! -For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. -For n == 0, returns 1 and sets pow10 := 1. -*/ -inline int find_largest_pow10(const uint32_t n, uint32_t& pow10) -{ - // LCOV_EXCL_START - if (n >= 1000000000) - { - pow10 = 1000000000; - return 10; - } - // LCOV_EXCL_STOP - else if (n >= 100000000) - { - pow10 = 100000000; - return 9; - } - else if (n >= 10000000) - { - pow10 = 10000000; - return 8; - } - else if (n >= 1000000) - { - pow10 = 1000000; - return 7; - } - else if (n >= 100000) - { - pow10 = 100000; - return 6; - } - else if (n >= 10000) - { - pow10 = 10000; - return 5; - } - else if (n >= 1000) - { - pow10 = 1000; - return 4; - } - else if (n >= 100) - { - pow10 = 100; - return 3; - } - else if (n >= 10) - { - pow10 = 10; - return 2; - } - else - { - pow10 = 1; - return 1; - } -} - -inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta, - uint64_t rest, uint64_t ten_k) -{ - assert(len >= 1); - assert(dist <= delta); - assert(rest <= delta); - assert(ten_k > 0); - - // <--------------------------- delta ----> - // <---- dist ---------> - // --------------[------------------+-------------------]-------------- - // M- w M+ - // - // ten_k - // <------> - // <---- rest ----> - // --------------[------------------+----+--------------]-------------- - // w V - // = buf * 10^k - // - // ten_k represents a unit-in-the-last-place in the decimal representation - // stored in buf. - // Decrement buf by ten_k while this takes buf closer to w. - - // The tests are written in this order to avoid overflow in unsigned - // integer arithmetic. - - while (rest < dist - and delta - rest >= ten_k - and (rest + ten_k < dist or dist - rest > rest + ten_k - dist)) - { - assert(buf[len - 1] != '0'); - buf[len - 1]--; - rest += ten_k; - } -} - -/*! -Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. -M- and M+ must be normalized and share the same exponent -60 <= e <= -32. -*/ -inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, - diyfp M_minus, diyfp w, diyfp M_plus) -{ - static_assert(kAlpha >= -60, "internal error"); - static_assert(kGamma <= -32, "internal error"); - - // Generates the digits (and the exponent) of a decimal floating-point - // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's - // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. - // - // <--------------------------- delta ----> - // <---- dist ---------> - // --------------[------------------+-------------------]-------------- - // M- w M+ - // - // Grisu2 generates the digits of M+ from left to right and stops as soon as - // V is in [M-,M+]. - - assert(M_plus.e >= kAlpha); - assert(M_plus.e <= kGamma); - - uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) - uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) - - // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): - // - // M+ = f * 2^e - // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e - // = ((p1 ) * 2^-e + (p2 )) * 2^e - // = p1 + p2 * 2^e - - const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e); - - uint32_t p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) - uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e - - // 1) - // - // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] - - assert(p1 > 0); - - uint32_t pow10; - const int k = find_largest_pow10(p1, pow10); - - // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) - // - // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) - // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) - // - // M+ = p1 + p2 * 2^e - // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e - // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e - // = d[k-1] * 10^(k-1) + ( rest) * 2^e - // - // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) - // - // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] - // - // but stop as soon as - // - // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e - - int n = k; - while (n > 0) - { - // Invariants: - // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) - // pow10 = 10^(n-1) <= p1 < 10^n - // - const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) - const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) - // - // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e - // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) - // - assert(d <= 9); - buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d - // - // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) - // - p1 = r; - n--; - // - // M+ = buffer * 10^n + (p1 + p2 * 2^e) - // pow10 = 10^n - // - - // Now check if enough digits have been generated. - // Compute - // - // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e - // - // Note: - // Since rest and delta share the same exponent e, it suffices to - // compare the significands. - const uint64_t rest = (uint64_t{p1} << -one.e) + p2; - if (rest <= delta) - { - // V = buffer * 10^n, with M- <= V <= M+. - - decimal_exponent += n; - - // We may now just stop. But instead look if the buffer could be - // decremented to bring V closer to w. - // - // pow10 = 10^n is now 1 ulp in the decimal representation V. - // The rounding procedure works with diyfp's with an implicit - // exponent of e. - // - // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e - // - const uint64_t ten_n = uint64_t{pow10} << -one.e; - grisu2_round(buffer, length, dist, delta, rest, ten_n); - - return; - } - - pow10 /= 10; - // - // pow10 = 10^(n-1) <= p1 < 10^n - // Invariants restored. - } - - // 2) - // - // The digits of the integral part have been generated: - // - // M+ = d[k-1]...d[1]d[0] + p2 * 2^e - // = buffer + p2 * 2^e - // - // Now generate the digits of the fractional part p2 * 2^e. - // - // Note: - // No decimal point is generated: the exponent is adjusted instead. - // - // p2 actually represents the fraction - // - // p2 * 2^e - // = p2 / 2^-e - // = d[-1] / 10^1 + d[-2] / 10^2 + ... - // - // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) - // - // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m - // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) - // - // using - // - // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) - // = ( d) * 2^-e + ( r) - // - // or - // 10^m * p2 * 2^e = d + r * 2^e - // - // i.e. - // - // M+ = buffer + p2 * 2^e - // = buffer + 10^-m * (d + r * 2^e) - // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e - // - // and stop as soon as 10^-m * r * 2^e <= delta * 2^e - - assert(p2 > delta); - - int m = 0; - for (;;) - { - // Invariant: - // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e - // = buffer * 10^-m + 10^-m * (p2 ) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e - // - assert(p2 <= UINT64_MAX / 10); - p2 *= 10; - const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e - const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e - // - // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) - // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e - // - assert(d <= 9); - buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d - // - // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e - // - p2 = r; - m++; - // - // M+ = buffer * 10^-m + 10^-m * p2 * 2^e - // Invariant restored. - - // Check if enough digits have been generated. - // - // 10^-m * p2 * 2^e <= delta * 2^e - // p2 * 2^e <= 10^m * delta * 2^e - // p2 <= 10^m * delta - delta *= 10; - dist *= 10; - if (p2 <= delta) - { - break; - } - } - - // V = buffer * 10^-m, with M- <= V <= M+. - - decimal_exponent -= m; - - // 1 ulp in the decimal representation is now 10^-m. - // Since delta and dist are now scaled by 10^m, we need to do the - // same with ulp in order to keep the units in sync. - // - // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e - // - const uint64_t ten_m = one.f; - grisu2_round(buffer, length, dist, delta, p2, ten_m); - - // By construction this algorithm generates the shortest possible decimal - // number (Loitsch, Theorem 6.2) which rounds back to w. - // For an input number of precision p, at least - // - // N = 1 + ceil(p * log_10(2)) - // - // decimal digits are sufficient to identify all binary floating-point - // numbers (Matula, "In-and-Out conversions"). - // This implies that the algorithm does not produce more than N decimal - // digits. - // - // N = 17 for p = 53 (IEEE double precision) - // N = 9 for p = 24 (IEEE single precision) -} - -/*! -v = buf * 10^decimal_exponent -len is the length of the buffer (number of decimal digits) -The buffer must be large enough, i.e. >= max_digits10. -*/ -inline void grisu2(char* buf, int& len, int& decimal_exponent, - diyfp m_minus, diyfp v, diyfp m_plus) -{ - assert(m_plus.e == m_minus.e); - assert(m_plus.e == v.e); - - // --------(-----------------------+-----------------------)-------- (A) - // m- v m+ - // - // --------------------(-----------+-----------------------)-------- (B) - // m- v m+ - // - // First scale v (and m- and m+) such that the exponent is in the range - // [alpha, gamma]. - - const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); - - const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k - - // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] - const diyfp w = diyfp::mul(v, c_minus_k); - const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); - const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); - - // ----(---+---)---------------(---+---)---------------(---+---)---- - // w- w w+ - // = c*m- = c*v = c*m+ - // - // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and - // w+ are now off by a small amount. - // In fact: - // - // w - v * 10^k < 1 ulp - // - // To account for this inaccuracy, add resp. subtract 1 ulp. - // - // --------+---[---------------(---+---)---------------]---+-------- - // w- M- w M+ w+ - // - // Now any number in [M-, M+] (bounds included) will round to w when input, - // regardless of how the input rounding algorithm breaks ties. - // - // And digit_gen generates the shortest possible such number in [M-, M+]. - // Note that this does not mean that Grisu2 always generates the shortest - // possible number in the interval (m-, m+). - const diyfp M_minus(w_minus.f + 1, w_minus.e); - const diyfp M_plus (w_plus.f - 1, w_plus.e ); - - decimal_exponent = -cached.k; // = -(-k) = k - - grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); -} - -/*! -v = buf * 10^decimal_exponent -len is the length of the buffer (number of decimal digits) -The buffer must be large enough, i.e. >= max_digits10. -*/ -template -void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) -{ - static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, - "internal error: not enough precision"); - - assert(std::isfinite(value)); - assert(value > 0); - - // If the neighbors (and boundaries) of 'value' are always computed for double-precision - // numbers, all float's can be recovered using strtod (and strtof). However, the resulting - // decimal representations are not exactly "short". - // - // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) - // says "value is converted to a string as if by std::sprintf in the default ("C") locale" - // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' - // does. - // On the other hand, the documentation for 'std::to_chars' requires that "parsing the - // representation using the corresponding std::from_chars function recovers value exactly". That - // indicates that single precision floating-point numbers should be recovered using - // 'std::strtof'. - // - // NB: If the neighbors are computed for single-precision numbers, there is a single float - // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision - // value is off by 1 ulp. -#if 0 - const boundaries w = compute_boundaries(static_cast(value)); -#else - const boundaries w = compute_boundaries(value); -#endif - - grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); -} - -/*! -@brief appends a decimal representation of e to buf -@return a pointer to the element following the exponent. -@pre -1000 < e < 1000 -*/ -inline char* append_exponent(char* buf, int e) -{ - assert(e > -1000); - assert(e < 1000); - - if (e < 0) - { - e = -e; - *buf++ = '-'; - } - else - { - *buf++ = '+'; - } - - uint32_t k = static_cast(e); - if (k < 10) - { - // Always print at least two digits in the exponent. - // This is for compatibility with printf("%g"). - *buf++ = '0'; - *buf++ = static_cast('0' + k); - } - else if (k < 100) - { - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } - else - { - *buf++ = static_cast('0' + k / 100); - k %= 100; - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } - - return buf; -} - -/*! -@brief prettify v = buf * 10^decimal_exponent - -If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point -notation. Otherwise it will be printed in exponential notation. - -@pre min_exp < 0 -@pre max_exp > 0 -*/ -inline char* format_buffer(char* buf, int len, int decimal_exponent, - int min_exp, int max_exp) -{ - assert(min_exp < 0); - assert(max_exp > 0); - - const int k = len; - const int n = len + decimal_exponent; - - // v = buf * 10^(n-k) - // k is the length of the buffer (number of decimal digits) - // n is the position of the decimal point relative to the start of the buffer. - - if (k <= n and n <= max_exp) - { - // digits[000] - // len <= max_exp + 2 - - std::memset(buf + k, '0', static_cast(n - k)); - // Make it look like a floating-point number (#362, #378) - buf[n + 0] = '.'; - buf[n + 1] = '0'; - return buf + (n + 2); - } - - if (0 < n and n <= max_exp) - { - // dig.its - // len <= max_digits10 + 1 - - assert(k > n); - - std::memmove(buf + (n + 1), buf + n, static_cast(k - n)); - buf[n] = '.'; - return buf + (k + 1); - } - - if (min_exp < n and n <= 0) - { - // 0.[000]digits - // len <= 2 + (-min_exp - 1) + max_digits10 - - std::memmove(buf + (2 + -n), buf, static_cast(k)); - buf[0] = '0'; - buf[1] = '.'; - std::memset(buf + 2, '0', static_cast(-n)); - return buf + (2 + (-n) + k); - } - - if (k == 1) - { - // dE+123 - // len <= 1 + 5 - - buf += 1; - } - else - { - // d.igitsE+123 - // len <= max_digits10 + 1 + 5 - - std::memmove(buf + 2, buf + 1, static_cast(k - 1)); - buf[1] = '.'; - buf += 1 + k; - } - - *buf++ = 'e'; - return append_exponent(buf, n - 1); -} - -} // namespace dtoa_impl - -/*! -@brief generates a decimal representation of the floating-point number value in [first, last). - -The format of the resulting decimal representation is similar to printf's %g -format. Returns an iterator pointing past-the-end of the decimal representation. - -@note The input number must be finite, i.e. NaN's and Inf's are not supported. -@note The buffer must be large enough. -@note The result is NOT null-terminated. -*/ -template -char* to_chars(char* first, char* last, FloatType value) -{ - static_cast(last); // maybe unused - fix warning - assert(std::isfinite(value)); - - // Use signbit(value) instead of (value < 0) since signbit works for -0. - if (std::signbit(value)) - { - value = -value; - *first++ = '-'; - } - - if (value == 0) // +-0 - { - *first++ = '0'; - // Make it look like a floating-point number (#362, #378) - *first++ = '.'; - *first++ = '0'; - return first; - } - - assert(last - first >= std::numeric_limits::max_digits10); - - // Compute v = buffer * 10^decimal_exponent. - // The decimal digits are stored in the buffer, which needs to be interpreted - // as an unsigned decimal integer. - // len is the length of the buffer, i.e. the number of decimal digits. - int len = 0; - int decimal_exponent = 0; - dtoa_impl::grisu2(first, len, decimal_exponent, value); - - assert(len <= std::numeric_limits::max_digits10); - - // Format the buffer like printf("%.*g", prec, value) - constexpr int kMinExp = -4; - // Use digits10 here to increase compatibility with version 2. - constexpr int kMaxExp = std::numeric_limits::digits10; - - assert(last - first >= kMaxExp + 2); - assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); - assert(last - first >= std::numeric_limits::max_digits10 + 6); - - return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); -} - -} // namespace detail -} // namespace nlohmann diff --git a/include/nlohmann/detail/conversions/to_json.hpp b/include/nlohmann/detail/conversions/to_json.hpp deleted file mode 100644 index 07946f5..0000000 --- a/include/nlohmann/detail/conversions/to_json.hpp +++ /dev/null @@ -1,357 +0,0 @@ -#pragma once - -#include // or, and, not -#include // begin, end -#include // tuple, get -#include // is_same, is_constructible, is_floating_point, is_enum, underlying_type -#include // move, forward, declval, pair -#include // valarray -#include // vector - -#include -#include -#include - -namespace nlohmann -{ -namespace detail -{ -////////////////// -// constructors // -////////////////// - -template struct external_constructor; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept - { - j.m_type = value_t::boolean; - j.m_value = b; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) - { - j.m_type = value_t::string; - j.m_value = s; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) - { - j.m_type = value_t::string; - j.m_value = std::move(s); - j.assert_invariant(); - } - - template::value, - int> = 0> - static void construct(BasicJsonType& j, const CompatibleStringType& str) - { - j.m_type = value_t::string; - j.m_value.string = j.template create(str); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept - { - j.m_type = value_t::number_float; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept - { - j.m_type = value_t::number_unsigned; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept - { - j.m_type = value_t::number_integer; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) - { - j.m_type = value_t::array; - j.m_value = arr; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) - { - j.m_type = value_t::array; - j.m_value = std::move(arr); - j.assert_invariant(); - } - - template::value, - int> = 0> - static void construct(BasicJsonType& j, const CompatibleArrayType& arr) - { - using std::begin; - using std::end; - j.m_type = value_t::array; - j.m_value.array = j.template create(begin(arr), end(arr)); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, const std::vector& arr) - { - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->reserve(arr.size()); - for (const bool x : arr) - { - j.m_value.array->push_back(x); - } - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const std::valarray& arr) - { - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->resize(arr.size()); - std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) - { - j.m_type = value_t::object; - j.m_value = obj; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) - { - j.m_type = value_t::object; - j.m_value = std::move(obj); - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const CompatibleObjectType& obj) - { - using std::begin; - using std::end; - - j.m_type = value_t::object; - j.m_value.object = j.template create(begin(obj), end(obj)); - j.assert_invariant(); - } -}; - -///////////// -// to_json // -///////////// - -template::value, int> = 0> -void to_json(BasicJsonType& j, T b) noexcept -{ - external_constructor::construct(j, b); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, const CompatibleString& s) -{ - external_constructor::construct(j, s); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) -{ - external_constructor::construct(j, std::move(s)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, FloatType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, EnumType e) noexcept -{ - using underlying_type = typename std::underlying_type::type; - external_constructor::construct(j, static_cast(e)); -} - -template -void to_json(BasicJsonType& j, const std::vector& e) -{ - external_constructor::construct(j, e); -} - -template::value or - std::is_same::value, - int> = 0> -void to_json(BasicJsonType& j, const CompatibleArrayType& arr) -{ - external_constructor::construct(j, arr); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, const std::valarray& arr) -{ - external_constructor::construct(j, std::move(arr)); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) -{ - external_constructor::construct(j, std::move(arr)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, const CompatibleObjectType& obj) -{ - external_constructor::construct(j, obj); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) -{ - external_constructor::construct(j, std::move(obj)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, T (&arr)[N]) -{ - external_constructor::construct(j, arr); -} - -template -void to_json(BasicJsonType& j, const std::pair& p) -{ - j = {p.first, p.second}; -} - -// for https://github.com/nlohmann/json/pull/1134 -template::iteration_proxy_internal>::value, int> = 0> -void to_json(BasicJsonType& j, T b) noexcept -{ - j = {{b.key(), b.value()}}; -} - -template -void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence) -{ - j = {std::get(t)...}; -} - -template -void to_json(BasicJsonType& j, const std::tuple& t) -{ - to_json_tuple_impl(j, t, index_sequence_for {}); -} - -struct to_json_fn -{ - private: - template - auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward(val)))) - -> decltype(to_json(j, std::forward(val)), void()) - { - return to_json(j, std::forward(val)); - } - - template - void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept - { - static_assert(sizeof(BasicJsonType) == 0, - "could not find to_json() method in T's namespace"); - -#ifdef _MSC_VER - // MSVC does not show a stacktrace for the above assert - using decayed = uncvref_t; - static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0, - "forcing MSVC stacktrace to show which T we're talking about."); -#endif - } - - public: - template - void operator()(BasicJsonType& j, T&& val) const - noexcept(noexcept(std::declval().call(j, std::forward(val), priority_tag<1> {}))) - { - return call(j, std::forward(val), priority_tag<1> {}); - } -}; -} - -/// namespace to hold default `to_json` function -namespace -{ -constexpr const auto& to_json = detail::static_const::value; -} -} diff --git a/include/nlohmann/detail/exceptions.hpp b/include/nlohmann/detail/exceptions.hpp deleted file mode 100644 index b73d7b1..0000000 --- a/include/nlohmann/detail/exceptions.hpp +++ /dev/null @@ -1,330 +0,0 @@ -#pragma once - -#include // exception -#include // runtime_error -#include // to_string - -namespace nlohmann -{ -namespace detail -{ -//////////////// -// exceptions // -//////////////// - -/*! -@brief general exception of the @ref basic_json class - -This class is an extension of `std::exception` objects with a member @a id for -exception ids. It is used as the base class for all exceptions thrown by the -@ref basic_json class. This class can hence be used as "wildcard" to catch -exceptions. - -Subclasses: -- @ref parse_error for exceptions indicating a parse error -- @ref invalid_iterator for exceptions indicating errors with iterators -- @ref type_error for exceptions indicating executing a member function with - a wrong type -- @ref out_of_range for exceptions indicating access out of the defined range -- @ref other_error for exceptions indicating other library errors - -@internal -@note To have nothrow-copy-constructible exceptions, we internally use - `std::runtime_error` which can cope with arbitrary-length error messages. - Intermediate strings are built with static functions and then passed to - the actual constructor. -@endinternal - -@liveexample{The following code shows how arbitrary library exceptions can be -caught.,exception} - -@since version 3.0.0 -*/ -class exception : public std::exception -{ - public: - /// returns the explanatory string - const char* what() const noexcept override - { - return m.what(); - } - - /// the id of the exception - const int id; - - protected: - exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} - - static std::string name(const std::string& ename, int id_) - { - return "[json.exception." + ename + "." + std::to_string(id_) + "] "; - } - - private: - /// an exception object as storage for error messages - std::runtime_error m; -}; - -/*! -@brief exception indicating a parse error - -This exception is thrown by the library when a parse error occurs. Parse errors -can occur during the deserialization of JSON text, CBOR, MessagePack, as well -as when using JSON Patch. - -Member @a byte holds the byte index of the last read character in the input -file. - -Exceptions have ids 1xx. - -name / id | example message | description ------------------------------- | --------------- | ------------------------- -json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. -json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. -json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. -json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. -json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. -json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. -json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. -json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. -json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. -json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. -json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. -json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. - -@note For an input with n bytes, 1 is the index of the first character and n+1 - is the index of the terminating null byte or the end of file. This also - holds true when reading a byte vector (CBOR or MessagePack). - -@liveexample{The following code shows how a `parse_error` exception can be -caught.,parse_error} - -@sa @ref exception for the base class of the library exceptions -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa @ref out_of_range for exceptions indicating access out of the defined range -@sa @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class parse_error : public exception -{ - public: - /*! - @brief create a parse error exception - @param[in] id_ the id of the exception - @param[in] byte_ the byte index where the error occurred (or 0 if the - position cannot be determined) - @param[in] what_arg the explanatory string - @return parse_error object - */ - static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") + - ": " + what_arg; - return parse_error(id_, byte_, w.c_str()); - } - - /*! - @brief byte index of the parse error - - The byte index of the last read character in the input file. - - @note For an input with n bytes, 1 is the index of the first character and - n+1 is the index of the terminating null byte or the end of file. - This also holds true when reading a byte vector (CBOR or MessagePack). - */ - const std::size_t byte; - - private: - parse_error(int id_, std::size_t byte_, const char* what_arg) - : exception(id_, what_arg), byte(byte_) {} -}; - -/*! -@brief exception indicating errors with iterators - -This exception is thrown if iterators passed to a library function do not match -the expected semantics. - -Exceptions have ids 2xx. - -name / id | example message | description ------------------------------------ | --------------- | ------------------------- -json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. -json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. -json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. -json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. -json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. -json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. -json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. -json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. -json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. -json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. -json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. -json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. -json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. -json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). - -@liveexample{The following code shows how an `invalid_iterator` exception can be -caught.,invalid_iterator} - -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa @ref out_of_range for exceptions indicating access out of the defined range -@sa @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class invalid_iterator : public exception -{ - public: - static invalid_iterator create(int id_, const std::string& what_arg) - { - std::string w = exception::name("invalid_iterator", id_) + what_arg; - return invalid_iterator(id_, w.c_str()); - } - - private: - invalid_iterator(int id_, const char* what_arg) - : exception(id_, what_arg) {} -}; - -/*! -@brief exception indicating executing a member function with a wrong type - -This exception is thrown in case of a type error; that is, a library function is -executed on a JSON value whose type does not match the expected semantics. - -Exceptions have ids 3xx. - -name / id | example message | description ------------------------------ | --------------- | ------------------------- -json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. -json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. -json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&. -json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. -json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. -json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. -json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. -json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. -json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. -json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. -json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. -json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. -json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. -json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. -json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. -json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | - -@liveexample{The following code shows how a `type_error` exception can be -caught.,type_error} - -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref out_of_range for exceptions indicating access out of the defined range -@sa @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class type_error : public exception -{ - public: - static type_error create(int id_, const std::string& what_arg) - { - std::string w = exception::name("type_error", id_) + what_arg; - return type_error(id_, w.c_str()); - } - - private: - type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/*! -@brief exception indicating access out of the defined range - -This exception is thrown in case a library function is called on an input -parameter that exceeds the expected range, for instance in case of array -indices or nonexisting object keys. - -Exceptions have ids 4xx. - -name / id | example message | description -------------------------------- | --------------- | ------------------------- -json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. -json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. -json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. -json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. -json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. -json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. -json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON only supports integers numbers up to 9223372036854775807. | -json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | - -@liveexample{The following code shows how an `out_of_range` exception can be -caught.,out_of_range} - -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa @ref other_error for exceptions indicating other library errors - -@since version 3.0.0 -*/ -class out_of_range : public exception -{ - public: - static out_of_range create(int id_, const std::string& what_arg) - { - std::string w = exception::name("out_of_range", id_) + what_arg; - return out_of_range(id_, w.c_str()); - } - - private: - out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/*! -@brief exception indicating other library errors - -This exception is thrown in case of errors that cannot be classified with the -other exception types. - -Exceptions have ids 5xx. - -name / id | example message | description ------------------------------- | --------------- | ------------------------- -json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. - -@sa @ref exception for the base class of the library exceptions -@sa @ref parse_error for exceptions indicating a parse error -@sa @ref invalid_iterator for exceptions indicating errors with iterators -@sa @ref type_error for exceptions indicating executing a member function with - a wrong type -@sa @ref out_of_range for exceptions indicating access out of the defined range - -@liveexample{The following code shows how an `other_error` exception can be -caught.,other_error} - -@since version 3.0.0 -*/ -class other_error : public exception -{ - public: - static other_error create(int id_, const std::string& what_arg) - { - std::string w = exception::name("other_error", id_) + what_arg; - return other_error(id_, w.c_str()); - } - - private: - other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; -} -} diff --git a/include/nlohmann/detail/input/binary_reader.hpp b/include/nlohmann/detail/input/binary_reader.hpp deleted file mode 100644 index 726e552..0000000 --- a/include/nlohmann/detail/input/binary_reader.hpp +++ /dev/null @@ -1,1693 +0,0 @@ -#pragma once - -#include // generate_n -#include // array -#include // assert -#include // ldexp -#include // size_t -#include // uint8_t, uint16_t, uint32_t, uint64_t -#include // snprintf -#include // memcpy -#include // back_inserter -#include // numeric_limits -#include // char_traits, string -#include // make_pair, move - -#include -#include -#include -#include -#include - -namespace nlohmann -{ -namespace detail -{ -/////////////////// -// binary reader // -/////////////////// - -/*! -@brief deserialization of CBOR, MessagePack, and UBJSON values -*/ -template -class binary_reader -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using json_sax_t = json_sax; - - public: - /*! - @brief create a binary reader - - @param[in] adapter input adapter to read from - */ - explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter)) - { - assert(ia); - } - - /*! - @param[in] format the binary format to parse - @param[in] sax_ a SAX event processor - @param[in] strict whether to expect the input to be consumed completed - - @return - */ - bool sax_parse(const input_format_t format, - json_sax_t* sax_, - const bool strict = true) - { - sax = sax_; - bool result; - - switch (format) - { - case input_format_t::cbor: - result = parse_cbor_internal(); - break; - - case input_format_t::msgpack: - result = parse_msgpack_internal(); - break; - - case input_format_t::ubjson: - result = parse_ubjson_internal(); - break; - - default: - assert(false); // LCOV_EXCL_LINE - } - - // strict mode: next byte must be EOF - if (result and strict) - { - if (format == input_format_t::ubjson) - { - get_ignore_noop(); - } - else - { - get(); - } - - if (JSON_UNLIKELY(current != std::char_traits::eof())) - { - return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, "expected end of input")); - } - } - - return result; - } - - /*! - @brief determine system byte order - - @return true if and only if system's byte order is little endian - - @note from http://stackoverflow.com/a/1001328/266378 - */ - static constexpr bool little_endianess(int num = 1) noexcept - { - return (*reinterpret_cast(&num) == 1); - } - - private: - /*! - @param[in] get_char whether a new character should be retrieved from the - input (true, default) or whether the last read - character should be considered instead - - @return whether a valid CBOR value was passed to the SAX parser - */ - bool parse_cbor_internal(const bool get_char = true) - { - switch (get_char ? get() : current) - { - // EOF - case std::char_traits::eof(): - return unexpect_eof(); - - // Integer 0x00..0x17 (0..23) - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - case 0x08: - case 0x09: - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x17: - return sax->number_unsigned(static_cast(current)); - - case 0x18: // Unsigned integer (one-byte uint8_t follows) - { - uint8_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 0x19: // Unsigned integer (two-byte uint16_t follows) - { - uint16_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 0x1A: // Unsigned integer (four-byte uint32_t follows) - { - uint32_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 0x1B: // Unsigned integer (eight-byte uint64_t follows) - { - uint64_t number; - return get_number(number) and sax->number_unsigned(number); - } - - // Negative integer -1-0x00..-1-0x17 (-1..-24) - case 0x20: - case 0x21: - case 0x22: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - return sax->number_integer(static_cast(0x20 - 1 - current)); - - case 0x38: // Negative integer (one-byte uint8_t follows) - { - uint8_t number; - return get_number(number) and sax->number_integer(static_cast(-1) - number); - } - - case 0x39: // Negative integer -1-n (two-byte uint16_t follows) - { - uint16_t number; - return get_number(number) and sax->number_integer(static_cast(-1) - number); - } - - case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) - { - uint32_t number; - return get_number(number) and sax->number_integer(static_cast(-1) - number); - } - - case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) - { - uint64_t number; - return get_number(number) and sax->number_integer(static_cast(-1) - - static_cast(number)); - } - - // UTF-8 string (0x00..0x17 bytes follow) - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: // UTF-8 string (one-byte uint8_t for n follows) - case 0x79: // UTF-8 string (two-byte uint16_t for n follow) - case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) - case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) - case 0x7F: // UTF-8 string (indefinite length) - { - string_t s; - return get_cbor_string(s) and sax->string(s); - } - - // array (0x00..0x17 data items follow) - case 0x80: - case 0x81: - case 0x82: - case 0x83: - case 0x84: - case 0x85: - case 0x86: - case 0x87: - case 0x88: - case 0x89: - case 0x8A: - case 0x8B: - case 0x8C: - case 0x8D: - case 0x8E: - case 0x8F: - case 0x90: - case 0x91: - case 0x92: - case 0x93: - case 0x94: - case 0x95: - case 0x96: - case 0x97: - return get_cbor_array(static_cast(current & 0x1F)); - - case 0x98: // array (one-byte uint8_t for n follows) - { - uint8_t len; - return get_number(len) and get_cbor_array(static_cast(len)); - } - - case 0x99: // array (two-byte uint16_t for n follow) - { - uint16_t len; - return get_number(len) and get_cbor_array(static_cast(len)); - } - - case 0x9A: // array (four-byte uint32_t for n follow) - { - uint32_t len; - return get_number(len) and get_cbor_array(static_cast(len)); - } - - case 0x9B: // array (eight-byte uint64_t for n follow) - { - uint64_t len; - return get_number(len) and get_cbor_array(static_cast(len)); - } - - case 0x9F: // array (indefinite length) - return get_cbor_array(json_sax_t::no_limit); - - // map (0x00..0x17 pairs of data items follow) - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - return get_cbor_object(static_cast(current & 0x1F)); - - case 0xB8: // map (one-byte uint8_t for n follows) - { - uint8_t len; - return get_number(len) and get_cbor_object(static_cast(len)); - } - - case 0xB9: // map (two-byte uint16_t for n follow) - { - uint16_t len; - return get_number(len) and get_cbor_object(static_cast(len)); - } - - case 0xBA: // map (four-byte uint32_t for n follow) - { - uint32_t len; - return get_number(len) and get_cbor_object(static_cast(len)); - } - - case 0xBB: // map (eight-byte uint64_t for n follow) - { - uint64_t len; - return get_number(len) and get_cbor_object(static_cast(len)); - } - - case 0xBF: // map (indefinite length) - return get_cbor_object(json_sax_t::no_limit); - - case 0xF4: // false - return sax->boolean(false); - - case 0xF5: // true - return sax->boolean(true); - - case 0xF6: // null - return sax->null(); - - case 0xF9: // Half-Precision Float (two-byte IEEE 754) - { - const int byte1 = get(); - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - const int byte2 = get(); - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - - // code from RFC 7049, Appendix D, Figure 3: - // As half-precision floating-point numbers were only added - // to IEEE 754 in 2008, today's programming platforms often - // still only have limited support for them. It is very - // easy to include at least decoding support for them even - // without such support. An example of a small decoder for - // half-precision floating-point numbers in the C language - // is shown in Fig. 3. - const int half = (byte1 << 8) + byte2; - const double val = [&half] - { - const int exp = (half >> 10) & 0x1F; - const int mant = half & 0x3FF; - assert(0 <= exp and exp <= 32); - assert(0 <= mant and mant <= 1024); - switch (exp) - { - case 0: - return std::ldexp(mant, -24); - case 31: - return (mant == 0) - ? std::numeric_limits::infinity() - : std::numeric_limits::quiet_NaN(); - default: - return std::ldexp(mant + 1024, exp - 25); - } - }(); - return sax->number_float((half & 0x8000) != 0 - ? static_cast(-val) - : static_cast(val), ""); - } - - case 0xFA: // Single-Precision Float (four-byte IEEE 754) - { - float number; - return get_number(number) and sax->number_float(static_cast(number), ""); - } - - case 0xFB: // Double-Precision Float (eight-byte IEEE 754) - { - double number; - return get_number(number) and sax->number_float(static_cast(number), ""); - } - - default: // anything else (0xFF is handled inside the other types) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + last_token)); - } - } - } - - /*! - @return whether a valid MessagePack value was passed to the SAX parser - */ - bool parse_msgpack_internal() - { - switch (get()) - { - // EOF - case std::char_traits::eof(): - return unexpect_eof(); - - // positive fixint - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - case 0x08: - case 0x09: - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x17: - case 0x18: - case 0x19: - case 0x1A: - case 0x1B: - case 0x1C: - case 0x1D: - case 0x1E: - case 0x1F: - case 0x20: - case 0x21: - case 0x22: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: - case 0x59: - case 0x5A: - case 0x5B: - case 0x5C: - case 0x5D: - case 0x5E: - case 0x5F: - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: - case 0x79: - case 0x7A: - case 0x7B: - case 0x7C: - case 0x7D: - case 0x7E: - case 0x7F: - return sax->number_unsigned(static_cast(current)); - - // fixmap - case 0x80: - case 0x81: - case 0x82: - case 0x83: - case 0x84: - case 0x85: - case 0x86: - case 0x87: - case 0x88: - case 0x89: - case 0x8A: - case 0x8B: - case 0x8C: - case 0x8D: - case 0x8E: - case 0x8F: - return get_msgpack_object(static_cast(current & 0x0F)); - - // fixarray - case 0x90: - case 0x91: - case 0x92: - case 0x93: - case 0x94: - case 0x95: - case 0x96: - case 0x97: - case 0x98: - case 0x99: - case 0x9A: - case 0x9B: - case 0x9C: - case 0x9D: - case 0x9E: - case 0x9F: - return get_msgpack_array(static_cast(current & 0x0F)); - - // fixstr - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBC: - case 0xBD: - case 0xBE: - case 0xBF: - { - string_t s; - return get_msgpack_string(s) and sax->string(s); - } - - case 0xC0: // nil - return sax->null(); - - case 0xC2: // false - return sax->boolean(false); - - case 0xC3: // true - return sax->boolean(true); - - case 0xCA: // float 32 - { - float number; - return get_number(number) and sax->number_float(static_cast(number), ""); - } - - case 0xCB: // float 64 - { - double number; - return get_number(number) and sax->number_float(static_cast(number), ""); - } - - case 0xCC: // uint 8 - { - uint8_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 0xCD: // uint 16 - { - uint16_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 0xCE: // uint 32 - { - uint32_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 0xCF: // uint 64 - { - uint64_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 0xD0: // int 8 - { - int8_t number; - return get_number(number) and sax->number_integer(number); - } - - case 0xD1: // int 16 - { - int16_t number; - return get_number(number) and sax->number_integer(number); - } - - case 0xD2: // int 32 - { - int32_t number; - return get_number(number) and sax->number_integer(number); - } - - case 0xD3: // int 64 - { - int64_t number; - return get_number(number) and sax->number_integer(number); - } - - case 0xD9: // str 8 - case 0xDA: // str 16 - case 0xDB: // str 32 - { - string_t s; - return get_msgpack_string(s) and sax->string(s); - } - - case 0xDC: // array 16 - { - uint16_t len; - return get_number(len) and get_msgpack_array(static_cast(len)); - } - - case 0xDD: // array 32 - { - uint32_t len; - return get_number(len) and get_msgpack_array(static_cast(len)); - } - - case 0xDE: // map 16 - { - uint16_t len; - return get_number(len) and get_msgpack_object(static_cast(len)); - } - - case 0xDF: // map 32 - { - uint32_t len; - return get_number(len) and get_msgpack_object(static_cast(len)); - } - - // negative fixint - case 0xE0: - case 0xE1: - case 0xE2: - case 0xE3: - case 0xE4: - case 0xE5: - case 0xE6: - case 0xE7: - case 0xE8: - case 0xE9: - case 0xEA: - case 0xEB: - case 0xEC: - case 0xED: - case 0xEE: - case 0xEF: - case 0xF0: - case 0xF1: - case 0xF2: - case 0xF3: - case 0xF4: - case 0xF5: - case 0xF6: - case 0xF7: - case 0xF8: - case 0xF9: - case 0xFA: - case 0xFB: - case 0xFC: - case 0xFD: - case 0xFE: - case 0xFF: - return sax->number_integer(static_cast(current)); - - default: // anything else - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading MessagePack; last byte: 0x" + last_token)); - } - } - } - - /*! - @param[in] get_char whether a new character should be retrieved from the - input (true, default) or whether the last read - character should be considered instead - - @return whether a valid UBJSON value was passed to the SAX parser - */ - bool parse_ubjson_internal(const bool get_char = true) - { - return get_ubjson_value(get_char ? get_ignore_noop() : current); - } - - /*! - @brief get next character from the input - - This function provides the interface to the used input adapter. It does - not throw in case the input reached EOF, but returns a -'ve valued - `std::char_traits::eof()` in that case. - - @return character read from the input - */ - int get() - { - ++chars_read; - return (current = ia->get_character()); - } - - /*! - @return character read from the input after ignoring all 'N' entries - */ - int get_ignore_noop() - { - do - { - get(); - } - while (current == 'N'); - - return current; - } - - /* - @brief read a number from the input - - @tparam NumberType the type of the number - @param[out] result number of type @a NumberType - - @return whether conversion completed - - @note This function needs to respect the system's endianess, because - bytes in CBOR, MessagePack, and UBJSON are stored in network order - (big endian) and therefore need reordering on little endian systems. - */ - template - bool get_number(NumberType& result) - { - // step 1: read input into array with system's byte order - std::array vec; - for (std::size_t i = 0; i < sizeof(NumberType); ++i) - { - get(); - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - - // reverse byte order prior to conversion if necessary - if (is_little_endian) - { - vec[sizeof(NumberType) - i - 1] = static_cast(current); - } - else - { - vec[i] = static_cast(current); // LCOV_EXCL_LINE - } - } - - // step 2: convert array into number of type T and return - std::memcpy(&result, vec.data(), sizeof(NumberType)); - return true; - } - - /*! - @brief create a string by reading characters from the input - - @tparam NumberType the type of the number - @param[in] len number of characters to read - @param[out] string created by reading @a len bytes - - @return whether string creation completed - - @note We can not reserve @a len bytes for the result, because @a len - may be too large. Usually, @ref unexpect_eof() detects the end of - the input before we run out of string memory. - */ - template - bool get_string(const NumberType len, string_t& result) - { - bool success = true; - std::generate_n(std::back_inserter(result), len, [this, &success]() - { - get(); - if (JSON_UNLIKELY(not unexpect_eof())) - { - success = false; - } - return static_cast(current); - }); - return success; - } - - /*! - @brief reads a CBOR string - - This function first reads starting bytes to determine the expected - string length and then copies this number of bytes into a string. - Additionally, CBOR's strings with indefinite lengths are supported. - - @param[out] result created string - - @return whether string creation completed - */ - bool get_cbor_string(string_t& result) - { - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - - switch (current) - { - // UTF-8 string (0x00..0x17 bytes follow) - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - { - return get_string(current & 0x1F, result); - } - - case 0x78: // UTF-8 string (one-byte uint8_t for n follows) - { - uint8_t len; - return get_number(len) and get_string(len, result); - } - - case 0x79: // UTF-8 string (two-byte uint16_t for n follow) - { - uint16_t len; - return get_number(len) and get_string(len, result); - } - - case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) - { - uint32_t len; - return get_number(len) and get_string(len, result); - } - - case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) - { - uint64_t len; - return get_number(len) and get_string(len, result); - } - - case 0x7F: // UTF-8 string (indefinite length) - { - while (get() != 0xFF) - { - string_t chunk; - if (not get_cbor_string(chunk)) - { - return false; - } - result.append(chunk); - } - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + last_token)); - } - } - } - - /*! - @param[in] len the length of the array or json_sax_t::no_limit for an - array of indefinite size - @return whether array creation completed - */ - bool get_cbor_array(const std::size_t len) - { - if (JSON_UNLIKELY(not sax->start_array(len))) - { - return false; - } - - if (len != json_sax_t::no_limit) - for (std::size_t i = 0; i < len; ++i) - { - if (JSON_UNLIKELY(not parse_cbor_internal())) - { - return false; - } - } - else - { - while (get() != 0xFF) - { - if (JSON_UNLIKELY(not parse_cbor_internal(false))) - { - return false; - } - } - } - - return sax->end_array(); - } - - /*! - @param[in] len the length of the object or json_sax_t::no_limit for an - object of indefinite size - @return whether object creation completed - */ - bool get_cbor_object(const std::size_t len) - { - if (not JSON_UNLIKELY(sax->start_object(len))) - { - return false; - } - - string_t key; - if (len != json_sax_t::no_limit) - { - for (std::size_t i = 0; i < len; ++i) - { - get(); - if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key))) - { - return false; - } - - if (JSON_UNLIKELY(not parse_cbor_internal())) - { - return false; - } - key.clear(); - } - } - else - { - while (get() != 0xFF) - { - if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key))) - { - return false; - } - - if (JSON_UNLIKELY(not parse_cbor_internal())) - { - return false; - } - key.clear(); - } - } - - return sax->end_object(); - } - - /*! - @brief reads a MessagePack string - - This function first reads starting bytes to determine the expected - string length and then copies this number of bytes into a string. - - @param[out] result created string - - @return whether string creation completed - */ - bool get_msgpack_string(string_t& result) - { - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - - switch (current) - { - // fixstr - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBC: - case 0xBD: - case 0xBE: - case 0xBF: - { - return get_string(current & 0x1F, result); - } - - case 0xD9: // str 8 - { - uint8_t len; - return get_number(len) and get_string(len, result); - } - - case 0xDA: // str 16 - { - uint16_t len; - return get_number(len) and get_string(len, result); - } - - case 0xDB: // str 32 - { - uint32_t len; - return get_number(len) and get_string(len, result); - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a MessagePack string; last byte: 0x" + last_token)); - } - } - } - - /*! - @param[in] len the length of the array - @return whether array creation completed - */ - bool get_msgpack_array(const std::size_t len) - { - if (JSON_UNLIKELY(not sax->start_array(len))) - { - return false; - } - - for (std::size_t i = 0; i < len; ++i) - { - if (JSON_UNLIKELY(not parse_msgpack_internal())) - { - return false; - } - } - - return sax->end_array(); - } - - /*! - @param[in] len the length of the object - @return whether object creation completed - */ - bool get_msgpack_object(const std::size_t len) - { - if (JSON_UNLIKELY(not sax->start_object(len))) - { - return false; - } - - string_t key; - for (std::size_t i = 0; i < len; ++i) - { - get(); - if (JSON_UNLIKELY(not get_msgpack_string(key) or not sax->key(key))) - { - return false; - } - - if (JSON_UNLIKELY(not parse_msgpack_internal())) - { - return false; - } - key.clear(); - } - - return sax->end_object(); - } - - /*! - @brief reads a UBJSON string - - This function is either called after reading the 'S' byte explicitly - indicating a string, or in case of an object key where the 'S' byte can be - left out. - - @param[out] result created string - @param[in] get_char whether a new character should be retrieved from the - input (true, default) or whether the last read - character should be considered instead - - @return whether string creation completed - */ - bool get_ubjson_string(string_t& result, const bool get_char = true) - { - if (get_char) - { - get(); // TODO: may we ignore N here? - } - - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - - switch (current) - { - case 'U': - { - uint8_t len; - return get_number(len) and get_string(len, result); - } - - case 'i': - { - int8_t len; - return get_number(len) and get_string(len, result); - } - - case 'I': - { - int16_t len; - return get_number(len) and get_string(len, result); - } - - case 'l': - { - int32_t len; - return get_number(len) and get_string(len, result); - } - - case 'L': - { - int64_t len; - return get_number(len) and get_string(len, result); - } - - default: - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a UBJSON string; last byte: 0x" + last_token)); - } - } - - /*! - @param[out] result determined size - @return whether size determination completed - */ - bool get_ubjson_size_value(std::size_t& result) - { - switch (get_ignore_noop()) - { - case 'U': - { - uint8_t number; - if (JSON_UNLIKELY(not get_number(number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'i': - { - int8_t number; - if (JSON_UNLIKELY(not get_number(number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'I': - { - int16_t number; - if (JSON_UNLIKELY(not get_number(number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'l': - { - int32_t number; - if (JSON_UNLIKELY(not get_number(number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'L': - { - int64_t number; - if (JSON_UNLIKELY(not get_number(number))) - { - return false; - } - result = static_cast(number); - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "byte after '#' must denote a number type; last byte: 0x" + last_token)); - } - } - } - - /*! - @brief determine the type and size for a container - - In the optimized UBJSON format, a type and a size can be provided to allow - for a more compact representation. - - @param[out] result pair of the size and the type - - @return whether pair creation completed - */ - bool get_ubjson_size_type(std::pair& result) - { - result.first = string_t::npos; // size - result.second = 0; // type - - get_ignore_noop(); - - if (current == '$') - { - result.second = get(); // must not ignore 'N', because 'N' maybe the type - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - - get_ignore_noop(); - if (JSON_UNLIKELY(current != '#')) - { - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "expected '#' after UBJSON type information; last byte: 0x" + last_token)); - } - - return get_ubjson_size_value(result.first); - } - else if (current == '#') - { - return get_ubjson_size_value(result.first); - } - return true; - } - - /*! - @param prefix the previously read or set type prefix - @return whether value creation completed - */ - bool get_ubjson_value(const int prefix) - { - switch (prefix) - { - case std::char_traits::eof(): // EOF - return unexpect_eof(); - - case 'T': // true - return sax->boolean(true); - case 'F': // false - return sax->boolean(false); - - case 'Z': // null - return sax->null(); - - case 'U': - { - uint8_t number; - return get_number(number) and sax->number_unsigned(number); - } - - case 'i': - { - int8_t number; - return get_number(number) and sax->number_integer(number); - } - - case 'I': - { - int16_t number; - return get_number(number) and sax->number_integer(number); - } - - case 'l': - { - int32_t number; - return get_number(number) and sax->number_integer(number); - } - - case 'L': - { - int64_t number; - return get_number(number) and sax->number_integer(number); - } - - case 'd': - { - float number; - return get_number(number) and sax->number_float(static_cast(number), ""); - } - - case 'D': - { - double number; - return get_number(number) and sax->number_float(static_cast(number), ""); - } - - case 'C': // char - { - get(); - if (JSON_UNLIKELY(not unexpect_eof())) - { - return false; - } - if (JSON_UNLIKELY(current > 127)) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token)); - } - string_t s(1, static_cast(current)); - return sax->string(s); - } - - case 'S': // string - { - string_t s; - return get_ubjson_string(s) and sax->string(s); - } - - case '[': // array - return get_ubjson_array(); - - case '{': // object - return get_ubjson_object(); - - default: // anything else - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading UBJSON; last byte: 0x" + last_token)); - } - } - } - - /*! - @return whether array creation completed - */ - bool get_ubjson_array() - { - std::pair size_and_type; - if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type))) - { - return false; - } - - if (size_and_type.first != string_t::npos) - { - if (JSON_UNLIKELY(not sax->start_array(size_and_type.first))) - { - return false; - } - - if (size_and_type.second != 0) - { - if (size_and_type.second != 'N') - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second))) - { - return false; - } - } - } - } - else - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_UNLIKELY(not parse_ubjson_internal())) - { - return false; - } - } - } - } - else - { - if (JSON_UNLIKELY(not sax->start_array())) - { - return false; - } - - while (current != ']') - { - if (JSON_UNLIKELY(not parse_ubjson_internal(false))) - { - return false; - } - get_ignore_noop(); - } - } - - return sax->end_array(); - } - - /*! - @return whether object creation completed - */ - bool get_ubjson_object() - { - std::pair size_and_type; - if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type))) - { - return false; - } - - string_t key; - if (size_and_type.first != string_t::npos) - { - if (JSON_UNLIKELY(not sax->start_object(size_and_type.first))) - { - return false; - } - - if (size_and_type.second != 0) - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key))) - { - return false; - } - if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second))) - { - return false; - } - key.clear(); - } - } - else - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key))) - { - return false; - } - if (JSON_UNLIKELY(not parse_ubjson_internal())) - { - return false; - } - key.clear(); - } - } - } - else - { - if (JSON_UNLIKELY(not sax->start_object())) - { - return false; - } - - while (current != '}') - { - if (JSON_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key))) - { - return false; - } - if (JSON_UNLIKELY(not parse_ubjson_internal())) - { - return false; - } - get_ignore_noop(); - key.clear(); - } - } - - return sax->end_object(); - } - - /*! - @return whether the last read character is not EOF - */ - bool unexpect_eof() const - { - if (JSON_UNLIKELY(current == std::char_traits::eof())) - { - return sax->parse_error(chars_read, "", parse_error::create(110, chars_read, "unexpected end of input")); - } - return true; - } - - /*! - @return a string representation of the last read byte - */ - std::string get_token_string() const - { - char cr[3]; - snprintf(cr, 3, "%.2hhX", static_cast(current)); - return std::string{cr}; - } - - private: - /// input adapter - input_adapter_t ia = nullptr; - - /// the current character - int current = std::char_traits::eof(); - - /// the number of characters read - std::size_t chars_read = 0; - - /// whether we can assume little endianess - const bool is_little_endian = little_endianess(); - - /// the SAX parser - json_sax_t* sax = nullptr; -}; -} -} diff --git a/include/nlohmann/detail/input/input_adapters.hpp b/include/nlohmann/detail/input/input_adapters.hpp deleted file mode 100644 index 01bec74..0000000 --- a/include/nlohmann/detail/input/input_adapters.hpp +++ /dev/null @@ -1,374 +0,0 @@ -#pragma once - -#include // assert -#include // size_t -#include // strlen -#include // istream -#include // begin, end, iterator_traits, random_access_iterator_tag, distance, next -#include // shared_ptr, make_shared, addressof -#include // accumulate -#include // string, char_traits -#include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer -#include // pair, declval - -#include - -namespace nlohmann -{ -namespace detail -{ -/// the supported input formats -enum class input_format_t { json, cbor, msgpack, ubjson }; - -//////////////////// -// input adapters // -//////////////////// - -/*! -@brief abstract input adapter interface - -Produces a stream of std::char_traits::int_type characters from a -std::istream, a buffer, or some other input type. Accepts the return of -exactly one non-EOF character for future input. The int_type characters -returned consist of all valid char values as positive values (typically -unsigned char), plus an EOF value outside that range, specified by the value -of the function std::char_traits::eof(). This value is typically -1, but -could be any arbitrary value which is not a valid char value. -*/ -struct input_adapter_protocol -{ - /// get a character [0,255] or std::char_traits::eof(). - virtual std::char_traits::int_type get_character() = 0; - virtual ~input_adapter_protocol() = default; -}; - -/// a type to simplify interfaces -using input_adapter_t = std::shared_ptr; - -/*! -Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at -beginning of input. Does not support changing the underlying std::streambuf -in mid-input. Maintains underlying std::istream and std::streambuf to support -subsequent use of standard std::istream operations to process any input -characters following those used in parsing the JSON input. Clears the -std::istream flags; any input errors (e.g., EOF) will be detected by the first -subsequent call for input from the std::istream. -*/ -class input_stream_adapter : public input_adapter_protocol -{ - public: - ~input_stream_adapter() override - { - // clear stream flags; we use underlying streambuf I/O, do not - // maintain ifstream flags - is.clear(); - } - - explicit input_stream_adapter(std::istream& i) - : is(i), sb(*i.rdbuf()) - {} - - // delete because of pointer members - input_stream_adapter(const input_stream_adapter&) = delete; - input_stream_adapter& operator=(input_stream_adapter&) = delete; - - // std::istream/std::streambuf use std::char_traits::to_int_type, to - // ensure that std::char_traits::eof() and the character 0xFF do not - // end up as the same value, eg. 0xFFFFFFFF. - std::char_traits::int_type get_character() override - { - return sb.sbumpc(); - } - - private: - /// the associated input stream - std::istream& is; - std::streambuf& sb; -}; - -/// input adapter for buffer input -class input_buffer_adapter : public input_adapter_protocol -{ - public: - input_buffer_adapter(const char* b, const std::size_t l) - : cursor(b), limit(b + l) - {} - - // delete because of pointer members - input_buffer_adapter(const input_buffer_adapter&) = delete; - input_buffer_adapter& operator=(input_buffer_adapter&) = delete; - - std::char_traits::int_type get_character() noexcept override - { - if (JSON_LIKELY(cursor < limit)) - { - return std::char_traits::to_int_type(*(cursor++)); - } - - return std::char_traits::eof(); - } - - private: - /// pointer to the current character - const char* cursor; - /// pointer past the last character - const char* const limit; -}; - -template -class wide_string_input_adapter : public input_adapter_protocol -{ - public: - explicit wide_string_input_adapter(const WideStringType& w) : str(w) {} - - std::char_traits::int_type get_character() noexcept override - { - // check if buffer needs to be filled - if (utf8_bytes_index == utf8_bytes_filled) - { - if (sizeof(typename WideStringType::value_type) == 2) - { - fill_buffer_utf16(); - } - else - { - fill_buffer_utf32(); - } - - assert(utf8_bytes_filled > 0); - assert(utf8_bytes_index == 0); - } - - // use buffer - assert(utf8_bytes_filled > 0); - assert(utf8_bytes_index < utf8_bytes_filled); - return utf8_bytes[utf8_bytes_index++]; - } - - private: - void fill_buffer_utf16() - { - utf8_bytes_index = 0; - - if (current_wchar == str.size()) - { - utf8_bytes[0] = std::char_traits::eof(); - utf8_bytes_filled = 1; - } - else - { - // get the current character - const int wc = static_cast(str[current_wchar++]); - - // UTF-16 to UTF-8 encoding - if (wc < 0x80) - { - utf8_bytes[0] = wc; - utf8_bytes_filled = 1; - } - else if (wc <= 0x7FF) - { - utf8_bytes[0] = 0xC0 | ((wc >> 6)); - utf8_bytes[1] = 0x80 | (wc & 0x3F); - utf8_bytes_filled = 2; - } - else if (0xD800 > wc or wc >= 0xE000) - { - utf8_bytes[0] = 0xE0 | ((wc >> 12)); - utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F); - utf8_bytes[2] = 0x80 | (wc & 0x3F); - utf8_bytes_filled = 3; - } - else - { - if (current_wchar < str.size()) - { - const int wc2 = static_cast(str[current_wchar++]); - const int charcode = 0x10000 + (((wc & 0x3FF) << 10) | (wc2 & 0x3FF)); - utf8_bytes[0] = 0xf0 | (charcode >> 18); - utf8_bytes[1] = 0x80 | ((charcode >> 12) & 0x3F); - utf8_bytes[2] = 0x80 | ((charcode >> 6) & 0x3F); - utf8_bytes[3] = 0x80 | (charcode & 0x3F); - utf8_bytes_filled = 4; - } - else - { - // unknown character - ++current_wchar; - utf8_bytes[0] = wc; - utf8_bytes_filled = 1; - } - } - } - } - - void fill_buffer_utf32() - { - utf8_bytes_index = 0; - - if (current_wchar == str.size()) - { - utf8_bytes[0] = std::char_traits::eof(); - utf8_bytes_filled = 1; - } - else - { - // get the current character - const int wc = static_cast(str[current_wchar++]); - - // UTF-32 to UTF-8 encoding - if (wc < 0x80) - { - utf8_bytes[0] = wc; - utf8_bytes_filled = 1; - } - else if (wc <= 0x7FF) - { - utf8_bytes[0] = 0xC0 | ((wc >> 6) & 0x1F); - utf8_bytes[1] = 0x80 | (wc & 0x3F); - utf8_bytes_filled = 2; - } - else if (wc <= 0xFFFF) - { - utf8_bytes[0] = 0xE0 | ((wc >> 12) & 0x0F); - utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F); - utf8_bytes[2] = 0x80 | (wc & 0x3F); - utf8_bytes_filled = 3; - } - else if (wc <= 0x10FFFF) - { - utf8_bytes[0] = 0xF0 | ((wc >> 18 ) & 0x07); - utf8_bytes[1] = 0x80 | ((wc >> 12) & 0x3F); - utf8_bytes[2] = 0x80 | ((wc >> 6) & 0x3F); - utf8_bytes[3] = 0x80 | (wc & 0x3F); - utf8_bytes_filled = 4; - } - else - { - // unknown character - utf8_bytes[0] = wc; - utf8_bytes_filled = 1; - } - } - } - - private: - /// the wstring to process - const WideStringType& str; - - /// index of the current wchar in str - std::size_t current_wchar = 0; - - /// a buffer for UTF-8 bytes - std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; - - /// index to the utf8_codes array for the next valid byte - std::size_t utf8_bytes_index = 0; - /// number of valid bytes in the utf8_codes array - std::size_t utf8_bytes_filled = 0; -}; - -class input_adapter -{ - public: - // native support - - /// input adapter for input stream - input_adapter(std::istream& i) - : ia(std::make_shared(i)) {} - - /// input adapter for input stream - input_adapter(std::istream&& i) - : ia(std::make_shared(i)) {} - - input_adapter(const std::wstring& ws) - : ia(std::make_shared>(ws)) {} - - input_adapter(const std::u16string& ws) - : ia(std::make_shared>(ws)) {} - - input_adapter(const std::u32string& ws) - : ia(std::make_shared>(ws)) {} - - /// input adapter for buffer - template::value and - std::is_integral::type>::value and - sizeof(typename std::remove_pointer::type) == 1, - int>::type = 0> - input_adapter(CharT b, std::size_t l) - : ia(std::make_shared(reinterpret_cast(b), l)) {} - - // derived support - - /// input adapter for string literal - template::value and - std::is_integral::type>::value and - sizeof(typename std::remove_pointer::type) == 1, - int>::type = 0> - input_adapter(CharT b) - : input_adapter(reinterpret_cast(b), - std::strlen(reinterpret_cast(b))) {} - - /// input adapter for iterator range with contiguous storage - template::iterator_category, std::random_access_iterator_tag>::value, - int>::type = 0> - input_adapter(IteratorType first, IteratorType last) - { - // assertion to check that the iterator range is indeed contiguous, - // see http://stackoverflow.com/a/35008842/266378 for more discussion - assert(std::accumulate( - first, last, std::pair(true, 0), - [&first](std::pair res, decltype(*first) val) - { - res.first &= (val == *(std::next(std::addressof(*first), res.second++))); - return res; - }).first); - - // assertion to check that each element is 1 byte long - static_assert( - sizeof(typename std::iterator_traits::value_type) == 1, - "each element in the iterator range must have the size of 1 byte"); - - const auto len = static_cast(std::distance(first, last)); - if (JSON_LIKELY(len > 0)) - { - // there is at least one element: use the address of first - ia = std::make_shared(reinterpret_cast(&(*first)), len); - } - else - { - // the address of first cannot be used: use nullptr - ia = std::make_shared(nullptr, len); - } - } - - /// input adapter for array - template - input_adapter(T (&array)[N]) - : input_adapter(std::begin(array), std::end(array)) {} - - /// input adapter for contiguous container - template::value and - std::is_base_of()))>::iterator_category>::value, - int>::type = 0> - input_adapter(const ContiguousContainer& c) - : input_adapter(std::begin(c), std::end(c)) {} - - operator input_adapter_t() - { - return ia; - } - - private: - /// the actual adapter - input_adapter_t ia = nullptr; -}; -} -} diff --git a/include/nlohmann/detail/input/json_sax.hpp b/include/nlohmann/detail/input/json_sax.hpp deleted file mode 100644 index 563eac3..0000000 --- a/include/nlohmann/detail/input/json_sax.hpp +++ /dev/null @@ -1,687 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include - -namespace nlohmann -{ - -/*! -@brief SAX interface -*/ -template -struct json_sax -{ - /// type for (signed) integers - using number_integer_t = typename BasicJsonType::number_integer_t; - /// type for unsigned integers - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - /// type for floating-point numbers - using number_float_t = typename BasicJsonType::number_float_t; - /// type for strings - using string_t = typename BasicJsonType::string_t; - - /// constant to indicate that no size limit is given for array or object - static constexpr auto no_limit = std::size_t(-1); - - /*! - @brief a null value was read - @return whether parsing should proceed - */ - virtual bool null() = 0; - - /*! - @brief a boolean value was read - @param[in] val boolean value - @return whether parsing should proceed - */ - virtual bool boolean(bool val) = 0; - - /*! - @brief an integer number was read - @param[in] val integer value - @return whether parsing should proceed - */ - virtual bool number_integer(number_integer_t val) = 0; - - /*! - @brief an unsigned integer number was read - @param[in] val unsigned integer value - @return whether parsing should proceed - */ - virtual bool number_unsigned(number_unsigned_t val) = 0; - - /*! - @brief an floating-point number was read - @param[in] val floating-point value - @param[in] s raw token value - @return whether parsing should proceed - */ - virtual bool number_float(number_float_t val, const string_t& s) = 0; - - /*! - @brief a string was read - @param[in] val string value - @return whether parsing should proceed - */ - virtual bool string(string_t& val) = 0; - - /*! - @brief the beginning of an object was read - @param[in] elements number of object elements or no_limit if unknown - @return whether parsing should proceed - @note binary formats may report the number of elements - */ - virtual bool start_object(std::size_t elements = no_limit) = 0; - - /*! - @brief an object key was read - @param[in] val object key - @return whether parsing should proceed - */ - virtual bool key(string_t& val) = 0; - - /*! - @brief the end of an object was read - @return whether parsing should proceed - */ - virtual bool end_object() = 0; - - /*! - @brief the beginning of an array was read - @param[in] elements number of array elements or no_limit if unknown - @return whether parsing should proceed - @note binary formats may report the number of elements - */ - virtual bool start_array(std::size_t elements = no_limit) = 0; - - /*! - @brief the end of an array was read - @return whether parsing should proceed - */ - virtual bool end_array() = 0; - - /*! - @brief a parse error occurred - @param[in] position the position in the input where the error occurs - @param[in] last_token the last read token - @param[in] error_msg a detailed error message - @return whether parsing should proceed (must return false) - */ - virtual bool parse_error(std::size_t position, - const std::string& last_token, - const detail::exception& ex) = 0; - - virtual ~json_sax() = default; -}; - - -namespace detail -{ -/*! -@brief SAX implementation to create a JSON value from SAX events - -This class implements the @ref json_sax interface and processes the SAX events -to create a JSON value which makes it basically a DOM parser. The structure or -hierarchy of the JSON value is managed by the stack `ref_stack` which contains -a pointer to the respective array or object for each recursion depth. - -After successful parsing, the value that is passed by reference to the -constructor contains the parsed value. - -@tparam BasicJsonType the JSON type -*/ -template -class json_sax_dom_parser : public json_sax -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - - /*! - @param[in, out] r reference to a JSON value that is manipulated while - parsing - @param[in] allow_exceptions_ whether parse errors yield exceptions - */ - json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) - : root(r), allow_exceptions(allow_exceptions_) - {} - - bool null() override - { - handle_value(nullptr); - return true; - } - - bool boolean(bool val) override - { - handle_value(val); - return true; - } - - bool number_integer(number_integer_t val) override - { - handle_value(val); - return true; - } - - bool number_unsigned(number_unsigned_t val) override - { - handle_value(val); - return true; - } - - bool number_float(number_float_t val, const string_t&) override - { - handle_value(val); - return true; - } - - bool string(string_t& val) override - { - handle_value(val); - return true; - } - - bool start_object(std::size_t len) override - { - ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); - - if (JSON_UNLIKELY(len != json_sax::no_limit and len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, - "excessive object size: " + std::to_string(len))); - } - - return true; - } - - bool key(string_t& val) override - { - // add null at given key and store the reference for later - object_element = &(ref_stack.back()->m_value.object->operator[](val)); - return true; - } - - bool end_object() override - { - ref_stack.pop_back(); - return true; - } - - bool start_array(std::size_t len) override - { - ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); - - if (JSON_UNLIKELY(len != json_sax::no_limit and len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, - "excessive array size: " + std::to_string(len))); - } - - return true; - } - - bool end_array() override - { - ref_stack.pop_back(); - return true; - } - - bool parse_error(std::size_t, const std::string&, - const detail::exception& ex) override - { - errored = true; - if (allow_exceptions) - { - // determine the proper exception type from the id - switch ((ex.id / 100) % 100) - { - case 1: - JSON_THROW(*reinterpret_cast(&ex)); - case 2: - JSON_THROW(*reinterpret_cast(&ex)); // LCOV_EXCL_LINE - case 3: - JSON_THROW(*reinterpret_cast(&ex)); // LCOV_EXCL_LINE - case 4: - JSON_THROW(*reinterpret_cast(&ex)); - case 5: - JSON_THROW(*reinterpret_cast(&ex)); // LCOV_EXCL_LINE - default: - assert(false); // LCOV_EXCL_LINE - } - } - return false; - } - - constexpr bool is_errored() const - { - return errored; - } - - private: - /*! - @invariant If the ref stack is empty, then the passed value will be the new - root. - @invariant If the ref stack contains a value, then it is an array or an - object to which we can add elements - */ - template - BasicJsonType* handle_value(Value&& v) - { - if (ref_stack.empty()) - { - root = BasicJsonType(std::forward(v)); - return &root; - } - else - { - assert(ref_stack.back()->is_array() or ref_stack.back()->is_object()); - if (ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->emplace_back(std::forward(v)); - return &(ref_stack.back()->m_value.array->back()); - } - else - { - assert(object_element); - *object_element = BasicJsonType(std::forward(v)); - return object_element; - } - } - } - - /// the parsed JSON value - BasicJsonType& root; - /// stack to model hierarchy of values - std::vector ref_stack; - /// helper to hold the reference for the next object element - BasicJsonType* object_element = nullptr; - /// whether a syntax error occurred - bool errored = false; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; -}; - -template -class json_sax_dom_callback_parser : public json_sax -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using parser_callback_t = typename BasicJsonType::parser_callback_t; - using parse_event_t = typename BasicJsonType::parse_event_t; - - json_sax_dom_callback_parser(BasicJsonType& r, - const parser_callback_t cb, - const bool allow_exceptions_ = true) - : root(r), callback(cb), allow_exceptions(allow_exceptions_) - { - keep_stack.push_back(true); - } - - bool null() override - { - handle_value(nullptr); - return true; - } - - bool boolean(bool val) override - { - handle_value(val); - return true; - } - - bool number_integer(number_integer_t val) override - { - handle_value(val); - return true; - } - - bool number_unsigned(number_unsigned_t val) override - { - handle_value(val); - return true; - } - - bool number_float(number_float_t val, const string_t&) override - { - handle_value(val); - return true; - } - - bool string(string_t& val) override - { - handle_value(val); - return true; - } - - bool start_object(std::size_t len) override - { - // check callback for object start - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); - keep_stack.push_back(keep); - - auto val = handle_value(BasicJsonType::value_t::object, true); - ref_stack.push_back(val.second); - - // check object limit - if (ref_stack.back()) - { - if (JSON_UNLIKELY(len != json_sax::no_limit and len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, - "excessive object size: " + std::to_string(len))); - } - } - - return true; - } - - bool key(string_t& val) override - { - BasicJsonType k = BasicJsonType(val); - - // check callback for key - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); - key_keep_stack.push_back(keep); - - // add discarded value at given key and store the reference for later - if (keep and ref_stack.back()) - { - object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); - } - - return true; - } - - bool end_object() override - { - if (ref_stack.back()) - { - if (not callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) - { - // discard object - *ref_stack.back() = discarded; - } - } - - assert(not ref_stack.empty()); - assert(not keep_stack.empty()); - ref_stack.pop_back(); - keep_stack.pop_back(); - - if (not ref_stack.empty() and ref_stack.back()) - { - // remove discarded value - if (ref_stack.back()->is_object()) - { - for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) - { - if (it->is_discarded()) - { - ref_stack.back()->erase(it); - break; - } - } - } - } - - return true; - } - - bool start_array(std::size_t len) override - { - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); - keep_stack.push_back(keep); - - auto val = handle_value(BasicJsonType::value_t::array, true); - ref_stack.push_back(val.second); - - // check array limit - if (ref_stack.back()) - { - if (JSON_UNLIKELY(len != json_sax::no_limit and len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, - "excessive array size: " + std::to_string(len))); - } - } - - return true; - } - - bool end_array() override - { - bool keep = true; - - if (ref_stack.back()) - { - keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); - if (not keep) - { - // discard array - *ref_stack.back() = discarded; - } - } - - assert(not ref_stack.empty()); - assert(not keep_stack.empty()); - ref_stack.pop_back(); - keep_stack.pop_back(); - - // remove discarded value - if (not keep and not ref_stack.empty()) - { - if (ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->pop_back(); - } - } - - return true; - } - - bool parse_error(std::size_t, const std::string&, - const detail::exception& ex) override - { - errored = true; - if (allow_exceptions) - { - // determine the proper exception type from the id - switch ((ex.id / 100) % 100) - { - case 1: - JSON_THROW(*reinterpret_cast(&ex)); - case 2: - JSON_THROW(*reinterpret_cast(&ex)); // LCOV_EXCL_LINE - case 3: - JSON_THROW(*reinterpret_cast(&ex)); // LCOV_EXCL_LINE - case 4: - JSON_THROW(*reinterpret_cast(&ex)); - case 5: - JSON_THROW(*reinterpret_cast(&ex)); // LCOV_EXCL_LINE - default: - assert(false); // LCOV_EXCL_LINE - } - } - return false; - } - - constexpr bool is_errored() const - { - return errored; - } - - private: - /*! - @param[in] v value to add to the JSON value we build during parsing - @param[in] skip_callback whether we should skip calling the callback - function; this is required after start_array() and - start_object() SAX events, because otherwise we would call the - callback function with an empty array or object, respectively. - - @invariant If the ref stack is empty, then the passed value will be the new - root. - @invariant If the ref stack contains a value, then it is an array or an - object to which we can add elements - - @return pair of boolean (whether value should be kept) and pointer (to the - passed value in the ref_stack hierarchy; nullptr if not kept) - */ - template - std::pair handle_value(Value&& v, const bool skip_callback = false) - { - assert(not keep_stack.empty()); - - // do not handle this value if we know it would be added to a discarded - // container - if (not keep_stack.back()) - { - return {false, nullptr}; - } - - // create value - auto value = BasicJsonType(std::forward(v)); - - // check callback - const bool keep = skip_callback or callback(static_cast(ref_stack.size()), parse_event_t::value, value); - - // do not handle this value if we just learnt it shall be discarded - if (not keep) - { - return {false, nullptr}; - } - - if (ref_stack.empty()) - { - root = std::move(value); - return {true, &root}; - } - else - { - assert(ref_stack.back()->is_array() or ref_stack.back()->is_object()); - if (ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->push_back(std::move(value)); - return {true, &(ref_stack.back()->m_value.array->back())}; - } - else - { - // check if we should store an element for the current key - assert(not key_keep_stack.empty()); - const bool store_element = key_keep_stack.back(); - key_keep_stack.pop_back(); - - if (not store_element) - { - return {false, nullptr}; - } - - assert(object_element); - *object_element = std::move(value); - return {true, object_element}; - } - } - } - - /// the parsed JSON value - BasicJsonType& root; - /// stack to model hierarchy of values - std::vector ref_stack; - /// stack to manage which values to keep - std::vector keep_stack; - /// stack to manage which object keys to keep - std::vector key_keep_stack; - /// helper to hold the reference for the next object element - BasicJsonType* object_element = nullptr; - /// whether a syntax error occurred - bool errored = false; - /// callback function - const parser_callback_t callback = nullptr; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; - /// a discarded value for the callback - BasicJsonType discarded = BasicJsonType::value_t::discarded; -}; - -template -class json_sax_acceptor : public json_sax -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - - bool null() override - { - return true; - } - - bool boolean(bool) override - { - return true; - } - - bool number_integer(number_integer_t) override - { - return true; - } - - bool number_unsigned(number_unsigned_t) override - { - return true; - } - - bool number_float(number_float_t, const string_t&) override - { - return true; - } - - bool string(string_t&) override - { - return true; - } - - bool start_object(std::size_t) override - { - return true; - } - - bool key(string_t&) override - { - return true; - } - - bool end_object() override - { - return true; - } - - bool start_array(std::size_t) override - { - return true; - } - - bool end_array() override - { - return true; - } - - bool parse_error(std::size_t, const std::string&, const detail::exception&) override - { - return false; - } -}; -} - -} diff --git a/include/nlohmann/detail/input/lexer.hpp b/include/nlohmann/detail/input/lexer.hpp deleted file mode 100644 index 9b7c8de..0000000 --- a/include/nlohmann/detail/input/lexer.hpp +++ /dev/null @@ -1,1329 +0,0 @@ -#pragma once - -#include // localeconv -#include // size_t -#include // strtof, strtod, strtold, strtoll, strtoull -#include // snprintf -#include // initializer_list -#include // char_traits, string -#include // vector - -#include -#include - -namespace nlohmann -{ -namespace detail -{ -/////////// -// lexer // -/////////// - -/*! -@brief lexical analysis - -This class organizes the lexical analysis during JSON deserialization. -*/ -template -class lexer -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - - public: - /// token types for the parser - enum class token_type - { - uninitialized, ///< indicating the scanner is uninitialized - literal_true, ///< the `true` literal - literal_false, ///< the `false` literal - literal_null, ///< the `null` literal - value_string, ///< a string -- use get_string() for actual value - value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value - value_integer, ///< a signed integer -- use get_number_integer() for actual value - value_float, ///< an floating point number -- use get_number_float() for actual value - begin_array, ///< the character for array begin `[` - begin_object, ///< the character for object begin `{` - end_array, ///< the character for array end `]` - end_object, ///< the character for object end `}` - name_separator, ///< the name separator `:` - value_separator, ///< the value separator `,` - parse_error, ///< indicating a parse error - end_of_input, ///< indicating the end of the input buffer - literal_or_value ///< a literal or the begin of a value (only for diagnostics) - }; - - /// return name of values of type token_type (only used for errors) - static const char* token_type_name(const token_type t) noexcept - { - switch (t) - { - case token_type::uninitialized: - return ""; - case token_type::literal_true: - return "true literal"; - case token_type::literal_false: - return "false literal"; - case token_type::literal_null: - return "null literal"; - case token_type::value_string: - return "string literal"; - case lexer::token_type::value_unsigned: - case lexer::token_type::value_integer: - case lexer::token_type::value_float: - return "number literal"; - case token_type::begin_array: - return "'['"; - case token_type::begin_object: - return "'{'"; - case token_type::end_array: - return "']'"; - case token_type::end_object: - return "'}'"; - case token_type::name_separator: - return "':'"; - case token_type::value_separator: - return "','"; - case token_type::parse_error: - return ""; - case token_type::end_of_input: - return "end of input"; - case token_type::literal_or_value: - return "'[', '{', or a literal"; - default: // catch non-enum values - return "unknown token"; // LCOV_EXCL_LINE - } - } - - explicit lexer(detail::input_adapter_t&& adapter) - : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {} - - // delete because of pointer members - lexer(const lexer&) = delete; - lexer& operator=(lexer&) = delete; - - private: - ///////////////////// - // locales - ///////////////////// - - /// return the locale-dependent decimal point - static char get_decimal_point() noexcept - { - const auto loc = localeconv(); - assert(loc != nullptr); - return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); - } - - ///////////////////// - // scan functions - ///////////////////// - - /*! - @brief get codepoint from 4 hex characters following `\u` - - For input "\u c1 c2 c3 c4" the codepoint is: - (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 - = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) - - Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' - must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The - conversion is done by subtracting the offset (0x30, 0x37, and 0x57) - between the ASCII value of the character and the desired integer value. - - @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or - non-hex character) - */ - int get_codepoint() - { - // this function only makes sense after reading `\u` - assert(current == 'u'); - int codepoint = 0; - - const auto factors = { 12, 8, 4, 0 }; - for (const auto factor : factors) - { - get(); - - if (current >= '0' and current <= '9') - { - codepoint += ((current - 0x30) << factor); - } - else if (current >= 'A' and current <= 'F') - { - codepoint += ((current - 0x37) << factor); - } - else if (current >= 'a' and current <= 'f') - { - codepoint += ((current - 0x57) << factor); - } - else - { - return -1; - } - } - - assert(0x0000 <= codepoint and codepoint <= 0xFFFF); - return codepoint; - } - - /*! - @brief check if the next byte(s) are inside a given range - - Adds the current byte and, for each passed range, reads a new byte and - checks if it is inside the range. If a violation was detected, set up an - error message and return false. Otherwise, return true. - - @param[in] ranges list of integers; interpreted as list of pairs of - inclusive lower and upper bound, respectively - - @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, - 1, 2, or 3 pairs. This precondition is enforced by an assertion. - - @return true if and only if no range violation was detected - */ - bool next_byte_in_range(std::initializer_list ranges) - { - assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6); - add(current); - - for (auto range = ranges.begin(); range != ranges.end(); ++range) - { - get(); - if (JSON_LIKELY(*range <= current and current <= *(++range))) - { - add(current); - } - else - { - error_message = "invalid string: ill-formed UTF-8 byte"; - return false; - } - } - - return true; - } - - /*! - @brief scan a string literal - - This function scans a string according to Sect. 7 of RFC 7159. While - scanning, bytes are escaped and copied into buffer token_buffer. Then the - function returns successfully, token_buffer is *not* null-terminated (as it - may contain \0 bytes), and token_buffer.size() is the number of bytes in the - string. - - @return token_type::value_string if string could be successfully scanned, - token_type::parse_error otherwise - - @note In case of errors, variable error_message contains a textual - description. - */ - token_type scan_string() - { - // reset token_buffer (ignore opening quote) - reset(); - - // we entered the function by reading an open quote - assert(current == '\"'); - - while (true) - { - // get next character - switch (get()) - { - // end of file while parsing string - case std::char_traits::eof(): - { - error_message = "invalid string: missing closing quote"; - return token_type::parse_error; - } - - // closing quote - case '\"': - { - return token_type::value_string; - } - - // escapes - case '\\': - { - switch (get()) - { - // quotation mark - case '\"': - add('\"'); - break; - // reverse solidus - case '\\': - add('\\'); - break; - // solidus - case '/': - add('/'); - break; - // backspace - case 'b': - add('\b'); - break; - // form feed - case 'f': - add('\f'); - break; - // line feed - case 'n': - add('\n'); - break; - // carriage return - case 'r': - add('\r'); - break; - // tab - case 't': - add('\t'); - break; - - // unicode escapes - case 'u': - { - const int codepoint1 = get_codepoint(); - int codepoint = codepoint1; // start with codepoint1 - - if (JSON_UNLIKELY(codepoint1 == -1)) - { - error_message = "invalid string: '\\u' must be followed by 4 hex digits"; - return token_type::parse_error; - } - - // check if code point is a high surrogate - if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF) - { - // expect next \uxxxx entry - if (JSON_LIKELY(get() == '\\' and get() == 'u')) - { - const int codepoint2 = get_codepoint(); - - if (JSON_UNLIKELY(codepoint2 == -1)) - { - error_message = "invalid string: '\\u' must be followed by 4 hex digits"; - return token_type::parse_error; - } - - // check if codepoint2 is a low surrogate - if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF)) - { - // overwrite codepoint - codepoint = - // high surrogate occupies the most significant 22 bits - (codepoint1 << 10) - // low surrogate occupies the least significant 15 bits - + codepoint2 - // there is still the 0xD800, 0xDC00 and 0x10000 noise - // in the result so we have to subtract with: - // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - - 0x35FDC00; - } - else - { - error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; - return token_type::parse_error; - } - } - else - { - error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; - return token_type::parse_error; - } - } - else - { - if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF)) - { - error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; - return token_type::parse_error; - } - } - - // result of the above calculation yields a proper codepoint - assert(0x00 <= codepoint and codepoint <= 0x10FFFF); - - // translate codepoint into bytes - if (codepoint < 0x80) - { - // 1-byte characters: 0xxxxxxx (ASCII) - add(codepoint); - } - else if (codepoint <= 0x7FF) - { - // 2-byte characters: 110xxxxx 10xxxxxx - add(0xC0 | (codepoint >> 6)); - add(0x80 | (codepoint & 0x3F)); - } - else if (codepoint <= 0xFFFF) - { - // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx - add(0xE0 | (codepoint >> 12)); - add(0x80 | ((codepoint >> 6) & 0x3F)); - add(0x80 | (codepoint & 0x3F)); - } - else - { - // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - add(0xF0 | (codepoint >> 18)); - add(0x80 | ((codepoint >> 12) & 0x3F)); - add(0x80 | ((codepoint >> 6) & 0x3F)); - add(0x80 | (codepoint & 0x3F)); - } - - break; - } - - // other characters after escape - default: - error_message = "invalid string: forbidden character after backslash"; - return token_type::parse_error; - } - - break; - } - - // invalid control characters - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - case 0x08: - case 0x09: - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x17: - case 0x18: - case 0x19: - case 0x1A: - case 0x1B: - case 0x1C: - case 0x1D: - case 0x1E: - case 0x1F: - { - error_message = "invalid string: control character must be escaped"; - return token_type::parse_error; - } - - // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) - case 0x20: - case 0x21: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: - case 0x59: - case 0x5A: - case 0x5B: - case 0x5D: - case 0x5E: - case 0x5F: - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: - case 0x79: - case 0x7A: - case 0x7B: - case 0x7C: - case 0x7D: - case 0x7E: - case 0x7F: - { - add(current); - break; - } - - // U+0080..U+07FF: bytes C2..DF 80..BF - case 0xC2: - case 0xC3: - case 0xC4: - case 0xC5: - case 0xC6: - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCB: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xD3: - case 0xD4: - case 0xD5: - case 0xD6: - case 0xD7: - case 0xD8: - case 0xD9: - case 0xDA: - case 0xDB: - case 0xDC: - case 0xDD: - case 0xDE: - case 0xDF: - { - if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF}))) - { - return token_type::parse_error; - } - break; - } - - // U+0800..U+0FFF: bytes E0 A0..BF 80..BF - case 0xE0: - { - if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF - // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF - case 0xE1: - case 0xE2: - case 0xE3: - case 0xE4: - case 0xE5: - case 0xE6: - case 0xE7: - case 0xE8: - case 0xE9: - case 0xEA: - case 0xEB: - case 0xEC: - case 0xEE: - case 0xEF: - { - if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+D000..U+D7FF: bytes ED 80..9F 80..BF - case 0xED: - { - if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF - case 0xF0: - { - if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF - case 0xF1: - case 0xF2: - case 0xF3: - { - if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF - case 0xF4: - { - if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // remaining bytes (80..C1 and F5..FF) are ill-formed - default: - { - error_message = "invalid string: ill-formed UTF-8 byte"; - return token_type::parse_error; - } - } - } - } - - static void strtof(float& f, const char* str, char** endptr) noexcept - { - f = std::strtof(str, endptr); - } - - static void strtof(double& f, const char* str, char** endptr) noexcept - { - f = std::strtod(str, endptr); - } - - static void strtof(long double& f, const char* str, char** endptr) noexcept - { - f = std::strtold(str, endptr); - } - - /*! - @brief scan a number literal - - This function scans a string according to Sect. 6 of RFC 7159. - - The function is realized with a deterministic finite state machine derived - from the grammar described in RFC 7159. Starting in state "init", the - input is read and used to determined the next state. Only state "done" - accepts the number. State "error" is a trap state to model errors. In the - table below, "anything" means any character but the ones listed before. - - state | 0 | 1-9 | e E | + | - | . | anything - ---------|----------|----------|----------|---------|---------|----------|----------- - init | zero | any1 | [error] | [error] | minus | [error] | [error] - minus | zero | any1 | [error] | [error] | [error] | [error] | [error] - zero | done | done | exponent | done | done | decimal1 | done - any1 | any1 | any1 | exponent | done | done | decimal1 | done - decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error] - decimal2 | decimal2 | decimal2 | exponent | done | done | done | done - exponent | any2 | any2 | [error] | sign | sign | [error] | [error] - sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] - any2 | any2 | any2 | done | done | done | done | done - - The state machine is realized with one label per state (prefixed with - "scan_number_") and `goto` statements between them. The state machine - contains cycles, but any cycle can be left when EOF is read. Therefore, - the function is guaranteed to terminate. - - During scanning, the read bytes are stored in token_buffer. This string is - then converted to a signed integer, an unsigned integer, or a - floating-point number. - - @return token_type::value_unsigned, token_type::value_integer, or - token_type::value_float if number could be successfully scanned, - token_type::parse_error otherwise - - @note The scanner is independent of the current locale. Internally, the - locale's decimal point is used instead of `.` to work with the - locale-dependent converters. - */ - token_type scan_number() - { - // reset token_buffer to store the number's bytes - reset(); - - // the type of the parsed number; initially set to unsigned; will be - // changed if minus sign, decimal point or exponent is read - token_type number_type = token_type::value_unsigned; - - // state (init): we just found out we need to scan a number - switch (current) - { - case '-': - { - add(current); - goto scan_number_minus; - } - - case '0': - { - add(current); - goto scan_number_zero; - } - - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - default: - { - // all other characters are rejected outside scan_number() - assert(false); // LCOV_EXCL_LINE - } - } - -scan_number_minus: - // state: we just parsed a leading minus sign - number_type = token_type::value_integer; - switch (get()) - { - case '0': - { - add(current); - goto scan_number_zero; - } - - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - default: - { - error_message = "invalid number; expected digit after '-'"; - return token_type::parse_error; - } - } - -scan_number_zero: - // state: we just parse a zero (maybe with a leading minus sign) - switch (get()) - { - case '.': - { - add(decimal_point_char); - goto scan_number_decimal1; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_any1: - // state: we just parsed a number 0-9 (maybe with a leading minus sign) - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - case '.': - { - add(decimal_point_char); - goto scan_number_decimal1; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_decimal1: - // state: we just parsed a decimal point - number_type = token_type::value_float; - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_decimal2; - } - - default: - { - error_message = "invalid number; expected digit after '.'"; - return token_type::parse_error; - } - } - -scan_number_decimal2: - // we just parsed at least one number after a decimal point - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_decimal2; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_exponent: - // we just parsed an exponent - number_type = token_type::value_float; - switch (get()) - { - case '+': - case '-': - { - add(current); - goto scan_number_sign; - } - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - { - error_message = - "invalid number; expected '+', '-', or digit after exponent"; - return token_type::parse_error; - } - } - -scan_number_sign: - // we just parsed an exponent sign - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - { - error_message = "invalid number; expected digit after exponent sign"; - return token_type::parse_error; - } - } - -scan_number_any2: - // we just parsed a number after the exponent or exponent sign - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - goto scan_number_done; - } - -scan_number_done: - // unget the character after the number (we only read it to know that - // we are done scanning a number) - unget(); - - char* endptr = nullptr; - errno = 0; - - // try to parse integers first and fall back to floats - if (number_type == token_type::value_unsigned) - { - const auto x = std::strtoull(token_buffer.data(), &endptr, 10); - - // we checked the number format before - assert(endptr == token_buffer.data() + token_buffer.size()); - - if (errno == 0) - { - value_unsigned = static_cast(x); - if (value_unsigned == x) - { - return token_type::value_unsigned; - } - } - } - else if (number_type == token_type::value_integer) - { - const auto x = std::strtoll(token_buffer.data(), &endptr, 10); - - // we checked the number format before - assert(endptr == token_buffer.data() + token_buffer.size()); - - if (errno == 0) - { - value_integer = static_cast(x); - if (value_integer == x) - { - return token_type::value_integer; - } - } - } - - // this code is reached if we parse a floating-point number or if an - // integer conversion above failed - strtof(value_float, token_buffer.data(), &endptr); - - // we checked the number format before - assert(endptr == token_buffer.data() + token_buffer.size()); - - return token_type::value_float; - } - - /*! - @param[in] literal_text the literal text to expect - @param[in] length the length of the passed literal text - @param[in] return_type the token type to return on success - */ - token_type scan_literal(const char* literal_text, const std::size_t length, - token_type return_type) - { - assert(current == literal_text[0]); - for (std::size_t i = 1; i < length; ++i) - { - if (JSON_UNLIKELY(get() != literal_text[i])) - { - error_message = "invalid literal"; - return token_type::parse_error; - } - } - return return_type; - } - - ///////////////////// - // input management - ///////////////////// - - /// reset token_buffer; current character is beginning of token - void reset() noexcept - { - token_buffer.clear(); - token_string.clear(); - token_string.push_back(std::char_traits::to_char_type(current)); - } - - /* - @brief get next character from the input - - This function provides the interface to the used input adapter. It does - not throw in case the input reached EOF, but returns a - `std::char_traits::eof()` in that case. Stores the scanned characters - for use in error messages. - - @return character read from the input - */ - std::char_traits::int_type get() - { - ++chars_read; - if (next_unget) - { - // just reset the next_unget variable and work with current - next_unget = false; - } - else - { - current = ia->get_character(); - } - - if (JSON_LIKELY(current != std::char_traits::eof())) - { - token_string.push_back(std::char_traits::to_char_type(current)); - } - return current; - } - - /*! - @brief unget current character (read it again on next get) - - We implement unget by setting variable next_unget to true. The input is not - changed - we just simulate ungetting by modifying chars_read and - token_string. The next call to get() will behave as if the unget character - is read again. - */ - void unget() - { - next_unget = true; - --chars_read; - if (JSON_LIKELY(current != std::char_traits::eof())) - { - assert(token_string.size() != 0); - token_string.pop_back(); - } - } - - /// add a character to token_buffer - void add(int c) - { - token_buffer.push_back(std::char_traits::to_char_type(c)); - } - - public: - ///////////////////// - // value getters - ///////////////////// - - /// return integer value - constexpr number_integer_t get_number_integer() const noexcept - { - return value_integer; - } - - /// return unsigned integer value - constexpr number_unsigned_t get_number_unsigned() const noexcept - { - return value_unsigned; - } - - /// return floating-point value - constexpr number_float_t get_number_float() const noexcept - { - return value_float; - } - - /// return current string value (implicitly resets the token; useful only once) - string_t& get_string() - { - return token_buffer; - } - - ///////////////////// - // diagnostics - ///////////////////// - - /// return position of last read token - constexpr std::size_t get_position() const noexcept - { - return chars_read; - } - - /// return the last read token (for errors only). Will never contain EOF - /// (an arbitrary value that is not a valid char value, often -1), because - /// 255 may legitimately occur. May contain NUL, which should be escaped. - std::string get_token_string() const - { - // escape control characters - std::string result; - for (const auto c : token_string) - { - if ('\x00' <= c and c <= '\x1F') - { - // escape control characters - char cs[9]; - snprintf(cs, 9, "", static_cast(c)); - result += cs; - } - else - { - // add character as is - result.push_back(c); - } - } - - return result; - } - - /// return syntax error message - constexpr const char* get_error_message() const noexcept - { - return error_message; - } - - ///////////////////// - // actual scanner - ///////////////////// - - /*! - @brief skip the UTF-8 byte order mark - @return true iff there is no BOM or the correct BOM has been skipped - */ - bool skip_bom() - { - if (get() == 0xEF) - { - if (get() == 0xBB and get() == 0xBF) - { - // we completely parsed the BOM - return true; - } - else - { - // after reading 0xEF, an unexpected character followed - return false; - } - } - else - { - // the first character is not the beginning of the BOM; unget it to - // process is later - unget(); - return true; - } - } - - token_type scan() - { - // initially, skip the BOM - if (chars_read == 0 and not skip_bom()) - { - error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; - return token_type::parse_error; - } - - // read next character and ignore whitespace - do - { - get(); - } - while (current == ' ' or current == '\t' or current == '\n' or current == '\r'); - - switch (current) - { - // structural characters - case '[': - return token_type::begin_array; - case ']': - return token_type::end_array; - case '{': - return token_type::begin_object; - case '}': - return token_type::end_object; - case ':': - return token_type::name_separator; - case ',': - return token_type::value_separator; - - // literals - case 't': - return scan_literal("true", 4, token_type::literal_true); - case 'f': - return scan_literal("false", 5, token_type::literal_false); - case 'n': - return scan_literal("null", 4, token_type::literal_null); - - // string - case '\"': - return scan_string(); - - // number - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return scan_number(); - - // end of input (the null byte is needed when parsing from - // string literals) - case '\0': - case std::char_traits::eof(): - return token_type::end_of_input; - - // error - default: - error_message = "invalid literal"; - return token_type::parse_error; - } - } - - private: - /// input adapter - detail::input_adapter_t ia = nullptr; - - /// the current character - std::char_traits::int_type current = std::char_traits::eof(); - - /// whether the next get() call should just return current - bool next_unget = false; - - /// the number of characters read - std::size_t chars_read = 0; - - /// raw input token string (for error messages) - std::vector token_string {}; - - /// buffer for variable-length tokens (numbers, strings) - string_t token_buffer {}; - - /// a description of occurred lexer errors - const char* error_message = ""; - - // number values - number_integer_t value_integer = 0; - number_unsigned_t value_unsigned = 0; - number_float_t value_float = 0; - - /// the decimal point - const char decimal_point_char = '.'; -}; -} -} diff --git a/include/nlohmann/detail/input/parser.hpp b/include/nlohmann/detail/input/parser.hpp deleted file mode 100644 index c3cfcd5..0000000 --- a/include/nlohmann/detail/input/parser.hpp +++ /dev/null @@ -1,486 +0,0 @@ -#pragma once - -#include // assert -#include // isfinite -#include // uint8_t -#include // function -#include // string -#include // move - -#include -#include -#include -#include -#include -#include - -namespace nlohmann -{ -namespace detail -{ -//////////// -// parser // -//////////// - -/*! -@brief syntax analysis - -This class implements a recursive decent parser. -*/ -template -class parser -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using lexer_t = lexer; - using token_type = typename lexer_t::token_type; - - public: - enum class parse_event_t : uint8_t - { - /// the parser read `{` and started to process a JSON object - object_start, - /// the parser read `}` and finished processing a JSON object - object_end, - /// the parser read `[` and started to process a JSON array - array_start, - /// the parser read `]` and finished processing a JSON array - array_end, - /// the parser read a key of a value in an object - key, - /// the parser finished reading a JSON value - value - }; - - using json_sax_t = json_sax; - - using parser_callback_t = - std::function; - - /// a parser reading from an input adapter - explicit parser(detail::input_adapter_t&& adapter, - const parser_callback_t cb = nullptr, - const bool allow_exceptions_ = true) - : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_) - { - // read first token - get_token(); - } - - /*! - @brief public parser interface - - @param[in] strict whether to expect the last token to be EOF - @param[in,out] result parsed JSON value - - @throw parse_error.101 in case of an unexpected token - @throw parse_error.102 if to_unicode fails or surrogate error - @throw parse_error.103 if to_unicode fails - */ - void parse(const bool strict, BasicJsonType& result) - { - if (callback) - { - json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); - sax_parse_internal(&sdp); - result.assert_invariant(); - - // in strict mode, input must be completely read - if (strict and (get_token() != token_type::end_of_input)) - { - sdp.parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input))); - } - - // in case of an error, return discarded value - if (sdp.is_errored()) - { - result = value_t::discarded; - return; - } - - // set top-level value to null if it was discarded by the callback - // function - if (result.is_discarded()) - { - result = nullptr; - } - } - else - { - json_sax_dom_parser sdp(result, allow_exceptions); - sax_parse_internal(&sdp); - result.assert_invariant(); - - // in strict mode, input must be completely read - if (strict and (get_token() != token_type::end_of_input)) - { - sdp.parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input))); - } - - // in case of an error, return discarded value - if (sdp.is_errored()) - { - result = value_t::discarded; - return; - } - } - } - - /*! - @brief public accept interface - - @param[in] strict whether to expect the last token to be EOF - @return whether the input is a proper JSON text - */ - bool accept(const bool strict = true) - { - json_sax_acceptor sax_acceptor; - return sax_parse(&sax_acceptor, strict); - } - - bool sax_parse(json_sax_t* sax, const bool strict = true) - { - const bool result = sax_parse_internal(sax); - - // strict mode: next byte must be EOF - if (result and strict and (get_token() != token_type::end_of_input)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input))); - } - - return result; - } - - private: - bool sax_parse_internal(json_sax_t* sax) - { - // stack to remember the hieararchy of structured values we are parsing - // true = array; false = object - std::vector states; - // value to avoid a goto (see comment where set to true) - bool skip_to_state_evaluation = false; - - while (true) - { - if (not skip_to_state_evaluation) - { - // invariant: get_token() was called before each iteration - switch (last_token) - { - case token_type::begin_object: - { - if (JSON_UNLIKELY(not sax->start_object())) - { - return false; - } - - // closing } -> we are done - if (get_token() == token_type::end_object) - { - if (JSON_UNLIKELY(not sax->end_object())) - { - return false; - } - break; - } - - // parse key - if (JSON_UNLIKELY(last_token != token_type::value_string)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string))); - } - else - { - if (JSON_UNLIKELY(not sax->key(m_lexer.get_string()))) - { - return false; - } - } - - // parse separator (:) - if (JSON_UNLIKELY(get_token() != token_type::name_separator)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator))); - } - - // remember we are now inside an object - states.push_back(false); - - // parse values - get_token(); - continue; - } - - case token_type::begin_array: - { - if (JSON_UNLIKELY(not sax->start_array())) - { - return false; - } - - // closing ] -> we are done - if (get_token() == token_type::end_array) - { - if (JSON_UNLIKELY(not sax->end_array())) - { - return false; - } - break; - } - - // remember we are now inside an array - states.push_back(true); - - // parse values (no need to call get_token) - continue; - } - - case token_type::value_float: - { - const auto res = m_lexer.get_number_float(); - - if (JSON_UNLIKELY(not std::isfinite(res))) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'")); - } - else - { - if (JSON_UNLIKELY(not sax->number_float(res, m_lexer.get_string()))) - { - return false; - } - break; - } - } - - case token_type::literal_false: - { - if (JSON_UNLIKELY(not sax->boolean(false))) - { - return false; - } - break; - } - - case token_type::literal_null: - { - if (JSON_UNLIKELY(not sax->null())) - { - return false; - } - break; - } - - case token_type::literal_true: - { - if (JSON_UNLIKELY(not sax->boolean(true))) - { - return false; - } - break; - } - - case token_type::value_integer: - { - if (JSON_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer()))) - { - return false; - } - break; - } - - case token_type::value_string: - { - if (JSON_UNLIKELY(not sax->string(m_lexer.get_string()))) - { - return false; - } - break; - } - - case token_type::value_unsigned: - { - if (JSON_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned()))) - { - return false; - } - break; - } - - case token_type::parse_error: - { - // using "uninitialized" to avoid "expected" message - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized))); - } - - default: // the last token was unexpected - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value))); - } - } - } - else - { - skip_to_state_evaluation = false; - } - - // we reached this line after we successfully parsed a value - if (states.empty()) - { - // empty stack: we reached the end of the hieararchy: done - return true; - } - else - { - if (states.back()) // array - { - // comma -> next value - if (get_token() == token_type::value_separator) - { - // parse a new value - get_token(); - continue; - } - - // closing ] - if (JSON_LIKELY(last_token == token_type::end_array)) - { - if (JSON_UNLIKELY(not sax->end_array())) - { - return false; - } - - // We are done with this array. Before we can parse a - // new value, we need to evaluate the new state first. - // By setting skip_to_state_evaluation to false, we - // are effectively jumping to the beginning of this if. - assert(not states.empty()); - states.pop_back(); - skip_to_state_evaluation = true; - continue; - } - else - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array))); - } - } - else // object - { - // comma -> next value - if (get_token() == token_type::value_separator) - { - // parse key - if (JSON_UNLIKELY(get_token() != token_type::value_string)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string))); - } - else - { - if (JSON_UNLIKELY(not sax->key(m_lexer.get_string()))) - { - return false; - } - } - - // parse separator (:) - if (JSON_UNLIKELY(get_token() != token_type::name_separator)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator))); - } - - // parse values - get_token(); - continue; - } - - // closing } - if (JSON_LIKELY(last_token == token_type::end_object)) - { - if (JSON_UNLIKELY(not sax->end_object())) - { - return false; - } - - // We are done with this object. Before we can parse a - // new value, we need to evaluate the new state first. - // By setting skip_to_state_evaluation to false, we - // are effectively jumping to the beginning of this if. - assert(not states.empty()); - states.pop_back(); - skip_to_state_evaluation = true; - continue; - } - else - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object))); - } - } - } - } - } - - /// get next token from lexer - token_type get_token() - { - return (last_token = m_lexer.scan()); - } - - std::string exception_message(const token_type expected) - { - std::string error_msg = "syntax error - "; - if (last_token == token_type::parse_error) - { - error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + - m_lexer.get_token_string() + "'"; - } - else - { - error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); - } - - if (expected != token_type::uninitialized) - { - error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); - } - - return error_msg; - } - - private: - /// callback function - const parser_callback_t callback = nullptr; - /// the type of the last read token - token_type last_token = token_type::uninitialized; - /// the lexer - lexer_t m_lexer; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; -}; -} -} diff --git a/include/nlohmann/detail/iterators/internal_iterator.hpp b/include/nlohmann/detail/iterators/internal_iterator.hpp deleted file mode 100644 index d9b8fb2..0000000 --- a/include/nlohmann/detail/iterators/internal_iterator.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include - -namespace nlohmann -{ -namespace detail -{ -/*! -@brief an iterator value - -@note This structure could easily be a union, but MSVC currently does not allow -unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. -*/ -template struct internal_iterator -{ - /// iterator for JSON objects - typename BasicJsonType::object_t::iterator object_iterator {}; - /// iterator for JSON arrays - typename BasicJsonType::array_t::iterator array_iterator {}; - /// generic iterator for all other types - primitive_iterator_t primitive_iterator {}; -}; -} -} diff --git a/include/nlohmann/detail/iterators/iter_impl.hpp b/include/nlohmann/detail/iterators/iter_impl.hpp deleted file mode 100644 index f34f7a5..0000000 --- a/include/nlohmann/detail/iterators/iter_impl.hpp +++ /dev/null @@ -1,614 +0,0 @@ -#pragma once - -#include // not -#include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next -#include // conditional, is_const, remove_const - -#include -#include -#include -#include -#include -#include - -namespace nlohmann -{ -namespace detail -{ -// forward declare, to be able to friend it later on -template class iteration_proxy; - -/*! -@brief a template for a bidirectional iterator for the @ref basic_json class - -This class implements a both iterators (iterator and const_iterator) for the -@ref basic_json class. - -@note An iterator is called *initialized* when a pointer to a JSON value has - been set (e.g., by a constructor or a copy assignment). If the iterator is - default-constructed, it is *uninitialized* and most methods are undefined. - **The library uses assertions to detect calls on uninitialized iterators.** - -@requirement The class satisfies the following concept requirements: -- -[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): - The iterator that can be moved can be moved in both directions (i.e. - incremented and decremented). - -@since version 1.0.0, simplified in version 2.0.9, change to bidirectional - iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) -*/ -template -class iter_impl -{ - /// allow basic_json to access private members - friend iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; - friend BasicJsonType; - friend iteration_proxy; - - using object_t = typename BasicJsonType::object_t; - using array_t = typename BasicJsonType::array_t; - // make sure BasicJsonType is basic_json or const basic_json - static_assert(is_basic_json::type>::value, - "iter_impl only accepts (const) basic_json"); - - public: - - /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. - /// The C++ Standard has never required user-defined iterators to derive from std::iterator. - /// A user-defined iterator should provide publicly accessible typedefs named - /// iterator_category, value_type, difference_type, pointer, and reference. - /// Note that value_type is required to be non-const, even for constant iterators. - using iterator_category = std::bidirectional_iterator_tag; - - /// the type of the values when the iterator is dereferenced - using value_type = typename BasicJsonType::value_type; - /// a type to represent differences between iterators - using difference_type = typename BasicJsonType::difference_type; - /// defines a pointer to the type iterated over (value_type) - using pointer = typename std::conditional::value, - typename BasicJsonType::const_pointer, - typename BasicJsonType::pointer>::type; - /// defines a reference to the type iterated over (value_type) - using reference = - typename std::conditional::value, - typename BasicJsonType::const_reference, - typename BasicJsonType::reference>::type; - - /// default constructor - iter_impl() = default; - - /*! - @brief constructor for a given JSON instance - @param[in] object pointer to a JSON object for this iterator - @pre object != nullptr - @post The iterator is initialized; i.e. `m_object != nullptr`. - */ - explicit iter_impl(pointer object) noexcept : m_object(object) - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = typename object_t::iterator(); - break; - } - - case value_t::array: - { - m_it.array_iterator = typename array_t::iterator(); - break; - } - - default: - { - m_it.primitive_iterator = primitive_iterator_t(); - break; - } - } - } - - /*! - @note The conventional copy constructor and copy assignment are implicitly - defined. Combined with the following converting constructor and - assignment, they support: (1) copy from iterator to iterator, (2) - copy from const iterator to const iterator, and (3) conversion from - iterator to const iterator. However conversion from const iterator - to iterator is not defined. - */ - - /*! - @brief converting constructor - @param[in] other non-const iterator to copy from - @note It is not checked whether @a other is initialized. - */ - iter_impl(const iter_impl::type>& other) noexcept - : m_object(other.m_object), m_it(other.m_it) {} - - /*! - @brief converting assignment - @param[in,out] other non-const iterator to copy from - @return const/non-const iterator - @note It is not checked whether @a other is initialized. - */ - iter_impl& operator=(const iter_impl::type>& other) noexcept - { - m_object = other.m_object; - m_it = other.m_it; - return *this; - } - - private: - /*! - @brief set the iterator to the first value - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - void set_begin() noexcept - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = m_object->m_value.object->begin(); - break; - } - - case value_t::array: - { - m_it.array_iterator = m_object->m_value.array->begin(); - break; - } - - case value_t::null: - { - // set to end so begin()==end() is true: null is empty - m_it.primitive_iterator.set_end(); - break; - } - - default: - { - m_it.primitive_iterator.set_begin(); - break; - } - } - } - - /*! - @brief set the iterator past the last value - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - void set_end() noexcept - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = m_object->m_value.object->end(); - break; - } - - case value_t::array: - { - m_it.array_iterator = m_object->m_value.array->end(); - break; - } - - default: - { - m_it.primitive_iterator.set_end(); - break; - } - } - } - - public: - /*! - @brief return a reference to the value pointed to by the iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference operator*() const - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - assert(m_it.object_iterator != m_object->m_value.object->end()); - return m_it.object_iterator->second; - } - - case value_t::array: - { - assert(m_it.array_iterator != m_object->m_value.array->end()); - return *m_it.array_iterator; - } - - case value_t::null: - JSON_THROW(invalid_iterator::create(214, "cannot get value")); - - default: - { - if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) - { - return *m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value")); - } - } - } - - /*! - @brief dereference the iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - pointer operator->() const - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - assert(m_it.object_iterator != m_object->m_value.object->end()); - return &(m_it.object_iterator->second); - } - - case value_t::array: - { - assert(m_it.array_iterator != m_object->m_value.array->end()); - return &*m_it.array_iterator; - } - - default: - { - if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) - { - return m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value")); - } - } - } - - /*! - @brief post-increment (it++) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl const operator++(int) - { - auto result = *this; - ++(*this); - return result; - } - - /*! - @brief pre-increment (++it) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator++() - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - std::advance(m_it.object_iterator, 1); - break; - } - - case value_t::array: - { - std::advance(m_it.array_iterator, 1); - break; - } - - default: - { - ++m_it.primitive_iterator; - break; - } - } - - return *this; - } - - /*! - @brief post-decrement (it--) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl const operator--(int) - { - auto result = *this; - --(*this); - return result; - } - - /*! - @brief pre-decrement (--it) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator--() - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - std::advance(m_it.object_iterator, -1); - break; - } - - case value_t::array: - { - std::advance(m_it.array_iterator, -1); - break; - } - - default: - { - --m_it.primitive_iterator; - break; - } - } - - return *this; - } - - /*! - @brief comparison: equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator==(const iter_impl& other) const - { - // if objects are not the same, the comparison is undefined - if (JSON_UNLIKELY(m_object != other.m_object)) - { - JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); - } - - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - return (m_it.object_iterator == other.m_it.object_iterator); - - case value_t::array: - return (m_it.array_iterator == other.m_it.array_iterator); - - default: - return (m_it.primitive_iterator == other.m_it.primitive_iterator); - } - } - - /*! - @brief comparison: not equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator!=(const iter_impl& other) const - { - return not operator==(other); - } - - /*! - @brief comparison: smaller - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator<(const iter_impl& other) const - { - // if objects are not the same, the comparison is undefined - if (JSON_UNLIKELY(m_object != other.m_object)) - { - JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); - } - - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators")); - - case value_t::array: - return (m_it.array_iterator < other.m_it.array_iterator); - - default: - return (m_it.primitive_iterator < other.m_it.primitive_iterator); - } - } - - /*! - @brief comparison: less than or equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator<=(const iter_impl& other) const - { - return not other.operator < (*this); - } - - /*! - @brief comparison: greater than - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator>(const iter_impl& other) const - { - return not operator<=(other); - } - - /*! - @brief comparison: greater than or equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator>=(const iter_impl& other) const - { - return not operator<(other); - } - - /*! - @brief add to iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator+=(difference_type i) - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); - - case value_t::array: - { - std::advance(m_it.array_iterator, i); - break; - } - - default: - { - m_it.primitive_iterator += i; - break; - } - } - - return *this; - } - - /*! - @brief subtract from iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator-=(difference_type i) - { - return operator+=(-i); - } - - /*! - @brief add to iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl operator+(difference_type i) const - { - auto result = *this; - result += i; - return result; - } - - /*! - @brief addition of distance and iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - friend iter_impl operator+(difference_type i, const iter_impl& it) - { - auto result = it; - result += i; - return result; - } - - /*! - @brief subtract from iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl operator-(difference_type i) const - { - auto result = *this; - result -= i; - return result; - } - - /*! - @brief return difference - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - difference_type operator-(const iter_impl& other) const - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); - - case value_t::array: - return m_it.array_iterator - other.m_it.array_iterator; - - default: - return m_it.primitive_iterator - other.m_it.primitive_iterator; - } - } - - /*! - @brief access to successor - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference operator[](difference_type n) const - { - assert(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators")); - - case value_t::array: - return *std::next(m_it.array_iterator, n); - - case value_t::null: - JSON_THROW(invalid_iterator::create(214, "cannot get value")); - - default: - { - if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n)) - { - return *m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value")); - } - } - } - - /*! - @brief return the key of an object iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - const typename object_t::key_type& key() const - { - assert(m_object != nullptr); - - if (JSON_LIKELY(m_object->is_object())) - { - return m_it.object_iterator->first; - } - - JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators")); - } - - /*! - @brief return the value of an iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference value() const - { - return operator*(); - } - - private: - /// associated JSON instance - pointer m_object = nullptr; - /// the actual iterator of the associated instance - internal_iterator::type> m_it; -}; -} -} diff --git a/include/nlohmann/detail/iterators/iteration_proxy.hpp b/include/nlohmann/detail/iterators/iteration_proxy.hpp deleted file mode 100644 index f5dbb2c..0000000 --- a/include/nlohmann/detail/iterators/iteration_proxy.hpp +++ /dev/null @@ -1,128 +0,0 @@ -#pragma once - -#include // size_t -#include // string, to_string -#include // input_iterator_tag - -#include - -namespace nlohmann -{ -namespace detail -{ -/// proxy class for the items() function -template class iteration_proxy -{ - private: - /// helper class for iteration - class iteration_proxy_internal - { - public: - using difference_type = std::ptrdiff_t; - using value_type = iteration_proxy_internal; - using pointer = iteration_proxy_internal*; - using reference = iteration_proxy_internal&; - using iterator_category = std::input_iterator_tag; - - private: - /// the iterator - IteratorType anchor; - /// an index for arrays (used to create key names) - std::size_t array_index = 0; - /// last stringified array index - mutable std::size_t array_index_last = 0; - /// a string representation of the array index - mutable std::string array_index_str = "0"; - /// an empty string (to return a reference for primitive values) - const std::string empty_str = ""; - - public: - explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {} - - iteration_proxy_internal(const iteration_proxy_internal&) = default; - iteration_proxy_internal& operator=(const iteration_proxy_internal&) = default; - - /// dereference operator (needed for range-based for) - iteration_proxy_internal& operator*() - { - return *this; - } - - /// increment operator (needed for range-based for) - iteration_proxy_internal& operator++() - { - ++anchor; - ++array_index; - - return *this; - } - - /// equality operator (needed for InputIterator) - bool operator==(const iteration_proxy_internal& o) const noexcept - { - return anchor == o.anchor; - } - - /// inequality operator (needed for range-based for) - bool operator!=(const iteration_proxy_internal& o) const noexcept - { - return anchor != o.anchor; - } - - /// return key of the iterator - const std::string& key() const - { - assert(anchor.m_object != nullptr); - - switch (anchor.m_object->type()) - { - // use integer array index as key - case value_t::array: - { - if (array_index != array_index_last) - { - array_index_str = std::to_string(array_index); - array_index_last = array_index; - } - return array_index_str; - } - - // use key from the object - case value_t::object: - return anchor.key(); - - // use an empty key for all primitive types - default: - return empty_str; - } - } - - /// return value of the iterator - typename IteratorType::reference value() const - { - return anchor.value(); - } - }; - - /// the container to iterate - typename IteratorType::reference container; - - public: - /// construct iteration proxy from a container - explicit iteration_proxy(typename IteratorType::reference cont) noexcept - : container(cont) {} - - /// return iterator begin (needed for range-based for) - iteration_proxy_internal begin() noexcept - { - return iteration_proxy_internal(container.begin()); - } - - /// return iterator end (needed for range-based for) - iteration_proxy_internal end() noexcept - { - return iteration_proxy_internal(container.end()); - } -}; -} -} diff --git a/include/nlohmann/detail/iterators/json_reverse_iterator.hpp b/include/nlohmann/detail/iterators/json_reverse_iterator.hpp deleted file mode 100644 index 2750de4..0000000 --- a/include/nlohmann/detail/iterators/json_reverse_iterator.hpp +++ /dev/null @@ -1,119 +0,0 @@ -#pragma once - -#include // ptrdiff_t -#include // reverse_iterator -#include // declval - -namespace nlohmann -{ -namespace detail -{ -////////////////////// -// reverse_iterator // -////////////////////// - -/*! -@brief a template for a reverse iterator class - -@tparam Base the base iterator type to reverse. Valid types are @ref -iterator (to create @ref reverse_iterator) and @ref const_iterator (to -create @ref const_reverse_iterator). - -@requirement The class satisfies the following concept requirements: -- -[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): - The iterator that can be moved can be moved in both directions (i.e. - incremented and decremented). -- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): - It is possible to write to the pointed-to element (only if @a Base is - @ref iterator). - -@since version 1.0.0 -*/ -template -class json_reverse_iterator : public std::reverse_iterator -{ - public: - using difference_type = std::ptrdiff_t; - /// shortcut to the reverse iterator adapter - using base_iterator = std::reverse_iterator; - /// the reference type for the pointed-to element - using reference = typename Base::reference; - - /// create reverse iterator from iterator - explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept - : base_iterator(it) {} - - /// create reverse iterator from base class - explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} - - /// post-increment (it++) - json_reverse_iterator const operator++(int) - { - return static_cast(base_iterator::operator++(1)); - } - - /// pre-increment (++it) - json_reverse_iterator& operator++() - { - return static_cast(base_iterator::operator++()); - } - - /// post-decrement (it--) - json_reverse_iterator const operator--(int) - { - return static_cast(base_iterator::operator--(1)); - } - - /// pre-decrement (--it) - json_reverse_iterator& operator--() - { - return static_cast(base_iterator::operator--()); - } - - /// add to iterator - json_reverse_iterator& operator+=(difference_type i) - { - return static_cast(base_iterator::operator+=(i)); - } - - /// add to iterator - json_reverse_iterator operator+(difference_type i) const - { - return static_cast(base_iterator::operator+(i)); - } - - /// subtract from iterator - json_reverse_iterator operator-(difference_type i) const - { - return static_cast(base_iterator::operator-(i)); - } - - /// return difference - difference_type operator-(const json_reverse_iterator& other) const - { - return base_iterator(*this) - base_iterator(other); - } - - /// access to successor - reference operator[](difference_type n) const - { - return *(this->operator+(n)); - } - - /// return the key of an object iterator - auto key() const -> decltype(std::declval().key()) - { - auto it = --this->base(); - return it.key(); - } - - /// return the value of an iterator - reference value() const - { - auto it = --this->base(); - return it.operator * (); - } -}; -} -} diff --git a/include/nlohmann/detail/iterators/primitive_iterator.hpp b/include/nlohmann/detail/iterators/primitive_iterator.hpp deleted file mode 100644 index db3f897..0000000 --- a/include/nlohmann/detail/iterators/primitive_iterator.hpp +++ /dev/null @@ -1,120 +0,0 @@ -#pragma once - -#include // ptrdiff_t -#include // numeric_limits - -namespace nlohmann -{ -namespace detail -{ -/* -@brief an iterator for primitive JSON types - -This class models an iterator for primitive JSON types (boolean, number, -string). It's only purpose is to allow the iterator/const_iterator classes -to "iterate" over primitive values. Internally, the iterator is modeled by -a `difference_type` variable. Value begin_value (`0`) models the begin, -end_value (`1`) models past the end. -*/ -class primitive_iterator_t -{ - private: - using difference_type = std::ptrdiff_t; - static constexpr difference_type begin_value = 0; - static constexpr difference_type end_value = begin_value + 1; - - /// iterator as signed integer type - difference_type m_it = (std::numeric_limits::min)(); - - public: - constexpr difference_type get_value() const noexcept - { - return m_it; - } - - /// set iterator to a defined beginning - void set_begin() noexcept - { - m_it = begin_value; - } - - /// set iterator to a defined past the end - void set_end() noexcept - { - m_it = end_value; - } - - /// return whether the iterator can be dereferenced - constexpr bool is_begin() const noexcept - { - return m_it == begin_value; - } - - /// return whether the iterator is at end - constexpr bool is_end() const noexcept - { - return m_it == end_value; - } - - friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it == rhs.m_it; - } - - friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it < rhs.m_it; - } - - primitive_iterator_t operator+(difference_type n) noexcept - { - auto result = *this; - result += n; - return result; - } - - friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it - rhs.m_it; - } - - primitive_iterator_t& operator++() noexcept - { - ++m_it; - return *this; - } - - primitive_iterator_t const operator++(int) noexcept - { - auto result = *this; - ++m_it; - return result; - } - - primitive_iterator_t& operator--() noexcept - { - --m_it; - return *this; - } - - primitive_iterator_t const operator--(int) noexcept - { - auto result = *this; - --m_it; - return result; - } - - primitive_iterator_t& operator+=(difference_type n) noexcept - { - m_it += n; - return *this; - } - - primitive_iterator_t& operator-=(difference_type n) noexcept - { - m_it -= n; - return *this; - } -}; -} -} diff --git a/include/nlohmann/detail/json_pointer.hpp b/include/nlohmann/detail/json_pointer.hpp deleted file mode 100644 index fce8001..0000000 --- a/include/nlohmann/detail/json_pointer.hpp +++ /dev/null @@ -1,696 +0,0 @@ -#pragma once - -#include // assert -#include // accumulate -#include // string -#include // vector - -#include -#include -#include - -namespace nlohmann -{ -template -class json_pointer -{ - // allow basic_json to access private members - NLOHMANN_BASIC_JSON_TPL_DECLARATION - friend class basic_json; - - public: - /*! - @brief create JSON pointer - - Create a JSON pointer according to the syntax described in - [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). - - @param[in] s string representing the JSON pointer; if omitted, the empty - string is assumed which references the whole JSON value - - @throw parse_error.107 if the given JSON pointer @a s is nonempty and does - not begin with a slash (`/`); see example below - - @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is - not followed by `0` (representing `~`) or `1` (representing `/`); see - example below - - @liveexample{The example shows the construction several valid JSON pointers - as well as the exceptional behavior.,json_pointer} - - @since version 2.0.0 - */ - explicit json_pointer(const std::string& s = "") - : reference_tokens(split(s)) - {} - - /*! - @brief return a string representation of the JSON pointer - - @invariant For each JSON pointer `ptr`, it holds: - @code {.cpp} - ptr == json_pointer(ptr.to_string()); - @endcode - - @return a string representation of the JSON pointer - - @liveexample{The example shows the result of `to_string`., - json_pointer__to_string} - - @since version 2.0.0 - */ - std::string to_string() const noexcept - { - return std::accumulate(reference_tokens.begin(), reference_tokens.end(), - std::string{}, - [](const std::string & a, const std::string & b) - { - return a + "/" + escape(b); - }); - } - - /// @copydoc to_string() - operator std::string() const - { - return to_string(); - } - - /*! - @param[in] s reference token to be converted into an array index - - @return integer representation of @a s - - @throw out_of_range.404 if string @a s could not be converted to an integer - */ - static int array_index(const std::string& s) - { - std::size_t processed_chars = 0; - const int res = std::stoi(s, &processed_chars); - - // check if the string was completely read - if (JSON_UNLIKELY(processed_chars != s.size())) - { - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'")); - } - - return res; - } - - private: - /*! - @brief remove and return last reference pointer - @throw out_of_range.405 if JSON pointer has no parent - */ - std::string pop_back() - { - if (JSON_UNLIKELY(is_root())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); - } - - auto last = reference_tokens.back(); - reference_tokens.pop_back(); - return last; - } - - /// return whether pointer points to the root document - bool is_root() const - { - return reference_tokens.empty(); - } - - json_pointer top() const - { - if (JSON_UNLIKELY(is_root())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); - } - - json_pointer result = *this; - result.reference_tokens = {reference_tokens[0]}; - return result; - } - - /*! - @brief create and return a reference to the pointed to value - - @complexity Linear in the number of reference tokens. - - @throw parse_error.109 if array index is not a number - @throw type_error.313 if value cannot be unflattened - */ - BasicJsonType& get_and_create(BasicJsonType& j) const - { - using size_type = typename BasicJsonType::size_type; - auto result = &j; - - // in case no reference tokens exist, return a reference to the JSON value - // j which will be overwritten by a primitive value - for (const auto& reference_token : reference_tokens) - { - switch (result->m_type) - { - case detail::value_t::null: - { - if (reference_token == "0") - { - // start a new array if reference token is 0 - result = &result->operator[](0); - } - else - { - // start a new object otherwise - result = &result->operator[](reference_token); - } - break; - } - - case detail::value_t::object: - { - // create an entry in the object - result = &result->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - // create an entry in the array - JSON_TRY - { - result = &result->operator[](static_cast(array_index(reference_token))); - } - JSON_CATCH(std::invalid_argument&) - { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); - } - break; - } - - /* - The following code is only reached if there exists a reference - token _and_ the current value is primitive. In this case, we have - an error situation, because primitive values may only occur as - single value; that is, with an empty list of reference tokens. - */ - default: - JSON_THROW(detail::type_error::create(313, "invalid value to unflatten")); - } - } - - return *result; - } - - /*! - @brief return a reference to the pointed to value - - @note This version does not throw if a value is not present, but tries to - create nested values instead. For instance, calling this function - with pointer `"/this/that"` on a null value is equivalent to calling - `operator[]("this").operator[]("that")` on that value, effectively - changing the null value to an object. - - @param[in] ptr a JSON value - - @return reference to the JSON value pointed to by the JSON pointer - - @complexity Linear in the length of the JSON pointer. - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - BasicJsonType& get_unchecked(BasicJsonType* ptr) const - { - using size_type = typename BasicJsonType::size_type; - for (const auto& reference_token : reference_tokens) - { - // convert null values to arrays or objects before continuing - if (ptr->m_type == detail::value_t::null) - { - // check if reference token is a number - const bool nums = - std::all_of(reference_token.begin(), reference_token.end(), - [](const char x) - { - return (x >= '0' and x <= '9'); - }); - - // change value to array for numbers or "-" or to object otherwise - *ptr = (nums or reference_token == "-") - ? detail::value_t::array - : detail::value_t::object; - } - - switch (ptr->m_type) - { - case detail::value_t::object: - { - // use unchecked object access - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) - { - JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + reference_token + - "' must not begin with '0'")); - } - - if (reference_token == "-") - { - // explicitly treat "-" as index beyond the end - ptr = &ptr->operator[](ptr->m_value.array->size()); - } - else - { - // convert array index to number; unchecked access - JSON_TRY - { - ptr = &ptr->operator[]( - static_cast(array_index(reference_token))); - } - JSON_CATCH(std::invalid_argument&) - { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); - } - } - break; - } - - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - BasicJsonType& get_checked(BasicJsonType* ptr) const - { - using size_type = typename BasicJsonType::size_type; - for (const auto& reference_token : reference_tokens) - { - switch (ptr->m_type) - { - case detail::value_t::object: - { - // note: at performs range check - ptr = &ptr->at(reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + std::to_string(ptr->m_value.array->size()) + - ") is out of range")); - } - - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) - { - JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + reference_token + - "' must not begin with '0'")); - } - - // note: at performs range check - JSON_TRY - { - ptr = &ptr->at(static_cast(array_index(reference_token))); - } - JSON_CATCH(std::invalid_argument&) - { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); - } - break; - } - - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); - } - } - - return *ptr; - } - - /*! - @brief return a const reference to the pointed to value - - @param[in] ptr a JSON value - - @return const reference to the JSON value pointed to by the JSON - pointer - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const - { - using size_type = typename BasicJsonType::size_type; - for (const auto& reference_token : reference_tokens) - { - switch (ptr->m_type) - { - case detail::value_t::object: - { - // use unchecked object access - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_UNLIKELY(reference_token == "-")) - { - // "-" cannot be used for const access - JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + std::to_string(ptr->m_value.array->size()) + - ") is out of range")); - } - - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) - { - JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + reference_token + - "' must not begin with '0'")); - } - - // use unchecked array access - JSON_TRY - { - ptr = &ptr->operator[]( - static_cast(array_index(reference_token))); - } - JSON_CATCH(std::invalid_argument&) - { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); - } - break; - } - - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - const BasicJsonType& get_checked(const BasicJsonType* ptr) const - { - using size_type = typename BasicJsonType::size_type; - for (const auto& reference_token : reference_tokens) - { - switch (ptr->m_type) - { - case detail::value_t::object: - { - // note: at performs range check - ptr = &ptr->at(reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + std::to_string(ptr->m_value.array->size()) + - ") is out of range")); - } - - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) - { - JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + reference_token + - "' must not begin with '0'")); - } - - // note: at performs range check - JSON_TRY - { - ptr = &ptr->at(static_cast(array_index(reference_token))); - } - JSON_CATCH(std::invalid_argument&) - { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); - } - break; - } - - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); - } - } - - return *ptr; - } - - /*! - @brief split the string input to reference tokens - - @note This function is only called by the json_pointer constructor. - All exceptions below are documented there. - - @throw parse_error.107 if the pointer is not empty or begins with '/' - @throw parse_error.108 if character '~' is not followed by '0' or '1' - */ - static std::vector split(const std::string& reference_string) - { - std::vector result; - - // special case: empty reference string -> no reference tokens - if (reference_string.empty()) - { - return result; - } - - // check if nonempty reference string begins with slash - if (JSON_UNLIKELY(reference_string[0] != '/')) - { - JSON_THROW(detail::parse_error::create(107, 1, - "JSON pointer must be empty or begin with '/' - was: '" + - reference_string + "'")); - } - - // extract the reference tokens: - // - slash: position of the last read slash (or end of string) - // - start: position after the previous slash - for ( - // search for the first slash after the first character - std::size_t slash = reference_string.find_first_of('/', 1), - // set the beginning of the first reference token - start = 1; - // we can stop if start == string::npos+1 = 0 - start != 0; - // set the beginning of the next reference token - // (will eventually be 0 if slash == std::string::npos) - start = slash + 1, - // find next slash - slash = reference_string.find_first_of('/', start)) - { - // use the text between the beginning of the reference token - // (start) and the last slash (slash). - auto reference_token = reference_string.substr(start, slash - start); - - // check reference tokens are properly escaped - for (std::size_t pos = reference_token.find_first_of('~'); - pos != std::string::npos; - pos = reference_token.find_first_of('~', pos + 1)) - { - assert(reference_token[pos] == '~'); - - // ~ must be followed by 0 or 1 - if (JSON_UNLIKELY(pos == reference_token.size() - 1 or - (reference_token[pos + 1] != '0' and - reference_token[pos + 1] != '1'))) - { - JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); - } - } - - // finally, store the reference token - unescape(reference_token); - result.push_back(reference_token); - } - - return result; - } - - /*! - @brief replace all occurrences of a substring by another string - - @param[in,out] s the string to manipulate; changed so that all - occurrences of @a f are replaced with @a t - @param[in] f the substring to replace with @a t - @param[in] t the string to replace @a f - - @pre The search string @a f must not be empty. **This precondition is - enforced with an assertion.** - - @since version 2.0.0 - */ - static void replace_substring(std::string& s, const std::string& f, - const std::string& t) - { - assert(not f.empty()); - for (auto pos = s.find(f); // find first occurrence of f - pos != std::string::npos; // make sure f was found - s.replace(pos, f.size(), t), // replace with t, and - pos = s.find(f, pos + t.size())) // find next occurrence of f - {} - } - - /// escape "~"" to "~0" and "/" to "~1" - static std::string escape(std::string s) - { - replace_substring(s, "~", "~0"); - replace_substring(s, "/", "~1"); - return s; - } - - /// unescape "~1" to tilde and "~0" to slash (order is important!) - static void unescape(std::string& s) - { - replace_substring(s, "~1", "/"); - replace_substring(s, "~0", "~"); - } - - /*! - @param[in] reference_string the reference string to the current value - @param[in] value the value to consider - @param[in,out] result the result object to insert values to - - @note Empty objects or arrays are flattened to `null`. - */ - static void flatten(const std::string& reference_string, - const BasicJsonType& value, - BasicJsonType& result) - { - switch (value.m_type) - { - case detail::value_t::array: - { - if (value.m_value.array->empty()) - { - // flatten empty array as null - result[reference_string] = nullptr; - } - else - { - // iterate array and use index as reference string - for (std::size_t i = 0; i < value.m_value.array->size(); ++i) - { - flatten(reference_string + "/" + std::to_string(i), - value.m_value.array->operator[](i), result); - } - } - break; - } - - case detail::value_t::object: - { - if (value.m_value.object->empty()) - { - // flatten empty object as null - result[reference_string] = nullptr; - } - else - { - // iterate object and use keys as reference string - for (const auto& element : *value.m_value.object) - { - flatten(reference_string + "/" + escape(element.first), element.second, result); - } - } - break; - } - - default: - { - // add primitive value with its reference string - result[reference_string] = value; - break; - } - } - } - - /*! - @param[in] value flattened JSON - - @return unflattened JSON - - @throw parse_error.109 if array index is not a number - @throw type_error.314 if value is not an object - @throw type_error.315 if object values are not primitive - @throw type_error.313 if value cannot be unflattened - */ - static BasicJsonType - unflatten(const BasicJsonType& value) - { - if (JSON_UNLIKELY(not value.is_object())) - { - JSON_THROW(detail::type_error::create(314, "only objects can be unflattened")); - } - - BasicJsonType result; - - // iterate the JSON object values - for (const auto& element : *value.m_value.object) - { - if (JSON_UNLIKELY(not element.second.is_primitive())) - { - JSON_THROW(detail::type_error::create(315, "values in object must be primitive")); - } - - // assign value to reference pointed to by JSON pointer; Note that if - // the JSON pointer is "" (i.e., points to the whole value), function - // get_and_create returns a reference to result itself. An assignment - // will then create a primitive value. - json_pointer(element.first).get_and_create(result) = element.second; - } - - return result; - } - - friend bool operator==(json_pointer const& lhs, - json_pointer const& rhs) noexcept - { - return (lhs.reference_tokens == rhs.reference_tokens); - } - - friend bool operator!=(json_pointer const& lhs, - json_pointer const& rhs) noexcept - { - return not (lhs == rhs); - } - - /// the reference tokens - std::vector reference_tokens; -}; -} diff --git a/include/nlohmann/detail/json_ref.hpp b/include/nlohmann/detail/json_ref.hpp deleted file mode 100644 index 8285be2..0000000 --- a/include/nlohmann/detail/json_ref.hpp +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once - -#include -#include - -namespace nlohmann -{ -namespace detail -{ -template -class json_ref -{ - public: - using value_type = BasicJsonType; - - json_ref(value_type&& value) - : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true) - {} - - json_ref(const value_type& value) - : value_ref(const_cast(&value)), is_rvalue(false) - {} - - json_ref(std::initializer_list init) - : owned_value(init), value_ref(&owned_value), is_rvalue(true) - {} - - template - json_ref(Args&& ... args) - : owned_value(std::forward(args)...), value_ref(&owned_value), is_rvalue(true) - {} - - // class should be movable only - json_ref(json_ref&&) = default; - json_ref(const json_ref&) = delete; - json_ref& operator=(const json_ref&) = delete; - - value_type moved_or_copied() const - { - if (is_rvalue) - { - return std::move(*value_ref); - } - return *value_ref; - } - - value_type const& operator*() const - { - return *static_cast(value_ref); - } - - value_type const* operator->() const - { - return static_cast(value_ref); - } - - private: - mutable value_type owned_value = nullptr; - value_type* value_ref = nullptr; - const bool is_rvalue; -}; -} -} diff --git a/include/nlohmann/detail/macro_scope.hpp b/include/nlohmann/detail/macro_scope.hpp deleted file mode 100644 index ae62fbf..0000000 --- a/include/nlohmann/detail/macro_scope.hpp +++ /dev/null @@ -1,117 +0,0 @@ -#pragma once - -// This file contains all internal macro definitions -// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them - -// exclude unsupported compilers -#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) - #if defined(__clang__) - #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 - #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) - #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 - #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #endif -#endif - -// disable float-equal warnings on GCC/clang -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - -// disable documentation warnings on clang -#if defined(__clang__) - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wdocumentation" -#endif - -// allow for portable deprecation warnings -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #define JSON_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) - #define JSON_DEPRECATED __declspec(deprecated) -#else - #define JSON_DEPRECATED -#endif - -// allow to disable exceptions -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) - #define JSON_THROW(exception) throw exception - #define JSON_TRY try - #define JSON_CATCH(exception) catch(exception) -#else - #define JSON_THROW(exception) std::abort() - #define JSON_TRY if(true) - #define JSON_CATCH(exception) if(false) -#endif - -// override exception macros -#if defined(JSON_THROW_USER) - #undef JSON_THROW - #define JSON_THROW JSON_THROW_USER -#endif -#if defined(JSON_TRY_USER) - #undef JSON_TRY - #define JSON_TRY JSON_TRY_USER -#endif -#if defined(JSON_CATCH_USER) - #undef JSON_CATCH - #define JSON_CATCH JSON_CATCH_USER -#endif - -// manual branch prediction -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #define JSON_LIKELY(x) __builtin_expect(!!(x), 1) - #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0) -#else - #define JSON_LIKELY(x) x - #define JSON_UNLIKELY(x) x -#endif - -// C++ language standard detection -#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 -#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) - #define JSON_HAS_CPP_14 -#endif - -// Ugly macros to avoid uglier copy-paste when specializing basic_json. They -// may be removed in the future once the class is split. - -#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ - template class ObjectType, \ - template class ArrayType, \ - class StringType, class BooleanType, class NumberIntegerType, \ - class NumberUnsignedType, class NumberFloatType, \ - template class AllocatorType, \ - template class JSONSerializer> - -#define NLOHMANN_BASIC_JSON_TPL \ - basic_json - -/*! -@brief Helper to determine whether there's a key_type for T. - -This helper is used to tell associative containers apart from other containers -such as sequence containers. For instance, `std::map` passes the test as it -contains a `mapped_type`, whereas `std::vector` fails the test. - -@sa http://stackoverflow.com/a/7728728/266378 -@since version 1.0.0, overworked in version 2.0.6 -*/ -#define NLOHMANN_JSON_HAS_HELPER(type) \ - template struct has_##type { \ - private: \ - template \ - static int detect(U &&); \ - static void detect(...); \ - public: \ - static constexpr bool value = \ - std::is_integral()))>::value; \ - } diff --git a/include/nlohmann/detail/macro_unscope.hpp b/include/nlohmann/detail/macro_unscope.hpp deleted file mode 100644 index 99a0abd..0000000 --- a/include/nlohmann/detail/macro_unscope.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -// restore GCC/clang diagnostic settings -#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) - #pragma GCC diagnostic pop -#endif -#if defined(__clang__) - #pragma GCC diagnostic pop -#endif - -// clean up -#undef JSON_CATCH -#undef JSON_THROW -#undef JSON_TRY -#undef JSON_LIKELY -#undef JSON_UNLIKELY -#undef JSON_DEPRECATED -#undef JSON_HAS_CPP_14 -#undef JSON_HAS_CPP_17 -#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION -#undef NLOHMANN_BASIC_JSON_TPL -#undef NLOHMANN_JSON_HAS_HELPER diff --git a/include/nlohmann/detail/meta.hpp b/include/nlohmann/detail/meta.hpp deleted file mode 100644 index 5020030..0000000 --- a/include/nlohmann/detail/meta.hpp +++ /dev/null @@ -1,278 +0,0 @@ -#pragma once - -#include // not -#include // size_t -#include // numeric_limits -#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type -#include // declval - -#include -#include - -namespace nlohmann -{ -/*! -@brief detail namespace with internal helper functions - -This namespace collects functions that should not be exposed, -implementations of some @ref basic_json methods, and meta-programming helpers. - -@since version 2.1.0 -*/ -namespace detail -{ -///////////// -// helpers // -///////////// - -template struct is_basic_json : std::false_type {}; - -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct is_basic_json : std::true_type {}; - -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; - -template -using uncvref_t = typename std::remove_cv::type>::type; - -// implementation of C++14 index_sequence and affiliates -// source: https://stackoverflow.com/a/32223343 -template -struct index_sequence -{ - using type = index_sequence; - using value_type = std::size_t; - static constexpr std::size_t size() noexcept - { - return sizeof...(Ints); - } -}; - -template -struct merge_and_renumber; - -template -struct merge_and_renumber, index_sequence> - : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; - -template -struct make_index_sequence - : merge_and_renumber < typename make_index_sequence < N / 2 >::type, - typename make_index_sequence < N - N / 2 >::type > {}; - -template<> struct make_index_sequence<0> : index_sequence<> {}; -template<> struct make_index_sequence<1> : index_sequence<0> {}; - -template -using index_sequence_for = make_index_sequence; - -/* -Implementation of two C++17 constructs: conjunction, negation. This is needed -to avoid evaluating all the traits in a condition - -For example: not std::is_same::value and has_value_type::value -will not compile when T = void (on MSVC at least). Whereas -conjunction>, has_value_type>::value will -stop evaluating if negation<...>::value == false - -Please note that those constructs must be used with caution, since symbols can -become very long quickly (which can slow down compilation and cause MSVC -internal compiler errors). Only use it when you have to (see example ahead). -*/ -template struct conjunction : std::true_type {}; -template struct conjunction : B1 {}; -template -struct conjunction : std::conditional, B1>::type {}; - -template struct negation : std::integral_constant {}; - -// dispatch utility (taken from ranges-v3) -template struct priority_tag : priority_tag < N - 1 > {}; -template<> struct priority_tag<0> {}; - -//////////////////////// -// has_/is_ functions // -//////////////////////// - -// source: https://stackoverflow.com/a/37193089/4116453 - -template -struct is_complete_type : std::false_type {}; - -template -struct is_complete_type : std::true_type {}; - -NLOHMANN_JSON_HAS_HELPER(mapped_type); -NLOHMANN_JSON_HAS_HELPER(key_type); -NLOHMANN_JSON_HAS_HELPER(value_type); -NLOHMANN_JSON_HAS_HELPER(iterator); - -template -struct is_compatible_object_type_impl : std::false_type {}; - -template -struct is_compatible_object_type_impl -{ - static constexpr auto value = - std::is_constructible::value and - std::is_constructible::value; -}; - -template -struct is_compatible_string_type_impl : std::false_type {}; - -template -struct is_compatible_string_type_impl -{ - static constexpr auto value = - std::is_same::value and - std::is_constructible::value; -}; - -template -struct is_compatible_object_type -{ - static auto constexpr value = is_compatible_object_type_impl < - conjunction>, - has_mapped_type, - has_key_type>::value, - typename BasicJsonType::object_t, CompatibleObjectType >::value; -}; - -template -struct is_compatible_string_type -{ - static auto constexpr value = is_compatible_string_type_impl < - conjunction>, - has_value_type>::value, - typename BasicJsonType::string_t, CompatibleStringType >::value; -}; - -template -struct is_basic_json_nested_type -{ - static auto constexpr value = std::is_same::value or - std::is_same::value or - std::is_same::value or - std::is_same::value; -}; - -template -struct is_compatible_array_type -{ - static auto constexpr value = - conjunction>, - negation>, - negation>, - negation>, - has_value_type, - has_iterator>::value; -}; - -template -struct is_compatible_integer_type_impl : std::false_type {}; - -template -struct is_compatible_integer_type_impl -{ - // is there an assert somewhere on overflows? - using RealLimits = std::numeric_limits; - using CompatibleLimits = std::numeric_limits; - - static constexpr auto value = - std::is_constructible::value and - CompatibleLimits::is_integer and - RealLimits::is_signed == CompatibleLimits::is_signed; -}; - -template -struct is_compatible_integer_type -{ - static constexpr auto value = - is_compatible_integer_type_impl < - std::is_integral::value and - not std::is_same::value, - RealIntegerType, CompatibleNumberIntegerType > ::value; -}; - -// trait checking if JSONSerializer::from_json(json const&, udt&) exists -template -struct has_from_json -{ - private: - // also check the return type of from_json - template::from_json( - std::declval(), std::declval()))>::value>> - static int detect(U&&); - static void detect(...); - - public: - static constexpr bool value = std::is_integral>()))>::value; -}; - -// This trait checks if JSONSerializer::from_json(json const&) exists -// this overload is used for non-default-constructible user-defined-types -template -struct has_non_default_from_json -{ - private: - template < - typename U, - typename = enable_if_t::from_json(std::declval()))>::value >> - static int detect(U&&); - static void detect(...); - - public: - static constexpr bool value = std::is_integral>()))>::value; -}; - -// This trait checks if BasicJsonType::json_serializer::to_json exists -template -struct has_to_json -{ - private: - template::to_json( - std::declval(), std::declval()))> - static int detect(U&&); - static void detect(...); - - public: - static constexpr bool value = std::is_integral>()))>::value; -}; - -template -struct is_compatible_complete_type -{ - static constexpr bool value = - not std::is_base_of::value and - not is_basic_json::value and - not is_basic_json_nested_type::value and - has_to_json::value; -}; - -template -struct is_compatible_type - : conjunction, - is_compatible_complete_type> -{ -}; - -// taken from ranges-v3 -template -struct static_const -{ - static constexpr T value{}; -}; - -template -constexpr T static_const::value; -} -} diff --git a/include/nlohmann/detail/output/binary_writer.hpp b/include/nlohmann/detail/output/binary_writer.hpp deleted file mode 100644 index 71e5ec8..0000000 --- a/include/nlohmann/detail/output/binary_writer.hpp +++ /dev/null @@ -1,949 +0,0 @@ -#pragma once - -#include // reverse -#include // array -#include // uint8_t, uint16_t, uint32_t, uint64_t -#include // memcpy -#include // numeric_limits - -#include -#include - -namespace nlohmann -{ -namespace detail -{ -/////////////////// -// binary writer // -/////////////////// - -/*! -@brief serialization to CBOR and MessagePack values -*/ -template -class binary_writer -{ - public: - /*! - @brief create a binary writer - - @param[in] adapter output adapter to write to - */ - explicit binary_writer(output_adapter_t adapter) : oa(adapter) - { - assert(oa); - } - - /*! - @brief[in] j JSON value to serialize - */ - void write_cbor(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::null: - { - oa->write_character(static_cast(0xF6)); - break; - } - - case value_t::boolean: - { - oa->write_character(j.m_value.boolean - ? static_cast(0xF5) - : static_cast(0xF4)); - break; - } - - case value_t::number_integer: - { - if (j.m_value.number_integer >= 0) - { - // CBOR does not differentiate between positive signed - // integers and unsigned integers. Therefore, we used the - // code from the value_t::number_unsigned case here. - if (j.m_value.number_integer <= 0x17) - { - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x18)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x19)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x1A)); - write_number(static_cast(j.m_value.number_integer)); - } - else - { - oa->write_character(static_cast(0x1B)); - write_number(static_cast(j.m_value.number_integer)); - } - } - else - { - // The conversions below encode the sign in the first - // byte, and the value is converted to a positive number. - const auto positive_number = -1 - j.m_value.number_integer; - if (j.m_value.number_integer >= -24) - { - write_number(static_cast(0x20 + positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x38)); - write_number(static_cast(positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x39)); - write_number(static_cast(positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x3A)); - write_number(static_cast(positive_number)); - } - else - { - oa->write_character(static_cast(0x3B)); - write_number(static_cast(positive_number)); - } - } - break; - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned <= 0x17) - { - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x18)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x19)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x1A)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else - { - oa->write_character(static_cast(0x1B)); - write_number(static_cast(j.m_value.number_unsigned)); - } - break; - } - - case value_t::number_float: - { - oa->write_character(get_cbor_float_prefix(j.m_value.number_float)); - write_number(j.m_value.number_float); - break; - } - - case value_t::string: - { - // step 1: write control byte and the string length - const auto N = j.m_value.string->size(); - if (N <= 0x17) - { - write_number(static_cast(0x60 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x78)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x79)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x7A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x7B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write the string - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - // step 1: write control byte and the array size - const auto N = j.m_value.array->size(); - if (N <= 0x17) - { - write_number(static_cast(0x80 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x98)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x99)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x9A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0x9B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - for (const auto& el : *j.m_value.array) - { - write_cbor(el); - } - break; - } - - case value_t::object: - { - // step 1: write control byte and the object size - const auto N = j.m_value.object->size(); - if (N <= 0x17) - { - write_number(static_cast(0xA0 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0xB8)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0xB9)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0xBA)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(static_cast(0xBB)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - for (const auto& el : *j.m_value.object) - { - write_cbor(el.first); - write_cbor(el.second); - } - break; - } - - default: - break; - } - } - - /*! - @brief[in] j JSON value to serialize - */ - void write_msgpack(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::null: // nil - { - oa->write_character(static_cast(0xC0)); - break; - } - - case value_t::boolean: // true and false - { - oa->write_character(j.m_value.boolean - ? static_cast(0xC3) - : static_cast(0xC2)); - break; - } - - case value_t::number_integer: - { - if (j.m_value.number_integer >= 0) - { - // MessagePack does not differentiate between positive - // signed integers and unsigned integers. Therefore, we used - // the code from the value_t::number_unsigned case here. - if (j.m_value.number_unsigned < 128) - { - // positive fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 8 - oa->write_character(static_cast(0xCC)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 16 - oa->write_character(static_cast(0xCD)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 32 - oa->write_character(static_cast(0xCE)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 64 - oa->write_character(static_cast(0xCF)); - write_number(static_cast(j.m_value.number_integer)); - } - } - else - { - if (j.m_value.number_integer >= -32) - { - // negative fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() and - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 8 - oa->write_character(static_cast(0xD0)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() and - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 16 - oa->write_character(static_cast(0xD1)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() and - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 32 - oa->write_character(static_cast(0xD2)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() and - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 64 - oa->write_character(static_cast(0xD3)); - write_number(static_cast(j.m_value.number_integer)); - } - } - break; - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned < 128) - { - // positive fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 8 - oa->write_character(static_cast(0xCC)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 16 - oa->write_character(static_cast(0xCD)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 32 - oa->write_character(static_cast(0xCE)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 64 - oa->write_character(static_cast(0xCF)); - write_number(static_cast(j.m_value.number_integer)); - } - break; - } - - case value_t::number_float: - { - oa->write_character(get_msgpack_float_prefix(j.m_value.number_float)); - write_number(j.m_value.number_float); - break; - } - - case value_t::string: - { - // step 1: write control byte and the string length - const auto N = j.m_value.string->size(); - if (N <= 31) - { - // fixstr - write_number(static_cast(0xA0 | N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 8 - oa->write_character(static_cast(0xD9)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 16 - oa->write_character(static_cast(0xDA)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 32 - oa->write_character(static_cast(0xDB)); - write_number(static_cast(N)); - } - - // step 2: write the string - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - // step 1: write control byte and the array size - const auto N = j.m_value.array->size(); - if (N <= 15) - { - // fixarray - write_number(static_cast(0x90 | N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // array 16 - oa->write_character(static_cast(0xDC)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // array 32 - oa->write_character(static_cast(0xDD)); - write_number(static_cast(N)); - } - - // step 2: write each element - for (const auto& el : *j.m_value.array) - { - write_msgpack(el); - } - break; - } - - case value_t::object: - { - // step 1: write control byte and the object size - const auto N = j.m_value.object->size(); - if (N <= 15) - { - // fixmap - write_number(static_cast(0x80 | (N & 0xF))); - } - else if (N <= (std::numeric_limits::max)()) - { - // map 16 - oa->write_character(static_cast(0xDE)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // map 32 - oa->write_character(static_cast(0xDF)); - write_number(static_cast(N)); - } - - // step 2: write each element - for (const auto& el : *j.m_value.object) - { - write_msgpack(el.first); - write_msgpack(el.second); - } - break; - } - - default: - break; - } - } - - /*! - @param[in] j JSON value to serialize - @param[in] use_count whether to use '#' prefixes (optimized format) - @param[in] use_type whether to use '$' prefixes (optimized format) - @param[in] add_prefix whether prefixes need to be used for this value - */ - void write_ubjson(const BasicJsonType& j, const bool use_count, - const bool use_type, const bool add_prefix = true) - { - switch (j.type()) - { - case value_t::null: - { - if (add_prefix) - { - oa->write_character(static_cast('Z')); - } - break; - } - - case value_t::boolean: - { - if (add_prefix) - oa->write_character(j.m_value.boolean - ? static_cast('T') - : static_cast('F')); - break; - } - - case value_t::number_integer: - { - write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); - break; - } - - case value_t::number_unsigned: - { - write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); - break; - } - - case value_t::number_float: - { - write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); - break; - } - - case value_t::string: - { - if (add_prefix) - { - oa->write_character(static_cast('S')); - } - write_number_with_ubjson_prefix(j.m_value.string->size(), true); - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - if (add_prefix) - { - oa->write_character(static_cast('[')); - } - - bool prefix_required = true; - if (use_type and not j.m_value.array->empty()) - { - assert(use_count); - const CharType first_prefix = ubjson_prefix(j.front()); - const bool same_prefix = std::all_of(j.begin() + 1, j.end(), - [this, first_prefix](const BasicJsonType & v) - { - return ubjson_prefix(v) == first_prefix; - }); - - if (same_prefix) - { - prefix_required = false; - oa->write_character(static_cast('$')); - oa->write_character(first_prefix); - } - } - - if (use_count) - { - oa->write_character(static_cast('#')); - write_number_with_ubjson_prefix(j.m_value.array->size(), true); - } - - for (const auto& el : *j.m_value.array) - { - write_ubjson(el, use_count, use_type, prefix_required); - } - - if (not use_count) - { - oa->write_character(static_cast(']')); - } - - break; - } - - case value_t::object: - { - if (add_prefix) - { - oa->write_character(static_cast('{')); - } - - bool prefix_required = true; - if (use_type and not j.m_value.object->empty()) - { - assert(use_count); - const CharType first_prefix = ubjson_prefix(j.front()); - const bool same_prefix = std::all_of(j.begin(), j.end(), - [this, first_prefix](const BasicJsonType & v) - { - return ubjson_prefix(v) == first_prefix; - }); - - if (same_prefix) - { - prefix_required = false; - oa->write_character(static_cast('$')); - oa->write_character(first_prefix); - } - } - - if (use_count) - { - oa->write_character(static_cast('#')); - write_number_with_ubjson_prefix(j.m_value.object->size(), true); - } - - for (const auto& el : *j.m_value.object) - { - write_number_with_ubjson_prefix(el.first.size(), true); - oa->write_characters( - reinterpret_cast(el.first.c_str()), - el.first.size()); - write_ubjson(el.second, use_count, use_type, prefix_required); - } - - if (not use_count) - { - oa->write_character(static_cast('}')); - } - - break; - } - - default: - break; - } - } - - private: - /* - @brief write a number to output input - - @param[in] n number of type @a NumberType - @tparam NumberType the type of the number - - @note This function needs to respect the system's endianess, because bytes - in CBOR, MessagePack, and UBJSON are stored in network order (big - endian) and therefore need reordering on little endian systems. - */ - template - void write_number(const NumberType n) - { - // step 1: write number to array of length NumberType - std::array vec; - std::memcpy(vec.data(), &n, sizeof(NumberType)); - - // step 2: write array to output (with possible reordering) - if (is_little_endian) - { - // reverse byte order prior to conversion if necessary - std::reverse(vec.begin(), vec.end()); - } - - oa->write_characters(vec.data(), sizeof(NumberType)); - } - - // UBJSON: write number (floating point) - template::value, int>::type = 0> - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if (add_prefix) - { - oa->write_character(get_ubjson_float_prefix(n)); - } - write_number(n); - } - - // UBJSON: write number (unsigned integer) - template::value, int>::type = 0> - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(static_cast('i')); // int8 - } - write_number(static_cast(n)); - } - else if (n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(static_cast('U')); // uint8 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(static_cast('I')); // int16 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(static_cast('l')); // int32 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(static_cast('L')); // int64 - } - write_number(static_cast(n)); - } - else - { - JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n))); - } - } - - // UBJSON: write number (signed integer) - template::value and - not std::is_floating_point::value, int>::type = 0> - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if ((std::numeric_limits::min)() <= n and n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(static_cast('i')); // int8 - } - write_number(static_cast(n)); - } - else if (static_cast((std::numeric_limits::min)()) <= n and n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(static_cast('U')); // uint8 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n and n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(static_cast('I')); // int16 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n and n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(static_cast('l')); // int32 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n and n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(static_cast('L')); // int64 - } - write_number(static_cast(n)); - } - // LCOV_EXCL_START - else - { - JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n))); - } - // LCOV_EXCL_STOP - } - - /*! - @brief determine the type prefix of container values - - @note This function does not need to be 100% accurate when it comes to - integer limits. In case a number exceeds the limits of int64_t, - this will be detected by a later call to function - write_number_with_ubjson_prefix. Therefore, we return 'L' for any - value that does not fit the previous limits. - */ - CharType ubjson_prefix(const BasicJsonType& j) const noexcept - { - switch (j.type()) - { - case value_t::null: - return 'Z'; - - case value_t::boolean: - return j.m_value.boolean ? 'T' : 'F'; - - case value_t::number_integer: - { - if ((std::numeric_limits::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'i'; - } - else if ((std::numeric_limits::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'U'; - } - else if ((std::numeric_limits::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'I'; - } - else if ((std::numeric_limits::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'l'; - } - else // no check and assume int64_t (see note above) - { - return 'L'; - } - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - return 'i'; - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - return 'U'; - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - return 'I'; - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - return 'l'; - } - else // no check and assume int64_t (see note above) - { - return 'L'; - } - } - - case value_t::number_float: - return get_ubjson_float_prefix(j.m_value.number_float); - - case value_t::string: - return 'S'; - - case value_t::array: - return '['; - - case value_t::object: - return '{'; - - default: // discarded values - return 'N'; - } - } - - static constexpr CharType get_cbor_float_prefix(float) - { - return static_cast(0xFA); // Single-Precision Float - } - - static constexpr CharType get_cbor_float_prefix(double) - { - return static_cast(0xFB); // Double-Precision Float - } - - static constexpr CharType get_msgpack_float_prefix(float) - { - return static_cast(0xCA); // float 32 - } - - static constexpr CharType get_msgpack_float_prefix(double) - { - return static_cast(0xCB); // float 64 - } - - static constexpr CharType get_ubjson_float_prefix(float) - { - return 'd'; // float 32 - } - - static constexpr CharType get_ubjson_float_prefix(double) - { - return 'D'; // float 64 - } - - private: - /// whether we can assume little endianess - const bool is_little_endian = binary_reader::little_endianess(); - - /// the output - output_adapter_t oa = nullptr; -}; -} -} diff --git a/include/nlohmann/detail/output/output_adapters.hpp b/include/nlohmann/detail/output/output_adapters.hpp deleted file mode 100644 index ff86a6e..0000000 --- a/include/nlohmann/detail/output/output_adapters.hpp +++ /dev/null @@ -1,113 +0,0 @@ -#pragma once - -#include // copy -#include // size_t -#include // streamsize -#include // back_inserter -#include // shared_ptr, make_shared -#include // basic_ostream -#include // basic_string -#include // vector - -namespace nlohmann -{ -namespace detail -{ -/// abstract output adapter interface -template struct output_adapter_protocol -{ - virtual void write_character(CharType c) = 0; - virtual void write_characters(const CharType* s, std::size_t length) = 0; - virtual ~output_adapter_protocol() = default; -}; - -/// a type to simplify interfaces -template -using output_adapter_t = std::shared_ptr>; - -/// output adapter for byte vectors -template -class output_vector_adapter : public output_adapter_protocol -{ - public: - explicit output_vector_adapter(std::vector& vec) : v(vec) {} - - void write_character(CharType c) override - { - v.push_back(c); - } - - void write_characters(const CharType* s, std::size_t length) override - { - std::copy(s, s + length, std::back_inserter(v)); - } - - private: - std::vector& v; -}; - -/// output adapter for output streams -template -class output_stream_adapter : public output_adapter_protocol -{ - public: - explicit output_stream_adapter(std::basic_ostream& s) : stream(s) {} - - void write_character(CharType c) override - { - stream.put(c); - } - - void write_characters(const CharType* s, std::size_t length) override - { - stream.write(s, static_cast(length)); - } - - private: - std::basic_ostream& stream; -}; - -/// output adapter for basic_string -template> -class output_string_adapter : public output_adapter_protocol -{ - public: - explicit output_string_adapter(StringType& s) : str(s) {} - - void write_character(CharType c) override - { - str.push_back(c); - } - - void write_characters(const CharType* s, std::size_t length) override - { - str.append(s, length); - } - - private: - StringType& str; -}; - -template> -class output_adapter -{ - public: - output_adapter(std::vector& vec) - : oa(std::make_shared>(vec)) {} - - output_adapter(std::basic_ostream& s) - : oa(std::make_shared>(s)) {} - - output_adapter(StringType& s) - : oa(std::make_shared>(s)) {} - - operator output_adapter_t() - { - return oa; - } - - private: - output_adapter_t oa = nullptr; -}; -} -} diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp deleted file mode 100644 index c0f8177..0000000 --- a/include/nlohmann/detail/output/serializer.hpp +++ /dev/null @@ -1,631 +0,0 @@ -#pragma once - -#include // reverse, remove, fill, find, none_of -#include // array -#include // assert -#include // and, or -#include // localeconv, lconv -#include // labs, isfinite, isnan, signbit -#include // size_t, ptrdiff_t -#include // uint8_t -#include // snprintf -#include // numeric_limits -#include // string -#include // is_same - -#include -#include -#include -#include -#include -#include - -namespace nlohmann -{ -namespace detail -{ -/////////////////// -// serialization // -/////////////////// - -template -class serializer -{ - using string_t = typename BasicJsonType::string_t; - using number_float_t = typename BasicJsonType::number_float_t; - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - static constexpr uint8_t UTF8_ACCEPT = 0; - static constexpr uint8_t UTF8_REJECT = 1; - - public: - /*! - @param[in] s output stream to serialize to - @param[in] ichar indentation character to use - */ - serializer(output_adapter_t s, const char ichar) - : o(std::move(s)), loc(std::localeconv()), - thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)), - decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)), - indent_char(ichar), indent_string(512, indent_char) - {} - - // delete because of pointer members - serializer(const serializer&) = delete; - serializer& operator=(const serializer&) = delete; - - /*! - @brief internal implementation of the serialization function - - This function is called by the public member function dump and organizes - the serialization internally. The indentation level is propagated as - additional parameter. In case of arrays and objects, the function is - called recursively. - - - strings and object keys are escaped using `escape_string()` - - integer numbers are converted implicitly via `operator<<` - - floating-point numbers are converted to a string using `"%g"` format - - @param[in] val value to serialize - @param[in] pretty_print whether the output shall be pretty-printed - @param[in] indent_step the indent level - @param[in] current_indent the current indent level (only used internally) - */ - void dump(const BasicJsonType& val, const bool pretty_print, - const bool ensure_ascii, - const unsigned int indent_step, - const unsigned int current_indent = 0) - { - switch (val.m_type) - { - case value_t::object: - { - if (val.m_value.object->empty()) - { - o->write_characters("{}", 2); - return; - } - - if (pretty_print) - { - o->write_characters("{\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - // first n-1 elements - auto i = val.m_value.object->cbegin(); - for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) - { - o->write_characters(indent_string.c_str(), new_indent); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\": ", 3); - dump(i->second, true, ensure_ascii, indent_step, new_indent); - o->write_characters(",\n", 2); - } - - // last element - assert(i != val.m_value.object->cend()); - assert(std::next(i) == val.m_value.object->cend()); - o->write_characters(indent_string.c_str(), new_indent); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\": ", 3); - dump(i->second, true, ensure_ascii, indent_step, new_indent); - - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character('}'); - } - else - { - o->write_character('{'); - - // first n-1 elements - auto i = val.m_value.object->cbegin(); - for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) - { - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\":", 2); - dump(i->second, false, ensure_ascii, indent_step, current_indent); - o->write_character(','); - } - - // last element - assert(i != val.m_value.object->cend()); - assert(std::next(i) == val.m_value.object->cend()); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\":", 2); - dump(i->second, false, ensure_ascii, indent_step, current_indent); - - o->write_character('}'); - } - - return; - } - - case value_t::array: - { - if (val.m_value.array->empty()) - { - o->write_characters("[]", 2); - return; - } - - if (pretty_print) - { - o->write_characters("[\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - // first n-1 elements - for (auto i = val.m_value.array->cbegin(); - i != val.m_value.array->cend() - 1; ++i) - { - o->write_characters(indent_string.c_str(), new_indent); - dump(*i, true, ensure_ascii, indent_step, new_indent); - o->write_characters(",\n", 2); - } - - // last element - assert(not val.m_value.array->empty()); - o->write_characters(indent_string.c_str(), new_indent); - dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); - - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character(']'); - } - else - { - o->write_character('['); - - // first n-1 elements - for (auto i = val.m_value.array->cbegin(); - i != val.m_value.array->cend() - 1; ++i) - { - dump(*i, false, ensure_ascii, indent_step, current_indent); - o->write_character(','); - } - - // last element - assert(not val.m_value.array->empty()); - dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); - - o->write_character(']'); - } - - return; - } - - case value_t::string: - { - o->write_character('\"'); - dump_escaped(*val.m_value.string, ensure_ascii); - o->write_character('\"'); - return; - } - - case value_t::boolean: - { - if (val.m_value.boolean) - { - o->write_characters("true", 4); - } - else - { - o->write_characters("false", 5); - } - return; - } - - case value_t::number_integer: - { - dump_integer(val.m_value.number_integer); - return; - } - - case value_t::number_unsigned: - { - dump_integer(val.m_value.number_unsigned); - return; - } - - case value_t::number_float: - { - dump_float(val.m_value.number_float); - return; - } - - case value_t::discarded: - { - o->write_characters("", 11); - return; - } - - case value_t::null: - { - o->write_characters("null", 4); - return; - } - } - } - - private: - /*! - @brief dump escaped string - - Escape a string by replacing certain special characters by a sequence of an - escape character (backslash) and another character and other control - characters by a sequence of "\u" followed by a four-digit hex - representation. The escaped string is written to output stream @a o. - - @param[in] s the string to escape - @param[in] ensure_ascii whether to escape non-ASCII characters with - \uXXXX sequences - - @complexity Linear in the length of string @a s. - */ - void dump_escaped(const string_t& s, const bool ensure_ascii) - { - uint32_t codepoint; - uint8_t state = UTF8_ACCEPT; - std::size_t bytes = 0; // number of bytes written to string_buffer - - for (std::size_t i = 0; i < s.size(); ++i) - { - const auto byte = static_cast(s[i]); - - switch (decode(state, codepoint, byte)) - { - case UTF8_ACCEPT: // decode found a new code point - { - switch (codepoint) - { - case 0x08: // backspace - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'b'; - break; - } - - case 0x09: // horizontal tab - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 't'; - break; - } - - case 0x0A: // newline - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'n'; - break; - } - - case 0x0C: // formfeed - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'f'; - break; - } - - case 0x0D: // carriage return - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'r'; - break; - } - - case 0x22: // quotation mark - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = '\"'; - break; - } - - case 0x5C: // reverse solidus - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = '\\'; - break; - } - - default: - { - // escape control characters (0x00..0x1F) or, if - // ensure_ascii parameter is used, non-ASCII characters - if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F))) - { - if (codepoint <= 0xFFFF) - { - std::snprintf(string_buffer.data() + bytes, 7, "\\u%04x", - static_cast(codepoint)); - bytes += 6; - } - else - { - std::snprintf(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", - static_cast(0xD7C0 + (codepoint >> 10)), - static_cast(0xDC00 + (codepoint & 0x3FF))); - bytes += 12; - } - } - else - { - // copy byte to buffer (all previous bytes - // been copied have in default case above) - string_buffer[bytes++] = s[i]; - } - break; - } - } - - // write buffer and reset index; there must be 13 bytes - // left, as this is the maximal number of bytes to be - // written ("\uxxxx\uxxxx\0") for one code point - if (string_buffer.size() - bytes < 13) - { - o->write_characters(string_buffer.data(), bytes); - bytes = 0; - } - break; - } - - case UTF8_REJECT: // decode found invalid UTF-8 byte - { - std::string sn(3, '\0'); - snprintf(&sn[0], sn.size(), "%.2X", byte); - JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn)); - } - - default: // decode found yet incomplete multi-byte code point - { - if (not ensure_ascii) - { - // code point will not be escaped - copy byte to buffer - string_buffer[bytes++] = s[i]; - } - break; - } - } - } - - if (JSON_LIKELY(state == UTF8_ACCEPT)) - { - // write buffer - if (bytes > 0) - { - o->write_characters(string_buffer.data(), bytes); - } - } - else - { - // we finish reading, but do not accept: string was incomplete - std::string sn(3, '\0'); - snprintf(&sn[0], sn.size(), "%.2X", static_cast(s.back())); - JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn)); - } - } - - /*! - @brief dump an integer - - Dump a given integer to output stream @a o. Works internally with - @a number_buffer. - - @param[in] x integer number (signed or unsigned) to dump - @tparam NumberType either @a number_integer_t or @a number_unsigned_t - */ - template::value or - std::is_same::value, - int> = 0> - void dump_integer(NumberType x) - { - // special case for "0" - if (x == 0) - { - o->write_character('0'); - return; - } - - const bool is_negative = (x <= 0) and (x != 0); // see issue #755 - std::size_t i = 0; - - while (x != 0) - { - // spare 1 byte for '\0' - assert(i < number_buffer.size() - 1); - - const auto digit = std::labs(static_cast(x % 10)); - number_buffer[i++] = static_cast('0' + digit); - x /= 10; - } - - if (is_negative) - { - // make sure there is capacity for the '-' - assert(i < number_buffer.size() - 2); - number_buffer[i++] = '-'; - } - - std::reverse(number_buffer.begin(), number_buffer.begin() + i); - o->write_characters(number_buffer.data(), i); - } - - /*! - @brief dump a floating-point number - - Dump a given floating-point number to output stream @a o. Works internally - with @a number_buffer. - - @param[in] x floating-point number to dump - */ - void dump_float(number_float_t x) - { - // NaN / inf - if (not std::isfinite(x)) - { - o->write_characters("null", 4); - return; - } - - // If number_float_t is an IEEE-754 single or double precision number, - // use the Grisu2 algorithm to produce short numbers which are - // guaranteed to round-trip, using strtof and strtod, resp. - // - // NB: The test below works if == . - static constexpr bool is_ieee_single_or_double - = (std::numeric_limits::is_iec559 and std::numeric_limits::digits == 24 and std::numeric_limits::max_exponent == 128) or - (std::numeric_limits::is_iec559 and std::numeric_limits::digits == 53 and std::numeric_limits::max_exponent == 1024); - - dump_float(x, std::integral_constant()); - } - - void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) - { - char* begin = number_buffer.data(); - char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); - - o->write_characters(begin, static_cast(end - begin)); - } - - void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) - { - // get number of digits for a float -> text -> float round-trip - static constexpr auto d = std::numeric_limits::max_digits10; - - // the actual conversion - std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x); - - // negative value indicates an error - assert(len > 0); - // check if buffer was large enough - assert(static_cast(len) < number_buffer.size()); - - // erase thousands separator - if (thousands_sep != '\0') - { - const auto end = std::remove(number_buffer.begin(), - number_buffer.begin() + len, thousands_sep); - std::fill(end, number_buffer.end(), '\0'); - assert((end - number_buffer.begin()) <= len); - len = (end - number_buffer.begin()); - } - - // convert decimal point to '.' - if (decimal_point != '\0' and decimal_point != '.') - { - const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); - if (dec_pos != number_buffer.end()) - { - *dec_pos = '.'; - } - } - - o->write_characters(number_buffer.data(), static_cast(len)); - - // determine if need to append ".0" - const bool value_is_int_like = - std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, - [](char c) - { - return (c == '.' or c == 'e'); - }); - - if (value_is_int_like) - { - o->write_characters(".0", 2); - } - } - - /*! - @brief check whether a string is UTF-8 encoded - - The function checks each byte of a string whether it is UTF-8 encoded. The - result of the check is stored in the @a state parameter. The function must - be called initially with state 0 (accept). State 1 means the string must - be rejected, because the current byte is not allowed. If the string is - completely processed, but the state is non-zero, the string ended - prematurely; that is, the last byte indicated more bytes should have - followed. - - @param[in,out] state the state of the decoding - @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) - @param[in] byte next byte to decode - @return new state - - @note The function has been edited: a std::array is used. - - @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann - @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ - */ - static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept - { - static const std::array utf8d = - { - { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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 1, 1, 1, 1, 1, 1, // s5..s6 - 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 - } - }; - - const uint8_t type = utf8d[byte]; - - codep = (state != UTF8_ACCEPT) - ? (byte & 0x3fu) | (codep << 6) - : static_cast(0xff >> type) & (byte); - - state = utf8d[256u + state * 16u + type]; - return state; - } - - private: - /// the output of the serializer - output_adapter_t o = nullptr; - - /// a (hopefully) large enough character buffer - std::array number_buffer{{}}; - - /// the locale - const std::lconv* loc = nullptr; - /// the locale's thousand separator character - const char thousands_sep = '\0'; - /// the locale's decimal point character - const char decimal_point = '\0'; - - /// string buffer - std::array string_buffer{{}}; - - /// the indentation character - const char indent_char; - /// the indentation string - string_t indent_string; -}; -} -} diff --git a/include/nlohmann/detail/value_t.hpp b/include/nlohmann/detail/value_t.hpp deleted file mode 100644 index 326367c..0000000 --- a/include/nlohmann/detail/value_t.hpp +++ /dev/null @@ -1,76 +0,0 @@ -#pragma once - -#include // array -#include // and -#include // size_t -#include // uint8_t - -namespace nlohmann -{ -namespace detail -{ -/////////////////////////// -// JSON type enumeration // -/////////////////////////// - -/*! -@brief the JSON type enumeration - -This enumeration collects the different JSON types. It is internally used to -distinguish the stored values, and the functions @ref basic_json::is_null(), -@ref basic_json::is_object(), @ref basic_json::is_array(), -@ref basic_json::is_string(), @ref basic_json::is_boolean(), -@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), -@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), -@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and -@ref basic_json::is_structured() rely on it. - -@note There are three enumeration entries (number_integer, number_unsigned, and -number_float), because the library distinguishes these three types for numbers: -@ref basic_json::number_unsigned_t is used for unsigned integers, -@ref basic_json::number_integer_t is used for signed integers, and -@ref basic_json::number_float_t is used for floating-point numbers or to -approximate integers which do not fit in the limits of their respective type. - -@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON -value with the default value for a given type - -@since version 1.0.0 -*/ -enum class value_t : std::uint8_t -{ - null, ///< null value - object, ///< object (unordered set of name/value pairs) - array, ///< array (ordered collection of values) - string, ///< string value - boolean, ///< boolean value - number_integer, ///< number value (signed integer) - number_unsigned, ///< number value (unsigned integer) - number_float, ///< number value (floating-point) - discarded ///< discarded by the the parser callback function -}; - -/*! -@brief comparison operator for JSON types - -Returns an ordering that is similar to Python: -- order: null < boolean < number < object < array < string -- furthermore, each type is not smaller than itself -- discarded values are not comparable - -@since version 1.0.0 -*/ -inline bool operator<(const value_t lhs, const value_t rhs) noexcept -{ - static constexpr std::array order = {{ - 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, - 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */ - } - }; - - const auto l_index = static_cast(lhs); - const auto r_index = static_cast(rhs); - return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index]; -} -} -} diff --git a/include/nlohmann/json.hpp b/include/nlohmann/json.hpp deleted file mode 100644 index 58b1998..0000000 --- a/include/nlohmann/json.hpp +++ /dev/null @@ -1,7723 +0,0 @@ -/* - __ _____ _____ _____ - __| | __| | | | JSON for Modern C++ -| | |__ | | | | | | version 3.1.2 -|_____|_____|_____|_|___| https://github.com/nlohmann/json - -Licensed under the MIT License . -SPDX-License-Identifier: MIT -Copyright (c) 2013-2018 Niels Lohmann . - -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. -*/ - -#ifndef NLOHMANN_JSON_HPP -#define NLOHMANN_JSON_HPP - -#define NLOHMANN_JSON_VERSION_MAJOR 3 -#define NLOHMANN_JSON_VERSION_MINOR 1 -#define NLOHMANN_JSON_VERSION_PATCH 2 - -#include // all_of, find, for_each -#include // assert -#include // and, not, or -#include // nullptr_t, ptrdiff_t, size_t -#include // hash, less -#include // initializer_list -#include // istream, ostream -#include // iterator_traits, random_access_iterator_tag -#include // accumulate -#include // string, stoi, to_string -#include // declval, forward, move, pair, swap - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ - -/*! -@brief a class to store JSON values - -@tparam ObjectType type for JSON objects (`std::map` by default; will be used -in @ref object_t) -@tparam ArrayType type for JSON arrays (`std::vector` by default; will be used -in @ref array_t) -@tparam StringType type for JSON strings and object keys (`std::string` by -default; will be used in @ref string_t) -@tparam BooleanType type for JSON booleans (`bool` by default; will be used -in @ref boolean_t) -@tparam NumberIntegerType type for JSON integer numbers (`int64_t` by -default; will be used in @ref number_integer_t) -@tparam NumberUnsignedType type for JSON unsigned integer numbers (@c -`uint64_t` by default; will be used in @ref number_unsigned_t) -@tparam NumberFloatType type for JSON floating-point numbers (`double` by -default; will be used in @ref number_float_t) -@tparam AllocatorType type of the allocator to use (`std::allocator` by -default) -@tparam JSONSerializer the serializer to resolve internal calls to `to_json()` -and `from_json()` (@ref adl_serializer by default) - -@requirement The class satisfies the following concept requirements: -- Basic - - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): - JSON values can be default constructed. The result will be a JSON null - value. - - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): - A JSON value can be constructed from an rvalue argument. - - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): - A JSON value can be copy-constructed from an lvalue expression. - - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): - A JSON value van be assigned from an rvalue argument. - - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): - A JSON value can be copy-assigned from an lvalue expression. - - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): - JSON values can be destructed. -- Layout - - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): - JSON values have - [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): - All non-static data members are private and standard layout types, the - class has no virtual functions or (virtual) base classes. -- Library-wide - - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): - JSON values can be compared with `==`, see @ref - operator==(const_reference,const_reference). - - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): - JSON values can be compared with `<`, see @ref - operator<(const_reference,const_reference). - - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): - Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of - other compatible types, using unqualified function call @ref swap(). - - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): - JSON values can be compared against `std::nullptr_t` objects which are used - to model the `null` value. -- Container - - [Container](https://en.cppreference.com/w/cpp/named_req/Container): - JSON values can be used like STL containers and provide iterator access. - - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer); - JSON values can be used like STL containers and provide reverse iterator - access. - -@invariant The member variables @a m_value and @a m_type have the following -relationship: -- If `m_type == value_t::object`, then `m_value.object != nullptr`. -- If `m_type == value_t::array`, then `m_value.array != nullptr`. -- If `m_type == value_t::string`, then `m_value.string != nullptr`. -The invariants are checked by member function assert_invariant(). - -@internal -@note ObjectType trick from http://stackoverflow.com/a/9860911 -@endinternal - -@see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange -Format](http://rfc7159.net/rfc7159) - -@since version 1.0.0 - -@nosubgrouping -*/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -class basic_json -{ - private: - template friend struct detail::external_constructor; - friend ::nlohmann::json_pointer; - friend ::nlohmann::detail::parser; - friend ::nlohmann::detail::serializer; - template - friend class ::nlohmann::detail::iter_impl; - template - friend class ::nlohmann::detail::binary_writer; - template - friend class ::nlohmann::detail::binary_reader; - template - friend class ::nlohmann::detail::json_sax_dom_parser; - template - friend class ::nlohmann::detail::json_sax_dom_callback_parser; - - /// workaround type for MSVC - using basic_json_t = NLOHMANN_BASIC_JSON_TPL; - - // convenience aliases for types residing in namespace detail; - using lexer = ::nlohmann::detail::lexer; - using parser = ::nlohmann::detail::parser; - - using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; - template - using internal_iterator = ::nlohmann::detail::internal_iterator; - template - using iter_impl = ::nlohmann::detail::iter_impl; - template - using iteration_proxy = ::nlohmann::detail::iteration_proxy; - template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; - - template - using output_adapter_t = ::nlohmann::detail::output_adapter_t; - - using binary_reader = ::nlohmann::detail::binary_reader; - template using binary_writer = ::nlohmann::detail::binary_writer; - - using serializer = ::nlohmann::detail::serializer; - - public: - using value_t = detail::value_t; - /// @copydoc nlohmann::json_pointer - using json_pointer = ::nlohmann::json_pointer; - template - using json_serializer = JSONSerializer; - /// helper type for initializer lists of basic_json values - using initializer_list_t = std::initializer_list>; - - using input_format_t = detail::input_format_t; - - //////////////// - // exceptions // - //////////////// - - /// @name exceptions - /// Classes to implement user-defined exceptions. - /// @{ - - /// @copydoc detail::exception - using exception = detail::exception; - /// @copydoc detail::parse_error - using parse_error = detail::parse_error; - /// @copydoc detail::invalid_iterator - using invalid_iterator = detail::invalid_iterator; - /// @copydoc detail::type_error - using type_error = detail::type_error; - /// @copydoc detail::out_of_range - using out_of_range = detail::out_of_range; - /// @copydoc detail::other_error - using other_error = detail::other_error; - - /// @} - - - ///////////////////// - // container types // - ///////////////////// - - /// @name container types - /// The canonic container types to use @ref basic_json like any other STL - /// container. - /// @{ - - /// the type of elements in a basic_json container - using value_type = basic_json; - - /// the type of an element reference - using reference = value_type&; - /// the type of an element const reference - using const_reference = const value_type&; - - /// a type to represent differences between iterators - using difference_type = std::ptrdiff_t; - /// a type to represent container sizes - using size_type = std::size_t; - - /// the allocator type - using allocator_type = AllocatorType; - - /// the type of an element pointer - using pointer = typename std::allocator_traits::pointer; - /// the type of an element const pointer - using const_pointer = typename std::allocator_traits::const_pointer; - - /// an iterator for a basic_json container - using iterator = iter_impl; - /// a const iterator for a basic_json container - using const_iterator = iter_impl; - /// a reverse iterator for a basic_json container - using reverse_iterator = json_reverse_iterator; - /// a const reverse iterator for a basic_json container - using const_reverse_iterator = json_reverse_iterator; - - /// @} - - - /*! - @brief returns the allocator associated with the container - */ - static allocator_type get_allocator() - { - return allocator_type(); - } - - /*! - @brief returns version information on the library - - This function returns a JSON object with information about the library, - including the version number and information on the platform and compiler. - - @return JSON object holding version information - key | description - ----------- | --------------- - `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). - `copyright` | The copyright line for the library as string. - `name` | The name of the library as string. - `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. - `url` | The URL of the project as string. - `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). - - @liveexample{The following code shows an example output of the `meta()` - function.,meta} - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @complexity Constant. - - @since 2.1.0 - */ - static basic_json meta() - { - basic_json result; - - result["copyright"] = "(C) 2013-2017 Niels Lohmann"; - result["name"] = "JSON for Modern C++"; - result["url"] = "https://github.com/nlohmann/json"; - result["version"]["string"] = - std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + - std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + - std::to_string(NLOHMANN_JSON_VERSION_PATCH); - result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; - result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; - result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; - -#ifdef _WIN32 - result["platform"] = "win32"; -#elif defined __linux__ - result["platform"] = "linux"; -#elif defined __APPLE__ - result["platform"] = "apple"; -#elif defined __unix__ - result["platform"] = "unix"; -#else - result["platform"] = "unknown"; -#endif - -#if defined(__ICC) || defined(__INTEL_COMPILER) - result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; -#elif defined(__clang__) - result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; -#elif defined(__GNUC__) || defined(__GNUG__) - result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; -#elif defined(__HP_cc) || defined(__HP_aCC) - result["compiler"] = "hp" -#elif defined(__IBMCPP__) - result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; -#elif defined(_MSC_VER) - result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; -#elif defined(__PGI) - result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; -#elif defined(__SUNPRO_CC) - result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; -#else - result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; -#endif - -#ifdef __cplusplus - result["compiler"]["c++"] = std::to_string(__cplusplus); -#else - result["compiler"]["c++"] = "unknown"; -#endif - return result; - } - - - /////////////////////////// - // JSON value data types // - /////////////////////////// - - /// @name JSON value data types - /// The data types to store a JSON value. These types are derived from - /// the template arguments passed to class @ref basic_json. - /// @{ - -#if defined(JSON_HAS_CPP_14) - // Use transparent comparator if possible, combined with perfect forwarding - // on find() and count() calls prevents unnecessary string construction. - using object_comparator_t = std::less<>; -#else - using object_comparator_t = std::less; -#endif - - /*! - @brief a type for an object - - [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: - > An object is an unordered collection of zero or more name/value pairs, - > where a name is a string and a value is a string, number, boolean, null, - > object, or array. - - To store objects in C++, a type is defined by the template parameters - described below. - - @tparam ObjectType the container to store objects (e.g., `std::map` or - `std::unordered_map`) - @tparam StringType the type of the keys or names (e.g., `std::string`). - The comparison function `std::less` is used to order elements - inside the container. - @tparam AllocatorType the allocator to use for objects (e.g., - `std::allocator`) - - #### Default type - - With the default values for @a ObjectType (`std::map`), @a StringType - (`std::string`), and @a AllocatorType (`std::allocator`), the default - value for @a object_t is: - - @code {.cpp} - std::map< - std::string, // key_type - basic_json, // value_type - std::less, // key_compare - std::allocator> // allocator_type - > - @endcode - - #### Behavior - - The choice of @a object_t influences the behavior of the JSON class. With - the default type, objects have the following behavior: - - - When all names are unique, objects will be interoperable in the sense - that all software implementations receiving that object will agree on - the name-value mappings. - - When the names within an object are not unique, it is unspecified which - one of the values for a given key will be chosen. For instance, - `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or - `{"key": 2}`. - - Internally, name/value pairs are stored in lexicographical order of the - names. Objects will also be serialized (see @ref dump) in this order. - For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored - and serialized as `{"a": 2, "b": 1}`. - - When comparing objects, the order of the name/value pairs is irrelevant. - This makes objects interoperable in the sense that they will not be - affected by these differences. For instance, `{"b": 1, "a": 2}` and - `{"a": 2, "b": 1}` will be treated as equal. - - #### Limits - - [RFC 7159](http://rfc7159.net/rfc7159) specifies: - > An implementation may set limits on the maximum depth of nesting. - - In this class, the object's limit of nesting is not explicitly constrained. - However, a maximum depth of nesting may be introduced by the compiler or - runtime environment. A theoretical limit can be queried by calling the - @ref max_size function of a JSON object. - - #### Storage - - Objects are stored as pointers in a @ref basic_json type. That is, for any - access to object values, a pointer of type `object_t*` must be - dereferenced. - - @sa @ref array_t -- type for an array value - - @since version 1.0.0 - - @note The order name/value pairs are added to the object is *not* - preserved by the library. Therefore, iterating an object may return - name/value pairs in a different order than they were originally stored. In - fact, keys will be traversed in alphabetical order as `std::map` with - `std::less` is used by default. Please note this behavior conforms to [RFC - 7159](http://rfc7159.net/rfc7159), because any order implements the - specified "unordered" nature of JSON objects. - */ - using object_t = ObjectType>>; - - /*! - @brief a type for an array - - [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: - > An array is an ordered sequence of zero or more values. - - To store objects in C++, a type is defined by the template parameters - explained below. - - @tparam ArrayType container type to store arrays (e.g., `std::vector` or - `std::list`) - @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) - - #### Default type - - With the default values for @a ArrayType (`std::vector`) and @a - AllocatorType (`std::allocator`), the default value for @a array_t is: - - @code {.cpp} - std::vector< - basic_json, // value_type - std::allocator // allocator_type - > - @endcode - - #### Limits - - [RFC 7159](http://rfc7159.net/rfc7159) specifies: - > An implementation may set limits on the maximum depth of nesting. - - In this class, the array's limit of nesting is not explicitly constrained. - However, a maximum depth of nesting may be introduced by the compiler or - runtime environment. A theoretical limit can be queried by calling the - @ref max_size function of a JSON array. - - #### Storage - - Arrays are stored as pointers in a @ref basic_json type. That is, for any - access to array values, a pointer of type `array_t*` must be dereferenced. - - @sa @ref object_t -- type for an object value - - @since version 1.0.0 - */ - using array_t = ArrayType>; - - /*! - @brief a type for a string - - [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: - > A string is a sequence of zero or more Unicode characters. - - To store objects in C++, a type is defined by the template parameter - described below. Unicode values are split by the JSON class into - byte-sized characters during deserialization. - - @tparam StringType the container to store strings (e.g., `std::string`). - Note this container is used for keys/names in objects, see @ref object_t. - - #### Default type - - With the default values for @a StringType (`std::string`), the default - value for @a string_t is: - - @code {.cpp} - std::string - @endcode - - #### Encoding - - Strings are stored in UTF-8 encoding. Therefore, functions like - `std::string::size()` or `std::string::length()` return the number of - bytes in the string rather than the number of characters or glyphs. - - #### String comparison - - [RFC 7159](http://rfc7159.net/rfc7159) states: - > Software implementations are typically required to test names of object - > members for equality. Implementations that transform the textual - > representation into sequences of Unicode code units and then perform the - > comparison numerically, code unit by code unit, are interoperable in the - > sense that implementations will agree in all cases on equality or - > inequality of two strings. For example, implementations that compare - > strings with escaped characters unconverted may incorrectly find that - > `"a\\b"` and `"a\u005Cb"` are not equal. - - This implementation is interoperable as it does compare strings code unit - by code unit. - - #### Storage - - String values are stored as pointers in a @ref basic_json type. That is, - for any access to string values, a pointer of type `string_t*` must be - dereferenced. - - @since version 1.0.0 - */ - using string_t = StringType; - - /*! - @brief a type for a boolean - - [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a - type which differentiates the two literals `true` and `false`. - - To store objects in C++, a type is defined by the template parameter @a - BooleanType which chooses the type to use. - - #### Default type - - With the default values for @a BooleanType (`bool`), the default value for - @a boolean_t is: - - @code {.cpp} - bool - @endcode - - #### Storage - - Boolean values are stored directly inside a @ref basic_json type. - - @since version 1.0.0 - */ - using boolean_t = BooleanType; - - /*! - @brief a type for a number (integer) - - [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: - > The representation of numbers is similar to that used in most - > programming languages. A number is represented in base 10 using decimal - > digits. It contains an integer component that may be prefixed with an - > optional minus sign, which may be followed by a fraction part and/or an - > exponent part. Leading zeros are not allowed. (...) Numeric values that - > cannot be represented in the grammar below (such as Infinity and NaN) - > are not permitted. - - This description includes both integer and floating-point numbers. - However, C++ allows more precise storage if it is known whether the number - is a signed integer, an unsigned integer or a floating-point number. - Therefore, three different types, @ref number_integer_t, @ref - number_unsigned_t and @ref number_float_t are used. - - To store integer numbers in C++, a type is defined by the template - parameter @a NumberIntegerType which chooses the type to use. - - #### Default type - - With the default values for @a NumberIntegerType (`int64_t`), the default - value for @a number_integer_t is: - - @code {.cpp} - int64_t - @endcode - - #### Default behavior - - - The restrictions about leading zeros is not enforced in C++. Instead, - leading zeros in integer literals lead to an interpretation as octal - number. Internally, the value will be stored as decimal number. For - instance, the C++ integer literal `010` will be serialized to `8`. - During deserialization, leading zeros yield an error. - - Not-a-number (NaN) values will be serialized to `null`. - - #### Limits - - [RFC 7159](http://rfc7159.net/rfc7159) specifies: - > An implementation may set limits on the range and precision of numbers. - - When the default type is used, the maximal integer number that can be - stored is `9223372036854775807` (INT64_MAX) and the minimal integer number - that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers - that are out of range will yield over/underflow when used in a - constructor. During deserialization, too large or small integer numbers - will be automatically be stored as @ref number_unsigned_t or @ref - number_float_t. - - [RFC 7159](http://rfc7159.net/rfc7159) further states: - > Note that when such software is used, numbers that are integers and are - > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense - > that implementations will agree exactly on their numeric values. - - As this range is a subrange of the exactly supported range [INT64_MIN, - INT64_MAX], this class's integer type is interoperable. - - #### Storage - - Integer number values are stored directly inside a @ref basic_json type. - - @sa @ref number_float_t -- type for number values (floating-point) - - @sa @ref number_unsigned_t -- type for number values (unsigned integer) - - @since version 1.0.0 - */ - using number_integer_t = NumberIntegerType; - - /*! - @brief a type for a number (unsigned) - - [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: - > The representation of numbers is similar to that used in most - > programming languages. A number is represented in base 10 using decimal - > digits. It contains an integer component that may be prefixed with an - > optional minus sign, which may be followed by a fraction part and/or an - > exponent part. Leading zeros are not allowed. (...) Numeric values that - > cannot be represented in the grammar below (such as Infinity and NaN) - > are not permitted. - - This description includes both integer and floating-point numbers. - However, C++ allows more precise storage if it is known whether the number - is a signed integer, an unsigned integer or a floating-point number. - Therefore, three different types, @ref number_integer_t, @ref - number_unsigned_t and @ref number_float_t are used. - - To store unsigned integer numbers in C++, a type is defined by the - template parameter @a NumberUnsignedType which chooses the type to use. - - #### Default type - - With the default values for @a NumberUnsignedType (`uint64_t`), the - default value for @a number_unsigned_t is: - - @code {.cpp} - uint64_t - @endcode - - #### Default behavior - - - The restrictions about leading zeros is not enforced in C++. Instead, - leading zeros in integer literals lead to an interpretation as octal - number. Internally, the value will be stored as decimal number. For - instance, the C++ integer literal `010` will be serialized to `8`. - During deserialization, leading zeros yield an error. - - Not-a-number (NaN) values will be serialized to `null`. - - #### Limits - - [RFC 7159](http://rfc7159.net/rfc7159) specifies: - > An implementation may set limits on the range and precision of numbers. - - When the default type is used, the maximal integer number that can be - stored is `18446744073709551615` (UINT64_MAX) and the minimal integer - number that can be stored is `0`. Integer numbers that are out of range - will yield over/underflow when used in a constructor. During - deserialization, too large or small integer numbers will be automatically - be stored as @ref number_integer_t or @ref number_float_t. - - [RFC 7159](http://rfc7159.net/rfc7159) further states: - > Note that when such software is used, numbers that are integers and are - > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense - > that implementations will agree exactly on their numeric values. - - As this range is a subrange (when considered in conjunction with the - number_integer_t type) of the exactly supported range [0, UINT64_MAX], - this class's integer type is interoperable. - - #### Storage - - Integer number values are stored directly inside a @ref basic_json type. - - @sa @ref number_float_t -- type for number values (floating-point) - @sa @ref number_integer_t -- type for number values (integer) - - @since version 2.0.0 - */ - using number_unsigned_t = NumberUnsignedType; - - /*! - @brief a type for a number (floating-point) - - [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: - > The representation of numbers is similar to that used in most - > programming languages. A number is represented in base 10 using decimal - > digits. It contains an integer component that may be prefixed with an - > optional minus sign, which may be followed by a fraction part and/or an - > exponent part. Leading zeros are not allowed. (...) Numeric values that - > cannot be represented in the grammar below (such as Infinity and NaN) - > are not permitted. - - This description includes both integer and floating-point numbers. - However, C++ allows more precise storage if it is known whether the number - is a signed integer, an unsigned integer or a floating-point number. - Therefore, three different types, @ref number_integer_t, @ref - number_unsigned_t and @ref number_float_t are used. - - To store floating-point numbers in C++, a type is defined by the template - parameter @a NumberFloatType which chooses the type to use. - - #### Default type - - With the default values for @a NumberFloatType (`double`), the default - value for @a number_float_t is: - - @code {.cpp} - double - @endcode - - #### Default behavior - - - The restrictions about leading zeros is not enforced in C++. Instead, - leading zeros in floating-point literals will be ignored. Internally, - the value will be stored as decimal number. For instance, the C++ - floating-point literal `01.2` will be serialized to `1.2`. During - deserialization, leading zeros yield an error. - - Not-a-number (NaN) values will be serialized to `null`. - - #### Limits - - [RFC 7159](http://rfc7159.net/rfc7159) states: - > This specification allows implementations to set limits on the range and - > precision of numbers accepted. Since software that implements IEEE - > 754-2008 binary64 (double precision) numbers is generally available and - > widely used, good interoperability can be achieved by implementations - > that expect no more precision or range than these provide, in the sense - > that implementations will approximate JSON numbers within the expected - > precision. - - This implementation does exactly follow this approach, as it uses double - precision floating-point numbers. Note values smaller than - `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` - will be stored as NaN internally and be serialized to `null`. - - #### Storage - - Floating-point number values are stored directly inside a @ref basic_json - type. - - @sa @ref number_integer_t -- type for number values (integer) - - @sa @ref number_unsigned_t -- type for number values (unsigned integer) - - @since version 1.0.0 - */ - using number_float_t = NumberFloatType; - - /// @} - - private: - - /// helper for exception-safe object creation - template - static T* create(Args&& ... args) - { - AllocatorType alloc; - using AllocatorTraits = std::allocator_traits>; - - auto deleter = [&](T * object) - { - AllocatorTraits::deallocate(alloc, object, 1); - }; - std::unique_ptr object(AllocatorTraits::allocate(alloc, 1), deleter); - AllocatorTraits::construct(alloc, object.get(), std::forward(args)...); - assert(object != nullptr); - return object.release(); - } - - //////////////////////// - // JSON value storage // - //////////////////////// - - /*! - @brief a JSON value - - The actual storage for a JSON value of the @ref basic_json class. This - union combines the different storage types for the JSON value types - defined in @ref value_t. - - JSON type | value_t type | used type - --------- | --------------- | ------------------------ - object | object | pointer to @ref object_t - array | array | pointer to @ref array_t - string | string | pointer to @ref string_t - boolean | boolean | @ref boolean_t - number | number_integer | @ref number_integer_t - number | number_unsigned | @ref number_unsigned_t - number | number_float | @ref number_float_t - null | null | *no value is stored* - - @note Variable-length types (objects, arrays, and strings) are stored as - pointers. The size of the union should not exceed 64 bits if the default - value types are used. - - @since version 1.0.0 - */ - union json_value - { - /// object (stored with pointer to save storage) - object_t* object; - /// array (stored with pointer to save storage) - array_t* array; - /// string (stored with pointer to save storage) - string_t* string; - /// boolean - boolean_t boolean; - /// number (integer) - number_integer_t number_integer; - /// number (unsigned integer) - number_unsigned_t number_unsigned; - /// number (floating-point) - number_float_t number_float; - - /// default constructor (for null values) - json_value() = default; - /// constructor for booleans - json_value(boolean_t v) noexcept : boolean(v) {} - /// constructor for numbers (integer) - json_value(number_integer_t v) noexcept : number_integer(v) {} - /// constructor for numbers (unsigned) - json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} - /// constructor for numbers (floating-point) - json_value(number_float_t v) noexcept : number_float(v) {} - /// constructor for empty values of a given type - json_value(value_t t) - { - switch (t) - { - case value_t::object: - { - object = create(); - break; - } - - case value_t::array: - { - array = create(); - break; - } - - case value_t::string: - { - string = create(""); - break; - } - - case value_t::boolean: - { - boolean = boolean_t(false); - break; - } - - case value_t::number_integer: - { - number_integer = number_integer_t(0); - break; - } - - case value_t::number_unsigned: - { - number_unsigned = number_unsigned_t(0); - break; - } - - case value_t::number_float: - { - number_float = number_float_t(0.0); - break; - } - - case value_t::null: - { - object = nullptr; // silence warning, see #821 - break; - } - - default: - { - object = nullptr; // silence warning, see #821 - if (JSON_UNLIKELY(t == value_t::null)) - { - JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.1.2")); // LCOV_EXCL_LINE - } - break; - } - } - } - - /// constructor for strings - json_value(const string_t& value) - { - string = create(value); - } - - /// constructor for rvalue strings - json_value(string_t&& value) - { - string = create(std::move(value)); - } - - /// constructor for objects - json_value(const object_t& value) - { - object = create(value); - } - - /// constructor for rvalue objects - json_value(object_t&& value) - { - object = create(std::move(value)); - } - - /// constructor for arrays - json_value(const array_t& value) - { - array = create(value); - } - - /// constructor for rvalue arrays - json_value(array_t&& value) - { - array = create(std::move(value)); - } - - void destroy(value_t t) noexcept - { - switch (t) - { - case value_t::object: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, object); - std::allocator_traits::deallocate(alloc, object, 1); - break; - } - - case value_t::array: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, array); - std::allocator_traits::deallocate(alloc, array, 1); - break; - } - - case value_t::string: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, string); - std::allocator_traits::deallocate(alloc, string, 1); - break; - } - - default: - { - break; - } - } - } - }; - - /*! - @brief checks the class invariants - - This function asserts the class invariants. It needs to be called at the - end of every constructor to make sure that created objects respect the - invariant. Furthermore, it has to be called each time the type of a JSON - value is changed, because the invariant expresses a relationship between - @a m_type and @a m_value. - */ - void assert_invariant() const noexcept - { - assert(m_type != value_t::object or m_value.object != nullptr); - assert(m_type != value_t::array or m_value.array != nullptr); - assert(m_type != value_t::string or m_value.string != nullptr); - } - - public: - ////////////////////////// - // JSON parser callback // - ////////////////////////// - - /*! - @brief parser event types - - The parser callback distinguishes the following events: - - `object_start`: the parser read `{` and started to process a JSON object - - `key`: the parser read a key of a value in an object - - `object_end`: the parser read `}` and finished processing a JSON object - - `array_start`: the parser read `[` and started to process a JSON array - - `array_end`: the parser read `]` and finished processing a JSON array - - `value`: the parser finished reading a JSON value - - @image html callback_events.png "Example when certain parse events are triggered" - - @sa @ref parser_callback_t for more information and examples - */ - using parse_event_t = typename parser::parse_event_t; - - /*! - @brief per-element parser callback type - - With a parser callback function, the result of parsing a JSON text can be - influenced. When passed to @ref parse, it is called on certain events - (passed as @ref parse_event_t via parameter @a event) with a set recursion - depth @a depth and context JSON value @a parsed. The return value of the - callback function is a boolean indicating whether the element that emitted - the callback shall be kept or not. - - We distinguish six scenarios (determined by the event type) in which the - callback function can be called. The following table describes the values - of the parameters @a depth, @a event, and @a parsed. - - parameter @a event | description | parameter @a depth | parameter @a parsed - ------------------ | ----------- | ------------------ | ------------------- - parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded - parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key - parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object - parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded - parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array - parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value - - @image html callback_events.png "Example when certain parse events are triggered" - - Discarding a value (i.e., returning `false`) has different effects - depending on the context in which function was called: - - - Discarded values in structured types are skipped. That is, the parser - will behave as if the discarded value was never read. - - In case a value outside a structured type is skipped, it is replaced - with `null`. This case happens if the top-level element is skipped. - - @param[in] depth the depth of the recursion during parsing - - @param[in] event an event of type parse_event_t indicating the context in - the callback function has been called - - @param[in,out] parsed the current intermediate parse result; note that - writing to this value has no effect for parse_event_t::key events - - @return Whether the JSON value which called the function during parsing - should be kept (`true`) or not (`false`). In the latter case, it is either - skipped completely or replaced by an empty discarded object. - - @sa @ref parse for examples - - @since version 1.0.0 - */ - using parser_callback_t = typename parser::parser_callback_t; - - using json_sax_t = typename parser::json_sax_t; - - ////////////////// - // constructors // - ////////////////// - - /// @name constructors and destructors - /// Constructors of class @ref basic_json, copy/move constructor, copy - /// assignment, static functions creating objects, and the destructor. - /// @{ - - /*! - @brief create an empty value with a given type - - Create an empty JSON value with a given type. The value will be default - initialized with an empty value which depends on the type: - - Value type | initial value - ----------- | ------------- - null | `null` - boolean | `false` - string | `""` - number | `0` - object | `{}` - array | `[]` - - @param[in] v the type of the value to create - - @complexity Constant. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @liveexample{The following code shows the constructor for different @ref - value_t values,basic_json__value_t} - - @sa @ref clear() -- restores the postcondition of this constructor - - @since version 1.0.0 - */ - basic_json(const value_t v) - : m_type(v), m_value(v) - { - assert_invariant(); - } - - /*! - @brief create a null object - - Create a `null` JSON value. It either takes a null pointer as parameter - (explicitly creating `null`) or no parameter (implicitly creating `null`). - The passed null pointer itself is not read -- it is only used to choose - the right constructor. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this constructor never throws - exceptions. - - @liveexample{The following code shows the constructor with and without a - null pointer parameter.,basic_json__nullptr_t} - - @since version 1.0.0 - */ - basic_json(std::nullptr_t = nullptr) noexcept - : basic_json(value_t::null) - { - assert_invariant(); - } - - /*! - @brief create a JSON value - - This is a "catch all" constructor for all compatible JSON types; that is, - types for which a `to_json()` method exists. The constructor forwards the - parameter @a val to that method (to `json_serializer::to_json` method - with `U = uncvref_t`, to be exact). - - Template type @a CompatibleType includes, but is not limited to, the - following types: - - **arrays**: @ref array_t and all kinds of compatible containers such as - `std::vector`, `std::deque`, `std::list`, `std::forward_list`, - `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, - `std::multiset`, and `std::unordered_multiset` with a `value_type` from - which a @ref basic_json value can be constructed. - - **objects**: @ref object_t and all kinds of compatible associative - containers such as `std::map`, `std::unordered_map`, `std::multimap`, - and `std::unordered_multimap` with a `key_type` compatible to - @ref string_t and a `value_type` from which a @ref basic_json value can - be constructed. - - **strings**: @ref string_t, string literals, and all compatible string - containers can be used. - - **numbers**: @ref number_integer_t, @ref number_unsigned_t, - @ref number_float_t, and all convertible number types such as `int`, - `size_t`, `int64_t`, `float` or `double` can be used. - - **boolean**: @ref boolean_t / `bool` can be used. - - See the examples below. - - @tparam CompatibleType a type such that: - - @a CompatibleType is not derived from `std::istream`, - - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move - constructors), - - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments) - - @a CompatibleType is not a @ref basic_json nested type (e.g., - @ref json_pointer, @ref iterator, etc ...) - - @ref @ref json_serializer has a - `to_json(basic_json_t&, CompatibleType&&)` method - - @tparam U = `uncvref_t` - - @param[in] val the value to be forwarded to the respective constructor - - @complexity Usually linear in the size of the passed @a val, also - depending on the implementation of the called `to_json()` - method. - - @exceptionsafety Depends on the called constructor. For types directly - supported by the library (i.e., all types for which no `to_json()` function - was provided), strong guarantee holds: if an exception is thrown, there are - no changes to any JSON value. - - @liveexample{The following code shows the constructor with several - compatible types.,basic_json__CompatibleType} - - @since version 2.1.0 - */ - template , - detail::enable_if_t< - detail::is_compatible_type::value, int> = 0> - basic_json(CompatibleType && val) noexcept(noexcept( - JSONSerializer::to_json(std::declval(), - std::forward(val)))) - { - JSONSerializer::to_json(*this, std::forward(val)); - assert_invariant(); - } - - /*! - @brief create a JSON value from an existing one - - This is a constructor for existing @ref basic_json types. - It does not hijack copy/move constructors, since the parameter has different - template arguments than the current ones. - - The constructor tries to convert the internal @ref m_value of the parameter. - - @tparam BasicJsonType a type such that: - - @a BasicJsonType is a @ref basic_json type. - - @a BasicJsonType has different template arguments than @ref basic_json_t. - - @param[in] val the @ref basic_json value to be converted. - - @complexity Usually linear in the size of the passed @a val, also - depending on the implementation of the called `to_json()` - method. - - @exceptionsafety Depends on the called constructor. For types directly - supported by the library (i.e., all types for which no `to_json()` function - was provided), strong guarantee holds: if an exception is thrown, there are - no changes to any JSON value. - - @since version 3.1.2 - */ - template ::value and not std::is_same::value, int> = 0> - basic_json(const BasicJsonType& val) - { - using other_boolean_t = typename BasicJsonType::boolean_t; - using other_number_float_t = typename BasicJsonType::number_float_t; - using other_number_integer_t = typename BasicJsonType::number_integer_t; - using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using other_string_t = typename BasicJsonType::string_t; - using other_object_t = typename BasicJsonType::object_t; - using other_array_t = typename BasicJsonType::array_t; - - switch (val.type()) - { - case value_t::boolean: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_float: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_integer: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_unsigned: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::string: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::object: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::array: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::null: - *this = nullptr; - break; - case value_t::discarded: - m_type = value_t::discarded; - break; - } - assert_invariant(); - } - - /*! - @brief create a container (array or object) from an initializer list - - Creates a JSON value of type array or object from the passed initializer - list @a init. In case @a type_deduction is `true` (default), the type of - the JSON value to be created is deducted from the initializer list @a init - according to the following rules: - - 1. If the list is empty, an empty JSON object value `{}` is created. - 2. If the list consists of pairs whose first element is a string, a JSON - object value is created where the first elements of the pairs are - treated as keys and the second elements are as values. - 3. In all other cases, an array is created. - - The rules aim to create the best fit between a C++ initializer list and - JSON values. The rationale is as follows: - - 1. The empty initializer list is written as `{}` which is exactly an empty - JSON object. - 2. C++ has no way of describing mapped types other than to list a list of - pairs. As JSON requires that keys must be of type string, rule 2 is the - weakest constraint one can pose on initializer lists to interpret them - as an object. - 3. In all other cases, the initializer list could not be interpreted as - JSON object type, so interpreting it as JSON array type is safe. - - With the rules described above, the following JSON values cannot be - expressed by an initializer list: - - - the empty array (`[]`): use @ref array(initializer_list_t) - with an empty initializer list in this case - - arrays whose elements satisfy rule 2: use @ref - array(initializer_list_t) with the same initializer list - in this case - - @note When used without parentheses around an empty initializer list, @ref - basic_json() is called instead of this function, yielding the JSON null - value. - - @param[in] init initializer list with JSON values - - @param[in] type_deduction internal parameter; when set to `true`, the type - of the JSON value is deducted from the initializer list @a init; when set - to `false`, the type provided via @a manual_type is forced. This mode is - used by the functions @ref array(initializer_list_t) and - @ref object(initializer_list_t). - - @param[in] manual_type internal parameter; when @a type_deduction is set - to `false`, the created JSON value will use the provided type (only @ref - value_t::array and @ref value_t::object are valid); when @a type_deduction - is set to `true`, this parameter has no effect - - @throw type_error.301 if @a type_deduction is `false`, @a manual_type is - `value_t::object`, but @a init contains an element which is not a pair - whose first element is a string. In this case, the constructor could not - create an object. If @a type_deduction would have be `true`, an array - would have been created. See @ref object(initializer_list_t) - for an example. - - @complexity Linear in the size of the initializer list @a init. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @liveexample{The example below shows how JSON values are created from - initializer lists.,basic_json__list_init_t} - - @sa @ref array(initializer_list_t) -- create a JSON array - value from an initializer list - @sa @ref object(initializer_list_t) -- create a JSON object - value from an initializer list - - @since version 1.0.0 - */ - basic_json(initializer_list_t init, - bool type_deduction = true, - value_t manual_type = value_t::array) - { - // check if each element is an array with two elements whose first - // element is a string - bool is_an_object = std::all_of(init.begin(), init.end(), - [](const detail::json_ref& element_ref) - { - return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string()); - }); - - // adjust type if type deduction is not wanted - if (not type_deduction) - { - // if array is wanted, do not create an object though possible - if (manual_type == value_t::array) - { - is_an_object = false; - } - - // if object is wanted but impossible, throw an exception - if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object)) - { - JSON_THROW(type_error::create(301, "cannot create object from initializer list")); - } - } - - if (is_an_object) - { - // the initializer list is a list of pairs -> create object - m_type = value_t::object; - m_value = value_t::object; - - std::for_each(init.begin(), init.end(), [this](const detail::json_ref& element_ref) - { - auto element = element_ref.moved_or_copied(); - m_value.object->emplace( - std::move(*((*element.m_value.array)[0].m_value.string)), - std::move((*element.m_value.array)[1])); - }); - } - else - { - // the initializer list describes an array -> create array - m_type = value_t::array; - m_value.array = create(init.begin(), init.end()); - } - - assert_invariant(); - } - - /*! - @brief explicitly create an array from an initializer list - - Creates a JSON array value from a given initializer list. That is, given a - list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the - initializer list is empty, the empty array `[]` is created. - - @note This function is only needed to express two edge cases that cannot - be realized with the initializer list constructor (@ref - basic_json(initializer_list_t, bool, value_t)). These cases - are: - 1. creating an array whose elements are all pairs whose first element is a - string -- in this case, the initializer list constructor would create an - object, taking the first elements as keys - 2. creating an empty array -- passing the empty initializer list to the - initializer list constructor yields an empty object - - @param[in] init initializer list with JSON values to create an array from - (optional) - - @return JSON array value - - @complexity Linear in the size of @a init. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @liveexample{The following code shows an example for the `array` - function.,array} - - @sa @ref basic_json(initializer_list_t, bool, value_t) -- - create a JSON value from an initializer list - @sa @ref object(initializer_list_t) -- create a JSON object - value from an initializer list - - @since version 1.0.0 - */ - static basic_json array(initializer_list_t init = {}) - { - return basic_json(init, false, value_t::array); - } - - /*! - @brief explicitly create an object from an initializer list - - Creates a JSON object value from a given initializer list. The initializer - lists elements must be pairs, and their first elements must be strings. If - the initializer list is empty, the empty object `{}` is created. - - @note This function is only added for symmetry reasons. In contrast to the - related function @ref array(initializer_list_t), there are - no cases which can only be expressed by this function. That is, any - initializer list @a init can also be passed to the initializer list - constructor @ref basic_json(initializer_list_t, bool, value_t). - - @param[in] init initializer list to create an object from (optional) - - @return JSON object value - - @throw type_error.301 if @a init is not a list of pairs whose first - elements are strings. In this case, no object can be created. When such a - value is passed to @ref basic_json(initializer_list_t, bool, value_t), - an array would have been created from the passed initializer list @a init. - See example below. - - @complexity Linear in the size of @a init. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @liveexample{The following code shows an example for the `object` - function.,object} - - @sa @ref basic_json(initializer_list_t, bool, value_t) -- - create a JSON value from an initializer list - @sa @ref array(initializer_list_t) -- create a JSON array - value from an initializer list - - @since version 1.0.0 - */ - static basic_json object(initializer_list_t init = {}) - { - return basic_json(init, false, value_t::object); - } - - /*! - @brief construct an array with count copies of given value - - Constructs a JSON array value by creating @a cnt copies of a passed value. - In case @a cnt is `0`, an empty array is created. - - @param[in] cnt the number of JSON copies of @a val to create - @param[in] val the JSON value to copy - - @post `std::distance(begin(),end()) == cnt` holds. - - @complexity Linear in @a cnt. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @liveexample{The following code shows examples for the @ref - basic_json(size_type\, const basic_json&) - constructor.,basic_json__size_type_basic_json} - - @since version 1.0.0 - */ - basic_json(size_type cnt, const basic_json& val) - : m_type(value_t::array) - { - m_value.array = create(cnt, val); - assert_invariant(); - } - - /*! - @brief construct a JSON container given an iterator range - - Constructs the JSON value with the contents of the range `[first, last)`. - The semantics depends on the different types a JSON value can have: - - In case of a null type, invalid_iterator.206 is thrown. - - In case of other primitive types (number, boolean, or string), @a first - must be `begin()` and @a last must be `end()`. In this case, the value is - copied. Otherwise, invalid_iterator.204 is thrown. - - In case of structured types (array, object), the constructor behaves as - similar versions for `std::vector` or `std::map`; that is, a JSON array - or object is constructed from the values in the range. - - @tparam InputIT an input iterator type (@ref iterator or @ref - const_iterator) - - @param[in] first begin of the range to copy from (included) - @param[in] last end of the range to copy from (excluded) - - @pre Iterators @a first and @a last must be initialized. **This - precondition is enforced with an assertion (see warning).** If - assertions are switched off, a violation of this precondition yields - undefined behavior. - - @pre Range `[first, last)` is valid. Usually, this precondition cannot be - checked efficiently. Only certain edge cases are detected; see the - description of the exceptions below. A violation of this precondition - yields undefined behavior. - - @warning A precondition is enforced with a runtime assertion that will - result in calling `std::abort` if this precondition is not met. - Assertions can be disabled by defining `NDEBUG` at compile time. - See https://en.cppreference.com/w/cpp/error/assert for more - information. - - @throw invalid_iterator.201 if iterators @a first and @a last are not - compatible (i.e., do not belong to the same JSON value). In this case, - the range `[first, last)` is undefined. - @throw invalid_iterator.204 if iterators @a first and @a last belong to a - primitive type (number, boolean, or string), but @a first does not point - to the first element any more. In this case, the range `[first, last)` is - undefined. See example code below. - @throw invalid_iterator.206 if iterators @a first and @a last belong to a - null value. In this case, the range `[first, last)` is undefined. - - @complexity Linear in distance between @a first and @a last. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @liveexample{The example below shows several ways to create JSON values by - specifying a subrange with iterators.,basic_json__InputIt_InputIt} - - @since version 1.0.0 - */ - template::value or - std::is_same::value, int>::type = 0> - basic_json(InputIT first, InputIT last) - { - assert(first.m_object != nullptr); - assert(last.m_object != nullptr); - - // make sure iterator fits the current value - if (JSON_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); - } - - // copy type from first iterator - m_type = first.m_object->m_type; - - // check if iterator range is complete for primitive values - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - { - if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin() - or not last.m_it.primitive_iterator.is_end())) - { - JSON_THROW(invalid_iterator::create(204, "iterators out of range")); - } - break; - } - - default: - break; - } - - switch (m_type) - { - case value_t::number_integer: - { - m_value.number_integer = first.m_object->m_value.number_integer; - break; - } - - case value_t::number_unsigned: - { - m_value.number_unsigned = first.m_object->m_value.number_unsigned; - break; - } - - case value_t::number_float: - { - m_value.number_float = first.m_object->m_value.number_float; - break; - } - - case value_t::boolean: - { - m_value.boolean = first.m_object->m_value.boolean; - break; - } - - case value_t::string: - { - m_value = *first.m_object->m_value.string; - break; - } - - case value_t::object: - { - m_value.object = create(first.m_it.object_iterator, - last.m_it.object_iterator); - break; - } - - case value_t::array: - { - m_value.array = create(first.m_it.array_iterator, - last.m_it.array_iterator); - break; - } - - default: - JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + - std::string(first.m_object->type_name()))); - } - - assert_invariant(); - } - - - /////////////////////////////////////// - // other constructors and destructor // - /////////////////////////////////////// - - /// @private - basic_json(const detail::json_ref& ref) - : basic_json(ref.moved_or_copied()) - {} - - /*! - @brief copy constructor - - Creates a copy of a given JSON value. - - @param[in] other the JSON value to copy - - @post `*this == other` - - @complexity Linear in the size of @a other. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes to any JSON value. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is linear. - - As postcondition, it holds: `other == basic_json(other)`. - - @liveexample{The following code shows an example for the copy - constructor.,basic_json__basic_json} - - @since version 1.0.0 - */ - basic_json(const basic_json& other) - : m_type(other.m_type) - { - // check of passed value is valid - other.assert_invariant(); - - switch (m_type) - { - case value_t::object: - { - m_value = *other.m_value.object; - break; - } - - case value_t::array: - { - m_value = *other.m_value.array; - break; - } - - case value_t::string: - { - m_value = *other.m_value.string; - break; - } - - case value_t::boolean: - { - m_value = other.m_value.boolean; - break; - } - - case value_t::number_integer: - { - m_value = other.m_value.number_integer; - break; - } - - case value_t::number_unsigned: - { - m_value = other.m_value.number_unsigned; - break; - } - - case value_t::number_float: - { - m_value = other.m_value.number_float; - break; - } - - default: - break; - } - - assert_invariant(); - } - - /*! - @brief move constructor - - Move constructor. Constructs a JSON value with the contents of the given - value @a other using move semantics. It "steals" the resources from @a - other and leaves it as JSON null value. - - @param[in,out] other value to move to this object - - @post `*this` has the same value as @a other before the call. - @post @a other is a JSON null value. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this constructor never throws - exceptions. - - @requirement This function helps `basic_json` satisfying the - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible) - requirements. - - @liveexample{The code below shows the move constructor explicitly called - via std::move.,basic_json__moveconstructor} - - @since version 1.0.0 - */ - basic_json(basic_json&& other) noexcept - : m_type(std::move(other.m_type)), - m_value(std::move(other.m_value)) - { - // check that passed value is valid - other.assert_invariant(); - - // invalidate payload - other.m_type = value_t::null; - other.m_value = {}; - - assert_invariant(); - } - - /*! - @brief copy assignment - - Copy assignment operator. Copies a JSON value via the "copy and swap" - strategy: It is expressed in terms of the copy constructor, destructor, - and the `swap()` member function. - - @param[in] other value to copy from - - @complexity Linear. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is linear. - - @liveexample{The code below shows and example for the copy assignment. It - creates a copy of value `a` which is then swapped with `b`. Finally\, the - copy of `a` (which is the null value after the swap) is - destroyed.,basic_json__copyassignment} - - @since version 1.0.0 - */ - reference& operator=(basic_json other) noexcept ( - std::is_nothrow_move_constructible::value and - std::is_nothrow_move_assignable::value and - std::is_nothrow_move_constructible::value and - std::is_nothrow_move_assignable::value - ) - { - // check that passed value is valid - other.assert_invariant(); - - using std::swap; - swap(m_type, other.m_type); - swap(m_value, other.m_value); - - assert_invariant(); - return *this; - } - - /*! - @brief destructor - - Destroys the JSON value and frees all allocated memory. - - @complexity Linear. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is linear. - - All stored elements are destroyed and all memory is freed. - - @since version 1.0.0 - */ - ~basic_json() noexcept - { - assert_invariant(); - m_value.destroy(m_type); - } - - /// @} - - public: - /////////////////////// - // object inspection // - /////////////////////// - - /// @name object inspection - /// Functions to inspect the type of a JSON value. - /// @{ - - /*! - @brief serialization - - Serialization function for JSON values. The function tries to mimic - Python's `json.dumps()` function, and currently supports its @a indent - and @a ensure_ascii parameters. - - @param[in] indent If indent is nonnegative, then array elements and object - members will be pretty-printed with that indent level. An indent level of - `0` will only insert newlines. `-1` (the default) selects the most compact - representation. - @param[in] indent_char The character to use for indentation if @a indent is - greater than `0`. The default is ` ` (space). - @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters - in the output are escaped with `\uXXXX` sequences, and the result consists - of ASCII characters only. - - @return string containing the serialization of the JSON value - - @throw type_error.316 if a string stored inside the JSON value is not - UTF-8 encoded - - @complexity Linear. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @liveexample{The following example shows the effect of different @a indent\, - @a indent_char\, and @a ensure_ascii parameters to the result of the - serialization.,dump} - - @see https://docs.python.org/2/library/json.html#json.dump - - @since version 1.0.0; indentation character @a indent_char, option - @a ensure_ascii and exceptions added in version 3.0.0 - */ - string_t dump(const int indent = -1, const char indent_char = ' ', - const bool ensure_ascii = false) const - { - string_t result; - serializer s(detail::output_adapter(result), indent_char); - - if (indent >= 0) - { - s.dump(*this, true, ensure_ascii, static_cast(indent)); - } - else - { - s.dump(*this, false, ensure_ascii, 0); - } - - return result; - } - - /*! - @brief return the type of the JSON value (explicit) - - Return the type of the JSON value as a value from the @ref value_t - enumeration. - - @return the type of the JSON value - Value type | return value - ------------------------- | ------------------------- - null | value_t::null - boolean | value_t::boolean - string | value_t::string - number (integer) | value_t::number_integer - number (unsigned integer) | value_t::number_unsigned - number (floating-point) | value_t::number_float - object | value_t::object - array | value_t::array - discarded | value_t::discarded - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `type()` for all JSON - types.,type} - - @sa @ref operator value_t() -- return the type of the JSON value (implicit) - @sa @ref type_name() -- return the type as string - - @since version 1.0.0 - */ - constexpr value_t type() const noexcept - { - return m_type; - } - - /*! - @brief return whether type is primitive - - This function returns true if and only if the JSON type is primitive - (string, number, boolean, or null). - - @return `true` if type is primitive (string, number, boolean, or null), - `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_primitive()` for all JSON - types.,is_primitive} - - @sa @ref is_structured() -- returns whether JSON value is structured - @sa @ref is_null() -- returns whether JSON value is `null` - @sa @ref is_string() -- returns whether JSON value is a string - @sa @ref is_boolean() -- returns whether JSON value is a boolean - @sa @ref is_number() -- returns whether JSON value is a number - - @since version 1.0.0 - */ - constexpr bool is_primitive() const noexcept - { - return is_null() or is_string() or is_boolean() or is_number(); - } - - /*! - @brief return whether type is structured - - This function returns true if and only if the JSON type is structured - (array or object). - - @return `true` if type is structured (array or object), `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_structured()` for all JSON - types.,is_structured} - - @sa @ref is_primitive() -- returns whether value is primitive - @sa @ref is_array() -- returns whether value is an array - @sa @ref is_object() -- returns whether value is an object - - @since version 1.0.0 - */ - constexpr bool is_structured() const noexcept - { - return is_array() or is_object(); - } - - /*! - @brief return whether value is null - - This function returns true if and only if the JSON value is null. - - @return `true` if type is null, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_null()` for all JSON - types.,is_null} - - @since version 1.0.0 - */ - constexpr bool is_null() const noexcept - { - return (m_type == value_t::null); - } - - /*! - @brief return whether value is a boolean - - This function returns true if and only if the JSON value is a boolean. - - @return `true` if type is boolean, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_boolean()` for all JSON - types.,is_boolean} - - @since version 1.0.0 - */ - constexpr bool is_boolean() const noexcept - { - return (m_type == value_t::boolean); - } - - /*! - @brief return whether value is a number - - This function returns true if and only if the JSON value is a number. This - includes both integer (signed and unsigned) and floating-point values. - - @return `true` if type is number (regardless whether integer, unsigned - integer or floating-type), `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_number()` for all JSON - types.,is_number} - - @sa @ref is_number_integer() -- check if value is an integer or unsigned - integer number - @sa @ref is_number_unsigned() -- check if value is an unsigned integer - number - @sa @ref is_number_float() -- check if value is a floating-point number - - @since version 1.0.0 - */ - constexpr bool is_number() const noexcept - { - return is_number_integer() or is_number_float(); - } - - /*! - @brief return whether value is an integer number - - This function returns true if and only if the JSON value is a signed or - unsigned integer number. This excludes floating-point values. - - @return `true` if type is an integer or unsigned integer number, `false` - otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_number_integer()` for all - JSON types.,is_number_integer} - - @sa @ref is_number() -- check if value is a number - @sa @ref is_number_unsigned() -- check if value is an unsigned integer - number - @sa @ref is_number_float() -- check if value is a floating-point number - - @since version 1.0.0 - */ - constexpr bool is_number_integer() const noexcept - { - return (m_type == value_t::number_integer or m_type == value_t::number_unsigned); - } - - /*! - @brief return whether value is an unsigned integer number - - This function returns true if and only if the JSON value is an unsigned - integer number. This excludes floating-point and signed integer values. - - @return `true` if type is an unsigned integer number, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_number_unsigned()` for all - JSON types.,is_number_unsigned} - - @sa @ref is_number() -- check if value is a number - @sa @ref is_number_integer() -- check if value is an integer or unsigned - integer number - @sa @ref is_number_float() -- check if value is a floating-point number - - @since version 2.0.0 - */ - constexpr bool is_number_unsigned() const noexcept - { - return (m_type == value_t::number_unsigned); - } - - /*! - @brief return whether value is a floating-point number - - This function returns true if and only if the JSON value is a - floating-point number. This excludes signed and unsigned integer values. - - @return `true` if type is a floating-point number, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_number_float()` for all - JSON types.,is_number_float} - - @sa @ref is_number() -- check if value is number - @sa @ref is_number_integer() -- check if value is an integer number - @sa @ref is_number_unsigned() -- check if value is an unsigned integer - number - - @since version 1.0.0 - */ - constexpr bool is_number_float() const noexcept - { - return (m_type == value_t::number_float); - } - - /*! - @brief return whether value is an object - - This function returns true if and only if the JSON value is an object. - - @return `true` if type is object, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_object()` for all JSON - types.,is_object} - - @since version 1.0.0 - */ - constexpr bool is_object() const noexcept - { - return (m_type == value_t::object); - } - - /*! - @brief return whether value is an array - - This function returns true if and only if the JSON value is an array. - - @return `true` if type is array, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_array()` for all JSON - types.,is_array} - - @since version 1.0.0 - */ - constexpr bool is_array() const noexcept - { - return (m_type == value_t::array); - } - - /*! - @brief return whether value is a string - - This function returns true if and only if the JSON value is a string. - - @return `true` if type is string, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_string()` for all JSON - types.,is_string} - - @since version 1.0.0 - */ - constexpr bool is_string() const noexcept - { - return (m_type == value_t::string); - } - - /*! - @brief return whether value is discarded - - This function returns true if and only if the JSON value was discarded - during parsing with a callback function (see @ref parser_callback_t). - - @note This function will always be `false` for JSON values after parsing. - That is, discarded values can only occur during parsing, but will be - removed when inside a structured value or replaced by null in other cases. - - @return `true` if type is discarded, `false` otherwise. - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies `is_discarded()` for all JSON - types.,is_discarded} - - @since version 1.0.0 - */ - constexpr bool is_discarded() const noexcept - { - return (m_type == value_t::discarded); - } - - /*! - @brief return the type of the JSON value (implicit) - - Implicitly return the type of the JSON value as a value from the @ref - value_t enumeration. - - @return the type of the JSON value - - @complexity Constant. - - @exceptionsafety No-throw guarantee: this member function never throws - exceptions. - - @liveexample{The following code exemplifies the @ref value_t operator for - all JSON types.,operator__value_t} - - @sa @ref type() -- return the type of the JSON value (explicit) - @sa @ref type_name() -- return the type as string - - @since version 1.0.0 - */ - constexpr operator value_t() const noexcept - { - return m_type; - } - - /// @} - - private: - ////////////////// - // value access // - ////////////////// - - /// get a boolean (explicit) - boolean_t get_impl(boolean_t* /*unused*/) const - { - if (JSON_LIKELY(is_boolean())) - { - return m_value.boolean; - } - - JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()))); - } - - /// get a pointer to the value (object) - object_t* get_impl_ptr(object_t* /*unused*/) noexcept - { - return is_object() ? m_value.object : nullptr; - } - - /// get a pointer to the value (object) - constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept - { - return is_object() ? m_value.object : nullptr; - } - - /// get a pointer to the value (array) - array_t* get_impl_ptr(array_t* /*unused*/) noexcept - { - return is_array() ? m_value.array : nullptr; - } - - /// get a pointer to the value (array) - constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept - { - return is_array() ? m_value.array : nullptr; - } - - /// get a pointer to the value (string) - string_t* get_impl_ptr(string_t* /*unused*/) noexcept - { - return is_string() ? m_value.string : nullptr; - } - - /// get a pointer to the value (string) - constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept - { - return is_string() ? m_value.string : nullptr; - } - - /// get a pointer to the value (boolean) - boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept - { - return is_boolean() ? &m_value.boolean : nullptr; - } - - /// get a pointer to the value (boolean) - constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept - { - return is_boolean() ? &m_value.boolean : nullptr; - } - - /// get a pointer to the value (integer number) - number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept - { - return is_number_integer() ? &m_value.number_integer : nullptr; - } - - /// get a pointer to the value (integer number) - constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept - { - return is_number_integer() ? &m_value.number_integer : nullptr; - } - - /// get a pointer to the value (unsigned number) - number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept - { - return is_number_unsigned() ? &m_value.number_unsigned : nullptr; - } - - /// get a pointer to the value (unsigned number) - constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept - { - return is_number_unsigned() ? &m_value.number_unsigned : nullptr; - } - - /// get a pointer to the value (floating-point number) - number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept - { - return is_number_float() ? &m_value.number_float : nullptr; - } - - /// get a pointer to the value (floating-point number) - constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept - { - return is_number_float() ? &m_value.number_float : nullptr; - } - - /*! - @brief helper function to implement get_ref() - - This function helps to implement get_ref() without code duplication for - const and non-const overloads - - @tparam ThisType will be deduced as `basic_json` or `const basic_json` - - @throw type_error.303 if ReferenceType does not match underlying value - type of the current JSON - */ - template - static ReferenceType get_ref_impl(ThisType& obj) - { - // delegate the call to get_ptr<>() - auto ptr = obj.template get_ptr::type>(); - - if (JSON_LIKELY(ptr != nullptr)) - { - return *ptr; - } - - JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()))); - } - - public: - /// @name value access - /// Direct access to the stored value of a JSON value. - /// @{ - - /*! - @brief get special-case overload - - This overloads avoids a lot of template boilerplate, it can be seen as the - identity method - - @tparam BasicJsonType == @ref basic_json - - @return a copy of *this - - @complexity Constant. - - @since version 2.1.0 - */ - template::type, basic_json_t>::value, - int> = 0> - basic_json get() const - { - return *this; - } - - /*! - @brief get special-case overload - - This overloads converts the current @ref basic_json in a different - @ref basic_json type - - @tparam BasicJsonType == @ref basic_json - - @return a copy of *this, converted into @tparam BasicJsonType - - @complexity Depending on the implementation of the called `from_json()` - method. - - @since version 3.1.2 - */ - template::value and - detail::is_basic_json::value, int> = 0> - BasicJsonType get() const - { - return *this; - } - - /*! - @brief get a value (explicit) - - Explicit type conversion between the JSON value and a compatible value - which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) - and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). - The value is converted by calling the @ref json_serializer - `from_json()` method. - - The function is equivalent to executing - @code {.cpp} - ValueType ret; - JSONSerializer::from_json(*this, ret); - return ret; - @endcode - - This overloads is chosen if: - - @a ValueType is not @ref basic_json, - - @ref json_serializer has a `from_json()` method of the form - `void from_json(const basic_json&, ValueType&)`, and - - @ref json_serializer does not have a `from_json()` method of - the form `ValueType from_json(const basic_json&)` - - @tparam ValueTypeCV the provided value type - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @a ValueType - - @throw what @ref json_serializer `from_json()` method throws - - @liveexample{The example below shows several conversions from JSON values - to other types. There a few things to note: (1) Floating-point numbers can - be converted to integers\, (2) A JSON array can be converted to a standard - `std::vector`\, (3) A JSON object can be converted to C++ - associative containers such as `std::unordered_map`.,get__ValueType_const} - - @since version 2.1.0 - */ - template, - detail::enable_if_t < - not detail::is_basic_json::value and - detail::has_from_json::value and - not detail::has_non_default_from_json::value, - int> = 0> - ValueType get() const noexcept(noexcept( - JSONSerializer::from_json(std::declval(), std::declval()))) - { - // we cannot static_assert on ValueTypeCV being non-const, because - // there is support for get(), which is why we - // still need the uncvref - static_assert(not std::is_reference::value, - "get() cannot be used with reference types, you might want to use get_ref()"); - static_assert(std::is_default_constructible::value, - "types must be DefaultConstructible when used with get()"); - - ValueType ret; - JSONSerializer::from_json(*this, ret); - return ret; - } - - /*! - @brief get a value (explicit); special case - - Explicit type conversion between the JSON value and a compatible value - which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) - and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). - The value is converted by calling the @ref json_serializer - `from_json()` method. - - The function is equivalent to executing - @code {.cpp} - return JSONSerializer::from_json(*this); - @endcode - - This overloads is chosen if: - - @a ValueType is not @ref basic_json and - - @ref json_serializer has a `from_json()` method of the form - `ValueType from_json(const basic_json&)` - - @note If @ref json_serializer has both overloads of - `from_json()`, this one is chosen. - - @tparam ValueTypeCV the provided value type - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @a ValueType - - @throw what @ref json_serializer `from_json()` method throws - - @since version 2.1.0 - */ - template, - detail::enable_if_t::value and - detail::has_non_default_from_json::value, - int> = 0> - ValueType get() const noexcept(noexcept( - JSONSerializer::from_json(std::declval()))) - { - static_assert(not std::is_reference::value, - "get() cannot be used with reference types, you might want to use get_ref()"); - return JSONSerializer::from_json(*this); - } - - /*! - @brief get a pointer value (explicit) - - Explicit pointer access to the internally stored JSON value. No copies are - made. - - @warning The pointer becomes invalid if the underlying JSON object - changes. - - @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref - object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, - @ref number_unsigned_t, or @ref number_float_t. - - @return pointer to the internally stored JSON value if the requested - pointer type @a PointerType fits to the JSON value; `nullptr` otherwise - - @complexity Constant. - - @liveexample{The example below shows how pointers to internal values of a - JSON value can be requested. Note that no type conversions are made and a - `nullptr` is returned if the value and the requested pointer type does not - match.,get__PointerType} - - @sa @ref get_ptr() for explicit pointer-member access - - @since version 1.0.0 - */ - template::value, int>::type = 0> - PointerType get() noexcept - { - // delegate the call to get_ptr - return get_ptr(); - } - - /*! - @brief get a pointer value (explicit) - @copydoc get() - */ - template::value, int>::type = 0> - constexpr const PointerType get() const noexcept - { - // delegate the call to get_ptr - return get_ptr(); - } - - /*! - @brief get a pointer value (implicit) - - Implicit pointer access to the internally stored JSON value. No copies are - made. - - @warning Writing data to the pointee of the result yields an undefined - state. - - @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref - object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, - @ref number_unsigned_t, or @ref number_float_t. Enforced by a static - assertion. - - @return pointer to the internally stored JSON value if the requested - pointer type @a PointerType fits to the JSON value; `nullptr` otherwise - - @complexity Constant. - - @liveexample{The example below shows how pointers to internal values of a - JSON value can be requested. Note that no type conversions are made and a - `nullptr` is returned if the value and the requested pointer type does not - match.,get_ptr} - - @since version 1.0.0 - */ - template::value, int>::type = 0> - PointerType get_ptr() noexcept - { - // get the type of the PointerType (remove pointer and const) - using pointee_t = typename std::remove_const::type>::type>::type; - // make sure the type matches the allowed types - static_assert( - std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - , "incompatible pointer type"); - - // delegate the call to get_impl_ptr<>() - return get_impl_ptr(static_cast(nullptr)); - } - - /*! - @brief get a pointer value (implicit) - @copydoc get_ptr() - */ - template::value and - std::is_const::type>::value, int>::type = 0> - constexpr const PointerType get_ptr() const noexcept - { - // get the type of the PointerType (remove pointer and const) - using pointee_t = typename std::remove_const::type>::type>::type; - // make sure the type matches the allowed types - static_assert( - std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - or std::is_same::value - , "incompatible pointer type"); - - // delegate the call to get_impl_ptr<>() const - return get_impl_ptr(static_cast(nullptr)); - } - - /*! - @brief get a reference value (implicit) - - Implicit reference access to the internally stored JSON value. No copies - are made. - - @warning Writing data to the referee of the result yields an undefined - state. - - @tparam ReferenceType reference type; must be a reference to @ref array_t, - @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or - @ref number_float_t. Enforced by static assertion. - - @return reference to the internally stored JSON value if the requested - reference type @a ReferenceType fits to the JSON value; throws - type_error.303 otherwise - - @throw type_error.303 in case passed type @a ReferenceType is incompatible - with the stored JSON value; see example below - - @complexity Constant. - - @liveexample{The example shows several calls to `get_ref()`.,get_ref} - - @since version 1.1.0 - */ - template::value, int>::type = 0> - ReferenceType get_ref() - { - // delegate call to get_ref_impl - return get_ref_impl(*this); - } - - /*! - @brief get a reference value (implicit) - @copydoc get_ref() - */ - template::value and - std::is_const::type>::value, int>::type = 0> - ReferenceType get_ref() const - { - // delegate call to get_ref_impl - return get_ref_impl(*this); - } - - /*! - @brief get a value (implicit) - - Implicit type conversion between the JSON value and a compatible value. - The call is realized by calling @ref get() const. - - @tparam ValueType non-pointer type compatible to the JSON value, for - instance `int` for JSON integer numbers, `bool` for JSON booleans, or - `std::vector` types for JSON arrays. The character type of @ref string_t - as well as an initializer list of this type is excluded to avoid - ambiguities as these types implicitly convert to `std::string`. - - @return copy of the JSON value, converted to type @a ValueType - - @throw type_error.302 in case passed type @a ValueType is incompatible - to the JSON value type (e.g., the JSON value is of type boolean, but a - string is requested); see example below - - @complexity Linear in the size of the JSON value. - - @liveexample{The example below shows several conversions from JSON values - to other types. There a few things to note: (1) Floating-point numbers can - be converted to integers\, (2) A JSON array can be converted to a standard - `std::vector`\, (3) A JSON object can be converted to C++ - associative containers such as `std::unordered_map`.,operator__ValueType} - - @since version 1.0.0 - */ - template < typename ValueType, typename std::enable_if < - not std::is_pointer::value and - not std::is_same>::value and - not std::is_same::value and - not detail::is_basic_json::value -#ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 - and not std::is_same>::value -#if defined(JSON_HAS_CPP_17) && _MSC_VER <= 1914 - and not std::is_same::value -#endif -#endif - , int >::type = 0 > - operator ValueType() const - { - // delegate the call to get<>() const - return get(); - } - - /// @} - - - //////////////////// - // element access // - //////////////////// - - /// @name element access - /// Access to the JSON value. - /// @{ - - /*! - @brief access specified array element with bounds checking - - Returns a reference to the element at specified location @a idx, with - bounds checking. - - @param[in] idx index of the element to access - - @return reference to the element at index @a idx - - @throw type_error.304 if the JSON value is not an array; in this case, - calling `at` with an index makes no sense. See example below. - @throw out_of_range.401 if the index @a idx is out of range of the array; - that is, `idx >= size()`. See example below. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Constant. - - @since version 1.0.0 - - @liveexample{The example below shows how array elements can be read and - written using `at()`. It also demonstrates the different exceptions that - can be thrown.,at__size_type} - */ - reference at(size_type idx) - { - // at only works for arrays - if (JSON_LIKELY(is_array())) - { - JSON_TRY - { - return m_value.array->at(idx); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); - } - } - - /*! - @brief access specified array element with bounds checking - - Returns a const reference to the element at specified location @a idx, - with bounds checking. - - @param[in] idx index of the element to access - - @return const reference to the element at index @a idx - - @throw type_error.304 if the JSON value is not an array; in this case, - calling `at` with an index makes no sense. See example below. - @throw out_of_range.401 if the index @a idx is out of range of the array; - that is, `idx >= size()`. See example below. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Constant. - - @since version 1.0.0 - - @liveexample{The example below shows how array elements can be read using - `at()`. It also demonstrates the different exceptions that can be thrown., - at__size_type_const} - */ - const_reference at(size_type idx) const - { - // at only works for arrays - if (JSON_LIKELY(is_array())) - { - JSON_TRY - { - return m_value.array->at(idx); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); - } - } - - /*! - @brief access specified object element with bounds checking - - Returns a reference to the element at with specified key @a key, with - bounds checking. - - @param[in] key key of the element to access - - @return reference to the element at key @a key - - @throw type_error.304 if the JSON value is not an object; in this case, - calling `at` with a key makes no sense. See example below. - @throw out_of_range.403 if the key @a key is is not stored in the object; - that is, `find(key) == end()`. See example below. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Logarithmic in the size of the container. - - @sa @ref operator[](const typename object_t::key_type&) for unchecked - access by reference - @sa @ref value() for access by value with a default value - - @since version 1.0.0 - - @liveexample{The example below shows how object elements can be read and - written using `at()`. It also demonstrates the different exceptions that - can be thrown.,at__object_t_key_type} - */ - reference at(const typename object_t::key_type& key) - { - // at only works for objects - if (JSON_LIKELY(is_object())) - { - JSON_TRY - { - return m_value.object->at(key); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); - } - } - - /*! - @brief access specified object element with bounds checking - - Returns a const reference to the element at with specified key @a key, - with bounds checking. - - @param[in] key key of the element to access - - @return const reference to the element at key @a key - - @throw type_error.304 if the JSON value is not an object; in this case, - calling `at` with a key makes no sense. See example below. - @throw out_of_range.403 if the key @a key is is not stored in the object; - that is, `find(key) == end()`. See example below. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Logarithmic in the size of the container. - - @sa @ref operator[](const typename object_t::key_type&) for unchecked - access by reference - @sa @ref value() for access by value with a default value - - @since version 1.0.0 - - @liveexample{The example below shows how object elements can be read using - `at()`. It also demonstrates the different exceptions that can be thrown., - at__object_t_key_type_const} - */ - const_reference at(const typename object_t::key_type& key) const - { - // at only works for objects - if (JSON_LIKELY(is_object())) - { - JSON_TRY - { - return m_value.object->at(key); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); - } - } - - /*! - @brief access specified array element - - Returns a reference to the element at specified location @a idx. - - @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), - then the array is silently filled up with `null` values to make `idx` a - valid reference to the last stored element. - - @param[in] idx index of the element to access - - @return reference to the element at index @a idx - - @throw type_error.305 if the JSON value is not an array or null; in that - cases, using the [] operator with an index makes no sense. - - @complexity Constant if @a idx is in the range of the array. Otherwise - linear in `idx - size()`. - - @liveexample{The example below shows how array elements can be read and - written using `[]` operator. Note the addition of `null` - values.,operatorarray__size_type} - - @since version 1.0.0 - */ - reference operator[](size_type idx) - { - // implicitly convert null value to an empty array - if (is_null()) - { - m_type = value_t::array; - m_value.array = create(); - assert_invariant(); - } - - // operator[] only works for arrays - if (JSON_LIKELY(is_array())) - { - // fill up array with null values if given idx is outside range - if (idx >= m_value.array->size()) - { - m_value.array->insert(m_value.array->end(), - idx - m_value.array->size() + 1, - basic_json()); - } - - return m_value.array->operator[](idx); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); - } - - /*! - @brief access specified array element - - Returns a const reference to the element at specified location @a idx. - - @param[in] idx index of the element to access - - @return const reference to the element at index @a idx - - @throw type_error.305 if the JSON value is not an array; in that case, - using the [] operator with an index makes no sense. - - @complexity Constant. - - @liveexample{The example below shows how array elements can be read using - the `[]` operator.,operatorarray__size_type_const} - - @since version 1.0.0 - */ - const_reference operator[](size_type idx) const - { - // const operator[] only works for arrays - if (JSON_LIKELY(is_array())) - { - return m_value.array->operator[](idx); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); - } - - /*! - @brief access specified object element - - Returns a reference to the element at with specified key @a key. - - @note If @a key is not found in the object, then it is silently added to - the object and filled with a `null` value to make `key` a valid reference. - In case the value was `null` before, it is converted to an object. - - @param[in] key key of the element to access - - @return reference to the element at key @a key - - @throw type_error.305 if the JSON value is not an object or null; in that - cases, using the [] operator with a key makes no sense. - - @complexity Logarithmic in the size of the container. - - @liveexample{The example below shows how object elements can be read and - written using the `[]` operator.,operatorarray__key_type} - - @sa @ref at(const typename object_t::key_type&) for access by reference - with range checking - @sa @ref value() for access by value with a default value - - @since version 1.0.0 - */ - reference operator[](const typename object_t::key_type& key) - { - // implicitly convert null value to an empty object - if (is_null()) - { - m_type = value_t::object; - m_value.object = create(); - assert_invariant(); - } - - // operator[] only works for objects - if (JSON_LIKELY(is_object())) - { - return m_value.object->operator[](key); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); - } - - /*! - @brief read-only access specified object element - - Returns a const reference to the element at with specified key @a key. No - bounds checking is performed. - - @warning If the element with key @a key does not exist, the behavior is - undefined. - - @param[in] key key of the element to access - - @return const reference to the element at key @a key - - @pre The element with key @a key must exist. **This precondition is - enforced with an assertion.** - - @throw type_error.305 if the JSON value is not an object; in that case, - using the [] operator with a key makes no sense. - - @complexity Logarithmic in the size of the container. - - @liveexample{The example below shows how object elements can be read using - the `[]` operator.,operatorarray__key_type_const} - - @sa @ref at(const typename object_t::key_type&) for access by reference - with range checking - @sa @ref value() for access by value with a default value - - @since version 1.0.0 - */ - const_reference operator[](const typename object_t::key_type& key) const - { - // const operator[] only works for objects - if (JSON_LIKELY(is_object())) - { - assert(m_value.object->find(key) != m_value.object->end()); - return m_value.object->find(key)->second; - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); - } - - /*! - @brief access specified object element - - Returns a reference to the element at with specified key @a key. - - @note If @a key is not found in the object, then it is silently added to - the object and filled with a `null` value to make `key` a valid reference. - In case the value was `null` before, it is converted to an object. - - @param[in] key key of the element to access - - @return reference to the element at key @a key - - @throw type_error.305 if the JSON value is not an object or null; in that - cases, using the [] operator with a key makes no sense. - - @complexity Logarithmic in the size of the container. - - @liveexample{The example below shows how object elements can be read and - written using the `[]` operator.,operatorarray__key_type} - - @sa @ref at(const typename object_t::key_type&) for access by reference - with range checking - @sa @ref value() for access by value with a default value - - @since version 1.1.0 - */ - template - reference operator[](T* key) - { - // implicitly convert null to object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // at only works for objects - if (JSON_LIKELY(is_object())) - { - return m_value.object->operator[](key); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); - } - - /*! - @brief read-only access specified object element - - Returns a const reference to the element at with specified key @a key. No - bounds checking is performed. - - @warning If the element with key @a key does not exist, the behavior is - undefined. - - @param[in] key key of the element to access - - @return const reference to the element at key @a key - - @pre The element with key @a key must exist. **This precondition is - enforced with an assertion.** - - @throw type_error.305 if the JSON value is not an object; in that case, - using the [] operator with a key makes no sense. - - @complexity Logarithmic in the size of the container. - - @liveexample{The example below shows how object elements can be read using - the `[]` operator.,operatorarray__key_type_const} - - @sa @ref at(const typename object_t::key_type&) for access by reference - with range checking - @sa @ref value() for access by value with a default value - - @since version 1.1.0 - */ - template - const_reference operator[](T* key) const - { - // at only works for objects - if (JSON_LIKELY(is_object())) - { - assert(m_value.object->find(key) != m_value.object->end()); - return m_value.object->find(key)->second; - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); - } - - /*! - @brief access specified object element with default value - - Returns either a copy of an object's element at the specified key @a key - or a given default value if no element with key @a key exists. - - The function is basically equivalent to executing - @code {.cpp} - try { - return at(key); - } catch(out_of_range) { - return default_value; - } - @endcode - - @note Unlike @ref at(const typename object_t::key_type&), this function - does not throw if the given key @a key was not found. - - @note Unlike @ref operator[](const typename object_t::key_type& key), this - function does not implicitly add an element to the position defined by @a - key. This function is furthermore also applicable to const objects. - - @param[in] key key of the element to access - @param[in] default_value the value to return if @a key is not found - - @tparam ValueType type compatible to JSON values, for instance `int` for - JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for - JSON arrays. Note the type of the expected value at @a key and the default - value @a default_value must be compatible. - - @return copy of the element at key @a key or @a default_value if @a key - is not found - - @throw type_error.306 if the JSON value is not an object; in that case, - using `value()` with a key makes no sense. - - @complexity Logarithmic in the size of the container. - - @liveexample{The example below shows how object elements can be queried - with a default value.,basic_json__value} - - @sa @ref at(const typename object_t::key_type&) for access by reference - with range checking - @sa @ref operator[](const typename object_t::key_type&) for unchecked - access by reference - - @since version 1.0.0 - */ - template::value, int>::type = 0> - ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const - { - // at only works for objects - if (JSON_LIKELY(is_object())) - { - // if key is found, return value and given default value otherwise - const auto it = find(key); - if (it != end()) - { - return *it; - } - - return default_value; - } - - JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); - } - - /*! - @brief overload for a default value of type const char* - @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const - */ - string_t value(const typename object_t::key_type& key, const char* default_value) const - { - return value(key, string_t(default_value)); - } - - /*! - @brief access specified object element via JSON Pointer with default value - - Returns either a copy of an object's element at the specified key @a key - or a given default value if no element with key @a key exists. - - The function is basically equivalent to executing - @code {.cpp} - try { - return at(ptr); - } catch(out_of_range) { - return default_value; - } - @endcode - - @note Unlike @ref at(const json_pointer&), this function does not throw - if the given key @a key was not found. - - @param[in] ptr a JSON pointer to the element to access - @param[in] default_value the value to return if @a ptr found no value - - @tparam ValueType type compatible to JSON values, for instance `int` for - JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for - JSON arrays. Note the type of the expected value at @a key and the default - value @a default_value must be compatible. - - @return copy of the element at key @a key or @a default_value if @a key - is not found - - @throw type_error.306 if the JSON value is not an object; in that case, - using `value()` with a key makes no sense. - - @complexity Logarithmic in the size of the container. - - @liveexample{The example below shows how object elements can be queried - with a default value.,basic_json__value_ptr} - - @sa @ref operator[](const json_pointer&) for unchecked access by reference - - @since version 2.0.2 - */ - template::value, int>::type = 0> - ValueType value(const json_pointer& ptr, const ValueType& default_value) const - { - // at only works for objects - if (JSON_LIKELY(is_object())) - { - // if pointer resolves a value, return it or use default value - JSON_TRY - { - return ptr.get_checked(this); - } - JSON_CATCH (out_of_range&) - { - return default_value; - } - } - - JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); - } - - /*! - @brief overload for a default value of type const char* - @copydoc basic_json::value(const json_pointer&, ValueType) const - */ - string_t value(const json_pointer& ptr, const char* default_value) const - { - return value(ptr, string_t(default_value)); - } - - /*! - @brief access the first element - - Returns a reference to the first element in the container. For a JSON - container `c`, the expression `c.front()` is equivalent to `*c.begin()`. - - @return In case of a structured type (array or object), a reference to the - first element is returned. In case of number, string, or boolean values, a - reference to the value is returned. - - @complexity Constant. - - @pre The JSON value must not be `null` (would throw `std::out_of_range`) - or an empty array or object (undefined behavior, **guarded by - assertions**). - @post The JSON value remains unchanged. - - @throw invalid_iterator.214 when called on `null` value - - @liveexample{The following code shows an example for `front()`.,front} - - @sa @ref back() -- access the last element - - @since version 1.0.0 - */ - reference front() - { - return *begin(); - } - - /*! - @copydoc basic_json::front() - */ - const_reference front() const - { - return *cbegin(); - } - - /*! - @brief access the last element - - Returns a reference to the last element in the container. For a JSON - container `c`, the expression `c.back()` is equivalent to - @code {.cpp} - auto tmp = c.end(); - --tmp; - return *tmp; - @endcode - - @return In case of a structured type (array or object), a reference to the - last element is returned. In case of number, string, or boolean values, a - reference to the value is returned. - - @complexity Constant. - - @pre The JSON value must not be `null` (would throw `std::out_of_range`) - or an empty array or object (undefined behavior, **guarded by - assertions**). - @post The JSON value remains unchanged. - - @throw invalid_iterator.214 when called on a `null` value. See example - below. - - @liveexample{The following code shows an example for `back()`.,back} - - @sa @ref front() -- access the first element - - @since version 1.0.0 - */ - reference back() - { - auto tmp = end(); - --tmp; - return *tmp; - } - - /*! - @copydoc basic_json::back() - */ - const_reference back() const - { - auto tmp = cend(); - --tmp; - return *tmp; - } - - /*! - @brief remove element given an iterator - - Removes the element specified by iterator @a pos. The iterator @a pos must - be valid and dereferenceable. Thus the `end()` iterator (which is valid, - but is not dereferenceable) cannot be used as a value for @a pos. - - If called on a primitive type other than `null`, the resulting JSON value - will be `null`. - - @param[in] pos iterator to the element to remove - @return Iterator following the last removed element. If the iterator @a - pos refers to the last element, the `end()` iterator is returned. - - @tparam IteratorType an @ref iterator or @ref const_iterator - - @post Invalidates iterators and references at or after the point of the - erase, including the `end()` iterator. - - @throw type_error.307 if called on a `null` value; example: `"cannot use - erase() with null"` - @throw invalid_iterator.202 if called on an iterator which does not belong - to the current JSON value; example: `"iterator does not fit current - value"` - @throw invalid_iterator.205 if called on a primitive type with invalid - iterator (i.e., any iterator which is not `begin()`); example: `"iterator - out of range"` - - @complexity The complexity depends on the type: - - objects: amortized constant - - arrays: linear in distance between @a pos and the end of the container - - strings: linear in the length of the string - - other types: constant - - @liveexample{The example shows the result of `erase()` for different JSON - types.,erase__IteratorType} - - @sa @ref erase(IteratorType, IteratorType) -- removes the elements in - the given range - @sa @ref erase(const typename object_t::key_type&) -- removes the element - from an object at the given key - @sa @ref erase(const size_type) -- removes the element from an array at - the given index - - @since version 1.0.0 - */ - template::value or - std::is_same::value, int>::type - = 0> - IteratorType erase(IteratorType pos) - { - // make sure iterator fits the current value - if (JSON_UNLIKELY(this != pos.m_object)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); - } - - IteratorType result = end(); - - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - { - if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin())) - { - JSON_THROW(invalid_iterator::create(205, "iterator out of range")); - } - - if (is_string()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.string); - std::allocator_traits::deallocate(alloc, m_value.string, 1); - m_value.string = nullptr; - } - - m_type = value_t::null; - assert_invariant(); - break; - } - - case value_t::object: - { - result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); - break; - } - - case value_t::array: - { - result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); - break; - } - - default: - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); - } - - return result; - } - - /*! - @brief remove elements given an iterator range - - Removes the element specified by the range `[first; last)`. The iterator - @a first does not need to be dereferenceable if `first == last`: erasing - an empty range is a no-op. - - If called on a primitive type other than `null`, the resulting JSON value - will be `null`. - - @param[in] first iterator to the beginning of the range to remove - @param[in] last iterator past the end of the range to remove - @return Iterator following the last removed element. If the iterator @a - second refers to the last element, the `end()` iterator is returned. - - @tparam IteratorType an @ref iterator or @ref const_iterator - - @post Invalidates iterators and references at or after the point of the - erase, including the `end()` iterator. - - @throw type_error.307 if called on a `null` value; example: `"cannot use - erase() with null"` - @throw invalid_iterator.203 if called on iterators which does not belong - to the current JSON value; example: `"iterators do not fit current value"` - @throw invalid_iterator.204 if called on a primitive type with invalid - iterators (i.e., if `first != begin()` and `last != end()`); example: - `"iterators out of range"` - - @complexity The complexity depends on the type: - - objects: `log(size()) + std::distance(first, last)` - - arrays: linear in the distance between @a first and @a last, plus linear - in the distance between @a last and end of the container - - strings: linear in the length of the string - - other types: constant - - @liveexample{The example shows the result of `erase()` for different JSON - types.,erase__IteratorType_IteratorType} - - @sa @ref erase(IteratorType) -- removes the element at a given position - @sa @ref erase(const typename object_t::key_type&) -- removes the element - from an object at the given key - @sa @ref erase(const size_type) -- removes the element from an array at - the given index - - @since version 1.0.0 - */ - template::value or - std::is_same::value, int>::type - = 0> - IteratorType erase(IteratorType first, IteratorType last) - { - // make sure iterator fits the current value - if (JSON_UNLIKELY(this != first.m_object or this != last.m_object)) - { - JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); - } - - IteratorType result = end(); - - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - { - if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin() - or not last.m_it.primitive_iterator.is_end())) - { - JSON_THROW(invalid_iterator::create(204, "iterators out of range")); - } - - if (is_string()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.string); - std::allocator_traits::deallocate(alloc, m_value.string, 1); - m_value.string = nullptr; - } - - m_type = value_t::null; - assert_invariant(); - break; - } - - case value_t::object: - { - result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, - last.m_it.object_iterator); - break; - } - - case value_t::array: - { - result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, - last.m_it.array_iterator); - break; - } - - default: - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); - } - - return result; - } - - /*! - @brief remove element from a JSON object given a key - - Removes elements from a JSON object with the key value @a key. - - @param[in] key value of the elements to remove - - @return Number of elements removed. If @a ObjectType is the default - `std::map` type, the return value will always be `0` (@a key was not - found) or `1` (@a key was found). - - @post References and iterators to the erased elements are invalidated. - Other references and iterators are not affected. - - @throw type_error.307 when called on a type other than JSON object; - example: `"cannot use erase() with null"` - - @complexity `log(size()) + count(key)` - - @liveexample{The example shows the effect of `erase()`.,erase__key_type} - - @sa @ref erase(IteratorType) -- removes the element at a given position - @sa @ref erase(IteratorType, IteratorType) -- removes the elements in - the given range - @sa @ref erase(const size_type) -- removes the element from an array at - the given index - - @since version 1.0.0 - */ - size_type erase(const typename object_t::key_type& key) - { - // this erase only works for objects - if (JSON_LIKELY(is_object())) - { - return m_value.object->erase(key); - } - - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); - } - - /*! - @brief remove element from a JSON array given an index - - Removes element from a JSON array at the index @a idx. - - @param[in] idx index of the element to remove - - @throw type_error.307 when called on a type other than JSON object; - example: `"cannot use erase() with null"` - @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 - is out of range"` - - @complexity Linear in distance between @a idx and the end of the container. - - @liveexample{The example shows the effect of `erase()`.,erase__size_type} - - @sa @ref erase(IteratorType) -- removes the element at a given position - @sa @ref erase(IteratorType, IteratorType) -- removes the elements in - the given range - @sa @ref erase(const typename object_t::key_type&) -- removes the element - from an object at the given key - - @since version 1.0.0 - */ - void erase(const size_type idx) - { - // this erase only works for arrays - if (JSON_LIKELY(is_array())) - { - if (JSON_UNLIKELY(idx >= size())) - { - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); - } - - m_value.array->erase(m_value.array->begin() + static_cast(idx)); - } - else - { - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); - } - } - - /// @} - - - //////////// - // lookup // - //////////// - - /// @name lookup - /// @{ - - /*! - @brief find an element in a JSON object - - Finds an element in a JSON object with key equivalent to @a key. If the - element is not found or the JSON value is not an object, end() is - returned. - - @note This method always returns @ref end() when executed on a JSON type - that is not an object. - - @param[in] key key value of the element to search for. - - @return Iterator to an element with key equivalent to @a key. If no such - element is found or the JSON value is not an object, past-the-end (see - @ref end()) iterator is returned. - - @complexity Logarithmic in the size of the JSON object. - - @liveexample{The example shows how `find()` is used.,find__key_type} - - @since version 1.0.0 - */ - template - iterator find(KeyT&& key) - { - auto result = end(); - - if (is_object()) - { - result.m_it.object_iterator = m_value.object->find(std::forward(key)); - } - - return result; - } - - /*! - @brief find an element in a JSON object - @copydoc find(KeyT&&) - */ - template - const_iterator find(KeyT&& key) const - { - auto result = cend(); - - if (is_object()) - { - result.m_it.object_iterator = m_value.object->find(std::forward(key)); - } - - return result; - } - - /*! - @brief returns the number of occurrences of a key in a JSON object - - Returns the number of elements with key @a key. If ObjectType is the - default `std::map` type, the return value will always be `0` (@a key was - not found) or `1` (@a key was found). - - @note This method always returns `0` when executed on a JSON type that is - not an object. - - @param[in] key key value of the element to count - - @return Number of elements with key @a key. If the JSON value is not an - object, the return value will be `0`. - - @complexity Logarithmic in the size of the JSON object. - - @liveexample{The example shows how `count()` is used.,count} - - @since version 1.0.0 - */ - template - size_type count(KeyT&& key) const - { - // return 0 for all nonobject types - return is_object() ? m_value.object->count(std::forward(key)) : 0; - } - - /// @} - - - /////////////// - // iterators // - /////////////// - - /// @name iterators - /// @{ - - /*! - @brief returns an iterator to the first element - - Returns an iterator to the first element. - - @image html range-begin-end.svg "Illustration from cppreference.com" - - @return iterator to the first element - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is constant. - - @liveexample{The following code shows an example for `begin()`.,begin} - - @sa @ref cbegin() -- returns a const iterator to the beginning - @sa @ref end() -- returns an iterator to the end - @sa @ref cend() -- returns a const iterator to the end - - @since version 1.0.0 - */ - iterator begin() noexcept - { - iterator result(this); - result.set_begin(); - return result; - } - - /*! - @copydoc basic_json::cbegin() - */ - const_iterator begin() const noexcept - { - return cbegin(); - } - - /*! - @brief returns a const iterator to the first element - - Returns a const iterator to the first element. - - @image html range-begin-end.svg "Illustration from cppreference.com" - - @return const iterator to the first element - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is constant. - - Has the semantics of `const_cast(*this).begin()`. - - @liveexample{The following code shows an example for `cbegin()`.,cbegin} - - @sa @ref begin() -- returns an iterator to the beginning - @sa @ref end() -- returns an iterator to the end - @sa @ref cend() -- returns a const iterator to the end - - @since version 1.0.0 - */ - const_iterator cbegin() const noexcept - { - const_iterator result(this); - result.set_begin(); - return result; - } - - /*! - @brief returns an iterator to one past the last element - - Returns an iterator to one past the last element. - - @image html range-begin-end.svg "Illustration from cppreference.com" - - @return iterator one past the last element - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is constant. - - @liveexample{The following code shows an example for `end()`.,end} - - @sa @ref cend() -- returns a const iterator to the end - @sa @ref begin() -- returns an iterator to the beginning - @sa @ref cbegin() -- returns a const iterator to the beginning - - @since version 1.0.0 - */ - iterator end() noexcept - { - iterator result(this); - result.set_end(); - return result; - } - - /*! - @copydoc basic_json::cend() - */ - const_iterator end() const noexcept - { - return cend(); - } - - /*! - @brief returns a const iterator to one past the last element - - Returns a const iterator to one past the last element. - - @image html range-begin-end.svg "Illustration from cppreference.com" - - @return const iterator one past the last element - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is constant. - - Has the semantics of `const_cast(*this).end()`. - - @liveexample{The following code shows an example for `cend()`.,cend} - - @sa @ref end() -- returns an iterator to the end - @sa @ref begin() -- returns an iterator to the beginning - @sa @ref cbegin() -- returns a const iterator to the beginning - - @since version 1.0.0 - */ - const_iterator cend() const noexcept - { - const_iterator result(this); - result.set_end(); - return result; - } - - /*! - @brief returns an iterator to the reverse-beginning - - Returns an iterator to the reverse-beginning; that is, the last element. - - @image html range-rbegin-rend.svg "Illustration from cppreference.com" - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) - requirements: - - The complexity is constant. - - Has the semantics of `reverse_iterator(end())`. - - @liveexample{The following code shows an example for `rbegin()`.,rbegin} - - @sa @ref crbegin() -- returns a const reverse iterator to the beginning - @sa @ref rend() -- returns a reverse iterator to the end - @sa @ref crend() -- returns a const reverse iterator to the end - - @since version 1.0.0 - */ - reverse_iterator rbegin() noexcept - { - return reverse_iterator(end()); - } - - /*! - @copydoc basic_json::crbegin() - */ - const_reverse_iterator rbegin() const noexcept - { - return crbegin(); - } - - /*! - @brief returns an iterator to the reverse-end - - Returns an iterator to the reverse-end; that is, one before the first - element. - - @image html range-rbegin-rend.svg "Illustration from cppreference.com" - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) - requirements: - - The complexity is constant. - - Has the semantics of `reverse_iterator(begin())`. - - @liveexample{The following code shows an example for `rend()`.,rend} - - @sa @ref crend() -- returns a const reverse iterator to the end - @sa @ref rbegin() -- returns a reverse iterator to the beginning - @sa @ref crbegin() -- returns a const reverse iterator to the beginning - - @since version 1.0.0 - */ - reverse_iterator rend() noexcept - { - return reverse_iterator(begin()); - } - - /*! - @copydoc basic_json::crend() - */ - const_reverse_iterator rend() const noexcept - { - return crend(); - } - - /*! - @brief returns a const reverse iterator to the last element - - Returns a const iterator to the reverse-beginning; that is, the last - element. - - @image html range-rbegin-rend.svg "Illustration from cppreference.com" - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) - requirements: - - The complexity is constant. - - Has the semantics of `const_cast(*this).rbegin()`. - - @liveexample{The following code shows an example for `crbegin()`.,crbegin} - - @sa @ref rbegin() -- returns a reverse iterator to the beginning - @sa @ref rend() -- returns a reverse iterator to the end - @sa @ref crend() -- returns a const reverse iterator to the end - - @since version 1.0.0 - */ - const_reverse_iterator crbegin() const noexcept - { - return const_reverse_iterator(cend()); - } - - /*! - @brief returns a const reverse iterator to one before the first - - Returns a const reverse iterator to the reverse-end; that is, one before - the first element. - - @image html range-rbegin-rend.svg "Illustration from cppreference.com" - - @complexity Constant. - - @requirement This function helps `basic_json` satisfying the - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) - requirements: - - The complexity is constant. - - Has the semantics of `const_cast(*this).rend()`. - - @liveexample{The following code shows an example for `crend()`.,crend} - - @sa @ref rend() -- returns a reverse iterator to the end - @sa @ref rbegin() -- returns a reverse iterator to the beginning - @sa @ref crbegin() -- returns a const reverse iterator to the beginning - - @since version 1.0.0 - */ - const_reverse_iterator crend() const noexcept - { - return const_reverse_iterator(cbegin()); - } - - public: - /*! - @brief wrapper to access iterator member functions in range-based for - - This function allows to access @ref iterator::key() and @ref - iterator::value() during range-based for loops. In these loops, a - reference to the JSON values is returned, so there is no access to the - underlying iterator. - - For loop without iterator_wrapper: - - @code{cpp} - for (auto it = j_object.begin(); it != j_object.end(); ++it) - { - std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; - } - @endcode - - Range-based for loop without iterator proxy: - - @code{cpp} - for (auto it : j_object) - { - // "it" is of type json::reference and has no key() member - std::cout << "value: " << it << '\n'; - } - @endcode - - Range-based for loop with iterator proxy: - - @code{cpp} - for (auto it : json::iterator_wrapper(j_object)) - { - std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; - } - @endcode - - @note When iterating over an array, `key()` will return the index of the - element as string (see example). - - @param[in] ref reference to a JSON value - @return iteration proxy object wrapping @a ref with an interface to use in - range-based for loops - - @liveexample{The following code shows how the wrapper is used,iterator_wrapper} - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Constant. - - @note The name of this function is not yet final and may change in the - future. - - @deprecated This stream operator is deprecated and will be removed in - future 4.0.0 of the library. Please use @ref items() instead; - that is, replace `json::iterator_wrapper(j)` with `j.items()`. - */ - JSON_DEPRECATED - static iteration_proxy iterator_wrapper(reference ref) noexcept - { - return ref.items(); - } - - /*! - @copydoc iterator_wrapper(reference) - */ - JSON_DEPRECATED - static iteration_proxy iterator_wrapper(const_reference ref) noexcept - { - return ref.items(); - } - - /*! - @brief helper to access iterator member functions in range-based for - - This function allows to access @ref iterator::key() and @ref - iterator::value() during range-based for loops. In these loops, a - reference to the JSON values is returned, so there is no access to the - underlying iterator. - - For loop without `items()` function: - - @code{cpp} - for (auto it = j_object.begin(); it != j_object.end(); ++it) - { - std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; - } - @endcode - - Range-based for loop without `items()` function: - - @code{cpp} - for (auto it : j_object) - { - // "it" is of type json::reference and has no key() member - std::cout << "value: " << it << '\n'; - } - @endcode - - Range-based for loop with `items()` function: - - @code{cpp} - for (auto it : j_object.items()) - { - std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; - } - @endcode - - @note When iterating over an array, `key()` will return the index of the - element as string (see example). For primitive types (e.g., numbers), - `key()` returns an empty string. - - @return iteration proxy object wrapping @a ref with an interface to use in - range-based for loops - - @liveexample{The following code shows how the function is used.,items} - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Constant. - - @since version 3.1.0. - */ - iteration_proxy items() noexcept - { - return iteration_proxy(*this); - } - - /*! - @copydoc items() - */ - iteration_proxy items() const noexcept - { - return iteration_proxy(*this); - } - - /// @} - - - ////////////// - // capacity // - ////////////// - - /// @name capacity - /// @{ - - /*! - @brief checks whether the container is empty. - - Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). - - @return The return value depends on the different types and is - defined as follows: - Value type | return value - ----------- | ------------- - null | `true` - boolean | `false` - string | `false` - number | `false` - object | result of function `object_t::empty()` - array | result of function `array_t::empty()` - - @liveexample{The following code uses `empty()` to check if a JSON - object contains any elements.,empty} - - @complexity Constant, as long as @ref array_t and @ref object_t satisfy - the Container concept; that is, their `empty()` functions have constant - complexity. - - @iterators No changes. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @note This function does not return whether a string stored as JSON value - is empty - it returns whether the JSON container itself is empty which is - false in the case of a string. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is constant. - - Has the semantics of `begin() == end()`. - - @sa @ref size() -- returns the number of elements - - @since version 1.0.0 - */ - bool empty() const noexcept - { - switch (m_type) - { - case value_t::null: - { - // null values are empty - return true; - } - - case value_t::array: - { - // delegate call to array_t::empty() - return m_value.array->empty(); - } - - case value_t::object: - { - // delegate call to object_t::empty() - return m_value.object->empty(); - } - - default: - { - // all other types are nonempty - return false; - } - } - } - - /*! - @brief returns the number of elements - - Returns the number of elements in a JSON value. - - @return The return value depends on the different types and is - defined as follows: - Value type | return value - ----------- | ------------- - null | `0` - boolean | `1` - string | `1` - number | `1` - object | result of function object_t::size() - array | result of function array_t::size() - - @liveexample{The following code calls `size()` on the different value - types.,size} - - @complexity Constant, as long as @ref array_t and @ref object_t satisfy - the Container concept; that is, their size() functions have constant - complexity. - - @iterators No changes. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @note This function does not return the length of a string stored as JSON - value - it returns the number of elements in the JSON value which is 1 in - the case of a string. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is constant. - - Has the semantics of `std::distance(begin(), end())`. - - @sa @ref empty() -- checks whether the container is empty - @sa @ref max_size() -- returns the maximal number of elements - - @since version 1.0.0 - */ - size_type size() const noexcept - { - switch (m_type) - { - case value_t::null: - { - // null values are empty - return 0; - } - - case value_t::array: - { - // delegate call to array_t::size() - return m_value.array->size(); - } - - case value_t::object: - { - // delegate call to object_t::size() - return m_value.object->size(); - } - - default: - { - // all other types have size 1 - return 1; - } - } - } - - /*! - @brief returns the maximum possible number of elements - - Returns the maximum number of elements a JSON value is able to hold due to - system or library implementation limitations, i.e. `std::distance(begin(), - end())` for the JSON value. - - @return The return value depends on the different types and is - defined as follows: - Value type | return value - ----------- | ------------- - null | `0` (same as `size()`) - boolean | `1` (same as `size()`) - string | `1` (same as `size()`) - number | `1` (same as `size()`) - object | result of function `object_t::max_size()` - array | result of function `array_t::max_size()` - - @liveexample{The following code calls `max_size()` on the different value - types. Note the output is implementation specific.,max_size} - - @complexity Constant, as long as @ref array_t and @ref object_t satisfy - the Container concept; that is, their `max_size()` functions have constant - complexity. - - @iterators No changes. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @requirement This function helps `basic_json` satisfying the - [Container](https://en.cppreference.com/w/cpp/named_req/Container) - requirements: - - The complexity is constant. - - Has the semantics of returning `b.size()` where `b` is the largest - possible JSON value. - - @sa @ref size() -- returns the number of elements - - @since version 1.0.0 - */ - size_type max_size() const noexcept - { - switch (m_type) - { - case value_t::array: - { - // delegate call to array_t::max_size() - return m_value.array->max_size(); - } - - case value_t::object: - { - // delegate call to object_t::max_size() - return m_value.object->max_size(); - } - - default: - { - // all other types have max_size() == size() - return size(); - } - } - } - - /// @} - - - /////////////// - // modifiers // - /////////////// - - /// @name modifiers - /// @{ - - /*! - @brief clears the contents - - Clears the content of a JSON value and resets it to the default value as - if @ref basic_json(value_t) would have been called with the current value - type from @ref type(): - - Value type | initial value - ----------- | ------------- - null | `null` - boolean | `false` - string | `""` - number | `0` - object | `{}` - array | `[]` - - @post Has the same effect as calling - @code {.cpp} - *this = basic_json(type()); - @endcode - - @liveexample{The example below shows the effect of `clear()` to different - JSON types.,clear} - - @complexity Linear in the size of the JSON value. - - @iterators All iterators, pointers and references related to this container - are invalidated. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @sa @ref basic_json(value_t) -- constructor that creates an object with the - same value than calling `clear()` - - @since version 1.0.0 - */ - void clear() noexcept - { - switch (m_type) - { - case value_t::number_integer: - { - m_value.number_integer = 0; - break; - } - - case value_t::number_unsigned: - { - m_value.number_unsigned = 0; - break; - } - - case value_t::number_float: - { - m_value.number_float = 0.0; - break; - } - - case value_t::boolean: - { - m_value.boolean = false; - break; - } - - case value_t::string: - { - m_value.string->clear(); - break; - } - - case value_t::array: - { - m_value.array->clear(); - break; - } - - case value_t::object: - { - m_value.object->clear(); - break; - } - - default: - break; - } - } - - /*! - @brief add an object to an array - - Appends the given element @a val to the end of the JSON value. If the - function is called on a JSON null value, an empty array is created before - appending @a val. - - @param[in] val the value to add to the JSON array - - @throw type_error.308 when called on a type other than JSON array or - null; example: `"cannot use push_back() with number"` - - @complexity Amortized constant. - - @liveexample{The example shows how `push_back()` and `+=` can be used to - add elements to a JSON array. Note how the `null` value was silently - converted to a JSON array.,push_back} - - @since version 1.0.0 - */ - void push_back(basic_json&& val) - { - // push_back only works for null objects or arrays - if (JSON_UNLIKELY(not(is_null() or is_array()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array (move semantics) - m_value.array->push_back(std::move(val)); - // invalidate object - val.m_type = value_t::null; - } - - /*! - @brief add an object to an array - @copydoc push_back(basic_json&&) - */ - reference operator+=(basic_json&& val) - { - push_back(std::move(val)); - return *this; - } - - /*! - @brief add an object to an array - @copydoc push_back(basic_json&&) - */ - void push_back(const basic_json& val) - { - // push_back only works for null objects or arrays - if (JSON_UNLIKELY(not(is_null() or is_array()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array - m_value.array->push_back(val); - } - - /*! - @brief add an object to an array - @copydoc push_back(basic_json&&) - */ - reference operator+=(const basic_json& val) - { - push_back(val); - return *this; - } - - /*! - @brief add an object to an object - - Inserts the given element @a val to the JSON object. If the function is - called on a JSON null value, an empty object is created before inserting - @a val. - - @param[in] val the value to add to the JSON object - - @throw type_error.308 when called on a type other than JSON object or - null; example: `"cannot use push_back() with number"` - - @complexity Logarithmic in the size of the container, O(log(`size()`)). - - @liveexample{The example shows how `push_back()` and `+=` can be used to - add elements to a JSON object. Note how the `null` value was silently - converted to a JSON object.,push_back__object_t__value} - - @since version 1.0.0 - */ - void push_back(const typename object_t::value_type& val) - { - // push_back only works for null objects or objects - if (JSON_UNLIKELY(not(is_null() or is_object()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); - } - - // transform null object into an object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // add element to array - m_value.object->insert(val); - } - - /*! - @brief add an object to an object - @copydoc push_back(const typename object_t::value_type&) - */ - reference operator+=(const typename object_t::value_type& val) - { - push_back(val); - return *this; - } - - /*! - @brief add an object to an object - - This function allows to use `push_back` with an initializer list. In case - - 1. the current value is an object, - 2. the initializer list @a init contains only two elements, and - 3. the first element of @a init is a string, - - @a init is converted into an object element and added using - @ref push_back(const typename object_t::value_type&). Otherwise, @a init - is converted to a JSON value and added using @ref push_back(basic_json&&). - - @param[in] init an initializer list - - @complexity Linear in the size of the initializer list @a init. - - @note This function is required to resolve an ambiguous overload error, - because pairs like `{"key", "value"}` can be both interpreted as - `object_t::value_type` or `std::initializer_list`, see - https://github.com/nlohmann/json/issues/235 for more information. - - @liveexample{The example shows how initializer lists are treated as - objects when possible.,push_back__initializer_list} - */ - void push_back(initializer_list_t init) - { - if (is_object() and init.size() == 2 and (*init.begin())->is_string()) - { - basic_json&& key = init.begin()->moved_or_copied(); - push_back(typename object_t::value_type( - std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); - } - else - { - push_back(basic_json(init)); - } - } - - /*! - @brief add an object to an object - @copydoc push_back(initializer_list_t) - */ - reference operator+=(initializer_list_t init) - { - push_back(init); - return *this; - } - - /*! - @brief add an object to an array - - Creates a JSON value from the passed parameters @a args to the end of the - JSON value. If the function is called on a JSON null value, an empty array - is created before appending the value created from @a args. - - @param[in] args arguments to forward to a constructor of @ref basic_json - @tparam Args compatible types to create a @ref basic_json object - - @throw type_error.311 when called on a type other than JSON array or - null; example: `"cannot use emplace_back() with number"` - - @complexity Amortized constant. - - @liveexample{The example shows how `push_back()` can be used to add - elements to a JSON array. Note how the `null` value was silently converted - to a JSON array.,emplace_back} - - @since version 2.0.8 - */ - template - void emplace_back(Args&& ... args) - { - // emplace_back only works for null objects or arrays - if (JSON_UNLIKELY(not(is_null() or is_array()))) - { - JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()))); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array (perfect forwarding) - m_value.array->emplace_back(std::forward(args)...); - } - - /*! - @brief add an object to an object if key does not exist - - Inserts a new element into a JSON object constructed in-place with the - given @a args if there is no element with the key in the container. If the - function is called on a JSON null value, an empty object is created before - appending the value created from @a args. - - @param[in] args arguments to forward to a constructor of @ref basic_json - @tparam Args compatible types to create a @ref basic_json object - - @return a pair consisting of an iterator to the inserted element, or the - already-existing element if no insertion happened, and a bool - denoting whether the insertion took place. - - @throw type_error.311 when called on a type other than JSON object or - null; example: `"cannot use emplace() with number"` - - @complexity Logarithmic in the size of the container, O(log(`size()`)). - - @liveexample{The example shows how `emplace()` can be used to add elements - to a JSON object. Note how the `null` value was silently converted to a - JSON object. Further note how no value is added if there was already one - value stored with the same key.,emplace} - - @since version 2.0.8 - */ - template - std::pair emplace(Args&& ... args) - { - // emplace only works for null objects or arrays - if (JSON_UNLIKELY(not(is_null() or is_object()))) - { - JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()))); - } - - // transform null object into an object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // add element to array (perfect forwarding) - auto res = m_value.object->emplace(std::forward(args)...); - // create result iterator and set iterator to the result of emplace - auto it = begin(); - it.m_it.object_iterator = res.first; - - // return pair of iterator and boolean - return {it, res.second}; - } - - /*! - @brief inserts element - - Inserts element @a val before iterator @a pos. - - @param[in] pos iterator before which the content will be inserted; may be - the end() iterator - @param[in] val element to insert - @return iterator pointing to the inserted @a val. - - @throw type_error.309 if called on JSON values other than arrays; - example: `"cannot use insert() with string"` - @throw invalid_iterator.202 if @a pos is not an iterator of *this; - example: `"iterator does not fit current value"` - - @complexity Constant plus linear in the distance between @a pos and end of - the container. - - @liveexample{The example shows how `insert()` is used.,insert} - - @since version 1.0.0 - */ - iterator insert(const_iterator pos, const basic_json& val) - { - // insert only works for arrays - if (JSON_LIKELY(is_array())) - { - // check if iterator pos fits to this JSON value - if (JSON_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); - } - - // insert to array and return iterator - iterator result(this); - result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); - return result; - } - - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); - } - - /*! - @brief inserts element - @copydoc insert(const_iterator, const basic_json&) - */ - iterator insert(const_iterator pos, basic_json&& val) - { - return insert(pos, val); - } - - /*! - @brief inserts elements - - Inserts @a cnt copies of @a val before iterator @a pos. - - @param[in] pos iterator before which the content will be inserted; may be - the end() iterator - @param[in] cnt number of copies of @a val to insert - @param[in] val element to insert - @return iterator pointing to the first element inserted, or @a pos if - `cnt==0` - - @throw type_error.309 if called on JSON values other than arrays; example: - `"cannot use insert() with string"` - @throw invalid_iterator.202 if @a pos is not an iterator of *this; - example: `"iterator does not fit current value"` - - @complexity Linear in @a cnt plus linear in the distance between @a pos - and end of the container. - - @liveexample{The example shows how `insert()` is used.,insert__count} - - @since version 1.0.0 - */ - iterator insert(const_iterator pos, size_type cnt, const basic_json& val) - { - // insert only works for arrays - if (JSON_LIKELY(is_array())) - { - // check if iterator pos fits to this JSON value - if (JSON_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); - } - - // insert to array and return iterator - iterator result(this); - result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); - return result; - } - - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); - } - - /*! - @brief inserts elements - - Inserts elements from range `[first, last)` before iterator @a pos. - - @param[in] pos iterator before which the content will be inserted; may be - the end() iterator - @param[in] first begin of the range of elements to insert - @param[in] last end of the range of elements to insert - - @throw type_error.309 if called on JSON values other than arrays; example: - `"cannot use insert() with string"` - @throw invalid_iterator.202 if @a pos is not an iterator of *this; - example: `"iterator does not fit current value"` - @throw invalid_iterator.210 if @a first and @a last do not belong to the - same JSON value; example: `"iterators do not fit"` - @throw invalid_iterator.211 if @a first or @a last are iterators into - container for which insert is called; example: `"passed iterators may not - belong to container"` - - @return iterator pointing to the first element inserted, or @a pos if - `first==last` - - @complexity Linear in `std::distance(first, last)` plus linear in the - distance between @a pos and end of the container. - - @liveexample{The example shows how `insert()` is used.,insert__range} - - @since version 1.0.0 - */ - iterator insert(const_iterator pos, const_iterator first, const_iterator last) - { - // insert only works for arrays - if (JSON_UNLIKELY(not is_array())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); - } - - // check if iterator pos fits to this JSON value - if (JSON_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); - } - - // check if range iterators belong to the same JSON object - if (JSON_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); - } - - if (JSON_UNLIKELY(first.m_object == this)) - { - JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); - } - - // insert to array and return iterator - iterator result(this); - result.m_it.array_iterator = m_value.array->insert( - pos.m_it.array_iterator, - first.m_it.array_iterator, - last.m_it.array_iterator); - return result; - } - - /*! - @brief inserts elements - - Inserts elements from initializer list @a ilist before iterator @a pos. - - @param[in] pos iterator before which the content will be inserted; may be - the end() iterator - @param[in] ilist initializer list to insert the values from - - @throw type_error.309 if called on JSON values other than arrays; example: - `"cannot use insert() with string"` - @throw invalid_iterator.202 if @a pos is not an iterator of *this; - example: `"iterator does not fit current value"` - - @return iterator pointing to the first element inserted, or @a pos if - `ilist` is empty - - @complexity Linear in `ilist.size()` plus linear in the distance between - @a pos and end of the container. - - @liveexample{The example shows how `insert()` is used.,insert__ilist} - - @since version 1.0.0 - */ - iterator insert(const_iterator pos, initializer_list_t ilist) - { - // insert only works for arrays - if (JSON_UNLIKELY(not is_array())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); - } - - // check if iterator pos fits to this JSON value - if (JSON_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); - } - - // insert to array and return iterator - iterator result(this); - result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end()); - return result; - } - - /*! - @brief inserts elements - - Inserts elements from range `[first, last)`. - - @param[in] first begin of the range of elements to insert - @param[in] last end of the range of elements to insert - - @throw type_error.309 if called on JSON values other than objects; example: - `"cannot use insert() with string"` - @throw invalid_iterator.202 if iterator @a first or @a last does does not - point to an object; example: `"iterators first and last must point to - objects"` - @throw invalid_iterator.210 if @a first and @a last do not belong to the - same JSON value; example: `"iterators do not fit"` - - @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number - of elements to insert. - - @liveexample{The example shows how `insert()` is used.,insert__range_object} - - @since version 3.0.0 - */ - void insert(const_iterator first, const_iterator last) - { - // insert only works for objects - if (JSON_UNLIKELY(not is_object())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); - } - - // check if range iterators belong to the same JSON object - if (JSON_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); - } - - // passed iterators must belong to objects - if (JSON_UNLIKELY(not first.m_object->is_object())) - { - JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); - } - - m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); - } - - /*! - @brief updates a JSON object from another object, overwriting existing keys - - Inserts all values from JSON object @a j and overwrites existing keys. - - @param[in] j JSON object to read values from - - @throw type_error.312 if called on JSON values other than objects; example: - `"cannot use update() with string"` - - @complexity O(N*log(size() + N)), where N is the number of elements to - insert. - - @liveexample{The example shows how `update()` is used.,update} - - @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update - - @since version 3.0.0 - */ - void update(const_reference j) - { - // implicitly convert null value to an empty object - if (is_null()) - { - m_type = value_t::object; - m_value.object = create(); - assert_invariant(); - } - - if (JSON_UNLIKELY(not is_object())) - { - JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); - } - if (JSON_UNLIKELY(not j.is_object())) - { - JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()))); - } - - for (auto it = j.cbegin(); it != j.cend(); ++it) - { - m_value.object->operator[](it.key()) = it.value(); - } - } - - /*! - @brief updates a JSON object from another object, overwriting existing keys - - Inserts all values from from range `[first, last)` and overwrites existing - keys. - - @param[in] first begin of the range of elements to insert - @param[in] last end of the range of elements to insert - - @throw type_error.312 if called on JSON values other than objects; example: - `"cannot use update() with string"` - @throw invalid_iterator.202 if iterator @a first or @a last does does not - point to an object; example: `"iterators first and last must point to - objects"` - @throw invalid_iterator.210 if @a first and @a last do not belong to the - same JSON value; example: `"iterators do not fit"` - - @complexity O(N*log(size() + N)), where N is the number of elements to - insert. - - @liveexample{The example shows how `update()` is used__range.,update} - - @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update - - @since version 3.0.0 - */ - void update(const_iterator first, const_iterator last) - { - // implicitly convert null value to an empty object - if (is_null()) - { - m_type = value_t::object; - m_value.object = create(); - assert_invariant(); - } - - if (JSON_UNLIKELY(not is_object())) - { - JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); - } - - // check if range iterators belong to the same JSON object - if (JSON_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); - } - - // passed iterators must belong to objects - if (JSON_UNLIKELY(not first.m_object->is_object() - or not last.m_object->is_object())) - { - JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); - } - - for (auto it = first; it != last; ++it) - { - m_value.object->operator[](it.key()) = it.value(); - } - } - - /*! - @brief exchanges the values - - Exchanges the contents of the JSON value with those of @a other. Does not - invoke any move, copy, or swap operations on individual elements. All - iterators and references remain valid. The past-the-end iterator is - invalidated. - - @param[in,out] other JSON value to exchange the contents with - - @complexity Constant. - - @liveexample{The example below shows how JSON values can be swapped with - `swap()`.,swap__reference} - - @since version 1.0.0 - */ - void swap(reference other) noexcept ( - std::is_nothrow_move_constructible::value and - std::is_nothrow_move_assignable::value and - std::is_nothrow_move_constructible::value and - std::is_nothrow_move_assignable::value - ) - { - std::swap(m_type, other.m_type); - std::swap(m_value, other.m_value); - assert_invariant(); - } - - /*! - @brief exchanges the values - - Exchanges the contents of a JSON array with those of @a other. Does not - invoke any move, copy, or swap operations on individual elements. All - iterators and references remain valid. The past-the-end iterator is - invalidated. - - @param[in,out] other array to exchange the contents with - - @throw type_error.310 when JSON value is not an array; example: `"cannot - use swap() with string"` - - @complexity Constant. - - @liveexample{The example below shows how arrays can be swapped with - `swap()`.,swap__array_t} - - @since version 1.0.0 - */ - void swap(array_t& other) - { - // swap only works for arrays - if (JSON_LIKELY(is_array())) - { - std::swap(*(m_value.array), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); - } - } - - /*! - @brief exchanges the values - - Exchanges the contents of a JSON object with those of @a other. Does not - invoke any move, copy, or swap operations on individual elements. All - iterators and references remain valid. The past-the-end iterator is - invalidated. - - @param[in,out] other object to exchange the contents with - - @throw type_error.310 when JSON value is not an object; example: - `"cannot use swap() with string"` - - @complexity Constant. - - @liveexample{The example below shows how objects can be swapped with - `swap()`.,swap__object_t} - - @since version 1.0.0 - */ - void swap(object_t& other) - { - // swap only works for objects - if (JSON_LIKELY(is_object())) - { - std::swap(*(m_value.object), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); - } - } - - /*! - @brief exchanges the values - - Exchanges the contents of a JSON string with those of @a other. Does not - invoke any move, copy, or swap operations on individual elements. All - iterators and references remain valid. The past-the-end iterator is - invalidated. - - @param[in,out] other string to exchange the contents with - - @throw type_error.310 when JSON value is not a string; example: `"cannot - use swap() with boolean"` - - @complexity Constant. - - @liveexample{The example below shows how strings can be swapped with - `swap()`.,swap__string_t} - - @since version 1.0.0 - */ - void swap(string_t& other) - { - // swap only works for strings - if (JSON_LIKELY(is_string())) - { - std::swap(*(m_value.string), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); - } - } - - /// @} - - public: - ////////////////////////////////////////// - // lexicographical comparison operators // - ////////////////////////////////////////// - - /// @name lexicographical comparison operators - /// @{ - - /*! - @brief comparison: equal - - Compares two JSON values for equality according to the following rules: - - Two JSON values are equal if (1) they are from the same type and (2) - their stored values are the same according to their respective - `operator==`. - - Integer and floating-point numbers are automatically converted before - comparison. Note than two NaN values are always treated as unequal. - - Two JSON null values are equal. - - @note Floating-point inside JSON values numbers are compared with - `json::number_float_t::operator==` which is `double::operator==` by - default. To compare floating-point while respecting an epsilon, an alternative - [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39) - could be used, for instance - @code {.cpp} - template::value, T>::type> - inline bool is_same(T a, T b, T epsilon = std::numeric_limits::epsilon()) noexcept - { - return std::abs(a - b) <= epsilon; - } - @endcode - - @note NaN values never compare equal to themselves or to other NaN values. - - @param[in] lhs first JSON value to consider - @param[in] rhs second JSON value to consider - @return whether the values @a lhs and @a rhs are equal - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @complexity Linear. - - @liveexample{The example demonstrates comparing several JSON - types.,operator__equal} - - @since version 1.0.0 - */ - friend bool operator==(const_reference lhs, const_reference rhs) noexcept - { - const auto lhs_type = lhs.type(); - const auto rhs_type = rhs.type(); - - if (lhs_type == rhs_type) - { - switch (lhs_type) - { - case value_t::array: - return (*lhs.m_value.array == *rhs.m_value.array); - - case value_t::object: - return (*lhs.m_value.object == *rhs.m_value.object); - - case value_t::null: - return true; - - case value_t::string: - return (*lhs.m_value.string == *rhs.m_value.string); - - case value_t::boolean: - return (lhs.m_value.boolean == rhs.m_value.boolean); - - case value_t::number_integer: - return (lhs.m_value.number_integer == rhs.m_value.number_integer); - - case value_t::number_unsigned: - return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned); - - case value_t::number_float: - return (lhs.m_value.number_float == rhs.m_value.number_float); - - default: - return false; - } - } - else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) - { - return (static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float); - } - else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) - { - return (lhs.m_value.number_float == static_cast(rhs.m_value.number_integer)); - } - else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) - { - return (static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float); - } - else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) - { - return (lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned)); - } - else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) - { - return (static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer); - } - else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) - { - return (lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned)); - } - - return false; - } - - /*! - @brief comparison: equal - @copydoc operator==(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept - { - return (lhs == basic_json(rhs)); - } - - /*! - @brief comparison: equal - @copydoc operator==(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept - { - return (basic_json(lhs) == rhs); - } - - /*! - @brief comparison: not equal - - Compares two JSON values for inequality by calculating `not (lhs == rhs)`. - - @param[in] lhs first JSON value to consider - @param[in] rhs second JSON value to consider - @return whether the values @a lhs and @a rhs are not equal - - @complexity Linear. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @liveexample{The example demonstrates comparing several JSON - types.,operator__notequal} - - @since version 1.0.0 - */ - friend bool operator!=(const_reference lhs, const_reference rhs) noexcept - { - return not (lhs == rhs); - } - - /*! - @brief comparison: not equal - @copydoc operator!=(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept - { - return (lhs != basic_json(rhs)); - } - - /*! - @brief comparison: not equal - @copydoc operator!=(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept - { - return (basic_json(lhs) != rhs); - } - - /*! - @brief comparison: less than - - Compares whether one JSON value @a lhs is less than another JSON value @a - rhs according to the following rules: - - If @a lhs and @a rhs have the same type, the values are compared using - the default `<` operator. - - Integer and floating-point numbers are automatically converted before - comparison - - In case @a lhs and @a rhs have different types, the values are ignored - and the order of the types is considered, see - @ref operator<(const value_t, const value_t). - - @param[in] lhs first JSON value to consider - @param[in] rhs second JSON value to consider - @return whether @a lhs is less than @a rhs - - @complexity Linear. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @liveexample{The example demonstrates comparing several JSON - types.,operator__less} - - @since version 1.0.0 - */ - friend bool operator<(const_reference lhs, const_reference rhs) noexcept - { - const auto lhs_type = lhs.type(); - const auto rhs_type = rhs.type(); - - if (lhs_type == rhs_type) - { - switch (lhs_type) - { - case value_t::array: - return (*lhs.m_value.array) < (*rhs.m_value.array); - - case value_t::object: - return *lhs.m_value.object < *rhs.m_value.object; - - case value_t::null: - return false; - - case value_t::string: - return *lhs.m_value.string < *rhs.m_value.string; - - case value_t::boolean: - return lhs.m_value.boolean < rhs.m_value.boolean; - - case value_t::number_integer: - return lhs.m_value.number_integer < rhs.m_value.number_integer; - - case value_t::number_unsigned: - return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; - - case value_t::number_float: - return lhs.m_value.number_float < rhs.m_value.number_float; - - default: - return false; - } - } - else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) - { - return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); - } - else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) - { - return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; - } - - // We only reach this line if we cannot compare values. In that case, - // we compare types. Note we have to call the operator explicitly, - // because MSVC has problems otherwise. - return operator<(lhs_type, rhs_type); - } - - /*! - @brief comparison: less than - @copydoc operator<(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept - { - return (lhs < basic_json(rhs)); - } - - /*! - @brief comparison: less than - @copydoc operator<(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept - { - return (basic_json(lhs) < rhs); - } - - /*! - @brief comparison: less than or equal - - Compares whether one JSON value @a lhs is less than or equal to another - JSON value by calculating `not (rhs < lhs)`. - - @param[in] lhs first JSON value to consider - @param[in] rhs second JSON value to consider - @return whether @a lhs is less than or equal to @a rhs - - @complexity Linear. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @liveexample{The example demonstrates comparing several JSON - types.,operator__greater} - - @since version 1.0.0 - */ - friend bool operator<=(const_reference lhs, const_reference rhs) noexcept - { - return not (rhs < lhs); - } - - /*! - @brief comparison: less than or equal - @copydoc operator<=(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept - { - return (lhs <= basic_json(rhs)); - } - - /*! - @brief comparison: less than or equal - @copydoc operator<=(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept - { - return (basic_json(lhs) <= rhs); - } - - /*! - @brief comparison: greater than - - Compares whether one JSON value @a lhs is greater than another - JSON value by calculating `not (lhs <= rhs)`. - - @param[in] lhs first JSON value to consider - @param[in] rhs second JSON value to consider - @return whether @a lhs is greater than to @a rhs - - @complexity Linear. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @liveexample{The example demonstrates comparing several JSON - types.,operator__lessequal} - - @since version 1.0.0 - */ - friend bool operator>(const_reference lhs, const_reference rhs) noexcept - { - return not (lhs <= rhs); - } - - /*! - @brief comparison: greater than - @copydoc operator>(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept - { - return (lhs > basic_json(rhs)); - } - - /*! - @brief comparison: greater than - @copydoc operator>(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept - { - return (basic_json(lhs) > rhs); - } - - /*! - @brief comparison: greater than or equal - - Compares whether one JSON value @a lhs is greater than or equal to another - JSON value by calculating `not (lhs < rhs)`. - - @param[in] lhs first JSON value to consider - @param[in] rhs second JSON value to consider - @return whether @a lhs is greater than or equal to @a rhs - - @complexity Linear. - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @liveexample{The example demonstrates comparing several JSON - types.,operator__greaterequal} - - @since version 1.0.0 - */ - friend bool operator>=(const_reference lhs, const_reference rhs) noexcept - { - return not (lhs < rhs); - } - - /*! - @brief comparison: greater than or equal - @copydoc operator>=(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept - { - return (lhs >= basic_json(rhs)); - } - - /*! - @brief comparison: greater than or equal - @copydoc operator>=(const_reference, const_reference) - */ - template::value, int>::type = 0> - friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept - { - return (basic_json(lhs) >= rhs); - } - - /// @} - - /////////////////// - // serialization // - /////////////////// - - /// @name serialization - /// @{ - - /*! - @brief serialize to stream - - Serialize the given JSON value @a j to the output stream @a o. The JSON - value will be serialized using the @ref dump member function. - - - The indentation of the output can be controlled with the member variable - `width` of the output stream @a o. For instance, using the manipulator - `std::setw(4)` on @a o sets the indentation level to `4` and the - serialization result is the same as calling `dump(4)`. - - - The indentation character can be controlled with the member variable - `fill` of the output stream @a o. For instance, the manipulator - `std::setfill('\\t')` sets indentation to use a tab character rather than - the default space character. - - @param[in,out] o stream to serialize to - @param[in] j JSON value to serialize - - @return the stream @a o - - @throw type_error.316 if a string stored inside the JSON value is not - UTF-8 encoded - - @complexity Linear. - - @liveexample{The example below shows the serialization with different - parameters to `width` to adjust the indentation level.,operator_serialize} - - @since version 1.0.0; indentation character added in version 3.0.0 - */ - friend std::ostream& operator<<(std::ostream& o, const basic_json& j) - { - // read width member and use it as indentation parameter if nonzero - const bool pretty_print = (o.width() > 0); - const auto indentation = (pretty_print ? o.width() : 0); - - // reset width to 0 for subsequent calls to this stream - o.width(0); - - // do the actual serialization - serializer s(detail::output_adapter(o), o.fill()); - s.dump(j, pretty_print, false, static_cast(indentation)); - return o; - } - - /*! - @brief serialize to stream - @deprecated This stream operator is deprecated and will be removed in - future 4.0.0 of the library. Please use - @ref operator<<(std::ostream&, const basic_json&) - instead; that is, replace calls like `j >> o;` with `o << j;`. - @since version 1.0.0; deprecated since version 3.0.0 - */ - JSON_DEPRECATED - friend std::ostream& operator>>(const basic_json& j, std::ostream& o) - { - return o << j; - } - - /// @} - - - ///////////////////// - // deserialization // - ///////////////////// - - /// @name deserialization - /// @{ - - /*! - @brief deserialize from a compatible input - - This function reads from a compatible input. Examples are: - - an array of 1-byte values - - strings with character/literal type with size of 1 byte - - input streams - - container with contiguous storage of 1-byte values. Compatible container - types include `std::vector`, `std::string`, `std::array`, - `std::valarray`, and `std::initializer_list`. Furthermore, C-style - arrays can be used with `std::begin()`/`std::end()`. User-defined - containers can be used as long as they implement random-access iterators - and a contiguous storage. - - @pre Each element of the container has a size of 1 byte. Violating this - precondition yields undefined behavior. **This precondition is enforced - with a static assertion.** - - @pre The container storage is contiguous. Violating this precondition - yields undefined behavior. **This precondition is enforced with an - assertion.** - @pre Each element of the container has a size of 1 byte. Violating this - precondition yields undefined behavior. **This precondition is enforced - with a static assertion.** - - @warning There is no way to enforce all preconditions at compile-time. If - the function is called with a noncompliant container and with - assertions switched off, the behavior is undefined and will most - likely yield segmentation violation. - - @param[in] i input to read from - @param[in] cb a parser callback function of type @ref parser_callback_t - which is used to control the deserialization by filtering unwanted values - (optional) - - @return result of the deserialization - - @throw parse_error.101 if a parse error occurs; example: `""unexpected end - of input; expected string literal""` - @throw parse_error.102 if to_unicode fails or surrogate error - @throw parse_error.103 if to_unicode fails - - @complexity Linear in the length of the input. The parser is a predictive - LL(1) parser. The complexity can be higher if the parser callback function - @a cb has a super-linear complexity. - - @note A UTF-8 byte order mark is silently ignored. - - @liveexample{The example below demonstrates the `parse()` function reading - from an array.,parse__array__parser_callback_t} - - @liveexample{The example below demonstrates the `parse()` function with - and without callback function.,parse__string__parser_callback_t} - - @liveexample{The example below demonstrates the `parse()` function with - and without callback function.,parse__istream__parser_callback_t} - - @liveexample{The example below demonstrates the `parse()` function reading - from a contiguous container.,parse__contiguouscontainer__parser_callback_t} - - @since version 2.0.3 (contiguous containers) - */ - static basic_json parse(detail::input_adapter&& i, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true) - { - basic_json result; - parser(i, cb, allow_exceptions).parse(true, result); - return result; - } - - static bool accept(detail::input_adapter&& i) - { - return parser(i).accept(true); - } - - static bool sax_parse(detail::input_adapter&& i, json_sax_t* sax, - input_format_t format = input_format_t::json, - const bool strict = true) - { - assert(sax); - switch (format) - { - case input_format_t::json: - return parser(std::move(i)).sax_parse(sax, strict); - default: - return binary_reader(std::move(i)).sax_parse(format, sax, strict); - } - } - - /*! - @brief deserialize from an iterator range with contiguous storage - - This function reads from an iterator range of a container with contiguous - storage of 1-byte values. Compatible container types include - `std::vector`, `std::string`, `std::array`, `std::valarray`, and - `std::initializer_list`. Furthermore, C-style arrays can be used with - `std::begin()`/`std::end()`. User-defined containers can be used as long - as they implement random-access iterators and a contiguous storage. - - @pre The iterator range is contiguous. Violating this precondition yields - undefined behavior. **This precondition is enforced with an assertion.** - @pre Each element in the range has a size of 1 byte. Violating this - precondition yields undefined behavior. **This precondition is enforced - with a static assertion.** - - @warning There is no way to enforce all preconditions at compile-time. If - the function is called with noncompliant iterators and with - assertions switched off, the behavior is undefined and will most - likely yield segmentation violation. - - @tparam IteratorType iterator of container with contiguous storage - @param[in] first begin of the range to parse (included) - @param[in] last end of the range to parse (excluded) - @param[in] cb a parser callback function of type @ref parser_callback_t - which is used to control the deserialization by filtering unwanted values - (optional) - @param[in] allow_exceptions whether to throw exceptions in case of a - parse error (optional, true by default) - - @return result of the deserialization - - @throw parse_error.101 in case of an unexpected token - @throw parse_error.102 if to_unicode fails or surrogate error - @throw parse_error.103 if to_unicode fails - - @complexity Linear in the length of the input. The parser is a predictive - LL(1) parser. The complexity can be higher if the parser callback function - @a cb has a super-linear complexity. - - @note A UTF-8 byte order mark is silently ignored. - - @liveexample{The example below demonstrates the `parse()` function reading - from an iterator range.,parse__iteratortype__parser_callback_t} - - @since version 2.0.3 - */ - template::iterator_category>::value, int>::type = 0> - static basic_json parse(IteratorType first, IteratorType last, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true) - { - basic_json result; - parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result); - return result; - } - - template::iterator_category>::value, int>::type = 0> - static bool accept(IteratorType first, IteratorType last) - { - return parser(detail::input_adapter(first, last)).accept(true); - } - - template::iterator_category>::value, int>::type = 0> - static bool sax_parse(IteratorType first, IteratorType last, json_sax_t* sax) - { - return parser(detail::input_adapter(first, last)).sax_parse(sax); - } - - /*! - @brief deserialize from stream - @deprecated This stream operator is deprecated and will be removed in - version 4.0.0 of the library. Please use - @ref operator>>(std::istream&, basic_json&) - instead; that is, replace calls like `j << i;` with `i >> j;`. - @since version 1.0.0; deprecated since version 3.0.0 - */ - JSON_DEPRECATED - friend std::istream& operator<<(basic_json& j, std::istream& i) - { - return operator>>(i, j); - } - - /*! - @brief deserialize from stream - - Deserializes an input stream to a JSON value. - - @param[in,out] i input stream to read a serialized JSON value from - @param[in,out] j JSON value to write the deserialized input to - - @throw parse_error.101 in case of an unexpected token - @throw parse_error.102 if to_unicode fails or surrogate error - @throw parse_error.103 if to_unicode fails - - @complexity Linear in the length of the input. The parser is a predictive - LL(1) parser. - - @note A UTF-8 byte order mark is silently ignored. - - @liveexample{The example below shows how a JSON value is constructed by - reading a serialization from a stream.,operator_deserialize} - - @sa parse(std::istream&, const parser_callback_t) for a variant with a - parser callback function to filter values while parsing - - @since version 1.0.0 - */ - friend std::istream& operator>>(std::istream& i, basic_json& j) - { - parser(detail::input_adapter(i)).parse(false, j); - return i; - } - - /// @} - - /////////////////////////// - // convenience functions // - /////////////////////////// - - /*! - @brief return the type as string - - Returns the type name as string to be used in error messages - usually to - indicate that a function was called on a wrong JSON type. - - @return a string representation of a the @a m_type member: - Value type | return value - ----------- | ------------- - null | `"null"` - boolean | `"boolean"` - string | `"string"` - number | `"number"` (for all number types) - object | `"object"` - array | `"array"` - discarded | `"discarded"` - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - - @complexity Constant. - - @liveexample{The following code exemplifies `type_name()` for all JSON - types.,type_name} - - @sa @ref type() -- return the type of the JSON value - @sa @ref operator value_t() -- return the type of the JSON value (implicit) - - @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` - since 3.0.0 - */ - const char* type_name() const noexcept - { - { - switch (m_type) - { - case value_t::null: - return "null"; - case value_t::object: - return "object"; - case value_t::array: - return "array"; - case value_t::string: - return "string"; - case value_t::boolean: - return "boolean"; - case value_t::discarded: - return "discarded"; - default: - return "number"; - } - } - } - - - private: - ////////////////////// - // member variables // - ////////////////////// - - /// the type of the current element - value_t m_type = value_t::null; - - /// the value of the current element - json_value m_value = {}; - - ////////////////////////////////////////// - // binary serialization/deserialization // - ////////////////////////////////////////// - - /// @name binary serialization/deserialization support - /// @{ - - public: - /*! - @brief create a CBOR serialization of a given JSON value - - Serializes a given JSON value @a j to a byte vector using the CBOR (Concise - Binary Object Representation) serialization format. CBOR is a binary - serialization format which aims to be more compact than JSON itself, yet - more efficient to parse. - - The library uses the following mapping from JSON values types to - CBOR types according to the CBOR specification (RFC 7049): - - JSON value type | value/range | CBOR type | first byte - --------------- | ------------------------------------------ | ---------------------------------- | --------------- - null | `null` | Null | 0xF6 - boolean | `true` | True | 0xF5 - boolean | `false` | False | 0xF4 - number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B - number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A - number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 - number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 - number_integer | -24..-1 | Negative integer | 0x20..0x37 - number_integer | 0..23 | Integer | 0x00..0x17 - number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 - number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 - number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A - number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B - number_unsigned | 0..23 | Integer | 0x00..0x17 - number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 - number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 - number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A - number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B - number_float | *any value* | Double-Precision Float | 0xFB - string | *length*: 0..23 | UTF-8 string | 0x60..0x77 - string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 - string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 - string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A - string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B - array | *size*: 0..23 | array | 0x80..0x97 - array | *size*: 23..255 | array (1 byte follow) | 0x98 - array | *size*: 256..65535 | array (2 bytes follow) | 0x99 - array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A - array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B - object | *size*: 0..23 | map | 0xA0..0xB7 - object | *size*: 23..255 | map (1 byte follow) | 0xB8 - object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 - object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA - object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB - - @note The mapping is **complete** in the sense that any JSON value type - can be converted to a CBOR value. - - @note If NaN or Infinity are stored inside a JSON number, they are - serialized properly. This behavior differs from the @ref dump() - function which serializes NaN or Infinity to `null`. - - @note The following CBOR types are not used in the conversion: - - byte strings (0x40..0x5F) - - UTF-8 strings terminated by "break" (0x7F) - - arrays terminated by "break" (0x9F) - - maps terminated by "break" (0xBF) - - date/time (0xC0..0xC1) - - bignum (0xC2..0xC3) - - decimal fraction (0xC4) - - bigfloat (0xC5) - - tagged items (0xC6..0xD4, 0xD8..0xDB) - - expected conversions (0xD5..0xD7) - - simple values (0xE0..0xF3, 0xF8) - - undefined (0xF7) - - half and single-precision floats (0xF9-0xFA) - - break (0xFF) - - @param[in] j JSON value to serialize - @return MessagePack serialization as byte vector - - @complexity Linear in the size of the JSON value @a j. - - @liveexample{The example shows the serialization of a JSON value to a byte - vector in CBOR format.,to_cbor} - - @sa http://cbor.io - @sa @ref from_cbor(detail::input_adapter, const bool strict) for the - analogous deserialization - @sa @ref to_msgpack(const basic_json&) for the related MessagePack format - @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the - related UBJSON format - - @since version 2.0.9 - */ - static std::vector to_cbor(const basic_json& j) - { - std::vector result; - to_cbor(j, result); - return result; - } - - static void to_cbor(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_cbor(j); - } - - static void to_cbor(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_cbor(j); - } - - /*! - @brief create a MessagePack serialization of a given JSON value - - Serializes a given JSON value @a j to a byte vector using the MessagePack - serialization format. MessagePack is a binary serialization format which - aims to be more compact than JSON itself, yet more efficient to parse. - - The library uses the following mapping from JSON values types to - MessagePack types according to the MessagePack specification: - - JSON value type | value/range | MessagePack type | first byte - --------------- | --------------------------------- | ---------------- | ---------- - null | `null` | nil | 0xC0 - boolean | `true` | true | 0xC3 - boolean | `false` | false | 0xC2 - number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 - number_integer | -2147483648..-32769 | int32 | 0xD2 - number_integer | -32768..-129 | int16 | 0xD1 - number_integer | -128..-33 | int8 | 0xD0 - number_integer | -32..-1 | negative fixint | 0xE0..0xFF - number_integer | 0..127 | positive fixint | 0x00..0x7F - number_integer | 128..255 | uint 8 | 0xCC - number_integer | 256..65535 | uint 16 | 0xCD - number_integer | 65536..4294967295 | uint 32 | 0xCE - number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF - number_unsigned | 0..127 | positive fixint | 0x00..0x7F - number_unsigned | 128..255 | uint 8 | 0xCC - number_unsigned | 256..65535 | uint 16 | 0xCD - number_unsigned | 65536..4294967295 | uint 32 | 0xCE - number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF - number_float | *any value* | float 64 | 0xCB - string | *length*: 0..31 | fixstr | 0xA0..0xBF - string | *length*: 32..255 | str 8 | 0xD9 - string | *length*: 256..65535 | str 16 | 0xDA - string | *length*: 65536..4294967295 | str 32 | 0xDB - array | *size*: 0..15 | fixarray | 0x90..0x9F - array | *size*: 16..65535 | array 16 | 0xDC - array | *size*: 65536..4294967295 | array 32 | 0xDD - object | *size*: 0..15 | fix map | 0x80..0x8F - object | *size*: 16..65535 | map 16 | 0xDE - object | *size*: 65536..4294967295 | map 32 | 0xDF - - @note The mapping is **complete** in the sense that any JSON value type - can be converted to a MessagePack value. - - @note The following values can **not** be converted to a MessagePack value: - - strings with more than 4294967295 bytes - - arrays with more than 4294967295 elements - - objects with more than 4294967295 elements - - @note The following MessagePack types are not used in the conversion: - - bin 8 - bin 32 (0xC4..0xC6) - - ext 8 - ext 32 (0xC7..0xC9) - - float 32 (0xCA) - - fixext 1 - fixext 16 (0xD4..0xD8) - - @note Any MessagePack output created @ref to_msgpack can be successfully - parsed by @ref from_msgpack. - - @note If NaN or Infinity are stored inside a JSON number, they are - serialized properly. This behavior differs from the @ref dump() - function which serializes NaN or Infinity to `null`. - - @param[in] j JSON value to serialize - @return MessagePack serialization as byte vector - - @complexity Linear in the size of the JSON value @a j. - - @liveexample{The example shows the serialization of a JSON value to a byte - vector in MessagePack format.,to_msgpack} - - @sa http://msgpack.org - @sa @ref from_msgpack(const std::vector&, const size_t) for the - analogous deserialization - @sa @ref to_cbor(const basic_json& for the related CBOR format - @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the - related UBJSON format - - @since version 2.0.9 - */ - static std::vector to_msgpack(const basic_json& j) - { - std::vector result; - to_msgpack(j, result); - return result; - } - - static void to_msgpack(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_msgpack(j); - } - - static void to_msgpack(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_msgpack(j); - } - - /*! - @brief create a UBJSON serialization of a given JSON value - - Serializes a given JSON value @a j to a byte vector using the UBJSON - (Universal Binary JSON) serialization format. UBJSON aims to be more compact - than JSON itself, yet more efficient to parse. - - The library uses the following mapping from JSON values types to - UBJSON types according to the UBJSON specification: - - JSON value type | value/range | UBJSON type | marker - --------------- | --------------------------------- | ----------- | ------ - null | `null` | null | `Z` - boolean | `true` | true | `T` - boolean | `false` | false | `F` - number_integer | -9223372036854775808..-2147483649 | int64 | `L` - number_integer | -2147483648..-32769 | int32 | `l` - number_integer | -32768..-129 | int16 | `I` - number_integer | -128..127 | int8 | `i` - number_integer | 128..255 | uint8 | `U` - number_integer | 256..32767 | int16 | `I` - number_integer | 32768..2147483647 | int32 | `l` - number_integer | 2147483648..9223372036854775807 | int64 | `L` - number_unsigned | 0..127 | int8 | `i` - number_unsigned | 128..255 | uint8 | `U` - number_unsigned | 256..32767 | int16 | `I` - number_unsigned | 32768..2147483647 | int32 | `l` - number_unsigned | 2147483648..9223372036854775807 | int64 | `L` - number_float | *any value* | float64 | `D` - string | *with shortest length indicator* | string | `S` - array | *see notes on optimized format* | array | `[` - object | *see notes on optimized format* | map | `{` - - @note The mapping is **complete** in the sense that any JSON value type - can be converted to a UBJSON value. - - @note The following values can **not** be converted to a UBJSON value: - - strings with more than 9223372036854775807 bytes (theoretical) - - unsigned integer numbers above 9223372036854775807 - - @note The following markers are not used in the conversion: - - `Z`: no-op values are not created. - - `C`: single-byte strings are serialized with `S` markers. - - @note Any UBJSON output created @ref to_ubjson can be successfully parsed - by @ref from_ubjson. - - @note If NaN or Infinity are stored inside a JSON number, they are - serialized properly. This behavior differs from the @ref dump() - function which serializes NaN or Infinity to `null`. - - @note The optimized formats for containers are supported: Parameter - @a use_size adds size information to the beginning of a container and - removes the closing marker. Parameter @a use_type further checks - whether all elements of a container have the same type and adds the - type marker to the beginning of the container. The @a use_type - parameter must only be used together with @a use_size = true. Note - that @a use_size = true alone may result in larger representations - - the benefit of this parameter is that the receiving side is - immediately informed on the number of elements of the container. - - @param[in] j JSON value to serialize - @param[in] use_size whether to add size annotations to container types - @param[in] use_type whether to add type annotations to container types - (must be combined with @a use_size = true) - @return UBJSON serialization as byte vector - - @complexity Linear in the size of the JSON value @a j. - - @liveexample{The example shows the serialization of a JSON value to a byte - vector in UBJSON format.,to_ubjson} - - @sa http://ubjson.org - @sa @ref from_ubjson(detail::input_adapter, const bool strict) for the - analogous deserialization - @sa @ref to_cbor(const basic_json& for the related CBOR format - @sa @ref to_msgpack(const basic_json&) for the related MessagePack format - - @since version 3.1.0 - */ - static std::vector to_ubjson(const basic_json& j, - const bool use_size = false, - const bool use_type = false) - { - std::vector result; - to_ubjson(j, result, use_size, use_type); - return result; - } - - static void to_ubjson(const basic_json& j, detail::output_adapter o, - const bool use_size = false, const bool use_type = false) - { - binary_writer(o).write_ubjson(j, use_size, use_type); - } - - static void to_ubjson(const basic_json& j, detail::output_adapter o, - const bool use_size = false, const bool use_type = false) - { - binary_writer(o).write_ubjson(j, use_size, use_type); - } - - /*! - @brief create a JSON value from an input in CBOR format - - Deserializes a given input @a i to a JSON value using the CBOR (Concise - Binary Object Representation) serialization format. - - The library maps CBOR types to JSON value types as follows: - - CBOR type | JSON value type | first byte - ---------------------- | --------------- | ---------- - Integer | number_unsigned | 0x00..0x17 - Unsigned integer | number_unsigned | 0x18 - Unsigned integer | number_unsigned | 0x19 - Unsigned integer | number_unsigned | 0x1A - Unsigned integer | number_unsigned | 0x1B - Negative integer | number_integer | 0x20..0x37 - Negative integer | number_integer | 0x38 - Negative integer | number_integer | 0x39 - Negative integer | number_integer | 0x3A - Negative integer | number_integer | 0x3B - Negative integer | number_integer | 0x40..0x57 - UTF-8 string | string | 0x60..0x77 - UTF-8 string | string | 0x78 - UTF-8 string | string | 0x79 - UTF-8 string | string | 0x7A - UTF-8 string | string | 0x7B - UTF-8 string | string | 0x7F - array | array | 0x80..0x97 - array | array | 0x98 - array | array | 0x99 - array | array | 0x9A - array | array | 0x9B - array | array | 0x9F - map | object | 0xA0..0xB7 - map | object | 0xB8 - map | object | 0xB9 - map | object | 0xBA - map | object | 0xBB - map | object | 0xBF - False | `false` | 0xF4 - True | `true` | 0xF5 - Nill | `null` | 0xF6 - Half-Precision Float | number_float | 0xF9 - Single-Precision Float | number_float | 0xFA - Double-Precision Float | number_float | 0xFB - - @warning The mapping is **incomplete** in the sense that not all CBOR - types can be converted to a JSON value. The following CBOR types - are not supported and will yield parse errors (parse_error.112): - - byte strings (0x40..0x5F) - - date/time (0xC0..0xC1) - - bignum (0xC2..0xC3) - - decimal fraction (0xC4) - - bigfloat (0xC5) - - tagged items (0xC6..0xD4, 0xD8..0xDB) - - expected conversions (0xD5..0xD7) - - simple values (0xE0..0xF3, 0xF8) - - undefined (0xF7) - - @warning CBOR allows map keys of any type, whereas JSON only allows - strings as keys in object values. Therefore, CBOR maps with keys - other than UTF-8 strings are rejected (parse_error.113). - - @note Any CBOR output created @ref to_cbor can be successfully parsed by - @ref from_cbor. - - @param[in] i an input in CBOR format convertible to an input adapter - @param[in] strict whether to expect the input to be consumed until EOF - (true by default) - @param[in] allow_exceptions whether to throw exceptions in case of a - parse error (optional, true by default) - - @return deserialized JSON value - - @throw parse_error.110 if the given input ends prematurely or the end of - file was not reached when @a strict was set to true - @throw parse_error.112 if unsupported features from CBOR were - used in the given input @a v or if the input is not valid CBOR - @throw parse_error.113 if a string was expected as map key, but not found - - @complexity Linear in the size of the input @a i. - - @liveexample{The example shows the deserialization of a byte vector in CBOR - format to a JSON value.,from_cbor} - - @sa http://cbor.io - @sa @ref to_cbor(const basic_json&) for the analogous serialization - @sa @ref from_msgpack(detail::input_adapter, const bool, const bool) for the - related MessagePack format - @sa @ref from_ubjson(detail::input_adapter, const bool, const bool) for the - related UBJSON format - - @since version 2.0.9; parameter @a start_index since 2.1.1; changed to - consume input adapters, removed start_index parameter, and added - @a strict parameter since 3.0.0; added @allow_exceptions parameter - since 3.2.0 - */ - static basic_json from_cbor(detail::input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /*! - @copydoc from_cbor(detail::input_adapter, const bool, const bool) - */ - template::value, int> = 0> - static basic_json from_cbor(A1 && a1, A2 && a2, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - const bool res = binary_reader(detail::input_adapter(std::forward(a1), std::forward(a2))).sax_parse(input_format_t::cbor, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /*! - @brief create a JSON value from an input in MessagePack format - - Deserializes a given input @a i to a JSON value using the MessagePack - serialization format. - - The library maps MessagePack types to JSON value types as follows: - - MessagePack type | JSON value type | first byte - ---------------- | --------------- | ---------- - positive fixint | number_unsigned | 0x00..0x7F - fixmap | object | 0x80..0x8F - fixarray | array | 0x90..0x9F - fixstr | string | 0xA0..0xBF - nil | `null` | 0xC0 - false | `false` | 0xC2 - true | `true` | 0xC3 - float 32 | number_float | 0xCA - float 64 | number_float | 0xCB - uint 8 | number_unsigned | 0xCC - uint 16 | number_unsigned | 0xCD - uint 32 | number_unsigned | 0xCE - uint 64 | number_unsigned | 0xCF - int 8 | number_integer | 0xD0 - int 16 | number_integer | 0xD1 - int 32 | number_integer | 0xD2 - int 64 | number_integer | 0xD3 - str 8 | string | 0xD9 - str 16 | string | 0xDA - str 32 | string | 0xDB - array 16 | array | 0xDC - array 32 | array | 0xDD - map 16 | object | 0xDE - map 32 | object | 0xDF - negative fixint | number_integer | 0xE0-0xFF - - @warning The mapping is **incomplete** in the sense that not all - MessagePack types can be converted to a JSON value. The following - MessagePack types are not supported and will yield parse errors: - - bin 8 - bin 32 (0xC4..0xC6) - - ext 8 - ext 32 (0xC7..0xC9) - - fixext 1 - fixext 16 (0xD4..0xD8) - - @note Any MessagePack output created @ref to_msgpack can be successfully - parsed by @ref from_msgpack. - - @param[in] i an input in MessagePack format convertible to an input - adapter - @param[in] strict whether to expect the input to be consumed until EOF - (true by default) - @param[in] allow_exceptions whether to throw exceptions in case of a - parse error (optional, true by default) - - @return deserialized JSON value - - @throw parse_error.110 if the given input ends prematurely or the end of - file was not reached when @a strict was set to true - @throw parse_error.112 if unsupported features from MessagePack were - used in the given input @a i or if the input is not valid MessagePack - @throw parse_error.113 if a string was expected as map key, but not found - - @complexity Linear in the size of the input @a i. - - @liveexample{The example shows the deserialization of a byte vector in - MessagePack format to a JSON value.,from_msgpack} - - @sa http://msgpack.org - @sa @ref to_msgpack(const basic_json&) for the analogous serialization - @sa @ref from_cbor(detail::input_adapter, const bool, const bool) for the - related CBOR format - @sa @ref from_ubjson(detail::input_adapter, const bool, const bool) for - the related UBJSON format - - @since version 2.0.9; parameter @a start_index since 2.1.1; changed to - consume input adapters, removed start_index parameter, and added - @a strict parameter since 3.0.0; added @allow_exceptions parameter - since 3.2.0 - */ - static basic_json from_msgpack(detail::input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /*! - @copydoc from_msgpack(detail::input_adapter, const bool, const bool) - */ - template::value, int> = 0> - static basic_json from_msgpack(A1 && a1, A2 && a2, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - const bool res = binary_reader(detail::input_adapter(std::forward(a1), std::forward(a2))).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /*! - @brief create a JSON value from an input in UBJSON format - - Deserializes a given input @a i to a JSON value using the UBJSON (Universal - Binary JSON) serialization format. - - The library maps UBJSON types to JSON value types as follows: - - UBJSON type | JSON value type | marker - ----------- | --------------------------------------- | ------ - no-op | *no value, next value is read* | `N` - null | `null` | `Z` - false | `false` | `F` - true | `true` | `T` - float32 | number_float | `d` - float64 | number_float | `D` - uint8 | number_unsigned | `U` - int8 | number_integer | `i` - int16 | number_integer | `I` - int32 | number_integer | `l` - int64 | number_integer | `L` - string | string | `S` - char | string | `C` - array | array (optimized values are supported) | `[` - object | object (optimized values are supported) | `{` - - @note The mapping is **complete** in the sense that any UBJSON value can - be converted to a JSON value. - - @param[in] i an input in UBJSON format convertible to an input adapter - @param[in] strict whether to expect the input to be consumed until EOF - (true by default) - @param[in] allow_exceptions whether to throw exceptions in case of a - parse error (optional, true by default) - - @return deserialized JSON value - - @throw parse_error.110 if the given input ends prematurely or the end of - file was not reached when @a strict was set to true - @throw parse_error.112 if a parse error occurs - @throw parse_error.113 if a string could not be parsed successfully - - @complexity Linear in the size of the input @a i. - - @liveexample{The example shows the deserialization of a byte vector in - UBJSON format to a JSON value.,from_ubjson} - - @sa http://ubjson.org - @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the - analogous serialization - @sa @ref from_cbor(detail::input_adapter, const bool, const bool) for the - related CBOR format - @sa @ref from_msgpack(detail::input_adapter, const bool, const bool) for - the related MessagePack format - - @since version 3.1.0; added @allow_exceptions parameter since 3.2.0 - */ - static basic_json from_ubjson(detail::input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /*! - @copydoc from_ubjson(detail::input_adapter, const bool, const bool) - */ - template::value, int> = 0> - static basic_json from_ubjson(A1 && a1, A2 && a2, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - const bool res = binary_reader(detail::input_adapter(std::forward(a1), std::forward(a2))).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @} - - ////////////////////////// - // JSON Pointer support // - ////////////////////////// - - /// @name JSON Pointer functions - /// @{ - - /*! - @brief access specified element via JSON Pointer - - Uses a JSON pointer to retrieve a reference to the respective JSON value. - No bound checking is performed. Similar to @ref operator[](const typename - object_t::key_type&), `null` values are created in arrays and objects if - necessary. - - In particular: - - If the JSON pointer points to an object key that does not exist, it - is created an filled with a `null` value before a reference to it - is returned. - - If the JSON pointer points to an array index that does not exist, it - is created an filled with a `null` value before a reference to it - is returned. All indices between the current maximum and the given - index are also filled with `null`. - - The special value `-` is treated as a synonym for the index past the - end. - - @param[in] ptr a JSON pointer - - @return reference to the element pointed to by @a ptr - - @complexity Constant. - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.404 if the JSON pointer can not be resolved - - @liveexample{The behavior is shown in the example.,operatorjson_pointer} - - @since version 2.0.0 - */ - reference operator[](const json_pointer& ptr) - { - return ptr.get_unchecked(this); - } - - /*! - @brief access specified element via JSON Pointer - - Uses a JSON pointer to retrieve a reference to the respective JSON value. - No bound checking is performed. The function does not change the JSON - value; no `null` values are created. In particular, the the special value - `-` yields an exception. - - @param[in] ptr JSON pointer to the desired element - - @return const reference to the element pointed to by @a ptr - - @complexity Constant. - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - - @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} - - @since version 2.0.0 - */ - const_reference operator[](const json_pointer& ptr) const - { - return ptr.get_unchecked(this); - } - - /*! - @brief access specified element via JSON Pointer - - Returns a reference to the element at with specified JSON pointer @a ptr, - with bounds checking. - - @param[in] ptr JSON pointer to the desired element - - @return reference to the element pointed to by @a ptr - - @throw parse_error.106 if an array index in the passed JSON pointer @a ptr - begins with '0'. See example below. - - @throw parse_error.109 if an array index in the passed JSON pointer @a ptr - is not a number. See example below. - - @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr - is out of range. See example below. - - @throw out_of_range.402 if the array index '-' is used in the passed JSON - pointer @a ptr. As `at` provides checked access (and no elements are - implicitly inserted), the index '-' is always invalid. See example below. - - @throw out_of_range.403 if the JSON pointer describes a key of an object - which cannot be found. See example below. - - @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. - See example below. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Constant. - - @since version 2.0.0 - - @liveexample{The behavior is shown in the example.,at_json_pointer} - */ - reference at(const json_pointer& ptr) - { - return ptr.get_checked(this); - } - - /*! - @brief access specified element via JSON Pointer - - Returns a const reference to the element at with specified JSON pointer @a - ptr, with bounds checking. - - @param[in] ptr JSON pointer to the desired element - - @return reference to the element pointed to by @a ptr - - @throw parse_error.106 if an array index in the passed JSON pointer @a ptr - begins with '0'. See example below. - - @throw parse_error.109 if an array index in the passed JSON pointer @a ptr - is not a number. See example below. - - @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr - is out of range. See example below. - - @throw out_of_range.402 if the array index '-' is used in the passed JSON - pointer @a ptr. As `at` provides checked access (and no elements are - implicitly inserted), the index '-' is always invalid. See example below. - - @throw out_of_range.403 if the JSON pointer describes a key of an object - which cannot be found. See example below. - - @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. - See example below. - - @exceptionsafety Strong guarantee: if an exception is thrown, there are no - changes in the JSON value. - - @complexity Constant. - - @since version 2.0.0 - - @liveexample{The behavior is shown in the example.,at_json_pointer_const} - */ - const_reference at(const json_pointer& ptr) const - { - return ptr.get_checked(this); - } - - /*! - @brief return flattened JSON value - - The function creates a JSON object whose keys are JSON pointers (see [RFC - 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all - primitive. The original JSON value can be restored using the @ref - unflatten() function. - - @return an object that maps JSON pointers to primitive values - - @note Empty objects and arrays are flattened to `null` and will not be - reconstructed correctly by the @ref unflatten() function. - - @complexity Linear in the size the JSON value. - - @liveexample{The following code shows how a JSON object is flattened to an - object whose keys consist of JSON pointers.,flatten} - - @sa @ref unflatten() for the reverse function - - @since version 2.0.0 - */ - basic_json flatten() const - { - basic_json result(value_t::object); - json_pointer::flatten("", *this, result); - return result; - } - - /*! - @brief unflatten a previously flattened JSON value - - The function restores the arbitrary nesting of a JSON value that has been - flattened before using the @ref flatten() function. The JSON value must - meet certain constraints: - 1. The value must be an object. - 2. The keys must be JSON pointers (see - [RFC 6901](https://tools.ietf.org/html/rfc6901)) - 3. The mapped values must be primitive JSON types. - - @return the original JSON from a flattened version - - @note Empty objects and arrays are flattened by @ref flatten() to `null` - values and can not unflattened to their original type. Apart from - this example, for a JSON value `j`, the following is always true: - `j == j.flatten().unflatten()`. - - @complexity Linear in the size the JSON value. - - @throw type_error.314 if value is not an object - @throw type_error.315 if object values are not primitive - - @liveexample{The following code shows how a flattened JSON object is - unflattened into the original nested JSON object.,unflatten} - - @sa @ref flatten() for the reverse function - - @since version 2.0.0 - */ - basic_json unflatten() const - { - return json_pointer::unflatten(*this); - } - - /// @} - - ////////////////////////// - // JSON Patch functions // - ////////////////////////// - - /// @name JSON Patch functions - /// @{ - - /*! - @brief applies a JSON patch - - [JSON Patch](http://jsonpatch.com) defines a JSON document structure for - expressing a sequence of operations to apply to a JSON) document. With - this function, a JSON Patch is applied to the current JSON value by - executing all operations from the patch. - - @param[in] json_patch JSON patch document - @return patched document - - @note The application of a patch is atomic: Either all operations succeed - and the patched document is returned or an exception is thrown. In - any case, the original value is not changed: the patch is applied - to a copy of the value. - - @throw parse_error.104 if the JSON patch does not consist of an array of - objects - - @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory - attributes are missing); example: `"operation add must have member path"` - - @throw out_of_range.401 if an array index is out of range. - - @throw out_of_range.403 if a JSON pointer inside the patch could not be - resolved successfully in the current JSON value; example: `"key baz not - found"` - - @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", - "move") - - @throw other_error.501 if "test" operation was unsuccessful - - @complexity Linear in the size of the JSON value and the length of the - JSON patch. As usually only a fraction of the JSON value is affected by - the patch, the complexity can usually be neglected. - - @liveexample{The following code shows how a JSON patch is applied to a - value.,patch} - - @sa @ref diff -- create a JSON patch by comparing two JSON values - - @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) - @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) - - @since version 2.0.0 - */ - basic_json patch(const basic_json& json_patch) const - { - // make a working copy to apply the patch to - basic_json result = *this; - - // the valid JSON Patch operations - enum class patch_operations {add, remove, replace, move, copy, test, invalid}; - - const auto get_op = [](const std::string & op) - { - if (op == "add") - { - return patch_operations::add; - } - if (op == "remove") - { - return patch_operations::remove; - } - if (op == "replace") - { - return patch_operations::replace; - } - if (op == "move") - { - return patch_operations::move; - } - if (op == "copy") - { - return patch_operations::copy; - } - if (op == "test") - { - return patch_operations::test; - } - - return patch_operations::invalid; - }; - - // wrapper for "add" operation; add value at ptr - const auto operation_add = [&result](json_pointer & ptr, basic_json val) - { - // adding to the root of the target document means replacing it - if (ptr.is_root()) - { - result = val; - } - else - { - // make sure the top element of the pointer exists - json_pointer top_pointer = ptr.top(); - if (top_pointer != ptr) - { - result.at(top_pointer); - } - - // get reference to parent of JSON pointer ptr - const auto last_path = ptr.pop_back(); - basic_json& parent = result[ptr]; - - switch (parent.m_type) - { - case value_t::null: - case value_t::object: - { - // use operator[] to add value - parent[last_path] = val; - break; - } - - case value_t::array: - { - if (last_path == "-") - { - // special case: append to back - parent.push_back(val); - } - else - { - const auto idx = json_pointer::array_index(last_path); - if (JSON_UNLIKELY(static_cast(idx) > parent.size())) - { - // avoid undefined behavior - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); - } - else - { - // default case: insert add offset - parent.insert(parent.begin() + static_cast(idx), val); - } - } - break; - } - - default: - { - // if there exists a parent it cannot be primitive - assert(false); // LCOV_EXCL_LINE - } - } - } - }; - - // wrapper for "remove" operation; remove value at ptr - const auto operation_remove = [&result](json_pointer & ptr) - { - // get reference to parent of JSON pointer ptr - const auto last_path = ptr.pop_back(); - basic_json& parent = result.at(ptr); - - // remove child - if (parent.is_object()) - { - // perform range check - auto it = parent.find(last_path); - if (JSON_LIKELY(it != parent.end())) - { - parent.erase(it); - } - else - { - JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found")); - } - } - else if (parent.is_array()) - { - // note erase performs range check - parent.erase(static_cast(json_pointer::array_index(last_path))); - } - }; - - // type check: top level value must be an array - if (JSON_UNLIKELY(not json_patch.is_array())) - { - JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); - } - - // iterate and apply the operations - for (const auto& val : json_patch) - { - // wrapper to get a value for an operation - const auto get_value = [&val](const std::string & op, - const std::string & member, - bool string_type) -> basic_json & - { - // find value - auto it = val.m_value.object->find(member); - - // context-sensitive error message - const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; - - // check if desired value is present - if (JSON_UNLIKELY(it == val.m_value.object->end())) - { - JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'")); - } - - // check if result is of type string - if (JSON_UNLIKELY(string_type and not it->second.is_string())) - { - JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'")); - } - - // no error: return value - return it->second; - }; - - // type check: every element of the array must be an object - if (JSON_UNLIKELY(not val.is_object())) - { - JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); - } - - // collect mandatory members - const std::string op = get_value("op", "op", true); - const std::string path = get_value(op, "path", true); - json_pointer ptr(path); - - switch (get_op(op)) - { - case patch_operations::add: - { - operation_add(ptr, get_value("add", "value", false)); - break; - } - - case patch_operations::remove: - { - operation_remove(ptr); - break; - } - - case patch_operations::replace: - { - // the "path" location must exist - use at() - result.at(ptr) = get_value("replace", "value", false); - break; - } - - case patch_operations::move: - { - const std::string from_path = get_value("move", "from", true); - json_pointer from_ptr(from_path); - - // the "from" location must exist - use at() - basic_json v = result.at(from_ptr); - - // The move operation is functionally identical to a - // "remove" operation on the "from" location, followed - // immediately by an "add" operation at the target - // location with the value that was just removed. - operation_remove(from_ptr); - operation_add(ptr, v); - break; - } - - case patch_operations::copy: - { - const std::string from_path = get_value("copy", "from", true); - const json_pointer from_ptr(from_path); - - // the "from" location must exist - use at() - basic_json v = result.at(from_ptr); - - // The copy is functionally identical to an "add" - // operation at the target location using the value - // specified in the "from" member. - operation_add(ptr, v); - break; - } - - case patch_operations::test: - { - bool success = false; - JSON_TRY - { - // check if "value" matches the one at "path" - // the "path" location must exist - use at() - success = (result.at(ptr) == get_value("test", "value", false)); - } - JSON_CATCH (out_of_range&) - { - // ignore out of range errors: success remains false - } - - // throw an exception if test fails - if (JSON_UNLIKELY(not success)) - { - JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump())); - } - - break; - } - - case patch_operations::invalid: - { - // op must be "add", "remove", "replace", "move", "copy", or - // "test" - JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid")); - } - } - } - - return result; - } - - /*! - @brief creates a diff as a JSON patch - - Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can - be changed into the value @a target by calling @ref patch function. - - @invariant For two JSON values @a source and @a target, the following code - yields always `true`: - @code {.cpp} - source.patch(diff(source, target)) == target; - @endcode - - @note Currently, only `remove`, `add`, and `replace` operations are - generated. - - @param[in] source JSON value to compare from - @param[in] target JSON value to compare against - @param[in] path helper value to create JSON pointers - - @return a JSON patch to convert the @a source to @a target - - @complexity Linear in the lengths of @a source and @a target. - - @liveexample{The following code shows how a JSON patch is created as a - diff for two JSON values.,diff} - - @sa @ref patch -- apply a JSON patch - @sa @ref merge_patch -- apply a JSON Merge Patch - - @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) - - @since version 2.0.0 - */ - static basic_json diff(const basic_json& source, const basic_json& target, - const std::string& path = "") - { - // the patch - basic_json result(value_t::array); - - // if the values are the same, return empty patch - if (source == target) - { - return result; - } - - if (source.type() != target.type()) - { - // different types: replace value - result.push_back( - { - {"op", "replace"}, {"path", path}, {"value", target} - }); - } - else - { - switch (source.type()) - { - case value_t::array: - { - // first pass: traverse common elements - std::size_t i = 0; - while (i < source.size() and i < target.size()) - { - // recursive call to compare array values at index i - auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); - result.insert(result.end(), temp_diff.begin(), temp_diff.end()); - ++i; - } - - // i now reached the end of at least one array - // in a second pass, traverse the remaining elements - - // remove my remaining elements - const auto end_index = static_cast(result.size()); - while (i < source.size()) - { - // add operations in reverse order to avoid invalid - // indices - result.insert(result.begin() + end_index, object( - { - {"op", "remove"}, - {"path", path + "/" + std::to_string(i)} - })); - ++i; - } - - // add other remaining elements - while (i < target.size()) - { - result.push_back( - { - {"op", "add"}, - {"path", path + "/" + std::to_string(i)}, - {"value", target[i]} - }); - ++i; - } - - break; - } - - case value_t::object: - { - // first pass: traverse this object's elements - for (auto it = source.cbegin(); it != source.cend(); ++it) - { - // escape the key name to be used in a JSON patch - const auto key = json_pointer::escape(it.key()); - - if (target.find(it.key()) != target.end()) - { - // recursive call to compare object values at key it - auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); - result.insert(result.end(), temp_diff.begin(), temp_diff.end()); - } - else - { - // found a key that is not in o -> remove it - result.push_back(object( - { - {"op", "remove"}, {"path", path + "/" + key} - })); - } - } - - // second pass: traverse other object's elements - for (auto it = target.cbegin(); it != target.cend(); ++it) - { - if (source.find(it.key()) == source.end()) - { - // found a key that is not in this -> add it - const auto key = json_pointer::escape(it.key()); - result.push_back( - { - {"op", "add"}, {"path", path + "/" + key}, - {"value", it.value()} - }); - } - } - - break; - } - - default: - { - // both primitive type: replace value - result.push_back( - { - {"op", "replace"}, {"path", path}, {"value", target} - }); - break; - } - } - } - - return result; - } - - /// @} - - //////////////////////////////// - // JSON Merge Patch functions // - //////////////////////////////// - - /// @name JSON Merge Patch functions - /// @{ - - /*! - @brief applies a JSON Merge Patch - - The merge patch format is primarily intended for use with the HTTP PATCH - method as a means of describing a set of modifications to a target - resource's content. This function applies a merge patch to the current - JSON value. - - The function implements the following algorithm from Section 2 of - [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396): - - ``` - define MergePatch(Target, Patch): - if Patch is an Object: - if Target is not an Object: - Target = {} // Ignore the contents and set it to an empty Object - for each Name/Value pair in Patch: - if Value is null: - if Name exists in Target: - remove the Name/Value pair from Target - else: - Target[Name] = MergePatch(Target[Name], Value) - return Target - else: - return Patch - ``` - - Thereby, `Target` is the current object; that is, the patch is applied to - the current value. - - @param[in] patch the patch to apply - - @complexity Linear in the lengths of @a patch. - - @liveexample{The following code shows how a JSON Merge Patch is applied to - a JSON document.,merge_patch} - - @sa @ref patch -- apply a JSON patch - @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396) - - @since version 3.0.0 - */ - void merge_patch(const basic_json& patch) - { - if (patch.is_object()) - { - if (not is_object()) - { - *this = object(); - } - for (auto it = patch.begin(); it != patch.end(); ++it) - { - if (it.value().is_null()) - { - erase(it.key()); - } - else - { - operator[](it.key()).merge_patch(it.value()); - } - } - } - else - { - *this = patch; - } - } - - /// @} -}; -} // namespace nlohmann - -/////////////////////// -// nonmember support // -/////////////////////// - -// specialization of std::swap, and std::hash -namespace std -{ -/*! -@brief exchanges the values of two JSON objects - -@since version 1.0.0 -*/ -template<> -inline void swap(nlohmann::json& j1, - nlohmann::json& j2) noexcept( - is_nothrow_move_constructible::value and - is_nothrow_move_assignable::value - ) -{ - j1.swap(j2); -} - -/// hash value for JSON objects -template<> -struct hash -{ - /*! - @brief return a hash value for a JSON object - - @since version 1.0.0 - */ - std::size_t operator()(const nlohmann::json& j) const - { - // a naive hashing via the string representation - const auto& h = hash(); - return h(j.dump()); - } -}; - -/// specialization for std::less -/// @note: do not remove the space after '<', -/// see https://github.com/nlohmann/json/pull/679 -template<> -struct less< ::nlohmann::detail::value_t> -{ - /*! - @brief compare two value_t enum values - @since version 3.0.0 - */ - bool operator()(nlohmann::detail::value_t lhs, - nlohmann::detail::value_t rhs) const noexcept - { - return nlohmann::detail::operator<(lhs, rhs); - } -}; - -} // namespace std - -/*! -@brief user-defined string literal for JSON values - -This operator implements a user-defined string literal for JSON objects. It -can be used by adding `"_json"` to a string literal and returns a JSON object -if no parse error occurred. - -@param[in] s a string representation of a JSON object -@param[in] n the length of string @a s -@return a JSON object - -@since version 1.0.0 -*/ -inline nlohmann::json operator "" _json(const char* s, std::size_t n) -{ - return nlohmann::json::parse(s, s + n); -} - -/*! -@brief user-defined string literal for JSON pointer - -This operator implements a user-defined string literal for JSON Pointers. It -can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer -object if no parse error occurred. - -@param[in] s a string representation of a JSON Pointer -@param[in] n the length of string @a s -@return a JSON pointer object - -@since version 2.0.0 -*/ -inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) -{ - return nlohmann::json::json_pointer(std::string(s, n)); -} - -#include - -#endif diff --git a/include/nlohmann/json_fwd.hpp b/include/nlohmann/json_fwd.hpp deleted file mode 100644 index 5ff0d75..0000000 --- a/include/nlohmann/json_fwd.hpp +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef NLOHMANN_JSON_FWD_HPP -#define NLOHMANN_JSON_FWD_HPP - -#include // int64_t, uint64_t -#include // map -#include // allocator -#include // string -#include // vector - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -/*! -@brief default JSONSerializer template argument - -This serializer ignores the template arguments and uses ADL -([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) -for serialization. -*/ -template -struct adl_serializer; - -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer> -class basic_json; - -/*! -@brief JSON Pointer - -A JSON pointer defines a string syntax for identifying a specific value -within a JSON document. It can be used with functions `at` and -`operator[]`. Furthermore, JSON pointers are the base for JSON patches. - -@sa [RFC 6901](https://tools.ietf.org/html/rfc6901) - -@since version 2.0.0 -*/ -template -class json_pointer; - -/*! -@brief default JSON class - -This type is the default specialization of the @ref basic_json class which -uses the standard template types. - -@since version 1.0.0 -*/ -using json = basic_json<>; -} - -#endif diff --git a/include/stb_image.h b/include/stb_image.h deleted file mode 100644 index 9eedabe..0000000 --- a/include/stb_image.h +++ /dev/null @@ -1,7988 +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 // ptrdiff_t on osx -#include -#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; ytype) { - default: - return stbi__errpuc("bad format","packet has bad compression type"); - - case 0: {//uncompressed - int x; - - for(x=0;xchannel,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; ichannel,dest,value); - left -= count; - } - } - break; - - case 2: {//Mixed RLE - int left=width; - while (left>0) { - int count = stbi__get8(s), i; - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); - - if (count >= 128) { // Repeated - stbi_uc value[4]; - - if (count==128) - count = stbi__get16be(s); - else - count -= 127; - if (count > left) - return stbi__errpuc("bad file","scanline overrun"); - - if (!stbi__readval(s,packet->channel,value)) - return 0; - - for(i=0;ichannel,dest,value); - } else { // Raw - ++count; - if (count>left) return stbi__errpuc("bad file","scanline overrun"); - - for(i=0;ichannel,dest)) - return 0; - } - left-=count; - } - break; - } - } - } - } - - return result; -} - -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. ------------------------------------------------------------------------------- -*/ diff --git a/include/stb_image_write.h b/include/stb_image_write.h deleted file mode 100644 index e4b32ed..0000000 --- a/include/stb_image_write.h +++ /dev/null @@ -1,1724 +0,0 @@ -/* stb_image_write - v1.16 - public domain - http://nothings.org/stb - writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 - no warranty implied; use at your own risk - - Before #including, - - #define STB_IMAGE_WRITE_IMPLEMENTATION - - in the file that you want to have the implementation. - - Will probably not work correctly with strict-aliasing optimizations. - -ABOUT: - - This header file is a library for writing images to C stdio or a callback. - - The PNG output is not optimal; it is 20-50% larger than the file - written by a decent optimizing implementation; though providing a custom - zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. - This library is designed for source code compactness and simplicity, - not optimal image file size or run-time performance. - -BUILDING: - - You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. - You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace - malloc,realloc,free. - You can #define STBIW_MEMMOVE() to replace memmove() - You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function - for PNG compression (instead of the builtin one), it must have the following signature: - unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); - The returned data will be freed with STBIW_FREE() (free() by default), - so it must be heap allocated with STBIW_MALLOC() (malloc() by default), - -UNICODE: - - If compiling for Windows and you wish to use Unicode filenames, compile - with - #define STBIW_WINDOWS_UTF8 - and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert - Windows wchar_t filenames to utf8. - -USAGE: - - There are five functions, one for each image file format: - - int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); - int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); - - void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically - - There are also five equivalent functions that use an arbitrary write function. You are - expected to open/close your file-equivalent before and after calling these: - - int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); - int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); - - where the callback is: - void stbi_write_func(void *context, void *data, int size); - - You can configure it with these global variables: - int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE - int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression - int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode - - - You can define STBI_WRITE_NO_STDIO to disable the file variant of these - functions, so the library will not use stdio.h at all. However, this will - also disable HDR writing, because it requires stdio for formatted output. - - Each function returns 0 on failure and non-0 on success. - - The functions create an image file defined by the parameters. The image - is a rectangle of pixels stored from left-to-right, top-to-bottom. - Each pixel contains 'comp' channels of data stored interleaved with 8-bits - per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is - monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. - The *data pointer points to the first byte of the top-left-most pixel. - For PNG, "stride_in_bytes" is the distance in bytes from the first byte of - a row of pixels to the first byte of the next row of pixels. - - PNG creates output files with the same number of components as the input. - The BMP format expands Y to RGB in the file format and does not - output alpha. - - PNG supports writing rectangles of data even when the bytes storing rows of - data are not consecutive in memory (e.g. sub-rectangles of a larger image), - by supplying the stride between the beginning of adjacent rows. The other - formats do not. (Thus you cannot write a native-format BMP through the BMP - writer, both because it is in BGR order and because it may have padding - at the end of the line.) - - PNG allows you to set the deflate compression level by setting the global - variable 'stbi_write_png_compression_level' (it defaults to 8). - - HDR expects linear float data. Since the format is always 32-bit rgb(e) - data, alpha (if provided) is discarded, and for monochrome data it is - replicated across all three channels. - - TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed - data, set the global variable 'stbi_write_tga_with_rle' to 0. - - JPEG does ignore alpha channels in input data; quality is between 1 and 100. - Higher quality looks better but results in a bigger image. - JPEG baseline (no JPEG progressive). - -CREDITS: - - - Sean Barrett - PNG/BMP/TGA - Baldur Karlsson - HDR - Jean-Sebastien Guay - TGA monochrome - Tim Kelsey - misc enhancements - Alan Hickman - TGA RLE - Emmanuel Julien - initial file IO callback implementation - Jon Olick - original jo_jpeg.cpp code - Daniel Gibson - integrate JPEG, allow external zlib - Aarni Koskela - allow choosing PNG filter - - bugfixes: - github:Chribba - Guillaume Chereau - github:jry2 - github:romigrou - Sergio Gonzalez - Jonas Karlsson - Filip Wasil - Thatcher Ulrich - github:poppolopoppo - Patrick Boettcher - github:xeekworx - Cap Petschulat - Simon Rodriguez - Ivan Tikhonov - github:ignotion - Adam Schackart - Andrew Kensler - -LICENSE - - See end of file for license information. - -*/ - -#ifndef INCLUDE_STB_IMAGE_WRITE_H -#define INCLUDE_STB_IMAGE_WRITE_H - -#include - -// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' -#ifndef STBIWDEF -#ifdef STB_IMAGE_WRITE_STATIC -#define STBIWDEF static -#else -#ifdef __cplusplus -#define STBIWDEF extern "C" -#else -#define STBIWDEF extern -#endif -#endif -#endif - -#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations -STBIWDEF int stbi_write_tga_with_rle; -STBIWDEF int stbi_write_png_compression_level; -STBIWDEF int stbi_write_force_png_filter; -#endif - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); -STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); - -#ifdef STBIW_WINDOWS_UTF8 -STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); -#endif -#endif - -typedef void stbi_write_func(void *context, void *data, int size); - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); -STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); - -STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); - -#endif//INCLUDE_STB_IMAGE_WRITE_H - -#ifdef STB_IMAGE_WRITE_IMPLEMENTATION - -#ifdef _WIN32 - #ifndef _CRT_SECURE_NO_WARNINGS - #define _CRT_SECURE_NO_WARNINGS - #endif - #ifndef _CRT_NONSTDC_NO_DEPRECATE - #define _CRT_NONSTDC_NO_DEPRECATE - #endif -#endif - -#ifndef STBI_WRITE_NO_STDIO -#include -#endif // STBI_WRITE_NO_STDIO - -#include -#include -#include -#include - -#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) -// ok -#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) -// ok -#else -#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." -#endif - -#ifndef STBIW_MALLOC -#define STBIW_MALLOC(sz) malloc(sz) -#define STBIW_REALLOC(p,newsz) realloc(p,newsz) -#define STBIW_FREE(p) free(p) -#endif - -#ifndef STBIW_REALLOC_SIZED -#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) -#endif - - -#ifndef STBIW_MEMMOVE -#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) -#endif - - -#ifndef STBIW_ASSERT -#include -#define STBIW_ASSERT(x) assert(x) -#endif - -#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) - -#ifdef STB_IMAGE_WRITE_STATIC -static int stbi_write_png_compression_level = 8; -static int stbi_write_tga_with_rle = 1; -static int stbi_write_force_png_filter = -1; -#else -int stbi_write_png_compression_level = 8; -int stbi_write_tga_with_rle = 1; -int stbi_write_force_png_filter = -1; -#endif - -static int stbi__flip_vertically_on_write = 0; - -STBIWDEF void stbi_flip_vertically_on_write(int flag) -{ - stbi__flip_vertically_on_write = flag; -} - -typedef struct -{ - stbi_write_func *func; - void *context; - unsigned char buffer[64]; - int buf_used; -} stbi__write_context; - -// initialize a callback-based context -static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) -{ - s->func = c; - s->context = context; -} - -#ifndef STBI_WRITE_NO_STDIO - -static void stbi__stdio_write(void *context, void *data, int size) -{ - fwrite(data,1,size,(FILE*) context); -} - -#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) -#ifdef __cplusplus -#define STBIW_EXTERN extern "C" -#else -#define STBIW_EXTERN extern -#endif -STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); -STBIW_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); - -STBIWDEF int stbiw_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 *stbiw__fopen(char const *filename, char const *mode) -{ - FILE *f; -#if defined(_WIN32) && defined(STBIW_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; -} - -static int stbi__start_write_file(stbi__write_context *s, const char *filename) -{ - FILE *f = stbiw__fopen(filename, "wb"); - stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); - return f != NULL; -} - -static void stbi__end_write_file(stbi__write_context *s) -{ - fclose((FILE *)s->context); -} - -#endif // !STBI_WRITE_NO_STDIO - -typedef unsigned int stbiw_uint32; -typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; - -static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) -{ - while (*fmt) { - switch (*fmt++) { - case ' ': break; - case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); - s->func(s->context,&x,1); - break; } - case '2': { int x = va_arg(v,int); - unsigned char b[2]; - b[0] = STBIW_UCHAR(x); - b[1] = STBIW_UCHAR(x>>8); - s->func(s->context,b,2); - break; } - case '4': { stbiw_uint32 x = va_arg(v,int); - unsigned char b[4]; - b[0]=STBIW_UCHAR(x); - b[1]=STBIW_UCHAR(x>>8); - b[2]=STBIW_UCHAR(x>>16); - b[3]=STBIW_UCHAR(x>>24); - s->func(s->context,b,4); - break; } - default: - STBIW_ASSERT(0); - return; - } - } -} - -static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) -{ - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); -} - -static void stbiw__write_flush(stbi__write_context *s) -{ - if (s->buf_used) { - s->func(s->context, &s->buffer, s->buf_used); - s->buf_used = 0; - } -} - -static void stbiw__putc(stbi__write_context *s, unsigned char c) -{ - s->func(s->context, &c, 1); -} - -static void stbiw__write1(stbi__write_context *s, unsigned char a) -{ - if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) - stbiw__write_flush(s); - s->buffer[s->buf_used++] = a; -} - -static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) -{ - int n; - if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) - stbiw__write_flush(s); - n = s->buf_used; - s->buf_used = n+3; - s->buffer[n+0] = a; - s->buffer[n+1] = b; - s->buffer[n+2] = c; -} - -static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) -{ - unsigned char bg[3] = { 255, 0, 255}, px[3]; - int k; - - if (write_alpha < 0) - stbiw__write1(s, d[comp - 1]); - - switch (comp) { - case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case - case 1: - if (expand_mono) - stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp - else - stbiw__write1(s, d[0]); // monochrome TGA - break; - case 4: - if (!write_alpha) { - // composite against pink background - for (k = 0; k < 3; ++k) - px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; - stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); - break; - } - /* FALLTHROUGH */ - case 3: - stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); - break; - } - if (write_alpha > 0) - stbiw__write1(s, d[comp - 1]); -} - -static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) -{ - stbiw_uint32 zero = 0; - int i,j, j_end; - - if (y <= 0) - return; - - if (stbi__flip_vertically_on_write) - vdir *= -1; - - if (vdir < 0) { - j_end = -1; j = y-1; - } else { - j_end = y; j = 0; - } - - for (; j != j_end; j += vdir) { - for (i=0; i < x; ++i) { - unsigned char *d = (unsigned char *) data + (j*x+i)*comp; - stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); - } - stbiw__write_flush(s); - s->func(s->context, &zero, scanline_pad); - } -} - -static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) -{ - if (y < 0 || x < 0) { - return 0; - } else { - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); - stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); - return 1; - } -} - -static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) -{ - if (comp != 4) { - // write RGB bitmap - int pad = (-x*3) & 3; - return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, - "11 4 22 4" "4 44 22 444444", - 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header - 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header - } else { - // RGBA bitmaps need a v4 header - // use BI_BITFIELDS mode with 32bpp and alpha mask - // (straight BI_RGB with alpha mask doesn't work in most readers) - return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, - "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", - 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header - 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header - } -} - -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_bmp_core(&s, x, y, comp, data); -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_bmp_core(&s, x, y, comp, data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif //!STBI_WRITE_NO_STDIO - -static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) -{ - int has_alpha = (comp == 2 || comp == 4); - int colorbytes = has_alpha ? comp-1 : comp; - int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 - - if (y < 0 || x < 0) - return 0; - - if (!stbi_write_tga_with_rle) { - return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, - "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); - } else { - int i,j,k; - int jend, jdir; - - stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); - - if (stbi__flip_vertically_on_write) { - j = 0; - jend = y; - jdir = 1; - } else { - j = y-1; - jend = -1; - jdir = -1; - } - for (; j != jend; j += jdir) { - unsigned char *row = (unsigned char *) data + j * x * comp; - int len; - - for (i = 0; i < x; i += len) { - unsigned char *begin = row + i * comp; - int diff = 1; - len = 1; - - if (i < x - 1) { - ++len; - diff = memcmp(begin, row + (i + 1) * comp, comp); - if (diff) { - const unsigned char *prev = begin; - for (k = i + 2; k < x && len < 128; ++k) { - if (memcmp(prev, row + k * comp, comp)) { - prev += comp; - ++len; - } else { - --len; - break; - } - } - } else { - for (k = i + 2; k < x && len < 128; ++k) { - if (!memcmp(begin, row + k * comp, comp)) { - ++len; - } else { - break; - } - } - } - } - - if (diff) { - unsigned char header = STBIW_UCHAR(len - 1); - stbiw__write1(s, header); - for (k = 0; k < len; ++k) { - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); - } - } else { - unsigned char header = STBIW_UCHAR(len - 129); - stbiw__write1(s, header); - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); - } - } - } - stbiw__write_flush(s); - } - return 1; -} - -STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_tga_core(&s, x, y, comp, (void *) data); -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif - -// ************************************************************************************************* -// Radiance RGBE HDR writer -// by Baldur Karlsson - -#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) - -#ifndef STBI_WRITE_NO_STDIO - -static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) -{ - int exponent; - float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); - - if (maxcomp < 1e-32f) { - rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; - } else { - float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; - - rgbe[0] = (unsigned char)(linear[0] * normalize); - rgbe[1] = (unsigned char)(linear[1] * normalize); - rgbe[2] = (unsigned char)(linear[2] * normalize); - rgbe[3] = (unsigned char)(exponent + 128); - } -} - -static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) -{ - unsigned char lengthbyte = STBIW_UCHAR(length+128); - STBIW_ASSERT(length+128 <= 255); - s->func(s->context, &lengthbyte, 1); - s->func(s->context, &databyte, 1); -} - -static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) -{ - unsigned char lengthbyte = STBIW_UCHAR(length); - STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code - s->func(s->context, &lengthbyte, 1); - s->func(s->context, data, length); -} - -static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) -{ - unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; - unsigned char rgbe[4]; - float linear[3]; - int x; - - scanlineheader[2] = (width&0xff00)>>8; - scanlineheader[3] = (width&0x00ff); - - /* skip RLE for images too small or large */ - if (width < 8 || width >= 32768) { - for (x=0; x < width; x++) { - switch (ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - s->func(s->context, rgbe, 4); - } - } else { - int c,r; - /* encode into scratch buffer */ - for (x=0; x < width; x++) { - switch(ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - scratch[x + width*0] = rgbe[0]; - scratch[x + width*1] = rgbe[1]; - scratch[x + width*2] = rgbe[2]; - scratch[x + width*3] = rgbe[3]; - } - - s->func(s->context, scanlineheader, 4); - - /* RLE each component separately */ - for (c=0; c < 4; c++) { - unsigned char *comp = &scratch[width*c]; - - x = 0; - while (x < width) { - // find first run - r = x; - while (r+2 < width) { - if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) - break; - ++r; - } - if (r+2 >= width) - r = width; - // dump up to first run - while (x < r) { - int len = r-x; - if (len > 128) len = 128; - stbiw__write_dump_data(s, len, &comp[x]); - x += len; - } - // if there's a run, output it - if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd - // find next byte after run - while (r < width && comp[r] == comp[x]) - ++r; - // output run up to r - while (x < r) { - int len = r-x; - if (len > 127) len = 127; - stbiw__write_run_data(s, len, comp[x]); - x += len; - } - } - } - } - } -} - -static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) -{ - if (y <= 0 || x <= 0 || data == NULL) - return 0; - else { - // Each component is stored separately. Allocate scratch space for full output scanline. - unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); - int i, len; - char buffer[128]; - char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; - s->func(s->context, header, sizeof(header)-1); - -#ifdef __STDC_LIB_EXT1__ - len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); -#else - len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); -#endif - s->func(s->context, buffer, len); - - for(i=0; i < y; i++) - stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); - STBIW_FREE(scratch); - return 1; - } -} - -STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_hdr_core(&s, x, y, comp, (float *) data); -} - -STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif // STBI_WRITE_NO_STDIO - - -////////////////////////////////////////////////////////////////////////////// -// -// PNG writer -// - -#ifndef STBIW_ZLIB_COMPRESS -// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() -#define stbiw__sbraw(a) ((int *) (void *) (a) - 2) -#define stbiw__sbm(a) stbiw__sbraw(a)[0] -#define stbiw__sbn(a) stbiw__sbraw(a)[1] - -#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) -#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) -#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) - -#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) -#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) -#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) - -static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) -{ - int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; - void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); - STBIW_ASSERT(p); - if (p) { - if (!*arr) ((int *) p)[1] = 0; - *arr = (void *) ((int *) p + 2); - stbiw__sbm(*arr) = m; - } - return *arr; -} - -static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) -{ - while (*bitcount >= 8) { - stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); - *bitbuffer >>= 8; - *bitcount -= 8; - } - return data; -} - -static int stbiw__zlib_bitrev(int code, int codebits) -{ - int res=0; - while (codebits--) { - res = (res << 1) | (code & 1); - code >>= 1; - } - return res; -} - -static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) -{ - int i; - for (i=0; i < limit && i < 258; ++i) - if (a[i] != b[i]) break; - return i; -} - -static unsigned int stbiw__zhash(unsigned char *data) -{ - stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - return hash; -} - -#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) -#define stbiw__zlib_add(code,codebits) \ - (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) -#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) -// default huffman tables -#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) -#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) -#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) -#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) -#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) -#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) - -#define stbiw__ZHASH 16384 - -#endif // STBIW_ZLIB_COMPRESS - -STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) -{ -#ifdef STBIW_ZLIB_COMPRESS - // user provided a zlib compress implementation, use that - return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); -#else // use builtin - static unsigned short lengthc[] = { 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, 259 }; - static unsigned char lengtheb[]= { 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 }; - static unsigned short distc[] = { 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, 32768 }; - static unsigned char disteb[] = { 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 }; - unsigned int bitbuf=0; - int i,j, bitcount=0; - unsigned char *out = NULL; - unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); - if (hash_table == NULL) - return NULL; - if (quality < 5) quality = 5; - - stbiw__sbpush(out, 0x78); // DEFLATE 32K window - stbiw__sbpush(out, 0x5e); // FLEVEL = 1 - stbiw__zlib_add(1,1); // BFINAL = 1 - stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman - - for (i=0; i < stbiw__ZHASH; ++i) - hash_table[i] = NULL; - - i=0; - while (i < data_len-3) { - // hash next 3 bytes of data to be compressed - int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; - unsigned char *bestloc = 0; - unsigned char **hlist = hash_table[h]; - int n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32768) { // if entry lies within window - int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); - if (d >= best) { best=d; bestloc=hlist[j]; } - } - } - // when hash table entry is too long, delete half the entries - if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { - STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); - stbiw__sbn(hash_table[h]) = quality; - } - stbiw__sbpush(hash_table[h],data+i); - - if (bestloc) { - // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal - h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); - hlist = hash_table[h]; - n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32767) { - int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); - if (e > best) { // if next match is better, bail on current match - bestloc = NULL; - break; - } - } - } - } - - if (bestloc) { - int d = (int) (data+i - bestloc); // distance back - STBIW_ASSERT(d <= 32767 && best <= 258); - for (j=0; best > lengthc[j+1]-1; ++j); - stbiw__zlib_huff(j+257); - if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); - for (j=0; d > distc[j+1]-1; ++j); - stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); - if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); - i += best; - } else { - stbiw__zlib_huffb(data[i]); - ++i; - } - } - // write out final bytes - for (;i < data_len; ++i) - stbiw__zlib_huffb(data[i]); - stbiw__zlib_huff(256); // end of block - // pad with 0 bits to byte boundary - while (bitcount) - stbiw__zlib_add(0,1); - - for (i=0; i < stbiw__ZHASH; ++i) - (void) stbiw__sbfree(hash_table[i]); - STBIW_FREE(hash_table); - - // store uncompressed instead if compression was worse - if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { - stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 - for (j = 0; j < data_len;) { - int blocklen = data_len - j; - if (blocklen > 32767) blocklen = 32767; - stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression - stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN - stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN - stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); - memcpy(out+stbiw__sbn(out), data+j, blocklen); - stbiw__sbn(out) += blocklen; - j += blocklen; - } - } - - { - // compute adler32 on input - unsigned int s1=1, s2=0; - int blocklen = (int) (data_len % 5552); - j=0; - while (j < data_len) { - for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } - s1 %= 65521; s2 %= 65521; - j += blocklen; - blocklen = 5552; - } - stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s2)); - stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s1)); - } - *out_len = stbiw__sbn(out); - // make returned pointer freeable - STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); - return (unsigned char *) stbiw__sbraw(out); -#endif // STBIW_ZLIB_COMPRESS -} - -static unsigned int stbiw__crc32(unsigned char *buffer, int len) -{ -#ifdef STBIW_CRC32 - return STBIW_CRC32(buffer, len); -#else - static unsigned int crc_table[256] = - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D - }; - - unsigned int crc = ~0u; - int i; - for (i=0; i < len; ++i) - crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; - return ~crc; -#endif -} - -#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) -#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); -#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) - -static void stbiw__wpcrc(unsigned char **data, int len) -{ - unsigned int crc = stbiw__crc32(*data - len - 4, len+4); - stbiw__wp32(*data, crc); -} - -static unsigned char stbiw__paeth(int a, int b, int c) -{ - int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); - if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); - if (pb <= pc) return STBIW_UCHAR(b); - return STBIW_UCHAR(c); -} - -// @OPTIMIZE: provide an option that always forces left-predict or paeth predict -static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) -{ - static int mapping[] = { 0,1,2,3,4 }; - static int firstmap[] = { 0,1,0,5,6 }; - int *mymap = (y != 0) ? mapping : firstmap; - int i; - int type = mymap[filter_type]; - unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); - int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; - - if (type==0) { - memcpy(line_buffer, z, width*n); - return; - } - - // first loop isn't optimized since it's just one pixel - for (i = 0; i < n; ++i) { - switch (type) { - case 1: line_buffer[i] = z[i]; break; - case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; - case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; - case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; - case 5: line_buffer[i] = z[i]; break; - case 6: line_buffer[i] = z[i]; break; - } - } - switch (type) { - case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; - case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; - case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; - case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; - case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; - case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; - } -} - -STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) -{ - int force_filter = stbi_write_force_png_filter; - int ctype[5] = { -1, 0, 4, 2, 6 }; - unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; - unsigned char *out,*o, *filt, *zlib; - signed char *line_buffer; - int j,zlen; - - if (stride_bytes == 0) - stride_bytes = x * n; - - if (force_filter >= 5) { - force_filter = -1; - } - - filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; - line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } - for (j=0; j < y; ++j) { - int filter_type; - if (force_filter > -1) { - filter_type = force_filter; - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); - } else { // Estimate the best filter by running through all of them: - int best_filter = 0, best_filter_val = 0x7fffffff, est, i; - for (filter_type = 0; filter_type < 5; filter_type++) { - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); - - // Estimate the entropy of the line using this filter; the less, the better. - est = 0; - for (i = 0; i < x*n; ++i) { - est += abs((signed char) line_buffer[i]); - } - if (est < best_filter_val) { - best_filter_val = est; - best_filter = filter_type; - } - } - if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); - filter_type = best_filter; - } - } - // when we get here, filter_type contains the filter type, and line_buffer contains the data - filt[j*(x*n+1)] = (unsigned char) filter_type; - STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); - } - STBIW_FREE(line_buffer); - zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); - STBIW_FREE(filt); - if (!zlib) return 0; - - // each tag requires 12 bytes of overhead - out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); - if (!out) return 0; - *out_len = 8 + 12+13 + 12+zlen + 12; - - o=out; - STBIW_MEMMOVE(o,sig,8); o+= 8; - stbiw__wp32(o, 13); // header length - stbiw__wptag(o, "IHDR"); - stbiw__wp32(o, x); - stbiw__wp32(o, y); - *o++ = 8; - *o++ = STBIW_UCHAR(ctype[n]); - *o++ = 0; - *o++ = 0; - *o++ = 0; - stbiw__wpcrc(&o,13); - - stbiw__wp32(o, zlen); - stbiw__wptag(o, "IDAT"); - STBIW_MEMMOVE(o, zlib, zlen); - o += zlen; - STBIW_FREE(zlib); - stbiw__wpcrc(&o, zlen); - - stbiw__wp32(o,0); - stbiw__wptag(o, "IEND"); - stbiw__wpcrc(&o,0); - - STBIW_ASSERT(o == out + *out_len); - - return out; -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) -{ - FILE *f; - int len; - unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - - f = stbiw__fopen(filename, "wb"); - if (!f) { STBIW_FREE(png); return 0; } - fwrite(png, 1, len, f); - fclose(f); - STBIW_FREE(png); - return 1; -} -#endif - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) -{ - int len; - unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - func(context, png, len); - STBIW_FREE(png); - return 1; -} - - -/* *************************************************************************** - * - * JPEG writer - * - * This is based on Jon Olick's jo_jpeg.cpp: - * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html - */ - -static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, - 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; - -static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { - int bitBuf = *bitBufP, bitCnt = *bitCntP; - bitCnt += bs[1]; - bitBuf |= bs[0] << (24 - bitCnt); - while(bitCnt >= 8) { - unsigned char c = (bitBuf >> 16) & 255; - stbiw__putc(s, c); - if(c == 255) { - stbiw__putc(s, 0); - } - bitBuf <<= 8; - bitCnt -= 8; - } - *bitBufP = bitBuf; - *bitCntP = bitCnt; -} - -static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { - float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; - float z1, z2, z3, z4, z5, z11, z13; - - float tmp0 = d0 + d7; - float tmp7 = d0 - d7; - float tmp1 = d1 + d6; - float tmp6 = d1 - d6; - float tmp2 = d2 + d5; - float tmp5 = d2 - d5; - float tmp3 = d3 + d4; - float tmp4 = d3 - d4; - - // Even part - float tmp10 = tmp0 + tmp3; // phase 2 - float tmp13 = tmp0 - tmp3; - float tmp11 = tmp1 + tmp2; - float tmp12 = tmp1 - tmp2; - - d0 = tmp10 + tmp11; // phase 3 - d4 = tmp10 - tmp11; - - z1 = (tmp12 + tmp13) * 0.707106781f; // c4 - d2 = tmp13 + z1; // phase 5 - d6 = tmp13 - z1; - - // Odd part - tmp10 = tmp4 + tmp5; // phase 2 - tmp11 = tmp5 + tmp6; - tmp12 = tmp6 + tmp7; - - // The rotator is modified from fig 4-8 to avoid extra negations. - z5 = (tmp10 - tmp12) * 0.382683433f; // c6 - z2 = tmp10 * 0.541196100f + z5; // c2-c6 - z4 = tmp12 * 1.306562965f + z5; // c2+c6 - z3 = tmp11 * 0.707106781f; // c4 - - z11 = tmp7 + z3; // phase 5 - z13 = tmp7 - z3; - - *d5p = z13 + z2; // phase 6 - *d3p = z13 - z2; - *d1p = z11 + z4; - *d7p = z11 - z4; - - *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; -} - -static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { - int tmp1 = val < 0 ? -val : val; - val = val < 0 ? val-1 : val; - bits[1] = 1; - while(tmp1 >>= 1) { - ++bits[1]; - } - bits[0] = val & ((1<0)&&(DU[end0pos]==0); --end0pos) { - } - // end0pos = first element in reverse order !=0 - if(end0pos == 0) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - return DU[0]; - } - for(i = 1; i <= end0pos; ++i) { - int startpos = i; - int nrzeroes; - unsigned short bits[2]; - for (; DU[i]==0 && i<=end0pos; ++i) { - } - nrzeroes = i-startpos; - if ( nrzeroes >= 16 ) { - int lng = nrzeroes>>4; - int nrmarker; - for (nrmarker=1; nrmarker <= lng; ++nrmarker) - stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); - nrzeroes &= 15; - } - stbiw__jpg_calcBits(DU[i], bits); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); - } - if(end0pos != 63) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - } - return DU[0]; -} - -static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { - // Constants that don't pollute global namespace - static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; - static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; - static const unsigned char std_ac_luminance_values[] = { - 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, - 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, - 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, - 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, - 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, - 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, - 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; - static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; - static const unsigned char std_ac_chrominance_values[] = { - 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, - 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, - 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, - 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, - 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, - 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, - 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - // Huffman tables - static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; - static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; - static const unsigned short YAC_HT[256][2] = { - {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const unsigned short UVAC_HT[256][2] = { - {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, - 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; - static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; - static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, - 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; - - int row, col, i, k, subsample; - float fdtbl_Y[64], fdtbl_UV[64]; - unsigned char YTable[64], UVTable[64]; - - if(!data || !width || !height || comp > 4 || comp < 1) { - return 0; - } - - quality = quality ? quality : 90; - subsample = quality <= 90 ? 1 : 0; - quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; - quality = quality < 50 ? 5000 / quality : 200 - quality * 2; - - for(i = 0; i < 64; ++i) { - int uvti, yti = (YQT[i]*quality+50)/100; - YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); - uvti = (UVQT[i]*quality+50)/100; - UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); - } - - for(row = 0, k = 0; row < 8; ++row) { - for(col = 0; col < 8; ++col, ++k) { - fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - } - } - - // Write Headers - { - static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; - static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; - const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), - 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; - s->func(s->context, (void*)head0, sizeof(head0)); - s->func(s->context, (void*)YTable, sizeof(YTable)); - stbiw__putc(s, 1); - s->func(s->context, UVTable, sizeof(UVTable)); - s->func(s->context, (void*)head1, sizeof(head1)); - s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); - s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); - stbiw__putc(s, 0x10); // HTYACinfo - s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); - s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); - stbiw__putc(s, 1); // HTUDCinfo - s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); - stbiw__putc(s, 0x11); // HTUACinfo - s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); - s->func(s->context, (void*)head2, sizeof(head2)); - } - - // Encode 8x8 macroblocks - { - static const unsigned short fillBits[] = {0x7F, 7}; - int DCY=0, DCU=0, DCV=0; - int bitBuf=0, bitCnt=0; - // comp == 2 is grey+alpha (alpha is ignored) - int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; - const unsigned char *dataR = (const unsigned char *)data; - const unsigned char *dataG = dataR + ofsG; - const unsigned char *dataB = dataR + ofsB; - int x, y, pos; - if(subsample) { - for(y = 0; y < height; y += 16) { - for(x = 0; x < width; x += 16) { - float Y[256], U[256], V[256]; - for(row = y, pos = 0; row < y+16; ++row) { - // row >= height => use last input row - int clamped_row = (row < height) ? row : height - 1; - int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; - for(col = x; col < x+16; ++col, ++pos) { - // if col >= width => use pixel from last input column - int p = base_p + ((col < width) ? col : (width-1))*comp; - float r = dataR[p], g = dataG[p], b = dataB[p]; - Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; - U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; - V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; - } - } - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - - // subsample U,V - { - float subU[64], subV[64]; - int yy, xx; - for(yy = 0, pos = 0; yy < 8; ++yy) { - for(xx = 0; xx < 8; ++xx, ++pos) { - int j = yy*32+xx*2; - subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; - subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; - } - } - DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); - DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - } - } - } - } else { - for(y = 0; y < height; y += 8) { - for(x = 0; x < width; x += 8) { - float Y[64], U[64], V[64]; - for(row = y, pos = 0; row < y+8; ++row) { - // row >= height => use last input row - int clamped_row = (row < height) ? row : height - 1; - int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; - for(col = x; col < x+8; ++col, ++pos) { - // if col >= width => use pixel from last input column - int p = base_p + ((col < width) ? col : (width-1))*comp; - float r = dataR[p], g = dataG[p], b = dataB[p]; - Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; - U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; - V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; - } - } - - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); - DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - } - } - } - - // Do the bit alignment of the EOI marker - stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); - } - - // EOI - stbiw__putc(s, 0xFF); - stbiw__putc(s, 0xD9); - - return 1; -} - -STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); -} - - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif - -#endif // STB_IMAGE_WRITE_IMPLEMENTATION - -/* Revision history - 1.16 (2021-07-11) - make Deflate code emit uncompressed blocks when it would otherwise expand - support writing BMPs with alpha channel - 1.15 (2020-07-13) unknown - 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels - 1.13 - 1.12 - 1.11 (2019-08-11) - - 1.10 (2019-02-07) - support utf8 filenames in Windows; fix warnings and platform ifdefs - 1.09 (2018-02-11) - fix typo in zlib quality API, improve STB_I_W_STATIC in C++ - 1.08 (2018-01-29) - add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter - 1.07 (2017-07-24) - doc fix - 1.06 (2017-07-23) - writing JPEG (using Jon Olick's code) - 1.05 ??? - 1.04 (2017-03-03) - monochrome BMP expansion - 1.03 ??? - 1.02 (2016-04-02) - avoid allocating large structures on the stack - 1.01 (2016-01-16) - STBIW_REALLOC_SIZED: support allocators with no realloc support - avoid race-condition in crc initialization - minor compile issues - 1.00 (2015-09-14) - installable file IO function - 0.99 (2015-09-13) - warning fixes; TGA rle support - 0.98 (2015-04-08) - added STBIW_MALLOC, STBIW_ASSERT etc - 0.97 (2015-01-18) - fixed HDR asserts, rewrote HDR rle logic - 0.96 (2015-01-17) - add HDR output - fix monochrome BMP - 0.95 (2014-08-17) - add monochrome TGA output - 0.94 (2014-05-31) - rename private functions to avoid conflicts with stb_image.h - 0.93 (2014-05-27) - warning fixes - 0.92 (2010-08-01) - casts to unsigned char to fix warnings - 0.91 (2010-07-17) - first public release - 0.90 first internal release -*/ - -/* ------------------------------------------------------------------------------- -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. ------------------------------------------------------------------------------- -*/ diff --git a/main.cpp b/main.cpp deleted file mode 100644 index f8b6e98..0000000 --- a/main.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include - -#include "WallpaperEngine/Application/CApplicationContext.h" -#include "WallpaperEngine/Application/CWallpaperApplication.h" -#include "WallpaperEngine/WebBrowser/CWebBrowserContext.h" -#include "common.h" - -WallpaperEngine::Application::CWallpaperApplication* appPointer; - -void signalhandler(int sig) -{ - if (appPointer == nullptr) - return; - - appPointer->signal (sig); -} - -void initLogging () -{ - sLog.addOutput (new std::ostream (std::cout.rdbuf ())); - sLog.addError (new std::ostream (std::cerr.rdbuf ())); -} - -int main (int argc, char* argv[]) { - initLogging (); - WallpaperEngine::WebBrowser::CWebBrowserContext webBrowserContext(argc, argv); - WallpaperEngine::Application::CApplicationContext appContext (argc, argv); - - // halt if the list-properties option was specified - if (appContext.settings.general.onlyListProperties) - return 0; - - WallpaperEngine::Application::CWallpaperApplication app (appContext, webBrowserContext); - - appPointer = &app; - - // attach signals to gracefully stop - std::signal (SIGINT, signalhandler); - std::signal (SIGTERM, signalhandler); - - // show the wallpaper application - app.show (); - - appPointer = nullptr; - return 0; -} \ No newline at end of file diff --git a/packaging/archlinux/PKGBUILD b/packaging/archlinux/PKGBUILD index 19ee1b2..2eff102 100644 --- a/packaging/archlinux/PKGBUILD +++ b/packaging/archlinux/PKGBUILD @@ -24,6 +24,12 @@ pkgver() { ) } +prepare() { + cd "$pkgname" + git submodule update --init --recursive + git -c protocol.file.allow=always submodule update +} + build() { cmake -B build -S "$pkgname" \ -DCMAKE_BUILD_TYPE='Release' \ diff --git a/share/patches/lens_flare_sun.frag.json b/share/patches/lens_flare_sun.frag.json deleted file mode 100644 index 322eda3..0000000 --- a/share/patches/lens_flare_sun.frag.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "patches": [ - { - "matches": [ - "uniform float u_pointerSpeed;", - "uniform vec2 g_PointerPosition;", - "float pointer= g_PointerPosition.xy * u_pointerSpeed;" - ], - "replacements": { - "float pointer= g_PointerPosition.xy * u_pointerSpeed;": "float pointer= (g_PointerPosition.xy * u_pointerSpeed).x;" - } - } - ] -} \ No newline at end of file diff --git a/share/patches/vhstest.vert.json b/share/patches/vhstest.vert.json deleted file mode 100644 index acdaa5c..0000000 --- a/share/patches/vhstest.vert.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "patches": [ - { - "matches": [ - "uniform float g_Chromatic;", - "g_AudioSpectrum16Left[g_Chromatic]" - ], - "replacements": { - "g_AudioSpectrum16Left[g_Chromatic]": "g_AudioSpectrum16Left[int(g_Chromatic)]" - } - } - ] -} \ No newline at end of file diff --git a/share/patches/water_caustics.frag.json b/share/patches/water_caustics.frag.json deleted file mode 100644 index ccc6660..0000000 --- a/share/patches/water_caustics.frag.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "patches": [ - { - "matches": [ - "varying vec2 v_TexCoord;", - "vec4 scene= texSample2D(g_Texture0, v_TexCoord);", - "float mask= texSample2D(g_Texture1, v_TexCoord.zw).r;" - ], - "replacements": { - "varying vec2 v_TexCoord;": "varying vec4 v_TexCoord;", - "vec4 scene= texSample2D(g_Texture0, v_TexCoord);": "vec4 scene= texSample2D(g_Texture0, v_TexCoord.xy);", - "vec3 colour= vec3(pow(abs(c), u_WaveColor * u_Brightness));": "vec3 colour= vec3(pow(abs(c), (u_WaveColor * u_Brightness).x));" - } - } - ] -} \ No newline at end of file diff --git a/src/External/Android/fft.cpp b/src/External/Android/fft.cpp deleted file mode 100644 index 3121192..0000000 --- a/src/External/Android/fft.cpp +++ /dev/null @@ -1,162 +0,0 @@ -#include "fft.h" - -namespace External::Android { -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* A Fixed point implementation of Fast Fourier Transform (FFT). Complex numbers - * are represented by 32-bit integers, where higher 16 bits are real part and - * lower ones are imaginary part. Few compromises are made between efficiency, - * accuracy, and maintainability. To make it fast, arithmetic shifts are used - * instead of divisions, and bitwise inverses are used instead of negates. To - * keep it small, only radix-2 Cooley-Tukey algorithm is implemented, and only - * half of the twiddle factors are stored. Although there are still ways to make - * it even faster or smaller, it costs too much on one of the aspects. - */ -#ifdef __arm__ -#include -#endif -#define LOG_FFT_SIZE 10 -#define MAX_FFT_SIZE (1 << LOG_FFT_SIZE) -static const int32_t twiddle [MAX_FFT_SIZE / 4] = { - 0x00008000, 0xff378001, 0xfe6e8002, 0xfda58006, 0xfcdc800a, 0xfc13800f, 0xfb4a8016, 0xfa81801e, 0xf9b88027, - 0xf8ef8032, 0xf827803e, 0xf75e804b, 0xf6958059, 0xf5cd8068, 0xf5058079, 0xf43c808b, 0xf374809e, 0xf2ac80b2, - 0xf1e480c8, 0xf11c80de, 0xf05580f6, 0xef8d8110, 0xeec6812a, 0xedff8146, 0xed388163, 0xec718181, 0xebab81a0, - 0xeae481c1, 0xea1e81e2, 0xe9588205, 0xe892822a, 0xe7cd824f, 0xe7078276, 0xe642829d, 0xe57d82c6, 0xe4b982f1, - 0xe3f4831c, 0xe3308349, 0xe26d8377, 0xe1a983a6, 0xe0e683d6, 0xe0238407, 0xdf61843a, 0xde9e846e, 0xdddc84a3, - 0xdd1b84d9, 0xdc598511, 0xdb998549, 0xdad88583, 0xda1885be, 0xd95885fa, 0xd8988637, 0xd7d98676, 0xd71b86b6, - 0xd65c86f6, 0xd59e8738, 0xd4e1877b, 0xd42487c0, 0xd3678805, 0xd2ab884c, 0xd1ef8894, 0xd13488dd, 0xd0798927, - 0xcfbe8972, 0xcf0489be, 0xce4b8a0c, 0xcd928a5a, 0xccd98aaa, 0xcc218afb, 0xcb698b4d, 0xcab28ba0, 0xc9fc8bf5, - 0xc9468c4a, 0xc8908ca1, 0xc7db8cf8, 0xc7278d51, 0xc6738dab, 0xc5c08e06, 0xc50d8e62, 0xc45b8ebf, 0xc3a98f1d, - 0xc2f88f7d, 0xc2488fdd, 0xc198903e, 0xc0e990a1, 0xc03a9105, 0xbf8c9169, 0xbedf91cf, 0xbe329236, 0xbd86929e, - 0xbcda9307, 0xbc2f9371, 0xbb8593dc, 0xbadc9448, 0xba3394b5, 0xb98b9523, 0xb8e39592, 0xb83c9603, 0xb7969674, - 0xb6f196e6, 0xb64c9759, 0xb5a897ce, 0xb5059843, 0xb46298b9, 0xb3c09930, 0xb31f99a9, 0xb27f9a22, 0xb1df9a9c, - 0xb1409b17, 0xb0a29b94, 0xb0059c11, 0xaf689c8f, 0xaecc9d0e, 0xae319d8e, 0xad979e0f, 0xacfd9e91, 0xac659f14, - 0xabcd9f98, 0xab36a01c, 0xaaa0a0a2, 0xaa0aa129, 0xa976a1b0, 0xa8e2a238, 0xa84fa2c2, 0xa7bda34c, 0xa72ca3d7, - 0xa69ca463, 0xa60ca4f0, 0xa57ea57e, 0xa4f0a60c, 0xa463a69c, 0xa3d7a72c, 0xa34ca7bd, 0xa2c2a84f, 0xa238a8e2, - 0xa1b0a976, 0xa129aa0a, 0xa0a2aaa0, 0xa01cab36, 0x9f98abcd, 0x9f14ac65, 0x9e91acfd, 0x9e0fad97, 0x9d8eae31, - 0x9d0eaecc, 0x9c8faf68, 0x9c11b005, 0x9b94b0a2, 0x9b17b140, 0x9a9cb1df, 0x9a22b27f, 0x99a9b31f, 0x9930b3c0, - 0x98b9b462, 0x9843b505, 0x97ceb5a8, 0x9759b64c, 0x96e6b6f1, 0x9674b796, 0x9603b83c, 0x9592b8e3, 0x9523b98b, - 0x94b5ba33, 0x9448badc, 0x93dcbb85, 0x9371bc2f, 0x9307bcda, 0x929ebd86, 0x9236be32, 0x91cfbedf, 0x9169bf8c, - 0x9105c03a, 0x90a1c0e9, 0x903ec198, 0x8fddc248, 0x8f7dc2f8, 0x8f1dc3a9, 0x8ebfc45b, 0x8e62c50d, 0x8e06c5c0, - 0x8dabc673, 0x8d51c727, 0x8cf8c7db, 0x8ca1c890, 0x8c4ac946, 0x8bf5c9fc, 0x8ba0cab2, 0x8b4dcb69, 0x8afbcc21, - 0x8aaaccd9, 0x8a5acd92, 0x8a0cce4b, 0x89becf04, 0x8972cfbe, 0x8927d079, 0x88ddd134, 0x8894d1ef, 0x884cd2ab, - 0x8805d367, 0x87c0d424, 0x877bd4e1, 0x8738d59e, 0x86f6d65c, 0x86b6d71b, 0x8676d7d9, 0x8637d898, 0x85fad958, - 0x85beda18, 0x8583dad8, 0x8549db99, 0x8511dc59, 0x84d9dd1b, 0x84a3dddc, 0x846ede9e, 0x843adf61, 0x8407e023, - 0x83d6e0e6, 0x83a6e1a9, 0x8377e26d, 0x8349e330, 0x831ce3f4, 0x82f1e4b9, 0x82c6e57d, 0x829de642, 0x8276e707, - 0x824fe7cd, 0x822ae892, 0x8205e958, 0x81e2ea1e, 0x81c1eae4, 0x81a0ebab, 0x8181ec71, 0x8163ed38, 0x8146edff, - 0x812aeec6, 0x8110ef8d, 0x80f6f055, 0x80def11c, 0x80c8f1e4, 0x80b2f2ac, 0x809ef374, 0x808bf43c, 0x8079f505, - 0x8068f5cd, 0x8059f695, 0x804bf75e, 0x803ef827, 0x8032f8ef, 0x8027f9b8, 0x801efa81, 0x8016fb4a, 0x800ffc13, - 0x800afcdc, 0x8006fda5, 0x8002fe6e, 0x8001ff37, -}; - -/* Returns the multiplication of \conj{a} and {b}. */ -static inline int32_t mult (int32_t a, int32_t b) { -#if __ARM_ARCH__ >= 6 - int32_t t = b; - __asm__ ("smuad %0, %0, %1" : "+r"(t) : "r"(a)); - __asm__ ("smusdx %0, %0, %1" : "+r"(b) : "r"(a)); - __asm__ ("pkhtb %0, %0, %1, ASR #16" : "+r"(t) : "r"(b)); - return t; -#else - return (((a >> 16) * (b >> 16) + static_cast (a) * static_cast (b)) & ~0xFFFF) | - ((((a >> 16) * static_cast (b) - static_cast (a) * (b >> 16)) >> 16) & 0xFFFF); -#endif -} - -static inline int32_t half (int32_t a) { -#if __ARM_ARCH__ >= 6 - __asm__ ("shadd16 %0, %0, %1" : "+r"(a) : "r"(0)); - return a; -#else - return ((a >> 1) & ~0x8000) | (a & 0x8000); -#endif -} - -void fixed_fft (int n, int32_t* v) { - int scale = LOG_FFT_SIZE, i, p, r; - for (r = 0, i = 1; i < n; ++i) { - for (p = n; !(p & r); p >>= 1, r ^= p) - ; - if (i < r) { - int32_t t = v [i]; - v [i] = v [r]; - v [r] = t; - } - } - for (p = 1; p < n; p <<= 1) { - --scale; - for (i = 0; i < n; i += p << 1) { - int32_t x = half (v [i]); - int32_t y = half (v [i + p]); - v [i] = x + y; - v [i + p] = x - y; - } - for (r = 1; r < p; ++r) { - int32_t w = MAX_FFT_SIZE / 4 - (r << scale); - i = w >> 31; - w = twiddle [(w ^ i) - i] ^ (i << 16); - for (i = r; i < n; i += p << 1) { - int32_t x = half (v [i]); - int32_t y = mult (w, v [i + p]); - v [i] = x - y; - v [i + p] = x + y; - } - } - } -} - -void fixed_fft_real (int n, int32_t* v) { - int scale = LOG_FFT_SIZE, m = n >> 1, i; - fixed_fft (n, v); - for (i = 1; i <= n; i <<= 1, --scale) - ; - v [0] = mult (~v [0], 0x80008000); - v [m] = half (v [m]); - for (i = 1; i < n >> 1; ++i) { - int32_t x = half (v [i]); - int32_t z = half (v [n - i]); - int32_t y = z - (x ^ 0xFFFF); - x = half (x + (z ^ 0xFFFF)); - y = mult (y, twiddle [i << scale]); - v [i] = x - y; - v [n - i] = (x + y) ^ 0xFFFF; - } -} - -bool doFft (uint8_t* fft, uint8_t* waveform) { - int32_t workspace [WAVE_BUFFER_SIZE >> 1]; - int32_t nonzero = 0; - for (uint32_t i = 0; i < WAVE_BUFFER_SIZE; i += 2) { - workspace [i >> 1] = ((waveform [i] ^ 0x80) << 24) | ((waveform [i + 1] ^ 0x80) << 8); - nonzero |= workspace [i >> 1]; - } - if (nonzero) { - fixed_fft_real (WAVE_BUFFER_SIZE >> 1, workspace); - } - for (uint32_t i = 0; i < WAVE_BUFFER_SIZE; i += 2) { - short tmp = workspace [i >> 1] >> 21; - while (tmp > 127 || tmp < -128) - tmp >>= 1; - fft [i] = tmp; - tmp = workspace [i >> 1]; - tmp >>= 5; - while (tmp > 127 || tmp < -128) - tmp >>= 1; - fft [i + 1] = tmp; - } - return true; -} -} // namespace External::Android \ No newline at end of file diff --git a/src/External/Android/fft.h b/src/External/Android/fft.h deleted file mode 100644 index 5f450eb..0000000 --- a/src/External/Android/fft.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include -#include -#include - -#define WAVE_BUFFER_SIZE 1024 - -namespace External::Android { -bool doFft (uint8_t* fft, uint8_t* waveform); -} \ No newline at end of file diff --git a/src/External/MimeTypes b/src/External/MimeTypes new file mode 160000 index 0000000..8990d6a --- /dev/null +++ b/src/External/MimeTypes @@ -0,0 +1 @@ +Subproject commit 8990d6a796bd9904ec3d41e5c150a1ffb48fe32e diff --git a/src/External/SPIRV-Cross-WallpaperEngine b/src/External/SPIRV-Cross-WallpaperEngine new file mode 160000 index 0000000..ad4d022 --- /dev/null +++ b/src/External/SPIRV-Cross-WallpaperEngine @@ -0,0 +1 @@ +Subproject commit ad4d02220b01c1800e5a4e6671d6d8ca8ab07783 diff --git a/src/External/argparse b/src/External/argparse new file mode 160000 index 0000000..d924b84 --- /dev/null +++ b/src/External/argparse @@ -0,0 +1 @@ +Subproject commit d924b84eba1f0f0adf38b20b7b4829f6f65b6570 diff --git a/src/External/glslang-WallpaperEngine b/src/External/glslang-WallpaperEngine new file mode 160000 index 0000000..077d4f3 --- /dev/null +++ b/src/External/glslang-WallpaperEngine @@ -0,0 +1 @@ +Subproject commit 077d4f3c89bbfbb7951a9011d4551b075f092334 diff --git a/src/External/json b/src/External/json new file mode 160000 index 0000000..4424a0f --- /dev/null +++ b/src/External/json @@ -0,0 +1 @@ +Subproject commit 4424a0fcc1c7fa640b5c87d26776d99150dacd10 diff --git a/src/External/kissfft b/src/External/kissfft new file mode 160000 index 0000000..febd4ca --- /dev/null +++ b/src/External/kissfft @@ -0,0 +1 @@ +Subproject commit febd4caeed32e33ad8b2e0bb5ea77542c40f18ec diff --git a/src/External/stb b/src/External/stb new file mode 160000 index 0000000..f056911 --- /dev/null +++ b/src/External/stb @@ -0,0 +1 @@ +Subproject commit f0569113c93ad095470c54bf34a17b36646bbbb5 diff --git a/src/Steam/FileSystem/FileSystem.cpp b/src/Steam/FileSystem/FileSystem.cpp index 62c1cfe..4b4fc8d 100644 --- a/src/Steam/FileSystem/FileSystem.cpp +++ b/src/Steam/FileSystem/FileSystem.cpp @@ -6,14 +6,21 @@ #include #include -const char* assets_default_paths [] = {".steam/steam/steamapps/common", ".local/share/Steam/steamapps/common", - ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/common", - "snap/steam/common/.local/share/Steam/steamapps/common", nullptr}; +const char* assets_default_paths [] = { + ".steam/steam/steamapps/common", + ".local/share/Steam/steamapps/common", + ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/common", + "snap/steam/common/.local/share/Steam/steamapps/common", + nullptr +}; const char* workshop_content_default_paths [] = { - ".local/share/Steam/steamapps/workshop/content", ".steam/steam/steamapps/workshop/content", + ".local/share/Steam/steamapps/workshop/content", + ".steam/steam/steamapps/workshop/content", ".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps/workshop/content", - "snap/steam/common/.local/share/Steam/steamapps/workshop/content", nullptr}; + "snap/steam/common/.local/share/Steam/steamapps/workshop/content", + nullptr +}; std::filesystem::path detectHomepath () { char* home = getenv ("HOME"); diff --git a/src/WallpaperEngine/Application/CApplicationContext.cpp b/src/WallpaperEngine/Application/CApplicationContext.cpp index 4f4d919..3084ac1 100644 --- a/src/WallpaperEngine/Application/CApplicationContext.cpp +++ b/src/WallpaperEngine/Application/CApplicationContext.cpp @@ -5,116 +5,225 @@ #include #include -#include +#include + +#include #define WORKSHOP_APP_ID 431960 #define APP_DIRECTORY "wallpaper_engine" using namespace WallpaperEngine::Application; -struct option long_options [] = { - {"screen-root", required_argument, nullptr, 'r'}, {"bg", required_argument, nullptr, 'b'}, - {"window", required_argument, nullptr, 'w'}, {"pkg", required_argument, nullptr, 'p'}, - {"dir", required_argument, nullptr, 'd'}, {"silent", no_argument, nullptr, 's'}, - {"volume", required_argument, nullptr, 'v'}, {"help", no_argument, nullptr, 'h'}, - {"fps", required_argument, nullptr, 'f'}, {"assets-dir", required_argument, nullptr, 'a'}, - {"screenshot", required_argument, nullptr, 'c'}, {"list-properties", no_argument, nullptr, 'l'}, - {"set-property", required_argument, nullptr, 'o'}, {"noautomute", no_argument, nullptr, 'm'}, - {"no-audio-processing", no_argument, nullptr, 'g'}, {"no-fullscreen-pause", no_argument, nullptr, 'n'}, - {"disable-mouse", no_argument, nullptr, 'e'}, {"scaling", required_argument, nullptr, 't'}, - {"clamping", required_argument, nullptr, 't'}, {nullptr, 0, nullptr, 0}}; - -/* std::hash::operator() isn't constexpr, so it can't be used to get hash values as compile-time constants - * So here is customHash. It skips all spaces, so hashes for " find " and "fi nd" are the same - * Basicly got it from here: https://stackoverflow.com/questions/8317508/hash-function-for-a-string - */ -constexpr size_t customHash (const char* str) { - constexpr size_t A = 54059; /* a prime */ - constexpr size_t B = 76963; /* another prime */ - constexpr size_t C = 86969; /* yet another prime */ - constexpr size_t FIRSTH = 37; /* also prime */ - size_t hash = FIRSTH; - while (*str) { - if (*str != ' ') // Skip spaces - hash = (hash * A) ^ (*str * B); - ++str; - } - return hash % C; -} - -std::string stringPathFixes (const std::string& s) { - if (s.empty ()) - return s; - - std::string str (s); - - // remove single-quotes from the arguments - if (str [0] == '\'' && str [str.size () - 1] == '\'') - str.erase (str.size () - 1, 1).erase (0, 1); - - return std::move (str); -} - -CApplicationContext::CApplicationContext (int argc, char* argv []) { - // setup structs with sane default values for now - this->settings = { - .general = - { - .onlyListProperties = false, - .assets = "", - .defaultBackground = "", - .screenBackgrounds = {}, - .properties = {}, - }, - .render = - { - .mode = NORMAL_WINDOW, - .maximumFPS = 30, - .pauseOnFullscreen = true, - .window = - { - .geometry = {}, - .clamp = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVs, - .scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs, - }, - }, - .audio = {.enabled = true, .volume = 15, .automute = true, .audioprocessing = true}, - .mouse = - { - .enabled = true, - }, - .screenshot = - { - .take = false, - .path = "", - }, - }; - - int c; - +CApplicationContext::CApplicationContext (int argc, char* argv []) : + m_argc (argc), + m_argv (argv) { std::string lastScreen; - while ((c = getopt_long (argc, argv, "b:r:p:d:shf:a:w:mnt:", long_options, nullptr)) != -1) { - switch (c) { - case 'n': this->settings.render.pauseOnFullscreen = false; break; + argparse::ArgumentParser program ("linux-wallpaperengine", "0.0", argparse::default_arguments::help); - case 'b': - if (lastScreen.empty ()) - sLog.exception ("--bg has to go after a --screen-root argument"); + auto& backgroundGroup = program.add_group ("Background options"); + auto& backgroundMode = backgroundGroup.add_mutually_exclusive_group (false); - // no need to check for previous screen being in the list, as it's the only way for this variable - // to have any value - this->settings.general.screenBackgrounds [lastScreen] = translateBackground (optarg); - this->settings.general.screenScalings [lastScreen] = this->settings.render.window.scalingMode; + backgroundGroup.add_argument ("background id") + .help ("The background to use as default for screens with no background specified") + .action([this](const std::string& value) -> void { + this->settings.general.defaultBackground = translateBackground (value); + }); - // update default background if not set - if (this->settings.general.defaultBackground.empty()) { - this->settings.general.defaultBackground = translateBackground (optarg); + backgroundMode.add_argument ("-w", "--window") + .help ("Window geometry to use for the given screen") + .action ([this](const std::string& value) -> void { + if (this->settings.render.mode == DESKTOP_BACKGROUND) { + sLog.exception ("Cannot run in both background and window mode"); + } + if (this->settings.render.mode == EXPLICIT_WINDOW) { + sLog.exception ("Only one window at a time can be specified in explicit window mode"); } - break; - case 'o': { - std::string value = optarg; + this->settings.render.mode = EXPLICIT_WINDOW; + + if (value.empty ()) { + sLog.exception ("Window geometry cannot be empty"); + } + + const char* str = value.c_str (); + const char* delim1 = strchr (str, 'x'); + const char* delim2 = delim1 ? strchr (delim1 + 1, 'x') : nullptr; + const char* delim3 = delim2 ? strchr (delim2 + 1, 'x') : nullptr; + + if (delim1 == nullptr || delim2 == nullptr || delim3 == nullptr) { + sLog.exception ("Window geometry must be in the format: XxYxWxH"); + } + + this->settings.render.window.geometry.x = strtol(str, nullptr, 10); + this->settings.render.window.geometry.y = strtol (delim1 + 1, nullptr, 10); + this->settings.render.window.geometry.z = strtol (delim2 + 1, nullptr, 10); + this->settings.render.window.geometry.w = strtol (delim3 + 1, nullptr, 10); + }) + .append (); + backgroundMode.add_argument ("-r", "--screen-root") + .help ("The screen the following settings will have an effect on") + .action([this, &lastScreen](const std::string& value) -> void { + if (this->settings.general.screenBackgrounds.find (value) != this->settings.general.screenBackgrounds.end ()) { + sLog.exception ("Cannot specify the same screen more than once: ", value); + } + if (this->settings.render.mode == EXPLICIT_WINDOW) { + sLog.exception ("Cannot run in both background and window mode"); + } + + this->settings.render.mode = DESKTOP_BACKGROUND; + lastScreen = value; + this->settings.general.screenBackgrounds [lastScreen] = ""; + this->settings.general.screenScalings [lastScreen] = this->settings.render.window.scalingMode; + this->settings.general.screenClamps [lastScreen] = this->settings.render.window.clamp; + }) + .append (); + backgroundGroup.add_argument ("-b", "--bg") + .help ("After --screen-root, specifies the background to use for the given screen") + .action ([this, &lastScreen](const std::string& value) -> void { + this->settings.general.screenBackgrounds [lastScreen] = translateBackground (value); + // set the default background to the last one used + this->settings.general.defaultBackground = translateBackground (value); + }) + .append (); + backgroundGroup.add_argument ("--scaling") + .help ("Scaling mode to use when rendering the background, this applies to the previous --window or --screen-root output, or the default background if no other background is specified") + .choices ("stretch", "fit", "fill", "default") + .action([this, &lastScreen](const std::string& value) -> void { + WallpaperEngine::Render::CWallpaperState::TextureUVsScaling mode; + + if (value == "stretch") { + mode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::StretchUVs; + } else if (value == "fit") { + mode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFitUVs; + } else if (value == "fill") { + mode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFillUVs; + } else if (value == "default") { + mode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs; + } else { + sLog.exception ("Invalid scaling mode: ", value); + } + + if (this->settings.render.mode == DESKTOP_BACKGROUND) { + this->settings.general.screenScalings [lastScreen] = mode; + } else { + this->settings.render.window.scalingMode = mode; + } + }) + .append (); + backgroundGroup.add_argument ("--clamp") + .help ("Clamp mode to use when rendering the background, this applies to the previous --window or --screen-root output, or the default background if no other background is specified") + .choices("clamp", "border", "repeat") + .action([this, &lastScreen](const std::string& value) -> void { + WallpaperEngine::Assets::ITexture::TextureFlags flags; + + if (value == "clamp") { + flags = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVs; + } else if (value == "border") { + flags = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVsBorder; + } else if (value == "repeat") { + flags = WallpaperEngine::Assets::ITexture::TextureFlags::NoFlags; + } else { + sLog.exception ("Invalid clamp mode: ", value); + } + + if (this->settings.render.mode == DESKTOP_BACKGROUND) { + this->settings.general.screenClamps [lastScreen] = flags; + } else { + this->settings.render.window.clamp = flags; + } + }); + + auto& performanceGroup = program.add_group ("Performance options"); + + performanceGroup.add_argument ("-f", "--fps") + .help ("Limits the FPS to the given number, useful to keep battery consumption low") + .default_value (30) + .store_into(this->settings.render.maximumFPS); + + performanceGroup.add_argument ("--no-fullscreen-pause") + .help ("Prevents the background pausing when an app is fullscreen") + .flag () + .action ([this](const std::string& value) -> void { + this->settings.render.pauseOnFullscreen = false; + }); + + auto& audioGroup = program.add_group ("Sound settings"); + auto& audioSettingsGroup = audioGroup.add_mutually_exclusive_group (false); + + audioSettingsGroup.add_argument ("-v", "--volume") + .help ("Volume for all the sounds in the background") + .default_value (15) + .store_into (this->settings.audio.volume); + + audioSettingsGroup.add_argument ("-s", "--silent") + .help ("Mutes all the sound the wallpaper might produce") + .flag () + .action ([this](const std::string& value) -> void { + this->settings.audio.enabled = false; + }); + + audioGroup.add_argument ("--noautomute") + .help ("Disables the automute when an app is playing sound") + .flag () + .action([this](const std::string& value) -> void { + this->settings.audio.automute = false; + }); + + audioGroup.add_argument ("--no-audio-processing") + .help ("Disables audio processing for backgrounds") + .flag () + .action ([this](const std::string& value) -> void { + this->settings.audio.audioprocessing = false; + }); + + auto& screenshotGroup = program.add_group ("Screenshot options"); + + screenshotGroup.add_argument ("--screenshot") + .help ("Takes a screenshot of the background for it's use with tools like PyWAL") + .default_value ("") + .action ([this](const std::string& value) -> void { + this->settings.screenshot.take = true; + this->settings.screenshot.path = value; + }); + + screenshotGroup.add_argument ("--screenshot-delay") + .help ("Frames to wait before taking the screenshot") + .default_value (5) + .store_into (this->settings.screenshot.delay); + + auto& contentGroup = program.add_group ("Content options"); + + contentGroup.add_argument ("--assets-dir") + .help ("Folder where the assets are stored") + .default_value ("") + .action ([this](const std::string& value) -> void { + this->settings.general.assets = value; + }); + + auto& configurationGroup = program.add_group ("Wallpaper configuration options"); + + configurationGroup.add_argument ("--disable-mouse") + .help ("Disables mouse interaction with the backgrounds") + .flag () + .action ([this](const std::string& value) -> void { + this->settings.mouse.enabled = false; + }); + configurationGroup.add_argument ("--disable-parallax") + .help ("Disables parallax effect for the backgrounds") + .flag () + .action ([this](const std::string& value) -> void { + this->settings.mouse.disableparallax = true; + }); + + configurationGroup.add_argument ("-l", "--list-properties") + .help ("List all the available properties and their configuration") + .flag () + .store_into (this->settings.general.onlyListProperties); + + configurationGroup.add_argument ("--set-property", "--property") + .help ("Overrides the default value of the given property") + .action([this](const std::string& value) -> void { const std::string::size_type equals = value.find ('='); // properties without value are treated as booleans for now @@ -122,122 +231,44 @@ CApplicationContext::CApplicationContext (int argc, char* argv []) { this->settings.general.properties [value] = "1"; else this->settings.general.properties [value.substr (0, equals)] = value.substr (equals + 1); - } break; + }); - case 'l': this->settings.general.onlyListProperties = true; break; + auto& debuggingGroup = program.add_group ("Debugging options"); - case 'r': - if (this->settings.general.screenBackgrounds.find (optarg) != - this->settings.general.screenBackgrounds.end ()) - sLog.exception ("Cannot specify the same screen more than once: ", optarg); - if (this->settings.render.mode == EXPLICIT_WINDOW) - sLog.exception ("Cannot run in both background and window mode"); + debuggingGroup.add_argument ("-z", "--dump-structure") + .help ("Dumps the structure of the backgrounds") + .flag () + .store_into (this->settings.general.dumpStructure); - this->settings.render.mode = DESKTOP_BACKGROUND; - lastScreen = optarg; - this->settings.general.screenBackgrounds [lastScreen] = ""; - this->settings.general.screenScalings [lastScreen] = this->settings.render.window.scalingMode; - break; + program.add_epilog ( + "Usage examples:\n" + " linux-wallpaperengine --screen-root HDMI-1 --bg 2317494988 --scaling fill --clamp border\n" + " Runs the background 2317494988 on screen HDMI-1, scaling it to fill the screen and clamping the UVs to the border\n\n" + " linux-wallpaperengine 2317494988\n" + " Previews the background 2317494988 on a window\n\n" + " linux-wallpaperengine --screen-root HDMI-1 --bg 2317494988 --screen-root HDMI-2 --bg 1108150151\n" + " Runs two backgrounds on two screens, one on HDMI-1 and the other on HDMI-2\n\n" + " linux-wallpaperengine --screen-root HDMI-1 --screen-root HDMI-2 2317494988\n" + " Runs the background 2317494988 on two screens, one on HDMI-1 and the other on HDMI-2\n\n" + ); - case 'w': - if (this->settings.render.mode == DESKTOP_BACKGROUND) - sLog.exception ("Cannot run in both background and window mode"); + program.parse_known_args (argc, argv); - if (optarg != nullptr) { - this->settings.render.mode = EXPLICIT_WINDOW; - // read window geometry - char* pos = optarg; + this->settings.audio.volume = std::max(0, std::min (this->settings.audio.volume, 128)); + this->settings.screenshot.delay = std::max (0, std::min (this->settings.screenshot.delay, 5)); - if (pos != nullptr) - this->settings.render.window.geometry.x = atoi (pos); - if ((pos = strchr (pos, 'x')) != nullptr) - this->settings.render.window.geometry.y = atoi (pos + 1); - if ((pos = strchr (pos + 1, 'x')) != nullptr) - this->settings.render.window.geometry.z = atoi (pos + 1); - if ((pos = strchr (pos + 1, 'x')) != nullptr) - this->settings.render.window.geometry.w = atoi (pos + 1); - } - break; + // use std::cout on this in case logging is disabled, this way it's easy to look at what is running + std::stringbuf buffer; + std::ostream bufferStream (&buffer); - case 'p': - case 'd': - sLog.error ("--dir/--pkg is deprecated and not used anymore"); - this->settings.general.defaultBackground = translateBackground (stringPathFixes (optarg)); - break; + bufferStream << "Running with: "; - case 's': this->settings.audio.enabled = false; break; - - case 'h': - printHelp (argv [0]); - std::exit (0); - break; - - case 'f': this->settings.render.maximumFPS = atoi (optarg); break; - - case 'a': this->settings.general.assets = stringPathFixes (optarg); break; - - case 'v': this->settings.audio.volume = std::max (atoi (optarg), 128); break; - - case 'c': - this->settings.screenshot.take = true; - this->settings.screenshot.path = stringPathFixes (optarg); - break; - - case 'm': this->settings.audio.automute = false; break; - - case 'g': this->settings.audio.audioprocessing = false; break; - - case 'e': this->settings.mouse.enabled = false; break; - - case 't': { - size_t hash = customHash (optarg); - // Use a switch statement with the hash - switch (hash) { - // --scale options - case customHash ("stretch"): - this->settings.render.window.scalingMode = - WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::StretchUVs; - break; - case customHash ("fit"): - this->settings.render.window.scalingMode = - WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFitUVs; - break; - case customHash ("fill"): - this->settings.render.window.scalingMode = - WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::ZoomFillUVs; - break; - case customHash ("default"): - this->settings.render.window.scalingMode = - WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs; - break; - // --clamp options - case customHash ("clamp"): - this->settings.render.window.clamp = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVs; - break; - case customHash ("border"): - this->settings.render.window.clamp = - WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVsBorder; - break; - case customHash ("repeat"): - this->settings.render.window.clamp = WallpaperEngine::Assets::ITexture::TextureFlags::NoFlags; - break; - default: - sLog.error ("Wrong argument:"); - sLog.error (optarg); - sLog.exception ("Wrong argument provided for --scale or --clamp option."); - break; - } - } break; - default: sLog.out ("Default on path parsing: ", optarg); break; - } - } - - if (this->settings.general.defaultBackground.empty ()) { - if (optind < argc && strlen (argv [optind]) > 0) { - this->settings.general.defaultBackground = translateBackground (argv [optind]); - } + for (int i = 0; i < argc; i ++) { + bufferStream << argv [i]; + bufferStream << " "; } + std::cout << buffer.str() << std::endl; // perform some extra validation on the inputs this->validateAssets (); this->validateScreenshot (); @@ -246,6 +277,23 @@ CApplicationContext::CApplicationContext (int argc, char* argv []) { this->state.general.keepRunning = true; this->state.audio.enabled = this->settings.audio.enabled; this->state.audio.volume = this->settings.audio.volume; + this->state.mouse.enabled = this->settings.mouse.enabled; + +#if DEMOMODE + sLog.error ("WARNING: RUNNING IN DEMO MODE WILL STOP WALLPAPERS AFTER 5 SECONDS SO VIDEO CAN BE RECORDED"); + // special settings for demomode + this->settings.render.maximumFPS = 30; + this->settings.screenshot.take = false; + this->settings.render.pauseOnFullscreen = false; +#endif /* DEMOMODE */ +} + +int CApplicationContext::getArgc () const { + return this->m_argc; +} + +char** CApplicationContext::getArgv () const { + return this->m_argv; } std::filesystem::path CApplicationContext::translateBackground (const std::string& bgIdOrPath) { @@ -270,7 +318,7 @@ void CApplicationContext::validateAssets () { } } -void CApplicationContext::validateScreenshot () { +void CApplicationContext::validateScreenshot () const { if (!this->settings.screenshot.take) return; @@ -282,35 +330,3 @@ void CApplicationContext::validateScreenshot () { if (extension != ".bmp" && extension != ".png" && extension != ".jpeg" && extension != ".jpg") sLog.exception ("Cannot determine screenshot format, unknown extension ", extension); } - -void CApplicationContext::printHelp (const char* route) { - sLog.out ("Usage: ", route, " [options] background_path/background_id"); - sLog.out (""); - sLog.out ("where background_path/background_id can be:"); - sLog.out ("\tthe ID of the background (for autodetection on your steam installation)"); - sLog.out ("\ta full path to the background's folder"); - sLog.out (""); - sLog.out ("options:"); - sLog.out ("\t--silent\t\t\t\t\tMutes all the sound the wallpaper might produce"); - sLog.out ("\t--volume \t\t\tSets the volume for all the sounds in the background"); - sLog.out ("\t--noautomute\t\t\t\tDisables the automute when an app is playing sound"); - sLog.out ("\t--no-audio-processing\t\t\t\tDisables audio processing for backgrounds"); - sLog.out ("\t--screen-root \tDisplay as screen's background"); - sLog.out ( - "\t--window \tRuns in window mode, geometry has to be XxYxWxH and sets the position and size of the window"); - sLog.out ("\t--fps \t\t\tLimits the FPS to the given number, useful to keep battery consumption low"); - sLog.out ("\t--assets-dir \t\t\tFolder where the assets are stored"); - sLog.out ("\t--screenshot\t\t\t\tTakes a screenshot of the background"); - sLog.out ("\t--list-properties\t\t\tList all the available properties and their possible values"); - sLog.out ("\t--set-property \tOverrides the default value of the given property"); - sLog.out ("\t--no-fullscreen-pause\tPrevents the background pausing when an app is fullscreen"); - sLog.out ("\t--disable-mouse\tDisables mouse interactions"); - sLog.out ( - "\t--bg \tAfter --screen-root uses the specified background only on that screen"); - sLog.out ( - "\t--scaling \t Scaling mode for wallpaper. Can be stretch, fit, fill, default. Must be used before wallpaper provided.\n\ - \t\t For default wallpaper last specified value will be used.\n\ - \t\t Example: ./wallengine --scaling stretch --screen-root eDP-1 --bg 2667198601 --scaling fill --screen-root eDP-2 2667198602"); - sLog.out ( - "\t--clamping \t Clamping mode for all wallpapers. Can be clamp, border, repeat. Enables GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, GL_REPEAT accordingly. Default is clamp."); -} diff --git a/src/WallpaperEngine/Application/CApplicationContext.h b/src/WallpaperEngine/Application/CApplicationContext.h index 3f824b0..95a3772 100644 --- a/src/WallpaperEngine/Application/CApplicationContext.h +++ b/src/WallpaperEngine/Application/CApplicationContext.h @@ -36,18 +36,20 @@ class CApplicationContext { struct { /** If the user requested a list of properties for the given background */ bool onlyListProperties; - + /** If the user requested a dump of the background structure */ + bool dumpStructure; /** The path to the assets folder */ std::filesystem::path assets; /** Background to load (provided as the final argument) as fallback for multi-screen setups */ std::filesystem::path defaultBackground; - /** The backgrounds specified for different screens */ std::map screenBackgrounds; /** Properties to change values for */ std::map properties; /** The scaling mode for different screens */ std::map screenScalings; + /** The clamping mode for different screens */ + std::map screenClamps; } general; /** @@ -89,6 +91,8 @@ class CApplicationContext { struct { /** If the mouse movement is enabled */ bool enabled; + /** If the mouse parallax should be disabled */ + bool disableparallax; } mouse; /** @@ -97,14 +101,60 @@ class CApplicationContext { struct { /** If an screenshot should be taken */ bool take; + /** The frames to wait until the screenshot is taken */ + int delay; /** The path to where the screenshot must be saved */ std::filesystem::path path; } screenshot; - } settings; + } settings = { + .general = { + .onlyListProperties = false, + .dumpStructure = false, + .assets = "", + .defaultBackground = "", + .screenBackgrounds = {}, + .properties = {}, + .screenScalings = {}, + .screenClamps = {}, + }, + .render = { + .mode = NORMAL_WINDOW, + .maximumFPS = 30, + .pauseOnFullscreen = true, + .window = { + .geometry = {}, + .clamp = WallpaperEngine::Assets::ITexture::TextureFlags::ClampUVs, + .scalingMode = WallpaperEngine::Render::CWallpaperState::TextureUVsScaling::DefaultUVs, + }, + }, + .audio = { + .enabled = true, + .volume = 15, + .automute = true, + .audioprocessing = true, + }, + .mouse = { + .enabled = true, + .disableparallax = false, + }, + .screenshot = { + .take = false, + .delay = 5, + .path = "", + }, + }; CApplicationState state; + [[nodiscard]] int getArgc() const; + [[nodiscard]] char** getArgv() const; + private: + /** Program argument count on startup */ + int m_argc; + /** Program arguments on startup */ + char** m_argv; + /** * Validates the assets folder and ensures a valid one is present */ @@ -113,7 +163,7 @@ class CApplicationContext { /** * Validates the screenshot settings */ - void validateScreenshot (); + void validateScreenshot () const; /** * Validates a background parameter and returns the real bgIdOrPath to it @@ -122,10 +172,5 @@ class CApplicationContext { * @return */ static std::filesystem::path translateBackground (const std::string& bgIdOrPath); - - /** - * Prints the normal help message - */ - static void printHelp (const char* route); }; } // namespace WallpaperEngine::Application \ No newline at end of file diff --git a/src/WallpaperEngine/Application/CApplicationState.cpp b/src/WallpaperEngine/Application/CApplicationState.cpp deleted file mode 100644 index 315d0c7..0000000 --- a/src/WallpaperEngine/Application/CApplicationState.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "CApplicationState.h" diff --git a/src/WallpaperEngine/Application/CWallpaperApplication.cpp b/src/WallpaperEngine/Application/CWallpaperApplication.cpp index 3379a38..0c118e1 100644 --- a/src/WallpaperEngine/Application/CWallpaperApplication.cpp +++ b/src/WallpaperEngine/Application/CWallpaperApplication.cpp @@ -6,18 +6,15 @@ #include "WallpaperEngine/Assets/CDirectory.h" #include "WallpaperEngine/Assets/CVirtualContainer.h" #include "WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h" -#include "WallpaperEngine/Input/Drivers/CGLFWMouseInput.h" #include "WallpaperEngine/Logging/CLog.h" #include "WallpaperEngine/Render/CRenderContext.h" +#include "WallpaperEngine/PrettyPrinter/CPrettyPrinter.h" +#include "WallpaperEngine/Core/Wallpapers/CWeb.h" +#include "WallpaperEngine/Render/Drivers/CVideoFactories.h" -#ifdef ENABLE_WAYLAND -#include "WallpaperEngine/Input/Drivers/CWaylandMouseInput.h" -#include "WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" -#endif /* ENABLE_WAYLAND */ - -#ifdef ENABLE_X11 -#include "WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h" -#endif /* ENABLE_X11 */ +#if DEMOMODE +#include "recording.h" +#endif /* DEMOMODE */ #include #define STB_IMAGE_WRITE_IMPLEMENTATION @@ -30,58 +27,28 @@ float g_TimeLast; float g_Daytime; namespace WallpaperEngine::Application { -CWallpaperApplication::CWallpaperApplication (CApplicationContext& context, - WallpaperEngine::WebBrowser::CWebBrowserContext& browserContext) : - m_context (context), - m_browserContext (browserContext) { +CWallpaperApplication::CWallpaperApplication (CApplicationContext& context) : + m_context (context) { this->loadBackgrounds (); this->setupProperties (); + this->setupBrowser(); } -CWallpaperApplication::~CWallpaperApplication () { - delete m_renderContext; - delete m_videoDriver; - delete m_audioContext; - delete m_audioDriver; - delete m_inputContext; -} - -void CWallpaperApplication::setupContainer (CCombinedContainer& container, const std::string& bg) const { +void CWallpaperApplication::setupContainer (const std::shared_ptr& container, const std::string& bg) const { const std::filesystem::path basepath = bg; - container.add (new CDirectory (basepath)); - container.addPkg (basepath / "scene.pkg"); - container.addPkg (basepath / "gifscene.pkg"); + container->add (std::make_shared (basepath)); + container->addPkg (basepath / "scene.pkg"); + container->addPkg (basepath / "gifscene.pkg"); try { - container.add (new CDirectory (this->m_context.settings.general.assets)); + container->add (std::make_shared (this->m_context.settings.general.assets)); } catch (CAssetLoadException&) { sLog.exception ("Cannot find a valid assets folder, resolved to ", this->m_context.settings.general.assets); } - // add two possible patches directories to the container - // hopefully one sticks - bool relative = true; - bool absolute = true; - - try { - container.add (new CDirectory ("../share/")); - } catch (CAssetLoadException&) { - relative = false; - } - - try { - container.add (new CDirectory (DATADIR)); - } catch (CAssetLoadException&) { - absolute = false; - } - - if (!relative && !absolute) - sLog.error ("WARNING: Shader patches directory cannot be found, this might make some backgrounds not work " - "properly"); - // TODO: move this somewhere else? - auto* virtualContainer = new CVirtualContainer (); + auto virtualContainer = std::make_shared (); // // Had to get a little creative with the effects to achieve the same bloom effect without any custom code @@ -92,84 +59,129 @@ void CWallpaperApplication::setupContainer (CCombinedContainer& container, const // add the effect file for screen bloom // add some model for the image element even if it's going to waste rendering cycles - virtualContainer->add ("effects/wpenginelinux/bloomeffect.json", - "{" - "\t\"name\":\"camerabloom_wpengine_linux\"," - "\t\"group\":\"wpengine_linux_camera\"," - "\t\"dependencies\":[]," - "\t\"passes\":" - "\t[" - "\t\t{" - "\t\t\t\"material\": \"materials/util/downsample_quarter_bloom.json\"," - "\t\t\t\"target\": \"_rt_4FrameBuffer\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_FullFrameBuffer\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}," - "\t\t{" - "\t\t\t\"material\": \"materials/util/downsample_eighth_blur_v.json\"," - "\t\t\t\"target\": \"_rt_8FrameBuffer\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_4FrameBuffer\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}," - "\t\t{" - "\t\t\t\"material\": \"materials/util/blur_h_bloom.json\"," - "\t\t\t\"target\": \"_rt_Bloom\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_8FrameBuffer\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}," - "\t\t{" - "\t\t\t\"material\": \"materials/util/combine.json\"," - "\t\t\t\"target\": \"_rt_FullFrameBuffer\"," - "\t\t\t\"bind\":" - "\t\t\t[" - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_imageLayerComposite_-1_a\"," - "\t\t\t\t\t\"index\": 0" - "\t\t\t\t}," - "\t\t\t\t{" - "\t\t\t\t\t\"name\": \"_rt_Bloom\"," - "\t\t\t\t\t\"index\": 1" - "\t\t\t\t}" - "\t\t\t]" - "\t\t}" - "\t]" - "}"); + virtualContainer->add ( + "effects/wpenginelinux/bloomeffect.json", + { + {"name", "camerabloom_wpengine_linux"}, + {"group", "wpengine_linux_camera"}, + {"dependencies", json::array ()}, + {"passes", + json::array ( + { + { + {"material", "materials/util/downsample_quarter_bloom.json"}, + {"target", "_rt_4FrameBuffer"}, + { + "bind", + json::array ( + { + { + {"name", "_rt_FullFrameBuffer"}, + {"index", 0} + } + } + ) + } + }, + { + {"material", "materials/util/downsample_eighth_blur_v.json"}, + {"target", "_rt_8FrameBuffer"}, + { + "bind", + json::array ( + { + { + {"name", "_rt_4FrameBuffer"}, + {"index", 0} + } + } + ) + } + }, + { + {"material", "materials/util/blur_h_bloom.json"}, + {"target", "_rt_Bloom"}, + { + "bind", + json::array ( + { + { + {"name", "_rt_8FrameBuffer"}, + {"index", 0} + } + } + ) + } + }, + { + {"material", "materials/util/combine.json"}, + {"target", "_rt_FullFrameBuffer"}, + { + "bind", + json::array ( + { + { + {"name", "_rt_imageLayerComposite_-1_a"}, + {"index", 0} + }, + { + {"name", "_rt_Bloom"}, + {"index", 1} + } + } + ) + } + } + } + ), + } + } + ); - virtualContainer->add ("models/wpenginelinux.json", "{" - "\t\"material\":\"materials/wpenginelinux.json\"" - "}"); + virtualContainer->add ( + "models/wpenginelinux.json", + { + {"material","materials/wpenginelinux.json"} + } + ); - // models require materials, so add that too - virtualContainer->add ("materials/wpenginelinux.json", "{" - "\t\"passes\":" - "\t\t[" - "\t\t\t{" - "\t\t\t\t\"blending\": \"normal\"," - "\t\t\t\t\"cullmode\": \"nocull\"," - "\t\t\t\t\"depthtest\": \"disabled\"," - "\t\t\t\t\"depthwrite\": \"disabled\"," - "\t\t\t\t\"shader\": \"genericimage2\"," - "\t\t\t\t\"textures\": [\"_rt_FullFrameBuffer\"]" - "\t\t\t}" - "\t\t]" - "}"); + virtualContainer->add( + "materials/wpenginelinux.json", + { + {"passes", json::array ( + { + { + {"blending", "normal"}, + {"cullmode", "nocull"}, + {"depthtest", "disabled"}, + {"depthwrite", "disabled"}, + {"shader", "genericimage2"}, + {"textures", json::array ({"_rt_FullFrameBuffer"})} + } + } + )}} + ); - container.add (virtualContainer); + virtualContainer->add( + "shaders/commands/copy.frag", + "uniform sampler2D g_Texture0;\n" + "in vec2 v_TexCoord;\n" + "void main () {\n" + "out_FragColor = texture (g_Texture0, v_TexCoord);\n" + "}" + ); + virtualContainer->add( + "shaders/commands/copy.vert", + "in vec3 a_Position;\n" + "in vec2 a_TexCoord;\n" + "out vec2 v_TexCoord;\n" + "void main () {\n" + "gl_Position = vec4 (a_Position, 1.0);\n" + "v_TexCoord = a_TexCoord;\n" + "}" + ); + + container->add (virtualContainer); } void CWallpaperApplication::loadBackgrounds () { @@ -189,24 +201,24 @@ void CWallpaperApplication::loadBackgrounds () { } } -Core::CProject* CWallpaperApplication::loadBackground (const std::string& bg) { - auto* container = new CCombinedContainer (); +std::shared_ptr CWallpaperApplication::loadBackground (const std::string& bg) { + const auto container = std::make_shared (); - this->setupContainer (*container, bg); + this->setupContainer (container, bg); return Core::CProject::fromFile ("project.json", container); } -void CWallpaperApplication::setupPropertiesForProject (const Core::CProject* project) { +void CWallpaperApplication::setupPropertiesForProject (const std::shared_ptr& project) { // show properties if required - for (const auto cur : project->getProperties ()) { + for (const auto& [key, cur] : project->getProperties ()) { // update the value of the property - auto override = this->m_context.settings.general.properties.find (cur->getName ()); + auto override = this->m_context.settings.general.properties.find (key); if (override != this->m_context.settings.general.properties.end ()) { - sLog.out ("Applying override value for ", cur->getName ()); + sLog.out ("Applying override value for ", key); - cur->update (override->second); + cur->set (override->second); } if (this->m_context.settings.general.onlyListProperties) @@ -215,35 +227,68 @@ void CWallpaperApplication::setupPropertiesForProject (const Core::CProject* pro } void CWallpaperApplication::setupProperties () { - for (const auto& [backgrounc, info] : this->m_backgrounds) + for (const auto& [background, info] : this->m_backgrounds) this->setupPropertiesForProject (info); } -void CWallpaperApplication::takeScreenshot (const std::filesystem::path& filename) { +void CWallpaperApplication::setupBrowser () { + bool anyWebProject = std::any_of ( + this->m_backgrounds.begin (), this->m_backgrounds.end (), + [](const std::pair>& pair) -> bool { + return pair.second->getWallpaper()->is (); + }); + + // do not perform any initialization if no web background is present + if (!anyWebProject) { + return; + } + + this->m_browserContext = std::make_unique (*this); +} + +void CWallpaperApplication::takeScreenshot (const std::filesystem::path& filename) const { // this should be getting called at the end of the frame, so the right thing should be bound already const int width = this->m_renderContext->getOutput ().getFullWidth (); const int height = this->m_renderContext->getOutput ().getFullHeight (); + const bool vflip = this->m_renderContext->getOutput ().renderVFlip (); // build the output file with stbi_image_write - auto* bitmap = new uint8_t [width * height * sizeof (uint8_t) * 3] {0}; + auto* bitmap = new uint8_t [width * height * 3] {0}; int xoffset = 0; for (const auto& [screen, viewport] : this->m_renderContext->getOutput ().getViewports ()) { // activate opengl context so we can read from the framebuffer viewport->makeCurrent (); // make room for storing the pixel of this viewport - auto* buffer = new uint8_t [viewport->viewport.z * viewport->viewport.w * sizeof (uint8_t) * 3]; + const auto bufferSize = (viewport->viewport.z - viewport->viewport.x) * (viewport->viewport.w - viewport->viewport.y) * 3; + auto* buffer = new uint8_t [bufferSize]; const uint8_t* pixel = buffer; // read the viewport data into the pixel buffer - glReadPixels (viewport->viewport.x, viewport->viewport.y, viewport->viewport.z, viewport->viewport.w, GL_RGB, - GL_UNSIGNED_BYTE, buffer); + glPixelStorei (GL_PACK_ALIGNMENT, 1); + // 4.5 supports glReadnPixels, anything older doesn't... + if (GLEW_VERSION_4_5) { + glReadnPixels (viewport->viewport.x, viewport->viewport.y, viewport->viewport.z, viewport->viewport.w, + GL_RGB, GL_UNSIGNED_BYTE, bufferSize, buffer); + } else { + // fallback to old version + glReadPixels (viewport->viewport.x, viewport->viewport.y, viewport->viewport.z, viewport->viewport.w, + GL_RGB, GL_UNSIGNED_BYTE, buffer); + } + + GLenum error = glGetError(); + + if (error != GL_NO_ERROR) { + sLog.error ("Cannot obtain pixel data for screen ", screen, ". OpenGL error: ", error); + delete [] buffer; + continue; + } // now get access to the pixels - for (int y = viewport->viewport.w; y > 0; y--) { + for (int y = 0; y < viewport->viewport.w; y++) { for (int x = 0; x < viewport->viewport.z; x++) { int xfinal = x + xoffset; - int yfinal = this->m_renderContext->getOutput ().renderVFlip () ? (viewport->viewport.w - y) : y; + int yfinal = vflip ? (viewport->viewport.w - y - 1) : y; bitmap [yfinal * width * 3 + xfinal * 3] = *pixel++; bitmap [yfinal * width * 3 + xfinal * 3 + 1] = *pixel++; @@ -267,9 +312,11 @@ void CWallpaperApplication::takeScreenshot (const std::filesystem::path& filenam } else if (extension == ".jpg" || extension == ".jpeg") { stbi_write_jpg (filename.c_str (), width, height, 3, bitmap, 100); } + + delete [] bitmap; } -void CWallpaperApplication::show () { +void CWallpaperApplication::setupOutput () { const char* XDG_SESSION_TYPE = getenv ("XDG_SESSION_TYPE"); if (!XDG_SESSION_TYPE) { @@ -279,122 +326,94 @@ void CWallpaperApplication::show () { sLog.debug ("Checking for window servers: "); -#ifdef ENABLE_WAYLAND - sLog.debug ("\twayland"); -#endif // ENABLE_WAYLAND - -#ifdef ENABLE_X11 - sLog.debug ("\tx11"); -#endif // ENABLE_X11 - -#ifdef ENABLE_WAYLAND - bool isWayland = strncmp ("wayland", XDG_SESSION_TYPE, strlen ("wayland")) == 0; -#endif // ENABLE_WAYLAND -#ifdef ENABLE_X11 - bool isX11 = strncmp ("x11", XDG_SESSION_TYPE, strlen ("x11")) == 0; -#endif // ENABLE_X11 - - if (this->m_context.settings.render.mode == CApplicationContext::DESKTOP_BACKGROUND) { -#ifdef ENABLE_WAYLAND - if (isWayland) { - m_videoDriver = new WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver (this->m_context, *this); - m_inputContext = - new WallpaperEngine::Input::CInputContext (new WallpaperEngine::Input::Drivers::CWaylandMouseInput ( - reinterpret_cast (m_videoDriver))); - this->m_fullScreenDetector = - new WallpaperEngine::Render::Drivers::Detectors::CWaylandFullScreenDetector (this->m_context); - } -#endif // ENABLE_WAYLAND -#ifdef ENABLE_X11 -#ifdef ENABLE_WAYLAND - else -#endif // ENABLE_WAYLAND - if (isX11) { - m_videoDriver = - new WallpaperEngine::Render::Drivers::CGLFWOpenGLDriver ("wallpaperengine", this->m_context, *this); - m_inputContext = - new WallpaperEngine::Input::CInputContext (new WallpaperEngine::Input::Drivers::CGLFWMouseInput ( - reinterpret_cast (m_videoDriver))); - this->m_fullScreenDetector = new WallpaperEngine::Render::Drivers::Detectors::CX11FullScreenDetector ( - this->m_context, *reinterpret_cast (m_videoDriver)); - } -#endif // ENABLE_X11 -#ifdef ENABLE_X11 - else -#endif // ENABLE_X11 - { - sLog.exception ( - "Cannot run in background mode, window server could not be detected. XDG_SESSION_TYPE must be wayland or x11"); - } - } else { - m_videoDriver = - new WallpaperEngine::Render::Drivers::CGLFWOpenGLDriver ("wallpaperengine", this->m_context, *this); - -#ifdef ENABLE_WAYLAND - if (isWayland) { - this->m_fullScreenDetector = - new WallpaperEngine::Render::Drivers::Detectors::CWaylandFullScreenDetector (this->m_context); - } -#endif // ENABLE_WAYLAND -#ifdef ENABLE_X11 -#ifdef ENABLE_WAYLAND - else -#endif // ENABLE_WAYLAND - if (isX11) { - this->m_fullScreenDetector = new WallpaperEngine::Render::Drivers::Detectors::CX11FullScreenDetector ( - this->m_context, *reinterpret_cast (m_videoDriver)); - } -#endif // ENABLE_X11 - else { - this->m_fullScreenDetector = - new WallpaperEngine::Render::Drivers::Detectors::CFullScreenDetector (this->m_context); - } - - m_inputContext = - new WallpaperEngine::Input::CInputContext (new WallpaperEngine::Input::Drivers::CGLFWMouseInput ( - reinterpret_cast (m_videoDriver))); + for (const auto& windowServer : sVideoFactories.getRegisteredDrivers ()) { + sLog.debug("\t", windowServer); } - if (this->m_context.settings.audio.audioprocessing) { - this->m_audioRecorder = new WallpaperEngine::Audio::Drivers::Recorders::CPulseAudioPlaybackRecorder (); + this->m_videoDriver = sVideoFactories.createVideoDriver ( + this->m_context.settings.render.mode, XDG_SESSION_TYPE, this->m_context, *this); + this->m_fullScreenDetector = sVideoFactories.createFullscreenDetector (XDG_SESSION_TYPE, this->m_context, *this->m_videoDriver); +} + +void CWallpaperApplication::setupAudio () { + // ensure audioprocessing is required by any background, and we have it enabled + bool audioProcessingRequired = std::any_of (this->m_backgrounds.begin (), this->m_backgrounds.end (), [](const auto& pair) -> bool { + return pair.second->supportsAudioProcessing (); + }); + + if (audioProcessingRequired && this->m_context.settings.audio.audioprocessing) { + this->m_audioRecorder = std::make_unique (); } else { - this->m_audioRecorder = new WallpaperEngine::Audio::Drivers::Recorders::CPlaybackRecorder (); + this->m_audioRecorder = std::make_unique (); + } + + if (this->m_context.settings.audio.automute) { + m_audioDetector = std::make_unique (this->m_context, *this->m_fullScreenDetector); + } else { + m_audioDetector = std::make_unique (this->m_context, *this->m_fullScreenDetector); } - // audio playing detector - WallpaperEngine::Audio::Drivers::Detectors::CPulseAudioPlayingDetector audioDetector (this->m_context, - *this->m_fullScreenDetector); // initialize sdl audio driver - m_audioDriver = - new WallpaperEngine::Audio::Drivers::CSDLAudioDriver (this->m_context, audioDetector, *this->m_audioRecorder); + m_audioDriver = std::make_unique (this->m_context, *this->m_audioDetector, *this->m_audioRecorder); // initialize audio context - m_audioContext = new WallpaperEngine::Audio::CAudioContext (*m_audioDriver); - // initialize render context - m_renderContext = new WallpaperEngine::Render::CRenderContext (*m_videoDriver, *m_inputContext, *this); + m_audioContext = std::make_unique (*m_audioDriver); +} +void CWallpaperApplication::prepareOutputs () { + // initialize render context + m_renderContext = std::make_unique (*m_videoDriver, *this); // create a new background for each screen // set all the specific wallpapers required for (const auto& [background, info] : this->m_backgrounds) { - m_renderContext->setWallpaper (background, - WallpaperEngine::Render::CWallpaper::fromWallpaper ( - info->getWallpaper (), *m_renderContext, *m_audioContext, m_browserContext, - this->m_context.settings.general.screenScalings [background])); + m_renderContext->setWallpaper ( + background, + WallpaperEngine::Render::CWallpaper::fromWallpaper ( + info->getWallpaper (), *m_renderContext, *m_audioContext, m_browserContext.get (), + this->m_context.settings.general.screenScalings [background], + this->m_context.settings.general.screenClamps [background] + ) + ); } +} - // wallpapers are setup, free browsesr context if possible - if (!this->m_browserContext.isUsed ()) { - this->m_browserContext.stop (); - } +void CWallpaperApplication::show () { + this->setupOutput (); + this->setupAudio (); + this->prepareOutputs (); static time_t seconds; static struct tm* timeinfo; - while (this->m_context.state.general.keepRunning && !m_videoDriver->closeRequested ()) { + if (this->m_context.settings.general.dumpStructure) { + auto prettyPrinter = PrettyPrinter::CPrettyPrinter (); + + for (const auto& [background, info] : this->m_renderContext->getWallpapers ()) { + prettyPrinter.printWallpaper (*info); + } + + std::cout << prettyPrinter.str () << std::endl; + } + +#if DEMOMODE + // ensure only one background is running so everything can be properly caught + if (this->m_renderContext->getWallpapers ().size () > 1) { + sLog.exception ("Demo mode only supports one background"); + } + + int width = this->m_renderContext->getWallpapers ().begin ()->second->getWidth (); + int height = this->m_renderContext->getWallpapers ().begin ()->second->getHeight (); + std::vector pixels(width * height * 3); + bool initialized = false; + int frame = 0; + int elapsed_frames = 0; +#endif /* DEMOMODE */ + + while (this->m_context.state.general.keepRunning) { // update g_Daytime time (&seconds); timeinfo = localtime (&seconds); - g_Daytime = ((timeinfo->tm_hour * 60) + timeinfo->tm_min) / (24.0 * 60.0); + g_Daytime = ((timeinfo->tm_hour * 60.0f) + timeinfo->tm_min) / (24.0f * 60.0f); // keep track of the previous frame's time g_TimeLast = g_Time; @@ -403,7 +422,43 @@ void CWallpaperApplication::show () { // update audio recorder m_audioDriver->update (); // update input information - m_inputContext->update (); + m_videoDriver->getInputContext ().update (); + // process driver events + m_videoDriver->dispatchEventQueue (); + + if (m_videoDriver->closeRequested()) { + sLog.out ("Stop requested by driver"); + this->m_context.state.general.keepRunning = false; + } + +#if DEMOMODE + elapsed_frames ++; + + // wait for a full render cycle before actually starting + // this gives some extra time for video and web decoders to set themselves up + // because of size changes + if (elapsed_frames > this->m_context.settings.render.maximumFPS) { + if (!initialized) { + width = this->m_renderContext->getWallpapers ().begin ()->second->getWidth (); + height = this->m_renderContext->getWallpapers ().begin ()->second->getHeight (); + pixels.reserve(width * height * 3); + init_encoder ("output.webm", width, height); + initialized = true; + } + + glBindFramebuffer (GL_FRAMEBUFFER, this->m_renderContext->getWallpapers ().begin ()->second->getWallpaperFramebuffer()); + + glPixelStorei (GL_PACK_ALIGNMENT, 1); + glReadPixels (0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels.data ()); + write_video_frame (pixels.data ()); + frame ++; + + // stop after the given framecount + if (frame >= FRAME_COUNT) { + this->m_context.state.general.keepRunning = false; + } + } +#endif /* DEMOMODE */ // check for fullscreen windows and wait until there's none fullscreen if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) { m_renderContext->setPause (true); @@ -411,20 +466,19 @@ void CWallpaperApplication::show () { usleep (FULLSCREEN_CHECK_WAIT_TIME); m_renderContext->setPause (false); } - // process driver events - m_videoDriver->dispatchEventQueue (); - if (!this->m_context.settings.screenshot.take || m_videoDriver->getFrameCounter () < 5) + if (!this->m_context.settings.screenshot.take || m_videoDriver->getFrameCounter () < this->m_context.settings.screenshot.delay) continue; this->takeScreenshot (this->m_context.settings.screenshot.path); this->m_context.settings.screenshot.take = false; } - // ensure this is updated as sometimes it might not come from a signal - this->m_context.state.general.keepRunning = false; + sLog.out ("Stopping"); - sLog.out ("Stop requested"); +#if DEMOMODE + close_encoder (); +#endif /* DEMOMODE */ SDL_Quit (); } @@ -435,10 +489,11 @@ void CWallpaperApplication::update (Render::Drivers::Output::COutputViewport* vi } void CWallpaperApplication::signal (int signal) { + sLog.out ("Stop requested by signal ", signal); this->m_context.state.general.keepRunning = false; } -const std::map& CWallpaperApplication::getBackgrounds () const { +const std::map>& CWallpaperApplication::getBackgrounds () const { return this->m_backgrounds; } diff --git a/src/WallpaperEngine/Application/CWallpaperApplication.h b/src/WallpaperEngine/Application/CWallpaperApplication.h index e8e62ab..2aa8465 100644 --- a/src/WallpaperEngine/Application/CWallpaperApplication.h +++ b/src/WallpaperEngine/Application/CWallpaperApplication.h @@ -10,24 +10,7 @@ #include "WallpaperEngine/Render/CWallpaper.h" #include "WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.h" #include "WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h" -#ifdef ENABLE_WAYLAND -#include "WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" -#endif - -#ifdef ENABLE_X11 -#include "WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h" -#endif -#ifdef ENABLE_WAYLAND -#include "WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h" -#endif - #include "WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h" -#ifdef ENABLE_X11 -#include "WallpaperEngine/Render/Drivers/Output/CX11Output.h" -#endif -#ifdef ENABLE_WAYLAND -#include "WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h" -#endif #include "WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h" @@ -42,8 +25,7 @@ namespace WallpaperEngine::Application { */ class CWallpaperApplication { public: - explicit CWallpaperApplication (CApplicationContext& context, WallpaperEngine::WebBrowser::CWebBrowserContext& browserContext); - ~CWallpaperApplication (); + explicit CWallpaperApplication (CApplicationContext& context); /** * Shows the application until it's closed @@ -58,7 +40,7 @@ class CWallpaperApplication { /** * @return Maps screens to loaded backgrounds */ - [[nodiscard]] const std::map& getBackgrounds () const; + [[nodiscard]] const std::map>& getBackgrounds () const; /** * @return The current application context */ @@ -79,7 +61,7 @@ class CWallpaperApplication { * @param container * @param bg */ - void setupContainer (CCombinedContainer& container, const std::string& bg) const; + void setupContainer (const std::shared_ptr& container, const std::string& bg) const; /** * Loads projects based off the settings */ @@ -90,7 +72,7 @@ class CWallpaperApplication { * @param bg * @return */ - Core::CProject* loadBackground (const std::string& bg); + [[nodiscard]] std::shared_ptr loadBackground (const std::string& bg); /** * Prepares all background's values and updates their properties if required */ @@ -100,26 +82,42 @@ class CWallpaperApplication { * * @param project */ - void setupPropertiesForProject (const Core::CProject* project); + void setupPropertiesForProject (const std::shared_ptr& project); + /** + * Prepares CEF browser to be used + */ + void setupBrowser (); + /** + * Prepares desktop environment-related things (like render, window, fullscreen detector, etc) + */ + void setupOutput (); + /** + * Prepares all audio-related things (like detector, output, etc) + */ + void setupAudio (); + /** + * Prepares the render-context of all the backgrounds so they can be displayed on the screen + */ + void prepareOutputs (); /** * Takes an screenshot of the background and saves it to the specified path * * @param filename */ - void takeScreenshot (const std::filesystem::path& filename); + void takeScreenshot (const std::filesystem::path& filename) const; /** The application context that contains the current app settings */ CApplicationContext& m_context; /** Maps screens to backgrounds */ - std::map m_backgrounds; + std::map> m_backgrounds {}; - WallpaperEngine::Audio::CAudioContext* m_audioContext; - WallpaperEngine::Audio::Drivers::CSDLAudioDriver* m_audioDriver; - WallpaperEngine::Audio::Drivers::Recorders::CPlaybackRecorder* m_audioRecorder; - WallpaperEngine::Input::CInputContext* m_inputContext; - WallpaperEngine::Render::CRenderContext* m_renderContext; - WallpaperEngine::Render::Drivers::CVideoDriver* m_videoDriver; - WallpaperEngine::Render::Drivers::Detectors::CFullScreenDetector* m_fullScreenDetector; - WallpaperEngine::WebBrowser::CWebBrowserContext& m_browserContext; + std::unique_ptr m_audioDetector = nullptr; + std::unique_ptr m_audioContext = nullptr; + std::unique_ptr m_audioDriver = nullptr; + std::unique_ptr m_audioRecorder = nullptr; + std::unique_ptr m_renderContext = nullptr; + std::unique_ptr m_videoDriver = nullptr; + std::unique_ptr m_fullScreenDetector = nullptr; + std::unique_ptr m_browserContext = nullptr; }; } // namespace WallpaperEngine::Application diff --git a/src/WallpaperEngine/Assets/CAssetLoadException.h b/src/WallpaperEngine/Assets/CAssetLoadException.h index 7c61856..829ceed 100644 --- a/src/WallpaperEngine/Assets/CAssetLoadException.h +++ b/src/WallpaperEngine/Assets/CAssetLoadException.h @@ -10,6 +10,6 @@ class CAssetLoadException final : public std::exception { [[nodiscard]] const char* what () const noexcept override; private: - std::string m_message; + std::string m_message {}; }; } // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CCombinedContainer.cpp b/src/WallpaperEngine/Assets/CCombinedContainer.cpp index 533a71a..b4fb32d 100644 --- a/src/WallpaperEngine/Assets/CCombinedContainer.cpp +++ b/src/WallpaperEngine/Assets/CCombinedContainer.cpp @@ -8,14 +8,14 @@ using namespace WallpaperEngine::Assets; CCombinedContainer::CCombinedContainer () : CContainer () {} -void CCombinedContainer::add (CContainer* container) { +void CCombinedContainer::add (const std::shared_ptr& container) { this->m_containers.emplace_back (container); } void CCombinedContainer::addPkg (const std::filesystem::path& path) { try { // add the package to the list - this->add (new CPackage (path)); + this->add (std::make_shared (path)); sLog.out ("Detected ", path.filename (), " file at ", path, ". Adding to list of searchable paths"); } catch (CPackageLoadException&) { // ignore this error, the package file was not found @@ -26,8 +26,8 @@ void CCombinedContainer::addPkg (const std::filesystem::path& path) { } } -std::filesystem::path CCombinedContainer::resolveRealFile (const std::string& filename) const { - for (const auto cur : this->m_containers) { +std::filesystem::path CCombinedContainer::resolveRealFile (const std::filesystem::path& filename) const { + for (const auto& cur : this->m_containers) { try { // try to read the file on the current container, if the file doesn't exists // an exception will be thrown @@ -41,13 +41,13 @@ std::filesystem::path CCombinedContainer::resolveRealFile (const std::string& fi throw CAssetLoadException (filename, "Cannot resolve file in any of the containers"); } -const uint8_t* CCombinedContainer::readFile (const std::string& filename, uint32_t* length) const { - for (const auto cur : this->m_containers) { +std::shared_ptr CCombinedContainer::readFile (const std::filesystem::path& filename, uint32_t* length) const { + for (const auto& cur : this->m_containers) { try { // try to read the file on the current container, if the file doesn't exists // an exception will be thrown return cur->readFile (filename, length); - } catch (CAssetLoadException&) { + } catch (CAssetLoadException& e) { // not found in this container, next try } } diff --git a/src/WallpaperEngine/Assets/CCombinedContainer.h b/src/WallpaperEngine/Assets/CCombinedContainer.h index 2ccceb5..147962e 100644 --- a/src/WallpaperEngine/Assets/CCombinedContainer.h +++ b/src/WallpaperEngine/Assets/CCombinedContainer.h @@ -19,7 +19,7 @@ class CCombinedContainer final : public CContainer { * * @param container */ - void add (CContainer* container); + void add (const std::shared_ptr& container); /** * Adds the given package to the list * @@ -27,13 +27,11 @@ class CCombinedContainer final : public CContainer { */ void addPkg (const std::filesystem::path& path); - /** @inheritdoc */ - [[nodiscard]] std::filesystem::path resolveRealFile (const std::string& filename) const override; - /** @inheritdoc */ - [[nodiscard]] const uint8_t* readFile (const std::string& filename, uint32_t* length) const override; + [[nodiscard]] std::filesystem::path resolveRealFile (const std::filesystem::path& filename) const override; + [[nodiscard]] std::shared_ptr readFile (const std::filesystem::path& filename, uint32_t* length) const override; private: /** The list of containers to search files off from */ - std::vector m_containers; + std::vector> m_containers {}; }; }; // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CContainer.cpp b/src/WallpaperEngine/Assets/CContainer.cpp index 1223f3d..c30c3c4 100644 --- a/src/WallpaperEngine/Assets/CContainer.cpp +++ b/src/WallpaperEngine/Assets/CContainer.cpp @@ -9,26 +9,25 @@ using namespace WallpaperEngine::Assets; -std::filesystem::path CContainer::resolveRealFile (const std::string& filename) const { +std::filesystem::path CContainer::resolveRealFile (const std::filesystem::path& filename) const { throw CAssetLoadException (filename, "Cannot resolve physical file in this container"); } -const ITexture* CContainer::readTexture (const std::string& filename) const { +std::shared_ptr CContainer::readTexture (const std::filesystem::path& filename) const { // get the texture's filename (usually .tex) - const std::string texture = "materials/" + filename + ".tex"; + std::filesystem::path texture = "materials" / std::filesystem::path (filename.string ().append (".tex")); - const void* textureContents = this->readFile (texture, nullptr); - - const ITexture* result = new CTexture (textureContents); + const auto textureContents = this->readFile (texture, nullptr); + const auto result = std::make_shared (textureContents); #if !NDEBUG - glObjectLabel (GL_TEXTURE, result->getTextureID (), -1, texture.c_str ()); + glObjectLabel (GL_TEXTURE, result->getTextureID (0), -1, texture.c_str ()); #endif /* NDEBUG */ return result; } -std::string CContainer::readShader (const std::string& filename) const { +std::string CContainer::readShader (const std::filesystem::path& filename) const { std::filesystem::path shader = filename; auto it = shader.begin (); @@ -37,7 +36,7 @@ std::string CContainer::readShader (const std::string& filename) const { const std::filesystem::path workshopId = *it++; if (++it != shader.end ()) { - const std::filesystem::path shaderfile = *it; + const std::filesystem::path& shaderfile = *it; try { shader = std::filesystem::path ("zcompat") / "scene" / "shaders" / workshopId / shaderfile; @@ -51,37 +50,29 @@ std::string CContainer::readShader (const std::string& filename) const { } } - return this->readFileAsString ("shaders/" + filename); + return this->readFileAsString ("shaders" / filename); } -std::string CContainer::readVertexShader (const std::string& filename) const { - return this->readShader (filename + ".vert"); +std::string CContainer::readVertexShader (const std::filesystem::path& filename) const { + std::filesystem::path shader = filename; + shader.replace_extension (".vert"); + return this->readShader (shader); } -std::string CContainer::readFragmentShader (const std::string& filename) const { - return this->readShader (filename + ".frag"); +std::string CContainer::readFragmentShader (const std::filesystem::path& filename) const { + std::filesystem::path shader = filename; + shader.replace_extension (".frag"); + return this->readShader (shader); } -std::string CContainer::readIncludeShader (const std::string& filename) const { - return this->readFileAsString ("shaders/" + filename); +std::string CContainer::readIncludeShader (const std::filesystem::path& filename) const { + return this->readFileAsString ("shaders" / filename); } -std::string CContainer::readFileAsString (const std::string& filename) const { +std::string CContainer::readFileAsString (const std::filesystem::path& filename) const { uint32_t length = 0; - // read file contents and allocate a buffer for a string - const uint8_t* contents = this->readFile (filename, &length); - char* buffer = new char [length + 1]; - - // ensure there's a 0 at the end - memset (buffer, 0, length + 1); - // copy over the data - memcpy (buffer, contents, length); - // now build the std::string to use - std::string result = buffer; - - // free the intermediate buffer used to generate the std::string - delete [] buffer; - - return result; + return { + reinterpret_cast (this->readFile (filename, &length).get ()), length + }; } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CContainer.h b/src/WallpaperEngine/Assets/CContainer.h index 4827512..e77228c 100644 --- a/src/WallpaperEngine/Assets/CContainer.h +++ b/src/WallpaperEngine/Assets/CContainer.h @@ -19,18 +19,20 @@ class CContainer { * @param filename * @return */ - [[nodiscard]] virtual std::filesystem::path resolveRealFile (const std::string& filename) const; + [[nodiscard]] virtual std::filesystem::path resolveRealFile (const std::filesystem::path& filename) const; /** * Reads the given file from the container and returns it's data * Additionally sets a length parameter to return back the file's length * + * The returned string must be deleted[] by the caller + * * @param filename The file to read * @param length The file's length after it's been read, null for not getting anything back * * @return */ - [[nodiscard]] virtual const uint8_t* readFile (const std::string& filename, uint32_t* length) const = 0; + [[nodiscard]] virtual std::shared_ptr readFile (const std::filesystem::path& filename, uint32_t* length) const = 0; /** * Wrapper for readFile, appends the texture extension at the end of the filename @@ -39,7 +41,7 @@ class CContainer { * * @return */ - [[nodiscard]] const ITexture* readTexture (const std::string& filename) const; + [[nodiscard]] std::shared_ptr readTexture (const std::filesystem::path& filename) const; /** * Wrapper for readFile, checks for compat versions of the given shader file @@ -48,7 +50,7 @@ class CContainer { * * @return The shader code as an string to be used */ - [[nodiscard]] std::string readShader (const std::string& filename) const; + [[nodiscard]] std::string readShader (const std::filesystem::path& filename) const; /** * Wrapper for readFile, appends the .vert extension at the end and opens the given shader file @@ -57,7 +59,7 @@ class CContainer { * * @return The shader code as an string to be used */ - [[nodiscard]] std::string readVertexShader (const std::string& filename) const; + [[nodiscard]] std::string readVertexShader (const std::filesystem::path& filename) const; /** * Wrapper for readFile, appends the .frag extension at the end and opens the given shader file @@ -66,7 +68,7 @@ class CContainer { * * @return The shader code as an string to be used */ - [[nodiscard]] std::string readFragmentShader (const std::string& filename) const; + [[nodiscard]] std::string readFragmentShader (const std::filesystem::path& filename) const; /** * Wrapper for readFile, appends the .h extension at the end and opens the given shader file @@ -75,7 +77,7 @@ class CContainer { * * @return The shader code as an string to be used */ - [[nodiscard]] std::string readIncludeShader (const std::string& filename) const; + [[nodiscard]] std::string readIncludeShader (const std::filesystem::path& filename) const; /** * Reads a file as string @@ -84,6 +86,6 @@ class CContainer { * * @return The file's contents as string */ - [[nodiscard]] std::string readFileAsString (const std::string& filename) const; + [[nodiscard]] std::string readFileAsString (const std::filesystem::path& filename) const; }; } // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CDirectory.cpp b/src/WallpaperEngine/Assets/CDirectory.cpp index 004195f..2d32768 100644 --- a/src/WallpaperEngine/Assets/CDirectory.cpp +++ b/src/WallpaperEngine/Assets/CDirectory.cpp @@ -1,61 +1,85 @@ -#include "common.h" -#include - -#include - #include "CAssetLoadException.h" #include "CDirectory.h" using namespace WallpaperEngine::Assets; -CDirectory::CDirectory (std::filesystem::path basepath) : m_basepath (std::move (basepath)) { - // ensure the specified path exists - struct stat buffer {}; +CDirectory::CDirectory (const std::filesystem::path& basepath) { + try { + // resolve the path to it's real location + std::filesystem::path finalpath = std::filesystem::canonical(basepath); + std::filesystem::file_status status = std::filesystem::status (finalpath); - if (stat (this->m_basepath.c_str (), &buffer) != 0) - throw CAssetLoadException (this->m_basepath, "Cannot find directory"); + if (!std::filesystem::exists (finalpath)) { + throw CAssetLoadException (basepath, "Cannot find directory"); + } - if (!S_ISDIR (buffer.st_mode)) - throw CAssetLoadException (this->m_basepath, "Expected directory but found a file"); -} + if (!std::filesystem::is_directory(status)) { + throw CAssetLoadException (basepath, "Expected directory but found a file"); + } -std::filesystem::path CDirectory::resolveRealFile (const std::string& filename) const { - return std::filesystem::path (this->m_basepath) / filename; -} - -const uint8_t* CDirectory::readFile (const std::string& filename, uint32_t* length) const { - const std::filesystem::path final = std::filesystem::path (this->m_basepath) / filename; - - // first check the cache, if the file is there already just return the data in there - const auto it = this->m_cache.find (final); - - if (it != this->m_cache.end ()) { - if (length != nullptr) - *length = it->second.length; - - return it->second.address; + this->m_basepath = finalpath; + } catch (std::bad_alloc&) { + throw CAssetLoadException (basepath, "Cannot allocate memory"); + } catch (std::filesystem::filesystem_error& e) { + throw CAssetLoadException (basepath, e.what ()); } +} + +std::filesystem::path CDirectory::resolveRealFile (const std::filesystem::path& filename) const { + try { + std::filesystem::path final = std::filesystem::canonical (this->m_basepath / filename); + + // first validate the path, so the message doesn't reflect if the file exists or not unless it's under the actual directory + if (final.string ().find (this->m_basepath.string ()) != 0) { + throw CAssetLoadException (filename, "File is not a child of the given directory"); + } + + std::filesystem::file_status status = std::filesystem::status (final); + + if (!std::filesystem::exists (final)) { + throw CAssetLoadException (filename, "Cannot find file"); + } + + if (!std::filesystem::is_regular_file (status)) { + throw CAssetLoadException (filename, "Expected file but found a directory"); + } + + return final; + } catch (std::filesystem::filesystem_error& e) { + throw CAssetLoadException (filename, e.what ()); + } +} + +std::shared_ptr CDirectory::readFile (const std::filesystem::path& filename, uint32_t* length) const { + std::filesystem::path final = this->resolveRealFile (filename); FILE* fp = fopen (final.c_str (), "rb"); - if (fp == nullptr) - throw CAssetLoadException (filename, "Cannot find file"); - - // go to the end, get the position and return to the beginning - fseek (fp, 0, SEEK_END); - const long size = ftell (fp); - fseek (fp, 0, SEEK_SET); - - // now read the whole file - auto* contents = new uint8_t [size]; - - if (fread (contents, size, 1, fp) != 1) { - delete [] contents; - throw CAssetLoadException (filename, "Unexpected error when reading the file"); + if (fp == nullptr) { + throw CAssetLoadException (filename, "Cannot open file for reading"); } - if (length != nullptr) - *length = size; + try { + // go to the end, get the position and return to the beginning + fseek (fp, 0, SEEK_END); + const long size = ftell (fp); + fseek (fp, 0, SEEK_SET); - return contents; + // now read the whole file + std::shared_ptr contents = std::shared_ptr(new uint8_t [size]); + + if (fread (contents.get(), size, 1, fp) != 1) { + throw CAssetLoadException (filename, "Unexpected error when reading the file"); + } + + if (length != nullptr) { + *length = size; + } + + fclose (fp); + return contents; + } catch (std::filesystem::filesystem_error& e) { + fclose (fp); + throw CAssetLoadException (filename, e.what ()); + } } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CDirectory.h b/src/WallpaperEngine/Assets/CDirectory.h index a8fce1d..c9a35b3 100644 --- a/src/WallpaperEngine/Assets/CDirectory.h +++ b/src/WallpaperEngine/Assets/CDirectory.h @@ -14,17 +14,13 @@ namespace WallpaperEngine::Assets { */ class CDirectory final : public CContainer { public: - explicit CDirectory (std::filesystem::path basepath); + explicit CDirectory (const std::filesystem::path& basepath); - /** @inheritdoc */ - [[nodiscard]] std::filesystem::path resolveRealFile (const std::string& filename) const override; - /** @inheritdoc */ - [[nodiscard]] const uint8_t* readFile (const std::string& filename, uint32_t* length) const override; + [[nodiscard]] std::filesystem::path resolveRealFile (const std::filesystem::path& filename) const override; + [[nodiscard]] std::shared_ptr readFile (const std::filesystem::path& filename, uint32_t* length) const override; private: /** The basepath for the directory */ - std::filesystem::path m_basepath; - /** File cache to simplify access to data */ - std::map m_cache; + std::filesystem::path m_basepath {}; }; } // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CFileEntry.h b/src/WallpaperEngine/Assets/CFileEntry.h index 3db710f..0dcb79e 100644 --- a/src/WallpaperEngine/Assets/CFileEntry.h +++ b/src/WallpaperEngine/Assets/CFileEntry.h @@ -1,6 +1,7 @@ #pragma once #include +#include namespace WallpaperEngine::Assets { /** @@ -8,15 +9,14 @@ namespace WallpaperEngine::Assets { */ class CFileEntry { public: - CFileEntry (const uint8_t* address, uint32_t length) : address (address), length (length) {} - - ~CFileEntry () { - delete [] address; - } + CFileEntry (std::shared_ptr content, uint32_t length) : + content (std::move(content)), + length (length) {} + ~CFileEntry() = default; /** File contents */ - const uint8_t* address; + std::shared_ptr content = nullptr; /** File length */ - uint32_t length; + uint32_t length = 0; }; } // namespace WallpaperEngine::Assets diff --git a/src/WallpaperEngine/Assets/CPackage.cpp b/src/WallpaperEngine/Assets/CPackage.cpp index ce3c5a6..26ec945 100644 --- a/src/WallpaperEngine/Assets/CPackage.cpp +++ b/src/WallpaperEngine/Assets/CPackage.cpp @@ -1,7 +1,7 @@ #include "CPackage.h" #include "CAssetLoadException.h" #include "CPackageLoadException.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include #include @@ -11,7 +11,7 @@ using namespace WallpaperEngine::Assets; class CPackageEntry { public: CPackageEntry (std::string filename, uint32_t offset, uint32_t length) : - filename (std::move (filename)), + filename (filename), offset (offset), length (length) {} @@ -24,7 +24,7 @@ CPackage::CPackage (std::filesystem::path path) : m_path (std::move (path)) { this->init (); } -const uint8_t* CPackage::readFile (const std::string& filename, uint32_t* length) const { +std::shared_ptr CPackage::readFile (const std::filesystem::path& filename, uint32_t* length) const { const auto it = this->m_contents.find (filename); if (it == this->m_contents.end ()) @@ -34,12 +34,7 @@ const uint8_t* CPackage::readFile (const std::string& filename, uint32_t* length if (length != nullptr) *length = it->second->length; - // clone original first - auto* result = new uint8_t [it->second->length]; - - memcpy (result, it->second->address, it->second->length); - - return result; + return it->second->content; } void CPackage::init () { @@ -128,15 +123,13 @@ void CPackage::loadFiles (FILE* fp) { sLog.exception ("Cannot find file ", cur.filename, " from package ", this->m_path); // allocate memory for the file's contents and read it from the file - auto* fileContents = new uint8_t [cur.length]; - - if (fread (fileContents, cur.length, 1, fp) != 1) { - delete [] fileContents; + std::shared_ptr contents = std::shared_ptr(new uint8_t [cur.length]); + if (fread (contents.get(), cur.length, 1, fp) != 1) { sLog.exception ("Cannot read file ", cur.filename, " contents from package ", this->m_path); } // add the file to the map - this->m_contents.insert_or_assign (cur.filename, new CFileEntry (fileContents, cur.length)); + this->m_contents.insert_or_assign (cur.filename, std::make_unique (contents, cur.length)); } } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CPackage.h b/src/WallpaperEngine/Assets/CPackage.h index ea41bb0..5baafe2 100644 --- a/src/WallpaperEngine/Assets/CPackage.h +++ b/src/WallpaperEngine/Assets/CPackage.h @@ -20,7 +20,7 @@ class CPackage final : public CContainer { public: explicit CPackage (std::filesystem::path path); - [[nodiscard]] const uint8_t* readFile (const std::string& filename, uint32_t* length) const override; + [[nodiscard]] std::shared_ptr readFile (const std::filesystem::path& filename, uint32_t* length) const override; protected: /** @@ -61,8 +61,8 @@ class CPackage final : public CContainer { private: /** The path to the package file */ - std::filesystem::path m_path; + std::filesystem::path m_path {}; /** Contents of the package file */ - std::map m_contents; + std::map> m_contents {}; }; } // namespace WallpaperEngine::Assets diff --git a/src/WallpaperEngine/Assets/CPackageLoadException.h b/src/WallpaperEngine/Assets/CPackageLoadException.h index 0be83f3..ef9a8dd 100644 --- a/src/WallpaperEngine/Assets/CPackageLoadException.h +++ b/src/WallpaperEngine/Assets/CPackageLoadException.h @@ -10,6 +10,6 @@ class CPackageLoadException final : public std::exception { [[nodiscard]] const char* what () const noexcept override; private: - std::string m_message; + std::string m_message {}; }; } // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CTexture.cpp b/src/WallpaperEngine/Assets/CTexture.cpp index d65e2f5..d55b01a 100644 --- a/src/WallpaperEngine/Assets/CTexture.cpp +++ b/src/WallpaperEngine/Assets/CTexture.cpp @@ -1,5 +1,5 @@ #include "CTexture.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include #include @@ -10,51 +10,12 @@ using namespace WallpaperEngine::Assets; -CTexture::CTexture (const void* fileData) : m_resolution () { +CTexture::CTexture (const std::shared_ptr& buffer) : m_resolution () { // ensure the header is parsed + const void* fileData = buffer.get (); this->m_header = parseHeader (static_cast (fileData)); - - GLint internalFormat; - - if (this->isAnimated ()) { - this->m_resolution = {this->m_header->textureWidth, this->m_header->textureHeight, this->m_header->gifWidth, - this->m_header->gifHeight}; - } else { - if (this->m_header->freeImageFormat != FreeImageFormat::FIF_UNKNOWN) { - // wpengine-texture format always has one mipmap - // get first image size - auto element = this->m_header->images.find (0)->second.begin (); - - // set the texture resolution - this->m_resolution = {(*element)->width, (*element)->height, this->m_header->width, this->m_header->height}; - } else { - // set the texture resolution - this->m_resolution = {this->m_header->textureWidth, this->m_header->textureHeight, this->m_header->width, - this->m_header->height}; - } - } - - if (this->m_header->freeImageFormat != FreeImageFormat::FIF_UNKNOWN) { - internalFormat = GL_RGBA8; - // set some extra information too as it's used for image sizing - // this ensures that a_TexCoord uses the full image instead of just part of it - // TODO: MAYBE IT'S BETTER TO CREATE A TEXTURE OF THE GIVEN SIZE AND COPY OVER WHAT WE READ FROM THE FILE? - /*this->m_header->width = this->m_header->mipmaps [0]->width; - this->m_header->height = this->m_header->mipmaps [0]->height; - this->m_header->textureWidth = this->m_header->mipmaps [0]->width; - this->m_header->textureHeight = this->m_header->mipmaps [0]->height;*/ - } else { - // detect the image format and hand it to openGL to be used - switch (this->m_header->format) { - case TextureFormat::DXT5: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; - case TextureFormat::DXT3: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; - case TextureFormat::DXT1: internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; - case TextureFormat::ARGB8888: internalFormat = GL_RGBA8; break; - case TextureFormat::R8: internalFormat = GL_R8; break; - case TextureFormat::RG88: internalFormat = GL_RG8; break; - default: delete this->m_header; sLog.exception ("Cannot determine texture format"); - } - } + this->setupResolution (); + GLint internalFormat = this->setupInternalFormat(); // allocate texture ids list this->m_textureID = new GLuint [this->m_header->imageCount]; @@ -65,38 +26,14 @@ CTexture::CTexture (const void* fileData) : m_resolution () { auto imgEnd = this->m_header->images.end (); for (int index = 0; imgCur != imgEnd; ++imgCur, index++) { - // bind the texture to assign information to it - glBindTexture (GL_TEXTURE_2D, this->m_textureID [index]); - - // set mipmap levels - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, this->m_header->mipmapCount - 1); - - // setup texture wrapping and filtering - if (this->m_header->flags & TextureFlags::ClampUVs) { - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - } else { - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - } - - if (this->m_header->flags & TextureFlags::NoInterpolation) { - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); - } else { - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - } - - glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY, 8.0f); + this->setupOpenGLParameters (index); auto cur = imgCur->second.begin (); auto end = imgCur->second.end (); for (int32_t level = 0; cur != end; ++cur, level++) { stbi_uc* handle = nullptr; - void* dataptr = (*cur)->uncompressedData; + void* dataptr = (*cur)->uncompressedData.get (); int width = (*cur)->width; int height = (*cur)->height; uint32_t bufferSize = (*cur)->uncompressedSize; @@ -106,7 +43,7 @@ CTexture::CTexture (const void* fileData) : m_resolution () { int fileChannels; dataptr = handle = stbi_load_from_memory ( - reinterpret_cast ((*cur)->uncompressedData), + reinterpret_cast ((*cur)->uncompressedData.get ()), (*cur)->uncompressedSize, &width, &height, @@ -126,14 +63,16 @@ CTexture::CTexture (const void* fileData) : m_resolution () { case GL_RGBA8: case GL_RG8: case GL_R8: - glTexImage2D (GL_TEXTURE_2D, level, internalFormat, width, height, 0, textureFormat, - GL_UNSIGNED_BYTE, dataptr); + glTexImage2D ( + GL_TEXTURE_2D, level, internalFormat, width, height, 0, textureFormat, + GL_UNSIGNED_BYTE, dataptr); break; case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - glCompressedTexImage2D (GL_TEXTURE_2D, level, internalFormat, width, height, 0, bufferSize, - dataptr); + glCompressedTexImage2D ( + GL_TEXTURE_2D, level, internalFormat, width, height, 0, bufferSize, + dataptr); break; default: sLog.exception ("Cannot load texture, unknown format", this->m_header->format); } @@ -146,86 +85,142 @@ CTexture::CTexture (const void* fileData) : m_resolution () { } } -CTexture::~CTexture () { - if (this->getHeader () == nullptr) - return; +void CTexture::setupResolution () { + if (this->isAnimated ()) { + this->m_resolution = {this->m_header->textureWidth, this->m_header->textureHeight, this->m_header->gifWidth, + this->m_header->gifHeight}; + } else { + if (this->m_header->freeImageFormat != FreeImageFormat::FIF_UNKNOWN) { + // wpengine-texture format always has one mipmap + // get first image size + auto element = this->m_header->images.find (0)->second.begin (); - // free the header if it was allocated - delete this->getHeader (); + // set the texture resolution + this->m_resolution = {(*element)->width, (*element)->height, this->m_header->width, this->m_header->height}; + } else { + // set the texture resolution + this->m_resolution = {this->m_header->textureWidth, this->m_header->textureHeight, this->m_header->width, + this->m_header->height}; + } + } } -const GLuint CTexture::getTextureID (uint32_t imageIndex) const { +GLint CTexture::setupInternalFormat () { + if (this->m_header->freeImageFormat != FreeImageFormat::FIF_UNKNOWN) { + return GL_RGBA8; + // set some extra information too as it's used for image sizing + // this ensures that a_TexCoord uses the full image instead of just part of it + // TODO: MAYBE IT'S BETTER TO CREATE A TEXTURE OF THE GIVEN SIZE AND COPY OVER WHAT WE READ FROM THE FILE? + /*this->m_header->width = this->m_header->mipmaps [0]->width; + this->m_header->height = this->m_header->mipmaps [0]->height; + this->m_header->textureWidth = this->m_header->mipmaps [0]->width; + this->m_header->textureHeight = this->m_header->mipmaps [0]->height;*/ + } else { + // detect the image format and hand it to openGL to be used + switch (this->m_header->format) { + case TextureFormat::DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; + case TextureFormat::DXT3: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; + case TextureFormat::DXT1: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; + case TextureFormat::ARGB8888: return GL_RGBA8; break; + case TextureFormat::R8: return GL_R8; break; + case TextureFormat::RG88: return GL_RG8; break; + default: sLog.exception ("Cannot determine texture format"); + } + } +} + +void CTexture::setupOpenGLParameters (uint32_t textureID) { + // bind the texture to assign information to it + glBindTexture (GL_TEXTURE_2D, this->m_textureID [textureID]); + + // set mipmap levels + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, this->m_header->images [textureID].size () - 1); + + // setup texture wrapping and filtering + if (this->m_header->flags & TextureFlags::ClampUVs) { + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } else { + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + } + + if (this->m_header->flags & TextureFlags::NoInterpolation) { + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); + } else { + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + } + + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY, 8.0f); +} + +GLuint CTexture::getTextureID (uint32_t imageIndex) const { // ensure we do not go out of bounds - if (imageIndex > this->m_header->imageCount) + if (imageIndex >= this->m_header->imageCount) return this->m_textureID [0]; return this->m_textureID [imageIndex]; } -const uint32_t CTexture::getTextureWidth (uint32_t imageIndex) const { - if (imageIndex > this->m_header->imageCount) +uint32_t CTexture::getTextureWidth (uint32_t imageIndex) const { + if (imageIndex >= this->m_header->imageCount) return this->getHeader ()->textureWidth; return (*this->m_header->images [imageIndex].begin ())->width; } -const uint32_t CTexture::getTextureHeight (uint32_t imageIndex) const { - if (imageIndex > this->m_header->imageCount) +uint32_t CTexture::getTextureHeight (uint32_t imageIndex) const { + if (imageIndex >= this->m_header->imageCount) return this->getHeader ()->textureHeight; return (*this->m_header->images [imageIndex].begin ())->height; } -const uint32_t CTexture::getRealWidth () const { +uint32_t CTexture::getRealWidth () const { return this->isAnimated () ? this->getHeader ()->gifWidth : this->getHeader ()->width; } -const uint32_t CTexture::getRealHeight () const { +uint32_t CTexture::getRealHeight () const { return this->isAnimated () ? this->getHeader ()->gifHeight : this->getHeader ()->height; } -const ITexture::TextureFormat CTexture::getFormat () const { +ITexture::TextureFormat CTexture::getFormat () const { return this->getHeader ()->format; } -const ITexture::TextureFlags CTexture::getFlags () const { +ITexture::TextureFlags CTexture::getFlags () const { return this->getHeader ()->flags; } const CTexture::TextureHeader* CTexture::getHeader () const { - return this->m_header; + return this->m_header.get (); } const glm::vec4* CTexture::getResolution () const { return &this->m_resolution; } -const std::vector& CTexture::getFrames () const { +const std::vector>& CTexture::getFrames () const { return this->getHeader ()->frames; } -const bool CTexture::isAnimated () const { +bool CTexture::isAnimated () const { return this->getHeader ()->isAnimated (); } -CTexture::TextureMipmap::TextureMipmap () = default; - -CTexture::TextureMipmap::~TextureMipmap () { - if (this->compression == 1) - delete this->compressedData; - - delete this->uncompressedData; -} - void CTexture::TextureMipmap::decompressData () { if (this->compression != 1) { return; } - this->uncompressedData = new char [this->uncompressedSize]; + this->uncompressedData = std::unique_ptr (new char [this->uncompressedSize]); - const int result = LZ4_decompress_safe (this->compressedData, this->uncompressedData, this->compressedSize, - this->uncompressedSize); + const int result = LZ4_decompress_safe ( + this->compressedData.get (), this->uncompressedData.get (), this->compressedSize, + this->uncompressedSize); if (!result) sLog.exception ("Cannot decompress texture data, LZ4_decompress_safe returned an error"); @@ -251,15 +246,9 @@ CTexture::TextureHeader::TextureHeader () : gifHeight (0), format (TextureFormat::UNKNOWN), imageCount (0), - mipmapCount (0) {} + isVideoMp4 (false) {} -CTexture::TextureHeader::~TextureHeader () { - for (const auto& [index, mipmaps] : this->images) - for (const auto cur : mipmaps) - delete cur; -} - -CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) { +std::unique_ptr CTexture::parseHeader (const char* fileData) { // check the magic value on the header first if (strncmp (fileData, "TEXV0005", 9) != 0) sLog.exception ("unexpected texture container type: ", std::string_view (fileData, 9)); @@ -271,8 +260,7 @@ CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) { // jump through the string again fileData += 9; - auto* header = new TextureHeader; - + auto header = std::make_unique (); const auto* pointer = reinterpret_cast (fileData); header->format = static_cast (*pointer++); @@ -289,45 +277,55 @@ CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) { // get the position of what comes after the texture data pointer = reinterpret_cast (fileData + 9); - if (strncmp (fileData, "TEXB0003", 9) == 0) { + header->imageCount = *pointer++; + + if (strncmp (fileData, "TEXB0004", 9) == 0) { + header->containerVersion = ContainerVersion::TEXB0004; + header->freeImageFormat = static_cast (*pointer++); + header->isVideoMp4 = *pointer++ == 1; + + if (header->freeImageFormat == FIF_UNKNOWN) { + header->freeImageFormat = FIF_MP4; + } + + // default to TEXB0003 behavior if no mp4 video is there + if (header->freeImageFormat != FIF_MP4) { + header->containerVersion = ContainerVersion::TEXB0003; + } + } else if (strncmp (fileData, "TEXB0003", 9) == 0) { header->containerVersion = ContainerVersion::TEXB0003; - header->imageCount = *pointer++; header->freeImageFormat = static_cast (*pointer++); } else if (strncmp (fileData, "TEXB0002", 9) == 0) { header->containerVersion = ContainerVersion::TEXB0002; - header->imageCount = *pointer++; } else if (strncmp (fileData, "TEXB0001", 9) == 0) { header->containerVersion = ContainerVersion::TEXB0001; - header->imageCount = *pointer++; } else { - delete header; sLog.exception ("unknown texture format type: ", std::string_view (fileData, 9)); } for (uint32_t image = 0; image < header->imageCount; image++) { // read the number of mipmaps available for this image - header->mipmapCount = *pointer++; - std::vector mipmaps; + uint32_t mipmapCount = *pointer++; + std::vector> mipmaps; fileData = reinterpret_cast (pointer); - for (uint32_t i = 0; i < header->mipmapCount; i++) - mipmaps.emplace_back (parseMipmap (header, &fileData)); + for (uint32_t i = 0; i < mipmapCount; i++) + mipmaps.emplace_back (parseMipmap (header.get (), &fileData)); // add the pixmaps back - header->images.insert (std::pair (image, mipmaps)); + header->images.emplace (image, mipmaps); pointer = reinterpret_cast (fileData); } // gifs have extra information after the mipmaps - if (header->isAnimated () == true) { + if (header->isAnimated ()) { if (strncmp (fileData, "TEXS0002", 9) == 0) { header->animatedVersion = AnimatedVersion::TEXS0002; } else if (strncmp (fileData, "TEXS0003", 9) == 0) { header->animatedVersion = AnimatedVersion::TEXS0003; } else { - delete header; sLog.exception ("found animation information of unknown type: ", std::string_view (fileData, 9)); } @@ -353,7 +351,7 @@ CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) { // ensure gif width and height is right for TEXS0002 if (header->animatedVersion == AnimatedVersion::TEXS0002) { - const TextureFrame* first = *header->frames.begin (); + auto first = *header->frames.begin (); header->gifWidth = first->width1; header->gifHeight = first->height1; @@ -363,13 +361,13 @@ CTexture::TextureHeader* CTexture::parseHeader (const char* fileData) { return header; } -CTexture::TextureFrame* CTexture::parseAnimation (const char** originalFileData) { +std::shared_ptr CTexture::parseAnimation (const char** originalFileData) { const char* fileData = *originalFileData; // get back the pointer into integer const auto* pointer = reinterpret_cast (fileData); // start reading frame information - auto* frame = new TextureFrame (); + auto frame = std::make_shared (); frame->frameNumber = *pointer++; @@ -390,20 +388,38 @@ CTexture::TextureFrame* CTexture::parseAnimation (const char** originalFileData) return frame; } -CTexture::TextureMipmap* CTexture::parseMipmap (const TextureHeader* header, const char** originalFileData) { - auto* mipmap = new TextureMipmap (); - +std::shared_ptr CTexture::parseMipmap (const TextureHeader* header, const char** originalFileData) { + auto mipmap = std::make_shared (); // get the current position const char* fileData = *originalFileData; // get an integer pointer const auto* pointer = reinterpret_cast (fileData); + // TEXB004 have some extra data (and even json) that we have to take into account + if (header->containerVersion == ContainerVersion::TEXB0004) { + // ignore various params, RePKG doesn't really use them + // and could be related to the editor really, so just ignore them + pointer++; + pointer++; + + fileData = reinterpret_cast (pointer); + while (*fileData != 0) { + mipmap->json += *fileData++; + } + + // skip the null terminator + fileData ++; + + pointer = reinterpret_cast (fileData); + } + mipmap->width = *pointer++; mipmap->height = *pointer++; if (header->containerVersion == ContainerVersion::TEXB0002 || - header->containerVersion == ContainerVersion::TEXB0003) { + header->containerVersion == ContainerVersion::TEXB0003 || + header->containerVersion == ContainerVersion::TEXB0004) { mipmap->compression = *pointer++; mipmap->uncompressedSize = *pointer++; } @@ -419,18 +435,18 @@ CTexture::TextureMipmap* CTexture::parseMipmap (const TextureHeader* header, con mipmap->uncompressedSize = mipmap->compressedSize; } - mipmap->uncompressedData = new char [mipmap->uncompressedSize]; + mipmap->uncompressedData = std::unique_ptr(new char [mipmap->uncompressedSize]); if (mipmap->compression == 1) { - mipmap->compressedData = new char [mipmap->compressedSize]; + mipmap->compressedData = std::unique_ptr(new char [mipmap->compressedSize]); - memcpy (mipmap->compressedData, fileData, mipmap->compressedSize); + memcpy (mipmap->compressedData.get (), fileData, mipmap->compressedSize); mipmap->decompressData (); // advance to the end of the mipmap fileData += mipmap->compressedSize; } else { - memcpy (mipmap->uncompressedData, fileData, mipmap->uncompressedSize); + memcpy (mipmap->uncompressedData.get (), fileData, mipmap->uncompressedSize); // advance to the end of the mipmap fileData += mipmap->uncompressedSize; } diff --git a/src/WallpaperEngine/Assets/CTexture.h b/src/WallpaperEngine/Assets/CTexture.h index 9c6cc4a..2c81a2b 100644 --- a/src/WallpaperEngine/Assets/CTexture.h +++ b/src/WallpaperEngine/Assets/CTexture.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +20,7 @@ class CTexture final : public ITexture { */ enum ContainerVersion : int { UNKNOWN = -1, + TEXB0004 = 4, TEXB0003 = 3, TEXB0002 = 2, TEXB0001 = 1 @@ -41,7 +43,7 @@ class CTexture final : public ITexture { FIF_JNG = 3, FIF_KOALA = 4, FIF_LBM = 5, - FIF_IFF = FIF_LBM, + FIF_IFF = FIF_LBM, FIF_MNG = 6, FIF_PBM = 7, FIF_PBMRAW = 8, @@ -61,7 +63,7 @@ class CTexture final : public ITexture { FIF_XBM = 22, FIF_XPM = 23, FIF_DDS = 24, - FIF_GIF = 25, + FIF_GIF = 25, FIF_HDR = 26, FIF_FAXG3 = 27, FIF_SGI = 28, @@ -72,6 +74,7 @@ class CTexture final : public ITexture { FIF_PICT = 33, FIF_RAW = 34, FIF_WEBP = 35, + FIF_MP4 = FIF_WEBP, FIF_JXR = 36 }; @@ -80,9 +83,6 @@ class CTexture final : public ITexture { */ class TextureMipmap { public: - TextureMipmap (); - ~TextureMipmap (); - /** Width of the mipmap */ uint32_t width = 0; /** Height of the mipmap */ @@ -94,9 +94,11 @@ class CTexture final : public ITexture { /** Compress size of the mipmap */ uint32_t compressedSize = 0; /** Pointer to the compressed data */ - char* compressedData = nullptr; + std::unique_ptr compressedData = nullptr; /** Pointer to the uncompressed data */ - char* uncompressedData = nullptr; + std::unique_ptr uncompressedData = nullptr; + /** JSON data */ + std::string json {}; /** * Performs actual decompression of the compressed data */ @@ -109,7 +111,7 @@ class CTexture final : public ITexture { class TextureHeader { public: TextureHeader (); - ~TextureHeader (); + ~TextureHeader () = default; [[nodiscard]] bool isAnimated () const; @@ -118,57 +120,46 @@ class CTexture final : public ITexture { /** The version of the animated data */ AnimatedVersion animatedVersion = AnimatedVersion::TEXSUNKN; /** Flags with extra texture information */ - TextureFlags flags; + TextureFlags flags = TextureFlags::NoFlags; /** Real width of the texture */ - uint32_t width; + uint32_t width = 0; /** Real height of the texture */ - uint32_t height; + uint32_t height = 0; /** Texture width in memory (power of 2) */ - uint32_t textureWidth; + uint32_t textureWidth = 0; /** Texture height in memory (power of 2) */ - uint32_t textureHeight; + uint32_t textureHeight = 0; /** Gif width */ - uint32_t gifWidth; + uint32_t gifWidth = 0; /** Gif height */ - uint32_t gifHeight; + uint32_t gifHeight = 0; /** Texture data format */ - TextureFormat format; + TextureFormat format = TextureFormat::UNKNOWN; /** Free Image format */ FreeImageFormat freeImageFormat = FreeImageFormat::FIF_UNKNOWN; + /** Indicates if we have an MP4 video */ + bool isVideoMp4 = false; /** The amount of images in the texture file */ - uint32_t imageCount; - /** Number of mipmap levels on the texture */ - uint32_t mipmapCount; + uint32_t imageCount = 0; /** List of mipmaps */ - std::map> images; + std::map>> images {}; /** List of animation frames */ - std::vector frames; + std::vector> frames {}; }; public: - explicit CTexture (const void* fileData); - ~CTexture () override; + explicit CTexture (const std::shared_ptr& fileData); - /** @inheritdoc */ - [[nodiscard]] const GLuint getTextureID (uint32_t imageIndex = 0) const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getTextureWidth (uint32_t imageIndex = 0) const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getTextureHeight (uint32_t imageIndex = 0) const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getRealWidth () const override; - /** @inheritdoc */ - [[nodiscard]] const uint32_t getRealHeight () const override; - /** @inheritdoc */ - [[nodiscard]] const TextureFormat getFormat () const override; - /** @inheritdoc */ - [[nodiscard]] const TextureFlags getFlags () const override; - /** @inheritdoc */ + [[nodiscard]] GLuint getTextureID (uint32_t imageIndex) const override; + [[nodiscard]] uint32_t getTextureWidth (uint32_t imageIndex) const override; + [[nodiscard]] uint32_t getTextureHeight (uint32_t imageIndex) const override; + [[nodiscard]] uint32_t getRealWidth () const override; + [[nodiscard]] uint32_t getRealHeight () const override; + [[nodiscard]] TextureFormat getFormat () const override; + [[nodiscard]] TextureFlags getFlags () const override; [[nodiscard]] const glm::vec4* getResolution () const override; - /** @inheritdoc */ - [[nodiscard]] const std::vector& getFrames () const override; - /** @inheritdoc */ - [[nodiscard]] const bool isAnimated () const override; + [[nodiscard]] const std::vector>& getFrames () const override; + [[nodiscard]] bool isAnimated () const override; private: /** @@ -182,14 +173,14 @@ class CTexture final : public ITexture { * @param fileData The point at which to start reading data off from * @return */ - static TextureHeader* parseHeader (const char* fileData); + static std::unique_ptr parseHeader (const char* fileData); /** * Tries to parse an animation frame off the given data pointer * * @param originalFileData The point at which to start reading data off from * @return */ - static TextureFrame* parseAnimation (const char** originalFileData); + static std::shared_ptr parseAnimation (const char** originalFileData); /** * Tries to parse mipmap information off the given data pointer * @@ -197,13 +188,26 @@ class CTexture final : public ITexture { * @param fileData The point at which to start reading data off from * @return */ - static TextureMipmap* parseMipmap (const TextureHeader* header, const char** fileData); + static std::shared_ptr parseMipmap (const TextureHeader* header, const char** fileData); + + /** + * Calculate's texture's resolution vec4 + */ + void setupResolution (); + /** + * Determines the texture's internal storage format + */ + GLint setupInternalFormat (); + /** + * Prepares openGL parameters for loading texture data + */ + void setupOpenGLParameters (uint32_t textureID); /** The texture header */ - TextureHeader* m_header; + std::unique_ptr m_header = nullptr; /** OpenGL's texture ID */ - GLuint* m_textureID; + GLuint* m_textureID = nullptr; /** Resolution vector of the texture */ - glm::vec4 m_resolution; + glm::vec4 m_resolution {}; }; } // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CVirtualContainer.cpp b/src/WallpaperEngine/Assets/CVirtualContainer.cpp index 5526def..c68ce32 100644 --- a/src/WallpaperEngine/Assets/CVirtualContainer.cpp +++ b/src/WallpaperEngine/Assets/CVirtualContainer.cpp @@ -5,21 +5,30 @@ using namespace WallpaperEngine::Assets; -void CVirtualContainer::add (const std::string& filename, const uint8_t* contents, uint32_t length) { - this->m_virtualFiles.insert (std::make_pair (filename, new CFileEntry (contents, length))); +void CVirtualContainer::add (const std::filesystem::path& filename, const std::shared_ptr& contents, uint32_t length) { + this->m_virtualFiles.emplace (filename, std::make_unique (contents, length)); } -void CVirtualContainer::add (const std::string& filename, const std::string& contents) { - auto* copy = new uint8_t [contents.length () + 1]; +void CVirtualContainer::add (const std::filesystem::path& filename, const std::string& contents) { + size_t length = contents.length () + 1; + std::shared_ptr copy = std::shared_ptr (new uint8_t [length]); // copy the text AND the \0 - memcpy (copy, contents.c_str (), contents.length () + 1); + memcpy (copy.get(), contents.c_str (), length); // finally add to the container - this->add (filename, copy, contents.length () + 1); + this->add (filename, copy, length); } -const uint8_t* CVirtualContainer::readFile (const std::string& filename, uint32_t* length) const { +void CVirtualContainer::add (const std::filesystem::path& filename, const char* contents) { + this->add (filename, std::string (contents)); +} + +void CVirtualContainer::add (const std::filesystem::path& filename, const json& contents) { + this->add (filename, contents.dump ()); +} + +std::shared_ptr CVirtualContainer::readFile (const std::filesystem::path& filename, uint32_t* length) const { const auto cur = this->m_virtualFiles.find (filename); if (cur == this->m_virtualFiles.end ()) @@ -29,9 +38,5 @@ const uint8_t* CVirtualContainer::readFile (const std::string& filename, uint32_ *length = cur->second->length; // clone original first - auto* result = new uint8_t [cur->second->length]; - - memcpy (result, cur->second->address, cur->second->length); - - return result; + return cur->second->content; } \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/CVirtualContainer.h b/src/WallpaperEngine/Assets/CVirtualContainer.h index 4181ac3..6957f3b 100644 --- a/src/WallpaperEngine/Assets/CVirtualContainer.h +++ b/src/WallpaperEngine/Assets/CVirtualContainer.h @@ -2,11 +2,15 @@ #include #include +#include #include "CContainer.h" #include "CFileEntry.h" +#include + namespace WallpaperEngine::Assets { +using json = nlohmann::json; /** * Virtual container implementation, provides virtual files for the backgrounds to use */ @@ -19,7 +23,7 @@ class CVirtualContainer final : public CContainer { * @param contents * @param length */ - void add (const std::string& filename, const uint8_t* contents, uint32_t length); + void add (const std::filesystem::path& filename, const std::shared_ptr& contents, uint32_t length); /** * Adds a new file to the virtual container @@ -27,12 +31,27 @@ class CVirtualContainer final : public CContainer { * @param filename * @param contents */ - void add (const std::string& filename, const std::string& contents); + void add (const std::filesystem::path& filename, const std::string& contents); + + /** + * Adds a new file to the virtual container + * + * @param filename + * @param contents + */ + void add (const std::filesystem::path& filename, const char* contents); + /** + * Adds a new file to the virtual container from a json object + * @param filename + * @param contents + */ + void add (const std::filesystem::path& filename, const json& contents); + /** @inheritdoc */ - const uint8_t* readFile (const std::string& filename, uint32_t* length) const override; + std::shared_ptr readFile (const std::filesystem::path& filename, uint32_t* length) const override; private: /** The recorded files in this virtual container */ - std::map m_virtualFiles; + std::map> m_virtualFiles = {}; }; } // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Assets/ITexture.h b/src/WallpaperEngine/Assets/ITexture.h index 03fa0a4..f647059 100644 --- a/src/WallpaperEngine/Assets/ITexture.h +++ b/src/WallpaperEngine/Assets/ITexture.h @@ -1,8 +1,10 @@ #pragma once +#include +#include + #include #include -#include namespace WallpaperEngine::Assets { /** @@ -22,19 +24,19 @@ class ITexture { virtual ~TextureFrame () = default; /** The image index of this frame */ - uint32_t frameNumber; + uint32_t frameNumber = 0; /** The amount of time this frame spends being displayed */ - float frametime; + float frametime = 0.0f; /** The x position of the frame in the texture */ - float x; + float x = 0.0f; /** The y position of the frame in the texture */ - float y; + float y = 0.0f; /** The width of the frame in the texture */ - float width1; - float width2; - float height2; + float width1 = 0.0f; + float width2 = 0.0f; /** The height of the frame in the texture */ - float height1; + float height1 = 0.0f; + float height2 = 0.0f; }; /** @@ -73,37 +75,37 @@ class ITexture { * @param imageIndex For animated textures, the frame to get the ID of * @return The OpenGL texture to use when rendering */ - [[nodiscard]] virtual const GLuint getTextureID (uint32_t imageIndex = 0) const = 0; + [[nodiscard]] virtual GLuint getTextureID (uint32_t imageIndex) const = 0; /** * @param imageIndex For animated textures, the frame to get the ID of * @return The texture's width */ - [[nodiscard]] virtual const uint32_t getTextureWidth (uint32_t imageIndex = 0) const = 0; + [[nodiscard]] virtual uint32_t getTextureWidth (uint32_t imageIndex) const = 0; /** * @param imageIndex For animated textures, the frame to get the ID of * @return The texture's height */ - [[nodiscard]] virtual const uint32_t getTextureHeight (uint32_t imageIndex = 0) const = 0; + [[nodiscard]] virtual uint32_t getTextureHeight (uint32_t imageIndex) const = 0; /** * @return The textures real width */ - [[nodiscard]] virtual const uint32_t getRealWidth () const = 0; + [[nodiscard]] virtual uint32_t getRealWidth () const = 0; /** * @return The textures real height */ - [[nodiscard]] virtual const uint32_t getRealHeight () const = 0; + [[nodiscard]] virtual uint32_t getRealHeight () const = 0; /** * @return The texture's memory format */ - [[nodiscard]] virtual const TextureFormat getFormat () const = 0; + [[nodiscard]] virtual TextureFormat getFormat () const = 0; /** * @return The texture's settings */ - [[nodiscard]] virtual const TextureFlags getFlags () const = 0; + [[nodiscard]] virtual TextureFlags getFlags () const = 0; /** * @return The list of frames this texture has */ - [[nodiscard]] virtual const std::vector& getFrames () const = 0; + [[nodiscard]] virtual const std::vector>& getFrames () const = 0; /** * @return The texture's resolution vector */ @@ -111,6 +113,6 @@ class ITexture { /** * @return If the texture is animated or not */ - [[nodiscard]] virtual const bool isAnimated () const = 0; + [[nodiscard]] virtual bool isAnimated () const = 0; }; } // namespace WallpaperEngine::Assets \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/CAudioStream.cpp b/src/WallpaperEngine/Audio/CAudioStream.cpp index d21610e..495639b 100644 --- a/src/WallpaperEngine/Audio/CAudioStream.cpp +++ b/src/WallpaperEngine/Audio/CAudioStream.cpp @@ -1,12 +1,10 @@ #include "CAudioStream.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include -#include #include +#include // maximum size of the queue to prevent reading too much data -#define MAX_QUEUE_SIZE (5 * 1024 * 1024) -#define MIN_FRAMES 25 using namespace WallpaperEngine::Audio; @@ -67,7 +65,7 @@ static int audio_read_data_callback (void* streamarg, uint8_t* buffer, int buffe buffer_size = FFMIN (buffer_size, left); - memcpy (buffer, stream->getBuffer () + stream->getPosition (), buffer_size); + memcpy (buffer, stream->getBuffer ().get() + stream->getPosition (), buffer_size); // update position stream->setPosition (stream->getPosition () + buffer_size); @@ -82,7 +80,6 @@ int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) { switch (whence) { case SEEK_CUR: stream->setPosition (stream->getPosition () + offset); break; - case SEEK_SET: stream->setPosition (offset); break; } @@ -90,14 +87,12 @@ int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) { } CAudioStream::CAudioStream (CAudioContext& context, const std::string& filename) : - m_audioContext (context), - m_swrctx (nullptr) { + m_audioContext (context) { this->loadCustomContent (filename.c_str ()); } -CAudioStream::CAudioStream (CAudioContext& context, const uint8_t* buffer, uint32_t length) : - m_audioContext (context), - m_swrctx (nullptr) { +CAudioStream::CAudioStream (CAudioContext& context, std::shared_ptr buffer, uint32_t length) : + m_audioContext (context) { // setup a custom context first this->m_formatContext = avformat_alloc_context (); @@ -120,10 +115,9 @@ CAudioStream::CAudioStream (CAudioContext& context, const uint8_t* buffer, uint3 } CAudioStream::CAudioStream (CAudioContext& audioContext, AVCodecContext* context) : - m_context (context), - m_queue (new PacketQueue), m_audioContext (audioContext), - m_swrctx (nullptr) { + m_context (context), + m_queue (new PacketQueue) { this->initialize (); } @@ -142,17 +136,14 @@ void CAudioStream::loadCustomContent (const char* filename) { if (avformat_find_stream_info (this->m_formatContext, nullptr) < 0) sLog.exception ("Cannot determine file format: ", filename); - bool hasAudioStream = false; - // find the audio stream for (unsigned int i = 0; i < this->m_formatContext->nb_streams; i++) { - if (this->m_formatContext->streams [i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && hasAudioStream == false) { - hasAudioStream = true; + if (this->m_formatContext->streams [i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && this->m_audioStream == NO_AUDIO_STREAM) { this->m_audioStream = i; } } - if (!hasAudioStream) + if (this->m_audioStream == NO_AUDIO_STREAM) sLog.exception ("Cannot find an audio stream in file ", filename); // get the decoder for it and alloc the required context @@ -282,12 +273,11 @@ bool CAudioStream::doQueue (AVPacket* pkt) { } void CAudioStream::dequeuePacket (AVPacket* output) { - MyAVPacketList entry; + MyAVPacketList entry{}; SDL_LockMutex (this->m_queue->mutex); while (this->m_audioContext.getApplicationContext ().state.general.keepRunning) { - #if FF_API_FIFO_OLD_API int ret = -1; @@ -324,7 +314,7 @@ AVFormatContext* CAudioStream::getFormatContext () { return this->m_formatContext; } -unsigned int CAudioStream::getAudioStream () const { +int CAudioStream::getAudioStream () const { return this->m_audioStream; } @@ -340,7 +330,7 @@ bool CAudioStream::isRepeat () const { return this->m_repeat; } -const uint8_t* CAudioStream::getBuffer () { +std::shared_ptr CAudioStream::getBuffer () { return this->m_buffer; } @@ -369,6 +359,10 @@ int CAudioStream::getQueuePacketCount () { } AVRational CAudioStream::getTimeBase () { + if (this->m_audioStream == NO_AUDIO_STREAM) { + return {0, 0}; + } + return this->m_formatContext->streams [this->m_audioStream]->time_base; } diff --git a/src/WallpaperEngine/Audio/CAudioStream.h b/src/WallpaperEngine/Audio/CAudioStream.h index d13cf3b..9cc8734 100644 --- a/src/WallpaperEngine/Audio/CAudioStream.h +++ b/src/WallpaperEngine/Audio/CAudioStream.h @@ -24,6 +24,10 @@ extern "C" { #define FF_API_OLD_CHANNEL_LAYOUT (LIBAVUTIL_VERSION_MAJOR < 59) #endif +#define MAX_QUEUE_SIZE (5 * 1024 * 1024) +#define MIN_FRAMES (25) +#define NO_AUDIO_STREAM (-1) + namespace WallpaperEngine::Audio { class CAudioContext; @@ -33,7 +37,7 @@ class CAudioContext; class CAudioStream { public: CAudioStream (CAudioContext& context, const std::string& filename); - CAudioStream (CAudioContext& context, const uint8_t* buffer, uint32_t length); + CAudioStream (CAudioContext& context, std::shared_ptr buffer, uint32_t length); CAudioStream (CAudioContext& audioContext, AVCodecContext* context); ~CAudioStream (); @@ -64,7 +68,7 @@ class CAudioStream { /** * @return The audio stream index of the given file */ - [[nodiscard]] unsigned int getAudioStream () const; + [[nodiscard]] int getAudioStream () const; /** * @return If the audio stream can be played or not */ @@ -84,7 +88,7 @@ class CAudioStream { /** * @return The file data buffer */ - [[nodiscard]] const uint8_t* getBuffer (); + [[nodiscard]] std::shared_ptr getBuffer (); /** * @return The length of the file data buffer */ @@ -167,23 +171,23 @@ class CAudioStream { void initialize (); /** The SwrContext that handles resampling */ - SwrContext* m_swrctx; + SwrContext* m_swrctx = nullptr; /** The audio context this stream will be played under */ CAudioContext& m_audioContext; /** If this stream was properly initialized or not */ - bool m_initialized {}; + bool m_initialized = false; /** Repeat enabled? */ - bool m_repeat {}; + bool m_repeat = false; /** The codec context that contains the original audio format information */ AVCodecContext* m_context = nullptr; /** The format context that controls how data is read off the file */ AVFormatContext* m_formatContext = nullptr; /** The stream index for the audio being played */ - unsigned int m_audioStream; + int m_audioStream = NO_AUDIO_STREAM; /** File data pointer */ - const uint8_t* m_buffer {}; + std::shared_ptr m_buffer = nullptr; /** The length of the file data pointer */ - uint32_t m_length {}; + uint32_t m_length = 0; /** The read position on the file data pointer */ uint32_t m_position = 0; @@ -196,16 +200,16 @@ class CAudioStream { */ struct PacketQueue { #if FF_API_FIFO_OLD_API - AVFifoBuffer* packetList; + AVFifoBuffer* packetList = nullptr; #else - AVFifo* packetList; + AVFifo* packetList = nullptr; #endif - int nb_packets; - int size; - int64_t duration; - SDL_mutex* mutex; - SDL_cond* wait; - SDL_cond* cond; + int nb_packets = 0; + int size = 0; + int64_t duration = 0; + SDL_mutex* mutex = nullptr; + SDL_cond* wait = nullptr; + SDL_cond* cond = nullptr; }* m_queue {}; }; } // namespace WallpaperEngine::Audio diff --git a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp index a68f9c2..2baa59f 100644 --- a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp +++ b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.cpp @@ -1,8 +1,10 @@ #include "CAudioDriver.h" namespace WallpaperEngine::Audio::Drivers { -CAudioDriver::CAudioDriver (Application::CApplicationContext& applicationContext, - Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder) : +CAudioDriver::CAudioDriver ( + Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, + Recorders::CPlaybackRecorder& recorder +) : m_applicationContext (applicationContext), m_detector (detector), m_recorder (recorder) {} diff --git a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h index 28eab39..ab24d8f 100644 --- a/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h +++ b/src/WallpaperEngine/Audio/Drivers/CAudioDriver.h @@ -29,8 +29,9 @@ class CPulseAudioPlaybackRecorder; */ class CAudioDriver { public: - explicit CAudioDriver (Application::CApplicationContext& applicationContext, - Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder); + explicit CAudioDriver ( + Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, + Recorders::CPlaybackRecorder& recorder); virtual ~CAudioDriver () = default; /** diff --git a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp index 98d2f9f..fc948c7 100644 --- a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp +++ b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.cpp @@ -1,5 +1,5 @@ #include "CSDLAudioDriver.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #define SDL_AUDIO_BUFFER_SIZE 4096 #define MAX_AUDIO_FRAME_SIZE 192000 @@ -53,8 +53,9 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) { len1 = streamLength; // mix the audio - SDL_MixAudioFormat (streamDataPointer, &buffer->audio_buf [buffer->audio_buf_index], - driver->getSpec ().format, len1, driver->getApplicationContext ().state.audio.volume); + SDL_MixAudioFormat ( + streamDataPointer, &buffer->audio_buf [buffer->audio_buf_index], driver->getSpec ().format, + len1, driver->getApplicationContext ().state.audio.volume); streamLength -= len1; streamDataPointer += len1; @@ -63,10 +64,11 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) { } } -CSDLAudioDriver::CSDLAudioDriver (Application::CApplicationContext& applicationContext, - Detectors::CAudioPlayingDetector& detector, Recorders::CPlaybackRecorder& recorder) : +CSDLAudioDriver::CSDLAudioDriver ( + Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, + Recorders::CPlaybackRecorder& recorder +) : CAudioDriver (applicationContext, detector, recorder), - m_initialized (false), m_audioSpec () { if (SDL_InitSubSystem (SDL_INIT_AUDIO) < 0) { sLog.error ("Cannot initialize SDL audio system, SDL_GetError: ", SDL_GetError ()); @@ -75,12 +77,14 @@ CSDLAudioDriver::CSDLAudioDriver (Application::CApplicationContext& applicationC return; } - const SDL_AudioSpec requestedSpec = {.freq = 48000, - .format = AUDIO_F32, - .channels = 2, - .samples = SDL_AUDIO_BUFFER_SIZE, - .callback = audio_callback, - .userdata = this}; + const SDL_AudioSpec requestedSpec = { + .freq = 48000, + .format = AUDIO_F32, + .channels = 2, + .samples = SDL_AUDIO_BUFFER_SIZE, + .callback = audio_callback, + .userdata = this + }; this->m_deviceID = SDL_OpenAudioDevice (nullptr, false, &requestedSpec, &this->m_audioSpec, SDL_AUDIO_ALLOW_ANY_CHANGE); diff --git a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h index 2c75716..3e441e7 100644 --- a/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h +++ b/src/WallpaperEngine/Audio/Drivers/CSDLAudioDriver.h @@ -15,7 +15,7 @@ namespace WallpaperEngine::Audio::Drivers { * Audio output buffers for streams being played under SDL */ struct CSDLAudioBuffer { - CAudioStream* stream; + CAudioStream* stream = nullptr; uint8_t audio_buf [(MAX_AUDIO_FRAME_SIZE * 3) / 2] = {0}; unsigned int audio_buf_size = 0; unsigned int audio_buf_index = 0; @@ -26,8 +26,9 @@ struct CSDLAudioBuffer { */ class CSDLAudioDriver final : public CAudioDriver { public: - CSDLAudioDriver (Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, - Recorders::CPlaybackRecorder& recorder); + CSDLAudioDriver ( + Application::CApplicationContext& applicationContext, Detectors::CAudioPlayingDetector& detector, + Recorders::CPlaybackRecorder& recorder); ~CSDLAudioDriver () override; /** @inheritdoc */ @@ -52,10 +53,10 @@ class CSDLAudioDriver final : public CAudioDriver { /** The device's ID */ SDL_AudioDeviceID m_deviceID; /** If the driver is initialized or not */ - bool m_initialized; + bool m_initialized = false; /** The sound output configuration */ - SDL_AudioSpec m_audioSpec; + SDL_AudioSpec m_audioSpec {}; /** All the playable steams */ - std::vector m_streams; + std::vector m_streams {}; }; } // namespace WallpaperEngine::Audio::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp index acf976c..5c18def 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.cpp @@ -5,8 +5,7 @@ CAudioPlayingDetector::CAudioPlayingDetector ( Application::CApplicationContext& appContext, const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector) : m_applicationContext (appContext), - m_fullscreenDetector (fullscreenDetector), - m_isPlaying (false) {} + m_fullscreenDetector (fullscreenDetector) {} bool CAudioPlayingDetector::anythingPlaying () const { return this->m_isPlaying; @@ -23,4 +22,7 @@ const Render::Drivers::Detectors::CFullScreenDetector& CAudioPlayingDetector::ge void CAudioPlayingDetector::setIsPlaying (bool newState) { this->m_isPlaying = newState; } + +void CAudioPlayingDetector::update () {} + } // namespace WallpaperEngine::Audio::Drivers::Detectors \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h index e99529e..c620754 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CAudioPlayingDetector.h @@ -18,8 +18,9 @@ namespace Audio::Drivers::Detectors { */ class CAudioPlayingDetector { public: - CAudioPlayingDetector (Application::CApplicationContext& appContext, - const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector); + CAudioPlayingDetector ( + Application::CApplicationContext& appContext, + const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector); virtual ~CAudioPlayingDetector () = default; @@ -38,7 +39,9 @@ class CAudioPlayingDetector { /** * Checks if any audio is playing and updates state accordingly */ - virtual void update () = 0; + virtual void update (); + + protected: /** * @return The application context using this detector */ @@ -49,7 +52,7 @@ class CAudioPlayingDetector { [[nodiscard]] const Render::Drivers::Detectors::CFullScreenDetector& getFullscreenDetector () const; private: - bool m_isPlaying; + bool m_isPlaying = false; Application::CApplicationContext& m_applicationContext; const Render::Drivers::Detectors::CFullScreenDetector& m_fullscreenDetector; diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp index 3720c0d..aac9fb3 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.cpp @@ -16,7 +16,7 @@ void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info, // get processid const char* value = pa_proplist_gets (info->proplist, PA_PROP_APPLICATION_PROCESS_ID); - if (value && atoi (value) != getpid () && pa_cvolume_avg (&info->volume) != PA_VOLUME_MUTED) + if (value && strtol (value, nullptr, 10) != getpid () && pa_cvolume_avg (&info->volume) != PA_VOLUME_MUTED) detector->setIsPlaying (true); } @@ -32,10 +32,7 @@ void defaultSinkInfoCallback (pa_context* context, const pa_server_info* info, v CPulseAudioPlayingDetector::CPulseAudioPlayingDetector ( Application::CApplicationContext& appContext, const Render::Drivers::Detectors::CFullScreenDetector& fullscreenDetector) : - CAudioPlayingDetector (appContext, fullscreenDetector), - m_mainloop (nullptr), - m_mainloopApi (nullptr), - m_context (nullptr) { + CAudioPlayingDetector (appContext, fullscreenDetector) { this->m_mainloop = pa_mainloop_new (); this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop); this->m_context = pa_context_new (this->m_mainloopApi, "wallpaperengine"); diff --git a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h index 6527df7..bb063c9 100644 --- a/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h +++ b/src/WallpaperEngine/Audio/Drivers/Detectors/CPulseAudioPlayingDetector.h @@ -8,15 +8,15 @@ namespace WallpaperEngine::Audio::Drivers::Detectors { class CPulseAudioPlayingDetector final : public CAudioPlayingDetector { public: - explicit CPulseAudioPlayingDetector (Application::CApplicationContext& appContext, - const Render::Drivers::Detectors::CFullScreenDetector&); + explicit CPulseAudioPlayingDetector ( + Application::CApplicationContext& appContext, const Render::Drivers::Detectors::CFullScreenDetector&); ~CPulseAudioPlayingDetector () override; void update () override; private: - pa_mainloop* m_mainloop; - pa_mainloop_api* m_mainloopApi; - pa_context* m_context; + pa_mainloop* m_mainloop = nullptr; + pa_mainloop_api* m_mainloopApi = nullptr; + pa_context* m_context = nullptr; }; } // namespace WallpaperEngine::Audio::Drivers::Detectors diff --git a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp index b2fe743..915af85 100644 --- a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp +++ b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.cpp @@ -1,11 +1,9 @@ #include "CPulseAudioPlaybackRecorder.h" -#include "External/Android/fft.h" #include "WallpaperEngine/Logging/CLog.h" #include #include #include -namespace WallpaperEngine::Audio::Drivers::Recorders { float movetowards (float current, float target, float maxDelta) { if (abs (target - current) <= maxDelta) return target; @@ -13,15 +11,17 @@ float movetowards (float current, float target, float maxDelta) { return current + glm::sign (target - current) * maxDelta; } +namespace WallpaperEngine::Audio::Drivers::Recorders { void pa_stream_notify_cb (pa_stream* stream, void* /*userdata*/) { switch (pa_stream_get_state (stream)) { case PA_STREAM_FAILED: sLog.error ("Cannot open stream for capture. Audio processing is disabled"); break; case PA_STREAM_READY: sLog.debug ("Capture stream ready"); break; + default: sLog.debug("pa_stream_get_state unknown result"); break; } } void pa_stream_read_cb (pa_stream* stream, const size_t /*nbytes*/, void* userdata) { - auto* recorder = static_cast (userdata); + auto* recorder = static_cast (userdata); // Careful when to pa_stream_peek() and pa_stream_drop()! // c.f. https://www.freedesktop.org/software/pulseaudio/doxygen/stream_8h.html#ac2838c449cde56e169224d7fe3d00824 @@ -46,27 +46,37 @@ void pa_stream_read_cb (pa_stream* stream, const size_t /*nbytes*/, void* userda } else if (currentSize > 0 && data) { size_t dataToCopy = std::min (currentSize, WAVE_BUFFER_SIZE - recorder->currentWritePointer); - memcpy (&recorder->audio_buffer_tmp [recorder->currentWritePointer], data, dataToCopy * sizeof (uint8_t)); + // depending on the amount of data available, we might want to read one or multiple frames + size_t end = recorder->currentWritePointer + dataToCopy; - recorder->currentWritePointer += dataToCopy; + // this packet will fill the buffer, perform some extra checks for extra full buffers and get the latest one + if (end == WAVE_BUFFER_SIZE) { + size_t numberOfFullBuffers = (currentSize - dataToCopy) / WAVE_BUFFER_SIZE; - if (recorder->currentWritePointer == WAVE_BUFFER_SIZE) { - // copy to the final buffer - memcpy (recorder->audio_buffer, recorder->audio_buffer_tmp, WAVE_BUFFER_SIZE * sizeof (uint8_t)); - // reset the write pointer - recorder->currentWritePointer = 0; - recorder->fullframeReady = true; - } + if (numberOfFullBuffers > 0) { + // calculate the start of the last block (we need the end of the previous block, hence the - 1) + size_t startOfLastBuffer = std::max(dataToCopy + (numberOfFullBuffers - 1) * WAVE_BUFFER_SIZE, currentSize - WAVE_BUFFER_SIZE); + // copy directly into the final buffer + memcpy (recorder->audioBuffer, &data [startOfLastBuffer], WAVE_BUFFER_SIZE * sizeof (uint8_t)); + // copy whatever is left to the read/write buffer + recorder->currentWritePointer = currentSize - startOfLastBuffer - WAVE_BUFFER_SIZE; + memcpy (recorder->audioBufferTmp, &data [startOfLastBuffer + WAVE_BUFFER_SIZE], recorder->currentWritePointer * sizeof (uint8_t)); + } else { + // okay, no full extra packets available, copy the rest of the data and flip the buffers + memcpy (&recorder->audioBufferTmp [recorder->currentWritePointer], data, dataToCopy * sizeof (uint8_t)); + uint8_t* tmp = recorder->audioBuffer; + recorder->audioBuffer = recorder->audioBufferTmp; + recorder->audioBufferTmp = tmp; + // reset write pointer + recorder->currentWritePointer = 0; + } - // any data read left? - if (dataToCopy < currentSize) { - while ((currentSize - dataToCopy) > WAVE_BUFFER_SIZE) - dataToCopy += WAVE_BUFFER_SIZE; // there's more than one full frame available, skip it entirely - - // data pending, keep it in the buffer - memcpy (recorder->audio_buffer_tmp, data + dataToCopy, (currentSize - dataToCopy) * sizeof (uint8_t)); - - recorder->currentWritePointer = currentSize - dataToCopy; + // signal a new frame is ready + recorder->fullFrameReady = true; + } else { + // copy over available data to the tmp buffer and everything should be set + memcpy (&recorder->audioBufferTmp [recorder->currentWritePointer], data, dataToCopy * sizeof (uint8_t)); + recorder->currentWritePointer += dataToCopy; } } @@ -76,31 +86,34 @@ void pa_stream_read_cb (pa_stream* stream, const size_t /*nbytes*/, void* userda } void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userdata) { - auto* recorder = static_cast (userdata); + auto* recorder = static_cast (userdata); pa_sample_spec spec; spec.format = PA_SAMPLE_U8; spec.rate = 44100; spec.channels = 1; - if (recorder->getCaptureStream ()) { - pa_stream_unref (recorder->getCaptureStream ()); - // get rid of the reference just in case - recorder->setCaptureStream (nullptr); + if (recorder->captureStream) { + pa_stream_unref (recorder->captureStream); } - pa_stream* captureStream = pa_stream_new (ctx, "output monitor", &spec, nullptr); + recorder->captureStream = pa_stream_new (ctx, "output monitor", &spec, nullptr); - // store the stream first, if the record start fails there'll still be a reference to it - // so it can be free'd later - recorder->setCaptureStream (captureStream), - - pa_stream_set_state_callback (captureStream, &pa_stream_notify_cb, userdata); - pa_stream_set_read_callback (captureStream, &pa_stream_read_cb, userdata); + pa_stream_set_state_callback (recorder->captureStream, &pa_stream_notify_cb, userdata); + pa_stream_set_read_callback (recorder->captureStream, &pa_stream_read_cb, userdata); std::string monitor_name (info->default_sink_name); monitor_name += ".monitor"; - if (pa_stream_connect_record (captureStream, monitor_name.c_str (), nullptr, PA_STREAM_NOFLAGS) != 0) { + + // setup latency + pa_buffer_attr attr {}; + + // 10 = latency msecs, 750 = max msecs to store + size_t bytesPerSec = pa_bytes_per_second (&spec); + attr.fragsize = bytesPerSec * 10 / 100; + attr.maxlength = attr.fragsize + bytesPerSec * 750 / 100; + + if (pa_stream_connect_record (recorder->captureStream, monitor_name.c_str (), &attr, PA_STREAM_ADJUST_LATENCY) != 0) { sLog.error ("Failed to connect to input for recording"); } } @@ -131,15 +144,23 @@ void pa_context_notify_cb (pa_context* ctx, void* userdata) { case PA_CONTEXT_FAILED: sLog.error ("PulseAudio context initialization failed. Audio processing is disabled"); break; + default: + sLog.debug ("pa_context_get_state unknown result"); + break; } } -CPulseAudioPlaybackRecorder::CPulseAudioPlaybackRecorder () : m_captureStream (nullptr) { +CPulseAudioPlaybackRecorder::CPulseAudioPlaybackRecorder () : + m_captureData({ + .kisscfg = kiss_fftr_alloc (WAVE_BUFFER_SIZE, 0, nullptr, nullptr), + .audioBuffer = new uint8_t [WAVE_BUFFER_SIZE], + .audioBufferTmp = new uint8_t [WAVE_BUFFER_SIZE] + }) { this->m_mainloop = pa_mainloop_new (); this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop); this->m_context = pa_context_new (this->m_mainloopApi, "wallpaperengine-audioprocessing"); - pa_context_set_state_callback (this->m_context, &pa_context_notify_cb, this); + pa_context_set_state_callback (this->m_context, &pa_context_notify_cb, &this->m_captureData); if (pa_context_connect (this->m_context, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) { sLog.error ("PulseAudio connection failed! Audio processing is disabled"); @@ -152,54 +173,62 @@ CPulseAudioPlaybackRecorder::CPulseAudioPlaybackRecorder () : m_captureStream (n } CPulseAudioPlaybackRecorder::~CPulseAudioPlaybackRecorder () { + if (m_captureData.captureStream) { + pa_stream_unref (m_captureData.captureStream); + } + + delete [] this->m_captureData.audioBufferTmp; + delete [] this->m_captureData.audioBuffer; + free (this->m_captureData.kisscfg); + pa_context_disconnect (this->m_context); pa_mainloop_free (this->m_mainloop); } -pa_stream* CPulseAudioPlaybackRecorder::getCaptureStream () { - return this->m_captureStream; -} - -void CPulseAudioPlaybackRecorder::setCaptureStream (pa_stream* stream) { - this->m_captureStream = stream; -} - void CPulseAudioPlaybackRecorder::update () { pa_mainloop_iterate (this->m_mainloop, 0, nullptr); // interpolate current values to the destination for (int i = 0; i < 64; i++) { - this->audio64 [i] = movetowards (this->audio64 [i], fft_destination64 [i], 0.1f); + this->audio64 [i] = movetowards (this->audio64 [i], this->m_FFTdestination64 [i], 0.3f); if (i >= 32) continue; - this->audio32 [i] = movetowards (this->audio32 [i], fft_destination32 [i], 0.1f); + this->audio32 [i] = movetowards (this->audio32 [i], this->m_FFTdestination32 [i], 0.3f); if (i >= 16) continue; - this->audio16 [i] = movetowards (this->audio16 [i], fft_destination16 [i], 0.1f); + this->audio16 [i] = movetowards (this->audio16 [i], this->m_FFTdestination16 [i], 0.3f); } - if (!this->fullframeReady) + if (!this->m_captureData.fullFrameReady) return; - this->fullframeReady = false; + this->m_captureData.fullFrameReady = false; - External::Android::doFft (audio_fft, audio_buffer); + // convert audio data to deltas so the fft library can properly handle it + for (int i = 0; i < WAVE_BUFFER_SIZE; i ++) { + this->m_audioFFTbuffer [i] = (this->m_captureData.audioBuffer[i] - 128) / 128.0f; + } - for (int i = 0; i < 64; i++) { - const int paramInt = (i + 2) * 2; - float f1 = audio_fft [paramInt]; - float f2 = audio_fft [paramInt + 1]; - f2 = f1 * f1 + f2 * f2; - f1 = 0.0F; - if (f2 > 0.0F) - f1 = 0.35F * static_cast (log10 (f2)); + // perform full fft pass + kiss_fftr (this->m_captureData.kisscfg, this->m_audioFFTbuffer, this->m_FFTinfo); - this->fft_destination64 [i] = - fmin (1.0F, f1 * static_cast (2.0f - pow (M_E, (1.0F - i / 63.0F) * 1.0f - 0.5f))); - this->fft_destination32 [i >> 1] = - fmin (1.0F, f1 * static_cast (2.0f - pow (M_E, (1.0F - i / 31.0F) * 1.0f - 0.5f))); - this->fft_destination16 [i >> 2] = - fmin (1.0F, f1 * static_cast (2.0f - pow (M_E, (1.0F - i / 15.0F) * 1.0f - 0.5f))); + // now reduce to the different bands + // use just one for loop to produce all 3 + for (int band = 0; band < 64; band ++) { + int index = band * 2; + float f1 = this->m_FFTinfo[index].r; + float f2 = this->m_FFTinfo[index].i; + f2 = f1 * f1 + f2 * f2; // magnitude + f1 = 0.0f; + + if (f2 > 0.0f) { + f1 = 0.35f * log10 (f2); + } + + this->m_FFTdestination64 [band] = fmin (1.0f, f1 * static_cast (2.0f - pow (M_E, (1.0f - band / 63.0f) * 1.0f - 0.5f))); + this->m_FFTdestination32 [band >> 1] = fmin (1.0f, f1 * static_cast (2.0f - pow (M_E, (1.0f - band / 31.0f) * 1.0f - 0.5f))); + this->m_FFTdestination16 [band >> 2] = fmin (1.0f, f1 * static_cast (2.0f - pow (M_E, (1.0f - band / 15.0f) * 1.0f - 0.5f))); } } + } // namespace WallpaperEngine::Audio::Drivers::Recorders \ No newline at end of file diff --git a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h index 7c38b08..aa576fe 100644 --- a/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h +++ b/src/WallpaperEngine/Audio/Drivers/Recorders/CPulseAudioPlaybackRecorder.h @@ -1,43 +1,43 @@ #pragma once +#include "kiss_fftr.h" #include "CPlaybackRecorder.h" -#include "External/Android/fft.h" #include +#define WAVE_BUFFER_SIZE 1024 + namespace WallpaperEngine::Audio::Drivers::Recorders { class CPlaybackRecorder; class CPulseAudioPlaybackRecorder final : public CPlaybackRecorder { public: + /** + * Struct that contains all the required data for the PulseAudio callbacks + */ + struct SPulseAudioData { + kiss_fftr_cfg kisscfg; + uint8_t* audioBuffer; + uint8_t* audioBufferTmp; + size_t currentWritePointer; + bool fullFrameReady; + pa_stream* captureStream; + }; + CPulseAudioPlaybackRecorder (); ~CPulseAudioPlaybackRecorder () override; void update () override; - /** - * @return The current stream we're capturing from - */ - [[nodiscard]] pa_stream* getCaptureStream (); - - /** - * @param stream The new stream to be capturing off from - */ - void setCaptureStream (pa_stream* stream); - - uint8_t audio_buffer [WAVE_BUFFER_SIZE] = {0x80}; - uint8_t audio_buffer_tmp [WAVE_BUFFER_SIZE] = {0x80}; - uint8_t audio_fft [WAVE_BUFFER_SIZE] = {0}; - size_t currentWritePointer = 0; - bool fullframeReady = false; - private: pa_mainloop* m_mainloop; pa_mainloop_api* m_mainloopApi; pa_context* m_context; - pa_stream* m_captureStream; + SPulseAudioData m_captureData; - float fft_destination64 [64]; - float fft_destination32 [32]; - float fft_destination16 [16]; + float m_audioFFTbuffer [WAVE_BUFFER_SIZE] = {0.0f}; + kiss_fft_cpx m_FFTinfo [WAVE_BUFFER_SIZE / 2 + 1] = {0}; + float m_FFTdestination64 [64] = {0}; + float m_FFTdestination32 [32] = {0}; + float m_FFTdestination16 [16] = {0}; }; } // namespace WallpaperEngine::Audio::Drivers::Recorders diff --git a/src/WallpaperEngine/Core/CObject.cpp b/src/WallpaperEngine/Core/CObject.cpp index 817ca74..83efacd 100644 --- a/src/WallpaperEngine/Core/CObject.cpp +++ b/src/WallpaperEngine/Core/CObject.cpp @@ -1,5 +1,6 @@ #include "CObject.h" -#include "common.h" + +#include #include "WallpaperEngine/Core/CProject.h" #include "WallpaperEngine/Core/Objects/CImage.h" @@ -7,56 +8,65 @@ #include "WallpaperEngine/Core/Objects/CSound.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" #include "WallpaperEngine/Core/Wallpapers/CScene.h" -#include #include "WallpaperEngine/Assets/CContainer.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Core::UserSettings; -CObject::CObject (CScene* scene, CUserSettingBoolean* visible, int id, std::string name, std::string type, - CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles) : - m_scene (scene), +CObject::CObject ( + std::shared_ptr project, const CUserSettingBoolean* visible, int id, std::string name, + const CUserSettingVector3* origin, const CUserSettingVector3* scale, const CUserSettingVector3* angles, + std::vector dependencies +) : m_visible (visible), m_id (id), - m_name (std::move (name)), - m_type (std::move (type)), + m_name (std::move(name)), m_origin (origin), m_scale (scale), - m_angles (angles) {} + m_angles (angles), + m_project (project), + m_dependencies (std::move(dependencies)) {} -CObject* CObject::fromJSON (json data, CScene* scene, CContainer* container) { - std::string json = data.dump (); +const CObject* CObject::fromJSON ( + const json& data, std::shared_ptr project, const std::shared_ptr& container +) { + const auto id = jsonFindRequired (data, "id", "Objects must have id"); + const auto visible = jsonFindUserConfig (data, *project, "visible", true); + const auto origin = jsonFindUserConfig (data, *project, "origin", {0, 0, 0}); + const auto scale = jsonFindUserConfig (data, *project, "scale", {1, 1, 1}); + const auto angles_val = jsonFindUserConfig (data, *project, "angles", glm::vec3 (0, 0, 0)); + const auto name = jsonFindRequired (data, "name", "Objects must have name"); + const auto effects_it = data.find ("effects"); + const auto dependencies_it = data.find ("dependencies"); - auto id_it = jsonFindRequired (data, "id", "Objects must have id"); - auto visible = jsonFindUserConfig (data, "visible", true); - auto origin = jsonFindUserConfig (data, "origin", {0, 0, 0}); - auto scale = jsonFindUserConfig (data, "scale", {1, 1, 1}); - auto angles_val = jsonFindDefault (data, "angles", "0.0 0.0 0.0"); - auto name_it = jsonFindRequired (data, "name", "Objects must have name"); - auto effects_it = data.find ("effects"); - auto dependencies_it = data.find ("dependencies"); + const auto image_it = data.find ("image"); + const auto sound_it = data.find ("sound"); + const auto particle_it = data.find ("particle"); + const auto text_it = data.find ("text"); + const auto light_it = data.find ("light"); - auto image_it = data.find ("image"); - auto sound_it = data.find ("sound"); - auto particle_it = data.find ("particle"); - auto text_it = data.find ("text"); - auto light_it = data.find ("light"); + std::vector dependencies; + std::vector effects; - CObject* object; + const CObject* object; + + if (dependencies_it != data.end () && dependencies_it->is_array ()) + for (const auto& cur : *dependencies_it) + dependencies.push_back (cur); if (image_it != data.end () && !image_it->is_null ()) { - object = Objects::CImage::fromJSON (scene, data, container, visible, *id_it, *name_it, origin, scale, - WallpaperEngine::Core::aToVector3 (angles_val)); + object = Objects::CImage::fromJSON ( + project, data, container, visible, id, name, origin, scale, angles_val, effects_it, dependencies); } else if (sound_it != data.end () && !sound_it->is_null ()) { - object = Objects::CSound::fromJSON (scene, data, visible, *id_it, *name_it, origin, scale, - WallpaperEngine::Core::aToVector3 (angles_val)); + object = Objects::CSound::fromJSON (project, data, visible, id, name, origin, scale, angles_val, dependencies); } else if (particle_it != data.end () && !particle_it->is_null ()) { /// TODO: XXXHACK -- TO REMOVE WHEN PARTICLE SUPPORT IS PROPERLY IMPLEMENTED try { - object = Objects::CParticle::fromFile (scene, particle_it->get (), container, visible, *id_it, - *name_it, origin, scale); + object = Objects::CParticle::fromFile ( + project, particle_it->get (), container, visible, id, name, origin, angles_val, scale, dependencies); } catch (std::runtime_error&) { return nullptr; } @@ -67,68 +77,40 @@ CObject* CObject::fromJSON (json data, CScene* scene, CContainer* container) { /// TODO: XXXHACK -- TO REMOVE WHEN LIGHT SUPPORT IS IMPLEMENTED return nullptr; } else { - sLog.exception ("Unknown object type detected: ", *name_it); + sLog.exception ("Unknown object type detected: ", name); } - if (effects_it != data.end () && effects_it->is_array ()) { - for (auto& cur : *effects_it) { - auto effectVisible = jsonFindUserConfig (cur, "visible", true); - - if (!effectVisible->processValue (scene->getProject ().getProperties ())) - continue; - - object->insertEffect (Objects::CEffect::fromJSON (cur, effectVisible, object, container)); - } - } - - if (dependencies_it != data.end () && dependencies_it->is_array ()) - for (const auto& cur : *dependencies_it) - object->insertDependency (cur); - return object; } -glm::vec3 CObject::getOrigin () const { - return this->m_origin->processValue (this->getScene ()->getProject ().getProperties ()); +const glm::vec3& CObject::getOrigin () const { + return this->m_origin->getVec3 (); } -glm::vec3 CObject::getScale () const { - return this->m_scale->processValue (this->getScene ()->getProject ().getProperties ()); +const glm::vec3& CObject::getScale () const { + return this->m_scale->getVec3 (); } const glm::vec3& CObject::getAngles () const { - return this->m_angles; + return this->m_angles->getVec3 (); } const std::string& CObject::getName () const { return this->m_name; } -const std::vector& CObject::getEffects () const { - return this->m_effects; -} - const std::vector& CObject::getDependencies () const { return this->m_dependencies; } bool CObject::isVisible () const { - // TODO: cache this - return this->m_visible->processValue (this->getScene ()->getProject ().getProperties ()); + return this->m_visible->getBool (); } -CScene* CObject::getScene () const { - return this->m_scene; +std::shared_ptr CObject::getProject () const { + return this->m_project; } int CObject::getId () const { return this->m_id; } - -void CObject::insertEffect (Objects::CEffect* effect) { - this->m_effects.push_back (effect); -} - -void CObject::insertDependency (int dependency) { - this->m_dependencies.push_back (dependency); -} \ No newline at end of file diff --git a/src/WallpaperEngine/Core/CObject.h b/src/WallpaperEngine/Core/CObject.h index 4269cf3..c0102ef 100644 --- a/src/WallpaperEngine/Core/CObject.h +++ b/src/WallpaperEngine/Core/CObject.h @@ -8,7 +8,7 @@ #include "WallpaperEngine/Core/UserSettings/CUserSettingFloat.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingVector3.h" -namespace WallpaperEngine::Core { +namespace WallpaperEngine::Core::Wallpapers { class CScene; } @@ -26,57 +26,61 @@ using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Core::UserSettings; class CObject { - friend class CScene; + friend class Wallpapers::CScene; public: - static CObject* fromJSON (json data, CScene* scene, CContainer* container); + static const CObject* fromJSON ( const json& data, std::shared_ptr project, + const std::shared_ptr& container); - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); } - [[nodiscard]] const std::vector& getEffects () const; [[nodiscard]] const std::vector& getDependencies () const; [[nodiscard]] int getId () const; - [[nodiscard]] glm::vec3 getOrigin () const; - [[nodiscard]] glm::vec3 getScale () const; + [[nodiscard]] const glm::vec3& getOrigin () const; + [[nodiscard]] const glm::vec3& getScale () const; [[nodiscard]] const glm::vec3& getAngles () const; [[nodiscard]] const std::string& getName () const; [[nodiscard]] bool isVisible () const; - [[nodiscard]] CScene* getScene () const; + [[nodiscard]] std::shared_ptr getProject () const; protected: - CObject (CScene* scene, CUserSettingBoolean* visible, int id, std::string name, std::string type, - CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles); + CObject ( + std::shared_ptr scene, const CUserSettingBoolean* visible, int id, std::string name, + const CUserSettingVector3* origin, const CUserSettingVector3* scale, const CUserSettingVector3* angles, + std::vector dependencies); - void insertEffect (Objects::CEffect* effect); - void insertDependency (int dependency); + virtual ~CObject () = default; private: - std::string m_type; + const CUserSettingBoolean* m_visible; + int m_id = 0; + const std::string m_name; + const CUserSettingVector3* m_origin; + const CUserSettingVector3* m_scale; + const CUserSettingVector3* m_angles; - CUserSettingBoolean* m_visible; - int m_id; - std::string m_name; - CUserSettingVector3* m_origin; - CUserSettingVector3* m_scale; - glm::vec3 m_angles; + const std::vector m_dependencies; - std::vector m_effects; - std::vector m_dependencies; - - CScene* m_scene; + const std::shared_ptr m_project; }; } // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/CProject.cpp b/src/WallpaperEngine/Core/CProject.cpp index 5c4dd37..3760f42 100644 --- a/src/WallpaperEngine/Core/CProject.cpp +++ b/src/WallpaperEngine/Core/CProject.cpp @@ -1,69 +1,95 @@ -#include "common.h" #include -#include + +#include #include "CProject.h" #include "WallpaperEngine/Core/Wallpapers/CScene.h" #include "WallpaperEngine/Core/Wallpapers/CVideo.h" #include "WallpaperEngine/Core/Wallpapers/CWeb.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core; +using namespace WallpaperEngine::Core::Wallpapers; using namespace WallpaperEngine::Assets; -CProject::CProject (std::string title, std::string type, CContainer* container) : - m_title (std::move (title)), - m_type (std::move (type)), - m_wallpaper (nullptr), - m_container (container) {} +static int backgroundId = -1; -CProject* CProject::fromFile (const std::string& filename, CContainer* container) { - json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)); +CProject::CProject ( + std::string title, std::string type, std::string workshopid, std::shared_ptr container, + bool supportsaudioprocessing, const std::map>& properties +) : + m_workshopid(std::move(workshopid)), + m_title (std::move(title)), + m_type (std::move(type)), + m_container (std::move(container)), + m_properties (properties), + m_supportsaudioprocessing (supportsaudioprocessing) {} - std::string dependency = jsonFindDefault (content, "dependency", "No dependency"); - if (dependency == "No dependency") { - std::string title = *jsonFindRequired (content, "title", "Project title missing"); - std::string type = *jsonFindRequired (content, "type", "Project type missing"); - std::string file = *jsonFindRequired (content, "file", "Project's main file missing"); - auto general = content.find ("general"); - CWallpaper* wallpaper; +std::shared_ptr CProject::fromFile (const std::string& filename, std::shared_ptr container) { + json content = json::parse (container->readFileAsString (filename)); - std::transform (type.begin (), type.end (), type.begin (), tolower); + const auto dependency = jsonFindDefault (content, "dependency", "No dependency"); - CProject* project = new CProject (title, type, container); - - if (type == "scene") - wallpaper = CScene::fromFile (file, *project, container); - else if (type == "video") - wallpaper = new CVideo (file.c_str (), *project); - else if (type == "web") - wallpaper = new CWeb (file.c_str (), *project); - else - sLog.exception ("Unsupported wallpaper type: ", type); - - project->setWallpaper (wallpaper); - - if (general != content.end ()) { - const auto properties = general->find ("properties"); - - if (properties != general->end ()) { - for (const auto& cur : properties->items ()) { - Projects::CProperty* property = Projects::CProperty::fromJSON (cur.value (), cur.key ()); - if (property != nullptr) - project->insertProperty (property); - } - } - } - return project; - } else { + if (dependency != "No dependency") { sLog.exception ("Project have dependency. They are not supported, quiting"); } + + // workshopid is not required, but we have to use it for some identification stuff, + // so using a static, decreasing number should be enough + bool supportsaudioprocessing = false; + auto type = jsonFindRequired (content, "type", "Project type missing"); + const auto file = jsonFindRequired (content, "file", "Project's main file missing"); + auto general = content.find ("general"); + std::shared_ptr wallpaper = nullptr; + std::map> properties; + + std::transform (type.begin (), type.end (), type.begin (), tolower); + + if (general != content.end ()) { + supportsaudioprocessing = jsonFindDefault (general, "supportsaudioprocessing", false); + const auto properties_it = general->find ("properties"); + + if (properties_it != general->end ()) { + for (const auto& cur : properties_it->items ()) { + auto property = Projects::CProperty::fromJSON (cur.value (), cur.key ()); + + if (property == nullptr) { + continue; + } + + properties.emplace (property->getName (), std::move (property)); + } + } + } + + std::shared_ptr project = std::make_shared ( + jsonFindRequired (content, "title", "Project title missing"), + type, + jsonFindDefault (content, "workshopid", std::to_string (backgroundId--)), + container, + supportsaudioprocessing, + properties + ); + + if (type == "scene") + wallpaper = CScene::fromFile (file, project, container); + else if (type == "video") + wallpaper = std::make_shared (file, project); + else if (type == "web") + wallpaper = std::make_shared (file, project); + else + sLog.exception ("Unsupported wallpaper type: ", type); + + project->setWallpaper (wallpaper); + + return project; } -void CProject::setWallpaper (CWallpaper* wallpaper) { +void CProject::setWallpaper (std::shared_ptr wallpaper) { this->m_wallpaper = wallpaper; } -CWallpaper* CProject::getWallpaper () const { +const std::shared_ptr CProject::getWallpaper () const { return this->m_wallpaper; } @@ -75,14 +101,18 @@ const std::string& CProject::getType () const { return this->m_type; } -const std::vector& CProject::getProperties () const { +const std::map>& CProject::getProperties () const { return this->m_properties; } -CContainer* CProject::getContainer () { +const std::string& CProject::getWorkshopId () const { + return this->m_workshopid; +} + +std::shared_ptr CProject::getContainer () const { return this->m_container; } -void CProject::insertProperty (Projects::CProperty* property) { - this->m_properties.push_back (property); +bool CProject::supportsAudioProcessing () const { + return this->m_supportsaudioprocessing; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/CProject.h b/src/WallpaperEngine/Core/CProject.h index 7f48677..18c0a5f 100644 --- a/src/WallpaperEngine/Core/CProject.h +++ b/src/WallpaperEngine/Core/CProject.h @@ -1,11 +1,18 @@ #pragma once +#include +#include + #include "CWallpaper.h" #include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/Projects/CProperty.h" #include "WallpaperEngine/Assets/CContainer.h" +namespace WallpaperEngine::Core::Projects { +class CProperty; +} + namespace WallpaperEngine::Core { using json = nlohmann::json; using namespace WallpaperEngine::Assets; @@ -14,28 +21,33 @@ class CWallpaper; class CProject { public: - static CProject* fromFile (const std::string& filename, CContainer* container); + CProject ( + std::string title, std::string type, std::string workshopid, std::shared_ptr container, + bool supportsaudioprocessing, const std::map>& properties); - CWallpaper* getWallpaper () const; + static std::shared_ptr fromFile (const std::string& filename, std::shared_ptr container); - const std::string& getTitle () const; - const std::string& getType () const; - const std::vector& getProperties () const; + [[nodiscard]] const std::shared_ptr getWallpaper () const; + [[nodiscard]] const std::string& getTitle () const; + [[nodiscard]] const std::string& getType () const; + [[nodiscard]] const std::map>& getProperties () const; + [[nodiscard]] const std::string& getWorkshopId () const; - CContainer* getContainer (); + [[nodiscard]] bool supportsAudioProcessing () const; + + [[nodiscard]] std::shared_ptr getContainer () const; protected: - CProject (std::string title, std::string type, CContainer* container); - - void setWallpaper (CWallpaper* wallpaper); - void insertProperty (Projects::CProperty* property); + void setWallpaper (std::shared_ptr wallpaper); private: - std::vector m_properties; + std::map> m_properties; - std::string m_title; - std::string m_type; - CWallpaper* m_wallpaper; - CContainer* m_container; + const std::string m_workshopid; + const std::string m_title; + const std::string m_type; + const bool m_supportsaudioprocessing; + std::shared_ptr m_wallpaper = nullptr; + std::shared_ptr m_container = nullptr; }; } // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/CWallpaper.cpp b/src/WallpaperEngine/Core/CWallpaper.cpp index 055fbcb..a403787 100644 --- a/src/WallpaperEngine/Core/CWallpaper.cpp +++ b/src/WallpaperEngine/Core/CWallpaper.cpp @@ -4,8 +4,9 @@ using namespace WallpaperEngine::Core; -CWallpaper::CWallpaper (std::string type, CProject& project) : m_type (std::move (type)), m_project (project) {} +CWallpaper::CWallpaper (std::shared_ptr project) : + m_project (project) {} -CProject& CWallpaper::getProject () const { +std::shared_ptr CWallpaper::getProject () const { return this->m_project; } diff --git a/src/WallpaperEngine/Core/CWallpaper.h b/src/WallpaperEngine/Core/CWallpaper.h index 5b81a00..a2a78d2 100644 --- a/src/WallpaperEngine/Core/CWallpaper.h +++ b/src/WallpaperEngine/Core/CWallpaper.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include "CProject.h" @@ -9,30 +10,35 @@ class CProject; class CWallpaper { public: - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid(*this) == typeid(T); } - CWallpaper (std::string type, CProject& project); - - CProject& getProject () const; + std::shared_ptr getProject () const; protected: friend class CProject; - private: - CProject& m_project; + explicit CWallpaper (std::shared_ptr project); + virtual ~CWallpaper() = default; - std::string m_type; + private: + std::shared_ptr m_project; }; } // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/Core.cpp b/src/WallpaperEngine/Core/Core.cpp index 250fd98..176dc99 100644 --- a/src/WallpaperEngine/Core/Core.cpp +++ b/src/WallpaperEngine/Core/Core.cpp @@ -1,10 +1,9 @@ -#include "common.h" - #include "Core.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingFloat.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingVector3.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine; using namespace WallpaperEngine::Core::UserSettings; @@ -45,6 +44,42 @@ glm::vec2 Core::aToVector2 (const char* str) { return {x, y}; } +glm::ivec4 Core::aToVector4i (const char* str) { + int x = strtol (str, const_cast (&str), 10); + while (*str == ' ') + str++; + int y = strtol (str, const_cast (&str), 10); + while (*str == ' ') + str++; + int z = strtol (str, const_cast (&str), 10); + while (*str == ' ') + str++; + int w = strtol (str, const_cast (&str), 10); + + return {x, y, z, w}; +} + +glm::ivec3 Core::aToVector3i (const char* str) { + int x = strtol (str, const_cast (&str), 10); + while (*str == ' ') + str++; + int y = strtol (str, const_cast (&str), 10); + while (*str == ' ') + str++; + int z = strtol (str, const_cast (&str), 10); + + return {x, y, z}; +} + +glm::ivec2 Core::aToVector2i (const char* str) { + int x = strtol (str, const_cast (&str), 10); + while (*str == ' ') + str++; + int y = strtol (str, const_cast (&str), 10); + + return {x, y}; +} + glm::vec4 Core::aToVector4 (const std::string& str) { return Core::aToVector4 (str.c_str ()); } @@ -57,6 +92,18 @@ glm::vec2 Core::aToVector2 (const std::string& str) { return Core::aToVector2 (str.c_str ()); } +glm::ivec4 Core::aToVector4i (const std::string& str) { + return Core::aToVector4i (str.c_str ()); +} + +glm::ivec3 Core::aToVector3i (const std::string& str) { + return Core::aToVector3i (str.c_str ()); +} + +glm::ivec2 Core::aToVector2i (const std::string& str) { + return Core::aToVector2i (str.c_str ()); +} + glm::vec3 Core::aToColorf (const char* str) { float r = strtof (str, const_cast (&str)); while (*str == ' ') @@ -89,17 +136,200 @@ glm::ivec3 Core::aToColori (const std::string& str) { return aToColori (str.c_str ()); } -nlohmann::json::iterator Core::jsonFindRequired (nlohmann::json& data, const char* key, const char* notFoundMsg) { - auto value = data.find (key); +template bool typeCheck (const nlohmann::json::const_iterator& value) { + if (value->type () == nlohmann::detail::value_t::null) { + return false; + } - if (value == data.end ()) - sLog.exception ("Cannot find required key (", key, ") in json: ", notFoundMsg); + // type checks + if constexpr ((std::is_same_v || std::is_same_v) ) { + if (value->type () != nlohmann::detail::value_t::number_float && + value->type () != nlohmann::detail::value_t::number_integer && + value->type () != nlohmann::detail::value_t::number_unsigned) { + return false; + } + } else if constexpr (std::is_same_v) { + if (value->type () != nlohmann::detail::value_t::string) { + return false; + } + } else if constexpr (std::is_same_v) { + if (value->type () != nlohmann::detail::value_t::boolean) { + return false; + } + } else if constexpr ( + std::is_same_v || std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v) { + if (value->type () != nlohmann::detail::value_t::string) { + return false; + } + } - return value; + return true; } -nlohmann::json::iterator Core::jsonFindRequired (const nlohmann::json::iterator& data, const char* key, - const char* notFoundMsg) { +template const T Core::jsonFindRequired ( + const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg +) { + const auto iterator = jsonFindRequired (data, key, notFoundMsg); + + // vector types need of special handling + if constexpr (std::is_same_v) { + // std::strings are special, type checking doesn't need to happen, we just want the string representation + // of whatever is in there + if (iterator->is_number_integer ()) { + return std::to_string (iterator->get ()); + } else if (iterator->is_number_float ()) { + return std::to_string (iterator->get ()); + } else if (iterator->is_boolean()) { + return std::to_string (iterator->get ()); + } else if (iterator->is_null ()) { + return "null"; + } else if (iterator->is_string ()) { + return *iterator; + } + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector4 (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector3 (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector2 (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector4i (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector3i (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector2i (*iterator); + } else if (typeCheck (iterator)) { + return *iterator; + } + + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), ": ", notFoundMsg); +} + +template const bool Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const std::string Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const int16_t Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const uint16_t Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const int32_t Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const uint32_t Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const int64_t Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const uint64_t Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const float Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const double Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const glm::vec4 Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const glm::vec3 Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const glm::vec2 Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const glm::ivec4 Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const glm::ivec3 Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const glm::ivec2 Core::jsonFindRequired (const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); + +template const T Core::jsonFindRequired ( + const nlohmann::json& data, const char* key, const char* notFoundMsg +) { + const auto iterator = jsonFindRequired (data, key, notFoundMsg); + + // vector types need of special handling + if constexpr (std::is_same_v) { + // std::strings are special, type checking doesn't need to happen, we just want the string representation + // of whatever is in there + if (iterator->is_number_integer ()) { + return std::to_string (iterator->get ()); + } else if (iterator->is_number_float ()) { + return std::to_string (iterator->get ()); + } else if (iterator->is_boolean()) { + return std::to_string (iterator->get ()); + } else if (iterator->is_null ()) { + return "null"; + } else if (iterator->is_string ()) { + return *iterator; + } + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector4 (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector3 (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector2 (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector4i (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector3i (*iterator); + } else if constexpr (std::is_same_v) { + if (!typeCheck (iterator)) { + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), " expected vector-like-string", ": ", notFoundMsg); + } + + return aToVector2i (*iterator); + } else if (typeCheck (iterator)) { + return *iterator; + } + + sLog.exception ("key value doesn't match expected type. Got ", iterator->type_name(), ": ", notFoundMsg); +} + +template const bool Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const std::string Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const int16_t Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const uint16_t Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const int32_t Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const uint32_t Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const int64_t Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const uint64_t Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const float Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const double Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const glm::vec4 Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const glm::vec3 Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const glm::vec2 Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const glm::ivec4 Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const glm::ivec3 Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const glm::ivec2 Core::jsonFindRequired (const nlohmann::json& data, const char* key, const char* notFoundMsg); + +nlohmann::json::const_iterator Core::jsonFindRequired ( + const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg +) { auto value = data->find (key); if (value == data->end ()) @@ -108,57 +338,204 @@ nlohmann::json::iterator Core::jsonFindRequired (const nlohmann::json::iterator& return value; } -template T Core::jsonFindDefault (nlohmann::json& data, const char* key, T defaultValue) { +nlohmann::json::const_iterator Core::jsonFindRequired ( + const nlohmann::json& data, const char* key, const char* notFoundMsg +) { + auto value = data.find (key); + + if (value == data.end ()) + sLog.exception ("Cannot find required key (", key, ") in json: ", notFoundMsg); + + return value; +} + +template const T Core::jsonFindDefault ( + const nlohmann::json::const_iterator& data, const char* key, const T defaultValue +) { + const auto value = data->find (key); + + if (value == data->end () || value->type () == nlohmann::detail::value_t::null) + return defaultValue; + + // vector types need of special handling + if constexpr (std::is_same_v) { + // std::strings are special, type checking doesn't need to happen, we just want the string representation + // of whatever is in there + if (value->is_number_integer ()) { + return std::to_string (value->get ()); + } else if (value->is_number_float ()) { + return std::to_string (value->get ()); + } else if (value->is_boolean()) { + return std::to_string (value->get ()); + } else if (value->is_null ()) { + return "null"; + } else if (value->is_string ()) { + return *value; + } + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector4 (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector3 (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector2 (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector4i (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector3i (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector2i (*value); + } else if (typeCheck (value)) { + return *value; + } + + return defaultValue; +} + +template const bool Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const bool defaultValue); +template const std::string Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const std::string defaultValue); +template const int16_t Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const int16_t defaultValue); +template const uint16_t Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const uint16_t defaultValue); +template const int32_t Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const int32_t defaultValue); +template const uint32_t Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const uint32_t defaultValue); +template const int64_t Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const int64_t defaultValue); +template const uint64_t Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const uint64_t defaultValue); +template const float Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const float defaultValue); +template const double Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const double defaultValue); +template const glm::vec2 Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const glm::vec2 defaultValue); +template const glm::vec3 Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const glm::vec3 defaultValue); +template const glm::vec4 Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const glm::vec4 defaultValue); +template const glm::ivec2 Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const glm::ivec2 defaultValue); +template const glm::ivec3 Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const glm::ivec3 defaultValue); +template const glm::ivec4 Core::jsonFindDefault (const nlohmann::json::const_iterator& data, const char* key, const glm::ivec4 defaultValue); + +template const T Core::jsonFindDefault ( + const nlohmann::json& data, const char* key, const T defaultValue +) { const auto value = data.find (key); if (value == data.end () || value->type () == nlohmann::detail::value_t::null) return defaultValue; - // type checks - if ((std::is_same_v || std::is_same_v) ) { - if (value->type () != nlohmann::detail::value_t::number_float && - value->type () != nlohmann::detail::value_t::number_integer && - value->type () != nlohmann::detail::value_t::number_unsigned) { - sLog.error (key, " is not of type double or integer, returning default value"); + // vector types need of special handling + if constexpr (std::is_same_v) { + if (!typeCheck (value)) { return defaultValue; } - } else if (std::is_same_v && value->type () != nlohmann::detail::value_t::string) { - sLog.error (key, " is not of type string, returning default value"); - return defaultValue; - } else if (std::is_same_v && value->type () != nlohmann::detail::value_t::boolean) { - sLog.error (key, " is not of type boolean, returning default value"); - return defaultValue; + + return aToVector4 (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector3 (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector2 (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector4i (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector3i (*value); + } else if constexpr (std::is_same_v) { + if (!typeCheck (value)) { + return defaultValue; + } + + return aToVector2i (*value); + } else if (typeCheck (value)) { + return *value; } - // TODO: SUPPORT INTEGERS AND OTHER TYPES - - return *value; + return defaultValue; } -template bool Core::jsonFindDefault (nlohmann::json& data, const char* key, bool defaultValue); -template std::string Core::jsonFindDefault (nlohmann::json& data, const char* key, std::string defaultValue); -template int16_t Core::jsonFindDefault (nlohmann::json& data, const char* key, int16_t defaultValue); -template uint16_t Core::jsonFindDefault (nlohmann::json& data, const char* key, uint16_t defaultValue); -template int32_t Core::jsonFindDefault (nlohmann::json& data, const char* key, int32_t defaultValue); -template uint32_t Core::jsonFindDefault (nlohmann::json& data, const char* key, uint32_t defaultValue); -template int64_t Core::jsonFindDefault (nlohmann::json& data, const char* key, int64_t defaultValue); -template uint64_t Core::jsonFindDefault (nlohmann::json& data, const char* key, uint64_t defaultValue); -template float Core::jsonFindDefault (nlohmann::json& data, const char* key, float defaultValue); -template double Core::jsonFindDefault (nlohmann::json& data, const char* key, double defaultValue); +template const bool Core::jsonFindDefault (const nlohmann::json& data, const char* key, const bool defaultValue); +template const std::string Core::jsonFindDefault (const nlohmann::json& data, const char* key, const std::string defaultValue); +template const int16_t Core::jsonFindDefault (const nlohmann::json& data, const char* key, const int16_t defaultValue); +template const uint16_t Core::jsonFindDefault (const nlohmann::json& data, const char* key, const uint16_t defaultValue); +template const int32_t Core::jsonFindDefault (const nlohmann::json& data, const char* key, const int32_t defaultValue); +template const uint32_t Core::jsonFindDefault (const nlohmann::json& data, const char* key, const uint32_t defaultValue); +template const int64_t Core::jsonFindDefault (const nlohmann::json& data, const char* key, const int64_t defaultValue); +template const uint64_t Core::jsonFindDefault (const nlohmann::json& data, const char* key, const uint64_t defaultValue); +template const float Core::jsonFindDefault (const nlohmann::json& data, const char* key, const float defaultValue); +template const double Core::jsonFindDefault (const nlohmann::json& data, const char* key, const double defaultValue); +template const glm::vec2 Core::jsonFindDefault (const nlohmann::json& data, const char* key, const glm::vec2 defaultValue); +template const glm::vec3 Core::jsonFindDefault (const nlohmann::json& data, const char* key, const glm::vec3 defaultValue); +template const glm::vec4 Core::jsonFindDefault (const nlohmann::json& data, const char* key, const glm::vec4 defaultValue); +template const glm::ivec2 Core::jsonFindDefault (const nlohmann::json& data, const char* key, const glm::ivec2 defaultValue); +template const glm::ivec3 Core::jsonFindDefault (const nlohmann::json& data, const char* key, const glm::ivec3 defaultValue); +template const glm::ivec4 Core::jsonFindDefault (const nlohmann::json& data, const char* key, const glm::ivec4 defaultValue); -template -T* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, typename T::data_type defaultValue) { +template const T* Core::jsonFindUserConfig ( + const nlohmann::json::const_iterator& data, const CProject& project, const char* key, typename T::data_type defaultValue +) { + const auto it = data->find (key); + + if (it == data->end () || it->type () == nlohmann::detail::value_t::null) + return T::fromScalar (defaultValue); + + return T::fromJSON (*it, project); +} + +template const CUserSettingBoolean* Core::jsonFindUserConfig ( + const nlohmann::json::const_iterator& data, const CProject& project, const char* key, + CUserSettingBoolean::data_type defaultValue); +template const CUserSettingVector3* Core::jsonFindUserConfig ( + const nlohmann::json::const_iterator& data, const CProject& project, const char* key, + CUserSettingVector3::data_type defaultValue); +template const CUserSettingFloat* Core::jsonFindUserConfig ( + const nlohmann::json::const_iterator& data, const CProject& project, const char* key, + CUserSettingFloat::data_type defaultValue); + +template const T* Core::jsonFindUserConfig ( + const nlohmann::json& data, const CProject& project, const char* key, typename T::data_type defaultValue +) { const auto it = data.find (key); if (it == data.end () || it->type () == nlohmann::detail::value_t::null) return T::fromScalar (defaultValue); - return T::fromJSON (*it); + return T::fromJSON (*it, project); } -template CUserSettingBoolean* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, - CUserSettingBoolean::data_type defaultValue); -template CUserSettingVector3* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, - CUserSettingVector3::data_type defaultValue); -template CUserSettingFloat* Core::jsonFindUserConfig (nlohmann::json& data, const char* key, - CUserSettingFloat::data_type defaultValue); \ No newline at end of file +template const CUserSettingBoolean* Core::jsonFindUserConfig ( + const nlohmann::json& data, const CProject& project, const char* key, CUserSettingBoolean::data_type defaultValue); +template const CUserSettingVector3* Core::jsonFindUserConfig ( + const nlohmann::json& data, const CProject& project, const char* key, CUserSettingVector3::data_type defaultValue); +template const CUserSettingFloat* Core::jsonFindUserConfig ( + const nlohmann::json& data, const CProject& project, const char* key, CUserSettingFloat::data_type defaultValue); diff --git a/src/WallpaperEngine/Core/Core.h b/src/WallpaperEngine/Core/Core.h index e0c9689..0dc9bab 100644 --- a/src/WallpaperEngine/Core/Core.h +++ b/src/WallpaperEngine/Core/Core.h @@ -1,5 +1,6 @@ #pragma once +#include "CProject.h" #include #include #include @@ -7,6 +8,8 @@ #include namespace WallpaperEngine::Core { +class CProject; + glm::vec4 aToVector4 (const char* str); glm::vec3 aToVector3 (const char* str); glm::vec2 aToVector2 (const char* str); @@ -15,15 +18,34 @@ glm::vec4 aToVector4 (const std::string& str); glm::vec3 aToVector3 (const std::string& str); glm::vec2 aToVector2 (const std::string& str); +glm::ivec4 aToVector4i (const char* str); +glm::ivec3 aToVector3i (const char* str); +glm::ivec2 aToVector2i (const char* str); + +glm::ivec4 aToVector4i (const std::string& str); +glm::ivec3 aToVector3i (const std::string& str); +glm::ivec2 aToVector2i (const std::string& str); + glm::vec3 aToColorf (const char* str); glm::vec3 aToColorf (const std::string& str); glm::ivec3 aToColori (const char* str); glm::ivec3 aToColori (const std::string& str); -nlohmann::json::iterator jsonFindRequired (nlohmann::json& data, const char* key, const char* notFoundMsg); -nlohmann::json::iterator jsonFindRequired (const nlohmann::json::iterator& data, const char* key, - const char* notFoundMsg); -template T jsonFindDefault (nlohmann::json& data, const char* key, T defaultValue); -template T* jsonFindUserConfig (nlohmann::json& data, const char* key, typename T::data_type defaultValue); +template const T jsonFindRequired ( + const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +template const T jsonFindRequired ( + const nlohmann::json& data, const char* key, const char* notFoundMsg); +nlohmann::json::const_iterator jsonFindRequired ( + const nlohmann::json::const_iterator& data, const char* key, const char* notFoundMsg); +nlohmann::json::const_iterator jsonFindRequired ( + const nlohmann::json& data, const char* key, const char* notFoundMsg); +template const T jsonFindDefault ( + const nlohmann::json::const_iterator& data, const char* key, const T defaultValue); +template const T jsonFindDefault ( + const nlohmann::json& data, const char* key, const T defaultValue); +template const T* jsonFindUserConfig ( + const nlohmann::json::const_iterator& data, const CProject& project, const char* key, typename T::data_type defaultValue); +template const T* jsonFindUserConfig ( + const nlohmann::json& data, const CProject& project, const char* key, typename T::data_type defaultValue); } // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/DynamicValues/CDynamicValue.cpp b/src/WallpaperEngine/Core/DynamicValues/CDynamicValue.cpp new file mode 100644 index 0000000..2353c1e --- /dev/null +++ b/src/WallpaperEngine/Core/DynamicValues/CDynamicValue.cpp @@ -0,0 +1,205 @@ +#include +#include "CDynamicValue.h" + +using namespace WallpaperEngine::Core::DynamicValues; + +CDynamicValue::~CDynamicValue() { + for (auto* connection : this->m_incomingConnections) { + connection->destroyOutgoingConnection (this); + } +} + +void CDynamicValue::update(float newValue) { + this->m_ivec4 = glm::ivec4(static_cast (newValue)); + this->m_ivec3 = glm::ivec3(static_cast (newValue)); + this->m_ivec2 = glm::ivec2(static_cast (newValue)); + this->m_vec4 = glm::vec4(newValue); + this->m_vec3 = glm::vec3(newValue); + this->m_vec2 = glm::vec2(newValue); + this->m_float = newValue; + this->m_int = static_cast (newValue); + this->m_bool = static_cast (newValue) != 0; + + this->propagate (); +} + +void CDynamicValue::update(int newValue) { + this->m_ivec4 = glm::ivec4(newValue); + this->m_ivec3 = glm::ivec3(newValue); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec4 = glm::vec4(static_cast (newValue)); + this->m_vec3 = glm::vec3(static_cast (newValue)); + this->m_vec2 = glm::vec2(static_cast (newValue)); + this->m_float = static_cast (newValue); + this->m_int = newValue; + this->m_bool = newValue != 0; + + this->propagate (); +} + +void CDynamicValue::update(bool newValue) { + this->m_ivec4 = glm::ivec4(newValue); + this->m_ivec3 = glm::ivec3(newValue); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec4 = glm::vec4(newValue); + this->m_vec3 = glm::vec3(newValue); + this->m_vec2 = glm::vec2(newValue); + this->m_float = newValue; + this->m_int = newValue; + this->m_bool = newValue; + + this->propagate (); +} + +void CDynamicValue::update(const glm::vec2& newValue) { + this->m_ivec4 = glm::ivec4(newValue, 0, 0); + this->m_ivec3 = glm::ivec3(newValue, 0); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec2 = newValue; + this->m_vec3 = glm::vec3(newValue, 0.0f); + this->m_vec4 = glm::vec4(newValue, 0.0f, 0.0f); + this->m_float = newValue.x; + this->m_int = static_cast (newValue.x); + this->m_bool = newValue.x != 0.0f; + + this->propagate (); +} + +void CDynamicValue::update(const glm::vec3& newValue) { + this->m_ivec4 = glm::ivec4(newValue, 0); + this->m_ivec3 = glm::ivec3(newValue); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec2 = glm::vec2(newValue); + this->m_vec3 = newValue; + this->m_vec4 = glm::vec4(newValue, 0.0f); + this->m_float = newValue.x; + this->m_int = static_cast (newValue.x); + this->m_bool = newValue.x != 0.0f; + + this->propagate (); +} + +void CDynamicValue::update(const glm::vec4& newValue) { + this->m_ivec4 = glm::ivec4(newValue); + this->m_ivec3 = glm::ivec3(newValue); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec2 = glm::vec2(newValue); + this->m_vec3 = glm::vec3(newValue); + this->m_vec4 = newValue; + this->m_float = newValue.x; + this->m_int = static_cast (newValue.x); + this->m_bool = newValue.x != 0.0f; + + this->propagate (); +} + +void CDynamicValue::update(const glm::ivec2& newValue) { + this->m_ivec4 = glm::ivec4(newValue, 0, 0); + this->m_ivec3 = glm::ivec3(newValue, 0); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec2 = newValue; + this->m_vec3 = glm::vec3(newValue, 0.0f); + this->m_vec4 = glm::vec4(newValue, 0.0f, 0.0f); + this->m_float = static_cast (newValue.x); + this->m_int = static_cast (newValue.x); + this->m_bool = newValue.x != 0; + + this->propagate (); +} + +void CDynamicValue::update(const glm::ivec3& newValue) { + this->m_ivec4 = glm::ivec4(newValue, 0); + this->m_ivec3 = glm::ivec3(newValue); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec2 = glm::vec2(newValue); + this->m_vec3 = newValue; + this->m_vec4 = glm::vec4(newValue, 0.0f); + this->m_float = static_cast (newValue.x); + this->m_int = static_cast (newValue.x); + this->m_bool = newValue.x != 0; + + this->propagate (); +} + +void CDynamicValue::update(const glm::ivec4& newValue) { + this->m_ivec4 = glm::ivec4(newValue); + this->m_ivec3 = glm::ivec3(newValue); + this->m_ivec2 = glm::ivec2(newValue); + this->m_vec2 = glm::vec2(newValue); + this->m_vec3 = glm::vec3(newValue); + this->m_vec4 = newValue; + this->m_float = static_cast (newValue.x); + this->m_int = static_cast (newValue.x); + this->m_bool = newValue.x != 0; + + this->propagate (); +} + +void CDynamicValue::connectOutgoing (CDynamicValue* value) const { + this->m_outgoingConnections.push_back (value); + + // ensure that new connection has the right value + this->propagate (); + // ensure the other value keeps track of our connection too + value->connectIncoming (this); +} + +void CDynamicValue::connectIncoming (const CDynamicValue* value) const { + this->m_incomingConnections.push_back (value); +} + +void CDynamicValue::destroyOutgoingConnection (CDynamicValue* value) const { + this->m_outgoingConnections.erase ( + std::remove (this->m_outgoingConnections.begin (), this->m_outgoingConnections.end (), value), this->m_outgoingConnections.end () + ); +} + +void CDynamicValue::propagate () const { + for (auto* cur : this->m_outgoingConnections) { + cur->m_bool = this->m_bool; + cur->m_int = this->m_int; + cur->m_float = this->m_float; + cur->m_ivec2 = this->m_ivec2; + cur->m_ivec3 = this->m_ivec3; + cur->m_ivec4 = this->m_ivec4; + cur->m_vec2 = this->m_vec2; + cur->m_vec3 = this->m_vec3; + cur->m_vec4 = this->m_vec4; + } +} + +const glm::ivec4& CDynamicValue::getIVec4 () const { + return this->m_ivec4; +} + +const glm::ivec3& CDynamicValue::getIVec3 () const { + return this->m_ivec3; +} + +const glm::ivec2& CDynamicValue::getIVec2 () const { + return this->m_ivec2; +} + +const glm::vec4& CDynamicValue::getVec4 () const { + return this->m_vec4; +} + +const glm::vec3& CDynamicValue::getVec3 () const { + return this->m_vec3; +} + +const glm::vec2& CDynamicValue::getVec2 () const { + return this->m_vec2; +} + +const float& CDynamicValue::getFloat () const { + return this->m_float; +} + +const int& CDynamicValue::getInt () const { + return this->m_int; +} + +const bool& CDynamicValue::getBool () const { + return this->m_bool; +} \ No newline at end of file diff --git a/src/WallpaperEngine/Core/DynamicValues/CDynamicValue.h b/src/WallpaperEngine/Core/DynamicValues/CDynamicValue.h new file mode 100644 index 0000000..c971283 --- /dev/null +++ b/src/WallpaperEngine/Core/DynamicValues/CDynamicValue.h @@ -0,0 +1,68 @@ +#pragma once + +#include +#include +#include +#include + +namespace WallpaperEngine::Core::DynamicValues { +class CDynamicValue { + public: + virtual ~CDynamicValue (); + + [[nodiscard]] const glm::ivec4& getIVec4 () const; + [[nodiscard]] const glm::ivec3& getIVec3 () const; + [[nodiscard]] const glm::ivec2& getIVec2 () const; + [[nodiscard]] const glm::vec4& getVec4 () const; + [[nodiscard]] const glm::vec3& getVec3 () const; + [[nodiscard]] const glm::vec2& getVec2 () const; + [[nodiscard]] const float& getFloat () const; + [[nodiscard]] const int& getInt () const; + [[nodiscard]] const bool& getBool () const; + + /** + * Connects the current instance to the given instance, updating it's values + * based on current instance's changes + * + * @param value + */ + void connectOutgoing (CDynamicValue* value) const; + + protected: + void update (float newValue); + void update (int newValue); + void update (bool newValue); + void update (const glm::vec2& newValue); + void update (const glm::vec3& newValue); + void update (const glm::vec4& newValue); + void update (const glm::ivec2& newValue); + void update (const glm::ivec3& newValue); + void update (const glm::ivec4& newValue); + /** + * Registers an incoming connection (another CDynamicValue affecting the current instance's value) + * Useful mainly for destroying the connection on delete + * + * @param value + */ + void connectIncoming (const CDynamicValue* value) const; + void destroyOutgoingConnection (CDynamicValue* value) const; + /** + * Propagates the current value to all it's connections + */ + virtual void propagate () const; + + private: + mutable std::vector m_outgoingConnections = {}; + mutable std::vector m_incomingConnections = {}; + // different values that we will be casted to automagically + glm::ivec4 m_ivec4 = {}; + glm::ivec3 m_ivec3 = {}; + glm::ivec2 m_ivec2 = {}; + glm::vec4 m_vec4 = {}; + glm::vec3 m_vec3 = {}; + glm::vec2 m_vec2 = {}; + float m_float = 0.0f; + int m_int = 0; + bool m_bool = false; +}; +}; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/CEffect.cpp b/src/WallpaperEngine/Core/Objects/CEffect.cpp index 4e820f9..7d2c482 100644 --- a/src/WallpaperEngine/Core/Objects/CEffect.cpp +++ b/src/WallpaperEngine/Core/Objects/CEffect.cpp @@ -1,230 +1,319 @@ #include "CEffect.h" -#include "common.h" -#include #include #include "WallpaperEngine/Core/CProject.h" #include "WallpaperEngine/Core/Objects/CImage.h" +#include "WallpaperEngine/Core/Objects/Images/Materials/CPass.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h" -#include "WallpaperEngine/Core/Wallpapers/CScene.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" - -#include "WallpaperEngine/FileSystem/FileSystem.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine; using namespace WallpaperEngine::Core::Objects; using namespace WallpaperEngine::Core::UserSettings; -CEffect::CEffect (std::string name, std::string description, std::string group, std::string preview, CObject* object, - CUserSettingBoolean* visible) : - m_name (std::move (name)), - m_description (std::move (description)), - m_group (std::move (group)), - m_preview (std::move (preview)), - m_object (object), - m_visible (visible) {} +CEffect::CEffect ( + std::string name, std::string description, std::string group, std::string preview, + std::shared_ptr project, const CUserSettingBoolean* visible, + std::vector dependencies, std::vector fbos, + std::vector materials +) : + m_name (std::move(name)), + m_description (std::move(description)), + m_group (std::move(group)), + m_preview (std::move(preview)), + m_visible (visible), + m_dependencies (std::move(dependencies)), + m_fbos (std::move(fbos)), + m_project (project), + m_materials (std::move(materials)) {} -CEffect* CEffect::fromJSON (json data, CUserSettingBoolean* visible, CObject* object, CContainer* container) { - auto file_it = jsonFindRequired (data, "file", "Object effect must have a file"); - auto effectpasses_it = data.find ("passes"); +const CEffect* CEffect::fromJSON ( + const json& data, const CUserSettingBoolean* visible, std::shared_ptr project, + const Images::CMaterial* material, const std::shared_ptr& container +) { + const auto file = jsonFindRequired (data, "file", "Object effect must have a file"); + const auto effectpasses_it = data.find ("passes"); - json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (file_it->get (), container)); + json content = json::parse (container->readFileAsString(file)); - auto name_it = jsonFindRequired (content, "name", "Effect must have a name"); - auto description = jsonFindDefault (content, "description", ""); - auto group_it = jsonFindRequired (content, "group", "Effect must have a group"); - auto preview = jsonFindDefault (content, "preview", ""); - auto passes_it = jsonFindRequired (content, "passes", "Effect must have a pass list"); - auto dependencies_it = jsonFindRequired (content, "dependencies", ""); - auto fbos_it = content.find ("fbos"); + const auto effectName = jsonFindRequired (content, "name", "Effect must have a name"); + const auto passes_it = jsonFindRequired (content, "passes", "Effect must have a pass list"); + const auto fbos_it = content.find ("fbos"); - auto* effect = new CEffect (*name_it, description, *group_it, preview, object, visible); - - CEffect::materialsFromJSON (passes_it, effect, container); - CEffect::dependencyFromJSON (dependencies_it, effect); + // info to override in the pass information, used by material generation + std::map overrides; + std::vector fbos; if (fbos_it != content.end ()) - CEffect::fbosFromJSON (fbos_it, effect); + fbos = CEffect::fbosFromJSON (fbos_it); if (effectpasses_it != data.end ()) { - auto cur = effectpasses_it->begin (); - auto end = effectpasses_it->end (); - - for (int passNumber = 0; cur != end; ++cur, passNumber++) { - auto constants_it = cur->find ("constantshadervalues"); - auto combos_it = cur->find ("combos"); - auto textures_it = cur->find ("textures"); - - if (constants_it == cur->end () && combos_it == cur->end () && textures_it == cur->end ()) - continue; - - Images::CMaterial* material = effect->getMaterials ().at (passNumber); - - for (const auto& passCur : material->getPasses ()) { - if (textures_it != cur->end ()) { - std::vector::size_type textureNumber = 0; - - for (const auto& texturesCur : (*textures_it)) { - std::string texture; - - if (texturesCur.is_null ()) { - if (textureNumber == 0) { - auto* image = object->as (); - - auto passTextures = (*image->getMaterial ()->getPasses ().begin ())->getTextures (); - - if (passTextures.empty ()) { - // TODO: SET CHECKERBOARD TEXTURE AS DEFAULT IN THESE SITUATIONS - texture = ""; - } else { - texture = *passTextures.begin (); - } - } else { - texture = ""; - } - } else { - texture = texturesCur; - } - - const auto& passTextures = passCur->getTextures (); - - if (textureNumber < passTextures.size ()) - passCur->setTexture (textureNumber, texture); - else - passCur->insertTexture (texture); - - textureNumber++; - } - } - - if (combos_it != cur->end ()) { - CEffect::combosFromJSON (combos_it, passCur); - } - - if (constants_it != cur->end ()) { - CEffect::constantsFromJSON (constants_it, passCur); - } - } - } + overrides = overridesFromJSON (effectpasses_it, material, project); } - return effect; + return new CEffect ( + effectName, + jsonFindDefault (content, "description", ""), + jsonFindRequired (content, "group", "Effect must have a group"), + jsonFindDefault (content, "preview", ""), + project, + visible, + dependenciesFromJSON (jsonFindRequired (content, "dependencies", "")), + fbos, + materialsFromJSON (passes_it, effectName, container, overrides) + ); } -void CEffect::combosFromJSON (const json::const_iterator& combos_it, Core::Objects::Images::Materials::CPass* pass) { - for (const auto& cur : combos_it->items ()) - pass->insertCombo (cur.key (), cur.value ()); +std::map CEffect::combosFromJSON (const json::const_iterator& combos_it) { + std::map combos; + + for (const auto& cur : combos_it->items ()) { + auto uppercase = std::string (cur.key ()); + + std::transform (uppercase.begin (), uppercase.end (), uppercase.begin (), ::toupper); + combos.emplace (uppercase, cur.value ()); + } + + return combos; } -void CEffect::constantsFromJSON (const json::const_iterator& constants_it, - Core::Objects::Images::Materials::CPass* pass) { +std::map CEffect::constantsFromJSON ( + const json::const_iterator& constants_it, std::shared_ptr project +) { + std::map constants; + for (auto& cur : constants_it->items ()) { auto val = cur.value (); - Effects::Constants::CShaderConstant* constant; + Effects::Constants::CShaderConstant* constant = nullptr; // if the constant is an object, that means the constant has some extra information // for the UI, take the value, which is what we need - // TODO: SUPPORT USER SETTINGS HERE if (cur.value ().is_object ()) { + auto user = cur.value ().find ("user"); auto it = cur.value ().find ("value"); - if (it == cur.value ().end ()) { - sLog.error ("Found object for shader constant without \"value\" member"); + if (user == cur.value ().end () && it == cur.value ().end ()) { + sLog.error (R"(Found object for shader constant without "value" and "user" setting)"); continue; } - val = it.value (); + if (user != cur.value ().end () && user->is_string ()) { + // look for a property with the correct name + const auto& properties = project->getProperties (); + const auto property = properties.find (*user); + + if (property != properties.end ()) { + constant = new Effects::Constants::CShaderConstantProperty (property->second); + } else { + sLog.error ("Shader constant pointing to non-existant project property: ", user->get ()); + val = it.value (); + } + } else { + val = it.value (); + } } - if (val.is_number_float ()) { - constant = new Effects::Constants::CShaderConstantFloat (val.get ()); - } else if (val.is_number_integer ()) { - constant = new Effects::Constants::CShaderConstantInteger (val.get ()); - } else if (val.is_string ()) { - // try a vector 4 first, then a vector3 and then a vector 2 - constant = new Effects::Constants::CShaderConstantVector4 (WallpaperEngine::Core::aToVector4 (val)); - } else { - sLog.exception ("unknown shader constant type ", val); + // TODO: REFACTOR THIS SO IT'S NOT SO DEEP INTO THE FUNCTION + if (constant == nullptr) { + if (val.is_number_float ()) { + constant = new Effects::Constants::CShaderConstantFloat (val.get ()); + } else if (val.is_number_integer ()) { + constant = new Effects::Constants::CShaderConstantInteger (val.get ()); + } else if (val.is_string ()) { + // count the amount of spaces to determine which type of vector we have + std::string value = val; + + size_t spaces = + std::count_if (value.begin (), value.end (), [&] (const auto& item) { return item == ' '; }); + + if (spaces == 1) { + constant = + new Effects::Constants::CShaderConstantVector2 (WallpaperEngine::Core::aToVector2 (value)); + } else if (spaces == 2) { + constant = + new Effects::Constants::CShaderConstantVector3 (WallpaperEngine::Core::aToVector3 (value)); + } else if (spaces == 3) { + constant = + new Effects::Constants::CShaderConstantVector4 (WallpaperEngine::Core::aToVector4 (value)); + } else { + sLog.exception ("unknown shader constant type ", value); + } + } else { + sLog.exception ("unknown shader constant type ", val); + } } - pass->insertConstant (cur.key (), constant); + constants.emplace (cur.key (), constant); } + + return constants; } -void CEffect::fbosFromJSON (const json::const_iterator& fbos_it, CEffect* effect) { +std::vector CEffect::fbosFromJSON (const json::const_iterator& fbos_it) { + std::vector fbos; + for (const auto& cur : (*fbos_it)) - effect->insertFBO (Effects::CFBO::fromJSON (cur)); + fbos.push_back (Effects::CFBO::fromJSON (cur)); + + return fbos; } -void CEffect::dependencyFromJSON (const json::const_iterator& dependencies_it, CEffect* effect) { +std::vector CEffect::dependenciesFromJSON (const json::const_iterator& dependencies_it) { + std::vector dependencies; + for (const auto& cur : (*dependencies_it)) - effect->insertDependency (cur); + dependencies.push_back (cur); + + return dependencies; } -void CEffect::materialsFromJSON (const json::const_iterator& passes_it, CEffect* effect, CContainer* container) { +std::vector CEffect::materialsFromJSON ( + const json::const_iterator& passes_it, const std::string& name, const std::shared_ptr& container, + std::map overrides +) { + std::vector materials; + + int materialNumber = -1; for (const auto& cur : (*passes_it)) { - auto materialfile = cur.find ("material"); - auto target = cur.find ("target"); - auto bind = cur.find ("bind"); + ++materialNumber; + const auto materialfile = cur.find ("material"); + const auto target_it = cur.find ("target"); + const auto bind_it = cur.find ("bind"); + const auto command_it = cur.find ("command"); + const auto compose_it = cur.find ("compose"); + const Images::CMaterial* material = nullptr; - if (materialfile == cur.end ()) - sLog.exception ("Found an effect ", effect->m_name, " without material"); - - Images::CMaterial* material; - - if (target == cur.end ()) - material = Images::CMaterial::fromFile (materialfile->get (), container); - else - material = Images::CMaterial::fromFile (materialfile->get (), *target, container); - - if (bind != cur.end ()) { - for (const auto& bindCur : (*bind)) - material->insertTextureBind (Effects::CBind::fromJSON (bindCur)); + if (compose_it != cur.end ()) { + sLog.error ("Composing materials is not supported yet..."); } - effect->insertMaterial (material); + if (materialfile != cur.end ()) { + std::map textureBindings; + + if (bind_it != cur.end ()) { + for (const auto& bindCur : (*bind_it)) { + const auto* bind = Effects::CBind::fromJSON (bindCur); + textureBindings.emplace (bind->getIndex (), bind); + } + } + + const Images::CMaterial::OverrideInfo* overrideInfo = nullptr; + const auto overrideIt = overrides.find (materialNumber); + + if (overrideIt != overrides.end ()) { + overrideInfo = &overrideIt->second; + } + + if (target_it == cur.end ()) { + material = Images::CMaterial::fromFile ( + materialfile->get (), container, false, textureBindings, overrideInfo); + } else { + material = Images::CMaterial::fromFile ( + materialfile->get (), *target_it, container, false, textureBindings, overrideInfo); + } + } else if (command_it != cur.end ()) { + material = Images::CMaterial::fromCommand (cur); + } else { + sLog.exception ("Material without command nor material file: ", name, " (", materialNumber,")"); + } + + materials.push_back (material); } + + return materials; +} + +std::map CEffect::overridesFromJSON ( + const json::const_iterator& passes_it, const Images::CMaterial* material, + std::shared_ptr project +) { + std::map result; + + int materialNumber = -1; + for (const auto& cur : (*passes_it)) { + ++materialNumber; + auto constants_it = cur.find ("constantshadervalues"); + auto combos_it = cur.find ("combos"); + auto textures_it = cur.find ("textures"); + Images::CMaterial::OverrideInfo override; + int textureNumber = -1; + + if (combos_it != cur.end ()) { + override.combos = CEffect::combosFromJSON (combos_it); + } + + if (constants_it != cur.end ()) { + override.constants = CEffect::constantsFromJSON (constants_it, project); + } + + if (textures_it != cur.end ()) { + // TODO: MAYBE CHANGE THIS TO BE SOMEWHERE ELSE? THIS IS REALLY MODIFYING THE DATA + // BUT IT'S USEFUL TO HAVE TO SIMPLIFY RENDERING CODE + for (const auto& texture : (*textures_it)) { + ++textureNumber; + std::string name; + + if (texture.is_null () && textureNumber > 0) { + continue; + } + + if (textureNumber == 0) { + auto passTextures = (*material->getPasses ().begin ())->getTextures (); + + if (passTextures.empty()) { + continue; + } else { + name = passTextures.begin ()->second; + } + } else { + name = texture; + } + + override.textures.emplace (textureNumber, name); + } + } + + result.emplace (materialNumber, override); + } + + return result; } const std::vector& CEffect::getDependencies () const { return this->m_dependencies; } -const std::vector& CEffect::getMaterials () const { +const std::vector& CEffect::getMaterials () const { return this->m_materials; } -const std::vector& CEffect::getFbos () const { +const std::vector& CEffect::getFbos () const { return this->m_fbos; } -bool CEffect::isVisible () const { - return this->m_visible->processValue (this->m_object->getScene ()->getProject ().getProperties ()); +const Core::CProject& CEffect::getProject () const { + return *this->m_project; } -Effects::CFBO* CEffect::findFBO (const std::string& name) { +bool CEffect::isVisible () const { + return this->m_visible->getBool (); +} + +const Effects::CFBO* CEffect::findFBO (const std::string& name) { for (const auto& cur : this->m_fbos) if (cur->getName () == name) return cur; sLog.exception ("cannot find fbo ", name); } - -void CEffect::insertDependency (const std::string& dep) { - this->m_dependencies.push_back (dep); -} - -void CEffect::insertMaterial (Images::CMaterial* material) { - this->m_materials.push_back (material); -} - -void CEffect::insertFBO (Effects::CFBO* fbo) { - this->m_fbos.push_back (fbo); -} \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/CEffect.h b/src/WallpaperEngine/Core/Objects/CEffect.h index e9210ff..602ec56 100644 --- a/src/WallpaperEngine/Core/Objects/CEffect.h +++ b/src/WallpaperEngine/Core/Objects/CEffect.h @@ -9,6 +9,7 @@ namespace WallpaperEngine::Core { class CObject; +class CProject; } namespace WallpaperEngine::Core::UserSettings { @@ -25,11 +26,15 @@ using namespace WallpaperEngine::Core::UserSettings; */ class CEffect { public: - CEffect (std::string name, std::string description, std::string group, std::string preview, CObject* object, - CUserSettingBoolean* visible); + CEffect ( + std::string name, std::string description, std::string group, std::string preview, + std::shared_ptr , const CUserSettingBoolean* visible, + std::vector dependencies, std::vector fbos, + std::vector materials); - static CEffect* fromJSON (json data, UserSettings::CUserSettingBoolean* visible, CObject* object, - CContainer* container); + static const CEffect* fromJSON ( + const json& data, const CUserSettingBoolean* visible, std::shared_ptr project, + const Images::CMaterial* material, const std::shared_ptr& container); /** * @return List of dependencies for the effect to work @@ -38,15 +43,19 @@ class CEffect { /** * @return List of materials the effect applies */ - [[nodiscard]] const std::vector& getMaterials () const; + [[nodiscard]] const std::vector& getMaterials () const; /** * @return The list of FBOs to be used for this effect */ - [[nodiscard]] const std::vector& getFbos () const; + [[nodiscard]] const std::vector& getFbos () const; /** * @return If the effect is visible or not */ [[nodiscard]] bool isVisible () const; + /** + * @return The project this effect is part of + */ + [[nodiscard]] const CProject& getProject () const; /** * Searches the FBOs list for the given FBO * @@ -54,39 +63,40 @@ class CEffect { * * @return */ - Effects::CFBO* findFBO (const std::string& name); + const Effects::CFBO* findFBO (const std::string& name); protected: - static void constantsFromJSON (const json::const_iterator& constants_it, - Core::Objects::Images::Materials::CPass* pass); - static void combosFromJSON (const json::const_iterator& combos_it, Core::Objects::Images::Materials::CPass* pass); - static void fbosFromJSON (const json::const_iterator& fbos_it, CEffect* effect); - static void dependencyFromJSON (const json::const_iterator& dependencies_it, CEffect* effect); - static void materialsFromJSON (const json::const_iterator& passes_it, CEffect* effect, CContainer* container); - - void insertDependency (const std::string& dep); - void insertMaterial (Images::CMaterial* material); - void insertFBO (Effects::CFBO* fbo); + static std::map constantsFromJSON ( + const json::const_iterator& constants_it, std::shared_ptr project); + static std::map combosFromJSON (const json::const_iterator& combos_it); + static std::vector fbosFromJSON (const json::const_iterator& fbos_it); + static std::vector dependenciesFromJSON (const json::const_iterator& dependencies_it); + static std::vector materialsFromJSON ( + const json::const_iterator& passes_it, const std::string& name, + const std::shared_ptr& container, std::map); + static std::map overridesFromJSON ( + const json::const_iterator& passes_it, const Images::CMaterial* material, + std::shared_ptr project); private: /** Effect's name */ - std::string m_name; + const std::string m_name; /** Effect's description used in the UI */ - std::string m_description; + const std::string m_description; /** Effect's group used in the UI */ - std::string m_group; + const std::string m_group; /** A project that previews the given effect, used in the UI */ - std::string m_preview; - /** The object the effect applies to */ - CObject* m_object; + const std::string m_preview; /** If the effect is visible or not */ - UserSettings::CUserSettingBoolean* m_visible; + const UserSettings::CUserSettingBoolean* m_visible; + /** Project this effect is part of */ + std::shared_ptr m_project; /** List of dependencies for the effect */ - std::vector m_dependencies; + const std::vector m_dependencies; /** List of materials the effect applies */ - std::vector m_materials; + const std::vector m_materials; /** List of FBOs required for this effect */ - std::vector m_fbos; + const std::vector m_fbos; }; } // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/CImage.cpp b/src/WallpaperEngine/Core/Objects/CImage.cpp index 36b96bd..eb6c0b1 100644 --- a/src/WallpaperEngine/Core/Objects/CImage.cpp +++ b/src/WallpaperEngine/Core/Objects/CImage.cpp @@ -1,59 +1,96 @@ #include "CImage.h" +#include + #include "WallpaperEngine/Core/Objects/Images/CMaterial.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingFloat.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingVector3.h" #include "WallpaperEngine/Core/Wallpapers/CScene.h" -#include - -#include "WallpaperEngine/FileSystem/FileSystem.h" using namespace WallpaperEngine::Core::Objects; using namespace WallpaperEngine::Core::UserSettings; -CImage::CImage (CScene* scene, Images::CMaterial* material, CUserSettingBoolean* visible, int id, std::string name, - CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles, const glm::vec2& size, - std::string alignment, CUserSettingVector3* color, CUserSettingFloat* alpha, float brightness, - uint32_t colorBlendMode, const glm::vec2& parallaxDepth, bool fullscreen, bool passthrough, - bool autosize) : - CObject (scene, visible, id, std::move (name), Type, origin, scale, angles), +CImage::CImage ( + std::shared_ptr project, const Images::CMaterial* material, + const CUserSettingBoolean* visible, int id, std::string name, const CUserSettingVector3* origin, + const CUserSettingVector3* scale, const CUserSettingVector3* angles, glm::vec2 size, std::string alignment, + const CUserSettingVector3* color, const CUserSettingFloat* alpha, float brightness, uint32_t colorBlendMode, + glm::vec2 parallaxDepth, bool fullscreen, bool passthrough, bool autosize, + std::vector effects, std::vector dependencies +) : + CObject (project, visible, id, std::move(name), origin, scale, angles, std::move(dependencies)), m_size (size), + m_parallaxDepth (parallaxDepth), m_material (material), - m_alignment (std::move (alignment)), - m_color (color), + m_alignment (std::move(alignment)), m_alpha (alpha), m_brightness (brightness), + m_color (color), m_colorBlendMode (colorBlendMode), - m_parallaxDepth (parallaxDepth), m_fullscreen (fullscreen), m_passthrough (passthrough), - m_autosize (autosize) {} + m_autosize (autosize), + m_effects (std::move(effects)) {} -WallpaperEngine::Core::CObject* CImage::fromJSON (CScene* scene, json data, CContainer* container, - CUserSettingBoolean* visible, int id, std::string name, - CUserSettingVector3* origin, CUserSettingVector3* scale, - const glm::vec3& angles) { - const auto image_it = data.find ("image"); - const auto size_val = jsonFindDefault (data, "size", "0.0 0.0"); // this one might need some adjustment - const auto alignment = jsonFindDefault (data, "alignment", "center"); - const auto alpha = jsonFindUserConfig (data, "alpha", 1.0); - const auto color = jsonFindUserConfig (data, "color", {1, 1, 1}); - const auto brightness_val = jsonFindDefault (data, "brightness", 1.0); - const auto colorBlendMode_val = jsonFindDefault (data, "colorBlendMode", 0); - const auto parallaxDepth_val = jsonFindDefault (data, "parallaxDepth", "0 0"); +const WallpaperEngine::Core::CObject* CImage::fromJSON ( + std::shared_ptr project, const json& data, const std::shared_ptr& container, + const CUserSettingBoolean* visible, int id, std::string name, const CUserSettingVector3* origin, + const CUserSettingVector3* scale, const CUserSettingVector3* angles, const json::const_iterator& effects_it, + std::vector dependencies +) { + const auto image = jsonFindRequired (data, "image", "Image must have an image"); + std::vector effects; + json content = json::parse (container->readFileAsString (image)); - json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (image_it->get (), container)); + const auto material = Images::CMaterial::fromFile ( + jsonFindRequired (content, "material", "Image must have a material"), + container, + jsonFindDefault (content, "solidlayer", false) + ); - const auto material_it = jsonFindRequired (content, "material", "Image must have a material"); - const auto fullscreen = jsonFindDefault (content, "fullscreen", false); - const auto passthrough = jsonFindDefault (content, "passthrough", false); - const auto autosize = jsonFindDefault (content, "autosize", false); + if (effects_it != data.end () && effects_it->is_array ()) { + for (auto& cur : *effects_it) { + const auto effectVisible = jsonFindUserConfig (cur, *project, "visible", true); - return new CImage (scene, Images::CMaterial::fromFile (material_it->get (), container), visible, id, - std::move (name), origin, scale, angles, WallpaperEngine::Core::aToVector2 (size_val), alignment, - color, alpha, brightness_val, colorBlendMode_val, - WallpaperEngine::Core::aToVector2 (parallaxDepth_val), fullscreen, passthrough, autosize); + // TODO: USER CANNOT MODIFY VALUES ON THE FLY, BUT IT MIGHT BE INTERESTING TO SUPPORT THAT AT SOME POINT? + // TODO: AT LEAST THE ORIGINAL SOFTWARE ALLOWS YOU TO DO THAT IN THE PREVIEW WINDOW + // TODO: THAT MIGHT INCREASE COMPLEXITY THO... + // TODO: ESPECIALLY IF THAT CHANGES RENDERING OF PASSES/IMAGES + // TODO: DECISIONS, DECISIONS, DECISIONS... + if (!effectVisible->getBool ()) + continue; + + effects.push_back ( + Objects::CEffect::fromJSON ( + cur, effectVisible, project, material, container + ) + ); + } + } + + return new CImage ( + project, + material, + visible, + id, + std::move(name), + origin, + scale, + angles, + jsonFindDefault (data, "size", glm::vec2 (0.0, 0.0)), + jsonFindDefault (data, "alignment", "center"), + jsonFindUserConfig (data, *project, "color", {1, 1, 1}), + jsonFindUserConfig (data, *project, "alpha", 1.0), + jsonFindDefault (data, "brightness", 1.0), + jsonFindDefault (data, "colorBlendMode", 0), + jsonFindDefault (data, "parallaxDepth", glm::vec2 (0.0, 0.0)), + jsonFindDefault (content, "fullscreen", false), + jsonFindDefault (content, "passthrough", false), + jsonFindDefault (content, "autosize", false), + effects, + std::move(dependencies) + ); } const Images::CMaterial* CImage::getMaterial () const { @@ -69,11 +106,11 @@ const std::string& CImage::getAlignment () const { } float CImage::getAlpha () const { - return this->m_alpha->processValue (this->getScene ()->getProject ().getProperties ()); + return this->m_alpha->getFloat (); } -glm::vec3 CImage::getColor () const { - return this->m_color->processValue (this->getScene ()->getProject ().getProperties ()); +const glm::vec3& CImage::getColor () const { + return this->m_color->getVec3 (); } float CImage::getBrightness () const { @@ -100,4 +137,6 @@ bool CImage::isAutosize () const { return this->m_autosize; } -const std::string CImage::Type = "image"; \ No newline at end of file +const std::vector& CImage::getEffects () const { + return this->m_effects; +} diff --git a/src/WallpaperEngine/Core/Objects/CImage.h b/src/WallpaperEngine/Core/Objects/CImage.h index d8e1145..f78cc4b 100644 --- a/src/WallpaperEngine/Core/Objects/CImage.h +++ b/src/WallpaperEngine/Core/Objects/CImage.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "WallpaperEngine/Core/Objects/Images/CMaterial.h" #include "WallpaperEngine/Core/CObject.h" @@ -11,7 +13,7 @@ #include "WallpaperEngine/Core/UserSettings/CUserSettingFloat.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingVector3.h" -namespace WallpaperEngine::Core { +namespace WallpaperEngine::Core::Wallpapers { class CScene; } @@ -27,9 +29,11 @@ class CImage : public CObject { friend class CObject; public: - static CObject* fromJSON (CScene* scene, json data, CContainer* container, CUserSettingBoolean* visible, - int id, std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale, - const glm::vec3& angles); + static const CObject* fromJSON ( + std::shared_ptr project, const json& data, + const std::shared_ptr& container, const CUserSettingBoolean* visible, int id, + std::string name, const CUserSettingVector3* origin, const CUserSettingVector3* scale, + const CUserSettingVector3* angles, const json::const_iterator& effects_it, std::vector dependencies); /** * @return The base material to use for the image @@ -50,7 +54,7 @@ class CImage : public CObject { /** * @return The color to use for the image */ - [[nodiscard]] glm::vec3 getColor () const; + [[nodiscard]] const glm::vec3& getColor () const; /** * @return The brightness to use for the image */ @@ -75,40 +79,44 @@ class CImage : public CObject { * @return If the image is autosized or not */ [[nodiscard]] bool isAutosize () const; + /** + * @return All of the effects applied to this image + */ + [[nodiscard]] const std::vector& getEffects () const; protected: - CImage (CScene* scene, Images::CMaterial* material, CUserSettingBoolean* visible, int id, std::string name, - CUserSettingVector3* origin, CUserSettingVector3* scale, const glm::vec3& angles, const glm::vec2& size, - std::string alignment, CUserSettingVector3* color, CUserSettingFloat* alpha, float brightness, - uint32_t colorBlendMode, const glm::vec2& parallaxDepth, bool fullscreen, bool passthrough, bool autosize); - - /** - * Type value used to differentiate the different types of objects in a background - */ - static const std::string Type; + CImage ( + std::shared_ptr project, const Images::CMaterial* material, + const CUserSettingBoolean* visible, int id, std::string name, const CUserSettingVector3* origin, + const CUserSettingVector3* scale, const CUserSettingVector3* angles, glm::vec2 size, std::string alignment, + const CUserSettingVector3* color, const CUserSettingFloat* alpha, float brightness, uint32_t colorBlendMode, + glm::vec2 parallaxDepth, bool fullscreen, bool passthrough, bool autosize, + std::vector effects, std::vector dependencies); private: /** The image's size */ - glm::vec2 m_size; + const glm::vec2 m_size; /** Parallax depth */ const glm::vec2 m_parallaxDepth; /** Base material for the image */ - Images::CMaterial* m_material; + const Images::CMaterial* m_material; /** What type of alignment to use for the image's position */ - std::string m_alignment; + const std::string m_alignment; /** The alpha value for the image */ - CUserSettingFloat* m_alpha; + const CUserSettingFloat* m_alpha; /** The brightness for the image */ float m_brightness; /** The color to use for the image */ - CUserSettingVector3* m_color; + const CUserSettingVector3* m_color; /** The color blending mode used for the image, special value for shaders */ - uint32_t m_colorBlendMode; + const uint32_t m_colorBlendMode; + /** Override for effects */ + const std::vector m_effects; /** If the image is fullscreen or not */ - bool m_fullscreen; + bool m_fullscreen = false; /** If the image is passthrough or not */ - bool m_passthrough; + bool m_passthrough = false; /** If the image's size should be automatically determined */ - bool m_autosize; + bool m_autosize = false; }; } // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/CParticle.cpp b/src/WallpaperEngine/Core/Objects/CParticle.cpp index 5bdd6ce..11ec6ba 100644 --- a/src/WallpaperEngine/Core/Objects/CParticle.cpp +++ b/src/WallpaperEngine/Core/Objects/CParticle.cpp @@ -1,62 +1,73 @@ #include "CParticle.h" -#include "WallpaperEngine/FileSystem/FileSystem.h" #include using namespace WallpaperEngine::Core::Objects; -CParticle* CParticle::fromFile (CScene* scene, const std::string& filename, CContainer* container, - CUserSettingBoolean* visible, int id, std::string name, CUserSettingVector3* origin, - CUserSettingVector3* scale) { - json data = json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)); +const CParticle* CParticle::fromFile ( + std::shared_ptr project, const std::string& filename, + const std::shared_ptr& container, const CUserSettingBoolean* visible, int id, + const std::string& name, const CUserSettingVector3* origin, const CUserSettingVector3* angles, + const CUserSettingVector3* scale, std::vector dependencies +) { + json data = json::parse (container->readFileAsString (filename)); const auto controlpoint_it = data.find ("controlpoint"); - const auto starttime_it = jsonFindRequired (data, "starttime", "Particles must have start time"); - const auto maxcount_it = jsonFindRequired (data, "maxcount", "Particles must have maximum count"); const auto emitter_it = jsonFindRequired (data, "emitter", "Particles must have emitters"); const auto initializer_it = jsonFindRequired (data, "initializer", "Particles must have initializers"); - auto* particle = new CParticle (scene, *starttime_it, *maxcount_it, visible, id, std::move (name), origin, scale); + std::vector controlpoints; + std::vector emitters; + std::vector initializers; if (controlpoint_it != data.end ()) for (const auto& cur : (*controlpoint_it)) - particle->insertControlPoint (Particles::CControlPoint::fromJSON (cur)); + controlpoints.push_back (Particles::CControlPoint::fromJSON (cur)); for (const auto& cur : (*emitter_it)) - particle->insertEmitter (Particles::CEmitter::fromJSON (cur)); + emitters.push_back (Particles::CEmitter::fromJSON (cur)); for (const auto& cur : (*initializer_it)) - particle->insertInitializer (Particles::CInitializer::fromJSON (cur)); + initializers.push_back (Particles::CInitializer::fromJSON (cur)); - return particle; + return new CParticle ( + project, + jsonFindRequired (data, "starttime", "Particles must have start time"), + jsonFindRequired (data, "maxcount", "Particles must have maximum count"), + visible, + id, + name, + origin, + scale, + angles, + controlpoints, + emitters, + initializers, + std::move(dependencies) + ); } -CParticle::CParticle (CScene* scene, uint32_t starttime, uint32_t maxcount, CUserSettingBoolean* visible, int id, - std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale) : - CObject (scene, visible, id, std::move (name), Type, origin, scale, glm::vec3 ()), +CParticle::CParticle ( + std::shared_ptr project, uint32_t starttime, uint32_t maxcount, + const CUserSettingBoolean* visible, int id, const std::string& name, const CUserSettingVector3* origin, + const CUserSettingVector3* scale, const CUserSettingVector3* angles, + const std::vector& controlpoints, + const std::vector& emitters, + const std::vector& initializers, std::vector dependencies +) : + CObject (project, visible, id, name, origin, scale, angles, std::move(dependencies)), m_starttime (starttime), - m_maxcount (maxcount) {} + m_maxcount (maxcount), + m_controlpoints (controlpoints), + m_emitters (emitters), + m_initializers (initializers) {} -const std::vector& CParticle::getEmitters () const { +const std::vector& CParticle::getEmitters () const { return this->m_emitters; } -const std::vector& CParticle::getControlPoints () const { +const std::vector& CParticle::getControlPoints () const { return this->m_controlpoints; } -const std::vector& CParticle::getInitializers () const { +const std::vector& CParticle::getInitializers () const { return this->m_initializers; } - -void CParticle::insertControlPoint (Particles::CControlPoint* controlpoint) { - this->m_controlpoints.push_back (controlpoint); -} - -void CParticle::insertEmitter (Particles::CEmitter* emitter) { - this->m_emitters.push_back (emitter); -} - -void CParticle::insertInitializer (Particles::CInitializer* initializer) { - this->m_initializers.push_back (initializer); -} - -const std::string CParticle::Type = "particle"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/CParticle.h b/src/WallpaperEngine/Core/Objects/CParticle.h index 9d288a2..687b50e 100644 --- a/src/WallpaperEngine/Core/Objects/CParticle.h +++ b/src/WallpaperEngine/Core/Objects/CParticle.h @@ -17,55 +17,44 @@ class CParticle : public CObject { friend class CObject; public: - static CParticle* fromFile (CScene* scene, const std::string& filename, CContainer* container, - CUserSettingBoolean* visible, int id, std::string name, - CUserSettingVector3* origin, CUserSettingVector3* scale); + static const CParticle* fromFile ( + std::shared_ptr project, const std::string& filename, + const std::shared_ptr& container, const CUserSettingBoolean* visible, int id, + const std::string& name, const CUserSettingVector3* origin, const CUserSettingVector3* angles, + const CUserSettingVector3* scale, std::vector dependencies); /** * @return The list of emitters for the particle system */ - [[nodiscard]] const std::vector& getEmitters () const; + [[nodiscard]] const std::vector& getEmitters () const; /** * @return The list of control points for the particle system */ - [[nodiscard]] const std::vector& getControlPoints () const; + [[nodiscard]] const std::vector& getControlPoints () const; /** * @return The list of initializers for the particle system */ - [[nodiscard]] const std::vector& getInitializers () const; + [[nodiscard]] const std::vector& getInitializers () const; protected: - CParticle (CScene* scene, uint32_t starttime, uint32_t maxcount, CUserSettingBoolean* visible, int id, - std::string name, CUserSettingVector3* origin, CUserSettingVector3* scale); - - /** - * @param controlpoint The control point to add to the particle system - */ - void insertControlPoint (Particles::CControlPoint* controlpoint); - /** - * @param emitter The emitter to add to the particle system - */ - void insertEmitter (Particles::CEmitter* emitter); - /** - * @param initializer The initializer to add to the particle system - */ - void insertInitializer (Particles::CInitializer* initializer); - - /** - * Type value used to differentiate the different types of objects in a background - */ - static const std::string Type; + CParticle ( + std::shared_ptr project, uint32_t starttime, uint32_t maxcount, + const CUserSettingBoolean* visible, int id, const std::string& name, const CUserSettingVector3* origin, + const CUserSettingVector3* scale, const CUserSettingVector3* angles, + const std::vector& controlpoints, + const std::vector& emitters, + const std::vector& initializers, std::vector dependencies); private: /** The time at which the particle system should start emitting */ - uint32_t m_starttime; + const uint32_t m_starttime; /** Maximum number of particles at the same time */ - uint32_t m_maxcount; + const uint32_t m_maxcount; /** List of control points */ - std::vector m_controlpoints; + const std::vector m_controlpoints; /** List of emitters */ - std::vector m_emitters; + const std::vector m_emitters; /** List of initializers */ - std::vector m_initializers; + const std::vector m_initializers; }; } // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/CSound.cpp b/src/WallpaperEngine/Core/Objects/CSound.cpp index e6e9238..3ca94e6 100644 --- a/src/WallpaperEngine/Core/Objects/CSound.cpp +++ b/src/WallpaperEngine/Core/Objects/CSound.cpp @@ -1,38 +1,47 @@ #include "CSound.h" + +#include #include "WallpaperEngine/Core/CObject.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core::Objects; -CSound::CSound (CScene* scene, CUserSettingBoolean* visible, int id, std::string name, CUserSettingVector3* origin, - CUserSettingVector3* scale, const glm::vec3& angles, bool repeat) : - CObject (scene, visible, id, std::move (name), Type, origin, scale, angles), - m_repeat (repeat) {} +CSound::CSound ( + std::shared_ptr project, const CUserSettingBoolean* visible, int id, std::string name, + const CUserSettingVector3* origin, const CUserSettingVector3* scale, const CUserSettingVector3* angles, + bool repeat, std::vector sounds, std::vector dependencies +) : + CObject (project, visible, id, std::move(name), origin, scale, angles, std::move(dependencies)), + m_repeat (repeat), + m_sounds (std::move(sounds)) {} -WallpaperEngine::Core::CObject* CSound::fromJSON (CScene* scene, json data, CUserSettingBoolean* visible, int id, - const std::string& name, CUserSettingVector3* origin, - CUserSettingVector3* scale, const glm::vec3& angles) { - bool repeat = false; +const WallpaperEngine::Core::CObject* CSound::fromJSON ( + std::shared_ptr project, const json& data, const CUserSettingBoolean* visible, + int id, const std::string& name, const CUserSettingVector3* origin, const CUserSettingVector3* scale, + const CUserSettingVector3* angles, std::vector dependencies +) { // TODO: PARSE AUDIO VOLUME + std::vector sounds; const auto sound_it = jsonFindRequired (data, "sound", "Sound information not present"); - const auto playbackmode = jsonFindDefault (data, "playbackmode", ""); - - if (playbackmode == "loop") - repeat = true; if (!sound_it->is_array ()) sLog.exception ("Expected sound list on element ", name); - auto* sound = new CSound (scene, visible, id, name, origin, scale, angles, repeat); - for (const auto& cur : (*sound_it)) - sound->insertSound (cur); + sounds.push_back (cur); - return sound; -} - -void CSound::insertSound (const std::string& filename) { - this->m_sounds.push_back (filename); + return new CSound ( + project, + visible, + id, + name, + origin, + scale, + angles, + jsonFindDefault (data, "playbackmode", "") == "loop", + sounds, + std::move(dependencies) + ); } const std::vector& CSound::getSounds () const { @@ -42,5 +51,3 @@ const std::vector& CSound::getSounds () const { bool CSound::isRepeat () const { return this->m_repeat; } - -const std::string CSound::Type = "sound"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/CSound.h b/src/WallpaperEngine/Core/Objects/CSound.h index 783af9f..8784788 100644 --- a/src/WallpaperEngine/Core/Objects/CSound.h +++ b/src/WallpaperEngine/Core/Objects/CSound.h @@ -4,6 +4,10 @@ #include "WallpaperEngine/Core/Core.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" +namespace WallpaperEngine::Core::Wallpapers { +class CScene; +} + namespace WallpaperEngine::Core::Objects { using json = nlohmann::json; using namespace WallpaperEngine::Core::UserSettings; @@ -15,9 +19,10 @@ class CSound : public CObject { friend class CObject; public: - static CObject* fromJSON (CScene* scene, json data, CUserSettingBoolean* visible, int id, - const std::string& name, CUserSettingVector3* origin, CUserSettingVector3* scale, - const glm::vec3& angles); + static const CObject* fromJSON ( + std::shared_ptr project, const json& data, const CUserSettingBoolean* visible, + int id, const std::string& name, const CUserSettingVector3* origin, const CUserSettingVector3* scale, + const CUserSettingVector3* angles, std::vector dependencies); /** * @return The list of sounds to play @@ -29,23 +34,15 @@ class CSound : public CObject { [[nodiscard]] bool isRepeat () const; protected: - CSound (CScene* scene, CUserSettingBoolean* visible, int id, std::string name, CUserSettingVector3* origin, - CUserSettingVector3* scale, const glm::vec3& angles, bool repeat); - - /** - * @param filename The sound to add - */ - void insertSound (const std::string& filename); - - /** - * Type value used to differentiate the different types of objects in a background - */ - static const std::string Type; + CSound ( + std::shared_ptr project, const CUserSettingBoolean* visible, int id, std::string name, + const CUserSettingVector3* origin, const CUserSettingVector3* scale, const CUserSettingVector3* angles, + bool repeat, std::vector sounds, std::vector dependencies); private: /** If the sounds should repeat or not */ - bool m_repeat; + bool m_repeat = false; /** The list of sounds to play */ - std::vector m_sounds; + std::vector m_sounds = {}; }; } // namespace WallpaperEngine::Core::Objects diff --git a/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp b/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp index 7522ff5..37ad6a9 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/CBind.cpp @@ -4,13 +4,15 @@ using namespace WallpaperEngine::Core::Objects::Effects; -CBind::CBind (std::string name, uint32_t index) : m_name (std::move (name)), m_index (index) {} +CBind::CBind (std::string name, uint32_t index) : + m_name (std::move(name)), + m_index (index) {} -CBind* CBind::fromJSON (json data) { - const auto name_it = jsonFindRequired (data, "name", "bind must have texture name"); - const auto index_it = jsonFindRequired (data, "index", "bind must have index"); - - return new CBind (*name_it, *index_it); +const CBind* CBind::fromJSON (const json& data) { + return new CBind ( + jsonFindRequired (data, "name", "bind must have texture name"), + jsonFindRequired (data, "index", "bind must have index") + ); } const std::string& CBind::getName () const { diff --git a/src/WallpaperEngine/Core/Objects/Effects/CBind.h b/src/WallpaperEngine/Core/Objects/Effects/CBind.h index f4a229d..6fd790c 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CBind.h +++ b/src/WallpaperEngine/Core/Objects/Effects/CBind.h @@ -20,9 +20,7 @@ class CBind { * @param data * @return */ - static CBind* fromJSON (json data); - - CBind (std::string name, uint32_t index); + static const CBind* fromJSON (const json& data); /** * @return The texture name, previous to use the one already specified by the object's passes @@ -33,10 +31,13 @@ class CBind { */ [[nodiscard]] const uint32_t& getIndex () const; + protected: + CBind (std::string name, uint32_t index); + private: /** The texture's name */ - std::string m_name; + const std::string m_name; /** The texture index to replace */ - uint32_t m_index; + const uint32_t m_index; }; } // namespace WallpaperEngine::Core::Objects::Effects diff --git a/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp b/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp index 65633a5..ad1c459 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/CFBO.cpp @@ -6,16 +6,16 @@ using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Objects::Effects; CFBO::CFBO (std::string name, float scale, std::string format) : - m_name (std::move (name)), + m_name (std::move(name)), m_scale (scale), - m_format (std::move (format)) {} + m_format (std::move(format)) {} -CFBO* CFBO::fromJSON (json data) { - const auto name_it = jsonFindRequired (data, "name", "Name for an FBO is required"); - const auto scale = jsonFindDefault (data, "scale", 1.0); - const auto format = jsonFindDefault (data, "format", ""); - - return new CFBO (*name_it, scale, format); +const CFBO* CFBO::fromJSON (const json& data) { + return new CFBO ( + jsonFindRequired (data, "name", "Name for an FBO is required"), + jsonFindDefault (data, "scale", 1.0), + jsonFindDefault (data, "format", "") + ); } const std::string& CFBO::getName () const { diff --git a/src/WallpaperEngine/Core/Objects/Effects/CFBO.h b/src/WallpaperEngine/Core/Objects/Effects/CFBO.h index 7e35b97..cc2e694 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/CFBO.h +++ b/src/WallpaperEngine/Core/Objects/Effects/CFBO.h @@ -15,9 +15,7 @@ using json = nlohmann::json; */ class CFBO { public: - CFBO (std::string name, float scale, std::string format); - - static CFBO* fromJSON (json data); + static const CFBO* fromJSON (const json& data); /** * @return The FBO name used to identify it in the background's files @@ -32,12 +30,15 @@ class CFBO { */ [[nodiscard]] const std::string& getFormat () const; + protected: + CFBO (std::string name, float scale, std::string format); + private: /** The name of the FBO */ - std::string m_name; + const std::string m_name; /** The scale factor of the FBO */ - float m_scale; + const float m_scale; /** The FBO's format for the render */ - std::string m_format; + const std::string m_format; }; } // namespace WallpaperEngine::Core::Objects::Effects \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp index fab60c3..2f7f343 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.cpp @@ -1,9 +1,5 @@ #include "CShaderConstant.h" +#include + using namespace WallpaperEngine::Core::Objects::Effects::Constants; - -CShaderConstant::CShaderConstant (std::string type) : m_type (std::move (type)) {} - -const std::string& CShaderConstant::getType () const { - return this->m_type; -} diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h index 7e191f2..df80be6 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h @@ -1,35 +1,40 @@ #pragma once +#include #include +#include "WallpaperEngine/Core/DynamicValues/CDynamicValue.h" namespace WallpaperEngine::Core::Objects::Effects::Constants { /** * Shader constants base class */ -class CShaderConstant { +class CShaderConstant : public DynamicValues::CDynamicValue { public: - explicit CShaderConstant (std::string type); + virtual ~CShaderConstant () = default; - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); } /** - * @return The type name of this constant + * @return String representation of the constant's value */ - [[nodiscard]] const std::string& getType () const; - - private: - std::string m_type; + [[nodiscard]] virtual std::string toString () const = 0; }; } // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp index 04b1877..43eb304 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.cpp @@ -2,10 +2,10 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantFloat::CShaderConstantFloat (float value) : CShaderConstant (Type), m_value (value) {} - -float* CShaderConstantFloat::getValue () { - return &this->m_value; +CShaderConstantFloat::CShaderConstantFloat (float value) { + this->update (value); } -const std::string CShaderConstantFloat::Type = "float"; \ No newline at end of file +std::string CShaderConstantFloat::toString () const { + return std::to_string (this->getFloat ()); +} diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h index 84be76e..6cc3eff 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h @@ -12,18 +12,6 @@ class CShaderConstantFloat : public CShaderConstant { public: explicit CShaderConstantFloat (float value); - /** - * @return A pointer to the actual value of the constant - */ - float* getValue (); - - /** - * Type string indicator - */ - static const std::string Type; - - protected: - /** The constant's value */ - float m_value; + [[nodiscard]] std::string toString () const override; }; } // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp index 7bc7b99..766d3a3 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.cpp @@ -2,10 +2,10 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantInteger::CShaderConstantInteger (int32_t value) : CShaderConstant (Type), m_value (value) {} - -int32_t* CShaderConstantInteger::getValue () { - return &this->m_value; +CShaderConstantInteger::CShaderConstantInteger (int32_t value) { + this->update (value); } -const std::string CShaderConstantInteger::Type = "int"; \ No newline at end of file +std::string CShaderConstantInteger::toString () const { + return std::to_string (this->getInt ()); +} diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h index 9101191..da70241 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h @@ -12,18 +12,6 @@ class CShaderConstantInteger : public CShaderConstant { public: explicit CShaderConstantInteger (int32_t value); - /** - * @return A pointer to the actual value of the constant - */ - int32_t* getValue (); - - /** - * Type string indicator - */ - static const std::string Type; - - protected: - /** The constant's value */ - int32_t m_value; + [[nodiscard]] std::string toString () const override; }; } // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.cpp new file mode 100644 index 0000000..18fbc99 --- /dev/null +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.cpp @@ -0,0 +1,12 @@ +#include "WallpaperEngine/Core/DynamicValues/CDynamicValue.h" +#include "CShaderConstantProperty.h" + +using namespace WallpaperEngine::Core::Objects::Effects::Constants; + +CShaderConstantProperty::CShaderConstantProperty (const std::shared_ptr & property) { + property->connectOutgoing (this); +} + +std::string CShaderConstantProperty::toString () const { + return "no string representation yet!"; +} diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.h new file mode 100644 index 0000000..2ce8c86 --- /dev/null +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.h @@ -0,0 +1,20 @@ +#pragma once + +#include "WallpaperEngine/Core/Projects/CProperty.h" + +#include "CShaderConstant.h" + +#include + +namespace WallpaperEngine::Core::Objects::Effects::Constants { +using namespace WallpaperEngine::Core::Projects; +/** + * Shader constant that comes from a property + */ +class CShaderConstantProperty : public CShaderConstant { + public: + explicit CShaderConstantProperty (const std::shared_ptr & property); + + [[nodiscard]] std::string toString () const override; +}; +} // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp index f361d80..28b7a35 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.cpp @@ -2,10 +2,17 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantVector2::CShaderConstantVector2 (glm::vec2 value) : CShaderConstant (Type), m_value (value) {} - -glm::vec2* CShaderConstantVector2::getValue () { - return &this->m_value; +CShaderConstantVector2::CShaderConstantVector2 (glm::vec2 value) { + this->update (value); } -const std::string CShaderConstantVector2::Type = "vec2"; \ No newline at end of file +std::string CShaderConstantVector2::toString () const { + std::string result = "("; + + result.append (std::to_string (this->getVec2 ().x)); + result.append (","); + result.append (std::to_string (this->getVec2 ().y)); + result.append (")"); + + return result; +} diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h index 2411825..e9d6f3a 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h @@ -14,18 +14,6 @@ class CShaderConstantVector2 : public CShaderConstant { public: explicit CShaderConstantVector2 (glm::vec2 value); - /** - * @return A pointer to the actual value of the constant - */ - glm::vec2* getValue (); - - /** - * Type string indicator - */ - static const std::string Type; - - protected: - /** The constant's value */ - glm::vec2 m_value; + [[nodiscard]] std::string toString () const override; }; } // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp index 9afa86a..b588d28 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.cpp @@ -2,10 +2,19 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantVector3::CShaderConstantVector3 (glm::vec3 value) : CShaderConstant (Type), m_value (value) {} - -glm::vec3* CShaderConstantVector3::getValue () { - return &this->m_value; +CShaderConstantVector3::CShaderConstantVector3 (glm::vec3 value) { + this->update (value); } -const std::string CShaderConstantVector3::Type = "vec3"; \ No newline at end of file +std::string CShaderConstantVector3::toString () const { + std::string result = "("; + + result.append (std::to_string (this->getVec3 ().x)); + result.append (","); + result.append (std::to_string (this->getVec3 ().y)); + result.append (","); + result.append (std::to_string (this->getVec3 ().z)); + result.append (")"); + + return result; +} diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h index 989044f..693d124 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h @@ -13,18 +13,6 @@ class CShaderConstantVector3 : public CShaderConstant { public: explicit CShaderConstantVector3 (glm::vec3 value); - /** - * @return A pointer to the actual value of the constant - */ - glm::vec3* getValue (); - - /** - * Type string indicator - */ - static const std::string Type; - - protected: - /** The constant's value */ - glm::vec3 m_value; + [[nodiscard]] std::string toString () const override; }; } // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp index 7502a95..4cf2ee1 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.cpp @@ -2,10 +2,21 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; -CShaderConstantVector4::CShaderConstantVector4 (glm::vec4 value) : CShaderConstant (Type), m_value (value) {} - -glm::vec4* CShaderConstantVector4::getValue () { - return &this->m_value; +CShaderConstantVector4::CShaderConstantVector4 (glm::vec4 value) { + this->update (value); } -const std::string CShaderConstantVector4::Type = "vec4"; \ No newline at end of file +std::string CShaderConstantVector4::toString () const { + std::string result = "("; + + result.append (std::to_string (this->getVec4 ().x)); + result.append (","); + result.append (std::to_string (this->getVec4 ().y)); + result.append (","); + result.append (std::to_string (this->getVec4 ().z)); + result.append (","); + result.append (std::to_string (this->getVec4 ().w)); + result.append (")"); + + return result; +} diff --git a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h index e9aa7e3..119662d 100644 --- a/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h +++ b/src/WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h @@ -13,18 +13,6 @@ class CShaderConstantVector4 : public CShaderConstant { public: explicit CShaderConstantVector4 (glm::vec4 value); - /** - * @return A pointer to the actual value of the constant - */ - glm::vec4* getValue (); - - /** - * Type string indicator - */ - static const std::string Type; - - protected: - /** The constant's value */ - glm::vec4 m_value; + [[nodiscard]] std::string toString () const override; }; } // namespace WallpaperEngine::Core::Objects::Effects::Constants diff --git a/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp b/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp index e76ad57..bf2eaab 100644 --- a/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp +++ b/src/WallpaperEngine/Core/Objects/Images/CMaterial.cpp @@ -1,61 +1,105 @@ #include "CMaterial.h" +#include "WallpaperEngine/Core/Objects/Images/Materials/CPass.h" +#include "WallpaperEngine/Logging/CLog.h" #include #include -#include "WallpaperEngine/FileSystem/FileSystem.h" - using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Core::Objects; using namespace WallpaperEngine::Core::Objects::Images; -CMaterial::CMaterial (std::string name) : m_name (std::move (name)) {} +CMaterial::CMaterial ( + std::string name, bool solidlayer, std::map textureBindings, + std::vector passes +) : + m_name (std::move(name)), + m_textureBindings (std::move(textureBindings)), + m_passes (std::move(passes)), + m_solidlayer (solidlayer) {} +CMaterial::CMaterial ( + std::string name, std::string target, bool solidlayer, + std::map textureBindings, std::vector passes +) : + m_name (std::move(name)), + m_target (std::move(target)), + m_textureBindings (std::move(textureBindings)), + m_passes (std::move(passes)), + m_solidlayer (solidlayer) {} -CMaterial* CMaterial::fromFile (const std::string& filename, CContainer* container) { - return fromJSON (filename, json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container))); +const CMaterial* CMaterial::fromFile ( + const std::filesystem::path& filename, const std::shared_ptr& container, bool solidlayer, + std::map textureBindings, const OverrideInfo* overrides +) { + return fromJSON (filename, json::parse (container->readFileAsString (filename)), solidlayer, std::move(textureBindings), overrides); } -CMaterial* CMaterial::fromFile (const std::string& filename, const std::string& target, CContainer* container) { - return fromJSON (filename, json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)), target); +const CMaterial* CMaterial::fromFile ( + const std::filesystem::path& filename, const std::string& target, const std::shared_ptr& container, bool solidlayer, + std::map textureBindings, const OverrideInfo* overrides +) { + return fromJSON (filename, json::parse (container->readFileAsString (filename)), target, solidlayer, std::move(textureBindings), overrides); } -CMaterial* CMaterial::fromJSON (const std::string& name, json data, const std::string& target) { - CMaterial* material = fromJSON (name, std::move (data)); - - material->setTarget (target); - - return material; -} - -CMaterial* CMaterial::fromJSON (const std::string& name, json data) { +const CMaterial* CMaterial::fromJSON ( + const std::string& name, const json& data, const std::string& target, bool solidlayer, + std::map textureBindings, const OverrideInfo* overrides +) { const auto passes_it = jsonFindRequired (data, "passes", "Material must have at least one pass"); - - auto* material = new CMaterial (name); + std::vector passes; for (const auto& cur : (*passes_it)) - material->insertPass (Materials::CPass::fromJSON (cur)); + passes.push_back (Materials::CPass::fromJSON (cur, overrides)); - return material; + return new CMaterial (name, target, solidlayer, std::move(textureBindings), passes); } -void CMaterial::insertPass (Materials::CPass* pass) { - this->m_passes.push_back (pass); +const CMaterial* CMaterial::fromJSON ( + const std::string& name, const json& data, bool solidlayer, std::map textureBindings, + const OverrideInfo* overrides +) { + const auto passes_it = jsonFindRequired (data, "passes", "Material must have at least one pass"); + std::vector passes; + + for (const auto& cur : (*passes_it)) + passes.push_back (Materials::CPass::fromJSON (cur, overrides)); + + return new CMaterial (name, solidlayer, std::move(textureBindings), passes); } -void CMaterial::insertTextureBind (Effects::CBind* bind) { - this->m_textureBindings.insert (std::make_pair (bind->getIndex (), bind)); +const CMaterial* CMaterial::fromCommand (const json& data) { + const std::string& command = jsonFindRequired (data, "command", "Command material must have a command"); + const std::string& target = jsonFindRequired (data, "target", "Command material must have a target"); + const std::string& source = jsonFindRequired (data, "source", "Command material must have a source"); + std::vector passes; + + if (command == "copy") { + passes.push_back ( + Materials::CPass::fromJSON ({ + {"blending", "normal"}, + {"cullmode", "nocull"}, + {"depthtest", "disabled"}, + {"depthwrite", "disabled"}, + {"shader", "commands/copy"}, + {"textures", json::array ({source, target})} + }, nullptr) + ); + } else if (command == "swap") { + // TODO: HOW TO IMPLEMENT THIS ONE? + sLog.exception ("Command material swap not implemented yet"); + } else { + sLog.exception ("Unknown command: ", command); + } + + return new CMaterial (command, false, {}, passes); } -void CMaterial::setTarget (const std::string& target) { - this->m_target = target; -} - -const std::vector& CMaterial::getPasses () const { +const std::vector& CMaterial::getPasses () const { return this->m_passes; } -const std::map& CMaterial::getTextureBinds () const { +const std::map& CMaterial::getTextureBinds () const { return this->m_textureBindings; } @@ -69,4 +113,8 @@ const std::string& CMaterial::getName () const { bool CMaterial::hasTarget () const { return !this->m_target.empty (); +} + +bool CMaterial::isSolidLayer () const { + return this->m_solidlayer; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Images/CMaterial.h b/src/WallpaperEngine/Core/Objects/Images/CMaterial.h index 6864e62..e1a3496 100644 --- a/src/WallpaperEngine/Core/Objects/Images/CMaterial.h +++ b/src/WallpaperEngine/Core/Objects/Images/CMaterial.h @@ -1,10 +1,14 @@ #pragma once #include "WallpaperEngine/Core/Objects/Effects/CBind.h" -#include "WallpaperEngine/Core/Objects/Images/Materials/CPass.h" #include "WallpaperEngine/Assets/CContainer.h" #include "WallpaperEngine/Core/Core.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" + +namespace WallpaperEngine::Core::Objects::Images::Materials { +class CPass; +} namespace WallpaperEngine::Core::Objects::Images { using json = nlohmann::json; @@ -15,29 +19,36 @@ using namespace WallpaperEngine::Assets; */ class CMaterial { public: - static CMaterial* fromFile (const std::string& filename, Assets::CContainer* container); - static CMaterial* fromJSON (const std::string& name, json data); - static CMaterial* fromFile (const std::string& filename, const std::string& target, Assets::CContainer* container); - static CMaterial* fromJSON (const std::string& name, json data, const std::string& target); + struct OverrideInfo { + std::map combos; + std::map constants; + std::map textures; + }; - /** - * @param pass The rendering pass to add to the material - */ - void insertPass (Materials::CPass* pass); - /** - * @param bind Texture bind override for the material - */ - void insertTextureBind (Effects::CBind* bind); + static const CMaterial* fromFile ( + const std::filesystem::path& filename, const std::shared_ptr& container, bool solidlayer = false, + std::map textureBindings = {}, const OverrideInfo* overrides = nullptr); + static const CMaterial* fromFile ( + const std::filesystem::path& filename, const std::string& target, const std::shared_ptr& container, + bool solidlayer = false, std::map textureBindings = {}, + const OverrideInfo* overrides = nullptr); + static const CMaterial* fromJSON ( + const std::string& name, const json& data, bool solidlayer = false, + std::map textureBindings = {}, const OverrideInfo* overrides = nullptr); + static const CMaterial* fromJSON ( + const std::string& name, const json& data, const std::string& target, bool solidlayer = false, + std::map textureBindings = {}, const OverrideInfo* overrides = nullptr); + static const CMaterial* fromCommand (const json& data); /** * @return All the rendering passes that happen for this material */ - [[nodiscard]] const std::vector& getPasses () const; + [[nodiscard]] const std::vector& getPasses () const; /** * @return The textures that have to be bound while rendering the material. * These act as an override of the textures specified by the parent effect */ - [[nodiscard]] const std::map& getTextureBinds () const; + [[nodiscard]] const std::map& getTextureBinds () const; /** * @return The materials destination (fbo) if required */ @@ -50,23 +61,29 @@ class CMaterial { * @return The name of the material */ [[nodiscard]] const std::string& getName () const; + /** + * @return If this material is a solidlayer or not + */ + [[nodiscard]] bool isSolidLayer () const; protected: - explicit CMaterial (std::string name); - - /** - * @param target The new target while rendering this material - */ - void setTarget (const std::string& target); + CMaterial ( + std::string name, bool solidlayer, std::map textureBindings, + std::vector passes); + CMaterial ( + std::string name, std::string target, bool solidlayer, std::map textureBindings, + std::vector passes); private: /** All the shader passes required to render this material */ - std::vector m_passes; + const std::vector m_passes; /** List of texture bind overrides to use for this material */ - std::map m_textureBindings; + const std::map m_textureBindings; /** The FBO target to render to (if any) */ - std::string m_target; + const std::string m_target; /** The material's name */ - std::string m_name; + const std::string m_name; + /** If this material is a solid layer or not */ + const bool m_solidlayer; }; } // namespace WallpaperEngine::Core::Objects::Images diff --git a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp index 6fa4902..e07c9b4 100644 --- a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp +++ b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.cpp @@ -1,5 +1,5 @@ #include "CPass.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include @@ -7,72 +7,81 @@ using namespace WallpaperEngine::Core::Objects::Effects::Constants; using namespace WallpaperEngine::Core::Objects::Images::Materials; CPass::CPass (std::string blending, std::string cullmode, std::string depthtest, std::string depthwrite, - std::string shader) : - m_blending (std::move (blending)), - m_cullmode (std::move (cullmode)), - m_depthtest (std::move (depthtest)), - m_depthwrite (std::move (depthwrite)), - m_shader (std::move (shader)) {} + std::string shader, std::map textures, std::map combos, + std::map constants) : + m_blending (std::move(blending)), + m_cullmode (std::move(cullmode)), + m_depthtest (std::move(depthtest)), + m_depthwrite (std::move(depthwrite)), + m_shader (std::move(shader)), + m_textures (std::move(textures)), + m_combos (std::move(combos)), + m_constants (std::move(constants)) {} -CPass* CPass::fromJSON (json data) { +const CPass* CPass::fromJSON (const json& data, const CMaterial::OverrideInfo* overrides) { // TODO: FIGURE OUT DEFAULT BLENDING MODE - const auto blending = jsonFindDefault (data, "blending", "normal"); - const auto cullmode = jsonFindDefault (data, "cullmode", "nocull"); - const auto depthtest_it = jsonFindRequired (data, "depthtest", "Material pass must have depthtest specified"); - const auto depthwrite_it = jsonFindRequired (data, "depthwrite", "Material pass must have depthwrite specified"); - const auto shader_it = jsonFindRequired (data, "shader", "Material pass must have shader specified"); const auto textures_it = data.find ("textures"); const auto combos_it = data.find ("combos"); + std::map textures; + std::map combos; + std::map constants; + if (textures_it != data.end ()) { // TODO: FETCH THIS FROM CImage TO MAKE IT COMPATIBLE WITH OLDER WALLPAPERS if (!textures_it->is_array ()) sLog.exception ("Material's textures must be a list"); - } - auto* pass = new CPass (blending, cullmode, *depthtest_it, *depthwrite_it, *shader_it); - - if (textures_it != data.end ()) + int textureNumber = -1; for (const auto& cur : (*textures_it)) - pass->insertTexture (cur.is_null () ? "" : cur); + textures.emplace (++textureNumber, cur.is_null () ? "" : cur); + } if (combos_it != data.end ()) { for (const auto& cur : combos_it->items ()) { - if (cur.value ().is_number_integer ()) - pass->insertCombo (cur.key (), cur.value ()); - else + if (cur.value ().is_number_integer ()) { + std::string uppercase = std::string (cur.key ()); + + std::transform (uppercase.begin (), uppercase.end (), uppercase.begin (), ::toupper); + combos.emplace (uppercase, cur.value ()); + } else { sLog.exception ("unexpected non-integer combo on pass"); + } } } - return pass; + // apply overrides + if (overrides != nullptr) { + for (const auto& [name, value] : overrides->combos) + combos[name] = value; + for (const auto& [name, value] : overrides->constants) + constants[name] = value; + for (const auto& [id, value] : overrides->textures) + textures[id] = value; + } + + return new CPass ( + jsonFindDefault (data, "blending", "normal"), + jsonFindDefault (data, "cullmode", "nocull"), + jsonFindRequired (data, "depthtest", "Material pass must have depthtest specified"), + jsonFindRequired (data, "depthwrite", "Material pass must have depthwrite specified"), + jsonFindRequired (data, "shader", "Material pass must have shader specified"), + textures, + combos, + constants + ); } -void CPass::insertTexture (const std::string& texture) { - this->m_textures.push_back (texture); -} - -void CPass::setTexture (std::vector::size_type index, const std::string& texture) { - this->m_textures.at (index) = texture; -} - -void CPass::insertCombo (const std::string& name, int value) { - std::string uppercase = std::string (name); - - std::transform (uppercase.begin (), uppercase.end (), uppercase.begin (), ::toupper); - this->m_combos.insert (std::pair (uppercase, value)); -} - -const std::vector& CPass::getTextures () const { +const std::map& CPass::getTextures () const { return this->m_textures; } -const std::map& CPass::getConstants () const { +const std::map& CPass::getConstants () const { return this->m_constants; } -std::map* CPass::getCombos () { - return &this->m_combos; +const std::map& CPass::getCombos () const { + return this->m_combos; } const std::string& CPass::getShader () const { @@ -94,11 +103,3 @@ const std::string& CPass::getDepthTest () const { const std::string& CPass::getDepthWrite () const { return this->m_depthwrite; } - -void CPass::setBlendingMode (const std::string& mode) { - this->m_blending = mode; -} - -void CPass::insertConstant (const std::string& name, CShaderConstant* constant) { - this->m_constants.insert (std::pair (name, constant)); -} \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h index bf36152..e14889a 100644 --- a/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h +++ b/src/WallpaperEngine/Core/Objects/Images/Materials/CPass.h @@ -1,13 +1,17 @@ #pragma once #include "WallpaperEngine/Core/Core.h" - +#include "WallpaperEngine/Core/Objects/Images/CMaterial.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" namespace WallpaperEngine::Core::Objects { class CEffect; } +namespace WallpaperEngine::Core::Objects::Images { +class CMaterial; +} + namespace WallpaperEngine::Core::Objects::Images::Materials { using json = nlohmann::json; @@ -18,20 +22,20 @@ class CPass { friend class WallpaperEngine::Core::Objects::CEffect; public: - static CPass* fromJSON (json data); + static const CPass* fromJSON (const json& data, const CMaterial::OverrideInfo* overrides); /** * @return The list of textures to bind while rendering */ - [[nodiscard]] const std::vector& getTextures () const; + [[nodiscard]] const std::map& getTextures () const; /** * @return Shader constants that alter how the shader should behave */ - [[nodiscard]] const std::map& getConstants () const; + [[nodiscard]] const std::map& getConstants () const; /** * @return Shader combos that alter how the shader should behave */ - [[nodiscard]] std::map* getCombos (); + [[nodiscard]] const std::map& getCombos () const; /** * @return Shader to be used while rendering the pass */ @@ -52,61 +56,29 @@ class CPass { * @return If depth write has to happen while rendering */ [[nodiscard]] const std::string& getDepthWrite () const; - /** - * @param mode The new blending mode to use - */ - void setBlendingMode (const std::string& mode); - - /** - * Add a shader combo value to the list - * - * @param name The combo name - * @param value It's value - */ - void insertCombo (const std::string& name, int value); - /** - * Adds a shader constant to the list - * - * @param name The constant's name - * @param constant It's value - */ - void insertConstant (const std::string& name, Effects::Constants::CShaderConstant* constant); protected: CPass (std::string blending, std::string cullmode, std::string depthtest, std::string depthwrite, - std::string shader); - - /** - * Adds a new texture to the list of textures to bind while rendering - * - * @param texture - */ - void insertTexture (const std::string& texture); - /** - * Updates a texture in the specified index for binding while rendering - * - * @param index - * @param texture - */ - void setTexture (std::vector::size_type index, const std::string& texture); + std::string shader, std::map textures, std::map combos, + std::map constants); private: // TODO: CREATE ENUMERATIONS FOR THESE INSTEAD OF USING STRING VALUES! /** The blending mode to use */ - std::string m_blending; + const std::string m_blending; /** The culling mode to use */ - std::string m_cullmode; + const std::string m_cullmode; /** If depthtesting has to happen while drawing */ - std::string m_depthtest; + const std::string m_depthtest; /** If depthwrite has to happen while drawing */ - std::string m_depthwrite; + const std::string m_depthwrite; /** The shader to use */ - std::string m_shader; + const std::string m_shader; /** The list of textures to use */ - std::vector m_textures; + const std::map m_textures; /** Different combo settings for shader input */ - std::map m_combos; + const std::map m_combos; /** Shader constant values to use for the shaders */ - std::map m_constants; + const std::map m_constants; }; } // namespace WallpaperEngine::Core::Objects::Images::Materials diff --git a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp index 47d55cd..586bf3a 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.cpp @@ -2,31 +2,18 @@ using namespace WallpaperEngine::Core::Objects::Particles; -CControlPoint* CControlPoint::fromJSON (json data) { - const auto flags_it = data.find ("flags"); - const auto id_it = jsonFindRequired (data, "id", "Particle's control point must have id"); - const auto offset_it = data.find ("offset"); - - auto* controlpoint = new CControlPoint (*id_it, 0); - - if (offset_it != data.end ()) - controlpoint->setOffset (WallpaperEngine::Core::aToVector3 (*offset_it)); - - if (flags_it != data.end ()) - controlpoint->setFlags (*flags_it); - - return controlpoint; +const CControlPoint* CControlPoint::fromJSON (const json& data) { + return new CControlPoint ( + jsonFindRequired (data, "id", "Particle's control point must have id"), + jsonFindDefault (data, "flags", 0), + jsonFindDefault (data, "offset", glm::vec3()) + ); } -CControlPoint::CControlPoint (uint32_t id, uint32_t flags) : m_id (id), m_flags (flags), m_offset (glm::vec3 ()) {} - -void CControlPoint::setOffset (const glm::vec3& offset) { - this->m_offset = offset; -} - -void CControlPoint::setFlags (uint32_t flags) { - this->m_flags = flags; -} +CControlPoint::CControlPoint (uint32_t id, uint32_t flags, glm::vec3 offset) : + m_id (id), + m_flags (flags), + m_offset (offset) {} uint32_t CControlPoint::getId () const { return this->m_id; diff --git a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h index b9f0725..734c714 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h +++ b/src/WallpaperEngine/Core/Objects/Particles/CControlPoint.h @@ -10,7 +10,7 @@ using json = nlohmann::json; */ class CControlPoint { public: - static CControlPoint* fromJSON (json data); + static const CControlPoint* fromJSON (const json& data); /** * @return The id of the controlpoint used for ordering purposes @@ -26,23 +26,14 @@ class CControlPoint { [[nodiscard]] uint32_t getFlags () const; protected: - explicit CControlPoint (uint32_t id, uint32_t flags = 0); - - /** - * @param offset The new offset - */ - void setOffset (const glm::vec3& offset); - /** - * @param flags The new flags - */ - void setFlags (uint32_t flags); + explicit CControlPoint (uint32_t id, uint32_t flags, glm::vec3 offset); private: /** ID used for ordering purposes */ - uint32_t m_id; + const uint32_t m_id; /** Flags that control how it behaves */ - uint32_t m_flags; + const uint32_t m_flags; /** The offset from starting position */ - glm::vec3 m_offset; + const glm::vec3 m_offset; }; } // namespace WallpaperEngine::Core::Objects::Particles diff --git a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp index 35628f7..d067c46 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.cpp @@ -1,18 +1,15 @@ #include "CEmitter.h" +#include + using namespace WallpaperEngine::Core::Objects::Particles; -CEmitter* CEmitter::fromJSON (json data) { - const auto directions_it = jsonFindRequired (data, "directions", "Particle emitter must have direction specified"); +const CEmitter* CEmitter::fromJSON (const json& data) { const auto distancemax_it = jsonFindRequired (data, "distancemax", "Particle emitter must have maximum distance"); const auto distancemin_it = jsonFindRequired (data, "distancemin", "Particle emitter must have minimum distance"); - const auto id_it = data.find ("id"); - const auto name_it = jsonFindRequired (data, "name", "Particle emitter must have a name"); - const auto origin_it = jsonFindRequired (data, "origin", "Particle emitter must have an origin"); - const auto rate_it = jsonFindRequired (data, "rate", "Particle emitter must have a rate"); - glm::vec3 distancemin = glm::vec3(0); - glm::vec3 distancemax = glm::vec3(0); + auto distancemin = glm::vec3(0); + auto distancemax = glm::vec3(0); if (distancemin_it->is_number()) { distancemin = glm::vec3(static_cast(*distancemin_it)); @@ -26,18 +23,26 @@ CEmitter* CEmitter::fromJSON (json data) { distancemax = WallpaperEngine::Core::aToVector3(*distancemax_it); } - return new CEmitter (WallpaperEngine::Core::aToVector3 (*directions_it), distancemax, distancemin, - (id_it == data.end () ? 0 : static_cast (*id_it)), *name_it, - WallpaperEngine::Core::aToVector3 (*origin_it), *rate_it); + return new CEmitter ( + jsonFindRequired (data, "directions", "Particle emitter must have direction specified"), + distancemax, + distancemin, + jsonFindDefault (data, "id", 0), + jsonFindRequired (data, "name", "Particle emitter must have a name"), + jsonFindRequired (data, "origin", "Particle emitter must have an origin"), + jsonFindRequired (data, "rate", "Particle emitter must have a rate") + ); } -CEmitter::CEmitter (const glm::vec3& directions, const glm::vec3& distancemax, const glm::vec3& distancemin, uint32_t id, - std::string name, const glm::vec3& origin, double rate) : +CEmitter::CEmitter ( + glm::vec3 directions, glm::vec3 distancemax, glm::vec3 distancemin, uint32_t id, std::string name, glm::vec3 origin, + double rate +) : m_directions (directions), m_distancemax (distancemax), m_distancemin (distancemin), m_id (id), - m_name (std::move (name)), + m_name (std::move(name)), m_origin (origin), m_rate (rate) {} diff --git a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h index ef5221e..c96cd3b 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h +++ b/src/WallpaperEngine/Core/Objects/Particles/CEmitter.h @@ -10,7 +10,7 @@ using json = nlohmann::json; */ class CEmitter { public: - static CEmitter* fromJSON (json data); + static const CEmitter* fromJSON (const json& data); /** * @return The ID of the emitter @@ -42,23 +42,24 @@ class CEmitter { [[nodiscard]] const double getRate () const; protected: - CEmitter (const glm::vec3& directions, const glm::vec3& distancemax, const glm::vec3& distancemin, uint32_t id, std::string name, - const glm::vec3& origin, double rate); + CEmitter ( + glm::vec3 directions, glm::vec3 distancemax, glm::vec3 distancemin, uint32_t id, std::string name, + glm::vec3 origin, double rate); private: /** Direction the particles should move to */ - glm::vec3 m_directions; + const glm::vec3 m_directions; /** Maximum distance before the particle is dead */ - glm::vec3 m_distancemax; + const glm::vec3 m_distancemax; /** Minimum distance before the particle is dead */ - glm::vec3 m_distancemin; + const glm::vec3 m_distancemin; /** ID of the emitter */ - uint32_t m_id; + const uint32_t m_id; /** Name of the emitter, indicates the type of emitter */ - std::string m_name; + const std::string m_name; /** The center of the emitter */ - glm::vec3 m_origin; + const glm::vec3 m_origin; /** The rate of emission */ - double m_rate; + const double m_rate; }; } // namespace WallpaperEngine::Core::Objects::Particles diff --git a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp index f7e1168..5d0be86 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.cpp @@ -1,5 +1,6 @@ #include "CInitializer.h" -#include "common.h" + +#include #include "WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h" #include "WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h" @@ -9,43 +10,45 @@ #include "WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h" #include "WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h" #include "WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core::Objects::Particles; -CInitializer* CInitializer::fromJSON (json data) { - const auto id_it = data.find ("id"); - const auto name_it = jsonFindRequired (data, "name", "Particle's initializer must have a name"); - const uint32_t id = ((id_it == data.end ()) ? 0 : static_cast (*id_it)); +const CInitializer* CInitializer::fromJSON (const json& data) { + const auto name = jsonFindRequired (data, "name", "Particle's initializer must have a name"); + const auto id = jsonFindDefault (data, "id", 0); - if (*name_it == "lifetimerandom") { + if (name == "lifetimerandom") { return Initializers::CLifeTimeRandom::fromJSON (data, id); } - if (*name_it == "sizerandom") { + if (name == "sizerandom") { return Initializers::CSizeRandom::fromJSON (data, id); } - if (*name_it == "rotationrandom") { + if (name == "rotationrandom") { return Initializers::CRotationRandom::fromJSON (data, id); } - if (*name_it == "velocityrandom") { + if (name == "velocityrandom") { return Initializers::CVelocityRandom::fromJSON (data, id); } - if (*name_it == "colorrandom") { + if (name == "colorrandom") { return Initializers::CColorRandom::fromJSON (data, id); } - if (*name_it == "alpharandom") { + if (name == "alpharandom") { return Initializers::CAlphaRandom::fromJSON (data, id); } - if (*name_it == "angularvelocityrandom") { + if (name == "angularvelocityrandom") { return Initializers::CAngularVelocityRandom::fromJSON (data, id); } - if (*name_it == "turbulentvelocityrandom") { + if (name == "turbulentvelocityrandom") { return Initializers::CTurbulentVelocityRandom::fromJSON (data, id); } - sLog.exception ("Found unknown initializer for particles: ", *name_it); + sLog.exception ("Found unknown initializer for particles: ", name); } -CInitializer::CInitializer (uint32_t id, std::string name) : m_id (id), m_name (std::move (name)) {} +CInitializer::CInitializer (uint32_t id, std::string name) : + m_id (id), + m_name (std::move(name)) {} const std::string& CInitializer::getName () const { return this->m_name; diff --git a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h index e085f6c..b3884cb 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h +++ b/src/WallpaperEngine/Core/Objects/Particles/CInitializer.h @@ -11,7 +11,27 @@ using json = nlohmann::json; */ class CInitializer { public: - static CInitializer* fromJSON (json data); + static const CInitializer* fromJSON (const json& data); + + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); + } + + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); + } + + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); + } /** * @return The name of the particle initializer, indicates what type of initialization to do @@ -25,10 +45,12 @@ class CInitializer { protected: CInitializer (uint32_t id, std::string name); + virtual ~CInitializer() = default; + private: /** ID for ordering purposes */ - uint32_t m_id; + const uint32_t m_id; /** The name of the initializer, indicates what type of initialization to do */ - std::string m_name; + const std::string m_name; }; } // namespace WallpaperEngine::Core::Objects::Particles diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp index c54ca63..2d33066 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.cpp @@ -2,17 +2,18 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CAlphaRandom* CAlphaRandom::fromJSON (json data, uint32_t id) { - const auto min_it = jsonFindRequired (data, "min", "Alpharandom initializer must have a minimum value"); - const auto max_it = jsonFindRequired (data, "max", "Alpharandom initializer must have a maximum value"); - - return new CAlphaRandom (id, *min_it, *max_it); +const CAlphaRandom* CAlphaRandom::fromJSON (const json& data, uint32_t id) { + return new CAlphaRandom ( + id, + jsonFindRequired (data, "min", "Alpharandom initializer must have a minimum value"), + jsonFindRequired (data, "max", "Alpharandom initializer must have a maximum value") + ); } CAlphaRandom::CAlphaRandom (uint32_t id, double min, double max) : CInitializer (id, "alpharandom"), - m_min (min), - m_max (max) {} + m_max (max), + m_min (min) {} double CAlphaRandom::getMinimum () const { return this->m_min; diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h index 8df942a..4c3e08b 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAlphaRandom.h @@ -21,14 +21,14 @@ class CAlphaRandom : CInitializer { protected: friend class CInitializer; - static CAlphaRandom* fromJSON (json data, uint32_t id); + static const CAlphaRandom* fromJSON (const json& data, uint32_t id); CAlphaRandom (uint32_t id, double min, double max); private: /** Maximum alpha */ - double m_max; + const double m_max; /** Minimum alpha */ - double m_min; + const double m_min; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp index 2d0e61c..838e90e 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.cpp @@ -2,18 +2,18 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CAngularVelocityRandom* CAngularVelocityRandom::fromJSON (json data, uint32_t id) { - const auto min_it = jsonFindRequired (data, "min", "Angularvelocityrandom initializer must have a minimum value"); - const auto max_it = jsonFindRequired (data, "max", "Angularvelocityrandom initializer must have a maximum value"); - - return new CAngularVelocityRandom (id, WallpaperEngine::Core::aToVector3 (*min_it), - WallpaperEngine::Core::aToVector3 (*max_it)); +const CAngularVelocityRandom* CAngularVelocityRandom::fromJSON (const json& data, uint32_t id) { + return new CAngularVelocityRandom ( + id, + jsonFindRequired (data, "min", "Angularvelocityrandom initializer must have a minimum value"), + jsonFindRequired (data, "max", "Angularvelocityrandom initializer must have a maximum value") + ); } CAngularVelocityRandom::CAngularVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max) : CInitializer (id, "angularvelocityrandom"), - m_min (min), - m_max (max) {} + m_max (max), + m_min (min) {} const glm::vec3& CAngularVelocityRandom::getMinimum () const { return this->m_min; diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h index b04d87d..ffc99ee 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CAngularVelocityRandom.h @@ -21,14 +21,14 @@ class CAngularVelocityRandom : CInitializer { protected: friend class CInitializer; - static CAngularVelocityRandom* fromJSON (json data, uint32_t id); + static const CAngularVelocityRandom* fromJSON (const json& data, uint32_t id); CAngularVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max); private: /** Maximum velocity (direction * speed) */ - glm::vec3 m_max; + const glm::vec3 m_max; /** Minimum velocity (direction * speed) */ - glm::vec3 m_min; + const glm::vec3 m_min; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp index a2952a2..e23c019 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.cpp @@ -2,18 +2,18 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CColorRandom* CColorRandom::fromJSON (json data, uint32_t id) { - const auto min_it = jsonFindRequired (data, "min", "Colorrandom initializer must have a minimum value"); - const auto max_it = jsonFindRequired (data, "max", "Colorrandom initializer must have a maximum value"); - - return new CColorRandom (id, WallpaperEngine::Core::aToColori (*min_it), - WallpaperEngine::Core::aToColori (*max_it)); +const CColorRandom* CColorRandom::fromJSON (const json& data, uint32_t id) { + return new CColorRandom ( + id, + jsonFindRequired (data, "min", "Colorrandom initializer must have a minimum value"), + jsonFindRequired (data, "max", "Colorrandom initializer must have a maximum value") + ); } CColorRandom::CColorRandom (uint32_t id, glm::ivec3 min, glm::ivec3 max) : CInitializer (id, "colorrandom"), - m_min (min), - m_max (max) {} + m_max (max), + m_min (min) {} const glm::ivec3& CColorRandom::getMinimum () const { return this->m_min; diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h index af7cc2d..b84f30b 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CColorRandom.h @@ -22,14 +22,14 @@ class CColorRandom : CInitializer { protected: friend class CInitializer; - static CColorRandom* fromJSON (json data, uint32_t id); + static const CColorRandom* fromJSON (const json& data, uint32_t id); CColorRandom (uint32_t id, glm::ivec3 min, glm::ivec3 max); private: /** Maximum color */ - glm::ivec3 m_max; + const glm::ivec3 m_max; /** Minimum color */ - glm::ivec3 m_min; + const glm::ivec3 m_min; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp index cdc008d..421ca2e 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.cpp @@ -2,17 +2,18 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CLifeTimeRandom* CLifeTimeRandom::fromJSON (json data, uint32_t id) { - const auto min_it = jsonFindRequired (data, "min", "Lifetimerandom initializer must have a minimum value"); - const auto max_it = jsonFindRequired (data, "max", "Lifetimerandom initializer must have a maximum value"); - - return new CLifeTimeRandom (id, *min_it, *max_it); +const CLifeTimeRandom* CLifeTimeRandom::fromJSON (const json& data, uint32_t id) { + return new CLifeTimeRandom ( + id, + jsonFindRequired (data, "min", "Lifetimerandom initializer must have a minimum value"), + jsonFindRequired (data, "max", "Lifetimerandom initializer must have a maximum value") + ); } CLifeTimeRandom::CLifeTimeRandom (uint32_t id, uint32_t min, uint32_t max) : CInitializer (id, "lifetimerandom"), - m_min (min), - m_max (max) {} + m_max (max), + m_min (min) {} uint32_t CLifeTimeRandom::getMinimum () const { return this->m_min; diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h index 6285efb..efdf379 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CLifeTimeRandom.h @@ -22,14 +22,14 @@ class CLifeTimeRandom : CInitializer { protected: friend class CInitializer; - static CLifeTimeRandom* fromJSON (json data, uint32_t id); + static const CLifeTimeRandom* fromJSON (const json& data, uint32_t id); CLifeTimeRandom (uint32_t id, uint32_t min, uint32_t max); private: /** Maximum lifetime */ - uint32_t m_max; + const uint32_t m_max; /** Minimum lifetime */ - uint32_t m_min; + const uint32_t m_min; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp index 384e8d9..0787bf7 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.cpp @@ -4,7 +4,7 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CRotationRandom* CRotationRandom::fromJSON (json data, uint32_t id) { +const CRotationRandom* CRotationRandom::fromJSON (const json& data, uint32_t id) { const auto min_it = data.find ("minVector"); const auto max_it = data.find ("max"); @@ -37,10 +37,10 @@ CRotationRandom* CRotationRandom::fromJSON (json data, uint32_t id) { CRotationRandom::CRotationRandom (uint32_t id, glm::vec3 minVector, double minNumber, bool isMinimumVector, glm::vec3 maxVector, double maxNumber, bool isMaximumVector) : CInitializer (id, "rotationrandom"), - m_minVector (minVector), m_maxVector (maxVector), - m_minNumber (minNumber), m_maxNumber (maxNumber), + m_minVector (minVector), + m_minNumber (minNumber), m_isMinimumVector (isMinimumVector), m_isMaximumVector (isMaximumVector) {} diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h index 5e92e7c..cc5d2ff 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CRotationRandom.h @@ -47,24 +47,24 @@ class CRotationRandom : CInitializer { protected: friend class CInitializer; - static CRotationRandom* fromJSON (json data, uint32_t id); + static const CRotationRandom* fromJSON (const json& data, uint32_t id); CRotationRandom (uint32_t id, glm::vec3 minVector, double minNumber, bool isMinimumVector, glm::vec3 maxVector, double maxNumber, bool isMaximumVector); private: /** Maximum rotation vector */ - glm::vec3 m_maxVector; + const glm::vec3 m_maxVector; /** Maximum rotation angle */ - double m_maxNumber; + const double m_maxNumber; /** Minimum rotation vector */ - glm::vec3 m_minVector; + const glm::vec3 m_minVector; /** Minimum rotation angle */ - double m_minNumber; + const double m_minNumber; /** If minimum is a vector */ - bool m_isMinimumVector; + const bool m_isMinimumVector; /** If maximum is a vector */ - bool m_isMaximumVector; + const bool m_isMaximumVector; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp index af455fa..191ff37 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.cpp @@ -2,17 +2,18 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CSizeRandom* CSizeRandom::fromJSON (json data, uint32_t id) { - const auto min_it = jsonFindRequired (data, "min", "Sizerandom initializer must have a minimum value"); - const auto max_it = jsonFindRequired (data, "max", "Sizerandom initializer must have a maximum value"); - - return new CSizeRandom (id, *min_it, *max_it); +const CSizeRandom* CSizeRandom::fromJSON (const json& data, uint32_t id) { + return new CSizeRandom ( + id, + jsonFindRequired (data, "min", "Sizerandom initializer must have a minimum value"), + jsonFindRequired (data, "max", "Sizerandom initializer must have a maximum value") + ); } CSizeRandom::CSizeRandom (uint32_t id, uint32_t min, uint32_t max) : CInitializer (id, "sizerandom"), - m_min (min), - m_max (max) {} + m_max (max), + m_min (min) {} uint32_t CSizeRandom::getMinimum () const { return this->m_min; diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h index 9dcf4f9..a398760 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CSizeRandom.h @@ -22,14 +22,14 @@ class CSizeRandom : CInitializer { protected: friend class CInitializer; - static CSizeRandom* fromJSON (json data, uint32_t id); + static const CSizeRandom* fromJSON (const json& data, uint32_t id); CSizeRandom (uint32_t id, uint32_t min, uint32_t max); private: /** Maximum size */ - uint32_t m_max; + const uint32_t m_max; /** Minimum size */ - uint32_t m_min; + const uint32_t m_min; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp index e42877e..40c92fb 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.cpp @@ -1,29 +1,19 @@ #include "CTurbulentVelocityRandom.h" -#include "common.h" #include "WallpaperEngine/Core/Core.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CTurbulentVelocityRandom* CTurbulentVelocityRandom::fromJSON (json data, uint32_t id) { - const auto phasemax_it = data.find ("phasemax"); - const auto scale_it = data.find ("scale"); - const auto speedmax_it = data.find ("speedmax"); - const auto speedmin_it = data.find ("speedmin"); - const auto timescale_it = data.find ("timescale"); - - if (phasemax_it == data.end ()) - sLog.exception ("TurbulentVelocityRandom initializer must have a phasemax value"); - if (scale_it == data.end ()) - sLog.exception ("TurbulentVelocityRandom initializer must have a scale value"); - if (speedmax_it == data.end ()) - sLog.exception ("TurbulentVelocityRandom initializer must have a maximum speed value"); - if (speedmin_it == data.end ()) - sLog.exception ("TurbulentVelocityRandom initializer must have a minimum speed value"); - if (timescale_it == data.end ()) - sLog.exception ("TurbulentVelocityRandom initializer must have a timescale value"); - - return new CTurbulentVelocityRandom (id, *phasemax_it, *scale_it, *timescale_it, *speedmin_it, *speedmax_it); +const CTurbulentVelocityRandom* CTurbulentVelocityRandom::fromJSON (const json& data, uint32_t id) { + return new CTurbulentVelocityRandom ( + id, + jsonFindRequired (data, "phasemax", "TurbulentVelocityRandom initializer must have a phasemax value"), + jsonFindRequired (data, "scale", "TurbulentVelocityRandom initializer must have a scale value"), + jsonFindRequired (data, "timescale", "TurbulentVelocityRandom initializer must have a timescale value"), + jsonFindRequired (data, "speedmin", "TurbulentVelocityRandom initializer must have a minimum speed value"), + jsonFindRequired (data, "speedmax", "TurbulentVelocityRandom initializer must have a maximum speed value") + ); } CTurbulentVelocityRandom::CTurbulentVelocityRandom (uint32_t id, double phasemax, double scale, double timescale, @@ -35,22 +25,22 @@ CTurbulentVelocityRandom::CTurbulentVelocityRandom (uint32_t id, double phasemax m_speedmin (speedmin), m_speedmax (speedmax) {} -double CTurbulentVelocityRandom::getPhaseMax () { +double CTurbulentVelocityRandom::getPhaseMax () const { return this->m_phasemax; } -double CTurbulentVelocityRandom::getScale () { +double CTurbulentVelocityRandom::getScale () const { return this->m_scale; } -double CTurbulentVelocityRandom::getTimeScale () { +double CTurbulentVelocityRandom::getTimeScale () const { return this->m_timescale; } -uint32_t CTurbulentVelocityRandom::getMinimumSpeed () { +uint32_t CTurbulentVelocityRandom::getMinimumSpeed () const { return this->m_speedmin; } -uint32_t CTurbulentVelocityRandom::getMaximumSpeed () { +uint32_t CTurbulentVelocityRandom::getMaximumSpeed () const { return this->m_speedmax; } diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h index 33250fc..e1d2293 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CTurbulentVelocityRandom.h @@ -13,42 +13,42 @@ class CTurbulentVelocityRandom : CInitializer { /** * @return The phase to use */ - double getPhaseMax (); + double getPhaseMax () const; /** * @return The scale to use */ - double getScale (); + double getScale () const; /** * @return How time affects to the scale */ - double getTimeScale (); + double getTimeScale () const; /** * @return The minimum speed */ - uint32_t getMinimumSpeed (); + uint32_t getMinimumSpeed () const; /** * @return The maximum speed */ - uint32_t getMaximumSpeed (); + uint32_t getMaximumSpeed () const; protected: friend class CInitializer; - static CTurbulentVelocityRandom* fromJSON (json data, uint32_t id); + static const CTurbulentVelocityRandom* fromJSON (const json& data, uint32_t id); CTurbulentVelocityRandom (uint32_t id, double phasemax, double scale, double timescale, uint32_t speedmin, uint32_t speedmax); private: /** Phase */ - double m_phasemax; + const double m_phasemax; /** Scale */ - double m_scale; + const double m_scale; /** Time scale, how the time affects the scale */ - double m_timescale; + const double m_timescale; /** Minimum speed */ - uint32_t m_speedmin; + const uint32_t m_speedmin; /** Maximum speed */ - uint32_t m_speedmax; + const uint32_t m_speedmax; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp index 847db03..3559850 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.cpp @@ -2,18 +2,18 @@ using namespace WallpaperEngine::Core::Objects::Particles::Initializers; -CVelocityRandom* CVelocityRandom::fromJSON (json data, uint32_t id) { - const auto min_it = jsonFindRequired (data, "min", "Velocityrandom initializer must have a minimum value"); - const auto max_it = jsonFindRequired (data, "max", "Velocityrandom initializer must have a maximum value"); - - return new CVelocityRandom (id, WallpaperEngine::Core::aToVector3 (*min_it), - WallpaperEngine::Core::aToVector3 (*max_it)); +const CVelocityRandom* CVelocityRandom::fromJSON (const json& data, uint32_t id) { + return new CVelocityRandom ( + id, + jsonFindRequired (data, "min", "Velocityrandom initializer must have a minimum value"), + jsonFindRequired (data, "max", "Velocityrandom initializer must have a maximum value") + ); } CVelocityRandom::CVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max) : CInitializer (id, "velocityrandom"), - m_min (min), - m_max (max) {} + m_max (max), + m_min (min) {} const glm::vec3& CVelocityRandom::getMinimum () const { return this->m_min; diff --git a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h index bce80b1..1fb390a 100644 --- a/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h +++ b/src/WallpaperEngine/Core/Objects/Particles/Initializers/CVelocityRandom.h @@ -22,14 +22,14 @@ class CVelocityRandom : CInitializer { protected: friend class CInitializer; - static CVelocityRandom* fromJSON (json data, uint32_t id); + static const CVelocityRandom* fromJSON (const json& data, uint32_t id); CVelocityRandom (uint32_t id, glm::vec3 min, glm::vec3 max); private: /** Maximum velocity */ - glm::vec3 m_max; + const glm::vec3 m_max; /** Minimum velocity */ - glm::vec3 m_min; + const glm::vec3 m_min; }; } // namespace WallpaperEngine::Core::Objects::Particles::Initializers diff --git a/src/WallpaperEngine/Core/Projects/CProperty.cpp b/src/WallpaperEngine/Core/Projects/CProperty.cpp index fd8fdb0..bffbcea 100644 --- a/src/WallpaperEngine/Core/Projects/CProperty.cpp +++ b/src/WallpaperEngine/Core/Projects/CProperty.cpp @@ -4,23 +4,24 @@ #include "CPropertyCombo.h" #include "CPropertySlider.h" #include "CPropertyText.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include +#include using namespace WallpaperEngine::Core::Projects; -CProperty* CProperty::fromJSON (json data, const std::string& name) { +std::shared_ptr CProperty::fromJSON (const json& data, const std::string& name) { const auto type = jsonFindRequired (data, "type", "Project properties must have the type field"); - if (*type == CPropertyColor::Type) + if (*type == "color") return CPropertyColor::fromJSON (data, name); - if (*type == CPropertyBoolean::Type) + if (*type == "bool") return CPropertyBoolean::fromJSON (data, name); - if (*type == CPropertySlider::Type) + if (*type == "slider") return CPropertySlider::fromJSON (data, name); - if (*type == CPropertyCombo::Type) + if (*type == "combo") return CPropertyCombo::fromJSON (data, name); - if (*type == CPropertyText::Type) + if (*type == "text") return CPropertyText::fromJSON (data, name); // show the error and ignore this property @@ -30,19 +31,26 @@ CProperty* CProperty::fromJSON (json data, const std::string& name) { return nullptr; } -CProperty::CProperty (std::string name, std::string type, std::string text) : - m_name (std::move (name)), - m_type (std::move (type)), - m_text (std::move (text)) {} +CProperty::CProperty (std::string name, std::string text) : + m_name (std::move(name)), + m_text (std::move(text)) {} + +void CProperty::subscribe (const function_type& callback) const { + this->m_subscriptions.push_back (callback); +} + +void CProperty::propagate () const { + CDynamicValue::propagate (); + + for (const auto& callback : this->m_subscriptions) { + callback(this); + } +} const std::string& CProperty::getName () const { return this->m_name; } -const std::string& CProperty::getType () const { - return this->m_type; -} - const std::string& CProperty::getText () const { return this->m_text; } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Projects/CProperty.h b/src/WallpaperEngine/Core/Projects/CProperty.h index ef26d68..cc179c9 100644 --- a/src/WallpaperEngine/Core/Projects/CProperty.h +++ b/src/WallpaperEngine/Core/Projects/CProperty.h @@ -1,35 +1,41 @@ #pragma once +#include "WallpaperEngine/Core/DynamicValues/CDynamicValue.h" #include "WallpaperEngine/Core/Core.h" namespace WallpaperEngine::Core::Projects { using json = nlohmann::json; - +using namespace WallpaperEngine::Core::DynamicValues; /** * Represents a property in a background * * Properties are settings that alter how the background looks or works * and are configurable by the user so they can customize it to their likings */ -class CPropertyColor; - -class CProperty { +class CProperty : public CDynamicValue { public: + typedef std::function function_type; virtual ~CProperty () = default; - static CProperty* fromJSON (json data, const std::string& name); + static std::shared_ptr fromJSON (const json& data, const std::string& name); - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); } /** @@ -41,29 +47,36 @@ class CProperty { * * @param value New value for the property */ - virtual void update (const std::string& value) = 0; - + virtual void set (const std::string& value) = 0; /** * @return Name of the property */ [[nodiscard]] const std::string& getName () const; /** - * @return Type of the property + * @return Textual type representation of this property */ - [[nodiscard]] const std::string& getType () const; + [[nodiscard]] virtual const char* getType () const = 0; /** * @return Text of the property */ [[nodiscard]] const std::string& getText () const; + /** + * Registers a function to be called when this instance's value changes + * + * @param callback + */ + void subscribe (const function_type& callback) const; protected: - CProperty (std::string name, std::string type, std::string text); + void propagate () const override; - /** Type of property */ - std::string m_type; + CProperty (std::string name, std::string text); + + /** Functions to call when this property's value changes */ + mutable std::vector m_subscriptions; /** Name of the property */ - std::string m_name; + const std::string m_name; /** Description of the property for the user */ - std::string m_text; + mutable std::string m_text; }; } // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp index 950cd9d..0c59ce8 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.cpp @@ -1,23 +1,22 @@ #include +#include #include "CPropertyBoolean.h" #include "WallpaperEngine/Core/Core.h" using namespace WallpaperEngine::Core::Projects; -CPropertyBoolean* CPropertyBoolean::fromJSON (json data, const std::string& name) { - const json::const_iterator value = data.find ("value"); - const auto text = jsonFindDefault (data, "text", ""); - - return new CPropertyBoolean (*value, name, text); +std::shared_ptr CPropertyBoolean::fromJSON (const json& data, std::string name) { + return std::make_shared ( + jsonFindRequired (data, "value", "Boolean property must have a value"), + std::move(name), + jsonFindDefault (data, "text", "") + ); } -bool CPropertyBoolean::getValue () const { - return this->m_value; -} -void CPropertyBoolean::update (const std::string& value) { - this->m_value = value == "1" || value == "true"; +void CPropertyBoolean::set (const std::string& value) { + this->update (value == "1" || value == "true" || value == "on"); } std::string CPropertyBoolean::dump () const { @@ -27,13 +26,14 @@ std::string CPropertyBoolean::dump () const { << "\t" << "Description: " << this->m_text << std::endl << "\t" - << "Value: " << this->m_value; + << "Value: " << &this->getBool (); return ss.str (); } -CPropertyBoolean::CPropertyBoolean (bool value, const std::string& name, const std::string& text) : - CProperty (name, Type, text), - m_value (value) {} +const char* CPropertyBoolean::getType () const { + return "bool"; +} -const std::string CPropertyBoolean::Type = "bool"; \ No newline at end of file +CPropertyBoolean::CPropertyBoolean (bool value, std::string name, std::string text) : + CProperty (std::move(name), std::move(text)) {} diff --git a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h index de4702b..ebaee63 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyBoolean.h @@ -10,23 +10,12 @@ using json = nlohmann::json; */ class CPropertyBoolean final : public CProperty { public: - static CPropertyBoolean* fromJSON (json data, const std::string& name); + CPropertyBoolean (bool value, std::string name, std::string text); - /** - * @return The value of the property - */ - [[nodiscard]] bool getValue () const; - /** @inheritdoc */ + static std::shared_ptr fromJSON (const json& data, std::string name); [[nodiscard]] std::string dump () const override; - /** @inheritdoc */ - void update (const std::string& value) override; + void set (const std::string& value) override; - static const std::string Type; - - private: - CPropertyBoolean (bool value, const std::string& name, const std::string& text); - - /** Property's value */ - bool m_value; + [[nodiscard]] const char* getType () const override; }; } // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp b/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp index d350465..71f8a21 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyColor.cpp @@ -1,10 +1,12 @@ #include +#include #include "CPropertyColor.h" using namespace WallpaperEngine::Core::Projects; glm::vec3 ParseColor (std::string value) { + // TODO: ENSURE THIS PARSING IS ACTUALLY ACCURATE if (value.find (',') != std::string::npos) { // replace commas with dots so it can be parsed std::replace (value.begin (), value.end (), ',', ' '); @@ -19,35 +21,35 @@ glm::vec3 ParseColor (std::string value) { return WallpaperEngine::Core::aToColorf (value); } -CPropertyColor* CPropertyColor::fromJSON (json data, const std::string& name) { - const std::string value = *jsonFindRequired (data, "value", "Color property must have a value"); +std::shared_ptr CPropertyColor::fromJSON (const json& data, std::string name) { + const auto value = jsonFindRequired (data, "value", "Color property must have a value"); const auto text = jsonFindDefault (data, "text", ""); - return new CPropertyColor (ParseColor (value), name, text); + return std::make_shared (value, std::move(name), text); } -const glm::vec3& CPropertyColor::getValue () const { - return this->m_color; -} - -void CPropertyColor::update (const std::string& value) { - this->m_color = ParseColor (std::string (value)); +void CPropertyColor::set (const std::string& value) { + this->update (ParseColor (std::string (value))); } std::string CPropertyColor::dump () const { + const auto color = this->getVec3 (); std::stringstream ss; ss << this->m_name << " - color" << std::endl << "\t" << "Description: " << this->m_text << std::endl << "\t" - << "R: " << this->m_color.r << " G: " << this->m_color.g << " B: " << this->m_color.b; + << "R: " << color.r << " G: " << color.g << " B: " << color.b; return ss.str (); } -CPropertyColor::CPropertyColor (glm::vec3 color, const std::string& name, const std::string& text) : - CProperty (name, Type, text), - m_color (color) {} +const char* CPropertyColor::getType () const { + return "color"; +} -const std::string CPropertyColor::Type = "color"; \ No newline at end of file +CPropertyColor::CPropertyColor (const std::string& color, std::string name, std::string text) : + CProperty (std::move(name), std::move(text)) { + this->set (color); +} diff --git a/src/WallpaperEngine/Core/Projects/CPropertyColor.h b/src/WallpaperEngine/Core/Projects/CPropertyColor.h index cdfb083..317bbd5 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyColor.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyColor.h @@ -12,20 +12,12 @@ using json = nlohmann::json; */ class CPropertyColor final : public CProperty { public: - static CPropertyColor* fromJSON (json data, const std::string& name); + CPropertyColor (const std::string& color, std::string name, std::string text); - /** - * @return The RGB color value in the 0-1 range - */ - [[nodiscard]] const glm::vec3& getValue () const; + static std::shared_ptr fromJSON (const json& data, std::string name); [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; + void set (const std::string& value) override; - static const std::string Type; - - private: - CPropertyColor (glm::vec3 color, const std::string& name, const std::string& text); - - glm::vec3 m_color; + [[nodiscard]] const char* getType () const override; }; } // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp b/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp index 60d782f..96dac63 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyCombo.cpp @@ -1,20 +1,17 @@ -#include "common.h" #include +#include #include "CPropertyCombo.h" #include "WallpaperEngine/Core/Core.h" -#include +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core::Projects; -CPropertyCombo* CPropertyCombo::fromJSON (json data, const std::string& name) { - const auto value = data.find ("value"); - const auto text = jsonFindDefault (data, "text", ""); +std::shared_ptr CPropertyCombo::fromJSON (const json& data, std::string name) { + std::vector values; const auto options = jsonFindRequired (data, "options", "Options for a property combo is required"); - auto* combo = new CPropertyCombo (name, text, value->dump ()); - if (!options->is_array ()) sLog.exception ("Property combo options should be an array"); @@ -24,26 +21,27 @@ CPropertyCombo* CPropertyCombo::fromJSON (json data, const std::string& name) { continue; // check for label and value to ensure they're there - auto label = jsonFindRequired (cur, "label", "Label is required for a property combo option"); - auto propertyValue = jsonFindRequired (cur, "value", "Value is required for a property combo option"); - - combo->addValue (*label, propertyValue->dump()); + values.push_back ({ + .label = jsonFindRequired (cur, "label", "Label is required for a property combo option"), + .value = jsonFindRequired (cur, "value", "Value is required for a property combo option") + }); } - return combo; + return std::make_shared ( + std::move(name), + jsonFindDefault (data, "text", ""), + jsonFindRequired (data, "value", "Value is required for a property combo"), + values + ); } -CPropertyCombo::CPropertyCombo (const std::string& name, const std::string& text, std::string defaultValue) : - CProperty (name, Type, text), - m_defaultValue (std::move (defaultValue)) {} - -CPropertyCombo::~CPropertyCombo () { - for (const auto* value : this->m_values) - delete value; -} - -const std::string& CPropertyCombo::getValue () const { - return this->m_defaultValue; +CPropertyCombo::CPropertyCombo ( + std::string name, std::string text, const std::string& defaultValue, + std::vector values +) : + CProperty (std::move(name), std::move(text)), + m_values (std::move(values)) { + this->set (defaultValue); } std::string CPropertyCombo::dump () const { @@ -53,40 +51,57 @@ std::string CPropertyCombo::dump () const { << "\t" << "Description: " << this->m_text << std::endl << "\t" - << "Value: " << this->m_defaultValue << std::endl + << "Value: " << &this->getInt () << std::endl << "\t\t" << "Posible values:" << std::endl; - for (const auto cur : this->m_values) - ss << "\t\t" << cur->label << " -> " << cur->value << std::endl; + for (const auto& cur : this->m_values) + ss << "\t\t" << cur.label << " -> " << cur.value << std::endl; return ss.str (); } -void CPropertyCombo::update (const std::string& value) { +void CPropertyCombo::set (const std::string& value) { bool found = false; + int index = 0; // ensure the value is present somewhere in the value list - for (const auto cur : this->m_values) { - if (cur->value != value) - continue; + for (const auto& cur : this->m_values) { + if (cur.value == value) { + found = true; + break; + } - found = true; + index ++; } if (!found) sLog.exception ("Assigning invalid value to property ", this->m_name); - this->m_defaultValue = value; + this->update (index); } -void CPropertyCombo::addValue (std::string label, std::string value) { - auto* prop = new CPropertyComboValue; +int CPropertyCombo::translateValueToIndex (const std::string& value) const { + bool found = false; + int index = 0; - prop->label = std::move (label); - prop->value = std::move (value); + // ensure the value is present somewhere in the value list + for (const auto& cur : this->m_values) { + if (cur.value == value) { + found = true; + break; + } - this->m_values.push_back (prop); + index ++; + } + + if (!found) { + return -1; + } + + return index; } -const std::string CPropertyCombo::Type = "combo"; \ No newline at end of file +const char* CPropertyCombo::getType () const { + return "combo"; +} diff --git a/src/WallpaperEngine/Core/Projects/CPropertyCombo.h b/src/WallpaperEngine/Core/Projects/CPropertyCombo.h index 47275af..d7015b1 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyCombo.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyCombo.h @@ -8,10 +8,10 @@ using json = nlohmann::json; /** * Represents different combo values */ -class CPropertyComboValue { +struct CPropertyComboValue { public: - std::string label; - std::string value; + const std::string label; + const std::string value; }; /** @@ -23,33 +23,20 @@ class CPropertyComboValue { */ class CPropertyCombo final : public CProperty { public: - static CPropertyCombo* fromJSON (json data, const std::string& name); + static std::shared_ptr fromJSON (const json& data, std::string name); - ~CPropertyCombo () override; + CPropertyCombo ( + std::string name, std::string text, const std::string& defaultValue, + std::vector values); - /** - * @return The selected value - */ - [[nodiscard]] const std::string& getValue () const; [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; + void set (const std::string& value) override; + int translateValueToIndex (const std::string& value) const; - static const std::string Type; + [[nodiscard]] const char* getType () const override; private: - CPropertyCombo (const std::string& name, const std::string& text, std::string defaultValue); - - /** - * Adds a combo value to the list of possible values - * - * @param label - * @param value - */ - void addValue (std::string label, std::string value); - /** List of values available to select */ - std::vector m_values; - /** The default value */ - std::string m_defaultValue; + const std::vector m_values; }; } // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp b/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp index 5c0ecb5..d83e1ad 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertySlider.cpp @@ -1,32 +1,28 @@ #include "CPropertySlider.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include using namespace WallpaperEngine::Core::Projects; -CPropertySlider* CPropertySlider::fromJSON (json data, const std::string& name) { +std::shared_ptr CPropertySlider::fromJSON (const json& data, const std::string& name) { const auto value = data.find ("value"); const auto text = jsonFindDefault (data, "text", ""); - const auto min = jsonFindDefault (data, "min", 0.0); - const auto max = jsonFindDefault (data, "max", 0.0); - const auto step = jsonFindDefault (data, "step", 0.0); + const auto min = jsonFindDefault (data, "min", 0.0f); + const auto max = jsonFindDefault (data, "max", 0.0f); + const auto step = jsonFindDefault (data, "step", 0.0f); - return new CPropertySlider (*value, name, text, min, max, step); + return std::make_shared (*value, name, text, min, max, step); } -const double& CPropertySlider::getValue () const { - return this->m_value; -} - -const double& CPropertySlider::getMinValue () const { +const float& CPropertySlider::getMinValue () const { return this->m_min; } -const double& CPropertySlider::getMaxValue () const { +const float& CPropertySlider::getMaxValue () const { return this->m_max; } -const double& CPropertySlider::getStep () const { +const float& CPropertySlider::getStep () const { return this->m_step; } @@ -37,7 +33,7 @@ std::string CPropertySlider::dump () const { << "\t" << "Description: " << this->m_text << std::endl << "\t" - << "Value: " << this->m_value << std::endl + << "Value: " << &this->getFloat () << std::endl << "\t" << "Minimum value: " << this->m_min << std::endl << "\t" @@ -48,21 +44,24 @@ std::string CPropertySlider::dump () const { return ss.str (); } -void CPropertySlider::update (const std::string& value) { - const double newValue = strtod (value.c_str (), nullptr); +void CPropertySlider::set (const std::string& value) { + const auto newValue = strtof (value.c_str (), nullptr); if (newValue < this->m_min || newValue > this->m_max) sLog.exception ("Slider value (", newValue, ") is out of range (", this->m_min, ",", this->m_max, ")"); - this->m_value = newValue; + this->update (newValue); } -CPropertySlider::CPropertySlider (double value, const std::string& name, const std::string& text, double min, - double max, double step) : - CProperty (name, Type, text), - m_value (value), +const char* CPropertySlider::getType () const { + return "slider"; +} + +CPropertySlider::CPropertySlider (float value, const std::string& name, const std::string& text, float min, + float max, float step) : + CProperty (name, text), m_min (min), m_max (max), - m_step (step) {} - -const std::string CPropertySlider::Type = "slider"; \ No newline at end of file + m_step (step) { + this->update (value); +} diff --git a/src/WallpaperEngine/Core/Projects/CPropertySlider.h b/src/WallpaperEngine/Core/Projects/CPropertySlider.h index d651526..3366a4a 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertySlider.h +++ b/src/WallpaperEngine/Core/Projects/CPropertySlider.h @@ -12,40 +12,32 @@ using json = nlohmann::json; */ class CPropertySlider final : public CProperty { public: - static CPropertySlider* fromJSON (json data, const std::string& name); + CPropertySlider (float value, const std::string& name, const std::string& text, float min, float max, float step); - /** - * @return The slider's value - */ - [[nodiscard]] const double& getValue () const; + static std::shared_ptr fromJSON (const json& data, const std::string& name); /** * @return The slider's minimum value */ - [[nodiscard]] const double& getMinValue () const; + [[nodiscard]] const float& getMinValue () const; /** * @return The slider's maximum value */ - [[nodiscard]] const double& getMaxValue () const; + [[nodiscard]] const float& getMaxValue () const; /** * @return The slider's value increment steps, only really used in the UI */ - [[nodiscard]] const double& getStep () const; + [[nodiscard]] const float& getStep () const; [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; + void set (const std::string& value) override; - static const std::string Type; + [[nodiscard]] const char* getType () const override; private: - CPropertySlider (double value, const std::string& name, const std::string& text, double min, double max, - double step); - - /** Actual slider value */ - double m_value; /** Minimum value */ - double m_min; + const float m_min; /** Maximum value */ - double m_max; + const float m_max; /** Increment steps for the slider in the UI */ - double m_step; + const float m_step; }; } // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Projects/CPropertyText.cpp b/src/WallpaperEngine/Core/Projects/CPropertyText.cpp index b6892aa..3079bd5 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyText.cpp +++ b/src/WallpaperEngine/Core/Projects/CPropertyText.cpp @@ -1,13 +1,13 @@ #include "CPropertyText.h" #include "WallpaperEngine/Core/Core.h" #include +#include using namespace WallpaperEngine::Core::Projects; -CPropertyText* CPropertyText::fromJSON (json data, const std::string& name) { - const json::const_iterator text = data.find ("type"); - - return new CPropertyText (name, *text); +std::shared_ptr CPropertyText::fromJSON (const json& data, std::string name) { + //TODO: VALIDATE THIS IS RIGHT + return std::make_shared (std::move(name), *data.find ("type")); } std::string CPropertyText::dump () const { @@ -20,10 +20,13 @@ std::string CPropertyText::dump () const { return ss.str (); } -void CPropertyText::update (const std::string& value) { +void CPropertyText::set (const std::string& value) { this->m_text = value; } -CPropertyText::CPropertyText (const std::string& name, const std::string& text) : CProperty (name, Type, text) {} +const char* CPropertyText::getType () const { + return "text"; +} -const std::string CPropertyText::Type = "text"; \ No newline at end of file +CPropertyText::CPropertyText (std::string name, std::string text) : + CProperty (std::move(name), std::move(text)) {} diff --git a/src/WallpaperEngine/Core/Projects/CPropertyText.h b/src/WallpaperEngine/Core/Projects/CPropertyText.h index 1586076..07cd717 100644 --- a/src/WallpaperEngine/Core/Projects/CPropertyText.h +++ b/src/WallpaperEngine/Core/Projects/CPropertyText.h @@ -10,13 +10,13 @@ using json = nlohmann::json; */ class CPropertyText final : public CProperty { public: - static CPropertyText* fromJSON (json data, const std::string& name); + CPropertyText (std::string name, std::string text); + + static std::shared_ptr fromJSON (const json& data, std::string name); [[nodiscard]] std::string dump () const override; - void update (const std::string& value) override; - - static const std::string Type; + void set (const std::string& value) override; + [[nodiscard]] const char* getType () const override; private: - CPropertyText (const std::string& name, const std::string& text); }; } // namespace WallpaperEngine::Core::Projects diff --git a/src/WallpaperEngine/Core/Scenes/CCamera.cpp b/src/WallpaperEngine/Core/Scenes/CCamera.cpp index 3cae285..05118bc 100644 --- a/src/WallpaperEngine/Core/Scenes/CCamera.cpp +++ b/src/WallpaperEngine/Core/Scenes/CCamera.cpp @@ -2,7 +2,10 @@ using namespace WallpaperEngine::Core::Scenes; -CCamera::CCamera (glm::vec3 center, glm::vec3 eye, glm::vec3 up) : m_center (center), m_eye (eye), m_up (up) {} +CCamera::CCamera (glm::vec3 center, glm::vec3 eye, glm::vec3 up) : + m_center (center), + m_eye (eye), + m_up (up) {} const glm::vec3& CCamera::getCenter () const { return this->m_center; @@ -16,11 +19,10 @@ const glm::vec3& CCamera::getUp () const { return this->m_up; } -CCamera* CCamera::fromJSON (json data) { - const auto center_it = jsonFindRequired (data, "center", "Camera must have a center position"); - const auto eye_it = jsonFindRequired (data, "eye", "Camera must have an eye position"); - const auto up_it = jsonFindRequired (data, "up", "Camera must have a up position"); - - return new CCamera (WallpaperEngine::Core::aToVector3 (*center_it), WallpaperEngine::Core::aToVector3 (*eye_it), - WallpaperEngine::Core::aToVector3 (*up_it)); +const CCamera* CCamera::fromJSON (const json::const_iterator& data) { + return new CCamera ( + jsonFindRequired (data, "center", "Camera must have a center position"), + jsonFindRequired (data, "eye", "Camera must have an eye position"), + jsonFindRequired (data, "up", "Camera must have a up position") + ); } \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Scenes/CCamera.h b/src/WallpaperEngine/Core/Scenes/CCamera.h index 7ef63ca..5d2f17f 100644 --- a/src/WallpaperEngine/Core/Scenes/CCamera.h +++ b/src/WallpaperEngine/Core/Scenes/CCamera.h @@ -7,7 +7,7 @@ using json = nlohmann::json; class CCamera { public: - static CCamera* fromJSON (json data); + static const CCamera* fromJSON (const json::const_iterator& data); const glm::vec3& getCenter () const; const glm::vec3& getEye () const; @@ -17,8 +17,8 @@ class CCamera { CCamera (glm::vec3 center, glm::vec3 eye, glm::vec3 up); private: - glm::vec3 m_center; - glm::vec3 m_eye; - glm::vec3 m_up; + const glm::vec3 m_center; + const glm::vec3 m_eye; + const glm::vec3 m_up; }; } // namespace WallpaperEngine::Core::Scenes diff --git a/src/WallpaperEngine/Core/Scenes/CProjection.cpp b/src/WallpaperEngine/Core/Scenes/CProjection.cpp index c94960a..d9ee5b0 100644 --- a/src/WallpaperEngine/Core/Scenes/CProjection.cpp +++ b/src/WallpaperEngine/Core/Scenes/CProjection.cpp @@ -2,9 +2,15 @@ using namespace WallpaperEngine::Core::Scenes; -CProjection::CProjection (int width, int height) : m_isAuto (false), m_width (width), m_height (height) {} +CProjection::CProjection (int width, int height) : + m_width (width), + m_height (height), + m_isAuto (false) {} -CProjection::CProjection (bool isAuto) : m_isAuto (isAuto), m_width (0), m_height (0) {} +CProjection::CProjection (bool isAuto) : + m_width (0), + m_height (0), + m_isAuto (isAuto) {} const int& CProjection::getWidth () const { return this->m_width; @@ -18,15 +24,15 @@ bool CProjection::isAuto () const { return this->m_isAuto; } -void CProjection::setWidth (int width) { +void CProjection::setWidth (int width) const { this->m_width = width; } -void CProjection::setHeight (int height) { +void CProjection::setHeight (int height) const { this->m_height = height; } -CProjection* CProjection::fromJSON (json data) { +const CProjection* CProjection::fromJSON (const json::const_iterator& data) { const auto auto_it = jsonFindDefault (data, "auto", false); const auto width_it = jsonFindRequired (data, "width", "Projection must have width"); diff --git a/src/WallpaperEngine/Core/Scenes/CProjection.h b/src/WallpaperEngine/Core/Scenes/CProjection.h index c531251..d3bfee4 100644 --- a/src/WallpaperEngine/Core/Scenes/CProjection.h +++ b/src/WallpaperEngine/Core/Scenes/CProjection.h @@ -7,22 +7,23 @@ using json = nlohmann::json; class CProjection { public: - static CProjection* fromJSON (json data); + static const CProjection* fromJSON (const json::const_iterator& data); [[nodiscard]] const int& getWidth () const; [[nodiscard]] const int& getHeight () const; [[nodiscard]] bool isAuto () const; - void setWidth (int width); - void setHeight (int height); + // TODO: CHANGE THIS SO THE RENDER IS THE ONE RESPONSIBLE FOR THIS? + void setWidth (int width) const; + void setHeight (int height) const; protected: CProjection (int width, int height); explicit CProjection (bool isAuto); private: - int m_width; - int m_height; - bool m_isAuto; + mutable int m_width; + mutable int m_height; + const bool m_isAuto; }; } // namespace WallpaperEngine::Core::Scenes diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp index 4792825..aea3a1a 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.cpp @@ -1,35 +1,53 @@ #include "CUserSettingBoolean.h" -#include "WallpaperEngine/Core/Core.h" -#include "common.h" +#include +#include "WallpaperEngine/Core/Core.h" + +#include "WallpaperEngine/Core/CProject.h" #include "WallpaperEngine/Core/Projects/CProperty.h" #include "WallpaperEngine/Core/Projects/CPropertyBoolean.h" #include "WallpaperEngine/Core/Projects/CPropertyCombo.h" #include "WallpaperEngine/Core/Projects/CPropertySlider.h" #include "WallpaperEngine/Core/Projects/CPropertyText.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Projects; using namespace WallpaperEngine::Core::UserSettings; -CUserSettingBoolean::CUserSettingBoolean (bool hasCondition, bool hasSource, bool defaultValue, std::string source, - std::string expectedValue) : - CUserSettingValue (Type), +CUserSettingBoolean::CUserSettingBoolean ( + bool hasCondition, bool defaultValue, std::shared_ptr source, std::string expectedValue +) : + CUserSettingValue (), m_hasCondition (hasCondition), - m_hasSource (hasSource), - m_default (defaultValue), - m_source (std::move (source)), - m_expectedValue (std::move (expectedValue)) {} + m_source (source), + m_expectedValue (std::move(expectedValue)) { + this->update (defaultValue); -CUserSettingBoolean* CUserSettingBoolean::fromJSON (nlohmann::json& data) { + if (this->m_source != nullptr) { + this->m_source->subscribe ([this](const Projects::CProperty* property) -> void { + if (!this->m_hasCondition) { + this->update (property->getBool ()); + } else if (property->is ()) { + this->update ( + property->as ()->translateValueToIndex (this->m_expectedValue) == property->getInt () + ); + } else { + sLog.error ("Cannot update boolean user setting for an unknown property type ", property->getType ()); + } + }); + } +} + +const CUserSettingBoolean* CUserSettingBoolean::fromJSON (const nlohmann::json& data, const CProject& project) { bool hasCondition = false; - bool hasSource = false; + std::shared_ptr sourceProperty = nullptr; bool defaultValue; std::string source; std::string expectedValue; if (data.is_object ()) { - hasSource = true; + auto animation = data.find ("animation"); auto userIt = data.find ("user"); defaultValue = jsonFindDefault (data, "value", true); // is this default value right? @@ -38,13 +56,28 @@ CUserSettingBoolean* CUserSettingBoolean::fromJSON (nlohmann::json& data) { source = *userIt; } else { hasCondition = true; - source = *jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); + source = jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); expectedValue = - *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + } + + for (const auto& [key, property] : project.getProperties ()) { + if (key == source) { + sourceProperty = property; + break; + } + } + + if (sourceProperty == nullptr) { + sLog.error ("Cannot find property ", source, " to get value from for user setting value, using default value: ", defaultValue); } } else { sLog.error ("Boolean property doesn't have user member, this could mean an scripted value"); } + + if (animation != data.end ()) { + sLog.error ("Detected a setting with animation data, which is not supported yet!"); + } } else { if (!data.is_boolean ()) sLog.error ("Expected boolean value on user setting"); @@ -52,40 +85,9 @@ CUserSettingBoolean* CUserSettingBoolean::fromJSON (nlohmann::json& data) { defaultValue = data.get (); } - return new CUserSettingBoolean (hasCondition, hasSource, defaultValue, source, expectedValue); + return new CUserSettingBoolean (hasCondition, defaultValue, sourceProperty, expectedValue); } -CUserSettingBoolean* CUserSettingBoolean::fromScalar (bool value) { - return new CUserSettingBoolean (false, false, value, "", ""); +const CUserSettingBoolean* CUserSettingBoolean::fromScalar (const bool value) { + return new CUserSettingBoolean (false, value, nullptr, ""); } - -bool CUserSettingBoolean::getDefaultValue () const { - return this->m_default; -} - -bool CUserSettingBoolean::processValue (const std::vector& properties) { - if (!this->m_hasSource && !this->m_hasCondition) - return this->getDefaultValue (); - - for (const auto cur : properties) { - if (cur->getName () != this->m_source) - continue; - - if (!this->m_hasCondition) { - if (cur->is ()) - return cur->as ()->getValue (); - - sLog.exception ("Property without condition must match type boolean"); - } - - // TODO: properly validate this as the combos might be more than just strings? - if (cur->is ()) - return cur->as ()->getValue () == this->m_expectedValue; - - sLog.exception ("Boolean property with condition doesn't match against combo value"); - } - - return this->m_default; -} - -std::string CUserSettingBoolean::Type = "boolean"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h index 09bd047..71188b1 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h @@ -1,6 +1,7 @@ #pragma once #include "CUserSettingValue.h" +#include "WallpaperEngine/Core/CProject.h" namespace WallpaperEngine::Core::Projects { class CProperty; @@ -11,21 +12,15 @@ class CUserSettingBoolean : public CUserSettingValue { public: typedef bool data_type; - static CUserSettingBoolean* fromJSON (nlohmann::json& data); - static CUserSettingBoolean* fromScalar (bool value); - static std::string Type; - - bool processValue (const std::vector& properties); - bool getDefaultValue () const; + static const CUserSettingBoolean* fromJSON (const nlohmann::json& data, const CProject& project); + static const CUserSettingBoolean* fromScalar (bool value); private: - CUserSettingBoolean (bool hasCondition, bool hasSource, bool defaultValue, std::string source, - std::string expectedValue); + CUserSettingBoolean ( + bool hasCondition, bool defaultValue, std::shared_ptr source, std::string expectedValue); - bool m_default; - bool m_hasCondition; - bool m_hasSource; - std::string m_source; - std::string m_expectedValue; + const bool m_hasCondition; + const std::string m_expectedValue; + const std::shared_ptr m_source; }; } // namespace WallpaperEngine::Core::UserSettings \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp index 2a8754c..d6ebe34 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.cpp @@ -1,44 +1,74 @@ #include "CUserSettingFloat.h" -#include "WallpaperEngine/Core/Core.h" -#include "common.h" +#include +#include "WallpaperEngine/Core/Core.h" + +#include "WallpaperEngine/Core/CProject.h" #include "WallpaperEngine/Core/Projects/CProperty.h" #include "WallpaperEngine/Core/Projects/CPropertySlider.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Projects; using namespace WallpaperEngine::Core::UserSettings; -CUserSettingFloat::CUserSettingFloat (bool hasCondition, bool hasSource, double defaultValue, std::string source, - std::string expectedValue) : - CUserSettingValue (Type), - m_hasCondition (hasCondition), - m_hasSource (hasSource), +CUserSettingFloat::CUserSettingFloat ( + bool hasCondition, float defaultValue, std::shared_ptr source, std::string expectedValue +) : + CUserSettingValue (), m_default (defaultValue), - m_source (std::move (source)), - m_expectedValue (std::move (expectedValue)) {} + m_hasCondition (hasCondition), + m_source (source), + m_expectedValue (std::move(expectedValue)) { + this->update (defaultValue); -CUserSettingFloat* CUserSettingFloat::fromJSON (nlohmann::json& data) { - double defaultValue; + if (this->m_source != nullptr) { + this->m_source->subscribe ([this](const Projects::CProperty* property) -> void { + if (!this->m_hasCondition) { + this->update (property->getFloat ()); + } else { + sLog.error ("Don't know how to check for condition on a float property... Expected value: ", this->m_expectedValue); + } + }); + } +} + +const CUserSettingFloat* CUserSettingFloat::fromJSON (const nlohmann::json& data, const CProject& project) { + float defaultValue; std::string source; std::string expectedValue; bool hasCondition = false; - bool hasSource = false; + std::shared_ptr sourceProperty = nullptr; if (data.is_object ()) { - hasSource = true; + auto animation = data.find ("animation"); auto userIt = data.find ("user"); - defaultValue = jsonFindDefault (data, "value", 1.0); // is this default value right? + defaultValue = jsonFindDefault (data, "value", 1.0f); // is this default value right? if (userIt != data.end ()) { if (userIt->is_string ()) { source = *userIt; } else { hasCondition = true; - source = *jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); + source = jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); expectedValue = - *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); } + + for (const auto& [key, property] : project.getProperties ()) { + if (key == source) { + sourceProperty = property; + break; + } + } + + if (sourceProperty == nullptr) { + sLog.error ("Cannot find property ", source, " to get value from for user setting value, using default value: ", defaultValue); + } + + if (animation != data.end ()) { + sLog.error ("Detected a setting with animation data, which is not supported yet!"); + } } else { sLog.error ("Float property doesn't have user member, this could mean an scripted value"); } @@ -46,39 +76,12 @@ CUserSettingFloat* CUserSettingFloat::fromJSON (nlohmann::json& data) { if (!data.is_number ()) sLog.exception ("Expected numeric value on user settings"); - defaultValue = data.get (); + defaultValue = data.get (); } - return new CUserSettingFloat (hasCondition, hasSource, defaultValue, source, expectedValue); + return new CUserSettingFloat (hasCondition, defaultValue, sourceProperty, expectedValue); } -CUserSettingFloat* CUserSettingFloat::fromScalar (double value) { - return new CUserSettingFloat (false, false, value, "", ""); +const CUserSettingFloat* CUserSettingFloat::fromScalar (const float value) { + return new CUserSettingFloat (false, value, nullptr, ""); } - -double CUserSettingFloat::getDefaultValue () const { - return this->m_default; -} - -double CUserSettingFloat::processValue (const std::vector& properties) { - if (!this->m_hasSource && !this->m_hasCondition) - return this->getDefaultValue (); - - for (const auto cur : properties) { - if (cur->getName () != this->m_source) - continue; - - if (!this->m_hasCondition) { - if (cur->is ()) - return cur->as ()->getValue (); - - sLog.exception ("Property without condition must match type (slider)"); - } - - sLog.exception ("Float property with condition doesn't match against combo value"); - } - - return this->m_default; -} - -std::string CUserSettingFloat::Type = "float"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h index 7ca5081..b359e63 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingFloat.h @@ -1,6 +1,7 @@ #pragma once #include "CUserSettingValue.h" +#include "WallpaperEngine/Core/CProject.h" namespace WallpaperEngine::Core::Projects { class CProperty; @@ -9,23 +10,18 @@ class CProperty; namespace WallpaperEngine::Core::UserSettings { class CUserSettingFloat : public CUserSettingValue { public: - typedef double data_type; + typedef float data_type; - static CUserSettingFloat* fromJSON (nlohmann::json& data); - static CUserSettingFloat* fromScalar (double value); - static std::string Type; - - double processValue (const std::vector& properties); - double getDefaultValue () const; + static const CUserSettingFloat* fromJSON (const nlohmann::json& data, const CProject& project); + static const CUserSettingFloat* fromScalar (float value); private: - CUserSettingFloat (bool hasCondition, bool hasSource, double defaultValue, std::string source, - std::string expectedValue); + CUserSettingFloat ( + bool hasCondition, float defaultValue, std::shared_ptr source, std::string expectedValue); - double m_default; - bool m_hasCondition; - bool m_hasSource; - std::string m_source; - std::string m_expectedValue; + const double m_default; + const bool m_hasCondition; + const std::shared_ptr m_source; + const std::string m_expectedValue; }; } // namespace WallpaperEngine::Core::UserSettings \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp index 3495739..5bcb172 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.cpp @@ -3,5 +3,3 @@ #include using namespace WallpaperEngine::Core::UserSettings; - -CUserSettingValue::CUserSettingValue (std::string type) : m_type (std::move (type)) {} \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h index b20a1cf..90ee8f7 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingValue.h @@ -2,27 +2,34 @@ #include +#include "WallpaperEngine/Core/DynamicValues/CDynamicValue.h" + namespace WallpaperEngine::Core::UserSettings { -class CUserSettingValue { +using namespace WallpaperEngine::Core::DynamicValues; + +class CUserSettingValue : public CDynamicValue { public: - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); } protected: - explicit CUserSettingValue (std::string type); - - private: - std::string m_type; + virtual ~CUserSettingValue() = default; }; } // namespace WallpaperEngine::Core::UserSettings diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp index 768c766..aa1e2da 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.cpp @@ -1,49 +1,77 @@ #include "CUserSettingVector3.h" + +#include #include "WallpaperEngine/Core/Core.h" -#include "common.h" #include "WallpaperEngine/Core/Projects/CProperty.h" #include "WallpaperEngine/Core/Projects/CPropertyColor.h" #include "WallpaperEngine/Core/Projects/CPropertySlider.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core; using namespace WallpaperEngine::Core::Projects; using namespace WallpaperEngine::Core::UserSettings; -CUserSettingVector3::CUserSettingVector3 (bool hasCondition, bool hasSource, glm::vec3 defaultValue, std::string source, - std::string expectedValue) : - CUserSettingValue (Type), +CUserSettingVector3::CUserSettingVector3 ( + bool hasCondition, glm::vec3 defaultValue, std::shared_ptr source, std::string expectedValue +) : + CUserSettingValue (), m_hasCondition (hasCondition), - m_hasSource (hasSource), - m_default (defaultValue), - m_source (std::move (source)), - m_expectedValue (std::move (expectedValue)) {} + m_source (source), + m_expectedValue (std::move(expectedValue)) { + this->update (defaultValue); -CUserSettingVector3* CUserSettingVector3::fromJSON (nlohmann::json& data) { + if (this->m_source != nullptr) { + this->m_source->subscribe ([this](const Projects::CProperty* property) -> void { + if (this->m_hasCondition) { + sLog.error ("Don't know how to check for condition on a float property... Expected value: ", this->m_expectedValue); + return; + } + + this->update (property->getVec3 ()); + }); + } +} + +const CUserSettingVector3* CUserSettingVector3::fromJSON (const nlohmann::json& data, const CProject& project) { bool hasCondition = false; - bool hasSource = false; + std::shared_ptr sourceProperty = nullptr; glm::vec3 defaultValue; std::string source; std::string expectedValue; if (data.is_object ()) { - hasSource = true; + auto animation = data.find ("animation"); auto userIt = data.find ("user"); - defaultValue = WallpaperEngine::Core::aToColorf ( - jsonFindDefault (data, "value", "").c_str ()); // is this default value right? + defaultValue = jsonFindDefault (data, "value", glm::vec3()); // is this default value right? if (userIt != data.end ()) { if (userIt->is_string ()) { source = *userIt; } else { hasCondition = true; - source = *jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); + source = jsonFindRequired (userIt, "name", "Name for conditional setting must be present"); expectedValue = - *jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + jsonFindRequired (userIt, "condition", "Condition for conditional setting must be present"); + } + + for (const auto& [key, property] : project.getProperties ()) { + if (key == source) { + sourceProperty = property; + break; + } + } + + if (sourceProperty == nullptr) { + sLog.error ("Cannot find property ", source, " to get value from for user setting value, using default value: (", defaultValue.x, ",", defaultValue.y, ",", defaultValue.z, ")"); } } else { sLog.error ("Vector property doesn't have user member, this could mean an scripted value"); } + + if (animation != data.end ()) { + sLog.error ("Detected a setting with animation data, which is not supported yet!"); + } } else { if (!data.is_string ()) sLog.exception ("Expected vector value on user settings"); @@ -51,39 +79,9 @@ CUserSettingVector3* CUserSettingVector3::fromJSON (nlohmann::json& data) { defaultValue = WallpaperEngine::Core::aToColorf (data.get ().c_str ()); } - return new CUserSettingVector3 (hasCondition, hasSource, defaultValue, source, expectedValue); + return new CUserSettingVector3 (hasCondition, defaultValue, sourceProperty, expectedValue); } -CUserSettingVector3* CUserSettingVector3::fromScalar (glm::vec3 value) { - return new CUserSettingVector3 (false, false, value, "", ""); +const CUserSettingVector3* CUserSettingVector3::fromScalar (const glm::vec3 value) { + return new CUserSettingVector3 (false, value, nullptr, ""); } - -glm::vec3 CUserSettingVector3::getDefaultValue () const { - return this->m_default; -} - -glm::vec3 CUserSettingVector3::processValue (const std::vector& properties) { - if (!this->m_hasSource && !this->m_hasCondition) - return this->getDefaultValue (); - - for (const auto cur : properties) { - if (cur->getName () != this->m_source) - continue; - - if (!this->m_hasCondition) { - if (cur->is ()) - return cur->as ()->getValue (); - if (cur->is ()) - return {cur->as ()->getValue (), cur->as ()->getValue (), - cur->as ()->getValue ()}; - - sLog.exception ("Property without condition must match type (vector3)"); - } - - sLog.exception ("Vector property with condition doesn't match against combo value"); - } - - return this->m_default; -} - -std::string CUserSettingVector3::Type = "color"; \ No newline at end of file diff --git a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h index 924936c..b3d5735 100644 --- a/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h +++ b/src/WallpaperEngine/Core/UserSettings/CUserSettingVector3.h @@ -3,6 +3,7 @@ #include #include "CUserSettingValue.h" +#include "WallpaperEngine/Core/CProject.h" namespace WallpaperEngine::Core::Projects { class CProperty; @@ -13,21 +14,16 @@ class CUserSettingVector3 : public CUserSettingValue { public: typedef glm::vec3 data_type; - static CUserSettingVector3* fromJSON (nlohmann::json& data); - static CUserSettingVector3* fromScalar (glm::vec3 value); - static std::string Type; - - glm::vec3 processValue (const std::vector& properties); - glm::vec3 getDefaultValue () const; + static const CUserSettingVector3* fromJSON (const nlohmann::json& data, const CProject& project); + static const CUserSettingVector3* fromScalar (glm::vec3 value); private: - CUserSettingVector3 (bool hasCondition, bool hasSource, glm::vec3 defaultValue, std::string source, - std::string expectedValue); + CUserSettingVector3 ( + bool hasCondition, glm::vec3 defaultValue, std::shared_ptr source, + std::string expectedValue); - glm::vec3 m_default; - bool m_hasCondition; - bool m_hasSource; - std::string m_source; - std::string m_expectedValue; + const bool m_hasCondition; + const std::shared_ptr m_source; + const std::string m_expectedValue; }; } // namespace WallpaperEngine::Core::UserSettings \ No newline at end of file diff --git a/src/WallpaperEngine/Core/Wallpapers/CScene.cpp b/src/WallpaperEngine/Core/Wallpapers/CScene.cpp index e7cce34..9e53446 100644 --- a/src/WallpaperEngine/Core/Wallpapers/CScene.cpp +++ b/src/WallpaperEngine/Core/Wallpapers/CScene.cpp @@ -1,21 +1,25 @@ #include "CScene.h" + +#include #include "WallpaperEngine/Core/CProject.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingBoolean.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingFloat.h" #include "WallpaperEngine/Core/UserSettings/CUserSettingVector3.h" -#include "WallpaperEngine/FileSystem/FileSystem.h" using namespace WallpaperEngine::Core; +using namespace WallpaperEngine::Core::Wallpapers; -CScene::CScene (CProject& project, CContainer* container, Scenes::CCamera* camera, glm::vec3 ambientColor, - CUserSettingBoolean* bloom, CUserSettingFloat* bloomStrength, CUserSettingFloat* bloomThreshold, - bool cameraFade, bool cameraParallax, double cameraParallaxAmount, double cameraParallaxDelay, - double cameraParallaxMouseInfluence, bool cameraPreview, bool cameraShake, double cameraShakeAmplitude, - double cameraShakeRoughness, double cameraShakeSpeed, CUserSettingVector3* clearColor, - Scenes::CProjection* orthogonalProjection, glm::vec3 skylightColor) : - CWallpaper (Type, project), - m_container (container), +CScene::CScene ( + std::shared_ptr project, std::shared_ptr container, const Scenes::CCamera* camera, + glm::vec3 ambientColor, const CUserSettingBoolean* bloom, const CUserSettingFloat* bloomStrength, + const CUserSettingFloat* bloomThreshold, bool cameraFade, bool cameraParallax, float cameraParallaxAmount, + float cameraParallaxDelay, float cameraParallaxMouseInfluence, bool cameraPreview, bool cameraShake, + float cameraShakeAmplitude, float cameraShakeRoughness, float cameraShakeSpeed, + const CUserSettingVector3* clearColor, const Scenes::CProjection* orthogonalProjection, glm::vec3 skylightColor +) : + CWallpaper (project), + m_container (std::move(container)), m_camera (camera), m_ambientColor (ambientColor), m_bloom (bloom), @@ -35,66 +39,63 @@ CScene::CScene (CProject& project, CContainer* container, Scenes::CCamera* camer m_orthogonalProjection (orthogonalProjection), m_skylightColor (skylightColor) {} -CScene* CScene::fromFile (const std::string& filename, CProject& project, CContainer* container) { - std::string stringContent = WallpaperEngine::FileSystem::loadFullFile (filename, container); - json content = json::parse (WallpaperEngine::FileSystem::loadFullFile (filename, container)); +std::shared_ptr CScene::fromFile ( + const std::string& filename, std::shared_ptr project, + const std::shared_ptr& container +) { + json content = json::parse (container->readFileAsString (filename)); - const auto camera_it = jsonFindRequired (content, "camera", "Scenes must have a defined camera"); const auto general_it = jsonFindRequired (content, "general", "Scenes must have a general section"); const auto objects_it = jsonFindRequired (content, "objects", "Scenes must have a list of objects to display"); // TODO: FIND IF THESE DEFAULTS ARE SENSIBLE OR NOT AND PERFORM PROPER VALIDATION WHEN CAMERA PREVIEW AND CAMERA // PARALLAX ARE PRESENT - const auto ambientcolor = jsonFindDefault (*general_it, "ambientcolor", "0 0 0"); - const auto bloom = jsonFindUserConfig (*general_it, "bloom", false); - const auto bloomstrength = jsonFindUserConfig (*general_it, "bloomstrength", 0.0); - const auto bloomthreshold = jsonFindUserConfig (*general_it, "bloomthreshold", 0.0); - const auto camerafade = jsonFindDefault (*general_it, "camerafade", false); - const auto cameraparallax = jsonFindDefault (*general_it, "cameraparallax", true); - const auto cameraparallaxamount = jsonFindDefault (*general_it, "cameraparallaxamount", 1.0f); - const auto cameraparallaxdelay = jsonFindDefault (*general_it, "cameraparallaxdelay", 0.0f); - const auto cameraparallaxmouseinfluence = - jsonFindDefault (*general_it, "cameraparallaxmouseinfluence", 1.0f); - const auto camerapreview = jsonFindDefault (*general_it, "camerapreview", false); - const auto camerashake = jsonFindDefault (*general_it, "camerashake", false); - const auto camerashakeamplitude = jsonFindDefault (*general_it, "camerashakeamplitude", 0.0f); - const auto camerashakeroughness = jsonFindDefault (*general_it, "camerashakeroughness", 0.0f); - const auto camerashakespeed = jsonFindDefault (*general_it, "camerashakespeed", 0.0f); - const auto clearcolor = jsonFindUserConfig (*general_it, "clearcolor", {1, 1, 1}); - const auto orthogonalprojection_it = - jsonFindRequired (*general_it, "orthogonalprojection", "General section must have orthogonal projection info"); - const auto skylightcolor = jsonFindDefault (*general_it, "skylightcolor", "0 0 0"); - auto* scene = new CScene ( - project, container, Scenes::CCamera::fromJSON (*camera_it), WallpaperEngine::Core::aToColorf (ambientcolor), - bloom, bloomstrength, bloomthreshold, camerafade, cameraparallax, cameraparallaxamount, cameraparallaxdelay, - cameraparallaxmouseinfluence, camerapreview, camerashake, camerashakeamplitude, camerashakeroughness, - camerashakespeed, clearcolor, Scenes::CProjection::fromJSON (*orthogonalprojection_it), - WallpaperEngine::Core::aToColorf (skylightcolor)); + auto scene = std::make_shared ( + project, container, + Scenes::CCamera::fromJSON (jsonFindRequired (content, "camera", "Scenes must have a defined camera")), + jsonFindDefault (*general_it, "ambientcolor", glm::vec3 (0, 0, 0)), + jsonFindUserConfig (*general_it, *project, "bloom", false), + jsonFindUserConfig (*general_it, *project, "bloomstrength", 0.0), + jsonFindUserConfig (*general_it, *project, "bloomthreshold", 0.0), + jsonFindDefault (*general_it, "camerafade", false), + jsonFindDefault (*general_it, "cameraparallax", true), + jsonFindDefault (*general_it, "cameraparallaxamount", 1.0f), + jsonFindDefault (*general_it, "cameraparallaxdelay", 0.0f), + jsonFindDefault (*general_it, "cameraparallaxmouseinfluence", 1.0f), + jsonFindDefault (*general_it, "camerapreview", false), + jsonFindDefault (*general_it, "camerashake", false), + jsonFindDefault (*general_it, "camerashakeamplitude", 0.0f), + jsonFindDefault (*general_it, "camerashakeroughness", 0.0f), + jsonFindDefault (*general_it, "camerashakespeed", 0.0f), + jsonFindUserConfig (*general_it, *project, "clearcolor", {1, 1, 1}), + Scenes::CProjection::fromJSON (jsonFindRequired (*general_it, "orthogonalprojection", "General section must have orthogonal projection info")), + jsonFindDefault (*general_it, "skylightcolor", glm::vec3 (0, 0, 0)) + ); for (const auto& cur : *objects_it) - scene->insertObject (CObject::fromJSON (cur, scene, container)); + scene->insertObject (CObject::fromJSON (cur, project, container)); return scene; } -const std::map& CScene::getObjects () const { +const std::map& CScene::getObjects () const { return this->m_objects; } -const std::vector& CScene::getObjectsByRenderOrder () const { +const std::vector& CScene::getObjectsByRenderOrder () const { return this->m_objectsByRenderOrder; } -void CScene::insertObject (CObject* object) { +void CScene::insertObject (const CObject* object) { /// TODO: XXXHACK -- TO REMOVE WHEN PARTICLE SUPPORT IS PROPERLY IMPLEMENTED if (object != nullptr) { - this->m_objects.insert (std::make_pair (object->getId (), object)); + this->m_objects.emplace (object->getId (), object); this->m_objectsByRenderOrder.emplace_back (object); } } -CContainer* CScene::getContainer () { +std::shared_ptr CScene::getContainer () const { return this->m_container; } @@ -106,68 +107,66 @@ const glm::vec3& CScene::getAmbientColor () const { return this->m_ambientColor; } -const bool CScene::isBloom () const { - return this->m_bloom->processValue (this->getProject ().getProperties ()); +bool CScene::isBloom () const { + return this->m_bloom->getBool (); } -double CScene::getBloomStrength () const { - return this->m_bloomStrength->processValue (this->getProject ().getProperties ()); +float CScene::getBloomStrength () const { + return this->m_bloomStrength->getFloat (); } -double CScene::getBloomThreshold () const { - return this->m_bloomThreshold->processValue (this->getProject ().getProperties ()); +float CScene::getBloomThreshold () const { + return this->m_bloomThreshold->getFloat (); } -const bool CScene::isCameraFade () const { +bool CScene::isCameraFade () const { return this->m_cameraFade; } -const bool CScene::isCameraParallax () const { +bool CScene::isCameraParallax () const { return this->m_cameraParallax; } -const double CScene::getCameraParallaxAmount () const { +float CScene::getCameraParallaxAmount () const { return this->m_cameraParallaxAmount; } -const double CScene::getCameraParallaxDelay () const { +float CScene::getCameraParallaxDelay () const { return this->m_cameraParallaxDelay; } -const double CScene::getCameraParallaxMouseInfluence () const { +float CScene::getCameraParallaxMouseInfluence () const { return this->m_cameraParallaxMouseInfluence; } -const bool CScene::isCameraPreview () const { +bool CScene::isCameraPreview () const { return this->m_cameraPreview; } -const bool CScene::isCameraShake () const { +bool CScene::isCameraShake () const { return this->m_cameraShake; } -const double CScene::getCameraShakeAmplitude () const { +float CScene::getCameraShakeAmplitude () const { return this->m_cameraShakeAmplitude; } -const double CScene::getCameraShakeRoughness () const { +float CScene::getCameraShakeRoughness () const { return this->m_cameraShakeRoughness; } -const double CScene::getCameraShakeSpeed () const { +float CScene::getCameraShakeSpeed () const { return this->m_cameraShakeSpeed; } -glm::vec3 CScene::getClearColor () const { - return this->m_clearColor->processValue (this->getProject ().getProperties ()); +const glm::vec3& CScene::getClearColor () const { + return this->m_clearColor->getVec3 (); } -Scenes::CProjection* CScene::getOrthogonalProjection () const { +const Scenes::CProjection* CScene::getOrthogonalProjection () const { return this->m_orthogonalProjection; } const glm::vec3& CScene::getSkylightColor () const { return this->m_skylightColor; } - -const std::string CScene::Type = "scene"; diff --git a/src/WallpaperEngine/Core/Wallpapers/CScene.h b/src/WallpaperEngine/Core/Wallpapers/CScene.h index 3062596..dfdff47 100644 --- a/src/WallpaperEngine/Core/Wallpapers/CScene.h +++ b/src/WallpaperEngine/Core/Wallpapers/CScene.h @@ -9,76 +9,80 @@ #include "WallpaperEngine/Core/Scenes/CProjection.h" namespace WallpaperEngine::Core { -using json = nlohmann::json; - class CObject; +} + +namespace WallpaperEngine::Core::Wallpapers { +using json = nlohmann::json; class CScene : public CWallpaper { public: - static CScene* fromFile (const std::string& filename, CProject& project, CContainer* container); + CScene ( + std::shared_ptr project, std::shared_ptr container, + const Scenes::CCamera* camera, glm::vec3 ambientColor, const CUserSettingBoolean* bloom, + const CUserSettingFloat* bloomStrength, const CUserSettingFloat* bloomThreshold, bool cameraFade, + bool cameraParallax, float cameraParallaxAmount, float cameraParallaxDelay, float cameraParallaxMouseInfluence, + bool cameraPreview, bool cameraShake, float cameraShakeAmplitude, float cameraShakeRoughness, + float cameraShakeSpeed, const CUserSettingVector3* clearColor, const Scenes::CProjection* orthogonalProjection, + glm::vec3 skylightColor); - const std::map& getObjects () const; - const std::vector& getObjectsByRenderOrder () const; + static std::shared_ptr fromFile ( + const std::string& filename, std::shared_ptr project, + const std::shared_ptr& container); + [[nodiscard]] const std::map& getObjects () const; - const glm::vec3& getAmbientColor () const; - const bool isBloom () const; - double getBloomStrength () const; - double getBloomThreshold () const; - const bool isCameraFade () const; - const bool isCameraParallax () const; - const double getCameraParallaxAmount () const; - const double getCameraParallaxDelay () const; - const double getCameraParallaxMouseInfluence () const; - const bool isCameraPreview () const; - const bool isCameraShake () const; - const double getCameraShakeAmplitude () const; - const double getCameraShakeRoughness () const; - const double getCameraShakeSpeed () const; - glm::vec3 getClearColor () const; - Scenes::CProjection* getOrthogonalProjection () const; - const glm::vec3& getSkylightColor () const; - const Scenes::CCamera* getCamera () const; + [[nodiscard]] const std::vector& getObjectsByRenderOrder () const; + [[nodiscard]] const glm::vec3& getAmbientColor () const; + [[nodiscard]] bool isBloom () const; + [[nodiscard]] float getBloomStrength () const; + [[nodiscard]] float getBloomThreshold () const; + [[nodiscard]] bool isCameraFade () const; + [[nodiscard]] bool isCameraParallax () const; + [[nodiscard]] float getCameraParallaxAmount () const; + [[nodiscard]] float getCameraParallaxDelay () const; + [[nodiscard]] float getCameraParallaxMouseInfluence () const; + [[nodiscard]] bool isCameraPreview () const; + [[nodiscard]] bool isCameraShake () const; + [[nodiscard]] float getCameraShakeAmplitude () const; + [[nodiscard]] float getCameraShakeRoughness () const; + [[nodiscard]] float getCameraShakeSpeed () const; + [[nodiscard]] const glm::vec3& getClearColor () const; + [[nodiscard]] const Scenes::CProjection* getOrthogonalProjection () const; + [[nodiscard]] const glm::vec3& getSkylightColor () const; + + [[nodiscard]] const Scenes::CCamera* getCamera () const; protected: friend class CWallpaper; - CScene (CProject& project, CContainer* container, Scenes::CCamera* camera, glm::vec3 ambientColor, - CUserSettingBoolean* bloom, CUserSettingFloat* bloomStrength, CUserSettingFloat* bloomThreshold, - bool cameraFade, bool cameraParallax, double cameraParallaxAmount, double cameraParallaxDelay, - double cameraParallaxMouseInfluence, bool cameraPreview, bool cameraShake, double cameraShakeAmplitude, - double cameraShakeRoughness, double cameraShakeSpeed, CUserSettingVector3* clearColor, - Scenes::CProjection* orthogonalProjection, glm::vec3 skylightColor); + void insertObject (const CObject* object); - static const std::string Type; - - void insertObject (CObject* object); - - CContainer* getContainer (); + [[nodiscard]] std::shared_ptr getContainer () const; private: - CContainer* m_container; - Scenes::CCamera* m_camera; + const std::shared_ptr m_container; + const Scenes::CCamera* m_camera; // data from general section on the json - glm::vec3 m_ambientColor; - CUserSettingBoolean* m_bloom; - CUserSettingFloat* m_bloomStrength; - CUserSettingFloat* m_bloomThreshold; - bool m_cameraFade; - bool m_cameraParallax; - double m_cameraParallaxAmount; - double m_cameraParallaxDelay; - double m_cameraParallaxMouseInfluence; - bool m_cameraPreview; - bool m_cameraShake; - double m_cameraShakeAmplitude; - double m_cameraShakeRoughness; - double m_cameraShakeSpeed; - CUserSettingVector3* m_clearColor; - Scenes::CProjection* m_orthogonalProjection; - glm::vec3 m_skylightColor; + const glm::vec3 m_ambientColor; + const CUserSettingBoolean* m_bloom; + const CUserSettingFloat* m_bloomStrength; + const CUserSettingFloat* m_bloomThreshold; + const bool m_cameraFade; + const bool m_cameraParallax; + const float m_cameraParallaxAmount; + const float m_cameraParallaxDelay; + const float m_cameraParallaxMouseInfluence; + const bool m_cameraPreview; + const bool m_cameraShake; + const float m_cameraShakeAmplitude; + const float m_cameraShakeRoughness; + const float m_cameraShakeSpeed; + const CUserSettingVector3* m_clearColor; + const Scenes::CProjection* m_orthogonalProjection; + const glm::vec3 m_skylightColor; - std::map m_objects; - std::vector m_objectsByRenderOrder; + std::map m_objects = {}; + std::vector m_objectsByRenderOrder = {}; }; } // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/Wallpapers/CVideo.cpp b/src/WallpaperEngine/Core/Wallpapers/CVideo.cpp index 385f0b3..31f7865 100644 --- a/src/WallpaperEngine/Core/Wallpapers/CVideo.cpp +++ b/src/WallpaperEngine/Core/Wallpapers/CVideo.cpp @@ -3,13 +3,12 @@ #include using namespace WallpaperEngine::Core; +using namespace WallpaperEngine::Core::Wallpapers; -CVideo::CVideo (std::string filename, CProject& project) : - CWallpaper (Type, project), - m_filename (std::move (filename)) {} +CVideo::CVideo (std::string filename, std::shared_ptr project) : + CWallpaper (project), + m_filename (std::move(filename)) {} -const std::string& CVideo::getFilename () { +const std::string& CVideo::getFilename () const { return this->m_filename; } - -const std::string CVideo::Type = "video"; diff --git a/src/WallpaperEngine/Core/Wallpapers/CVideo.h b/src/WallpaperEngine/Core/Wallpapers/CVideo.h index a2ace06..1391f04 100644 --- a/src/WallpaperEngine/Core/Wallpapers/CVideo.h +++ b/src/WallpaperEngine/Core/Wallpapers/CVideo.h @@ -10,18 +10,16 @@ extern "C" { #include } -namespace WallpaperEngine::Core { +namespace WallpaperEngine::Core::Wallpapers { class CVideo : public CWallpaper { public: - explicit CVideo (std::string filename, CProject& project); + CVideo (std::string filename, std::shared_ptr project); - const std::string& getFilename (); + const std::string& getFilename () const; protected: friend class CWallpaper; const std::string m_filename; - - static const std::string Type; }; } // namespace WallpaperEngine::Core diff --git a/src/WallpaperEngine/Core/Wallpapers/CWeb.cpp b/src/WallpaperEngine/Core/Wallpapers/CWeb.cpp index be38213..755a86f 100644 --- a/src/WallpaperEngine/Core/Wallpapers/CWeb.cpp +++ b/src/WallpaperEngine/Core/Wallpapers/CWeb.cpp @@ -1,14 +1,14 @@ #include "CWeb.h" -#include "common.h" #include using namespace WallpaperEngine::Core; +using namespace WallpaperEngine::Core::Wallpapers; -const std::string& CWeb::getFilename () { +const std::string& CWeb::getFilename () const { return this->m_filename; } -CWeb::CWeb (std::string filename, CProject& project) : CWallpaper (Type, project), m_filename (std::move (filename)) {} - -const std::string CWeb::Type = "web"; +CWeb::CWeb (std::string filename, std::shared_ptr project) : + CWallpaper (project), + m_filename (std::move(filename)) {} diff --git a/src/WallpaperEngine/Core/Wallpapers/CWeb.h b/src/WallpaperEngine/Core/Wallpapers/CWeb.h index ffeda01..3272a15 100644 --- a/src/WallpaperEngine/Core/Wallpapers/CWeb.h +++ b/src/WallpaperEngine/Core/Wallpapers/CWeb.h @@ -16,22 +16,16 @@ extern "C" #include } -namespace WallpaperEngine::Core -{ - class CWeb : public CWallpaper - { - public: - explicit CWeb (std::string filename, CProject& project); +namespace WallpaperEngine::Core::Wallpapers { +class CWeb : public CWallpaper { + public: + CWeb (std::string filename, std::shared_ptr project); - const std::string& getFilename (); - - protected: - friend class CWallpaper; + const std::string& getFilename () const; - const std::string m_filename; + protected: + friend class CWallpaper; - static const std::string Type; - - private: - }; + const std::string m_filename; +}; } \ No newline at end of file diff --git a/src/WallpaperEngine/FileSystem/FileSystem.cpp b/src/WallpaperEngine/FileSystem/FileSystem.cpp deleted file mode 100644 index 92c099b..0000000 --- a/src/WallpaperEngine/FileSystem/FileSystem.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// filesystem includes -#include "FileSystem.h" - -#include - -using namespace WallpaperEngine; - -std::string FileSystem::loadFullFile (const std::string& file, const WallpaperEngine::Assets::CContainer* containers) { - uint32_t length = 0; - const void* contents = containers->readFile (file, &length); - - // build a new buffer that can fit in the string - char* filedata = new char [length + 1]; - // ensure there's a null termination at the end - memset (filedata, 0, length + 1); - // copy file contents over - memcpy (filedata, contents, length); - - std::string content = filedata; - - delete [] filedata; - - return content; -} \ No newline at end of file diff --git a/src/WallpaperEngine/FileSystem/FileSystem.h b/src/WallpaperEngine/FileSystem/FileSystem.h deleted file mode 100644 index c7fe214..0000000 --- a/src/WallpaperEngine/FileSystem/FileSystem.h +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @author Alexis Maiquez Murcia - */ -#pragma once - -#include -#include -#include - -#include "WallpaperEngine/Assets/CContainer.h" - -namespace WallpaperEngine::FileSystem { -/** - * Loads a full file into an std::string - * - * @param file - * @param containers - * @return - */ -std::string loadFullFile (const std::string& file, const WallpaperEngine::Assets::CContainer* containers); -} // namespace WallpaperEngine::FileSystem diff --git a/src/WallpaperEngine/Input/CInputContext.cpp b/src/WallpaperEngine/Input/CInputContext.cpp index be57877..025b07e 100644 --- a/src/WallpaperEngine/Input/CInputContext.cpp +++ b/src/WallpaperEngine/Input/CInputContext.cpp @@ -3,12 +3,12 @@ using namespace WallpaperEngine::Input; using namespace WallpaperEngine::Render::Drivers; -CInputContext::CInputContext (CMouseInput* mouseInput) : m_mouse (mouseInput) {} +CInputContext::CInputContext (CMouseInput& mouseInput) : m_mouse (mouseInput) {} void CInputContext::update () { - this->m_mouse->update (); + this->m_mouse.update (); } const CMouseInput& CInputContext::getMouseInput () const { - return *this->m_mouse; + return this->m_mouse; } \ No newline at end of file diff --git a/src/WallpaperEngine/Input/CInputContext.h b/src/WallpaperEngine/Input/CInputContext.h index a1e09f6..46eee81 100644 --- a/src/WallpaperEngine/Input/CInputContext.h +++ b/src/WallpaperEngine/Input/CInputContext.h @@ -9,7 +9,7 @@ class CVideoDriver; namespace WallpaperEngine::Input { class CInputContext { public: - explicit CInputContext (CMouseInput* mouseInput); + explicit CInputContext (CMouseInput& mouseInput); /** * Updates input information @@ -19,6 +19,6 @@ class CInputContext { [[nodiscard]] const CMouseInput& getMouseInput () const; private: - CMouseInput* m_mouse; + CMouseInput& m_mouse; }; } // namespace WallpaperEngine::Input diff --git a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp index ce96911..1d28bb4 100644 --- a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp +++ b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.cpp @@ -5,25 +5,23 @@ using namespace WallpaperEngine::Input::Drivers; -CGLFWMouseInput::CGLFWMouseInput (Render::Drivers::CGLFWOpenGLDriver* driver) : - m_reportedPosition (), - m_mousePosition (), +CGLFWMouseInput::CGLFWMouseInput (const Render::Drivers::CGLFWOpenGLDriver& driver) : m_driver (driver) {} void CGLFWMouseInput::update () { - if (!this->m_driver->getApp ().getContext ().settings.mouse.enabled) { + if (!this->m_driver.getApp ().getContext ().settings.mouse.enabled) { this->m_reportedPosition = {0, 0}; return; } - int leftClickState = glfwGetMouseButton (this->m_driver->getWindow (), GLFW_MOUSE_BUTTON_LEFT); - int rightClickState = glfwGetMouseButton (this->m_driver->getWindow (), GLFW_MOUSE_BUTTON_RIGHT); + int leftClickState = glfwGetMouseButton (this->m_driver.getWindow (), GLFW_MOUSE_BUTTON_LEFT); + int rightClickState = glfwGetMouseButton (this->m_driver.getWindow (), GLFW_MOUSE_BUTTON_RIGHT); this->m_leftClick = leftClickState == GLFW_RELEASE ? MouseClickStatus::Released : MouseClickStatus::Clicked; this->m_rightClick = rightClickState == GLFW_RELEASE ? MouseClickStatus::Released : MouseClickStatus::Clicked; // update current mouse position - glfwGetCursorPos (this->m_driver->getWindow (), &this->m_mousePosition.x, &this->m_mousePosition.y); + glfwGetCursorPos (this->m_driver.getWindow (), &this->m_mousePosition.x, &this->m_mousePosition.y); // interpolate to the new position this->m_reportedPosition = glm::mix (this->m_reportedPosition, this->m_mousePosition, 1.0); } diff --git a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h index d6cf235..5bc2884 100644 --- a/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h +++ b/src/WallpaperEngine/Input/Drivers/CGLFWMouseInput.h @@ -14,7 +14,7 @@ namespace WallpaperEngine::Input::Drivers { */ class CGLFWMouseInput final : public CMouseInput { public: - explicit CGLFWMouseInput (Render::Drivers::CGLFWOpenGLDriver* driver); + explicit CGLFWMouseInput (const Render::Drivers::CGLFWOpenGLDriver& driver); /** * Takes current mouse position and updates it @@ -37,14 +37,14 @@ class CGLFWMouseInput final : public CMouseInput { [[nodiscard]] MouseClickStatus rightClick () const override; private: - Render::Drivers::CGLFWOpenGLDriver* m_driver; + const Render::Drivers::CGLFWOpenGLDriver& m_driver; /** * The current mouse position */ - glm::dvec2 m_mousePosition; - glm::dvec2 m_reportedPosition; - MouseClickStatus m_leftClick; - MouseClickStatus m_rightClick; + glm::dvec2 m_mousePosition = {}; + glm::dvec2 m_reportedPosition = {}; + MouseClickStatus m_leftClick = Released; + MouseClickStatus m_rightClick = Released; }; } // namespace WallpaperEngine::Input::Drivers diff --git a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp index 36940ec..b1a703e 100644 --- a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp +++ b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.cpp @@ -1,35 +1,35 @@ -#include "CWaylandMouseInput.h" #include +#include "CWaylandMouseInput.h" +#include "WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" using namespace WallpaperEngine::Input::Drivers; -CWaylandMouseInput::CWaylandMouseInput (WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* driver) : - waylandDriver (driver), - m_pos () {} +CWaylandMouseInput::CWaylandMouseInput (const WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver& driver) : + m_waylandDriver (driver) {} void CWaylandMouseInput::update () {} glm::dvec2 CWaylandMouseInput::position () const { - if (!this->waylandDriver->getApp ().getContext ().settings.mouse.enabled) { + if (!this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) { return {0, 0}; } - if (waylandDriver->viewportInFocus && waylandDriver->viewportInFocus->rendering) - return waylandDriver->viewportInFocus->mousePos; + if (m_waylandDriver.viewportInFocus && m_waylandDriver.viewportInFocus->rendering) + return m_waylandDriver.viewportInFocus->mousePos; return {0, 0}; } WallpaperEngine::Input::MouseClickStatus CWaylandMouseInput::leftClick () const { - if (waylandDriver->viewportInFocus && waylandDriver->viewportInFocus->rendering) - return waylandDriver->viewportInFocus->leftClick; + if (m_waylandDriver.viewportInFocus && m_waylandDriver.viewportInFocus->rendering) + return m_waylandDriver.viewportInFocus->leftClick; return MouseClickStatus::Released; } WallpaperEngine::Input::MouseClickStatus CWaylandMouseInput::rightClick () const { - if (waylandDriver->viewportInFocus && waylandDriver->viewportInFocus->rendering) - return waylandDriver->viewportInFocus->rightClick; + if (m_waylandDriver.viewportInFocus && m_waylandDriver.viewportInFocus->rendering) + return m_waylandDriver.viewportInFocus->rightClick; return MouseClickStatus::Released; } \ No newline at end of file diff --git a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h index 4f4a298..d3f3cd4 100644 --- a/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h +++ b/src/WallpaperEngine/Input/Drivers/CWaylandMouseInput.h @@ -3,18 +3,20 @@ #ifdef ENABLE_WAYLAND #include "WallpaperEngine/Input/CMouseInput.h" -#include "WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h" -#include "GLFW/glfw3.h" #include +namespace WallpaperEngine::Render::Drivers { +class CWaylandOpenGLDriver; +}; + namespace WallpaperEngine::Input::Drivers { /** * Handles mouse input for the background */ class CWaylandMouseInput final : public CMouseInput { public: - explicit CWaylandMouseInput (WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* driver); + explicit CWaylandMouseInput (const WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver& driver); /** * Takes current mouse position and updates it @@ -40,9 +42,9 @@ class CWaylandMouseInput final : public CMouseInput { /** * Wayland: Driver */ - WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver* waylandDriver = nullptr; + const WallpaperEngine::Render::Drivers::CWaylandOpenGLDriver& m_waylandDriver; - glm::dvec2 m_pos; + glm::dvec2 m_pos = {}; }; } // namespace WallpaperEngine::Input::Drivers diff --git a/src/WallpaperEngine/Logging/CLog.cpp b/src/WallpaperEngine/Logging/CLog.cpp index 45f35b6..9be98c6 100644 --- a/src/WallpaperEngine/Logging/CLog.cpp +++ b/src/WallpaperEngine/Logging/CLog.cpp @@ -1,6 +1,7 @@ #include "CLog.h" #include +#include using namespace WallpaperEngine::Logging; @@ -9,8 +10,9 @@ CLog::CLog () { } CLog& CLog::get () { - if (sInstance == nullptr) - sInstance.reset (new CLog ()); + if (sInstance == nullptr) { + sInstance = std::make_unique (); + } return *sInstance; } @@ -23,4 +25,4 @@ void CLog::addError (std::ostream* stream) { this->mErrors.push_back (stream); } -std::shared_ptr CLog::sInstance = nullptr; \ No newline at end of file +std::unique_ptr CLog::sInstance = nullptr; \ No newline at end of file diff --git a/src/WallpaperEngine/Logging/CLog.h b/src/WallpaperEngine/Logging/CLog.h index cff431c..9a86c91 100644 --- a/src/WallpaperEngine/Logging/CLog.h +++ b/src/WallpaperEngine/Logging/CLog.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -17,70 +18,49 @@ class CLog { void addError (std::ostream* stream); template void out (Data... data) { - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); - - ((bufferStream << std::forward (data)), ...); + std::string str = this->buildBuffer (data...); // then send it to all the outputs configured for (const auto cur : this->mOutputs) - *cur << buffer.str () << std::endl; + *cur << str << std::endl; } template void debug (Data... data) { #if (!NDEBUG) && (!ERRORONLY) - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); - - ((bufferStream << std::forward (data)), ...); + std::string str = this->buildBuffer (data...); // then send it to all the outputs configured for (const auto cur : this->mOutputs) - *cur << buffer.str () << std::endl; + *cur << str << std::endl; #endif /* DEBUG */ } template void debugerror (Data... data) { #if (!NDEBUG) && (ERRORONLY) - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); - - ((bufferStream << std::forward (data)), ...); + std::string str = this->buildBuffer (data...); // then send it to all the outputs configured for (const auto cur : this->mOutputs) - *cur << buffer.str () << std::endl; + *cur << str << std::endl; #endif /* DEBUG */ } template void error (Data... data) { - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); - - ((bufferStream << std::forward (data)), ...); + std::string str = this->buildBuffer (data...); // then send it to all the outputs configured for (const auto cur : this->mErrors) - *cur << buffer.str () << std::endl; + *cur << str << std::endl; } template [[noreturn]] void exception (Data... data) { - // buffer the string first - std::stringbuf buffer; - std::ostream bufferStream (&buffer); - - ((bufferStream << std::forward (data)), ...); - + std::string str = this->buildBuffer (data...); // then send it to all the outputs configured for (const auto cur : this->mErrors) - *cur << buffer.str () << std::endl; + *cur << str << std::endl; // now throw the exception - throw EX (buffer.str ()); + throw EX (str); } template [[noreturn]] void exception (Data... data) { @@ -90,9 +70,19 @@ class CLog { static CLog& get (); private: - std::vector mOutputs; - std::vector mErrors; - static std::shared_ptr sInstance; + template std::string buildBuffer (Data... data) { + // buffer the string first + std::stringbuf buffer; + std::ostream bufferStream (&buffer); + + ((bufferStream << std::forward (data)), ...); + + return buffer.str (); + } + + std::vector mOutputs = {}; + std::vector mErrors = {}; + static std::unique_ptr sInstance; }; } // namespace WallpaperEngine::Logging diff --git a/src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.cpp b/src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.cpp new file mode 100644 index 0000000..a54dd15 --- /dev/null +++ b/src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.cpp @@ -0,0 +1,403 @@ +#include "CPrettyPrinter.h" + +#include "WallpaperEngine/Render/Wallpapers/CVideo.h" +#include "WallpaperEngine/Render/Wallpapers/CWeb.h" +#include "WallpaperEngine/Render/Objects/CEffect.h" + +using namespace WallpaperEngine::Render; +using namespace WallpaperEngine::PrettyPrinter; +using namespace WallpaperEngine::Render::Objects; + +CPrettyPrinter::CPrettyPrinter () : + m_out (&this->m_buffer) {} + +void CPrettyPrinter::printWallpaper (const CWallpaper& wallpaper) { + bool isScene = wallpaper.is (); + bool isVideo = wallpaper.is (); + bool isWeb = wallpaper.is (); + + if (isScene) { + const auto scene = wallpaper.as (); + + this->m_out << "Scene wallpaper: "; + this->increaseIndentation (); + + const auto fbos = scene->getFBOs (); + + this->m_out << "FBOs count: " << fbos.size (); + + if (!fbos.empty()) { + this->increaseIndentation (); + + for (const auto& fbo : fbos) { + this->printFBO (*fbo.second); + } + + this->decreaseIndentation (); + } else { + this->lineEnd (); + } + + const auto objects = scene->getObjectsByRenderOrder (); + + if (!objects.empty()) { + this->m_out << "Objects count: " << objects.size (); + this->increaseIndentation (); + + for (const auto object : objects) { + if (object->is ()) { + this->printImage (*object->as ()); + } + } + + this->decreaseIndentation (); + } + + this->decreaseIndentation (); + } else if (isVideo) { + const auto video = wallpaper.as (); + + this->m_out << "Video wallpaper: " << video->getVideo ()->getFilename (); + this->lineEnd (); + } else if (isWeb) { + const auto web = wallpaper.as (); + + this->m_out << "Web wallpaper"; + this->lineEnd (); + } +} + +void CPrettyPrinter::printImage (const CImage& image) { + auto base = image.getImage (); + + this->m_out << "Image " << image.getId () << " " << base->getName () << ":"; + this->increaseIndentation (); + + const auto material = image.getMaterial (); + + if (material != nullptr) { + this->printMaterial (*image.getMaterial ()); + } + + int effects = 0; + + for (const auto effect : image.getEffects ()) { + this->printEffect (*effect, ++effects); + } + + this->decreaseIndentation (); +} + +void CPrettyPrinter::printEffect (const CEffect& effect, int effectId) { + if (effectId != 0) { + this->m_out << "Effect " << effectId << ":"; + } else { + this->m_out << "Effect:"; + } + + this->increaseIndentation (); + this->m_out << "Visibility status: " << effect.isVisible (); + this->lineEnd (); + + const auto& fbos = effect.getFBOs(); + + this->m_out << "FBOs count: " << fbos.size(); + + if (!fbos.empty()) { + this->increaseIndentation (); + + for (const auto& [name, fbo] : fbos) { + this->printFBO (*fbo); + } + + this->decreaseIndentation (); + } else { + this->lineEnd (); + } + + const auto& materials = effect.getMaterials (); + + for (const auto material : materials) { + this->printMaterial (*material); + } + + this->decreaseIndentation (); +} + +void CPrettyPrinter::printFBO (const CFBO& fbo) { + this->m_out << "FBO " << fbo.getName () << ":"; + this->increaseIndentation (); + + this->m_out << "Scale: " << fbo.getScale (); + this->lineEnd (); + this->printTextureInfo (fbo); + + this->decreaseIndentation (); +} + +void CPrettyPrinter::printMaterial (const CMaterial& material) { + const auto base = material.getMaterial (); + + this->m_out << "Material " << base->getName () << ":"; + this->increaseIndentation (); + + if (base->hasTarget ()) { + this->m_out << "Target: " << base->getTarget (); + this->lineEnd (); + } + + const auto& passes = material.getPasses (); + + this->m_out << "Passes count: " << passes.size (); + + if (!passes.empty()) { + this->increaseIndentation (); + + int passId = 0; + for (const auto pass : passes) { + this->printPass (*pass, ++passId); + } + this->decreaseIndentation (); + } else { + this->lineEnd (); + } + + const auto textureBinds = base->getTextureBinds (); + + if (!textureBinds.empty()) { + this->m_out << "Texture binds count: " << textureBinds.size (); + this->increaseIndentation (); + + for (const auto bind : textureBinds) { + this->m_out << "Bind " << bind.first << " = " << bind.second->getIndex () << "," << bind.second->getName (); + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + this->decreaseIndentation (); +} + +void CPrettyPrinter::printPass (const CPass& pass, int passId) { + const auto base = pass.getPass (); + + this->m_out << "Pass " << passId << ":"; + this->increaseIndentation (); + + if (pass.getBlendingMode () != base->getBlendingMode ()) { + this->m_out << "Render blending mode: " << pass.getBlendingMode (); + this->lineEnd (); + this->m_out << "Blending mode: " << base->getBlendingMode (); + this->lineEnd (); + } else { + this->m_out << "Blending mode: " << base->getBlendingMode (); + this->lineEnd (); + } + + this->m_out << "Culling mode: " << base->getCullingMode(); + this->lineEnd (); + this->m_out << "Depth test: " << base->getDepthTest(); + this->lineEnd (); + this->m_out << "Depth write: " << base->getDepthWrite(); + this->lineEnd (); + this->m_out << "Shader: " << base->getShader(); + this->lineEnd (); + const auto textures = base->getTextures (); + + if (!textures.empty()) { + this->m_out << "Textures " << textures.size () << ":"; + this->increaseIndentation (); + + for (const auto& texture : textures) { + this->m_out << texture.first << ": " << texture.second; + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + const auto& fragmentTextures = pass.getShader ()->getFragment ().getTextures (); + + if (!fragmentTextures.empty()) { + this->m_out << "Fragment textures " << fragmentTextures.size () << ":"; + this->increaseIndentation (); + + for (const auto& texture : fragmentTextures) { + this->m_out << texture.first << ": " << texture.second; + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + const auto& vertexTextures = pass.getShader ()->getFragment ().getTextures (); + + if (!vertexTextures.empty()) { + this->m_out << "Vertex textures " << textures.size () << ":"; + this->increaseIndentation (); + + for (const auto& texture : vertexTextures) { + this->m_out << texture.first << ": " << texture.second; + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + const auto& combos = base->getCombos(); + + if (!combos.empty()) { + this->m_out << "Combos " << combos.size () << ":"; + this->increaseIndentation (); + + for (const auto& combo : combos) { + this->m_out << combo.first << " = " << combo.second; + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + const auto& vertexCombos = pass.getShader ()->getVertex ().getDiscoveredCombos (); + + if (!vertexCombos.empty()) { + this->m_out << "Vertex combos " << vertexCombos.size () << ":"; + this->increaseIndentation (); + + for (const auto& combo : vertexCombos) { + this->m_out << combo.first << " = " << combo.second; + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + const auto& fragmentCombos = pass.getShader ()->getFragment ().getDiscoveredCombos (); + + if (!fragmentCombos.empty()) { + this->m_out << "Vertex combos " << fragmentCombos.size () << ":"; + this->increaseIndentation (); + + for (const auto& combo : fragmentCombos) { + this->m_out << combo.first << " = " << combo.second; + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + const auto& constants = base->getConstants (); + + if (!constants.empty()) { + this->m_out << "Constants " << constants.size () << ":"; + this->increaseIndentation (); + + for (const auto& constant : constants) { + this->m_out << constant.first << " = " << constant.second->toString (); + this->lineEnd (); + } + + this->decreaseIndentation (); + } + + this->decreaseIndentation (); +} + +void CPrettyPrinter::printTextureInfo (const ITexture& texture) { + this->m_out << "Texture Dimensions: " << texture.getTextureWidth(0) << "x" << texture.getTextureHeight (0); + this->lineEnd (); + this->m_out << "Part Dimensions: " << texture.getRealWidth () << "x" << texture.getRealHeight (); + this->lineEnd (); + this->m_out << "Texture format: "; + this->printTextureFormat (texture.getFormat ()); + this->lineEnd (); + this->m_out << "Texture flags: "; + this->printTextureFlags (texture.getFlags ()); + this->lineEnd (); + this->m_out << "Is animated: " << texture.isAnimated (); + this->lineEnd (); + + const auto& frames = texture.getFrames (); + + if (frames.size () > 1) { + this->m_out << frames.size () << " frames: "; + this->increaseIndentation (); + + for (const auto frame : frames) { + this->m_out << "Frame " << frame->frameNumber << ":"; + this->increaseIndentation (); + this->m_out << "Frametime " << frame->frametime; + this->lineEnd (); + this->m_out << "Position in atlas: " << frame->x << "x" << frame->y; + this->lineEnd (); + this->m_out << "Size1: " << frame->width1 << "x" << frame->height1; + this->lineEnd (); + this->m_out << "Size2: " << frame->width2 << "x" << frame->height2; + this->decreaseIndentation (); + } + + this->decreaseIndentation (); + } +} + +void CPrettyPrinter::printTextureFormat (ITexture::TextureFormat format) { + switch (format) { + case ITexture::UNKNOWN: this->m_out << "UNKNOWN"; break; + case ITexture::ARGB8888: this->m_out << "ARGB8888"; break; + case ITexture::RGB888: this->m_out << "RGB888"; break; + case ITexture::RGB565: this->m_out << "RGB565"; break; + case ITexture::DXT5: this->m_out << "DXT5"; break; + case ITexture::DXT3: this->m_out << "DXT3"; break; + case ITexture::DXT1: this->m_out << "DXT1"; break; + case ITexture::RG88: this->m_out << "RG88"; break; + case ITexture::R8: this->m_out << "R8"; break; + case ITexture::RG1616f: this->m_out << "RG1616f"; break; + case ITexture::R16f: this->m_out << "R16f"; break; + case ITexture::BC7: this->m_out << "BC7"; break; + case ITexture::RGBa1010102: this->m_out << "RGBa1010102"; break; + case ITexture::RGBA16161616f: this->m_out << "RGBA16161616f"; break; + case ITexture::RGB161616f: this->m_out << "RGB161616f"; break; + } +} + +void CPrettyPrinter::printTextureFlags (ITexture::TextureFlags flags) { + if (flags & ITexture::NoInterpolation) { + this->m_out << "No interpolation"; + } + if (flags & ITexture::ClampUVs) { + this->m_out << "Clamp UVs "; + } + if (flags & ITexture::IsGif) { + this->m_out << "Is gif "; + } + if (flags & ITexture::ClampUVsBorder) { + this->m_out << "ClampUVs border "; + } + if (flags == ITexture::NoFlags) { + this->m_out << "No flags"; + } +} + +void CPrettyPrinter::indentation () { + this->m_out << std::string(this->m_level, '\t'); +} + +void CPrettyPrinter::lineEnd () { + this->m_out << '\n'; + this->indentation (); +} + +void CPrettyPrinter::increaseIndentation () { + this->m_level ++; + this->lineEnd (); +} + +void CPrettyPrinter::decreaseIndentation () { + this->m_level --; + this->lineEnd (); +} + +std::string CPrettyPrinter::str () { + return this->m_buffer.str (); +} \ No newline at end of file diff --git a/src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.h b/src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.h new file mode 100644 index 0000000..3ba89ef --- /dev/null +++ b/src/WallpaperEngine/PrettyPrinter/CPrettyPrinter.h @@ -0,0 +1,108 @@ +#pragma once + +#include + +#include "WallpaperEngine/Render/Objects/CImage.h" + +using namespace WallpaperEngine::Render; +using namespace WallpaperEngine::Render::Objects; +using namespace WallpaperEngine::Render::Objects::Effects; + +namespace WallpaperEngine::PrettyPrinter { +/** + * Provides insights on the actual data that is being used to render the wallpaper + * to the screens + */ +class CPrettyPrinter { + public: + CPrettyPrinter (); + ~CPrettyPrinter () = default; + + /** + * Prints the information of the given wallpaper + * + * @param wallpaper + */ + void printWallpaper (const CWallpaper& wallpaper); + + /** + * Prints the information of the given image + * @param image + */ + void printImage (const CImage& image); + + /** + * Prints the information of the given effect + * + * @param effect + * @param effectId The effect ID to show on the output if required + */ + void printEffect (const CEffect& effect, int effectId = 0); + + /** + * Prints the information of the given FBO + * + * @param fbo + */ + void printFBO (const CFBO& fbo); + + /** + * Prints the information of the given material + * + * @param material + */ + void printMaterial (const CMaterial& material); + + /** + * Prints the information of the given material's pass + * + * @param pass + */ + void printPass (const CPass& pass, int passId = 0); + + /** + * @return The contents of the pretty printer buffer + */ + std::string str (); + + private: + /** + * Prints the current indentation level in tabs + */ + void indentation (); + /** + * Prints an end of line and indentates the next line to the aproppiate level + */ + void lineEnd (); + /** + * Increases the indentation level and prints a new line up to the specified level + */ + void increaseIndentation (); + /** + * Decreases the indentation level and prints a new line up to the specified level + */ + void decreaseIndentation (); + /** + * Prints a texture's format as string in-place + * + * @param format + */ + void printTextureFormat (ITexture::TextureFormat format); + /** + * Prints a texture's flags as string in-place + * + * @param flags + */ + void printTextureFlags (ITexture::TextureFlags flags); + /** + * Prints information about a given ITexture in-place + * + * @param texture + */ + void printTextureInfo (const ITexture& texture); + + int m_level = 0; + std::stringbuf m_buffer = {}; + std::ostream m_out; +}; +} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CCamera.cpp b/src/WallpaperEngine/Render/CCamera.cpp index 783cf25..423b180 100644 --- a/src/WallpaperEngine/Render/CCamera.cpp +++ b/src/WallpaperEngine/Render/CCamera.cpp @@ -6,12 +6,9 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Render; -CCamera::CCamera (CScene* scene, const Core::Scenes::CCamera* camera) : +CCamera::CCamera (Wallpapers::CScene* scene, const Core::Scenes::CCamera* camera) : m_camera (camera), - m_scene (scene), - m_isOrthogonal (false), - m_projection (), - m_lookat () { + m_scene (scene) { // get the lookat position // TODO: ENSURE THIS IS ONLY USED WHEN NOT DOING AN ORTOGRAPHIC CAMERA AS IT THROWS OFF POINTS this->m_lookat = glm::lookAt (this->getEye (), this->getCenter (), this->getUp ()); @@ -43,7 +40,7 @@ bool CCamera::isOrthogonal () const { return this->m_isOrthogonal; } -CScene* CCamera::getScene () const { +Wallpapers::CScene* CCamera::getScene () const { return this->m_scene; } diff --git a/src/WallpaperEngine/Render/CCamera.h b/src/WallpaperEngine/Render/CCamera.h index c23cc31..0496c5f 100644 --- a/src/WallpaperEngine/Render/CCamera.h +++ b/src/WallpaperEngine/Render/CCamera.h @@ -7,29 +7,31 @@ #include "WallpaperEngine/Core/Scenes/CCamera.h" -namespace WallpaperEngine::Render { +namespace WallpaperEngine::Render::Wallpapers { class CScene; +} +namespace WallpaperEngine::Render { class CCamera { public: - CCamera (CScene* scene, const Core::Scenes::CCamera* camera); + CCamera (Wallpapers::CScene* scene, const Core::Scenes::CCamera* camera); ~CCamera (); void setOrthogonalProjection (float width, float height); - const glm::vec3& getCenter () const; - const glm::vec3& getEye () const; - const glm::vec3& getUp () const; - const glm::mat4& getProjection () const; - const glm::mat4& getLookAt () const; - CScene* getScene () const; - bool isOrthogonal () const; + [[nodiscard]] const glm::vec3& getCenter () const; + [[nodiscard]] const glm::vec3& getEye () const; + [[nodiscard]] const glm::vec3& getUp () const; + [[nodiscard]] const glm::mat4& getProjection () const; + [[nodiscard]] const glm::mat4& getLookAt () const; + [[nodiscard]] Wallpapers::CScene* getScene () const; + [[nodiscard]] bool isOrthogonal () const; private: - bool m_isOrthogonal; - glm::mat4 m_projection; - glm::mat4 m_lookat; + bool m_isOrthogonal = false; + glm::mat4 m_projection = {}; + glm::mat4 m_lookat = {}; const Core::Scenes::CCamera* m_camera; - CScene* m_scene; + Wallpapers::CScene* m_scene = nullptr; }; } // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CFBO.cpp b/src/WallpaperEngine/Render/CFBO.cpp index 4605d96..d345164 100644 --- a/src/WallpaperEngine/Render/CFBO.cpp +++ b/src/WallpaperEngine/Render/CFBO.cpp @@ -1,18 +1,14 @@ #include "CFBO.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Render; CFBO::CFBO (std::string name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight) : + m_scale (scale), m_name (std::move (name)), m_format (format), - m_scale (scale), - m_flags (flags), - m_framebuffer (GL_NONE), - m_depthbuffer (GL_NONE), - m_texture (GL_NONE), - m_resolution () { + m_flags (flags) { // create an empty texture that'll be free'd so the FBO is transparent const GLenum drawBuffers [1] = {GL_COLOR_ATTACHMENT0}; // create the main framebuffer @@ -65,7 +61,7 @@ CFBO::CFBO (std::string name, ITexture::TextureFormat format, ITexture::TextureF this->m_resolution = {textureWidth, textureHeight, realWidth, realHeight}; // create the textureframe entries - auto* frame = new TextureFrame; + auto frame = std::make_shared (); frame->frameNumber = 0; frame->frametime = 0; @@ -80,10 +76,6 @@ CFBO::CFBO (std::string name, ITexture::TextureFormat format, ITexture::TextureF } CFBO::~CFBO () { - // free all the resources - for (const auto* frame : this->m_frames) - delete frame; - // free opengl texture and framebuffer glDeleteTextures (1, &this->m_texture); glDeleteFramebuffers (1, &this->m_framebuffer); @@ -97,11 +89,11 @@ const float& CFBO::getScale () const { return this->m_scale; } -const ITexture::TextureFormat CFBO::getFormat () const { +ITexture::TextureFormat CFBO::getFormat () const { return this->m_format; } -const ITexture::TextureFlags CFBO::getFlags () const { +ITexture::TextureFlags CFBO::getFlags () const { return this->m_flags; } @@ -113,27 +105,27 @@ GLuint CFBO::getDepthbuffer () const { return this->m_depthbuffer; } -const GLuint CFBO::getTextureID (uint32_t imageIndex) const { +GLuint CFBO::getTextureID (uint32_t imageIndex) const { return this->m_texture; } -const uint32_t CFBO::getTextureWidth (uint32_t imageIndex) const { +uint32_t CFBO::getTextureWidth (uint32_t imageIndex) const { return this->m_resolution.x; } -const uint32_t CFBO::getTextureHeight (uint32_t imageIndex) const { +uint32_t CFBO::getTextureHeight (uint32_t imageIndex) const { return this->m_resolution.y; } -const uint32_t CFBO::getRealWidth () const { +uint32_t CFBO::getRealWidth () const { return this->m_resolution.z; } -const uint32_t CFBO::getRealHeight () const { +uint32_t CFBO::getRealHeight () const { return this->m_resolution.w; } -const std::vector& CFBO::getFrames () const { +const std::vector>& CFBO::getFrames () const { return this->m_frames; } @@ -141,6 +133,6 @@ const glm::vec4* CFBO::getResolution () const { return &this->m_resolution; } -const bool CFBO::isAnimated () const { +bool CFBO::isAnimated () const { return false; } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CFBO.h b/src/WallpaperEngine/Render/CFBO.h index 19be83b..b3b5700 100644 --- a/src/WallpaperEngine/Render/CFBO.h +++ b/src/WallpaperEngine/Render/CFBO.h @@ -15,31 +15,31 @@ class CFBO final : public ITexture { // TODO: ADD DESTRUCTOR TO FREE RESOURCES - const std::string& getName () const; - const float& getScale () const; - const ITexture::TextureFormat getFormat () const override; - const ITexture::TextureFlags getFlags () const override; - GLuint getFramebuffer () const; - GLuint getDepthbuffer () const; - const GLuint getTextureID (uint32_t imageIndex = 0) const override; - const uint32_t getTextureWidth (uint32_t imageIndex = 0) const override; - const uint32_t getTextureHeight (uint32_t imageIndex = 0) const override; - const uint32_t getRealWidth () const override; - const uint32_t getRealHeight () const override; - const std::vector& getFrames () const override; - const glm::vec4* getResolution () const override; - const bool isAnimated () const override; + [[nodiscard]] const std::string& getName () const; + [[nodiscard]] const float& getScale () const; + [[nodiscard]] ITexture::TextureFormat getFormat () const override; + [[nodiscard]] ITexture::TextureFlags getFlags () const override; + [[nodiscard]] GLuint getFramebuffer () const; + [[nodiscard]] GLuint getDepthbuffer () const; + [[nodiscard]] GLuint getTextureID (uint32_t imageIndex) const override; + [[nodiscard]] uint32_t getTextureWidth (uint32_t imageIndex) const override; + [[nodiscard]] uint32_t getTextureHeight (uint32_t imageIndex) const override; + [[nodiscard]] uint32_t getRealWidth () const override; + [[nodiscard]] uint32_t getRealHeight () const override; + [[nodiscard]] const std::vector>& getFrames () const override; + [[nodiscard]] const glm::vec4* getResolution () const override; + [[nodiscard]] bool isAnimated () const override; private: - GLuint m_framebuffer; - GLuint m_depthbuffer; - GLuint m_texture; - glm::vec4 m_resolution; - float m_scale; - std::string m_name; - ITexture::TextureFormat m_format; - ITexture::TextureFlags m_flags; + GLuint m_framebuffer = GL_NONE; + GLuint m_depthbuffer = GL_NONE; + GLuint m_texture = GL_NONE; + glm::vec4 m_resolution = {}; + float m_scale = 0; + std::string m_name = ""; + ITexture::TextureFormat m_format = UNKNOWN; + ITexture::TextureFlags m_flags = NoFlags; /** Placeholder for frames, FBOs only have ONE */ - std::vector m_frames; + std::vector> m_frames = {}; }; } // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CObject.cpp b/src/WallpaperEngine/Render/CObject.cpp index ca05c35..ea666df 100644 --- a/src/WallpaperEngine/Render/CObject.cpp +++ b/src/WallpaperEngine/Render/CObject.cpp @@ -4,18 +4,18 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Render; +using namespace WallpaperEngine::Render::Wallpapers; -CObject::CObject (CScene* scene, std::string type, Core::CObject* object) : +CObject::CObject (Wallpapers::CScene* scene, const Core::CObject* object) : Helpers::CContextAware (scene), m_scene (scene), - m_object (object), - m_type (std::move (type)) {} + m_object (object) {} -CScene* CObject::getScene () const { +Wallpapers::CScene* CObject::getScene () const { return this->m_scene; } -CContainer* CObject::getContainer () const { +std::shared_ptr CObject::getContainer () const { return this->getScene ()->getContainer (); } diff --git a/src/WallpaperEngine/Render/CObject.h b/src/WallpaperEngine/Render/CObject.h index 77b0130..ae0656b 100644 --- a/src/WallpaperEngine/Render/CObject.h +++ b/src/WallpaperEngine/Render/CObject.h @@ -7,39 +7,45 @@ #include "WallpaperEngine/Render/Wallpapers/CScene.h" -namespace WallpaperEngine::Render { +namespace WallpaperEngine::Render::Wallpapers { class CScene; +} +namespace WallpaperEngine::Render { class CObject : public Helpers::CContextAware { public: - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); } virtual void render () = 0; - CScene* getScene () const; - CContainer* getContainer () const; - int getId () const; + [[nodiscard]] Wallpapers::CScene* getScene () const; + [[nodiscard]] std::shared_ptr getContainer () const; + [[nodiscard]] int getId () const; protected: - CObject (CScene* scene, std::string type, Core::CObject* object); - ~CObject () override = default; + CObject (Wallpapers::CScene* scene, const Core::CObject* object); + virtual ~CObject () override = default; private: - std::string m_type; - - CScene* m_scene; - Core::CObject* m_object; + Wallpapers::CScene* m_scene = nullptr; + const Core::CObject* m_object; }; } // namespace WallpaperEngine::Render \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CRenderContext.cpp b/src/WallpaperEngine/Render/CRenderContext.cpp index 87c8b6d..c644016 100644 --- a/src/WallpaperEngine/Render/CRenderContext.cpp +++ b/src/WallpaperEngine/Render/CRenderContext.cpp @@ -1,18 +1,14 @@ -#include "common.h" #include #include #include "CRenderContext.h" #include "CWallpaper.h" -#include "WallpaperEngine/Render/Wallpapers/CVideo.h" namespace WallpaperEngine::Render { -CRenderContext::CRenderContext (Drivers::CVideoDriver& driver, Input::CInputContext& input, - CWallpaperApplication& app) : +CRenderContext::CRenderContext (Drivers::CVideoDriver& driver, CWallpaperApplication& app) : m_driver (driver), m_app (app), - m_input (input), m_textureCache (new CTextureCache (*this)) {} void CRenderContext::render (Drivers::Output::COutputViewport* viewport) { @@ -38,7 +34,7 @@ void CRenderContext::render (Drivers::Output::COutputViewport* viewport) { viewport->swapOutput (); } -void CRenderContext::setWallpaper (const std::string& display, CWallpaper* wallpaper) { +void CRenderContext::setWallpaper (const std::string& display, std::shared_ptr wallpaper) { this->m_wallpapers.insert_or_assign (display, wallpaper); } @@ -48,7 +44,7 @@ void CRenderContext::setPause (bool newState) { } Input::CInputContext& CRenderContext::getInputContext () const { - return this->m_input; + return this->m_driver.getInputContext (); } const CWallpaperApplication& CRenderContext::getApp () const { @@ -63,7 +59,11 @@ const Drivers::Output::COutput& CRenderContext::getOutput () const { return this->m_driver.getOutput (); } -const ITexture* CRenderContext::resolveTexture (const std::string& name) { +std::shared_ptr CRenderContext::resolveTexture (const std::string& name) { return this->m_textureCache->resolve (name); } + +const std::map>& CRenderContext::getWallpapers () const { + return this->m_wallpapers; +} } // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CRenderContext.h b/src/WallpaperEngine/Render/CRenderContext.h index 5e51a29..97fc6f3 100644 --- a/src/WallpaperEngine/Render/CRenderContext.h +++ b/src/WallpaperEngine/Render/CRenderContext.h @@ -2,6 +2,7 @@ #include #include +#include #include "CTextureCache.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" @@ -31,28 +32,27 @@ class CTextureCache; class CRenderContext { public: - CRenderContext (Drivers::CVideoDriver& driver, Input::CInputContext& input, CWallpaperApplication& app); + CRenderContext (Drivers::CVideoDriver& driver, CWallpaperApplication& app); void render (Drivers::Output::COutputViewport* viewport); - void setWallpaper (const std::string& display, CWallpaper* wallpaper); + void setWallpaper (const std::string& display, std::shared_ptr wallpaper); void setPause (bool newState); [[nodiscard]] Input::CInputContext& getInputContext () const; [[nodiscard]] const CWallpaperApplication& getApp () const; [[nodiscard]] const Drivers::CVideoDriver& getDriver () const; [[nodiscard]] const Drivers::Output::COutput& getOutput () const; - const ITexture* resolveTexture (const std::string& name); + std::shared_ptr resolveTexture (const std::string& name); + [[nodiscard]] const std::map>& getWallpapers () const; private: /** Video driver in use */ Drivers::CVideoDriver& m_driver; /** Maps screen -> wallpaper list */ - std::map m_wallpapers; - /** Input context for interactions */ - Input::CInputContext& m_input; + std::map> m_wallpapers = {}; /** App that holds the render context */ CWallpaperApplication& m_app; /** Texture cache for the render */ - CTextureCache* m_textureCache; + CTextureCache* m_textureCache = nullptr; }; } // namespace Render } // namespace WallpaperEngine diff --git a/src/WallpaperEngine/Render/CTextureCache.cpp b/src/WallpaperEngine/Render/CTextureCache.cpp index 31a809b..b7e97e0 100644 --- a/src/WallpaperEngine/Render/CTextureCache.cpp +++ b/src/WallpaperEngine/Render/CTextureCache.cpp @@ -8,7 +8,7 @@ using namespace WallpaperEngine::Assets; CTextureCache::CTextureCache (CRenderContext& context) : Helpers::CContextAware (context) {} -const ITexture* CTextureCache::resolve (const std::string& filename) { +std::shared_ptr CTextureCache::resolve (const std::string& filename) { const auto found = this->m_textureCache.find (filename); if (found != this->m_textureCache.end ()) @@ -17,7 +17,7 @@ const ITexture* CTextureCache::resolve (const std::string& filename) { // search for the texture in all the different containers just in case for (const auto& it : this->getContext ().getApp ().getBackgrounds ()) { try { - const ITexture* texture = it.second->getContainer ()->readTexture (filename); + std::shared_ptr texture = it.second->getContainer ()->readTexture (filename); this->store (filename, texture); @@ -30,6 +30,6 @@ const ITexture* CTextureCache::resolve (const std::string& filename) { throw CAssetLoadException (filename, "Cannot find file"); } -void CTextureCache::store (const std::string& name, const ITexture* texture) { +void CTextureCache::store (const std::string& name, std::shared_ptr texture) { this->m_textureCache.insert_or_assign (name, texture); } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/CTextureCache.h b/src/WallpaperEngine/Render/CTextureCache.h index 484539c..4af38d9 100644 --- a/src/WallpaperEngine/Render/CTextureCache.h +++ b/src/WallpaperEngine/Render/CTextureCache.h @@ -2,6 +2,7 @@ #include #include +#include #include "WallpaperEngine/Assets/ITexture.h" #include "WallpaperEngine/Render/CRenderContext.h" @@ -27,7 +28,7 @@ class CTextureCache final : Helpers::CContextAware { * @param filename * @return */ - const ITexture* resolve (const std::string& filename); + std::shared_ptr resolve (const std::string& filename); /** * Registers a texture in the cache @@ -35,10 +36,10 @@ class CTextureCache final : Helpers::CContextAware { * @param name * @param texture */ - void store (const std::string& name, const ITexture* texture); + void store (const std::string& name, std::shared_ptr texture); private: /** Cached textures */ - std::map m_textureCache; + std::map> m_textureCache = {}; }; } // namespace WallpaperEngine::Render diff --git a/src/WallpaperEngine/Render/CWallpaper.cpp b/src/WallpaperEngine/Render/CWallpaper.cpp index 801bf41..3263eb8 100644 --- a/src/WallpaperEngine/Render/CWallpaper.cpp +++ b/src/WallpaperEngine/Render/CWallpaper.cpp @@ -1,31 +1,23 @@ #include "CWallpaper.h" +#include "WallpaperEngine/Logging/CLog.h" #include "WallpaperEngine/Render/Wallpapers/CScene.h" #include "WallpaperEngine/Render/Wallpapers/CVideo.h" #include "WallpaperEngine/Render/Wallpapers/CWeb.h" -#include "common.h" #include #include -#include using namespace WallpaperEngine::Render; -CWallpaper::CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRenderContext& context, - CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode) : +CWallpaper::CWallpaper ( + std::shared_ptr wallpaperData, CRenderContext& context,CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode +) : CContextAware (context), m_wallpaperData (wallpaperData), - m_type (std::move (type)), - m_destFramebuffer (GL_NONE), - m_sceneFBO (nullptr), - m_texCoordBuffer (GL_NONE), - m_positionBuffer (GL_NONE), - m_shader (GL_NONE), - g_Texture0 (GL_NONE), - a_Position (GL_NONE), - a_TexCoord (GL_NONE), - m_vaoBuffer (GL_NONE), m_audioContext (audioContext), - m_state (scalingMode) { + m_state (scalingMode, clampMode) { // generate the VAO to stop opengl from complaining glGenVertexArrays (1, &this->m_vaoBuffer); glBindVertexArray (this->m_vaoBuffer); @@ -49,11 +41,11 @@ CWallpaper::CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRend CWallpaper::~CWallpaper () = default; -CContainer* CWallpaper::getContainer () const { - return this->m_wallpaperData->getProject ().getContainer (); +std::shared_ptr CWallpaper::getContainer () const { + return this->m_wallpaperData->getProject ()->getContainer (); } -WallpaperEngine::Core::CWallpaper* CWallpaper::getWallpaperData () const { +std::shared_ptr CWallpaper::getWallpaperData () const { return this->m_wallpaperData; } @@ -237,11 +229,12 @@ void CWallpaper::setPause (bool newState) {} void CWallpaper::setupFramebuffers () { const uint32_t width = this->getWidth (); const uint32_t height = this->getHeight (); - const ITexture::TextureFlags clamp = this->getContext ().getApp ().getContext ().settings.render.window.clamp; + const ITexture::TextureFlags clamp = this->m_state.getClampingMode (); // create framebuffer for the scene - this->m_sceneFBO = this->createFBO ("_rt_FullFrameBuffer", ITexture::TextureFormat::ARGB8888, clamp, 1.0, width, - height, width, height); + this->m_sceneFBO = this->createFBO ( + "_rt_FullFrameBuffer", ITexture::TextureFormat::ARGB8888, clamp, 1.0, width, + height, width, height); this->aliasFBO ("_rt_MipMappedFrameBuffer", this->m_sceneFBO); } @@ -250,25 +243,26 @@ CAudioContext& CWallpaper::getAudioContext () { return this->m_audioContext; } -CFBO* CWallpaper::createFBO (const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, - float scale, uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, - uint32_t textureHeight) { - CFBO* fbo = new CFBO (name, format, flags, scale, realWidth, realHeight, textureWidth, textureHeight); +std::shared_ptr CWallpaper::createFBO ( + const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, + uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight +) { + std::shared_ptr fbo = std::make_shared (name, format, flags, scale, realWidth, realHeight, textureWidth, textureHeight); - this->m_fbos.insert (std::make_pair (name, fbo)); + this->m_fbos.emplace (name, fbo); return fbo; } -void CWallpaper::aliasFBO (const std::string& alias, CFBO* original) { - this->m_fbos.insert (std::make_pair (alias, original)); +void CWallpaper::aliasFBO (const std::string& alias, const std::shared_ptr& original) { + this->m_fbos.emplace (alias, original); } -const std::map& CWallpaper::getFBOs () const { +const std::map>& CWallpaper::getFBOs () const { return this->m_fbos; } -CFBO* CWallpaper::findFBO (const std::string& name) const { +std::shared_ptr CWallpaper::findFBO (const std::string& name) const { const auto it = this->m_fbos.find (name); if (it == this->m_fbos.end ()) @@ -277,20 +271,24 @@ CFBO* CWallpaper::findFBO (const std::string& name) const { return it->second; } -CFBO* CWallpaper::getFBO () const { +std::shared_ptr CWallpaper::getFBO () const { return this->m_sceneFBO; } -CWallpaper* CWallpaper::fromWallpaper (Core::CWallpaper* wallpaper, CRenderContext& context, - CAudioContext& audioContext, CWebBrowserContext& browserContext, - const CWallpaperState::TextureUVsScaling& scalingMode) { - if (wallpaper->is ()) - return new WallpaperEngine::Render::CScene (wallpaper->as (), context, audioContext, scalingMode); - if (wallpaper->is ()) - return new WallpaperEngine::Render::CVideo (wallpaper->as (), context, audioContext, scalingMode); - else if (wallpaper->is ()) - return new WallpaperEngine::Render::CWeb (wallpaper->as (), context, audioContext, browserContext, - scalingMode); - else +std::shared_ptr CWallpaper::fromWallpaper ( + std::shared_ptr wallpaper, CRenderContext& context, CAudioContext& audioContext, + WebBrowser::CWebBrowserContext* browserContext, const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode +) { + if (wallpaper->is ()) { + return std::make_shared ( + wallpaper, context, audioContext, scalingMode, clampMode); + } else if (wallpaper->is ()) { + return std::make_shared ( + wallpaper, context, audioContext, scalingMode, clampMode); + } else if (wallpaper->is ()) { + return std::make_shared ( + wallpaper, context, audioContext, *browserContext, scalingMode, clampMode); + } else sLog.exception ("Unsupported wallpaper type"); } diff --git a/src/WallpaperEngine/Render/CWallpaper.h b/src/WallpaperEngine/Render/CWallpaper.h index 57e6736..3e668df 100644 --- a/src/WallpaperEngine/Render/CWallpaper.h +++ b/src/WallpaperEngine/Render/CWallpaper.h @@ -14,13 +14,14 @@ #include "WallpaperEngine/Render/CRenderContext.h" #include "WallpaperEngine/Render/Helpers/CContextAware.h" -#include "WallpaperEngine/WebBrowser/CWebBrowserContext.h" - #include "CWallpaperState.h" using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Audio; -using namespace WallpaperEngine::WebBrowser; + +namespace WallpaperEngine::WebBrowser { +class CWebBrowserContext; +} namespace WallpaperEngine::Render { namespace Helpers { @@ -29,21 +30,27 @@ class CContextAware; class CWallpaper : public Helpers::CContextAware { public: - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); } - ~CWallpaper () override; + virtual ~CWallpaper () override; /** * Performs a render pass of the wallpaper @@ -58,7 +65,7 @@ class CWallpaper : public Helpers::CContextAware { /** * @return The container to resolve files for this wallpaper */ - [[nodiscard]] CContainer* getContainer () const; + [[nodiscard]] std::shared_ptr getContainer () const; /** * @return The current audio context for this wallpaper @@ -86,32 +93,33 @@ class CWallpaper : public Helpers::CContextAware { * @param textureHeight * @return */ - CFBO* createFBO (const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, - uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight); + std::shared_ptr createFBO ( + const std::string& name, ITexture::TextureFormat format, ITexture::TextureFlags flags, float scale, + uint32_t realWidth, uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight); /** * Creates an alias of an existing fbo * @param alias * @param original */ - void aliasFBO (const std::string& alias, CFBO* original); + void aliasFBO (const std::string& alias, const std::shared_ptr& original); /** * @return The full FBO list to work with */ - [[nodiscard]] const std::map& getFBOs () const; + [[nodiscard]] const std::map>& getFBOs () const; /** * Searches the FBO list for the given FBO * * @param name * @return */ - [[nodiscard]] CFBO* findFBO (const std::string& name) const; + [[nodiscard]] std::shared_ptr findFBO (const std::string& name) const; /** * @return The main FBO of this wallpaper */ - [[nodiscard]] CFBO* getFBO () const; + [[nodiscard]] std::shared_ptr getFBO () const; /** * Updates the UVs coordinates if window/screen/vflip/projection has changed @@ -145,13 +153,16 @@ class CWallpaper : public Helpers::CContextAware { * * @return */ - static CWallpaper* fromWallpaper (Core::CWallpaper* wallpaper, CRenderContext& context, CAudioContext& audioContext, - CWebBrowserContext& browserContext, - const CWallpaperState::TextureUVsScaling& scalingMode); + static std::shared_ptr fromWallpaper ( + std::shared_ptr wallpaper, CRenderContext& context, CAudioContext& audioContext, + WebBrowser::CWebBrowserContext* browserContext, const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode); protected: - CWallpaper (Core::CWallpaper* wallpaperData, std::string type, CRenderContext& context, CAudioContext& audioContext, - const CWallpaperState::TextureUVsScaling& scalingMode); + CWallpaper ( + std::shared_ptr wallpaperData, CRenderContext& context, + CAudioContext& audioContext, const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode); /** * Renders a frame of the wallpaper @@ -163,31 +174,29 @@ class CWallpaper : public Helpers::CContextAware { */ void setupFramebuffers (); - Core::CWallpaper* m_wallpaperData; + std::shared_ptr m_wallpaperData; - [[nodiscard]] Core::CWallpaper* getWallpaperData () const; + [[nodiscard]] std::shared_ptr getWallpaperData () const; /** The FBO used for scene output */ - CFBO* m_sceneFBO; + std::shared_ptr m_sceneFBO = nullptr; private: /** The texture used for the scene output */ - GLuint m_texCoordBuffer; - GLuint m_positionBuffer; - GLuint m_shader; + GLuint m_texCoordBuffer = GL_NONE; + GLuint m_positionBuffer = GL_NONE; + GLuint m_shader = GL_NONE; // shader variables - GLint g_Texture0; - GLint a_Position; - GLint a_TexCoord; - GLuint m_vaoBuffer; + GLint g_Texture0 = GL_NONE; + GLint a_Position = GL_NONE; + GLint a_TexCoord = GL_NONE; + GLuint m_vaoBuffer = GL_NONE; /** The framebuffer to draw the background to */ - GLuint m_destFramebuffer; + GLuint m_destFramebuffer = GL_NONE; /** Setups OpenGL's shaders for this wallpaper backbuffer */ void setupShaders (); - /** The type of background this wallpaper is */ - std::string m_type; /** List of FBOs registered for this wallpaper */ - std::map m_fbos; + std::map> m_fbos = {}; /** Audio context that is using this wallpaper */ CAudioContext& m_audioContext; /** Current Wallpaper state */ diff --git a/src/WallpaperEngine/Render/CWallpaperState.cpp b/src/WallpaperEngine/Render/CWallpaperState.cpp index c22572c..fd21f3a 100644 --- a/src/WallpaperEngine/Render/CWallpaperState.cpp +++ b/src/WallpaperEngine/Render/CWallpaperState.cpp @@ -1,9 +1,22 @@ #include "CWallpaperState.h" +#include "WallpaperEngine/Assets/ITexture.h" #include "WallpaperEngine/Logging/CLog.h" #include using namespace WallpaperEngine::Render; +CWallpaperState::CWallpaperState ( + const TextureUVsScaling& textureUVsMode, const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode) : + m_textureUVsMode (textureUVsMode) {} + +bool CWallpaperState::hasChanged ( + const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth,const int& projectionHeight +) const { + return this->viewport.width != viewport.z || this->viewport.height != viewport.w || + this->projection.width != projectionWidth || this->projection.height != projectionHeight || + this->vflip != vflip; +} + // Reset UVs to 0/1 values void CWallpaperState::resetUVs () { this->UVs.ustart = 0; @@ -123,6 +136,34 @@ template void CWallpaperState::updateText This message is for developers, if you are just user it's a bug."); } +CWallpaperState::TextureUVsScaling CWallpaperState::getTextureUVsScaling () const { + return this->m_textureUVsMode; +} + +WallpaperEngine::Assets::ITexture::TextureFlags CWallpaperState::getClampingMode () const { + return this->m_clampingMode; +} + +void CWallpaperState::setTextureUVsStrategy (CWallpaperState::TextureUVsScaling strategy) { + this->m_textureUVsMode = strategy; +} + +int CWallpaperState::getViewportWidth () const { + return this->viewport.width; +} + +int CWallpaperState::getViewportHeight () const { + return this->viewport.height; +} + +int CWallpaperState::getProjectionWidth () const { + return this->projection.width; +} + +int CWallpaperState::getProjectionHeight () const { + return this->projection.height; +} + void CWallpaperState::updateState (const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, const int& projectionHeight) { this->viewport.width = viewport.z; diff --git a/src/WallpaperEngine/Render/CWallpaperState.h b/src/WallpaperEngine/Render/CWallpaperState.h index 86b8cb3..59ceb33 100644 --- a/src/WallpaperEngine/Render/CWallpaperState.h +++ b/src/WallpaperEngine/Render/CWallpaperState.h @@ -4,6 +4,8 @@ #include #include +#include "WallpaperEngine/Assets/ITexture.h" + namespace WallpaperEngine::Render { /** * Represents current wallpaper state @@ -18,66 +20,93 @@ class CWallpaperState { StretchUVs, }; - CWallpaperState (const TextureUVsScaling& textureUVsMode) : m_textureUVsMode (textureUVsMode) {}; + CWallpaperState ( + const TextureUVsScaling& textureUVsMode, const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode); - // Compares saved state values with passed arguments - bool hasChanged (const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, - const int& projectionHeight) const { - return this->viewport.width != viewport.z || this->viewport.height != viewport.w || - this->projection.width != projectionWidth || this->projection.height != projectionHeight || - this->vflip != vflip; - } + /** + * Checks if any of the given values has changed + * @param viewport + * @param vflip + * @param projectionWidth + * @param projectionHeight + * @return + */ + [[nodiscard]] bool hasChanged ( + const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, const int& projectionHeight) const; - // Reset UVs to 0/1 values + /** + * Resets UVs to 0/1 values. + */ void resetUVs (); - // Update Us coordinates for current viewport and projection + /** + * Updates UVs coordinates for current viewport and projection + * + * @param projectionWidth + * @param projectionHeight + */ void updateUs (const int& projectionWidth, const int& projectionHeight); - // Update Vs coordinates for current viewport and projection + /** + * Updates Vs coordinates for current viewport and projection + * + * @param projectionWidth + * @param projectionHeight + */ void updateVs (const int& projectionWidth, const int& projectionHeight); - // Get texture UV coordinates - auto getTextureUVs () const { + /** + * @return Texture UV coordinates for current viewport and projection + */ + [[nodiscard]] auto getTextureUVs () const { return UVs; }; - // Set texture UV coordinates according to texture scaling mode + /** + * Updates UVs coordinates for current viewport and projection + */ template void updateTextureUVs (); // Updates state with provided values void updateState (const glm::ivec4& viewport, const bool& vflip, const int& projectionWidth, const int& projectionHeight); - // @return The texture scaling mode - TextureUVsScaling getTextureUVsScaling () const { - return m_textureUVsMode; - }; + /** + * @return The texture scaling mode + */ + [[nodiscard]] TextureUVsScaling getTextureUVsScaling () const; - // Set texture scaling mode - void setTextureUVsStrategy (const TextureUVsScaling strategy) { - m_textureUVsMode = strategy; - }; + /** + * @return The texture clamping mode. + */ + [[nodiscard]] WallpaperEngine::Assets::ITexture::TextureFlags getClampingMode () const; - // @return The width of viewport - int getViewportWidth () const { - return viewport.width; - }; + /** + * Sets the texture scaling mode + * + * @param strategy + */ + void setTextureUVsStrategy (TextureUVsScaling strategy); - // @return The height of viewport - int getViewportHeight () const { - return viewport.height; - }; + /** + * @return The width of viewport + */ + [[nodiscard]] int getViewportWidth () const; - // @return The width of viewport - int getProjectionWidth () const { - return projection.width; - }; + /** + * @return The height of viewport + */ + [[nodiscard]] int getViewportHeight () const; - // @return The height of viewport - int getProjectionHeight () const { - return projection.height; - }; + /** + * @return The width of the projection + */ + [[nodiscard]] int getProjectionWidth () const; + + /** + * @return The height of the projection + */ + [[nodiscard]] int getProjectionHeight () const; private: // Cached UVs value for texture coordinates. No need to recalculate if viewport and projection haven't changed. @@ -105,5 +134,6 @@ class CWallpaperState { // Texture scaling mode TextureUVsScaling m_textureUVsMode = TextureUVsScaling::DefaultUVs; + WallpaperEngine::Assets::ITexture::TextureFlags m_clampingMode = WallpaperEngine::Assets::ITexture::TextureFlags::NoFlags; }; } // namespace WallpaperEngine::Render \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.cpp b/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.cpp index 4cd821e..5d73167 100644 --- a/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.cpp +++ b/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.cpp @@ -1,6 +1,10 @@ #include "CGLFWOpenGLDriver.h" +#include "CVideoFactories.h" +#include "WallpaperEngine/Logging/CLog.h" #include "WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h" -#include "common.h" +#ifdef ENABLE_X11 +#include "WallpaperEngine/Render/Drivers/Output/CX11Output.h" +#endif #define GLFW_EXPOSE_NATIVE_X11 #include @@ -13,11 +17,12 @@ void CustomGLFWErrorHandler (int errorCode, const char* reason) { sLog.error ("GLFW error ", errorCode, ": ", reason); } -CGLFWOpenGLDriver::CGLFWOpenGLDriver (const char* windowTitle, CApplicationContext& context, - CWallpaperApplication& app) : - m_frameCounter (0), - m_context (context), - CVideoDriver (app) { +CGLFWOpenGLDriver::CGLFWOpenGLDriver ( + const char* windowTitle, CApplicationContext& context, CWallpaperApplication& app +) : + m_mouseInput (*this), + CVideoDriver (app, m_mouseInput), + m_context (context) { glfwSetErrorCallback (CustomGLFWErrorHandler); // initialize glfw @@ -132,9 +137,22 @@ void CGLFWOpenGLDriver::dispatchEventQueue () { this->getApp ().update (viewport); // read the full texture into the image - if (this->m_output->haveImageBuffer ()) - glReadPixels (0, 0, this->m_output->getFullWidth (), this->m_output->getFullHeight (), GL_BGRA, - GL_UNSIGNED_BYTE, this->m_output->getImageBuffer ()); + if (this->m_output->haveImageBuffer ()) { + // 4.5 supports glReadnPixels, anything older doesn't... + if (GLEW_VERSION_4_5) { + glReadnPixels (0, 0, this->m_output->getFullWidth (), this->m_output->getFullHeight (), GL_BGRA, + GL_UNSIGNED_BYTE, this->m_output->getImageBufferSize (), this->m_output->getImageBuffer ()); + } else { + // fallback to old version + glReadPixels (0, 0, this->m_output->getFullWidth (), this->m_output->getFullHeight (), GL_BGRA, GL_UNSIGNED_BYTE, this->m_output->getImageBuffer ()); + } + + GLenum error = glGetError(); + + if (error != GL_NO_ERROR) { + sLog.exception("OpenGL error when reading texture ", error); + } + } // TODO: FRAMETIME CONTROL SHOULD GO BACK TO THE CWALLPAPAERAPPLICATION ONCE ACTUAL PARTICLES ARE IMPLEMENTED // TODO: AS THOSE, MORE THAN LIKELY, WILL REQUIRE OF A DIFFERENT PROCESSING RATE @@ -158,6 +176,31 @@ void* CGLFWOpenGLDriver::getProcAddress (const char* name) const { return reinterpret_cast (glfwGetProcAddress (name)); } -GLFWwindow* CGLFWOpenGLDriver::getWindow () { +GLFWwindow* CGLFWOpenGLDriver::getWindow () const { return this->m_window; } + + +__attribute__((constructor)) void registerGLFWOpenGLDriver () { + sVideoFactories.registerDriver ( + CApplicationContext::DESKTOP_BACKGROUND, + "x11", + [](CApplicationContext& context, CWallpaperApplication& application) -> std::unique_ptr { + return std::make_unique ("wallpaperengine", context, application); + } + ); + sVideoFactories.registerDriver ( + CApplicationContext::EXPLICIT_WINDOW, + DEFAULT_WINDOW_NAME, + [](CApplicationContext& context, CWallpaperApplication& application) -> std::unique_ptr { + return std::make_unique ("wallpaperengine", context, application); + } + ); + sVideoFactories.registerDriver ( + CApplicationContext::NORMAL_WINDOW, + DEFAULT_WINDOW_NAME, + [](CApplicationContext& context, CWallpaperApplication& application) -> std::unique_ptr { + return std::make_unique ("wallpaperengine", context, application); + } + ); +} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.h b/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.h index 94e47e1..b332d1b 100644 --- a/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.h +++ b/src/WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.h @@ -2,6 +2,7 @@ #include "WallpaperEngine/Application/CApplicationContext.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" +#include "WallpaperEngine/Input/Drivers/CGLFWMouseInput.h" #include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "WallpaperEngine/Render/Drivers/Detectors/CFullScreenDetector.h" #include @@ -32,12 +33,13 @@ class CGLFWOpenGLDriver final : public CVideoDriver { void dispatchEventQueue () override; [[nodiscard]] void* getProcAddress (const char* name) const override; - GLFWwindow* getWindow (); + GLFWwindow* getWindow () const; private: CApplicationContext& m_context; - Output::COutput* m_output; - GLFWwindow* m_window; - uint32_t m_frameCounter; + Input::Drivers::CGLFWMouseInput m_mouseInput; + Output::COutput* m_output = nullptr; + GLFWwindow* m_window = nullptr; + uint32_t m_frameCounter = 0; }; } // namespace WallpaperEngine::Render::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp b/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp index fb8c98a..c278914 100644 --- a/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp +++ b/src/WallpaperEngine/Render/Drivers/CVideoDriver.cpp @@ -1,11 +1,16 @@ #include "CVideoDriver.h" +using namespace WallpaperEngine::Input; using namespace WallpaperEngine::Render::Drivers; -CVideoDriver::CVideoDriver (CWallpaperApplication& app) : m_app (app) {} - -CVideoDriver::~CVideoDriver () {} +CVideoDriver::CVideoDriver (CWallpaperApplication& app, CMouseInput& mouseInput) : + m_app (app), + m_inputContext (mouseInput) {} CWallpaperApplication& CVideoDriver::getApp () const { return this->m_app; +} + +CInputContext& CVideoDriver::getInputContext () { + return this->m_inputContext; } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CVideoDriver.h b/src/WallpaperEngine/Render/Drivers/CVideoDriver.h index d945331..b02afe3 100644 --- a/src/WallpaperEngine/Render/Drivers/CVideoDriver.h +++ b/src/WallpaperEngine/Render/Drivers/CVideoDriver.h @@ -1,6 +1,8 @@ #pragma once #include "WallpaperEngine/Render/Drivers/Output/COutput.h" +#include "WallpaperEngine/Input/CMouseInput.h" +#include "WallpaperEngine/Input/CInputContext.h" #include #include #include @@ -9,6 +11,11 @@ namespace WallpaperEngine::Application { class CWallpaperApplication; } +namespace WallpaperEngine::Input { +class CInputContext; +class CWaylandMouseInput; +} + namespace WallpaperEngine::Render::Drivers { namespace Detectors { class CFullScreenDetector; @@ -16,8 +23,8 @@ class CFullScreenDetector; class CVideoDriver { public: - explicit CVideoDriver (CWallpaperApplication& app); - virtual ~CVideoDriver (); + explicit CVideoDriver (CWallpaperApplication& app, Input::CMouseInput& mouseInput); + virtual ~CVideoDriver () = default; /** * @return The current output in use @@ -69,8 +76,14 @@ class CVideoDriver { */ [[nodiscard]] CWallpaperApplication& getApp () const; + /** + * @return The input context in use by this driver + */ + [[nodiscard]] Input::CInputContext& getInputContext (); + private: /** App that owns this driver */ CWallpaperApplication& m_app; + Input::CInputContext m_inputContext; }; } // namespace WallpaperEngine::Render::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CVideoFactories.cpp b/src/WallpaperEngine/Render/Drivers/CVideoFactories.cpp new file mode 100644 index 0000000..bf9df0f --- /dev/null +++ b/src/WallpaperEngine/Render/Drivers/CVideoFactories.cpp @@ -0,0 +1,93 @@ +#include + +#include "CVideoFactories.h" +#include "WallpaperEngine/Logging/CLog.h" +#include + +using namespace WallpaperEngine::Render::Drivers; + +CVideoFactories::CVideoFactories () { + assert (this->sInstance == nullptr); +} + +CVideoFactories& CVideoFactories::get () { + if (sInstance == nullptr) { + sInstance = std::make_unique (); + } + + return *sInstance; +} + +void CVideoFactories::registerDriver ( + CApplicationContext::WINDOW_MODE forMode, std::string xdgSessionType, + WallpaperEngine::Render::Drivers::CVideoFactories::DriverConstructionFunc factory) { + const auto cur = this->m_driverFactories.find (forMode); + + if (cur == this->m_driverFactories.end ()) { + SessionTypeToFactoryType map; + + map.emplace (xdgSessionType, factory); + this->m_driverFactories.emplace (forMode, map); + } else { + cur->second.emplace (xdgSessionType, factory); + } +} + +void CVideoFactories::registerFullscreenDetector (std::string xdgSessionType, FullscreenDetectorConstructionFunc factory) { + this->m_fullscreenFactories.emplace (xdgSessionType, factory); +} + +std::vector CVideoFactories::getRegisteredDrivers () const { + std::vector result; + + for (const auto& [windowMode, sessionTypeToFactory] : this->m_driverFactories) { + for (const auto& [xdgSessionType, _] : sessionTypeToFactory) { + result.push_back (xdgSessionType); + } + } + + auto last = std::unique (result.begin (), result.end ()); + + result.erase (last, result.end ()); + + return result; +} + +std::unique_ptr CVideoFactories::createVideoDriver ( + CApplicationContext::WINDOW_MODE mode, const std::string& xdgSessionType, + CApplicationContext& context, CWallpaperApplication& application +) { + const auto sessionTypeToFactory = this->m_driverFactories.find (mode); + + if (sessionTypeToFactory == this->m_driverFactories.end ()) { + sLog.exception ("Cannot find a driver for window mode ", mode, " and XDG_SESSION_TYPE ", xdgSessionType); + } + + // windows are a bit special, there's just one handler + // and it's not like the current map properly allows for storing this + // so hijacking the detection is probably best for now + const auto factory = + mode != Application::CApplicationContext::DESKTOP_BACKGROUND + ? sessionTypeToFactory->second.find (DEFAULT_WINDOW_NAME) + : sessionTypeToFactory->second.find (xdgSessionType); + + if (factory == sessionTypeToFactory->second.end ()) { + sLog.exception ("Cannot find a driver for window mode ", mode, " and XDG_SESSION_TYPE ", xdgSessionType); + } + + return factory->second (context, application); +} + +std::unique_ptr CVideoFactories::createFullscreenDetector ( + std::string xdgSessionType, CApplicationContext& context, CVideoDriver& driver +) { + const auto it = this->m_fullscreenFactories.find (xdgSessionType); + + if (it == this->m_fullscreenFactories.end () || !context.settings.render.pauseOnFullscreen) { + return std::make_unique (context); + } + + return it->second (context, driver); +} + +std::unique_ptr CVideoFactories::sInstance = nullptr; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CVideoFactories.h b/src/WallpaperEngine/Render/Drivers/CVideoFactories.h new file mode 100644 index 0000000..af2951b --- /dev/null +++ b/src/WallpaperEngine/Render/Drivers/CVideoFactories.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include + +#include "CVideoDriver.h" + +#define DEFAULT_WINDOW_NAME "default" + +namespace WallpaperEngine::Render::Drivers { +class CVideoFactories { + public: + using DriverConstructionFunc = std::function(CApplicationContext&, CWallpaperApplication&)>; + using FullscreenDetectorConstructionFunc = std::function(CApplicationContext&, CVideoDriver&)>; + CVideoFactories (); + + static CVideoFactories& get (); + + /** + * Adds a new handler for the given window mode and XDG_SESSION_TYPE + * + * @param forMode + * @param factory + */ + void registerDriver ( + CApplicationContext::WINDOW_MODE forMode, std::string xdgSessionType, DriverConstructionFunc factory); + + /** + * Adds a new handler for the given XDG_SESSION_TYPE + * + * @param xdgSessionType + * @param factory + */ + void registerFullscreenDetector (std::string xdgSessionType, FullscreenDetectorConstructionFunc factory); + + /** + * @return List of drivers supported over all the different window modes + */ + [[nodiscard]] std::vector getRegisteredDrivers () const; + + /** + * Calls the factory and builds the requested video driver + * + * @param mode + * @param xdgSessionType + * @return + */ + [[nodiscard]] std::unique_ptr createVideoDriver ( + CApplicationContext::WINDOW_MODE mode, const std::string& xdgSessionType, + CApplicationContext& context, CWallpaperApplication& application); + + /** + * Calls the factory and builds the requested fullscreen detector or provides a stub if not possible + * + * @return + */ + [[nodiscard]] std::unique_ptr createFullscreenDetector ( + std::string xdgSessionType, CApplicationContext& context, CVideoDriver& driver); + + private: + using SessionTypeToFullscreenDetectorType = std::map ; + using SessionTypeToFactoryType = std::map ; + using WindowModeToSessionType = std::map ; + + SessionTypeToFullscreenDetectorType m_fullscreenFactories = {}; + WindowModeToSessionType m_driverFactories = {}; + static std::unique_ptr sInstance; +}; +} // namespace WallpaperEngine::Render::Drivers + +#define sVideoFactories (WallpaperEngine::Render::Drivers::CVideoFactories::get ()) \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp index faa442f..7555e9f 100644 --- a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp +++ b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.cpp @@ -1,7 +1,7 @@ #include "CWaylandOpenGLDriver.h" +#include "CVideoFactories.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" - -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #define class _class #define namespace _namespace @@ -150,7 +150,7 @@ void CWaylandOpenGLDriver::initEGL () { sLog.exception ("eglInitialize failed!"); } - const std::string CLIENTEXTENSIONSPOSTINIT = std::string (eglQueryString (m_eglContext.display, EGL_EXTENSIONS)); + const auto CLIENTEXTENSIONSPOSTINIT = std::string (eglQueryString (m_eglContext.display, EGL_EXTENSIONS)); if (CLIENTEXTENSIONSPOSTINIT.find ("EGL_KHR_create_context") == std::string::npos) { this->finishEGL (); @@ -232,11 +232,12 @@ void CWaylandOpenGLDriver::onLayerClose (Output::CWaylandOutputViewport* viewpor } CWaylandOpenGLDriver::CWaylandOpenGLDriver (CApplicationContext& context, CWallpaperApplication& app) : - m_frameCounter (0), + m_mouseInput (*this), + CVideoDriver (app, m_mouseInput), m_output (context, *this), m_requestedExit (false), - m_context (context), - CVideoDriver (app) { + m_frameCounter (0), + m_context (context) { m_waylandContext.display = wl_display_connect (nullptr); if (!m_waylandContext.display) @@ -372,3 +373,13 @@ Output::CWaylandOutputViewport* CWaylandOpenGLDriver::surfaceToViewport (const w return nullptr; } + +__attribute__((constructor)) void registerWaylandOpenGL () { + sVideoFactories.registerDriver ( + CApplicationContext::DESKTOP_BACKGROUND, + "wayland", + [](CApplicationContext& context, CWallpaperApplication& application) -> std::unique_ptr { + return std::make_unique (context, application); + } + ); +} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h index 06683f8..27cc429 100644 --- a/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h +++ b/src/WallpaperEngine/Render/Drivers/CWaylandOpenGLDriver.h @@ -11,6 +11,7 @@ #include "WallpaperEngine/Application/CApplicationContext.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" +#include "WallpaperEngine/Input/Drivers/CWaylandMouseInput.h" #include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include "WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h" #include "WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h" @@ -83,22 +84,23 @@ class CWaylandOpenGLDriver final : public CVideoDriver { [[nodiscard]] SWaylandContext* getWaylandContext (); /** List of available screens */ - std::vector m_screens; + std::vector m_screens = {}; private: /** The output used by the driver */ Output::CWaylandOutput m_output; /** The EGL context in use */ - SEGLContext m_eglContext; + SEGLContext m_eglContext = {}; /** The Wayland context in use */ - SWaylandContext m_waylandContext; + SWaylandContext m_waylandContext = {}; mutable bool m_requestedExit; void initEGL (); void finishEGL () const; - uint32_t m_frameCounter; + uint32_t m_frameCounter = 0; CApplicationContext& m_context; + CWaylandMouseInput m_mouseInput; std::chrono::high_resolution_clock::time_point renderStart = std::chrono::high_resolution_clock::now (); }; diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp index 7e58e91..cd34d89 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.cpp @@ -1,6 +1,7 @@ #include "CWaylandFullScreenDetector.h" #include "WallpaperEngine/Logging/CLog.h" +#include "WallpaperEngine/Render/Drivers/CVideoFactories.h" #include "wlr-foreign-toplevel-management-unstable-v1-protocol.h" #include @@ -147,4 +148,14 @@ bool CWaylandFullScreenDetector::anythingFullscreen () const { void CWaylandFullScreenDetector::reset () {} + +__attribute__((constructor)) void registerWaylandFullscreenDetector () { + sVideoFactories.registerFullscreenDetector( + "wayland", + [](CApplicationContext& context, CVideoDriver& driver) -> std::unique_ptr { + return std::make_unique (context); + } + ); +} + } // namespace WallpaperEngine::Render::Drivers::Detectors diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h index 423e14f..e081f9e 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CWaylandFullScreenDetector.h @@ -25,8 +25,8 @@ class CWaylandFullScreenDetector final : public CFullScreenDetector { uint32_t m_fullscreenCount = 0; - friend void handleGlobal (void* data, struct wl_registry* registry, uint32_t name, const char* interface, - uint32_t version); + friend void handleGlobal ( + void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version); }; } // namespace WallpaperEngine::Render::Drivers::Detectors diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp index 9aa759d..8947a69 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.cpp @@ -5,6 +5,7 @@ #include #include "WallpaperEngine/Render/Drivers/CGLFWOpenGLDriver.h" +#include "WallpaperEngine/Render/Drivers/CVideoFactories.h" namespace WallpaperEngine::Render::Drivers::Detectors { void CustomXIOErrorExitHandler (Display* dsp, void* userdata) { @@ -28,10 +29,21 @@ int CustomXIOErrorHandler (Display* dsp) { return 0; } -CX11FullScreenDetector::CX11FullScreenDetector (Application::CApplicationContext& appContext, - CGLFWOpenGLDriver& driver) : +CX11FullScreenDetector::CX11FullScreenDetector ( + Application::CApplicationContext& appContext, CVideoDriver& driver +) : CFullScreenDetector (appContext), + m_display (nullptr), + m_root (0), m_driver (driver) { + try { + // attempt casting to CGLFWOpenGLDriver, this will throw if it's not possible + // so we can gracely handle the error + dynamic_cast (this->m_driver); + } catch (std::exception&) { + sLog.exception ("X11 FullScreen Detector initialized with the wrong video driver... This is a bug..."); + } + // do not use previous handler, it might stop the app under weird circumstances // these handlers might be replaced by other X11-specific functionality, they // should only be used to ignore X11 errors and nothing else @@ -47,9 +59,6 @@ CX11FullScreenDetector::~CX11FullScreenDetector () { } bool CX11FullScreenDetector::anythingFullscreen () const { - if (!this->getApplicationContext ().settings.render.pauseOnFullscreen) - return false; - // stop rendering if anything is fullscreen bool isFullscreen = false; XWindowAttributes attribs; @@ -60,14 +69,14 @@ bool CX11FullScreenDetector::anythingFullscreen () const { if (!XQueryTree (this->m_display, this->m_root, &_, &_, &children, &nchildren)) return false; - const auto ourWindow = reinterpret_cast (this->m_driver.getWindow ()); + const auto ourWindow = reinterpret_cast (dynamic_cast (this->m_driver).getWindow ()); Window parentWindow; { Window root, *schildren = nullptr; unsigned int num_children; - if (!XQueryTree (m_display, ourWindow, &root, &parentWindow, &schildren, &num_children)) + if (!XQueryTree (this->m_display, ourWindow, &root, &parentWindow, &schildren, &num_children)) return false; if (schildren) @@ -86,7 +95,7 @@ bool CX11FullScreenDetector::anythingFullscreen () const { continue; // compare width and height with the different screens we have - for (const auto& [viewport, name] : this->m_screens) { + for (const auto& [name, viewport] : this->m_screens) { if (attribs.x == viewport.x && attribs.y == viewport.y && attribs.width == viewport.z && attribs.height == viewport.w) { isFullscreen = true; @@ -142,7 +151,7 @@ void CX11FullScreenDetector::initialize () { continue; // add the screen to the list of screens - this->m_screens.push_back ({{crtc->x, crtc->y, crtc->width, crtc->height}, info->name}); + this->m_screens.emplace (std::string (info->name), glm::ivec4 (crtc->x, crtc->y, crtc->width, crtc->height)); XRRFreeCrtcInfo (crtc); } @@ -158,4 +167,13 @@ void CX11FullScreenDetector::stop () { this->m_display = nullptr; } +__attribute__((constructor)) void registerX11FullscreenDetector () { + sVideoFactories.registerFullscreenDetector( + "x11", + [](CApplicationContext& context, CVideoDriver& driver) -> std::unique_ptr { + return std::make_unique (context, driver); + } + ); +} + } // namespace WallpaperEngine::Render::Drivers::Detectors diff --git a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h index bd13965..85bceb4 100644 --- a/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h +++ b/src/WallpaperEngine/Render/Drivers/Detectors/CX11FullScreenDetector.h @@ -5,6 +5,7 @@ #include #include "CFullScreenDetector.h" +#include "WallpaperEngine/Render/Drivers/CVideoDriver.h" #include namespace WallpaperEngine::Render::Drivers { @@ -13,7 +14,7 @@ class CGLFWOpenGLDriver; namespace Detectors { class CX11FullScreenDetector final : public CFullScreenDetector { public: - CX11FullScreenDetector (Application::CApplicationContext& appContext, CGLFWOpenGLDriver& driver); + CX11FullScreenDetector (Application::CApplicationContext& appContext, CVideoDriver& driver); ~CX11FullScreenDetector () override; [[nodiscard]] bool anythingFullscreen () const override; @@ -23,15 +24,10 @@ class CX11FullScreenDetector final : public CFullScreenDetector { void initialize (); void stop (); - struct ScreenInfo { - glm::ivec4 viewport; - std::string name; - }; - - Display* m_display; + Display* m_display = nullptr; Window m_root; - std::vector m_screens; - CGLFWOpenGLDriver& m_driver; + std::map m_screens = {}; + CVideoDriver& m_driver; }; } // namespace Detectors } // namespace WallpaperEngine::Render::Drivers \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp index e566564..f4b116d 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.cpp @@ -56,6 +56,10 @@ void* CGLFWWindowOutput::getImageBuffer () const { return nullptr; } +uint32_t CGLFWWindowOutput::getImageBufferSize () const { + return 0; +} + void CGLFWWindowOutput::updateRender () const { if (this->m_context.settings.render.mode != Application::CApplicationContext::NORMAL_WINDOW) return; diff --git a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h index f7d7582..b8817f5 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CGLFWWindowOutput.h @@ -13,6 +13,7 @@ class CGLFWWindowOutput final : public COutput { bool renderMultiple () const override; bool haveImageBuffer () const override; void* getImageBuffer () const override; + uint32_t getImageBufferSize () const override; void updateRender () const override; private: diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp b/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp index 2d39f11..8948c0f 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/COutput.cpp @@ -3,8 +3,6 @@ using namespace WallpaperEngine::Render::Drivers::Output; COutput::COutput (CApplicationContext& context, CVideoDriver& driver) : - m_fullWidth (0), - m_fullHeight (0), m_context (context), m_driver (driver) {} diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutput.h b/src/WallpaperEngine/Render/Drivers/Output/COutput.h index 934f411..26e64e9 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutput.h +++ b/src/WallpaperEngine/Render/Drivers/Output/COutput.h @@ -38,12 +38,13 @@ class COutput { virtual bool haveImageBuffer () const = 0; const std::map& getViewports () const; virtual void* getImageBuffer () const = 0; + virtual uint32_t getImageBufferSize () const = 0; virtual void updateRender () const = 0; protected: - mutable int m_fullWidth; - mutable int m_fullHeight; - mutable std::map m_viewports; + mutable int m_fullWidth = 0; + mutable int m_fullHeight = 0; + mutable std::map m_viewports = {}; CApplicationContext& m_context; CVideoDriver& m_driver; }; diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp index 52f216f..5040118 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.cpp @@ -8,5 +8,3 @@ COutputViewport::COutputViewport (glm::ivec4 viewport, std::string name, bool si viewport (viewport), name (std::move (name)), single (single) {} - -COutputViewport::~COutputViewport () {} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h index be21f74..ec11d34 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h +++ b/src/WallpaperEngine/Render/Drivers/Output/COutputViewport.h @@ -7,7 +7,7 @@ namespace WallpaperEngine::Render::Drivers::Output { class COutputViewport { public: COutputViewport (glm::ivec4 viewport, std::string name, bool single = false); - virtual ~COutputViewport (); + virtual ~COutputViewport () = default; glm::ivec4 viewport; std::string name; diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp index 824b46e..49942fd 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.cpp @@ -1,7 +1,6 @@ #include "CWaylandOutput.h" #include "../CWaylandOpenGLDriver.h" #include "WallpaperEngine/Application/CWallpaperApplication.h" -#include "common.h" using namespace WallpaperEngine::Render::Drivers::Output; @@ -10,8 +9,6 @@ CWaylandOutput::CWaylandOutput (CApplicationContext& context, CWaylandOpenGLDriv updateViewports (); } -CWaylandOutput::~CWaylandOutput () {} - void CWaylandOutput::updateViewports () { m_viewports.clear (); const auto PDRIVER = dynamic_cast (&m_driver); @@ -51,4 +48,8 @@ void* CWaylandOutput::getImageBuffer () const { return nullptr; } +uint32_t CWaylandOutput::getImageBufferSize () const { + return 0; +} + void CWaylandOutput::updateRender () const {} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h index 52b840b..fc6f44f 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutput.h @@ -16,7 +16,7 @@ namespace Output { class CWaylandOutput final : public COutput { public: CWaylandOutput (CApplicationContext& context, CWaylandOpenGLDriver& driver); - ~CWaylandOutput () override; + ~CWaylandOutput () override = default; void reset () override; @@ -24,6 +24,7 @@ class CWaylandOutput final : public COutput { bool renderMultiple () const override; bool haveImageBuffer () const override; void* getImageBuffer () const override; + uint32_t getImageBufferSize () const override; void updateRender () const override; private: diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp index 91fed4d..398cade 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.cpp @@ -1,5 +1,4 @@ #include "CWaylandOutputViewport.h" -#include "WallpaperEngine/Application/CWallpaperApplication.h" #include "WallpaperEngine/Logging/CLog.h" #define class _class @@ -13,7 +12,6 @@ extern "C" { #undef namespace #undef static -#include using namespace WallpaperEngine::Render::Drivers; using namespace WallpaperEngine::Render::Drivers::Output; @@ -105,13 +103,12 @@ constexpr struct zwlr_layer_surface_v1_listener layerSurfaceListener = { CWaylandOutputViewport::CWaylandOutputViewport (CWaylandOpenGLDriver* driver, uint32_t waylandName, struct wl_registry* registry) : - m_driver (driver), + COutputViewport ({0, 0, 0, 0}, "", true), + size ({0, 0}), waylandName (waylandName), - COutputViewport ({0, 0, 0, 0}, "", true) { + m_driver (driver) { // setup output listener this->output = static_cast (wl_registry_bind (registry, waylandName, &wl_output_interface, 4)); - this->name = ""; - this->size = {0, 0}; wl_output_add_listener (output, &outputListener, this); } diff --git a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h index 9c75bb7..d091347 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CWaylandOutputViewport.h @@ -32,8 +32,8 @@ class CWaylandOutputViewport final : public COutputViewport { */ CWaylandOpenGLDriver* getDriver (); - wl_output* output; - glm::ivec2 size; + wl_output* output = nullptr; + glm::ivec2 size = {}; uint32_t waylandName; int scale = 1; bool initialized = false; @@ -69,7 +69,7 @@ class CWaylandOutputViewport final : public COutputViewport { void resize (); private: - CWaylandOpenGLDriver* m_driver; + CWaylandOpenGLDriver* m_driver = nullptr; }; } // namespace Output } // namespace WallpaperEngine::Render::Drivers diff --git a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp index 74d7778..05a13d9 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp +++ b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.cpp @@ -1,11 +1,10 @@ #include "CX11Output.h" #include "CGLFWOutputViewport.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include #include #include -#include using namespace WallpaperEngine::Render::Drivers::Output; @@ -30,7 +29,14 @@ int CustomXIOErrorHandler (Display* dsp) { return 0; } -CX11Output::CX11Output (CApplicationContext& context, CVideoDriver& driver) : COutput (context, driver) { +CX11Output::CX11Output (CApplicationContext& context, CVideoDriver& driver) : COutput (context, driver), + m_display (nullptr), + m_pixmap (None), + m_root (None), + m_gc (None), + m_imageData (nullptr), + m_imageSize (0), + m_image (nullptr) { // do not use previous handler, it might stop the app under weird circumstances XSetErrorHandler (CustomXErrorHandler); XSetIOErrorHandler (CustomXIOErrorHandler); @@ -83,10 +89,11 @@ bool CX11Output::haveImageBuffer () const { return true; } -void CX11Output::loadScreenInfo () { - // reset the viewports - this->m_viewports.clear (); +uint32_t CX11Output::getImageBufferSize () const { + return this->m_imageSize; +} +void CX11Output::loadScreenInfo () { this->m_display = XOpenDisplay (nullptr); // set the error handling to try and recover from X disconnections #ifdef HAVE_XSETIOERROREXITHANDLER @@ -163,6 +170,7 @@ void CX11Output::loadScreenInfo () { // set the window background as our pixmap XSetWindowBackgroundPixmap (this->m_display, this->m_root, this->m_pixmap); // allocate space for the image's data + this->m_imageSize = this->m_fullWidth * this->m_fullHeight * 4; this->m_imageData = new char [this->m_fullWidth * this->m_fullHeight * 4]; // create an image so we can copy it over this->m_image = XCreateImage (this->m_display, CopyFromParent, 24, ZPixmap, 0, this->m_imageData, this->m_fullWidth, diff --git a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h index 6e255c8..eb479fd 100644 --- a/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h +++ b/src/WallpaperEngine/Render/Drivers/Output/CX11Output.h @@ -21,18 +21,20 @@ class CX11Output final : public COutput { bool renderMultiple () const override; bool haveImageBuffer () const override; void* getImageBuffer () const override; + uint32_t getImageBufferSize () const override; void updateRender () const override; private: void loadScreenInfo (); void free (); - Display* m_display; + Display* m_display = nullptr; Pixmap m_pixmap; Window m_root; GC m_gc; - char* m_imageData; - XImage* m_image; - std::vector m_screens; + char* m_imageData = nullptr; + uint32_t m_imageSize = 0; + XImage* m_image = nullptr; + std::vector m_screens = {}; }; } // namespace WallpaperEngine::Render::Drivers::Output \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/CEffect.cpp b/src/WallpaperEngine/Render/Objects/CEffect.cpp index 1f3dc7a..cc62945 100644 --- a/src/WallpaperEngine/Render/Objects/CEffect.cpp +++ b/src/WallpaperEngine/Render/Objects/CEffect.cpp @@ -3,7 +3,9 @@ using namespace WallpaperEngine::Render; using namespace WallpaperEngine::Render::Objects; -CEffect::CEffect (CImage* image, Core::Objects::CEffect* effect) : m_image (image), m_effect (effect) { +CEffect::CEffect (CImage* image, const Core::Objects::CEffect* effect) : + m_image (image), + m_effect (effect) { this->generateFBOs (); this->generatePasses (); } @@ -16,12 +18,14 @@ const std::vector& CEffect::getMaterials () const { return this->m_materials; } -const CFBO* CEffect::findFBO (const std::string& name) const { - for (const auto& cur : this->m_fbos) - if (cur->getName () == name) - return cur; +std::shared_ptr CEffect::findFBO (const std::string& name) const { + const auto fbo = this->m_fbos.find (name); - return nullptr; + if (fbo == this->m_fbos.end ()) { + return nullptr; + } + + return fbo->second; } void CEffect::generatePasses () { @@ -32,16 +36,25 @@ void CEffect::generatePasses () { void CEffect::generateFBOs () { for (const auto& cur : this->m_effect->getFbos ()) { // TODO: IS THAT DIVISION OKAY? SHOULDN'T IT BE A MULTIPLICATION? WTF? - this->m_fbos.push_back (new CFBO (cur->getName (), - ITexture::TextureFormat::ARGB8888, // TODO: CHANGE - this->m_image->getTexture ()->getFlags (), // TODO: CHANGE - cur->getScale (), this->m_image->getSize ().x / cur->getScale (), - this->m_image->getSize ().y / cur->getScale (), - this->m_image->getSize ().x / cur->getScale (), - this->m_image->getSize ().y / cur->getScale ())); + this->m_fbos.emplace ( + cur->getName(), + new CFBO ( + // TODO: SET PROPER FLAGS AND FORMAT + cur->getName (), ITexture::TextureFormat::ARGB8888, + this->m_image->getTexture ()->getFlags (), cur->getScale (), + this->m_image->getSize ().x / cur->getScale (), + this->m_image->getSize ().y / cur->getScale (), + this->m_image->getSize ().x / cur->getScale (), + this->m_image->getSize ().y / cur->getScale () + ) + ); } } +const std::map>& CEffect::getFBOs () const { + return this->m_fbos; +} + bool CEffect::isVisible () const { return this->m_effect->isVisible (); } \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/CEffect.h b/src/WallpaperEngine/Render/Objects/CEffect.h index 06748cb..d76fdb6 100644 --- a/src/WallpaperEngine/Render/Objects/CEffect.h +++ b/src/WallpaperEngine/Render/Objects/CEffect.h @@ -5,6 +5,12 @@ #include "WallpaperEngine/Render/Objects/Effects/CMaterial.h" #include "WallpaperEngine/Render/Objects/Effects/CPass.h" +#include "WallpaperEngine/PrettyPrinter/CPrettyPrinter.h" + +namespace WallpaperEngine::PrettyPrinter { +class CPrettyPrinter; +} + namespace WallpaperEngine::Render::Objects::Effects { class CMaterial; } @@ -14,23 +20,28 @@ class CImage; class CEffect { public: - CEffect (CImage* image, Core::Objects::CEffect* effect); + CEffect (CImage* image, const Core::Objects::CEffect* effect); - CImage* getImage () const; + [[nodiscard]] CImage* getImage () const; - const std::vector& getMaterials () const; + [[nodiscard]] const std::vector& getMaterials () const; - const CFBO* findFBO (const std::string& name) const; - bool isVisible () const; + [[nodiscard]] std::shared_ptr findFBO (const std::string& name) const; + [[nodiscard]] bool isVisible () const; + + protected: + friend class WallpaperEngine::PrettyPrinter::CPrettyPrinter; + + [[nodiscard]] const std::map>& getFBOs () const; private: void generatePasses (); void generateFBOs (); - CImage* m_image; - Core::Objects::CEffect* m_effect; + CImage* m_image = nullptr; + const Core::Objects::CEffect* m_effect; - std::vector m_fbos; - std::vector m_materials; + std::map> m_fbos = {}; + std::vector m_materials = {}; }; } // namespace WallpaperEngine::Render::Objects diff --git a/src/WallpaperEngine/Render/Objects/CImage.cpp b/src/WallpaperEngine/Render/Objects/CImage.cpp index 4ab155b..4438009 100644 --- a/src/WallpaperEngine/Render/Objects/CImage.cpp +++ b/src/WallpaperEngine/Render/Objects/CImage.cpp @@ -4,26 +4,28 @@ using namespace WallpaperEngine; using namespace WallpaperEngine::Render::Objects; -CImage::CImage (CScene* scene, Core::Objects::CImage* image) : - Render::CObject (scene, Type, image), - m_image (image), - m_animationTime (0.0), - m_material (nullptr), - m_colorBlendMaterial (nullptr), +CImage::CImage (Wallpapers::CScene* scene, const Core::Objects::CImage* image) : + Render::CObject (scene, image), m_texture (nullptr), - m_initialized (false), m_sceneSpacePosition (GL_NONE), m_copySpacePosition (GL_NONE), + m_passSpacePosition (GL_NONE), m_texcoordCopy (GL_NONE), m_texcoordPass (GL_NONE), - m_passSpacePosition (GL_NONE), m_modelViewProjectionScreen (), - m_modelViewProjectionScreenInverse (), - m_modelViewProjectionCopy (), - m_modelViewProjectionCopyInverse (), m_modelViewProjectionPass (glm::mat4 (1.0)), + m_modelViewProjectionCopy (), + m_modelViewProjectionScreenInverse (), m_modelViewProjectionPassInverse (glm::inverse (m_modelViewProjectionPass)), - m_pos () { + m_modelViewProjectionCopyInverse (), + m_modelMatrix(), + m_viewProjectionMatrix(), + m_image (image), + m_material (nullptr), + m_colorBlendMaterial (nullptr), + m_pos (), + m_animationTime (0.0), + m_initialized (false) { auto projection = this->getScene ()->getScene ()->getOrthogonalProjection (); // get scene width and height to calculate positions @@ -77,7 +79,7 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : auto textures = (*this->m_image->getMaterial ()->getPasses ().begin ())->getTextures (); if (!textures.empty ()) { - std::string textureName = *textures.begin (); + std::string textureName = textures.begin ()->second; if (textureName.find ("_rt_") == 0) { this->m_texture = this->getScene ()->findFBO (textureName); @@ -86,10 +88,17 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : this->m_texture = this->getContext ().resolveTexture (textureName); } } else { + if (this->m_image->getMaterial ()->isSolidLayer()) { + size.x = scene_width; + size.y = scene_height; + } + // if (this->m_image->isSolid ()) // layer receives cursor events: https://docs.wallpaperengine.io/en/scene/scenescript/reference/event/cursor.html + // same applies to effects // TODO: create a dummy texture of correct size, fbo constructors should be enough, but this should be properly // handled - this->m_texture = new CFBO ("", ITexture::TextureFormat::ARGB8888, ITexture::TextureFlags::NoFlags, 1, size.x, - size.y, size.x, size.y); + this->m_texture = std::make_shared ( + "", ITexture::TextureFormat::ARGB8888, ITexture::TextureFlags::NoFlags, 1, size.x, + size.y, size.x, size.y); } // register both FBOs into the scene @@ -101,12 +110,10 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : this->m_currentMainFBO = this->m_mainFBO = scene->createFBO (nameA.str (), ITexture::TextureFormat::ARGB8888, this->m_texture->getFlags (), 1, - this->m_texture->getRealWidth (), this->m_texture->getRealHeight (), - this->m_texture->getRealWidth (), this->m_texture->getRealHeight ()); + size.x, size.y, size.x, size.y); this->m_currentSubFBO = this->m_subFBO = scene->createFBO (nameB.str (), ITexture::TextureFormat::ARGB8888, this->m_texture->getFlags (), 1, - this->m_texture->getRealWidth (), this->m_texture->getRealHeight (), - this->m_texture->getRealWidth (), this->m_texture->getRealHeight ()); + size.x, size.y, size.x, size.y); // build a list of vertices, these might need some change later (or maybe invert the camera) GLfloat sceneSpacePosition [] = {this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f, @@ -119,14 +126,14 @@ CImage::CImage (CScene* scene, Core::Objects::CImage* image) : if (this->getTexture ()->isAnimated ()) { // animated images use different coordinates as they're essentially a texture atlas width = static_cast (this->getTexture ()->getRealWidth ()) / - static_cast (this->getTexture ()->getTextureWidth ()); + static_cast (this->getTexture ()->getTextureWidth (0)); height = static_cast (this->getTexture ()->getRealHeight ()) / - static_cast (this->getTexture ()->getTextureHeight ()); + static_cast (this->getTexture ()->getTextureHeight (0)); } // calculate the correct texCoord limits for the texture based on the texture screen size and real size else if (this->getTexture () != nullptr && - (this->getTexture ()->getTextureWidth () != this->getTexture ()->getRealWidth () || - this->getTexture ()->getTextureHeight () != this->getTexture ()->getRealHeight ())) { + (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth () || + this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())) { uint32_t x = 1; uint32_t y = 1; @@ -224,17 +231,20 @@ void CImage::setup () { if (this->getImage ()->isPassthrough () && this->getImage ()->getEffects ().empty ()) return; - { - // generate the main material used to render the image - this->m_material = new Effects::CMaterial ( - new CEffect (this, new Core::Objects::CEffect ("", "", "", "", this->m_image, - Core::UserSettings::CUserSettingBoolean::fromScalar (true))), - this->m_image->getMaterial ()); + // generate the main material used to render the image + this->m_material = new Effects::CMaterial ( + new CEffect ( + this, + new Core::Objects::CEffect ( + "", "", "", "", this->m_image->getProject (), + Core::UserSettings::CUserSettingBoolean::fromScalar (true), + {}, {}, {})), + this->m_image->getMaterial () + ); - // add blendmode to the combos - for (const auto& cur : this->m_material->getPasses ()) - this->m_passes.push_back (cur); - } + // add blendmode to the combos + for (const auto& cur : this->m_material->getPasses ()) + this->m_passes.push_back (cur); // prepare the passes list if (!this->getImage ()->getEffects ().empty ()) { @@ -251,17 +261,23 @@ void CImage::setup () { } if (this->m_image->getColorBlendMode () > 0) { - const auto material = - Core::Objects::Images::CMaterial::fromFile ("materials/util/effectpassthrough.json", this->getContainer ()); + Core::Objects::Images::CMaterial::OverrideInfo overrides; - // effectpasshthrough only has one pass - (*material->getPasses ().begin ())->insertCombo ("BLENDMODE", this->m_image->getColorBlendMode ()); + overrides.combos.emplace ("BLENDMODE", this->m_image->getColorBlendMode ()); + const auto material = + Core::Objects::Images::CMaterial::fromFile ("materials/util/effectpassthrough.json", this->getContainer (), false, {}, &overrides); // generate the main material used to render the image this->m_colorBlendMaterial = new Effects::CMaterial ( - new CEffect (this, new Core::Objects::CEffect ("", "", "", "", this->m_image, - Core::UserSettings::CUserSettingBoolean::fromScalar (true))), - material); + new CEffect ( + this, + new Core::Objects::CEffect ( + "", "", "", "", this->m_image->getProject (), + Core::UserSettings::CUserSettingBoolean::fromScalar (true), {}, {}, {} + ) + ), + material + ); // add blendmode to the combos for (const auto& cur : this->m_colorBlendMaterial->getPasses ()) @@ -273,8 +289,8 @@ void CImage::setup () { const auto first = this->m_passes.begin (); const auto last = this->m_passes.rbegin (); - (*last)->getPass ()->setBlendingMode ((*first)->getPass ()->getBlendingMode ()); - (*first)->getPass ()->setBlendingMode ("normal"); + (*last)->setBlendingMode ((*first)->getBlendingMode ()); + (*first)->setBlendingMode ("normal"); } // calculate full animation time (if any) @@ -289,8 +305,8 @@ void CImage::setup () { void CImage::setupPasses () { // do a pass on everything and setup proper inputs and values - const CFBO* drawTo = this->m_currentMainFBO; - const ITexture* asInput = this->getTexture (); + std::shared_ptr drawTo = this->m_currentMainFBO; + std::shared_ptr asInput = this->getTexture (); GLuint texcoord = this->getTexCoordCopy (); auto cur = this->m_passes.begin (); @@ -300,7 +316,7 @@ void CImage::setupPasses () { for (; cur != end; ++cur) { // TODO: PROPERLY CHECK EFFECT'S VISIBILITY AND TAKE IT INTO ACCOUNT Effects::CPass* pass = *cur; - const CFBO* prevDrawTo = drawTo; + std::shared_ptr prevDrawTo = drawTo; GLuint spacePosition = (first) ? this->getCopySpacePosition () : this->getPassSpacePosition (); const glm::mat4* projection = (first) ? &this->m_modelViewProjectionCopy : &this->m_modelViewProjectionPass; const glm::mat4* inverseProjection = @@ -346,10 +362,10 @@ void CImage::setupPasses () { } } -void CImage::pinpongFramebuffer (const CFBO** drawTo, const ITexture** asInput) { +void CImage::pinpongFramebuffer (std::shared_ptr* drawTo, std::shared_ptr* asInput) { // temporarily store FBOs used - CFBO* currentMainFBO = this->m_currentMainFBO; - CFBO* currentSubFBO = this->m_currentSubFBO; + std::shared_ptr currentMainFBO = this->m_currentMainFBO; + std::shared_ptr currentSubFBO = this->m_currentSubFBO; if (drawTo != nullptr) *drawTo = currentSubFBO; @@ -367,9 +383,6 @@ void CImage::render () { if (!this->m_initialized) return; - if (!this->getImage()->isVisible()) - return; - glColorMask (true, true, true, true); // update the position if required @@ -407,6 +420,11 @@ void CImage::render () { } void CImage::updateScreenSpacePosition () { + // do not perform any changes to the image based on the parallax if it was explicitly disabled + if (this->getScene ()->getContext ().getApp ().getContext ().settings.mouse.disableparallax) { + return; + } + const double parallaxAmount = this->getScene ()->getScene ()->getCameraParallaxAmount (); const glm::vec2 depth = this->getImage ()->getParallaxDepth (); const glm::vec2* displacement = this->getScene ()->getParallaxDisplacement (); @@ -419,7 +437,7 @@ void CImage::updateScreenSpacePosition () { {x, y, 0.0f}); } -const ITexture* CImage::getTexture () const { +std::shared_ptr CImage::getTexture () const { return this->m_texture; } @@ -435,6 +453,10 @@ const std::vector& CImage::getEffects () const { return this->m_effects; } +const Effects::CMaterial* CImage::getMaterial () const { + return this->m_material; +} + glm::vec2 CImage::getSize () const { if (this->m_texture == nullptr) return this->getImage ()->getSize (); @@ -461,5 +483,3 @@ GLuint CImage::getTexCoordCopy () const { GLuint CImage::getTexCoordPass () const { return this->m_texcoordPass; } - -const std::string CImage::Type = "image"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/CImage.h b/src/WallpaperEngine/Render/Objects/CImage.h index 649be5b..5003479 100644 --- a/src/WallpaperEngine/Render/Objects/CImage.h +++ b/src/WallpaperEngine/Render/Objects/CImage.h @@ -8,7 +8,7 @@ #include "WallpaperEngine/Render/Objects/Effects/CPass.h" #include "WallpaperEngine/Render/Wallpapers/CScene.h" -#include "WallpaperEngine/Render/Shaders/Compiler.h" +#include "WallpaperEngine/Render/Shaders/CShader.h" #include "WallpaperEngine/Assets/ITexture.h" @@ -29,22 +29,23 @@ class CImage final : public CObject { friend CObject; public: - CImage (CScene* scene, Core::Objects::CImage* image); + CImage (Wallpapers::CScene* scene, const Core::Objects::CImage* image); void setup (); void render () override; - const Core::Objects::CImage* getImage () const; - const std::vector& getEffects () const; - glm::vec2 getSize () const; + [[nodiscard]] const Core::Objects::CImage* getImage () const; + [[nodiscard]] const std::vector& getEffects () const; + [[nodiscard]] const Effects::CMaterial* getMaterial () const; + [[nodiscard]] glm::vec2 getSize () const; - GLuint getSceneSpacePosition () const; - GLuint getCopySpacePosition () const; - GLuint getPassSpacePosition () const; - GLuint getTexCoordCopy () const; - GLuint getTexCoordPass () const; - const ITexture* getTexture () const; - double getAnimationTime () const; + [[nodiscard]] GLuint getSceneSpacePosition () const; + [[nodiscard]] GLuint getCopySpacePosition () const; + [[nodiscard]] GLuint getPassSpacePosition () const; + [[nodiscard]] GLuint getTexCoordCopy () const; + [[nodiscard]] GLuint getTexCoordPass () const; + [[nodiscard]] std::shared_ptr getTexture () const; + [[nodiscard]] double getAnimationTime () const; /** * Performs a ping-pong on the available framebuffers to be able to continue rendering things to them @@ -52,49 +53,47 @@ class CImage final : public CObject { * @param drawTo The framebuffer to use * @param asInput The last texture used as output (if needed) */ - void pinpongFramebuffer (const CFBO** drawTo, const ITexture** asInput); + void pinpongFramebuffer (std::shared_ptr* drawTo, std::shared_ptr* asInput); protected: - static const std::string Type; - void setupPasses (); void updateScreenSpacePosition (); private: - const ITexture* m_texture; + std::shared_ptr m_texture = nullptr; GLuint m_sceneSpacePosition; GLuint m_copySpacePosition; GLuint m_passSpacePosition; GLuint m_texcoordCopy; GLuint m_texcoordPass; - glm::mat4 m_modelViewProjectionScreen; - glm::mat4 m_modelViewProjectionPass; - glm::mat4 m_modelViewProjectionCopy; - glm::mat4 m_modelViewProjectionScreenInverse; - glm::mat4 m_modelViewProjectionPassInverse; - glm::mat4 m_modelViewProjectionCopyInverse; + glm::mat4 m_modelViewProjectionScreen = {}; + glm::mat4 m_modelViewProjectionPass = {}; + glm::mat4 m_modelViewProjectionCopy = {}; + glm::mat4 m_modelViewProjectionScreenInverse = {}; + glm::mat4 m_modelViewProjectionPassInverse = {}; + glm::mat4 m_modelViewProjectionCopyInverse = {}; - glm::mat4 m_modelMatrix; - glm::mat4 m_viewProjectionMatrix; + glm::mat4 m_modelMatrix = {}; + glm::mat4 m_viewProjectionMatrix = {}; - CFBO* m_mainFBO; - CFBO* m_subFBO; - CFBO* m_currentMainFBO; - CFBO* m_currentSubFBO; + std::shared_ptr m_mainFBO = nullptr; + std::shared_ptr m_subFBO = nullptr; + std::shared_ptr m_currentMainFBO = nullptr; + std::shared_ptr m_currentSubFBO = nullptr; - Core::Objects::CImage* m_image; + const Core::Objects::CImage* m_image; - std::vector m_effects; - Effects::CMaterial* m_material; - Effects::CMaterial* m_colorBlendMaterial; - std::vector m_passes; + std::vector m_effects = {}; + Effects::CMaterial* m_material = nullptr; + Effects::CMaterial* m_colorBlendMaterial = nullptr; + std::vector m_passes = {}; - glm::vec4 m_pos; + glm::vec4 m_pos = {}; - double m_animationTime; + double m_animationTime = 0.0; - bool m_initialized; + bool m_initialized = false; }; } // namespace WallpaperEngine::Render::Objects diff --git a/src/WallpaperEngine/Render/Objects/CSound.cpp b/src/WallpaperEngine/Render/Objects/CSound.cpp index 413c240..9e17301 100644 --- a/src/WallpaperEngine/Render/Objects/CSound.cpp +++ b/src/WallpaperEngine/Render/Objects/CSound.cpp @@ -4,15 +4,26 @@ using namespace WallpaperEngine::Render::Objects; -CSound::CSound (CScene* scene, Core::Objects::CSound* sound) : CObject (scene, Type, sound), m_sound (sound) { +CSound::CSound (Wallpapers::CScene* scene, const Core::Objects::CSound* sound) : + CObject (scene, sound), + m_sound (sound) { if (this->getContext ().getApp ().getContext ().settings.audio.enabled) this->load (); } +CSound::~CSound() { + // free all the sound buffers and streams + for (const auto& stream : this->m_audioStreams) { + delete stream; + } + + this->m_soundBuffer.clear (); +} + void CSound::load () { for (const auto& cur : this->m_sound->getSounds ()) { uint32_t filesize = 0; - const uint8_t* filebuffer = this->getContainer ()->readFile (cur, &filesize); + std::shared_ptr filebuffer = this->getContainer ()->readFile (cur, &filesize); auto stream = new Audio::CAudioStream (this->getScene ()->getAudioContext (), filebuffer, filesize); @@ -27,5 +38,3 @@ void CSound::load () { } void CSound::render () {} - -const std::string CSound::Type = "sound"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Objects/CSound.h b/src/WallpaperEngine/Render/Objects/CSound.h index 8307e61..35c0398 100644 --- a/src/WallpaperEngine/Render/Objects/CSound.h +++ b/src/WallpaperEngine/Render/Objects/CSound.h @@ -7,22 +7,25 @@ using namespace WallpaperEngine; +namespace WallpaperEngine::Render::Wallpapers { +class CScene; +} + namespace WallpaperEngine::Render::Objects { class CSound final : public CObject { public: - CSound (CScene* scene, Core::Objects::CSound* sound); + CSound (Wallpapers::CScene* scene, const Core::Objects::CSound* sound); + ~CSound () override; void render () override; protected: - static const std::string Type; - void load (); private: - std::vector m_soundBuffer; - std::vector m_audioStreams; + std::vector> m_soundBuffer = {}; + std::vector m_audioStreams = {}; - Core::Objects::CSound* m_sound; + const Core::Objects::CSound* m_sound; }; } // namespace WallpaperEngine::Render::Objects diff --git a/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h b/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h index ec47a52..6fe5642 100644 --- a/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h +++ b/src/WallpaperEngine/Render/Objects/Effects/CMaterial.h @@ -37,6 +37,6 @@ class CMaterial final : public Helpers::CContextAware { const Render::Objects::CEffect* m_effect; const Core::Objects::Images::CMaterial* m_material; - std::vector m_passes; + std::vector m_passes = {}; }; } // namespace WallpaperEngine::Render::Objects::Effects diff --git a/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp b/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp index ea0a6ae..dba9467 100644 --- a/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp +++ b/src/WallpaperEngine/Render/Objects/Effects/CPass.cpp @@ -1,7 +1,13 @@ #include "CPass.h" #include "WallpaperEngine/Render/CFBO.h" -#include "common.h" #include +#include + +#include "WallpaperEngine/Core/Projects/CProperty.h" +#include "WallpaperEngine/Core/Projects/CPropertyColor.h" +#include "WallpaperEngine/Core/Projects/CPropertyCombo.h" +#include "WallpaperEngine/Core/Projects/CPropertySlider.h" +#include "WallpaperEngine/Core/Projects/CPropertyBoolean.h" #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h" @@ -13,7 +19,11 @@ #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantProperty.h" +#include "WallpaperEngine/Logging/CLog.h" using namespace WallpaperEngine::Core::Objects::Effects::Constants; using namespace WallpaperEngine::Render::Shaders::Variables; @@ -23,16 +33,16 @@ using namespace WallpaperEngine::Render::Objects::Effects; extern float g_Time; extern float g_Daytime; -CPass::CPass (CMaterial* material, Core::Objects::Images::Materials::CPass* pass) : +CPass::CPass (CMaterial* material, const Core::Objects::Images::Materials::CPass* pass) : Helpers::CContextAware (material), m_material (material), - m_pass (pass) { - this->setupTextures (); + m_pass (pass), + m_blendingmode (pass->getBlendingMode ()) { this->setupShaders (); this->setupShaderVariables (); } -const ITexture* CPass::resolveTexture (const ITexture* expected, int index, const ITexture* previous) { +std::shared_ptr CPass::resolveTexture (std::shared_ptr expected, int index, std::shared_ptr previous) { if (expected == nullptr) { const auto it = this->m_fbos.find (index); @@ -51,16 +61,24 @@ const ITexture* CPass::resolveTexture (const ITexture* expected, int index, cons return previous ?: expected; // the bind actually has a name, search the FBO in the effect and return it - const auto fbo = this->m_material->m_effect->findFBO (it->second->getName ()); + return this->resolveFBO (it->second->getName ()); +} - // try scene FBOs, these are our last resort, i guess the exception is better than a nullpo - if (fbo == nullptr) - return this->m_material->getImage ()->getScene ()->findFBO (it->second->getName ()); +std::shared_ptr CPass::resolveFBO (const std::string& name) const { + auto fbo = this->m_material->getEffect()->findFBO (name); + + if (fbo == nullptr) { + fbo = this->m_material->getImage ()->getScene ()->findFBO (name); + } + + if (fbo == nullptr) { + sLog.exception ("Tried to resolve and FBO without any luck: ", name); + } return fbo; } -void CPass::render () { +void CPass::setupRenderFramebuffer () { // set the framebuffer we're drawing to glBindFramebuffer (GL_FRAMEBUFFER, this->m_drawTo->getFramebuffer ()); @@ -68,13 +86,13 @@ void CPass::render () { glViewport (0, 0, this->m_drawTo->getRealWidth (), this->m_drawTo->getRealHeight ()); // set texture blending - if (this->m_pass->getBlendingMode () == "translucent") { + if (this->getBlendingMode () == "translucent") { glEnable (GL_BLEND); glBlendFuncSeparate (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } else if (this->m_pass->getBlendingMode () == "additive") { + } else if (this->getBlendingMode () == "additive") { glEnable (GL_BLEND); glBlendFuncSeparate (GL_SRC_ALPHA, GL_ONE, GL_SRC_ALPHA, GL_ONE); - } else if (this->m_pass->getBlendingMode () == "normal") { + } else if (this->getBlendingMode () == "normal") { glEnable (GL_BLEND); glBlendFuncSeparate (GL_ONE, GL_ZERO, GL_ONE, GL_ZERO); } else { @@ -99,12 +117,14 @@ void CPass::render () { } else { glDepthMask (true); } +} +void CPass::setupRenderTexture () { // use the shader we have registered glUseProgram (this->m_programID); // maybe we can do this when setting the texture? - const ITexture* texture = this->resolveTexture (this->m_input, 0, this->m_input); + std::shared_ptr texture = this->resolveTexture (this->m_input, 0, this->m_input); uint32_t currentTexture = 0; glm::vec2 translation = {0.0f, 0.0f}; @@ -139,15 +159,57 @@ void CPass::render () { glBindTexture (GL_TEXTURE_2D, texture->getTextureID (currentTexture)); // continue on the map from the second texture - if (!this->m_finalTextures.empty ()) { - for (const auto& [index, expectedTexture] : this->m_finalTextures) { - texture = this->resolveTexture (expectedTexture, index, this->m_input); + if (!this->m_textures.empty ()) { + for (const auto& [index, expectedTexture] : this->m_textures) { + if (expectedTexture == nullptr) { + texture = this->m_input; + } else { + texture = expectedTexture; + } glActiveTexture (GL_TEXTURE0 + index); glBindTexture (GL_TEXTURE_2D, texture->getTextureID (0)); } } + // used in animations when one of the frames is vertical instead of horizontal + // rotation with translation = origin and end of the image to display + if (this->g_Texture0Rotation != -1) + glUniform4f (this->g_Texture0Rotation, rotation.x, rotation.y, rotation.z, rotation.w); + // this actually picks the origin point of the image from the atlast + if (this->g_Texture0Translation != -1) + glUniform2f (this->g_Texture0Translation, translation.x, translation.y); +} + +void CPass::setupRenderReferenceUniforms () { + // add reference uniforms + for (const auto& [name, value] : this->m_referenceUniforms) { + switch (value->type) { + case Double: glUniform1d (value->id, *static_cast (*value->value)); break; + case Float: glUniform1f (value->id, *static_cast (*value->value)); break; + case Integer: glUniform1i (value->id, *static_cast (*value->value)); break; + case Vector4: + glUniform4fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); + break; + case Vector3: + glUniform3fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); + break; + case Vector2: + glUniform2fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); + break; + case Matrix4: + glUniformMatrix4fv (value->id, 1, GL_FALSE, + glm::value_ptr (*static_cast (*value->value))); + break; + case Matrix3: + glUniformMatrix3fv (value->id, 1, GL_FALSE, + glm::value_ptr (*static_cast (*value->value))); + break; + } + } +} + +void CPass::setupRenderUniforms () { // add uniforms for (const auto& [name, value] : this->m_uniforms) { switch (value->type) { @@ -174,40 +236,9 @@ void CPass::render () { break; } } - // add reference uniforms - for (const auto& [name, value] : this->m_referenceUniforms) { - switch (value->type) { - case Double: glUniform1d (value->id, *static_cast (*value->value)); break; - case Float: glUniform1f (value->id, *static_cast (*value->value)); break; - case Integer: glUniform1i (value->id, *static_cast (*value->value)); break; - case Vector4: - glUniform4fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); - break; - case Vector3: - glUniform3fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); - break; - case Vector2: - glUniform2fv (value->id, 1, glm::value_ptr (*static_cast (*value->value))); - break; - case Matrix4: - glUniformMatrix4fv (value->id, 1, GL_FALSE, - glm::value_ptr (*static_cast (*value->value))); - break; - case Matrix3: - glUniformMatrix3fv (value->id, 1, GL_FALSE, - glm::value_ptr (*static_cast (*value->value))); - break; - } - } - - // used in animations when one of the frames is vertical instead of horizontal - // rotation with translation = origin and end of the image to display - if (this->g_Texture0Rotation != -1) - glUniform4f (this->g_Texture0Rotation, rotation.x, rotation.y, rotation.z, rotation.w); - // this actually picks the origin point of the image from the atlast - if (this->g_Texture0Translation != -1) - glUniform2f (this->g_Texture0Translation, translation.x, translation.y); +} +void CPass::setupRenderAttributes () { for (const auto& cur : this->m_attribs) { glEnableVertexAttribArray (cur->id); glBindBuffer (GL_ARRAY_BUFFER, *cur->value); @@ -220,11 +251,15 @@ void CPass::render () { .c_str ()); #endif /* DEBUG */ } +} +void CPass::renderGeometry () const { // start actual rendering now glBindBuffer (GL_ARRAY_BUFFER, this->a_Position); glDrawArrays (GL_TRIANGLES, 0, 6); +} +void CPass::cleanupRenderSetup () { // disable vertex attribs array and textures for (const auto& cur : this->m_attribs) glDisableVertexAttribArray (cur->id); @@ -234,24 +269,34 @@ void CPass::render () { glBindTexture (GL_TEXTURE_2D, 0); // continue on the map from the second texture - if (!this->m_finalTextures.empty ()) { - for (const auto& [index, _] : this->m_finalTextures) { + if (!this->m_textures.empty ()) { + for (const auto& [index, _] : this->m_textures) { glActiveTexture (GL_TEXTURE0 + index); glBindTexture (GL_TEXTURE_2D, 0); } } } +void CPass::render () { + this->setupRenderFramebuffer (); + this->setupRenderTexture (); + this->setupRenderUniforms (); + this->setupRenderReferenceUniforms (); + this->setupRenderAttributes (); + this->renderGeometry (); + this->cleanupRenderSetup (); +} + const CMaterial* CPass::getMaterial () const { return this->m_material; } -void CPass::setDestination (const CFBO* drawTo) { - this->m_drawTo = drawTo; +void CPass::setDestination (std::shared_ptr drawTo) { + this->m_drawTo = std::move(drawTo); } -void CPass::setInput (const ITexture* input) { - this->m_input = input; +void CPass::setInput (std::shared_ptr input) { + this->m_input = std::move(input); } void CPass::setModelViewProjectionMatrix (const glm::mat4* projection) { @@ -270,6 +315,14 @@ void CPass::setViewProjectionMatrix (const glm::mat4* viewProjection) { this->m_viewProjectionMatrix = viewProjection; } +void CPass::setBlendingMode (std::string blendingmode) { + this->m_blendingmode = std::move(blendingmode); +} + +const std::string& CPass::getBlendingMode () const { + return this->m_blendingmode; +} + void CPass::setTexCoord (GLuint texcoord) { this->a_TexCoord = texcoord; } @@ -278,18 +331,19 @@ void CPass::setPosition (GLuint position) { this->a_Position = position; } -Core::Objects::Images::Materials::CPass* CPass::getPass () { +const Core::Objects::Images::Materials::CPass* CPass::getPass () const { return this->m_pass; } -GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) { +Render::Shaders::CShader* CPass::getShader () const { + return this->m_shader; +} + +GLuint CPass::compileShader (const char* shader, GLuint type) { // reserve shaders in OpenGL const GLuint shaderID = glCreateShader (type); - // give shader's source code to OpenGL to be compiled - const char* sourcePointer = shader->getCompiled ().c_str (); - - glShaderSource (shaderID, 1, &sourcePointer, nullptr); + glShaderSource (shaderID, 1, &shader, nullptr); glCompileShader (shaderID); GLint result = GL_FALSE; @@ -307,11 +361,17 @@ GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) { glGetShaderInfoLog (shaderID, infoLogLength, nullptr, logBuffer); // throw an exception about the issue std::stringstream buffer; - buffer << logBuffer << std::endl << "Compiled source code:" << std::endl << shader->getCompiled (); + buffer << logBuffer << std::endl << "Compiled source code:" << std::endl << shader; // free the buffer delete [] logBuffer; - // throw an exception - sLog.exception (buffer.str ()); + + if (result == GL_FALSE) { + // shader compilation failed completely, throw an exception + sLog.exception (buffer.str ()); + } else { + // some warning was emitted, log the error and keep chuging along + sLog.error (buffer.str ()); + } } return shaderID; @@ -319,33 +379,35 @@ GLuint CPass::compileShader (Render::Shaders::Compiler* shader, GLuint type) { void CPass::setupShaders () { // ensure the constants are defined - const ITexture* texture0 = this->m_material->getImage ()->getTexture (); + std::shared_ptr texture0 = this->m_material->getImage ()->getTexture (); + + // copy the combos from the pass + this->m_combos.insert (this->m_pass->getCombos ().begin (), this->m_pass->getCombos ().end ()); // TODO: THE VALUES ARE THE SAME AS THE ENUMERATION, SO MAYBE IT HAS TO BE SPECIFIED FOR THE TEXTURE 0 OF ALL // ELEMENTS? if (texture0 != nullptr) { if (texture0->getFormat () == ITexture::TextureFormat::RG88) { - this->m_pass->insertCombo ("TEX0FORMAT", 8); + this->m_combos.insert_or_assign ("TEX0FORMAT", 8); } else if (texture0->getFormat () == ITexture::TextureFormat::R8) { - this->m_pass->insertCombo ("TEX0FORMAT", 9); + this->m_combos.insert_or_assign ("TEX0FORMAT", 9); } } - // prepare the shaders - this->m_fragShader = new Render::Shaders::Compiler ( - this->m_material->getImage ()->getContainer (), this->m_pass->getShader (), Shaders::Compiler::Type_Pixel, - this->m_pass->getCombos (), &m_foundCombos, this->m_pass->getTextures (), this->m_pass->getConstants ()); - this->m_fragShader->precompile (); - this->m_vertShader = new Render::Shaders::Compiler ( - this->m_material->getImage ()->getContainer (), this->m_pass->getShader (), Shaders::Compiler::Type_Vertex, - this->m_pass->getCombos (), &m_foundCombos, this->m_pass->getTextures (), this->m_pass->getConstants ()); - this->m_vertShader->precompile (); - this->m_fragShader->precompile (); - this->m_vertShader->precompile (); + // TODO: REVIEW THE SHADER TEXTURES HERE, THE ONES PASSED ON TO THE SHADER SHOULD NOT BE IN THE LIST + // TODO: USED TO BUILD THE TEXTURES LATER + // use the combos copied from the pass so it includes the texture format + this->m_shader = new Render::Shaders::CShader ( + this->getMaterial ()->getImage ()->getContainer (), this->m_pass->getShader (), this->m_combos, + this->m_pass->getTextures (), this->m_pass->getConstants () + ); + + const auto shaders = Shaders::CGLSLContext::get ().toGlsl ( + this->m_shader->vertex (), this->m_shader->fragment ()); // compile the shaders - const GLuint vertexShaderID = compileShader (this->m_vertShader, GL_VERTEX_SHADER); - const GLuint fragmentShaderID = compileShader (this->m_fragShader, GL_FRAGMENT_SHADER); + const GLuint vertexShaderID = compileShader (shaders.first.c_str (), GL_VERTEX_SHADER); + const GLuint fragmentShaderID = compileShader (shaders.second.c_str (), GL_FRAGMENT_SHADER); // create the final program this->m_programID = glCreateProgram (); // link the shaders together @@ -369,8 +431,13 @@ void CPass::setupShaders () { const std::string message = logBuffer; // free the buffer delete [] logBuffer; - // throw an exception - sLog.exception (message); + if (result == GL_FALSE) { + // shader compilation failed completely, throw an exception + sLog.exception (message); + } else { + // some warning was emitted, log the error and keep chuging along + sLog.error (message); + } } #if !NDEBUG @@ -401,9 +468,71 @@ void CPass::setupAttributes () { this->addAttribute ("a_Position", GL_FLOAT, 3, &this->a_Position); } -void CPass::setupUniforms () { +void CPass::setupTextureUniforms () { + // first set default textures extracted from the shader + // vertex shader doesn't seem to have texture info + // but for now just set first vertex's textures + // and then try with fragment's and override any existing + for (const auto& [index, textureName] : this->m_shader->getVertex ().getTextures ()) { + try { + // resolve the texture first + std::shared_ptr textureRef; + + if (textureName.find ("_rt_") == 0 || textureName.find ("_alias_") == 0) { + textureRef = this->resolveFBO (textureName); + } else { + textureRef = this->getContext ().resolveTexture (textureName); + } + + this->m_textures [index] = textureRef; + } catch (std::runtime_error& ex) { + sLog.error ("Cannot resolve texture ", textureName, " for fragment shader ", ex.what ()); + } + } + + for (const auto& [index, textureName] : this->m_shader->getFragment ().getTextures ()) { + try { + // resolve the texture first + std::shared_ptr textureRef; + + if (textureName.find ("_rt_") == 0 || textureName.find ("_alias_") == 0) { + textureRef = this->resolveFBO (textureName); + } else { + textureRef = this->getContext ().resolveTexture (textureName); + } + + this->m_textures [index] = textureRef; + } catch (std::runtime_error& ex) { + sLog.error ("Cannot resolve texture ", textureName, " for fragment shader ", ex.what ()); + } + } + + for (const auto& [index, textureName] : this->m_pass->getTextures ()) { + // ignore first texture as that'll be the input of the previous pass (or the image if it's the first pass) + if (index == 0) { + continue; + } + + if (textureName.find ("_rt_") == 0) { + this->m_textures[index] = this->resolveFBO (textureName); + } else if (!textureName.empty ()) { + this->m_textures[index] = this->m_material->getImage ()->getContext ().resolveTexture (textureName); + } + } + + // binds are set last as they're the most important to be set + for (const auto& [index, bind] : this->m_material->getMaterial ()->getTextureBinds ()) { + if (bind->getName () == "previous") { + // use nullptr as indication for "previous" texture + this->m_textures [index] = nullptr; + } else { + // a normal bind, search for the corresponding FBO and set it + this->m_textures [index] = this->resolveFBO (bind->getName ()); + } + } + // resolve the main texture - const ITexture* texture = this->resolveTexture (this->m_material->getImage ()->getTexture (), 0); + std::shared_ptr texture = this->resolveTexture (this->m_material->getImage ()->getTexture (), 0); // register all the texture uniforms with correct values this->addUniform ("g_Texture0", 0); this->addUniform ("g_Texture1", 1); @@ -415,97 +544,18 @@ void CPass::setupUniforms () { this->addUniform ("g_Texture7", 7); this->addUniform ("g_Texture0Resolution", texture->getResolution ()); - // do the real, final texture setup for the whole process - { - auto cur = this->m_textures.begin (); - const auto end = this->m_textures.end (); - auto fragCur = this->m_fragShader->getTextures ().begin (); - const auto fragEnd = this->m_fragShader->getTextures ().end (); - auto vertCur = this->m_vertShader->getTextures ().begin (); - const auto vertEnd = this->m_vertShader->getTextures ().end (); - auto bindCur = this->m_material->getMaterial ()->getTextureBinds ().begin (); - const auto bindEnd = this->m_material->getMaterial ()->getTextureBinds ().end (); - - int index = 1; - - // technically m_textures should have the right amount of textures - // but better be safe than sorry - while (bindCur != bindEnd || cur != end || fragCur != fragEnd || vertCur != vertEnd) { - if (bindCur != bindEnd) { - this->m_finalTextures [bindCur->first] = nullptr; - ++bindCur; - } - - if (cur != end) { - if ((*cur) != nullptr) - this->m_finalTextures [index] = *cur; - - index++; - ++cur; - } - - if (fragCur != fragEnd) { - std::string textureName = fragCur->second; - - try { - // resolve the texture first - const ITexture* textureRef; - - if (textureName.find ("_rt_") == 0 || textureName.find ("_alias_") == 0) { - textureRef = this->getMaterial ()->getEffect ()->findFBO (textureName); - - if (textureRef == nullptr) - textureRef = this->getMaterial ()->getImage ()->getScene ()->findFBO (textureName); - } else - textureRef = this->getContext ().resolveTexture (textureName); - - // ensure there's no texture in that slot already, shader textures are defaults in case nothing is - // there - if (this->m_finalTextures.find (fragCur->first) == this->m_finalTextures.end ()) - this->m_finalTextures [fragCur->first] = textureRef; - } catch (std::runtime_error& ex) { - sLog.error ("Cannot resolve texture ", textureName, " for fragment shader ", ex.what ()); - } - - ++fragCur; - } - - if (vertCur != vertEnd) { - std::string textureName = vertCur->second; - - try { - // resolve the texture first - const ITexture* textureRef; - - if (textureName.find ("_rt_") == 0) { - textureRef = this->getMaterial ()->getEffect ()->findFBO (textureName); - - if (textureRef == nullptr) - textureRef = this->getMaterial ()->getImage ()->getScene ()->findFBO (textureName); - } else - textureRef = this->getContext ().resolveTexture (textureName); - - // ensure there's no texture in that slot already, shader textures are defaults in case nothing is - // there - if (this->m_finalTextures.find (vertCur->first) == this->m_finalTextures.end ()) - this->m_finalTextures [vertCur->first] = textureRef; - } catch (std::runtime_error& ex) { - sLog.error ("Cannot resolve texture ", textureName, " for vertex shader ", ex.what ()); - } - - ++vertCur; - } - } - } - - for (const auto& [index, expectedTexture] : this->m_finalTextures) { + for (const auto& [textureIndex, expectedTexture] : this->m_textures) { std::ostringstream namestream; - namestream << "g_Texture" << index << "Resolution"; + namestream << "g_Texture" << textureIndex << "Resolution"; - texture = this->resolveTexture (expectedTexture, index, texture); + texture = this->resolveTexture (expectedTexture, textureIndex, texture); this->addUniform (namestream.str (), texture->getResolution ()); } +} + +void CPass::setupUniforms () { + this->setupTextureUniforms (); const auto projection = this->getMaterial ()->getImage ()->getScene ()->getScene ()->getOrthogonalProjection (); @@ -567,11 +617,18 @@ template void CPass::addUniform (const std::string& name, UniformTy if (id == -1) return; + // free the uniform that's already registered if it's there already + const auto it = this->m_uniforms.find (name); + + if (it != this->m_uniforms.end ()) { + delete it->second; + } + // build a copy of the value and allocate it somewhere T* newValue = new T (value); // uniform found, add it to the list - this->m_uniforms.insert (std::make_pair (name, new UniformEntry (id, name, type, newValue, 1))); + this->m_uniforms.insert_or_assign (name, new UniformEntry (id, name, type, newValue, 1)); } template void CPass::addUniform (const std::string& name, UniformType type, T* value, int count) { @@ -582,8 +639,15 @@ template void CPass::addUniform (const std::string& name, UniformTy if (id == -1) return; + // free the uniform that's already registered if it's there already + const auto it = this->m_uniforms.find (name); + + if (it != this->m_uniforms.end ()) { + delete it->second; + } + // uniform found, add it to the list - this->m_uniforms.insert (std::make_pair (name, new UniformEntry (id, name, type, value, count))); + this->m_uniforms.insert_or_assign (name, new UniformEntry (id, name, type, value, count)); } template void CPass::addUniform (const std::string& name, UniformType type, T** value) { @@ -594,122 +658,65 @@ template void CPass::addUniform (const std::string& name, UniformTy if (id == -1) return; - // uniform found, add it to the list - this->m_referenceUniforms.insert ( - std::make_pair (name, new ReferenceUniformEntry (id, name, type, reinterpret_cast (value)))); -} + // free the uniform that's already registered if it's there already + const auto it = this->m_uniforms.find (name); -void CPass::setupTextures () { - auto cur = this->m_pass->getTextures ().begin (); - const auto end = this->m_pass->getTextures ().end (); - - for (int index = 0; cur != end; ++cur, index++) { - // ignore first texture as that'll be the input of the last pass/image (unless the image is an FBO) - if (index == 0) - continue; - - if (cur->find ("_rt_") == 0) { - const CFBO* fbo = this->m_material->m_effect->findFBO ((*cur)); - - if (fbo == nullptr) - fbo = this->m_material->getImage ()->getScene ()->findFBO ((*cur)); - - if (fbo != nullptr) { - this->m_fbos.insert (std::make_pair (index, fbo)); - this->m_textures.emplace_back (fbo); - } - // _rt_texture - } else { - if (cur->empty ()) { - this->m_textures.emplace_back (nullptr); - } else { - this->m_textures.emplace_back (this->m_material->getImage ()->getContext ().resolveTexture ((*cur))); - } - } + if (it != this->m_uniforms.end ()) { + delete it->second; } + + // uniform found, add it to the list + this->m_referenceUniforms.insert_or_assign ( + name, new ReferenceUniformEntry (id, name, type, reinterpret_cast (value))); } void CPass::setupShaderVariables () { + for (const auto& cur : this->m_shader->getVertex ().getParameters ()) + if (this->m_uniforms.find (cur->getName ()) == this->m_uniforms.end ()) + this->addUniform (cur); + + for (const auto& cur : this->m_shader->getFragment ().getParameters ()) + if (this->m_uniforms.find (cur->getName ()) == this->m_uniforms.end ()) + this->addUniform (cur); + // find variables in the shaders and set the value with the constants if possible for (const auto& [name, value] : this->m_pass->getConstants ()) { - CShaderVariable* vertexVar = this->m_vertShader->findParameter (name); - CShaderVariable* pixelVar = this->m_fragShader->findParameter (name); + const auto parameters = this->m_shader->findParameter (name); // variable not found, can be ignored - if (vertexVar == nullptr && pixelVar == nullptr) + if (parameters.vertex == nullptr && parameters.fragment == nullptr) continue; // get one instance of it - CShaderVariable* var = vertexVar == nullptr ? pixelVar : vertexVar; + CShaderVariable* var = parameters.vertex == nullptr ? parameters.fragment : parameters.vertex; - // ensure the shader's and the constant are of the same type - if (value->getType () == var->getType ()) { - this->addUniform (var->getName (), value); - continue; - } - - // there's situations where this type mismatch is actually expected - // integers and floats are equivalent, this could be detected at load time - // but that'd mean to compile the shader in the load, and not on the render stage - // so take into account these conversions here - if (value->is () && var->is ()) { - // create an integer value from a float - this->addUniform (var->getName (), static_cast (*value->as ()->getValue ())); - } else if (value->is () && var->is ()) { - // create a float value from an integer - this->addUniform (var->getName (), static_cast (*value->as ()->getValue ())); - } else if (value->is () && var->is ()) { - auto* val = value->as (); - - // create a new vector2 with the first two values - this->addUniform (var->getName (), {val->getValue ()->x, val->getValue ()->y}); - } else if (value->is () && var->is ()) { - auto* val = value->as (); - - this->addUniform (var->getName (), {val->getValue ()->x, val->getValue ()->y, val->getValue ()->z}); - } else { - sLog.exception ("Constant ", name, - " type does not match pixel/vertex shader variable and cannot be converted (", - value->getType (), " to ", var->getType ()); - } + // this takes care of all possible casts, even invalid ones, which will use whatever default behaviour + // of the underlying CDynamicValue used for the value + this->addUniform (var, value); } - - for (const auto& cur : this->m_vertShader->getParameters ()) - if (this->m_uniforms.find (cur->getName ()) == this->m_uniforms.end ()) - this->addUniform (cur); - - for (const auto& cur : this->m_fragShader->getParameters ()) - if (this->m_uniforms.find (cur->getName ()) == this->m_uniforms.end ()) - this->addUniform (cur); } // define some basic methods for the template void CPass::addUniform (CShaderVariable* value) { - if (value->is ()) - this->addUniform (value->getName (), - static_cast (value->as ()->getValue ())); - else if (value->is ()) - this->addUniform (value->getName (), - static_cast (value->as ()->getValue ())); - else if (value->is ()) - this->addUniform (value->getName (), - static_cast (value->as ()->getValue ())); - else if (value->is ()) - this->addUniform (value->getName (), - static_cast (value->as ()->getValue ())); - else if (value->is ()) - this->addUniform (value->getName (), - static_cast (value->as ()->getValue ())); + // no need to re-implement this, call the version that takes a CDynamicValue as second parameter + // and that handles casting and everything + this->addUniform (value, value); } -void CPass::addUniform (const std::string& name, CShaderConstant* value) { - // now determine the constant's type and register the correct uniform for it - if (value->is ()) - this->addUniform (name, value->as ()->getValue ()); - else if (value->is ()) - this->addUniform (name, value->as ()->getValue ()); - else if (value->is ()) - this->addUniform (name, value->as ()->getValue ()); +void CPass::addUniform (CShaderVariable* value, const CDynamicValue* setting) { + if (value->is ()) { + this->addUniform (value->getName (), setting->getFloat ()); + } else if (value->is ()) { + this->addUniform (value->getName (), setting->getInt ()); + } else if (value->is ()) { + this->addUniform (value->getName (), setting->getVec2 ()); + } else if (value->is ()) { + this->addUniform (value->getName (), setting->getVec3 ()); + } else if (value->is ()) { + this->addUniform (value->getName (), setting->getVec4 ()); + } else { + sLog.error ("Cannot convert setting dynamic value to ", value->getName (), ". Using default value"); + } } void CPass::addUniform (const std::string& name, int value) { diff --git a/src/WallpaperEngine/Render/Objects/Effects/CPass.h b/src/WallpaperEngine/Render/Objects/Effects/CPass.h index a5dea99..e3dbe5a 100644 --- a/src/WallpaperEngine/Render/Objects/Effects/CPass.h +++ b/src/WallpaperEngine/Render/Objects/Effects/CPass.h @@ -5,37 +5,43 @@ #include "WallpaperEngine/Assets/ITexture.h" #include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" +#include "WallpaperEngine/Core/Objects/Images/Materials/CPass.h" #include "WallpaperEngine/Render/CFBO.h" #include "WallpaperEngine/Render/Objects/Effects/CMaterial.h" -#include "WallpaperEngine/Render/Shaders/Compiler.h" +#include "WallpaperEngine/Render/Shaders/CShader.h" #include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" - +#include "WallpaperEngine/Core/UserSettings/CUserSettingValue.h" #include "WallpaperEngine/Render/Helpers/CContextAware.h" namespace WallpaperEngine::Render::Objects::Effects { using namespace WallpaperEngine::Assets; using namespace WallpaperEngine::Render::Shaders::Variables; +using namespace WallpaperEngine::Core::Projects; using namespace WallpaperEngine::Core::Objects::Effects::Constants; class CMaterial; class CPass final : public Helpers::CContextAware { public: - CPass (CMaterial* material, Core::Objects::Images::Materials::CPass* pass); + CPass (CMaterial* material, const Core::Objects::Images::Materials::CPass* pass); void render (); - void setDestination (const CFBO* drawTo); - void setInput (const ITexture* input); + void setDestination (std::shared_ptr drawTo); + void setInput (std::shared_ptr input); void setTexCoord (GLuint texcoord); void setPosition (GLuint position); void setModelViewProjectionMatrix (const glm::mat4* projection); void setModelViewProjectionMatrixInverse (const glm::mat4* projection); void setModelMatrix (const glm::mat4* model); void setViewProjectionMatrix (const glm::mat4* viewProjection); + void setBlendingMode (std::string blendingmode); + [[nodiscard]] const std::string& getBlendingMode () const; + [[nodiscard]] std::shared_ptr resolveFBO (const std::string& name) const; - const CMaterial* getMaterial () const; - Core::Objects::Images::Materials::CPass* getPass (); + [[nodiscard]] const CMaterial* getMaterial () const; + [[nodiscard]] const Core::Objects::Images::Materials::CPass* getPass () const; + [[nodiscard]] Render::Shaders::CShader* getShader () const; private: enum UniformType { @@ -95,15 +101,15 @@ class CPass final : public Helpers::CContextAware { const GLuint* value; }; - static GLuint compileShader (Render::Shaders::Compiler* shader, GLuint type); - void setupTextures (); + static GLuint compileShader (const char* shader, GLuint type); void setupShaders (); void setupShaderVariables (); void setupUniforms (); + void setupTextureUniforms (); void setupAttributes (); void addAttribute (const std::string& name, GLint type, GLint elements, const GLuint* value); void addUniform (CShaderVariable* value); - void addUniform (const std::string& name, CShaderConstant* value); + void addUniform (CShaderVariable* value, const CDynamicValue* setting); void addUniform (const std::string& name, int value); void addUniform (const std::string& name, double value); void addUniform (const std::string& name, float value); @@ -132,16 +138,24 @@ class CPass final : public Helpers::CContextAware { template void addUniform (const std::string& name, UniformType type, T* value, int count = 1); template void addUniform (const std::string& name, UniformType type, T** value); - const ITexture* resolveTexture (const ITexture* expected, int index, const ITexture* previous = nullptr); + void setupRenderFramebuffer (); + void setupRenderTexture (); + void setupRenderUniforms (); + void setupRenderReferenceUniforms (); + void setupRenderAttributes (); + void renderGeometry () const; + void cleanupRenderSetup (); - CMaterial* m_material; - Core::Objects::Images::Materials::CPass* m_pass; - std::vector m_textures; - std::map m_fbos; - std::map m_foundCombos; - std::vector m_attribs; - std::map m_uniforms; - std::map m_referenceUniforms; + std::shared_ptr resolveTexture (std::shared_ptr expected, int index, std::shared_ptr previous = nullptr); + + CMaterial* m_material = nullptr; + const Core::Objects::Images::Materials::CPass* m_pass; + std::map> m_fbos = {}; + std::map m_combos = {}; + std::vector m_attribs = {}; + std::map m_uniforms = {}; + std::map m_referenceUniforms = {}; + std::string m_blendingmode = ""; const glm::mat4* m_modelViewProjectionMatrix; const glm::mat4* m_modelViewProjectionMatrixInverse; const glm::mat4* m_modelMatrix; @@ -150,13 +164,12 @@ class CPass final : public Helpers::CContextAware { /** * Contains the final map of textures to be used */ - std::map m_finalTextures; + std::map> m_textures = {}; - Render::Shaders::Compiler* m_fragShader; - Render::Shaders::Compiler* m_vertShader; + Render::Shaders::CShader* m_shader = nullptr; - const CFBO* m_drawTo; - const ITexture* m_input; + std::shared_ptr m_drawTo = nullptr; + std::shared_ptr m_input = nullptr; GLuint m_programID; diff --git a/src/WallpaperEngine/Render/Shaders/CGLSLContext.cpp b/src/WallpaperEngine/Render/Shaders/CGLSLContext.cpp new file mode 100644 index 0000000..4892f53 --- /dev/null +++ b/src/WallpaperEngine/Render/Shaders/CGLSLContext.cpp @@ -0,0 +1,198 @@ +#include "CGLSLContext.h" +#include "WallpaperEngine/Logging/CLog.h" + +#include +#include + +#include "glslang/Include/ResourceLimits.h" +#include "glslang/Public/ShaderLang.h" +#include "SPIRV/GlslangToSpv.h" +#include "spirv_glsl.hpp" + +using namespace WallpaperEngine::Render::Shaders; + +TBuiltInResource BuiltInResource = { + .maxLights = 32, + .maxClipPlanes = 6, + .maxTextureUnits = 32, + .maxTextureCoords = 32, + .maxVertexAttribs = 64, + .maxVertexUniformComponents = 4096, + .maxVaryingFloats = 64, + .maxVertexTextureImageUnits = 32, + .maxCombinedTextureImageUnits = 80, + .maxTextureImageUnits = 32, + .maxFragmentUniformComponents = 4096, + .maxDrawBuffers = 32, + .maxVertexUniformVectors = 128, + .maxVaryingVectors = 8, + .maxFragmentUniformVectors = 16, + .maxVertexOutputVectors = 16, + .maxFragmentInputVectors = 15, + .minProgramTexelOffset = -8, + .maxProgramTexelOffset = 7, + .maxClipDistances = 8, + .maxComputeWorkGroupCountX = 65535, + .maxComputeWorkGroupCountY = 65535, + .maxComputeWorkGroupCountZ = 65535, + .maxComputeWorkGroupSizeX = 1024, + .maxComputeWorkGroupSizeY = 1024, + .maxComputeWorkGroupSizeZ = 64, + .maxComputeUniformComponents = 1024, + .maxComputeTextureImageUnits = 16, + .maxComputeImageUniforms = 8, + .maxComputeAtomicCounters = 8, + .maxComputeAtomicCounterBuffers = 1, + .maxVaryingComponents = 60, + .maxVertexOutputComponents = 64, + .maxGeometryInputComponents = 64, + .maxGeometryOutputComponents = 128, + .maxFragmentInputComponents = 128, + .maxImageUnits = 8, + .maxCombinedImageUnitsAndFragmentOutputs = 8, + .maxCombinedShaderOutputResources = 8, + .maxImageSamples = 0, + .maxVertexImageUniforms = 0, + .maxTessControlImageUniforms = 0, + .maxTessEvaluationImageUniforms = 0, + .maxGeometryImageUniforms = 0, + .maxFragmentImageUniforms = 8, + .maxCombinedImageUniforms = 8, + .maxGeometryTextureImageUnits = 16, + .maxGeometryOutputVertices = 256, + .maxGeometryTotalOutputComponents = 1024, + .maxGeometryUniformComponents = 1024, + .maxGeometryVaryingComponents = 64, + .maxTessControlInputComponents = 128, + .maxTessControlOutputComponents = 128, + .maxTessControlTextureImageUnits = 16, + .maxTessControlUniformComponents = 1024, + .maxTessControlTotalOutputComponents = 4096, + .maxTessEvaluationInputComponents = 128, + .maxTessEvaluationOutputComponents = 128, + .maxTessEvaluationTextureImageUnits = 16, + .maxTessEvaluationUniformComponents = 1024, + .maxTessPatchComponents = 120, + .maxPatchVertices = 32, + .maxTessGenLevel = 64, + .maxViewports = 16, + .maxVertexAtomicCounters = 0, + .maxTessControlAtomicCounters = 0, + .maxTessEvaluationAtomicCounters = 0, + .maxGeometryAtomicCounters = 0, + .maxFragmentAtomicCounters = 8, + .maxCombinedAtomicCounters = 8, + .maxAtomicCounterBindings = 1, + .maxVertexAtomicCounterBuffers = 0, + .maxTessControlAtomicCounterBuffers = 0, + .maxTessEvaluationAtomicCounterBuffers = 0, + .maxGeometryAtomicCounterBuffers = 0, + .maxFragmentAtomicCounterBuffers = 1, + .maxCombinedAtomicCounterBuffers = 1, + .maxAtomicCounterBufferSize = 16384, + .maxTransformFeedbackBuffers = 4, + .maxTransformFeedbackInterleavedComponents = 64, + .maxCullDistances = 8, + .maxCombinedClipAndCullDistances = 8, + .maxSamples = 4, + .maxMeshOutputVerticesNV = 256, + .maxMeshOutputPrimitivesNV = 512, + .maxMeshWorkGroupSizeX_NV = 32, + .maxMeshWorkGroupSizeY_NV = 1, + .maxMeshWorkGroupSizeZ_NV = 1, + .maxTaskWorkGroupSizeX_NV = 32, + .maxTaskWorkGroupSizeY_NV = 1, + .maxTaskWorkGroupSizeZ_NV = 1, + .maxMeshViewCountNV = 4, + .limits = { + .nonInductiveForLoops = 1, + .whileLoops = 1, + .doWhileLoops = 1, + .generalUniformIndexing = 1, + .generalAttributeMatrixVectorIndexing = 1, + .generalVaryingIndexing = 1, + .generalSamplerIndexing = 1, + .generalVariableIndexing = 1, + .generalConstantMatrixVectorIndexing = 1, + } +}; + +CGLSLContext::CGLSLContext () { + assert (this->sInstance == nullptr); + + glslang::InitializeProcess(); +} + +CGLSLContext::~CGLSLContext () { + glslang::FinalizeProcess(); +} + +CGLSLContext& CGLSLContext::get () { + if (sInstance == nullptr) + sInstance = std::make_unique (); + + return *sInstance; +} + +std::pair CGLSLContext::toGlsl (const std::string& vertex, const std::string& fragment) { + glslang::TShader vertexShader (EShLangVertex); + + const char* vertexSource = vertex.c_str(); + vertexShader.setStrings(&vertexSource, 1); + vertexShader.setEntryPoint("main"); + vertexShader.setEnvInput(glslang::EShSourceGlsl, EShLangVertex, glslang::EShClientOpenGL, 330); + vertexShader.setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450); + vertexShader.setEnvTarget(glslang::EShTargetSpv, glslang::EShTargetSpv_1_5); + vertexShader.setAutoMapLocations (true); + vertexShader.setAutoMapBindings (true); + + if (!vertexShader.parse (&BuiltInResource, 100, false, EShMsgDefault)) { + sLog.error ("GLSL vertex unit parsing Failed: ", vertexShader.getInfoLog()); + return {"", ""}; + } + glslang::TShader fragmentShader (EShLangFragment); + + const char* fragmentSource = fragment.c_str(); + fragmentShader.setStrings(&fragmentSource, 1); + fragmentShader.setEntryPoint("main"); + fragmentShader.setEnvInput(glslang::EShSourceGlsl, EShLangFragment, glslang::EShClientOpenGL, 330); + fragmentShader.setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450); + fragmentShader.setEnvTarget(glslang::EShTargetSpv, glslang::EShTargetSpv_1_5); + fragmentShader.setAutoMapLocations (true); + fragmentShader.setAutoMapBindings (true); + + if (!fragmentShader.parse (&BuiltInResource, 100, false, EShMsgDefault)) { + sLog.error ("GLSL fragment unit parsing Failed: ", fragmentShader.getInfoLog()); + return {"", ""}; + } + glslang::TProgram program; + program.addShader (&vertexShader); + program.addShader (&fragmentShader); + + if (!program.link (EShMsgDefault)) { + sLog.error ("Program Linking Failed: ", program.getInfoLog()); + return {"", ""}; + } + + std::vector spirv; + glslang::GlslangToSpv (*program.getIntermediate (EShLangVertex), spirv); + + spirv_cross::CompilerGLSL vertexCompiler (spirv); + spirv_cross::CompilerGLSL::Options options; + options.version = 330; + options.es = false; + vertexCompiler.set_common_options(options); + + spirv.clear (); + glslang::GlslangToSpv (*program.getIntermediate (EShLangFragment), spirv); + + spirv_cross::CompilerGLSL fragmentCompiler (spirv); + options.version = 330; + options.es = false; + fragmentCompiler .set_common_options(options); + + return {vertexCompiler.compile() + "#if 0\n" + vertex + "#endif", fragmentCompiler.compile() + "#if 0\n" + fragment + "#endif"}; +} + + +std::unique_ptr CGLSLContext::sInstance = nullptr; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/CGLSLContext.h b/src/WallpaperEngine/Render/Shaders/CGLSLContext.h new file mode 100644 index 0000000..e4cd893 --- /dev/null +++ b/src/WallpaperEngine/Render/Shaders/CGLSLContext.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace WallpaperEngine::Render::Shaders { +class CGLSLContext { + public: + /** + * Types of shaders + */ + enum UnitType { + UnitType_Vertex = 0, + UnitType_Fragment = 1 + }; + + CGLSLContext (); + ~CGLSLContext (); + + [[nodiscard]] std::pair toGlsl (const std::string& vertex, const std::string& fragment); + + [[nodiscard]] static CGLSLContext& get (); + + private: + static std::unique_ptr sInstance; +}; +} // namespace WallpaperEngine::Render::Shaders \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/CShader.cpp b/src/WallpaperEngine/Render/Shaders/CShader.cpp new file mode 100644 index 0000000..3df9888 --- /dev/null +++ b/src/WallpaperEngine/Render/Shaders/CShader.cpp @@ -0,0 +1,82 @@ +#include +#include +#include + +// shader compiler +#include +#include +#include +#include +#include + +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" + +#include "CGLSLContext.h" + +using namespace WallpaperEngine::Core; +using namespace WallpaperEngine::Assets; + +namespace WallpaperEngine::Render::Shaders { +CShader::CShader ( + std::shared_ptr container, std::string filename, const std::map& combos, + const std::map& textures, const std::map& constants +) : + m_file (std::move (filename)), + m_combos (combos), + m_passTextures (textures), + m_vertex ( + CGLSLContext::UnitType_Vertex, filename, container->readVertexShader (filename), + container, constants, textures, combos), + m_fragment ( + CGLSLContext::UnitType_Fragment, filename, container->readFragmentShader (filename), + container, constants, textures, combos) { + // link shaders between them + this->m_vertex.linkToUnit (&this->m_fragment); + this->m_fragment.linkToUnit (&this->m_vertex); +} + + +const std::string& CShader::vertex () { + return this->m_vertex.compile (); +} + +const std::string& CShader::fragment () { + return this->m_fragment.compile (); +} + +const CShaderUnit& CShader::getVertex () const { + return this->m_vertex; +} + +const CShaderUnit& CShader::getFragment () const { + return this->m_fragment; +} + +const std::map& CShader::getCombos () const { + return this->m_combos; +} + +CShader::ParameterSearchResult CShader::findParameter (const std::string& name) { + Variables::CShaderVariable* vertex = nullptr; + Variables::CShaderVariable* fragment = nullptr; + + for (const auto& cur : this->m_vertex.getParameters ()) { + if (cur->getIdentifierName () == name) { + vertex = cur; + break; + } + } + + for (const auto& cur : this->m_fragment.getParameters()) { + if (cur->getIdentifierName () == name) { + fragment = cur; + break; + } + } + + return { + .vertex = vertex, + .fragment = fragment, + }; +} +} // namespace WallpaperEngine::Render::Shaders diff --git a/src/WallpaperEngine/Render/Shaders/CShader.h b/src/WallpaperEngine/Render/Shaders/CShader.h new file mode 100644 index 0000000..f332daa --- /dev/null +++ b/src/WallpaperEngine/Render/Shaders/CShader.h @@ -0,0 +1,102 @@ +#pragma once + +#include +#include +#include + +#include "WallpaperEngine/Assets/CContainer.h" +#include "WallpaperEngine/Assets/ITexture.h" +#include "WallpaperEngine/Core/Core.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" + +#include "CShaderUnit.h" +#include "CGLSLContext.h" + +namespace WallpaperEngine::Render::Shaders { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Core::Objects::Effects::Constants; + +/** + * A basic shader loader that adds basic function definitions to every loaded shader + */ +class CShader { + public: + struct ParameterSearchResult { + Variables::CShaderVariable* vertex; + Variables::CShaderVariable* fragment; + }; + /** + * Compiler constructor, loads the given shader file and prepares + * the pre-processing and compilation of the shader, adding + * required definitions if needed + * + * @param container The container to use for file lookup + * @param filename The file to load + * @param type The type of shader + * @param combos Settings for the shader + * @param foundCombos The list of currently defined combos + * @param textures The list of available textures for the shader + * @param constants Default values for shader variables + * @param recursive Whether the compiler should add base definitions or not + */ + CShader ( + std::shared_ptr container, std::string filename, + const std::map& combos, const std::map& textures, + const std::map& constants); + /** + * @return The vertex's shader coude for OpenGL to use + */ + const std::string& vertex (); + /** + * @return The fragment's shader code for OpenGL to use + */ + const std::string& fragment (); + /** + * @return The vertex shader unit + */ + [[nodiscard]] const CShaderUnit& getVertex () const; + /** + * @return The fragment shader unit + */ + [[nodiscard]] const CShaderUnit& getFragment () const; + /** + * @return The list of combos available for this shader after compilation + */ + [[nodiscard]] const std::map& getCombos () const; + /** + * Searches for the given parameter in the two shader units and return whatever was found + * + * @param name + * @return + */ + [[nodiscard]] ParameterSearchResult findParameter (const std::string& name); + + private: + /** + * The vertex shader unit used in this shader + */ + CShaderUnit m_vertex; + /** + * The fragment shader unit used in this shader + */ + CShaderUnit m_fragment; + /** + * The shader file this instance is loading + */ + std::string m_file = ""; + /** + * The parameters the shader needs + */ + std::vector m_parameters = {}; + /** + * The combos the shader should be generated with + */ + const std::map& m_combos; + /** + * The list of textures the pass knows about + */ + const std::map m_passTextures; +}; +} // namespace WallpaperEngine::Render::Shaders diff --git a/src/WallpaperEngine/Render/Shaders/CShaderUnit.cpp b/src/WallpaperEngine/Render/Shaders/CShaderUnit.cpp new file mode 100644 index 0000000..a4cc72b --- /dev/null +++ b/src/WallpaperEngine/Render/Shaders/CShaderUnit.cpp @@ -0,0 +1,570 @@ +#include "CShaderUnit.h" + +#include +#include +#include +#include +#include "WallpaperEngine/Logging/CLog.h" + +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantFloat.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantInteger.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector2.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector3.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstantVector4.h" + +#include "CGLSLContext.h" +#include "WallpaperEngine/Assets/CAssetLoadException.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h" + +#define SHADER_HEADER(filename) "#version 330\n" \ + "// ======================================================\n" \ + "// Processed shader " + \ + filename + \ + "\n" \ + "// ======================================================\n" \ + "precision highp float;\n" \ + "#define mul(x, y) ((y) * (x))\n" \ + "#define max(x, y) max (y, x)\n" \ + "#define lerp mix\n" \ + "#define frac fract\n" \ + "#define CAST2(x) (vec2(x))\n" \ + "#define CAST3(x) (vec3(x))\n" \ + "#define CAST4(x) (vec4(x))\n" \ + "#define CAST3X3(x) (mat3(x))\n" \ + "#define saturate(x) (clamp(x, 0.0, 1.0))\n" \ + "#define texSample2D texture\n" \ + "#define texSample2DLod textureLod\n" \ + "#define log10(x) log2(x) * 0.301029995663981\n" \ + "#define atan2 atan\n" \ + "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n" \ + "#define ddx dFdx\n" \ + "#define ddy(x) dFdy(-(x))\n" \ + "#define GLSL 1\n\n"; +#define FRAGMENT_SHADER_DEFINES "out vec4 out_FragColor;\n" \ + "#define varying in\n" +#define VERTEX_SHADER_DEFINES "#define attribute in\n" \ + "#define varying out\n" +#define DEFINE_COMBO(name, value) "#define " + name + " " + std::to_string (value) + "\n"; + +using namespace WallpaperEngine::Core; +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Render::Shaders; + +CShaderUnit::CShaderUnit ( + CGLSLContext::UnitType type, std::string file, std::string content, std::shared_ptr container, + const std::map& constants, const std::map& passTextures, + const std::map& combos +) : + m_type (type), + m_link (nullptr), + m_container (std::move(container)), + m_file (std::move (file)), + m_constants (constants), + m_content (std::move(content)), + m_passTextures (passTextures), + m_combos (combos), + m_discoveredCombos (), + m_usedCombos () { + // pre-process the shader so the units are clear + this->preprocess (); +} + +void CShaderUnit::preprocess () { + this->m_preprocessed = this->m_content; + this->m_includes = ""; + + this->preprocessVariables (); + this->preprocessIncludes (); + this->preprocessRequires (); + + // replace gl_FragColor with the equivalent + std::string from = "gl_FragColor"; + std::string to = "out_FragColor"; + + size_t start_pos = 0; + while ((start_pos = this->m_preprocessed.find (from, start_pos)) != std::string::npos) { + this->m_preprocessed.replace (start_pos, from.length (), to); + start_pos += to.length (); // Handles case where 'to' is a substring of 'from' + } +} + +void CShaderUnit::preprocessVariables () { + this->m_preprocessed = this->m_content; + this->m_includes = ""; + + size_t start = 0, end = 0; + while ((end = this->m_preprocessed.find ('\n', start)) != std::string::npos) { + // Extract a line from the string + std::string line = this->m_preprocessed.substr (start, end - start); + size_t combo = line.find("// [COMBO] "); + size_t uniform = line.find("uniform "); + size_t comment = line.find("// "); + size_t semicolon = line.find(';'); + + if (combo != std::string::npos) { + this->parseComboConfiguration (line.substr(combo + strlen("// [COMBO] ")), 0); + } else if ( + uniform != std::string::npos && + comment != std::string::npos && + semicolon != std::string::npos && + // this check ensures that the comment is after the semicolon (so it's not a commented-out line) + // this needs further refining as it's not taking into account block comments + semicolon < comment) { + // uniforms with comments should never have a value assigned, use this fact to detect the required parts + size_t last_space = line.find_last_of (' ', semicolon); + + if (last_space != std::string::npos) { + size_t previous_space = line.find_last_of (' ', last_space - 1); + + if (previous_space != std::string::npos) { + // extract type and name + std::string type = line.substr (previous_space + 1, last_space - previous_space - 1); + std::string name = line.substr (last_space + 1, semicolon - last_space - 1); + std::string json = line.substr (comment + 2); + + this->parseParameterConfiguration (type, name, json); + } + } + } + + // Move to the next line + start = end + 1; + } +} + +void CShaderUnit::preprocessIncludes () { + size_t start = 0, end = 0; + // prepare the include content + while((start = this->m_preprocessed.find("#include", end)) != std::string::npos) { + // TODO: CHECK FOR ERRORS HERE, MALFORMED INCLUDES WILL NOT BE PROPERLY HANDLED + size_t quoteStart = this->m_preprocessed.find_first_of ('"', start) + 1; + size_t quoteEnd = this->m_preprocessed.find_first_of('"', quoteStart); + std::string filename = this->m_preprocessed.substr(quoteStart, quoteEnd - quoteStart); + + // some includes might not be present + // and that should not be treated as an error mainly because these could come from + // commented out content + std::string content; + + try { + content += "// begin of include from file "; + content += filename; + content += "\n"; + content += this->m_container->readIncludeShader (filename); + content += "\n// end of included from file "; + content += filename; + content += "\n"; + } catch (CAssetLoadException&) { + content += "// tried including file "; + content += filename; + content += " but was not found\n"; + } + + // replace the first two letters with a comment so the filelength doesn't change + this->m_preprocessed = this->m_preprocessed.replace (start, 2, "//"); + + this->m_includes += content; + + // go to the end of the line + end = start; + } + + // ensure the included files do not include other files + end = 0; + + // then apply includes in-place + while((start = this->m_includes.find("#include", end)) != std::string::npos) { + size_t lineEnd = this->m_includes.find_first_of ('\n', start); + // TODO: CHECK FOR ERRORS HERE, MALFORMED INCLUDES WILL NOT BE PROPERLY HANDLED + size_t quoteStart = this->m_includes.find_first_of ('"', start) + 1; + size_t quoteEnd = this->m_includes.find_first_of('"', quoteStart); + std::string filename = this->m_includes.substr(quoteStart, quoteEnd - quoteStart); + + // some includes might not be present + // and that should not be treated as an error mainly because these could come from + // commented out content + std::string content; + + try { + content = "// begin of include from file "; + content += filename; + content += "\n"; + content += this->m_container->readIncludeShader (filename); + content += "\n// end of included from file "; + content += filename; + content += "\n"; + } catch (CAssetLoadException&) { + content = "// tried including file "; + content += filename; + content += " but was not found\n"; + } + + // file contents ready, replace things + this->m_includes = this->m_includes.replace (start, lineEnd - start,content); + + // go back to the beginning of the line to properly continue detecting things + end = start; + } + + // search for the main function and add the includes before that for now + end = 0; + bool includesAdded = false; + + // finally, try to place the include contents before the main function + while ((start = this->m_preprocessed.find (" main", end)) != std::string::npos) { + char value = this->m_preprocessed.at(start + 5); + + end = start + 5; + + if (value != ' ' && value != '(') { + continue; + } + + // main located, search for uniforms and find the latest one available + size_t lastAttribute = this->m_preprocessed.rfind ("attribute", start); + size_t lastVarying = this->m_preprocessed.rfind ("varying", start); + size_t lastUniform = this->m_preprocessed.rfind ("uniform", start); + size_t latest = lastAttribute; + + if (latest == std::string::npos) { + latest = lastVarying; + } else if (latest < lastVarying && lastVarying != std::string::npos) { + latest = lastVarying; + } + + if (latest == std::string::npos) { + latest = lastUniform; + } else if (latest < lastUniform && lastUniform != std::string::npos) { + latest = lastUniform; + } + + if (latest < start) { + // find the end of the current line + latest = this->m_preprocessed.find ('\n', latest); + } else { + // find the end of the previous line + latest = this->m_preprocessed.rfind ('\n', start); + } + + // update the function start to point to the end of the previous line + // as this will be used to determine the position of the includes + start = this->m_preprocessed.rfind ('\n', start); + + // keeps track of the start and end of ifdefs to look for the right + // place to put the includes in + std::stack ifdefStack; + + // start looking for #if and #endif results and add to the stack so we find the start of the current chain of ifdefs + // and use that as point + + // for this we'll use regex + std::regex ifdef (R"((#if|#endif))"); + std::smatch match; + size_t current = 0; + + while (std::regex_search (this->m_preprocessed.cbegin () + current, this->m_preprocessed.cend (), match, ifdef)) { + current += match.position (); + + // if it's opening an #ifdef keep track of the start of the block + // and that's it + if (this->m_preprocessed.substr (current, 3) == "#if") { + // go to the next character so the regex doesn't match with the same thing again + ifdefStack.push (current++); + continue; + } + + // go to the next character so the regex doesn't match with the same thing again + current ++; + + // most likely a syntax error, but we'll ignore it for now... + if (ifdefStack.empty ()) { + continue; + } + + size_t stackStart = ifdefStack.top (); + ifdefStack.pop (); + + if (latest > stackStart && latest <= current) { + latest = this->m_preprocessed.find ('\n', current); + } + } + + // no more matches, get the one that happens the earliest + // TODO: IS THIS GOOD ENOUGH? MAYBE WE SHOULD BE GETTING THE FIRST #IF BLOCK INSTEAD? + latest = std::min (latest, start); + + // finally insert it there + this->m_preprocessed.insert (latest + 1, this->m_includes + '\n'); + includesAdded = true; + break; + } + + if (!includesAdded) { + sLog.exception ("Could not find where to place includes for shader unit ", this->m_file); + } +} + +void CShaderUnit::preprocessRequires () { + size_t start = 0, end = 0; + // comment out requires + while((start = this->m_preprocessed.find("#require", end)) != std::string::npos) { + // TODO: CHECK FOR ERRORS HERE + size_t lineEnd = this->m_preprocessed.find_first_of('\n', start); + sLog.out("Shader has a require block ", this->m_preprocessed.substr (start, lineEnd - start)); + // replace the first two letters with a comment so the filelength doesn't change + this->m_preprocessed = this->m_preprocessed.replace(start, 2, "//"); + + // go to the end of the line + end = lineEnd; + } +} + +void CShaderUnit::parseComboConfiguration (const std::string& content, int defaultValue) { + // TODO: SUPPORT REQUIRES SO WE PROPERLY FOLLOW THE REQUIRED CHAIN + json data = json::parse (content); + const auto combo = jsonFindRequired (data, "combo", "cannot parse combo information"); + // ignore type as it seems to be used only on the editor + // const auto type = data.find ("type"); + const auto defvalue = data.find ("default"); + + // check the combos + const auto entry = this->m_combos.find (combo->get ()); + + // add the combo to the found list + this->m_usedCombos.emplace (*combo, true); + + // if the combo was not found in the predefined values this means that the default value in the JSON data can be + // used so only define the ones that are not already defined + if (entry == this->m_combos.end ()) { + + // if no combo is defined just load the default settings + if (defvalue == data.end ()) { + // TODO: PROPERLY SUPPORT EMPTY COMBOS + this->m_discoveredCombos.emplace (*combo, (int) defaultValue); + } else if (defvalue->is_number_float ()) { + sLog.exception ("float combos are not supported in shader ", this->m_file, ". ", *combo); + } else if (defvalue->is_number_integer ()) { + this->m_discoveredCombos.emplace (*combo, defvalue->get ()); + } else if (defvalue->is_string ()) { + sLog.exception ("string combos are not supported in shader ", this->m_file, ". ", *combo); + } else { + sLog.exception ("cannot parse combo information ", *combo, ". unknown type for ", defvalue->dump ()); + } + } +} + +void CShaderUnit::parseParameterConfiguration ( + const std::string& type, const std::string& name, const std::string& content +) { + json data = json::parse (content); + const auto material = data.find ("material"); + const auto defvalue = data.find ("default"); + // auto range = data.find ("range"); + const auto combo = data.find ("combo"); + + // this is not a real parameter + auto constant = this->m_constants.end (); + + if (material != data.end ()) + constant = this->m_constants.find (*material); + + if (constant == this->m_constants.end () && defvalue == data.end ()) { + if (type != "sampler2D") + sLog.exception ("Cannot parse parameter data for ", name, " in shader ", this->m_file); + } + + Variables::CShaderVariable* parameter = nullptr; + + // TODO: SUPPORT VALUES FOR ALL THESE TYPES + // TODO: MAYBE EVEN CONNECT THESE TO THE CORRESPONDING PROPERTY SO THINGS ARE UPDATED AS THE ORIGIN VALUES CHANGE? + if (type == "vec4") { + parameter = new Variables::CShaderVariableVector4 (WallpaperEngine::Core::aToVector4 (*defvalue)); + } else if (type == "vec3") { + parameter = new Variables::CShaderVariableVector3 (WallpaperEngine::Core::aToVector3 (*defvalue)); + } else if (type == "vec2") { + parameter = new Variables::CShaderVariableVector2 (WallpaperEngine::Core::aToVector2 (*defvalue)); + } else if (type == "float") { + if (defvalue->is_string ()) { + parameter = new Variables::CShaderVariableFloat (strtof32 ((defvalue->get ()).c_str (), nullptr)); + } else { + parameter = new Variables::CShaderVariableFloat (*defvalue); + } + } else if (type == "int") { + if (defvalue->is_string ()) { + parameter = new Variables::CShaderVariableInteger (strtol((defvalue->get ()).c_str (), nullptr, 10)); + } else { + parameter = new Variables::CShaderVariableInteger (*defvalue); + } + } else if (type == "sampler2D" || type == "sampler2DComparison") { + // samplers can have special requirements, check what sampler we're working with and create definitions + // if needed + const auto textureName = data.find ("default"); + // extract the texture number from the name + const char value = name.at (std::string ("g_Texture").length ()); + const auto requireany = data.find ("requireany"); + const auto require = data.find ("require"); + // now convert it to integer + size_t index = value - '0'; + + if (combo != data.end ()) { + // if the texture exists (and is not null), add to the combo + auto texture = this->m_passTextures.find (index); + bool isRequired = false; + int comboValue = 1; + + if (texture != this->m_passTextures.end ()) { + // nothing extra to do, the texture exists, the combo must be set + // these tend to not have default value + isRequired = true; + } else if (require != data.end ()) { + // this is required based on certain conditions + if (requireany != data.end () && requireany->get ()) { + // any of the values set are valid, check for them + for (const auto& item : require->items ()) { + const std::string& macro = item.key (); + const auto it = this->m_combos.find (macro); + + // if any of the values matched, this option is required + if (it == this->m_combos.end () || it->second != item.value ()) { + isRequired = true; + break; + } + } + } else { + isRequired = true; + + // all values must match for it to be required + for (const auto& item : require->items ()) { + const std::string& macro = item.key (); + const auto it = this->m_combos.find (macro); + + // these can not exist and that'd be fine, we just care about the values + if (it != this->m_combos.end () && it->second == item.value ()) { + isRequired = false; + break; + } + } + } + } + + if (isRequired && texture == this->m_passTextures.end ()) { + if (defvalue == data.end ()) { + isRequired = false; + } else { + // is the combo registered already? + // if not, add it with the default value + const auto combo_it = this->m_combos.find (*combo); + + // there's already a combo providing this value, so it doesn't need to be added + if (combo_it != this->m_combos.end ()) { + isRequired = false; + // otherwise a default value must be used + } else if (defvalue->is_string ()) { + comboValue = strtol (defvalue->get ().c_str (), nullptr, 10); + } else if (defvalue->is_number()) { + comboValue = *defvalue; + } else { + sLog.exception ("Cannot determine default value for combo ", combo->get (), " because it's not specified by the shader and is not given a default value: ", this->m_file); + } + } + } + + if (isRequired) { + // add the new combo to the list + this->m_discoveredCombos.emplace (*combo, comboValue); + // textures linked to combos need to be tracked too + this->m_usedCombos.emplace (*combo, true); + } + } + + if (textureName != data.end ()) + this->m_defaultTextures.emplace (index, *textureName); + + // samplers are not saved, we can ignore them for now + return; + } else { + sLog.error ("Unknown parameter type: ", type, " for ", name, " in shader ", this->m_file); + return; + } + + if (material != data.end () && parameter != nullptr) { + parameter->setIdentifierName (*material); + parameter->setName (name); + + this->m_parameters.push_back (parameter); + } +} + +const std::map& CShaderUnit::getCombos () const { + return this->m_combos; +} + +const std::map& CShaderUnit::getDiscoveredCombos () const { + return this->m_discoveredCombos; +} + +void CShaderUnit::linkToUnit (const CShaderUnit* unit) { + this->m_link = unit; +} + +const CShaderUnit* CShaderUnit::getLinkedUnit () const { + return this->m_link; +} + +const std::string& CShaderUnit::compile () { + if (!this->m_final.empty ()) { + return this->m_final; + } + + this->m_final = SHADER_HEADER(this->m_file); + + if (this->m_type == CGLSLContext::UnitType_Fragment) { + this->m_final += FRAGMENT_SHADER_DEFINES; + } else { + this->m_final += VERTEX_SHADER_DEFINES; + } + + std::map addedCombos; + + // now add all the combos to the source + for (const auto& combo : this->m_combos) { + if (addedCombos.find (combo.first) == addedCombos.end ()) { + this->m_final += DEFINE_COMBO (combo.first, combo.second); + } + } + for (const auto& combo : this->m_discoveredCombos) { + if (addedCombos.find (combo.first) == addedCombos.end ()) { + this->m_final += DEFINE_COMBO (combo.first, combo.second); + } + } + if (this->m_link != nullptr) { + for (const auto& combo : this->m_link->getCombos ()) { + if (addedCombos.find (combo.first) == addedCombos.end ()) { + this->m_final += DEFINE_COMBO (combo.first, combo.second); + } + } + for (const auto& combo : this->m_link->getDiscoveredCombos ()) { + if (addedCombos.find (combo.first) == addedCombos.end ()) { + this->m_final += DEFINE_COMBO (combo.first, combo.second); + } + } + } + + // this should be the rest of the shader + this->m_final += this->m_preprocessed; + + // shader compilation is handled by the pass itself, the unit doesn't have enough information for this step + return this->m_final; +} + +const std::vector& CShaderUnit::getParameters () const { + return this->m_parameters; +} +const std::map& CShaderUnit::getTextures () const { + return this->m_defaultTextures; +} \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/CShaderUnit.h b/src/WallpaperEngine/Render/Shaders/CShaderUnit.h new file mode 100644 index 0000000..2c13e09 --- /dev/null +++ b/src/WallpaperEngine/Render/Shaders/CShaderUnit.h @@ -0,0 +1,156 @@ +#pragma once + +#include +#include +#include + +#include "CGLSLContext.h" +#include "WallpaperEngine/Assets/CContainer.h" +#include "WallpaperEngine/Core/Core.h" +#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" +#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" +#include "nlohmann/json.hpp" + +namespace WallpaperEngine::Render::Shaders { +using json = nlohmann::json; +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::Core::Objects::Effects::Constants; +/** + * Represents a whole shader unit + */ +class CShaderUnit { + public: + CShaderUnit ( + CGLSLContext::UnitType type, std::string file, std::string content, std::shared_ptr container, + const std::map& constants, const std::map& passTextures, + const std::map& combos); + ~CShaderUnit () = default; + + /** + * Links this shader unit with another unit so they're treated as one + * + * @param unit + */ + void linkToUnit (const CShaderUnit* unit); + /** + * @return The shader unit linked to this unit (if any) + */ + [[nodiscard]] const CShaderUnit* getLinkedUnit () const; + + /** + * @return The unit's source code already compiled and ready to be used by OpenGL + */ + [[nodiscard]] const std::string& compile (); + + /** + * @return The parameters the shader unit has as input + */ + [[nodiscard]] const std::vector& getParameters () const; + /** + * @return The textures this shader unit requires + */ + [[nodiscard]] const std::map& getTextures () const; + /** + * @return The combos set for this shader unit by the configuration + */ + [[nodiscard]] const std::map& getCombos () const; + /** + * @return Other combos detected by this shader unit during the preprocess + */ + [[nodiscard]] const std::map& getDiscoveredCombos () const; + + protected: + /** + * Extracts any and all possible shader combo configurations + * available in this shader unit, prepares includes + * and lays the ground for the actual code to be ready + */ + void preprocess (); + + private: + /** + * Parses the input shader looking for possible combo values that are required for it to properly work + */ + void preprocessVariables (); + /** + * Parses the input shader looking for include directives to extract the full list of included files + */ + void preprocessIncludes (); + /** + * Parses the input shader lookin for require directives to comment them out for now + */ + void preprocessRequires (); + + /** + * Parses a COMBO value to add the proper define to the code + * + * @param content The parameter configuration + * @param defaultValue + */ + void parseComboConfiguration (const std::string& content, int defaultValue = 0); + /** + * Parses a parameter extra metadata created by wallpaper engine + * + * @param type The type of variable to parse + * @param name The name of the variable in the shader (for actual variable declaration) + * @param content The parameter configuration + */ + void parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content); + /** + * The type of shder unit we have + */ + CGLSLContext::UnitType m_type; + /** + * The filename of this shader unit + */ + std::string m_file = ""; + /** + * Shader's original contents + */ + std::string m_content = ""; + /** + * Includes content to be added on compilation + */ + std::string m_includes = ""; + /** + * Shader's content after the preprocessing step + */ + std::string m_preprocessed = ""; + /** + * Shader's code after the compilation of glslang and spirv + */ + std::string m_final = ""; + /** + * The parameters the shader needs + */ + std::vector m_parameters = {}; + /** + * Pre-defined values for the combos + */ + const std::map& m_combos; + /** + * The combos discovered in the pre-processing step that were not in the combos list + */ + std::map m_discoveredCombos = {}; + /** + * The combos used by this unit that should be added + */ + std::map m_usedCombos = {}; + /** + * The constants defined for this unit + */ + const std::map& m_constants; + /** The textures that are already applied to this shader */ + const std::map m_passTextures; + /** The default textures to use when a texture is not applied in a given slot */ + std::map m_defaultTextures = {}; + /** + * The shader unit this unit is linked to + */ + const CShaderUnit* m_link; + /** + * The container to source files from + */ + const std::shared_ptr m_container; +}; +} diff --git a/src/WallpaperEngine/Render/Shaders/Compiler.cpp b/src/WallpaperEngine/Render/Shaders/Compiler.cpp deleted file mode 100644 index 1325237..0000000 --- a/src/WallpaperEngine/Render/Shaders/Compiler.cpp +++ /dev/null @@ -1,771 +0,0 @@ -#include "common.h" -#include -#include -#include -#include - -// filesystem -#include - -// shader compiler -#include -#include -#include -#include -#include -#include - -#include "WallpaperEngine/Assets/CAssetLoadException.h" -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h" -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h" -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h" -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h" -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h" - -using namespace WallpaperEngine::Core; -using namespace WallpaperEngine::Assets; - -namespace WallpaperEngine::Render::Shaders { -Compiler::Compiler (CContainer* container, std::string filename, Type type, std::map* combos, - std::map* foundCombos, const std::vector& textures, - const std::map& constants, bool recursive) : - m_combos (combos), - m_foundCombos (foundCombos), - m_passTextures (textures), - m_recursive (recursive), - m_type (type), - m_file (std::move (filename)), - m_error (), - m_constants (constants), - m_container (container) { - if (type == Type_Vertex) - this->m_content = this->m_container->readVertexShader (this->m_file); - else if (type == Type_Pixel) - this->m_content = this->m_container->readFragmentShader (this->m_file); - else if (type == Type_Include) - this->m_content = this->m_container->readIncludeShader (this->m_file); - - // clone the combos into the baseCombos to keep track of values that must be embedded no matter what - for (const auto& [name, value] : *this->m_combos) - this->m_baseCombos.insert (std::make_pair (name, value)); -} - -bool Compiler::peekString (std::string str, std::string::const_iterator& it) { - std::string::const_iterator check = str.begin (); - std::string::const_iterator cur = it; - - while (cur != this->m_content.end () && check != str.end ()) { - if (*cur != *check) - return false; - - ++cur; - ++check; - } - - if (cur == this->m_content.end ()) { - return false; - } - - if (check != str.end ()) { - return false; - } - - it = cur; - - return true; -} - -bool Compiler::expectSemicolon (std::string::const_iterator& it) { - if (*it != ';') { - this->m_error = true; - this->m_errorInfo = std::string ("Expected semicolon but got ") + *it; - return false; - } - - ++it; - - return true; -} - -void Compiler::ignoreSpaces (std::string::const_iterator& it) { - while (it != this->m_content.end () && (*it == ' ' || *it == '\t')) - ++it; -} - -void Compiler::ignoreUpToNextLineFeed (std::string::const_iterator& it) { - while (it != this->m_content.end () && *it != '\n') - ++it; -} - -void Compiler::ignoreUpToBlockCommentEnd (std::string::const_iterator& it) { - while (it != this->m_content.end () && !this->peekString ("*/", it)) - ++it; -} - -std::string Compiler::extractType (std::string::const_iterator& it) { - // first of all check for highp/mediump/lowp as these operators have to be ignored - this->peekString ("highp", it); - this->peekString ("mediump", it); - this->peekString ("lowp", it); - this->ignoreSpaces (it); - - auto cur = sTypes.begin (); - const auto end = sTypes.end (); - - while (cur != end) { - if (this->peekString (*cur + " ", it)) - return *cur; - - ++cur; - } - - this->m_error = true; - this->m_errorInfo = "Expected type"; - return ""; -} - -std::string Compiler::extractName (std::string::const_iterator& it) { - std::string::const_iterator cur = it; - std::string::const_iterator begin = cur; - - // first character has to be a valid alphabetic characer - if (!this->isChar (cur) && *cur != '_') { - this->m_error = true; - this->m_errorInfo = "Expected name doesn't start with a valid character"; - return ""; - } - - ++cur; - - while (cur != this->m_content.end () && (this->isChar (cur) || *cur == '_' || this->isNumeric (cur))) - ++cur; - - it = cur; - - return {begin, cur}; -} - -std::string Compiler::extractArray (std::string::const_iterator& it, bool mustExists) { - auto cur = it; - auto begin = cur; - - if (*cur != '[') { - if (!mustExists) { - return ""; - } - - this->m_error = true; - this->m_errorInfo = "Expected an array but found nothing"; - return ""; - } - - ++cur; - - while (cur != this->m_content.end () && *cur != ']') - ++cur; - - it = ++cur; - - return {begin, cur}; -} - -bool Compiler::isChar (const std::string::const_iterator& it) { - return ((*it) >= 'A' && (*it) <= 'Z') || ((*it) >= 'a' && (*it) <= 'z'); -} - -bool Compiler::isNumeric (const std::string::const_iterator& it) { - return (*it) >= '0' && (*it) <= '9'; -} - -std::string Compiler::extractQuotedValue (std::string::const_iterator& it) { - std::string::const_iterator cur = it; - - if (*cur != '"') { - m_error = true; - m_errorInfo = std::string ("Expected opening \" but got ") + (*cur); - return ""; - } - - ++cur; - - while (cur != this->m_content.end () && *cur != '\n' && *cur != '"') - ++cur; - - if (cur == this->m_content.end ()) { - m_error = true; - m_errorInfo = "Expected closing \" not found"; - it = cur; - return ""; - } - - std::string filename = std::string (++it, cur); - - it = ++cur; - - return filename; -} - -std::string Compiler::lookupShaderFile (std::string filename) { - // now compile the new shader - // do not include the default header (as it's already included in the parent) - Compiler loader (this->m_container, std::move (filename), Type_Include, this->m_combos, this->m_foundCombos, - this->m_passTextures, this->m_constants, true); - - loader.precompile (); - - return loader.getCompiled (); -} - -std::string& Compiler::getCompiled () { - return this->m_compiledContent; -} - -void Compiler::precompile () { - // TODO: SEPARATE THIS IN TWO SO THE COMBOS ARE DETECTED FIRST AND WE DO NOT REQUIRE DOUBLE COMPILATION OF THE - // SHADER'S SOURCE -#define BREAK_IF_ERROR \ - if (this->m_error) { \ - sLog.exception ("ERROR PRE-COMPILING SHADER.", this->m_errorInfo); \ - } - // parse the shader and find #includes and such things and translate them to the correct name - // also remove any #version definition to prevent errors - std::string::const_iterator it = this->m_content.begin (); - - // reset error indicator - this->m_error = false; - this->m_errorInfo = ""; - this->m_compiledContent = ""; - this->m_includesContent = ""; - this->m_includesProcessed = false; - - // search preprocessor macros and parse them - while (it != this->m_content.end () && !this->m_error) { - if (*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r' || *it == '\0' || *it == '{' || *it == '}' || - *it == '[' || *it == ']' || *it == '.') { - this->m_compiledContent += *it; - ++it; - } else if (*it == '#') { - if (this->peekString ("#include ", it)) { - // ignore whitespaces - this->ignoreSpaces (it); - BREAK_IF_ERROR - // extract value between quotes - std::string filename = this->extractQuotedValue (it); - BREAK_IF_ERROR - - if (this->m_recursive) { - this->m_compiledContent += "// begin of include from file " + filename + "\r\n"; - this->m_compiledContent += this->lookupShaderFile (filename); - this->m_compiledContent += "\r\n// end of included from file " + filename + "\r\n"; - } else { - // load the content to the includes contents and continue with the next one - // try to find the file first - this->m_includesContent += "// begin of included from file " + filename + "\r\n"; - this->m_includesContent += this->lookupShaderFile (filename); - this->m_includesContent += "\r\n// end of included from file " + filename + "\r\n"; - } - } else if (this->peekString ("#require ", it)) { - // TODO: PROPERLY IMPLEMENT #require - this->m_compiledContent += "// #require "; - // ignore whitespaces - this->ignoreSpaces (it); - BREAK_IF_ERROR - std::string name = this->extractName (it); - BREAK_IF_ERROR - this->m_compiledContent += name; - } else { - this->m_compiledContent += '#'; - ++it; - } - } else if (*it == 'u') { - // uniforms might have extra information for their values - if (this->peekString ("uniform ", it)) { - this->ignoreSpaces (it); - std::string type = this->extractType (it); - BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string name = this->extractName (it); - BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string array = this->extractArray (it, false); - BREAK_IF_ERROR - this->ignoreSpaces (it); - this->expectSemicolon (it); - BREAK_IF_ERROR - this->ignoreSpaces (it); - - // check if there is any actual extra information and parse it - if (this->peekString ("//", it)) { - this->ignoreSpaces (it); - std::string::const_iterator begin = it; - this->ignoreUpToNextLineFeed (it); - - std::string configuration; - configuration.append (begin, it); - - // parse the parameter information - this->parseParameterConfiguration (type, name, configuration); - BREAK_IF_ERROR - this->m_compiledContent += "uniform "; - this->m_compiledContent += type; - this->m_compiledContent += " "; - this->m_compiledContent += name; - this->m_compiledContent += array; - this->m_compiledContent += "; // "; - this->m_compiledContent += configuration; - } else { - this->m_compiledContent += "uniform "; - this->m_compiledContent += type; - this->m_compiledContent += " "; - this->m_compiledContent += name; - this->m_compiledContent += array; - this->m_compiledContent += ";"; - } - } else { - // continue reading the original shader as this most likely is a variable name or something - // that is not really interesting for the compiler - this->m_compiledContent += *it; - ++it; - } - } else if (*it == 'a') { - // find attribute definitions - if (this->peekString ("attribute ", it)) { - this->ignoreSpaces (it); - std::string type = this->extractType (it); - BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string name = this->extractName (it); - BREAK_IF_ERROR - this->ignoreSpaces (it); - std::string array = this->extractArray (it, false); - BREAK_IF_ERROR - this->ignoreSpaces (it); - this->expectSemicolon (it); - BREAK_IF_ERROR - - this->m_compiledContent += "attribute " + type + " " + name + array + ";"; - } else { - // check for types first - std::string type = this->extractType (it); - - // types not found, try names - if (!this->m_error) { - this->ignoreSpaces (it); - this->m_compiledContent += type; - } else { - this->m_error = false; - std::string name = this->extractName (it); - - if (!this->m_error) { - // check if the name is a translated one or not - this->m_compiledContent += name; - } else { - this->m_error = false; - this->m_compiledContent += *it; - ++it; - } - } - } - } else if (*it == '/') { - if (this->peekString ("//", it)) { - std::string::const_iterator begin = it - 2; - // is there a COMBO mark to take care of? - this->ignoreSpaces (it); - - if (this->peekString ("[COMBO]", it)) { - // parse combo json data to define the proper variables - this->ignoreSpaces (it); - begin = it; - this->ignoreUpToNextLineFeed (it); - - std::string configuration; - configuration.append (begin, it); - - this->m_compiledContent += "// [COMBO] " + configuration; - - this->parseComboConfiguration (configuration, 0); - BREAK_IF_ERROR; - } else if (this->peekString ("[COMBO_OFF]", it)) { - // parse combo json data to define the proper variables - this->ignoreSpaces (it); - begin = it; - this->ignoreUpToNextLineFeed (it); - - std::string configuration; - configuration.append (begin, it); - - this->m_compiledContent += "// [COMBO_OFF] " + configuration; - - this->parseComboConfiguration (configuration, 0); - BREAK_IF_ERROR; - } else { - // the comment can be ignored and put back as is - this->ignoreUpToNextLineFeed (it); - this->m_compiledContent.append (begin, it); - } - } else if (this->peekString ("/*", it)) { - std::string::const_iterator begin = it - 2; - this->ignoreUpToBlockCommentEnd (it); - this->m_compiledContent.append (begin, it); - } else { - this->m_compiledContent += *it; - ++it; - } - } else { - // check for types first - std::string type = this->extractType (it); - - // type found - if (!this->m_error) { - this->ignoreSpaces (it); - // check for main, and take it into account, this also helps adding the includes - std::string name = this->extractName (it); - - this->ignoreSpaces (it); - - if (this->peekString ("(", it)) { - if (!this->m_includesProcessed) { - this->m_compiledContent += "\n\n" + this->m_includesContent + "\n\n"; - this->m_includesProcessed = true; - } - - this->m_compiledContent += type + " " + name + "("; - } else { - this->m_compiledContent += type + " " + name; - } - } else { - this->m_error = false; - std::string name = this->extractName (it); - - if (!this->m_error) { - // check if the name is a translated one or not - this->m_compiledContent += name; - } else { - this->m_error = false; - this->m_compiledContent += *it++; - } - } - } - } - - std::string finalCode; - - if (!this->m_recursive) { - // add the opengl compatibility at the top - finalCode = "#version 330\n" - "// ======================================================\n" - "// Processed shader " + - this->m_file + - "\n" - "// ======================================================\n" - "precision highp float;\n" - "#define mul(x, y) ((y) * (x))\n" - "#define max(x, y) max (y, x)\n" - "#define lerp mix\n" - "#define frac fract\n" - "#define CAST2(x) (vec2(x))\n" - "#define CAST3(x) (vec3(x))\n" - "#define CAST4(x) (vec4(x))\n" - "#define CAST3X3(x) (mat3(x))\n" - "#define saturate(x) (clamp(x, 0.0, 1.0))\n" - "#define texSample2D texture\n" - "#define texSample2DLod textureLod\n" - "#define atan2 atan\n" - "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n" - "#define ddx dFdx\n" - "#define ddy(x) dFdy(-(x))\n" - "#define GLSL 1\n\n"; - - if (this->m_type == Type_Vertex) { - finalCode += "#define attribute in\n" - "#define varying out\n"; - } else { - finalCode += "out vec4 out_FragColor;\n" - "#define varying in\n"; - } - - finalCode += "// ======================================================\n" - "// Shader combo parameter definitions\n" - "// ======================================================\n"; - - finalCode += "// found combos from current shader\n"; - - // add combo values - for (const auto& [name, value] : *this->m_foundCombos) { - // find the right value for the combo in the combos map - auto combo = this->m_combos->find (name); - - if (combo == this->m_combos->end ()) - continue; - - finalCode += "#define " + name + " " + std::to_string (combo->second) + "\n"; - } - - finalCode += "// combos from pass\n"; - - // add base combos that come from the pass change that MUST be added - for (const auto& [name, value] : this->m_baseCombos) { - auto alreadyFound = this->m_foundCombos->find (name); - - if (alreadyFound != this->m_foundCombos->end ()) - continue; - - finalCode += "#define " + name + " " + std::to_string (value) + "\n"; - } - } - - // replace gl_FragColor with the equivalent - std::string from = "gl_FragColor"; - std::string to = "out_FragColor"; - - size_t start_pos = 0; - while ((start_pos = this->m_compiledContent.find (from, start_pos)) != std::string::npos) { - this->m_compiledContent.replace (start_pos, from.length (), to); - start_pos += to.length (); // Handles case where 'to' is a substring of 'from' - } - - // replace sample occurrences - from = "sample"; - to = "_sample"; - - start_pos = 0; - while ((start_pos = this->m_compiledContent.find (from, start_pos)) != std::string::npos) { - // ensure that after it comes something like a space or a ; or a tab - std::string after = this->m_compiledContent.substr (start_pos + from.length (), 1); - - if (after != " " && after != ";" && after != "\t" && after != "=" && after != "+" && after != "-" && - after != "/" && after != "*" && after != "." && after != "," && after != ")") { - start_pos += to.length (); // Handles case where 'to' is a substring of 'from' - continue; - } - - this->m_compiledContent.replace (start_pos, from.length (), to); - start_pos += to.length (); // Handles case where 'to' is a substring of 'from' - } - - try { - this->applyPatches (); - } catch (CAssetLoadException&) { - // nothing important, no patch was found - } - - finalCode += this->m_compiledContent; - - if (!this->m_recursive) { - sLog.debug ("======================== COMPILED ", (this->m_type == Type_Vertex ? "VERTEX" : "FRAGMENT"), - " SHADER ", this->m_file, " ========================"); - sLog.debug (finalCode); - } - - // store the final final code here - this->m_compiledContent = finalCode; -#undef BREAK_IF_ERROR -} - -void Compiler::applyPatches () { - // small patches for things, looks like the official wpengine does the same thing - std::filesystem::path file = this->m_file; - file = "patches" / file.filename (); - - if (this->m_type == Type_Vertex) - file += ".vert"; - else if (this->m_type == Type_Pixel) - file += ".frag"; - - file += ".json"; - - std::string tmp = file; - const std::string patchContents = this->m_container->readFileAsString (file); - - json data = json::parse (patchContents); - const auto patches = data.find ("patches"); - - for (auto patch : *patches) { - auto matches = patch.find ("matches"); - bool canApply = true; - - // check for matches first, as these signal whether the patch can be applied or not - for (const auto& match : *matches) { - if (this->m_compiledContent.find (match) == std::string::npos) { - canApply = false; - break; - } - } - - if (canApply == false) - continue; - - const auto replacements = patch.find ("replacements"); - - for (const auto& replacement : replacements->items ()) { - // replace gl_FragColor with the equivalent - std::string from = replacement.key (); - std::string to = replacement.value (); - - size_t start_pos = 0; - while ((start_pos = this->m_compiledContent.find (from, start_pos)) != std::string::npos) { - this->m_compiledContent.replace (start_pos, from.length (), to); - start_pos += to.length (); // Handles case where 'to' is a substring of 'from' - } - } - } -} - -void Compiler::parseComboConfiguration (const std::string& content, int defaultValue) { - json data = json::parse (content); - const auto combo = jsonFindRequired (data, "combo", "cannot parse combo information"); - const auto type = data.find ("type"); - const auto defvalue = data.find ("default"); - - // add line feed just in case - this->m_compiledContent += "\n"; - - // check the combos - const auto entry = this->m_combos->find (combo->get ()); - - // add the combo to the found list - this->m_foundCombos->insert (std::make_pair (*combo, true)); - - // if the combo was not found in the predefined values this means that the default value in the JSON data can be - // used so only define the ones that are not already defined - if (entry == this->m_combos->end ()) { - if (type != data.end ()) - sLog.error ("Resorting to default value as type ", *type, " is unknown"); - - // if no combo is defined just load the default settings - if (defvalue == data.end ()) { - // TODO: PROPERLY SUPPORT EMPTY COMBOS - this->m_combos->insert (std::make_pair (*combo, (int) defaultValue)); - } else if (defvalue->is_number_float ()) { - sLog.exception ("float combos are not supported in shader ", this->m_file, ". ", *combo); - } else if (defvalue->is_number_integer ()) { - this->m_combos->insert (std::make_pair (*combo, defvalue->get ())); - } else if (defvalue->is_string ()) { - sLog.exception ("string combos are not supported in shader ", this->m_file, ". ", *combo); - } else { - sLog.exception ("cannot parse combo information ", *combo, ". unknown type for ", defvalue->dump ()); - } - } -} - -void Compiler::parseParameterConfiguration (const std::string& type, const std::string& name, - const std::string& content) { - json data = json::parse (content); - const auto material = data.find ("material"); - const auto defvalue = data.find ("default"); - // auto range = data.find ("range"); - const auto combo = data.find ("combo"); - - // this is not a real parameter - auto constant = this->m_constants.end (); - - if (material != data.end ()) - constant = this->m_constants.find (*material); - - if (constant == this->m_constants.end () && defvalue == data.end ()) { - if (type != "sampler2D") - sLog.exception ("Cannot parse parameter data for ", name, " in shader ", this->m_file); - } - - Variables::CShaderVariable* parameter; - - // TODO: SUPPORT VALUES FOR ALL THESE TYPES - if (type == "vec4") { - parameter = new Variables::CShaderVariableVector4 ( - constant == this->m_constants.end () ? WallpaperEngine::Core::aToVector4 (*defvalue) - : *constant->second->as ()->getValue ()); - } else if (type == "vec3") { - parameter = new Variables::CShaderVariableVector3 ( - constant == this->m_constants.end () ? WallpaperEngine::Core::aToVector3 (*defvalue) - : *constant->second->as ()->getValue ()); - } else if (type == "vec2") { - parameter = new Variables::CShaderVariableVector2 (WallpaperEngine::Core::aToVector2 (*defvalue)); - } else if (type == "float") { - float value = 0; - - if (constant == this->m_constants.end ()) - value = defvalue->get (); - else if (constant->second->is ()) - value = *constant->second->as ()->getValue (); - else if (constant->second->is ()) - value = *constant->second->as ()->getValue (); - - parameter = new Variables::CShaderVariableFloat (value); - } else if (type == "int") { - int value = 0; - - if (constant == this->m_constants.end ()) - value = defvalue->get (); - else if (constant->second->is ()) - value = *constant->second->as ()->getValue (); - else if (constant->second->is ()) - value = *constant->second->as ()->getValue (); - - parameter = new Variables::CShaderVariableInteger (value); - } else if (type == "sampler2D" || type == "sampler2DComparison") { - // samplers can have special requirements, check what sampler we're working with and create definitions - // if needed - const auto textureName = data.find ("default"); - // extract the texture number from the name - const char value = name.at (std::string ("g_Texture").length ()); - // now convert it to integer - size_t index = value - '0'; - - if (combo != data.end ()) { - // if the texture exists (and is not null), add to the combo - if (this->m_passTextures.size () > index && - (!this->m_passTextures.at (index).empty () || textureName != data.end ())) { - // add the new combo to the list - this->m_combos->insert (std::make_pair (*combo, 1)); - - // textures linked to combos need to be tracked too - if (this->m_foundCombos->find (*combo) == this->m_foundCombos->end ()) - this->m_foundCombos->insert (std::make_pair (*combo, true)); - } - } - - if (textureName != data.end ()) - this->m_textures.insert (std::make_pair (index, *textureName)); - - // samplers are not saved, we can ignore them for now - return; - } else { - this->m_error = true; - this->m_errorInfo = "Unknown parameter type: " + type + " for " + name; - return; - } - - if (material != data.end ()) { - parameter->setIdentifierName (*material); - parameter->setName (name); - - this->m_parameters.push_back (parameter); - } -} - -Variables::CShaderVariable* Compiler::findParameter (const std::string& identifier) { - for (const auto& cur : this->m_parameters) - if (cur->getIdentifierName () == identifier) - return cur; - - return nullptr; -} - -const std::vector& Compiler::getParameters () const { - return this->m_parameters; -} - -std::map* Compiler::getCombos () const { - return this->m_combos; -} - -const std::map& Compiler::getTextures () const { - return this->m_textures; -} - -std::vector Compiler::sTypes = {"vec4", "uvec4", "ivec4", "dvec4", "bvec4", "vec3", - "uvec3", "ivec3", "dvec3", "bvec3", "vec2", "uvec2", - "ivec2", "dvec2", "bvec2", "float", "sampler2D", "sampler2DComparison", - "mat4x3", "mat4", "mat3", "uint", "uint4", "void"}; -} // namespace WallpaperEngine::Render::Shaders diff --git a/src/WallpaperEngine/Render/Shaders/Compiler.h b/src/WallpaperEngine/Render/Shaders/Compiler.h deleted file mode 100644 index 79d69a5..0000000 --- a/src/WallpaperEngine/Render/Shaders/Compiler.h +++ /dev/null @@ -1,267 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "WallpaperEngine/Assets/CContainer.h" -#include "WallpaperEngine/Assets/ITexture.h" -#include "WallpaperEngine/Core/Core.h" -#include "WallpaperEngine/Core/Objects/Effects/Constants/CShaderConstant.h" -#include "WallpaperEngine/FileSystem/FileSystem.h" -#include "WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h" - -namespace WallpaperEngine::Render::Shaders { -using json = nlohmann::json; -using namespace WallpaperEngine::Assets; -using namespace WallpaperEngine::Core::Objects::Effects::Constants; - -/** - * A basic shader loader that adds basic function definitions to every loaded shader - */ -class Compiler { - public: - /** - * Types of shaders - */ - enum Type { - Type_Vertex = 0, - Type_Pixel = 1, - Type_Include = 2 - }; - - /** - * Types of variables the pre-processor understands - */ - static std::vector sTypes; - - /** - * Compiler constructor, loads the given shader file and prepares - * the pre-processing and compilation of the shader, adding - * required definitions if needed - * - * @param container The container to use for file lookup - * @param filename The file to load - * @param type The type of shader - * @param combos Settings for the shader - * @param foundCombos The list of currently defined combos - * @param textures The list of available textures for the shader - * @param constants Default values for shader variables - * @param recursive Whether the compiler should add base definitions or not - */ - Compiler (CContainer* container, std::string filename, Type type, std::map* combos, - std::map* foundCombos, const std::vector& textures, - const std::map& constants, bool recursive = false); - /** - * Performs the actual pre-compilation/pre-processing over the shader files - * This step is kinda big, replaces variables names on sVariableReplacement, - * ensures #include directives are correctly handled - * and takes care of attribute comments for the wallpaper engine specifics - */ - void precompile (); - /** - * @return The compiled shader's text (if available) - */ - std::string& getCompiled (); - - /** - * Searches the list of parameters available for the parameter with the given value - * - * @param identifier The identifier to search for - * @return The shader information - */ - Variables::CShaderVariable* findParameter (const std::string& identifier); - - /** - * @return The list of parameters available for this shader with their default values - */ - [[nodiscard]] const std::vector& getParameters () const; - /** - * @return The list of combos available for this shader after compilation - */ - [[nodiscard]] std::map* getCombos () const; - /** - * @return The list of textures inferred from the shader's code - */ - [[nodiscard]] const std::map& getTextures () const; - - private: - /** - * Checks if there is "str" in the current position without advancing the - * iterator in use - * - * @param str The string to check for - * @param it The position to start checking at - * - * @return - */ - bool peekString (std::string str, std::string::const_iterator& it); - /** - * Checks for a semicolon as current character, advancing the iterator - * after finding it, otherwise returns an error - * - * @param it The position where to expect the semicolon - * - * @return - */ - bool expectSemicolon (std::string::const_iterator& it); - /** - * Ignores contiguous space characters in the string advancing the iterator - * until the first non-space character - * - * @param it The iterator to increase - */ - void ignoreSpaces (std::string::const_iterator& it); - /** - * Ignores all characters until next line-fee (\n) advancing the interator - * - * @param it The iterator to increase - */ - void ignoreUpToNextLineFeed (std::string::const_iterator& it); - /** - * Ignores all characters until a block comment end is found, advancing the iterator - * - * @param it The iterator to increase - */ - void ignoreUpToBlockCommentEnd (std::string::const_iterator& it); - /** - * Parses the current position as a variable type, extracts it and compares it - * to the registered types in the pre-processor, returning it's name if valid - * increasing the iterator at the same time - * - * @param it The position to extract it from - * - * @return The type name - */ - std::string extractType (std::string::const_iterator& it); - /** - * Parses the current position as a variable name, extractig it's name and - * increasing the iterator as the name is extracted - * - * @param it The position to start extracting the variable name from - * - * @return The variable name - */ - std::string extractName (std::string::const_iterator& it); - /** - * Parses the current position as an array indicator - * - * @param it The position to start extracting the array from - * @param mustExists Whether the array indicator must exists or not - * @return - */ - std::string extractArray (std::string::const_iterator& it, bool mustExists = false); - /** - * Parses the current position as a quoted value, extracting it's value - * and increasing the iterator at the same time - * - * @param it The position to start extracting the value from - * - * @return The value - */ - std::string extractQuotedValue (std::string::const_iterator& it); - /** - * Tries to find the given shader file and compile it - * - * @param filename The shader's filename - * - * @return The compiled contents - */ - std::string lookupShaderFile (std::string filename); - - /** - * @return Whether the character in the current position is a character or not - */ - static bool isChar (const std::string::const_iterator& it); - /** - * @return Whether the character in the current position is a number or not - */ - static bool isNumeric (const std::string::const_iterator& it); - /** - * Parses a COMBO value to add the proper define to the code - * - * @param content The parameter configuration - * @param defaultValue - */ - void parseComboConfiguration (const std::string& content, int defaultValue = 0); - /** - * Parses a parameter extra metadata created by wallpaper engine - * - * @param type The type of variable to parse - * @param name The name of the variable in the shader (for actual variable declaration) - * @param content The parameter configuration - */ - void parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content); - /** - * Applies any available patches for this shader - */ - void applyPatches (); - - /** - * The shader file this instance is loading - */ - std::string m_file; - /** - * The original file content - */ - std::string m_content; - /** The content of all the included files */ - std::string m_includesContent; - /** - * The final, compiled content ready to be used by OpenGL - */ - std::string m_compiledContent; - /** - * Whether there was any kind of error in the compilation or not - */ - bool m_error; - /** - * Extra information about the error (if any) - */ - std::string m_errorInfo; - /** - * The type of shader - */ - Type m_type; - /** - * The parameters the shader needs - */ - std::vector m_parameters; - /** - * The combos the shader should be generated with - */ - std::map* m_combos; - - /** - * Combos that come from the pass' chain that should be added - */ - std::map m_baseCombos; - - /** - * The combos the shader code has defined (shared between fragment and vertex) - */ - std::map* m_foundCombos; - - /** - * The list of textures the pass knows about - */ - const std::vector m_passTextures; - /** - * The shader constants with values for variables inside the shader - */ - const std::map& m_constants; - /** - * Whether this compilation is a recursive one or not - */ - bool m_recursive; - /** - * The container to load files from - */ - CContainer* m_container; - /** - * List of textures that the shader expects (inferred from sampler2D and it's JSON data) - */ - std::map m_textures; - bool m_includesProcessed = false; -}; -} // namespace WallpaperEngine::Render::Shaders diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp index ecfe9ae..779504b 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.cpp @@ -4,22 +4,6 @@ using namespace WallpaperEngine::Render::Shaders::Variables; -CShaderVariable::CShaderVariable (void* defaultValue, void* value, std::string type) : - m_defaultValue (defaultValue), - m_value (value), - m_type (std::move (type)) {} - -const void* CShaderVariable::getValue () const { - if (this->m_value) - return this->m_value; - - return this->m_defaultValue; -} - -void CShaderVariable::setValue (void* value) { - this->m_value = value; -} - const std::string& CShaderVariable::getIdentifierName () const { return this->m_identifierName; } @@ -28,9 +12,6 @@ const std::string& CShaderVariable::getName () const { return this->m_name; } -const std::string& CShaderVariable::getType () const { - return this->m_type; -} void CShaderVariable::setIdentifierName (std::string identifierName) { this->m_identifierName = std::move (identifierName); diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h index ebc00ef..f5d09ce 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariable.h @@ -1,46 +1,41 @@ #pragma once +#include "WallpaperEngine/Core/DynamicValues/CDynamicValue.h" #include namespace WallpaperEngine::Render::Shaders::Variables { -class CShaderVariable { +class CShaderVariable : public Core::DynamicValues::CDynamicValue { public: - CShaderVariable (void* defaultValue, void* value, std::string type); virtual ~CShaderVariable () = default; - template const T* as () const { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] const T* as () const { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template T* as () { - assert (is ()); - return reinterpret_cast (this); + template [[nodiscard]] T* as () { + if (is ()) { + return static_cast (this); + } + + throw std::bad_cast (); } - template bool is () { - return this->m_type == T::Type; + template [[nodiscard]] bool is () const { + return typeid (*this) == typeid(T); } - const std::string& getIdentifierName () const; - const std::string& getName () const; - const std::string& getType () const; + [[nodiscard]] const std::string& getIdentifierName () const; + [[nodiscard]] const std::string& getName () const; void setIdentifierName (std::string identifierName); void setName (const std::string& name); - const void* getValue () const; - - virtual const int getSize () const = 0; - - protected: - void setValue (void* value); private: - std::string m_identifierName; - std::string m_name; - std::string m_type; - - void* m_defaultValue; - void* m_value; + std::string m_identifierName = ""; + std::string m_name = ""; }; } // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp index 07d7e12..d171b0d 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.cpp @@ -5,25 +5,12 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableFloat::CShaderVariableFloat (float defaultValue) : - m_defaultValue (defaultValue), - m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) {} + CShaderVariable () { + this->update (defaultValue); +} CShaderVariableFloat::CShaderVariableFloat (float defaultValue, const std::string& name) : - m_defaultValue (defaultValue), - m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) { + CShaderVariable () { this->setName (name); + this->update (defaultValue); } - -void CShaderVariableFloat::setValue (float value) { - this->m_value = value; - - CShaderVariable::setValue (&this->m_value); -} - -const int CShaderVariableFloat::getSize () const { - return 1; -} - -const std::string CShaderVariableFloat::Type = "float"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h index e60c460..6a7b2ce 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableFloat.h @@ -7,15 +7,5 @@ class CShaderVariableFloat final : public CShaderVariable { public: explicit CShaderVariableFloat (float defaultValue); CShaderVariableFloat (float defaultValue, const std::string& name); - - const int getSize () const override; - - void setValue (float value); - - static const std::string Type; - - private: - float m_defaultValue; - float m_value; }; } // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp index 117c753..3e551ba 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.cpp @@ -5,24 +5,12 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableInteger::CShaderVariableInteger (int32_t defaultValue) : - m_defaultValue (defaultValue), - m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) {} - -CShaderVariableInteger::CShaderVariableInteger (int32_t defaultValue, std::string name) : - m_defaultValue (defaultValue), - m_value (0), - CShaderVariable (&this->m_defaultValue, nullptr, Type) { - this->setName (std::move (name)); + CShaderVariable () { + this->update (defaultValue); } -void CShaderVariableInteger::setValue (int32_t value) { - this->m_value = value; - CShaderVariable::setValue (&this->m_value); +CShaderVariableInteger::CShaderVariableInteger (int32_t defaultValue, const std::string& name) : + CShaderVariable () { + this->setName (name); + this->update (defaultValue); } - -const int CShaderVariableInteger::getSize () const { - return 1; -} - -const std::string CShaderVariableInteger::Type = "int"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h index 1011d92..bc53dd3 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableInteger.h @@ -6,16 +6,6 @@ namespace WallpaperEngine::Render::Shaders::Variables { class CShaderVariableInteger final : public CShaderVariable { public: explicit CShaderVariableInteger (int32_t defaultValue); - CShaderVariableInteger (int32_t defaultValue, std::string name); - - const int getSize () const override; - - static const std::string Type; - - void setValue (int32_t value); - - private: - int32_t m_defaultValue; - int32_t m_value; + CShaderVariableInteger (int32_t defaultValue, const std::string& name); }; } // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp index 4e89c22..84198ec 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.cpp @@ -5,25 +5,12 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableVector2::CShaderVariableVector2 (const glm::vec2& defaultValue) : - m_defaultValue (defaultValue), - m_value (glm::vec2 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) {} - -CShaderVariableVector2::CShaderVariableVector2 (const glm::vec2& defaultValue, std::string name) : - m_defaultValue (defaultValue), - m_value (glm::vec2 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) { - this->setName (std::move (name)); + CShaderVariable () { + this->update (defaultValue); } -void CShaderVariableVector2::setValue (const glm::vec2& value) { - this->m_value = value; - - CShaderVariable::setValue (&this->m_value); +CShaderVariableVector2::CShaderVariableVector2 (const glm::vec2& defaultValue, const std::string& name) : + CShaderVariable () { + this->setName (name); + this->update (defaultValue); } - -const int CShaderVariableVector2::getSize () const { - return 2; -} - -const std::string CShaderVariableVector2::Type = "vec2"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h index a992728..b225277 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector2.h @@ -7,16 +7,6 @@ namespace WallpaperEngine::Render::Shaders::Variables { class CShaderVariableVector2 final : public CShaderVariable { public: explicit CShaderVariableVector2 (const glm::vec2& defaultValue); - CShaderVariableVector2 (const glm::vec2& defaultValue, std::string name); - - const int getSize () const override; - - void setValue (const glm::vec2& value); - - static const std::string Type; - - private: - glm::vec2 m_defaultValue; - glm::vec2 m_value; + CShaderVariableVector2 (const glm::vec2& defaultValue, const std::string& name); }; } // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp index c2109e7..fadf009 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.cpp @@ -3,24 +3,12 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableVector3::CShaderVariableVector3 (const glm::vec3& defaultValue) : - m_defaultValue (defaultValue), - m_value (glm::vec3 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) {} + CShaderVariable () { + this->update (defaultValue); +} CShaderVariableVector3::CShaderVariableVector3 (const glm::vec3& defaultValue, const std::string& name) : - m_defaultValue (defaultValue), - m_value (glm::vec3 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) { + CShaderVariable () { this->setName (name); + this->update (defaultValue); } - -void CShaderVariableVector3::setValue (const glm::vec3& value) { - this->m_value = value; - CShaderVariable::setValue (&this->m_value); -} - -const int CShaderVariableVector3::getSize () const { - return 3; -} - -const std::string CShaderVariableVector3::Type = "vec3"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h index c7c8731..7c989c1 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector3.h @@ -9,15 +9,5 @@ class CShaderVariableVector3 final : public CShaderVariable { public: explicit CShaderVariableVector3 (const glm::vec3& defaultValue); CShaderVariableVector3 (const glm::vec3& defaultValue, const std::string& name); - - const int getSize () const override; - - void setValue (const glm::vec3& value); - - static const std::string Type; - - private: - glm::vec3 m_defaultValue; - glm::vec3 m_value; }; } // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp index 1349a40..1b8a519 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.cpp @@ -5,24 +5,12 @@ using namespace WallpaperEngine::Render::Shaders::Variables; CShaderVariableVector4::CShaderVariableVector4 (const glm::vec4& defaultValue) : - m_defaultValue (defaultValue), - m_value (glm::vec4 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) {} + CShaderVariable () { + this->update (defaultValue); +} CShaderVariableVector4::CShaderVariableVector4 (const glm::vec4& defaultValue, const std::string& name) : - m_defaultValue (defaultValue), - m_value (glm::vec4 ()), - CShaderVariable (&this->m_defaultValue, nullptr, Type) { + CShaderVariable () { this->setName (name); + this->update (defaultValue); } - -void CShaderVariableVector4::setValue (const glm::vec4& value) { - this->m_value = value; - CShaderVariable::setValue (&this->m_value); -} - -const int CShaderVariableVector4::getSize () const { - return 4; -} - -const std::string CShaderVariableVector4::Type = "vec4"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h index 6e05f89..d1e00d5 100644 --- a/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h +++ b/src/WallpaperEngine/Render/Shaders/Variables/CShaderVariableVector4.h @@ -8,15 +8,5 @@ class CShaderVariableVector4 final : public CShaderVariable { public: explicit CShaderVariableVector4 (const glm::vec4& defaultValue); CShaderVariableVector4 (const glm::vec4& defaultValue, const std::string& name); - - const int getSize () const override; - - void setValue (const glm::vec4& value); - - static const std::string Type; - - private: - glm::vec4 m_defaultValue; - glm::vec4 m_value; }; } // namespace WallpaperEngine::Render::Shaders::Variables diff --git a/src/WallpaperEngine/Render/Wallpapers/CScene.cpp b/src/WallpaperEngine/Render/Wallpapers/CScene.cpp index 3c2cc7f..d268012 100644 --- a/src/WallpaperEngine/Render/Wallpapers/CScene.cpp +++ b/src/WallpaperEngine/Render/Wallpapers/CScene.cpp @@ -1,5 +1,3 @@ -#include "common.h" - #include "WallpaperEngine/Core/Objects/CImage.h" #include "WallpaperEngine/Core/Objects/CSound.h" @@ -9,19 +7,23 @@ #include "WallpaperEngine/Render/CWallpaperState.h" #include "CScene.h" +#include "WallpaperEngine/Logging/CLog.h" extern float g_Time; extern float g_TimeLast; using namespace WallpaperEngine; using namespace WallpaperEngine::Render; +using namespace WallpaperEngine::Render::Wallpapers; -CScene::CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& audioContext, - const CWallpaperState::TextureUVsScaling& scalingMode) : - CWallpaper (scene, Type, context, audioContext, scalingMode), - m_mousePosition (), - m_mousePositionLast (), - m_parallaxDisplacement () { +CScene::CScene ( + std::shared_ptr wallpaper, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode +) : + CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) { + // caller should check this, if not a std::bad_cast is good to throw + const auto& scene = wallpaper->as (); // setup the scene camera this->m_camera = new CCamera (this, scene->getCamera ()); @@ -148,13 +150,13 @@ CScene::CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& aud // create image for bloom passes if (this->getScene ()->isBloom ()) { this->m_bloomObject = this->createObject ( - WallpaperEngine::Core::CObject::fromJSON (json, this->getScene (), this->getContainer ())); + WallpaperEngine::Core::CObject::fromJSON (json, scene->getProject (), this->getContainer ())); this->m_objectsByRenderOrder.push_back (this->m_bloomObject); } } -Render::CObject* CScene::createObject (Core::CObject* object) { +Render::CObject* CScene::createObject (const Core::CObject* object) { Render::CObject* renderObject = nullptr; // ensure the item is not loaded already @@ -191,7 +193,7 @@ Render::CObject* CScene::createObject (Core::CObject* object) { } if (renderObject != nullptr) - this->m_objects.insert (std::make_pair (renderObject->getId (), renderObject)); + this->m_objects.emplace (renderObject->getId (), renderObject); return renderObject; } @@ -205,7 +207,7 @@ void CScene::renderFrame (glm::ivec4 viewport) { this->updateMouse (viewport); // update the parallax position if required - if (this->getScene ()->isCameraParallax ()) { + if (this->getScene ()->isCameraParallax () && !this->getContext ().getApp ().getContext ().settings.mouse.disableparallax) { const float influence = this->getScene ()->getCameraParallaxMouseInfluence (); const float amount = this->getScene ()->getCameraParallaxAmount (); const float delay = @@ -241,8 +243,8 @@ void CScene::updateMouse (glm::ivec4 viewport) { // screen-space positions have to be transposed to what the screen will actually show } -Core::CScene* CScene::getScene () const { - return this->getWallpaperData ()->as (); +const Core::Wallpapers::CScene* CScene::getScene () const { + return this->getWallpaperData ()->as (); } int CScene::getWidth () const { @@ -265,4 +267,6 @@ glm::vec2* CScene::getParallaxDisplacement () { return &this->m_parallaxDisplacement; } -const std::string CScene::Type = "scene"; +const std::vector& CScene::getObjectsByRenderOrder () const { + return this->m_objectsByRenderOrder; +} diff --git a/src/WallpaperEngine/Render/Wallpapers/CScene.h b/src/WallpaperEngine/Render/Wallpapers/CScene.h index 1ec53d0..4b3c6e1 100644 --- a/src/WallpaperEngine/Render/Wallpapers/CScene.h +++ b/src/WallpaperEngine/Render/Wallpapers/CScene.h @@ -9,43 +9,47 @@ namespace WallpaperEngine::Render { class CCamera; class CObject; +} +namespace WallpaperEngine::Render::Wallpapers { class CScene final : public CWallpaper { public: - CScene (Core::CScene* scene, CRenderContext& context, CAudioContext& audioContext, - const CWallpaperState::TextureUVsScaling& scalingMode); + CScene ( + std::shared_ptr wallpaper, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode); - CCamera* getCamera () const; + [[nodiscard]] CCamera* getCamera () const; - Core::CScene* getScene () const; + [[nodiscard]] const Core::Wallpapers::CScene* getScene () const; - int getWidth () const override; - int getHeight () const override; + [[nodiscard]] int getWidth () const override; + [[nodiscard]] int getHeight () const override; glm::vec2* getMousePosition (); glm::vec2* getMousePositionLast (); glm::vec2* getParallaxDisplacement (); + [[nodiscard]] const std::vector& getObjectsByRenderOrder () const; + protected: void renderFrame (glm::ivec4 viewport) override; void updateMouse (glm::ivec4 viewport); friend class CWallpaper; - static const std::string Type; - private: - Render::CObject* createObject (Core::CObject* object); + Render::CObject* createObject (const Core::CObject* object); - CCamera* m_camera; - CObject* m_bloomObject; - std::map m_objects; - std::vector m_objectsByRenderOrder; - glm::vec2 m_mousePosition; - glm::vec2 m_mousePositionLast; - glm::vec2 m_parallaxDisplacement; - CFBO* _rt_4FrameBuffer; - CFBO* _rt_8FrameBuffer; - CFBO* _rt_Bloom; + CCamera* m_camera = nullptr; + CObject* m_bloomObject = nullptr; + std::map m_objects = {}; + std::vector m_objectsByRenderOrder = {}; + glm::vec2 m_mousePosition = {}; + glm::vec2 m_mousePositionLast = {}; + glm::vec2 m_parallaxDisplacement = {}; + std::shared_ptr _rt_4FrameBuffer = nullptr; + std::shared_ptr _rt_8FrameBuffer = nullptr; + std::shared_ptr _rt_Bloom = nullptr; }; -} // namespace WallpaperEngine::Render +} // namespace WallpaperEngine::Render::Wallpaper diff --git a/src/WallpaperEngine/Render/Wallpapers/CVideo.cpp b/src/WallpaperEngine/Render/Wallpapers/CVideo.cpp index 9e72f64..56f88c3 100644 --- a/src/WallpaperEngine/Render/Wallpapers/CVideo.cpp +++ b/src/WallpaperEngine/Render/Wallpapers/CVideo.cpp @@ -1,22 +1,22 @@ #include "CVideo.h" -#include "common.h" +#include "WallpaperEngine/Logging/CLog.h" #include using namespace WallpaperEngine; using namespace WallpaperEngine::Render; +using namespace WallpaperEngine::Render::Wallpapers; void* get_proc_address (void* ctx, const char* name) { return static_cast (ctx)->getContext ().getDriver ().getProcAddress (name); } -CVideo::CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& audioContext, - const CWallpaperState::TextureUVsScaling& scalingMode) : - CWallpaper (video, Type, context, audioContext, scalingMode), - m_width (16), - m_height (16), - m_paused (false), - m_mpvGl (nullptr) { +CVideo::CVideo ( + std::shared_ptr wallpaper, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode +) : + CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) { double volume = this->getContext ().getApp ().getContext ().settings.audio.volume * 100.0 / 128.0; // create mpv contexts @@ -54,7 +54,7 @@ CVideo::CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& aud sLog.exception ("Failed to initialize MPV's GL context"); const std::filesystem::path videopath = - this->getVideo ()->getProject ().getContainer ()->resolveRealFile (this->getVideo ()->getFilename ()); + this->getVideo ()->getProject ()->getContainer ()->resolveRealFile (this->getVideo ()->getFilename ()); // build the path to the video file const char* command [] = {"loadfile", videopath.c_str (), nullptr}; @@ -118,8 +118,8 @@ void CVideo::renderFrame (glm::ivec4 viewport) { mpv_render_context_render (this->m_mpvGl, params); } -Core::CVideo* CVideo::getVideo () { - return this->getWallpaperData ()->as (); +const Core::Wallpapers::CVideo* CVideo::getVideo () const { + return this->getWallpaperData ()->as (); } void CVideo::setPause (bool newState) { @@ -137,5 +137,3 @@ int CVideo::getWidth () const { int CVideo::getHeight () const { return this->m_height; } - -const std::string CVideo::Type = "video"; diff --git a/src/WallpaperEngine/Render/Wallpapers/CVideo.h b/src/WallpaperEngine/Render/Wallpapers/CVideo.h index a6c9830..0438a8e 100644 --- a/src/WallpaperEngine/Render/Wallpapers/CVideo.h +++ b/src/WallpaperEngine/Render/Wallpapers/CVideo.h @@ -7,13 +7,15 @@ #include #include -namespace WallpaperEngine::Render { +namespace WallpaperEngine::Render::Wallpapers { class CVideo final : public CWallpaper { public: - CVideo (Core::CVideo* video, CRenderContext& context, CAudioContext& audioContext, - const CWallpaperState::TextureUVsScaling& scalingMode); + CVideo ( + std::shared_ptr video, CRenderContext& context, CAudioContext& audioContext, + const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode); - Core::CVideo* getVideo (); + const Core::Wallpapers::CVideo* getVideo () const; [[nodiscard]] int getWidth () const override; [[nodiscard]] int getHeight () const override; @@ -26,14 +28,12 @@ class CVideo final : public CWallpaper { friend class CWallpaper; - static const std::string Type; - private: - mpv_handle* m_mpv; - mpv_render_context* m_mpvGl; + mpv_handle* m_mpv = nullptr; + mpv_render_context* m_mpvGl = nullptr; - bool m_paused; - int64_t m_width; - int64_t m_height; + bool m_paused = false; + int64_t m_width = 16; + int64_t m_height = 16; }; -} // namespace WallpaperEngine::Render +} // namespace WallpaperEngine::Render::Wallpapers diff --git a/src/WallpaperEngine/Render/Wallpapers/CWeb.cpp b/src/WallpaperEngine/Render/Wallpapers/CWeb.cpp index f1790e2..9f69cea 100644 --- a/src/WallpaperEngine/Render/Wallpapers/CWeb.cpp +++ b/src/WallpaperEngine/Render/Wallpapers/CWeb.cpp @@ -2,38 +2,41 @@ // https://github.com/if1live/cef-gl-example // https://github.com/andmcgregor/cefgui #include "CWeb.h" +#include "WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.h" using namespace WallpaperEngine::Render; -using namespace WallpaperEngine::WebBrowser; +using namespace WallpaperEngine::Render::Wallpapers; -CWeb::CWeb (Core::CWeb* web, CRenderContext& context, CAudioContext& audioContext, CWebBrowserContext& browserContext, - const CWallpaperState::TextureUVsScaling& scalingMode) : - CWallpaper (web, Type, context, audioContext, scalingMode), - m_width (16), - m_height (16), - m_browserContext (browserContext), - m_browser (), - m_client () { - this->m_browserContext.markAsUsed (); +using namespace WallpaperEngine::WebBrowser; +using namespace WallpaperEngine::WebBrowser::CEF; + +CWeb::CWeb ( + std::shared_ptr wallpaper, CRenderContext& context, CAudioContext& audioContext, + CWebBrowserContext& browserContext, const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode +) : + CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode), + m_browserContext (browserContext) { // setup framebuffers this->setupFramebuffers (); CefWindowInfo window_info; window_info.SetAsWindowless (0); - this->m_render_handler = new RenderHandler (this); + this->m_renderHandler = new WebBrowser::CEF::CRenderHandler (this); CefBrowserSettings browserSettings; // Documentaion says that 60 fps is maximum value browserSettings.windowless_frame_rate = std::max (60, context.getApp ().getContext ().settings.render.maximumFPS); - m_client = new BrowserClient (m_render_handler); - std::filesystem::path htmlpath = - this->getWeb ()->getProject ().getContainer ()->resolveRealFile (this->getWeb ()->getFilename ()); - // To open local file in browser URL must be "file:///path/to/file.html" - const std::string htmlURL = std::string ("file:///") + htmlpath.c_str (); - m_browser = - CefBrowserHost::CreateBrowserSync (window_info, m_client.get (), htmlURL, browserSettings, nullptr, nullptr); + this->m_client = new WebBrowser::CEF::CBrowserClient (m_renderHandler); + // use the custom scheme for the wallpaper's files + const std::string htmlURL = + CWPSchemeHandlerFactory::generateSchemeName(this->getWeb ()->getProject ()->getWorkshopId ()) + + "://root/" + + this->getWeb()->getFilename (); + this->m_browser = + CefBrowserHost::CreateBrowserSync (window_info, this->m_client, htmlURL, browserSettings, nullptr, nullptr); } void CWeb::setSize (int width, int height) { @@ -50,7 +53,7 @@ void CWeb::setSize (int width, int height) { nullptr); // Notify cef that it was resized(maybe it's not even needed) - m_browser->GetHost ()->WasResized (); + this->m_browser->GetHost ()->WasResized (); } void CWeb::renderFrame (glm::ivec4 viewport) { @@ -90,15 +93,15 @@ void CWeb::updateMouse (glm::ivec4 viewport) { evt.x = std::clamp (int (position.x - viewport.x), 0, viewport.z); evt.y = std::clamp (int (position.y - viewport.y), 0, viewport.w); // Send mouse position to cef - m_browser->GetHost ()->SendMouseMoveEvent (evt, false); + this->m_browser->GetHost ()->SendMouseMoveEvent (evt, false); // TODO: ANY OTHER MOUSE EVENTS TO SEND? if (leftClick != this->m_leftClick) { - m_browser->GetHost ()->SendMouseClickEvent (evt, CefBrowserHost::MouseButtonType::MBT_LEFT, leftClick == WallpaperEngine::Input::MouseClickStatus::Released, 1); + this->m_browser->GetHost ()->SendMouseClickEvent (evt, CefBrowserHost::MouseButtonType::MBT_LEFT, leftClick == WallpaperEngine::Input::MouseClickStatus::Released, 1); } if (rightClick != this->m_rightClick) { - m_browser->GetHost ()->SendMouseClickEvent (evt, CefBrowserHost::MouseButtonType::MBT_RIGHT, rightClick == WallpaperEngine::Input::MouseClickStatus::Released, 1); + this->m_browser->GetHost ()->SendMouseClickEvent (evt, CefBrowserHost::MouseButtonType::MBT_RIGHT, rightClick == WallpaperEngine::Input::MouseClickStatus::Released, 1); } this->m_leftClick = leftClick; @@ -107,24 +110,7 @@ void CWeb::updateMouse (glm::ivec4 viewport) { CWeb::~CWeb () { CefDoMessageLoopWork (); - m_browser->GetHost ()->CloseBrowser (true); + this->m_browser->GetHost ()->CloseBrowser (true); + + delete this->m_renderHandler; } - -CWeb::RenderHandler::RenderHandler (CWeb* webdata) : m_webdata (webdata) {} - -// Required by CEF -void CWeb::RenderHandler::GetViewRect (CefRefPtr browser, CefRect& rect) { - rect = CefRect (0, 0, this->m_webdata->getWidth (), this->m_webdata->getHeight ()); -} - -// Will be executed in CEF message loop -void CWeb::RenderHandler::OnPaint (CefRefPtr browser, PaintElementType type, const RectList& dirtyRects, - const void* buffer, int width, int height) { - // sLog.debug("BrowserView::RenderHandler::OnPaint"); - glActiveTexture (GL_TEXTURE0); - glBindTexture (GL_TEXTURE_2D, this->texture ()); - glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, (unsigned char*) buffer); - glBindTexture (GL_TEXTURE_2D, 0); -} - -const std::string CWeb::Type = "web"; \ No newline at end of file diff --git a/src/WallpaperEngine/Render/Wallpapers/CWeb.h b/src/WallpaperEngine/Render/Wallpapers/CWeb.h index 858beb1..759f9e9 100644 --- a/src/WallpaperEngine/Render/Wallpapers/CWeb.h +++ b/src/WallpaperEngine/Render/Wallpapers/CWeb.h @@ -13,106 +13,51 @@ #include "WallpaperEngine/Audio/CAudioStream.h" #include "WallpaperEngine/Core/Wallpapers/CWeb.h" #include "WallpaperEngine/Render/CWallpaper.h" -#include "common.h" +#include "WallpaperEngine/WebBrowser/CEF/CBrowserClient.h" +#include "WallpaperEngine/WebBrowser/CEF/CRenderHandler.h" -namespace WallpaperEngine::Render -{ - class CWeb : public CWallpaper - { - public: - CWeb (Core::CWeb* scene, CRenderContext& context, CAudioContext& audioContext, WallpaperEngine::WebBrowser::CWebBrowserContext& browserContext, const CWallpaperState::TextureUVsScaling& scalingMode); - ~CWeb() override; - [[nodiscard]] int getWidth () const override { return this->m_width; } - - [[nodiscard]] int getHeight () const override { return this->m_height; } - - void setSize (int width, int height); - - protected: - void renderFrame (glm::ivec4 viewport) override; - void updateMouse (glm::ivec4 viewport); - Core::CWeb* getWeb () - { - return this->getWallpaperData ()->as (); - } - - friend class CWallpaper; - - static const std::string Type; - - private: - // ************************************************************************* - //! \brief Private implementation to handle CEF events to draw the web page. - // ************************************************************************* - class RenderHandler: public CefRenderHandler - { - public: - explicit RenderHandler(CWeb* webdata); - - //! \brief - ~RenderHandler() override = default; - - //! \brief CefRenderHandler interface - void GetViewRect(CefRefPtr browser, CefRect &rect) override; - - //! \brief CefRenderHandler interface - //! Update the OpenGL texture. - void OnPaint(CefRefPtr browser, PaintElementType type, - const RectList &dirtyRects, const void *buffer, - int width, int height) override; - - //! \brief CefBase interface - IMPLEMENT_REFCOUNTING(RenderHandler); - - private: - CWeb* m_webdata; - - int getWidth () const { - return this->m_webdata->getWidth(); - }; - int getHeight () const { - return this->m_webdata->getHeight(); - }; - //! \brief Return the OpenGL texture handle - GLuint texture() const - { - return this->m_webdata->getWallpaperFramebuffer(); - } - }; - - // ************************************************************************* - //! \brief Provide access to browser-instance-specific callbacks. A single - //! CefClient instance can be shared among any number of browsers. - // ************************************************************************* - class BrowserClient: public CefClient - { - public: - explicit BrowserClient(CefRefPtr ptr) - : m_renderHandler(std::move(ptr)) - {} - - CefRefPtr GetRenderHandler() override - { - return m_renderHandler; - } - - CefRefPtr m_renderHandler; - - IMPLEMENT_REFCOUNTING(BrowserClient); - }; - - WallpaperEngine::WebBrowser::CWebBrowserContext& m_browserContext; - CefRefPtr m_browser; - CefRefPtr m_client; - RenderHandler* m_render_handler = nullptr; - - int m_width; - int m_height; - - WallpaperEngine::Input::MouseClickStatus m_leftClick; - WallpaperEngine::Input::MouseClickStatus m_rightClick; - - glm::vec2 m_mousePosition; - glm::vec2 m_mousePositionLast; - }; +namespace WallpaperEngine::WebBrowser::CEF { +class CRenderHandler; +} + +namespace WallpaperEngine::Render::Wallpapers { +class CWeb : public CWallpaper +{ + public: + CWeb ( + std::shared_ptr wallpaper, CRenderContext& context, CAudioContext& audioContext, + WallpaperEngine::WebBrowser::CWebBrowserContext& browserContext, + const CWallpaperState::TextureUVsScaling& scalingMode, + const WallpaperEngine::Assets::ITexture::TextureFlags& clampMode); + ~CWeb() override; + [[nodiscard]] int getWidth () const override { return this->m_width; } + + [[nodiscard]] int getHeight () const override { return this->m_height; } + + void setSize (int width, int height); + + protected: + void renderFrame (glm::ivec4 viewport) override; + void updateMouse (glm::ivec4 viewport); + const Core::Wallpapers::CWeb* getWeb () const { + return this->getWallpaperData ()->as (); + } + + friend class CWallpaper; + + private: + WallpaperEngine::WebBrowser::CWebBrowserContext& m_browserContext; + CefRefPtr m_browser = nullptr; + CefRefPtr m_client = nullptr; + WallpaperEngine::WebBrowser::CEF::CRenderHandler* m_renderHandler = nullptr; + + int m_width = 16; + int m_height = 17; + + WallpaperEngine::Input::MouseClickStatus m_leftClick = Input::Released; + WallpaperEngine::Input::MouseClickStatus m_rightClick = Input::Released; + + glm::vec2 m_mousePosition = {}; + glm::vec2 m_mousePositionLast = {}; +}; } diff --git a/src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.cpp b/src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.cpp new file mode 100644 index 0000000..b56fe7b --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.cpp @@ -0,0 +1,56 @@ +#include "CBrowserApp.h" +#include "WallpaperEngine/Logging/CLog.h" + +using namespace WallpaperEngine::WebBrowser::CEF; + +CBrowserApp::CBrowserApp (WallpaperEngine::Application::CWallpaperApplication& application) : + CSubprocessApp (application) { +} + +CefRefPtr CBrowserApp::GetBrowserProcessHandler () { + return this; +} + +void CBrowserApp::OnContextInitialized () { + // register all the needed schemes, "wp" + the background id is going to be our scheme + for (const auto& [workshopId, factory] : this->getHandlerFactories ()) { + CefRegisterSchemeHandlerFactory ( + CWPSchemeHandlerFactory::generateSchemeName (workshopId), + (const char*) nullptr, + factory + ); + } +} + +void CBrowserApp::OnBeforeCommandLineProcessing (const CefString& process_type, CefRefPtr command_line) { + command_line->AppendSwitchWithValue ("--disable-features", "IsolateOrigins,HardwareMediaKeyHandling,WebContentsOcclusion,RendererCodeIntegrityEnabled,site-per-process"); + command_line->AppendSwitch ("--disable-gpu-shader-disk-cache"); + command_line->AppendSwitch ("--disable-site-isolation-trials"); + command_line->AppendSwitch ("--disable-web-security"); + command_line->AppendSwitchWithValue ("--remote-allow-origins", "*"); + command_line->AppendSwitchWithValue ("--autoplay-policy", "no-user-gesture-required"); + command_line->AppendSwitch("--disable-background-timer-throttling"); + command_line->AppendSwitch("--disable-backgrounding-occluded-windows"); + command_line->AppendSwitch("--disable-background-media-suspend"); + command_line->AppendSwitch("--disable-renderer-backgrounding"); + command_line->AppendSwitch("--disable-test-root-certs"); + command_line->AppendSwitch("--disable-bundled-ppapi-flash"); + command_line->AppendSwitch("--disable-breakpad"); + command_line->AppendSwitch("--disable-field-trial-config"); + command_line->AppendSwitch("--no-experiments"); + // TODO: ACTIVATE THIS IF WE EVER SUPPORT MACOS OFFICIALLY + /* +if (process_type.empty()) { +#if defined(OS_MACOSX) + // Disable the macOS keychain prompt. Cookies will not be encrypted. + command_line->AppendSwitch("use-mock-keychain"); +#endif +}*/ +} + +void CBrowserApp::OnBeforeChildProcessLaunch(CefRefPtr command_line) { + // add back any parameters we had before so the new process can load up everything needed + for (int i = 1; i < this->getApplication ().getContext ().getArgc (); i ++) { + command_line->AppendArgument (this->getApplication ().getContext ().getArgv () [i]); + } +} \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.h b/src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.h new file mode 100644 index 0000000..fee39c2 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CBrowserApp.h @@ -0,0 +1,30 @@ +#pragma once + +#include "CSubprocessApp.h" +#include "CWPSchemeHandlerFactory.h" +#include "WallpaperEngine/WebBrowser/CWebBrowserContext.h" +#include "include/cef_app.h" + +namespace WallpaperEngine::Application { +class CWallpaperApplication; +} + +namespace WallpaperEngine::WebBrowser::CEF { +/** + * Provides custom protocol to contain everything under it + */ +class CBrowserApp : public CSubprocessApp, public CefBrowserProcessHandler { + public: + explicit CBrowserApp (WallpaperEngine::Application::CWallpaperApplication& application); + + [[nodiscard]] CefRefPtr GetBrowserProcessHandler () override; + + void OnContextInitialized () override; + void OnBeforeCommandLineProcessing (const CefString& process_type, CefRefPtr command_line) override; + void OnBeforeChildProcessLaunch(CefRefPtr command_line) override; + + private: + IMPLEMENT_REFCOUNTING (CBrowserApp); + DISALLOW_COPY_AND_ASSIGN (CBrowserApp); +}; +} // namespace WallpaperEngine::WebBrowser::CEF \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.cpp b/src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.cpp new file mode 100644 index 0000000..4df9e94 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.cpp @@ -0,0 +1,11 @@ +#include "CBrowserClient.h" + +using namespace WallpaperEngine::WebBrowser::CEF; + +CBrowserClient::CBrowserClient(CefRefPtr ptr) : + m_renderHandler(std::move(ptr)) {} + +CefRefPtr CBrowserClient::GetRenderHandler() +{ + return m_renderHandler; +} \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.h b/src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.h new file mode 100644 index 0000000..d8c1234 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CBrowserClient.h @@ -0,0 +1,21 @@ +#pragma once + +#include "include/cef_client.h" + +namespace WallpaperEngine::WebBrowser::CEF { +// ************************************************************************* +//! \brief Provide access to browser-instance-specific callbacks. A single +//! CefClient instance can be shared among any number of browsers. +// ************************************************************************* +class CBrowserClient: public CefClient +{ + public: + explicit CBrowserClient(CefRefPtr ptr); + + [[nodiscard]] CefRefPtr GetRenderHandler() override; + + CefRefPtr m_renderHandler = nullptr; + + IMPLEMENT_REFCOUNTING(CBrowserClient); +}; +} // namespace WallpaperEngine::WebBrowser::CEF \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.cpp b/src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.cpp new file mode 100644 index 0000000..267819b --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.cpp @@ -0,0 +1,32 @@ +#include "CRenderHandler.h" + +using namespace WallpaperEngine::WebBrowser::CEF; + +CRenderHandler::CRenderHandler (WallpaperEngine::Render::Wallpapers::CWeb* webdata) : + m_webdata (webdata) {} + +// Required by CEF +void CRenderHandler::GetViewRect (CefRefPtr browser, CefRect& rect) { + rect = CefRect (0, 0, this->m_webdata->getWidth (), this->m_webdata->getHeight ()); +} + +// Will be executed in CEF message loop +void CRenderHandler::OnPaint (CefRefPtr browser, PaintElementType type, const RectList& dirtyRects, + const void* buffer, int width, int height) { + glActiveTexture (GL_TEXTURE0); + glBindTexture (GL_TEXTURE_2D, this->texture ()); + glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, (unsigned char*) buffer); + glBindTexture (GL_TEXTURE_2D, 0); +} + +int CRenderHandler::getWidth() const { + return this->m_webdata->getWidth (); +} + +int CRenderHandler::getHeight() const { + return this->m_webdata->getHeight (); +} + +GLuint CRenderHandler::texture () const { + return this->m_webdata->getWallpaperFramebuffer(); +} \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.h b/src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.h new file mode 100644 index 0000000..b0e8ba0 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CRenderHandler.h @@ -0,0 +1,41 @@ +#pragma once + +#include "WallpaperEngine/Render/Wallpapers/CWeb.h" +#include "include/cef_browser.h" + +namespace WallpaperEngine::Render::Wallpapers { +class CWeb; +} + +namespace WallpaperEngine::WebBrowser::CEF { +// ************************************************************************* +//! \brief Private implementation to handle CEF events to draw the web page. +// ************************************************************************* +class CRenderHandler : public CefRenderHandler { + public: + explicit CRenderHandler (WallpaperEngine::Render::Wallpapers::CWeb* webdata); + + //! \brief + ~CRenderHandler () override = default; + + //! \brief CefRenderHandler interface + void GetViewRect (CefRefPtr browser, CefRect& rect) override; + + //! \brief CefRenderHandler interface + //! Update the OpenGL texture. + void OnPaint (CefRefPtr browser, PaintElementType type, const RectList& dirtyRects, const void* buffer, + int width, int height) override; + + //! \brief CefBase interface + IMPLEMENT_REFCOUNTING (CRenderHandler); + + private: + WallpaperEngine::Render::Wallpapers::CWeb* m_webdata = nullptr; + + [[nodiscard]] int getWidth () const; + [[nodiscard]] int getHeight () const; + + //! \brief Return the OpenGL texture handle + [[nodiscard]] GLuint texture () const; +}; +} // namespace WallpaperEngine::WebBrowser::CEF \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.cpp b/src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.cpp new file mode 100644 index 0000000..2864af8 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.cpp @@ -0,0 +1,29 @@ +#include "CSubprocessApp.h" +#include "CWPSchemeHandlerFactory.h" + +using namespace WallpaperEngine::WebBrowser::CEF; + +CSubprocessApp::CSubprocessApp (WallpaperEngine::Application::CWallpaperApplication& application) : + m_application (application) { + for (const auto& [_, info] : this->m_application.getBackgrounds()) { + this->m_handlerFactories [info->getWorkshopId ()] = new CWPSchemeHandlerFactory (info); + } +} + +void CSubprocessApp::OnRegisterCustomSchemes (CefRawPtr registrar) { + // register all the needed schemes, "wp" + the background id is going to be our scheme + for (const auto& [workshopId, _] : this->m_handlerFactories) { + registrar->AddCustomScheme ( + CWPSchemeHandlerFactory::generateSchemeName (workshopId), + CEF_SCHEME_OPTION_STANDARD | CEF_SCHEME_OPTION_SECURE | CEF_SCHEME_OPTION_FETCH_ENABLED + ); + } +} + +const WallpaperEngine::Application::CWallpaperApplication& CSubprocessApp::getApplication () const { + return this->m_application; +} + +const std::map& CSubprocessApp::getHandlerFactories () const { + return this->m_handlerFactories; +} \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.h b/src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.h new file mode 100644 index 0000000..a2c9013 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CSubprocessApp.h @@ -0,0 +1,28 @@ +#pragma once + +#include "CWPSchemeHandlerFactory.h" +#include "WallpaperEngine/WebBrowser/CWebBrowserContext.h" +#include "include/cef_app.h" + +namespace WallpaperEngine::Application { +class CWallpaperApplication; +} + +namespace WallpaperEngine::WebBrowser::CEF { +class CSubprocessApp : public CefApp { + public: + explicit CSubprocessApp (WallpaperEngine::Application::CWallpaperApplication& application); + + void OnRegisterCustomSchemes (CefRawPtr registrar) override; + + protected: + const WallpaperEngine::Application::CWallpaperApplication& getApplication () const; + const std::map& getHandlerFactories () const; + + private: + std::map m_handlerFactories = {}; + WallpaperEngine::Application::CWallpaperApplication& m_application; + IMPLEMENT_REFCOUNTING (CSubprocessApp); + DISALLOW_COPY_AND_ASSIGN (CSubprocessApp); +}; +} \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.cpp b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.cpp new file mode 100644 index 0000000..debd1cd --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.cpp @@ -0,0 +1,101 @@ +#include "CWPSchemeHandler.h" +#include "WallpaperEngine/Assets/CAssetLoadException.h" +#include + +#include "MimeTypes.h" +#include "include/cef_parser.h" + +using namespace WallpaperEngine::Assets; +using namespace WallpaperEngine::WebBrowser::CEF; + +CWPSchemeHandler::CWPSchemeHandler(std::shared_ptr project) : + m_project (project) { + this->m_container = this->m_project->getWallpaper ()->getProject ()->getContainer (); +} + +bool CWPSchemeHandler::Open(CefRefPtr request, + bool& handle_request, + CefRefPtr callback) { + DCHECK(!CefCurrentlyOn(TID_UI) && !CefCurrentlyOn(TID_IO)); + +#if !NDEBUG + std::cout << "Processing request for path " << request->GetURL ().c_str () << std::endl; +#endif + // url contains the full path, we need to get rid of the protocol + // otherwise files won't be found + CefURLParts parts; + + // url parsing is a must + if (!CefParseURL (request->GetURL (), parts)) { + return false; + } + + std::string host = CefString(&parts.host); + std::string path = CefString(&parts.path); + + std::string file = path.substr(1); + + try { + // try to read the file on the current container, if the file doesn't exists + // an exception will be thrown + const char* mime = MimeTypes::getType (file.c_str ()); + + if (!mime) { + this->m_mimeType = "application/octet+stream"; + } else { + this->m_mimeType = mime; + } + + this->m_contents = this->m_container->readFile (file, &this->m_filesize); + callback->Continue (); + } catch (CAssetLoadException&) { +#if !NDEBUG + std::cout << "Cannot read file " << file << std::endl; +#endif + } + + handle_request = true; + + return true; +} + + +void CWPSchemeHandler::GetResponseHeaders(CefRefPtr response, + int64_t& response_length, + CefString& redirectUrl) { + CEF_REQUIRE_IO_THREAD(); + + if (!this->m_contents) { + response->SetError (ERR_FILE_NOT_FOUND); + response->SetStatus (404); + response_length = 0; + return; + } + + response->SetMimeType (this->m_mimeType); + response->SetStatus (200); + + response_length = this->m_filesize; +} + +void CWPSchemeHandler::Cancel () { + CEF_REQUIRE_IO_THREAD(); +} + +bool CWPSchemeHandler::Read(void* data_out, int bytes_to_read, int& bytes_read, + CefRefPtr callback) { + DCHECK(!CefCurrentlyOn(TID_UI) && !CefCurrentlyOn(TID_IO)); + + bytes_read = 0; + + if (this->m_contents && this->m_offset < this->m_filesize) { + int bytes_to_transfer = std::min (bytes_to_read, static_cast (this->m_filesize - this->m_offset)); + + memcpy (data_out, &this->m_contents [this->m_offset], bytes_to_transfer); + + this->m_offset += bytes_read = bytes_to_transfer; + return true; + } + + return false; +} \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.h b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.h new file mode 100644 index 0000000..df94ba1 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandler.h @@ -0,0 +1,47 @@ +#pragma once + +#include + +#include "WallpaperEngine/Core/CProject.h" +#include "include/cef_resource_handler.h" +#include "include/wrapper/cef_helpers.h" + +namespace WallpaperEngine::Assets { +class CContainer; +} + +namespace WallpaperEngine::WebBrowser::CEF { +/** + * wp{id}:// actual handler called by cef to access files + */ +class CWPSchemeHandler : public CefResourceHandler { + public: + explicit CWPSchemeHandler(std::shared_ptr project); + + bool Open(CefRefPtr request, + bool& handle_request, + CefRefPtr callback) override; + + void GetResponseHeaders(CefRefPtr response, + int64_t& response_length, + CefString& redirectUrl) override; + + void Cancel() override; + + bool Read(void* data_out, int bytes_to_read, int& bytes_read, + CefRefPtr callback) override; + + private: + std::shared_ptr m_project = nullptr; + + std::shared_ptr m_container = nullptr; + std::shared_ptr m_contents = nullptr; + uint32_t m_filesize = 0; + std::string m_mimeType = ""; + uint32_t m_offset = 0; + + + IMPLEMENT_REFCOUNTING(CWPSchemeHandler); + DISALLOW_COPY_AND_ASSIGN(CWPSchemeHandler); +}; +}; \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.cpp b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.cpp new file mode 100644 index 0000000..331eab9 --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.cpp @@ -0,0 +1,20 @@ +#include "CWPSchemeHandlerFactory.h" +#include "CWPSchemeHandler.h" +#include "WallpaperEngine/WebBrowser/CWebBrowserContext.h" +#include "include/wrapper/cef_helpers.h" + +using namespace WallpaperEngine::WebBrowser::CEF; + +CWPSchemeHandlerFactory::CWPSchemeHandlerFactory (const std::shared_ptr& project) : + m_project (project) {} + +CefRefPtr CWPSchemeHandlerFactory::Create ( + CefRefPtr browser, CefRefPtr frame, + const CefString& scheme_name, CefRefPtr request) { + CEF_REQUIRE_IO_THREAD (); + return new CWPSchemeHandler(this->m_project); +} + +std::string CWPSchemeHandlerFactory::generateSchemeName (const std::string& workshopId) { + return std::string(WPENGINE_SCHEME) + workshopId; +} \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.h b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.h new file mode 100644 index 0000000..8ee1a4b --- /dev/null +++ b/src/WallpaperEngine/WebBrowser/CEF/CWPSchemeHandlerFactory.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include "WallpaperEngine/Core/CProject.h" +#include "include/cef_scheme.h" + +namespace WallpaperEngine::WebBrowser::CEF { +/** + * Simple factory that creates a scheme handler for wp when requested by Cef + */ +class CWPSchemeHandlerFactory : public CefSchemeHandlerFactory { + public: + explicit CWPSchemeHandlerFactory (const std::shared_ptr& project); + + CefRefPtr Create ( + CefRefPtr browser, CefRefPtr frame, + const CefString& scheme_name, CefRefPtr request) override; + + static std::string generateSchemeName (const std::string& workshopId); + private: + std::shared_ptr m_project = nullptr; + + IMPLEMENT_REFCOUNTING (CWPSchemeHandlerFactory); + DISALLOW_COPY_AND_ASSIGN (CWPSchemeHandlerFactory); +}; +} // namespace WallpaperEngine::WebBrowser::CEF \ No newline at end of file diff --git a/src/WallpaperEngine/WebBrowser/CWebBrowserContext.cpp b/src/WallpaperEngine/WebBrowser/CWebBrowserContext.cpp index 61df7be..5810842 100644 --- a/src/WallpaperEngine/WebBrowser/CWebBrowserContext.cpp +++ b/src/WallpaperEngine/WebBrowser/CWebBrowserContext.cpp @@ -1,31 +1,76 @@ #include "CWebBrowserContext.h" +#include "CEF/CBrowserApp.h" #include "WallpaperEngine/Logging/CLog.h" +#include "WallpaperEngine/WebBrowser/CEF/CSubprocessApp.h" #include "include/cef_app.h" -#include "include/cef_client.h" #include "include/cef_render_handler.h" +#include +#include using namespace WallpaperEngine::WebBrowser; -CWebBrowserContext::CWebBrowserContext (int argc, char** argv) : m_stopped (false) { - // clone original argc/argv as they'll be modified by cef - char** argv2 = new char*[argc]; +// TODO: THIS IS USED TO GENERATE A RANDOM FOLDER FOR THE CHROME PROFILE, MAYBE A DIFFERENT APPROACH WOULD BE BETTER? +namespace uuid { +static std::random_device rd; +static std::mt19937 gen(rd()); +static std::uniform_int_distribution<> dis(0, 15); +static std::uniform_int_distribution<> dis2(8, 11); - for (int i = 0; i < argc; i++) { - argv2 [i] = new char [strlen (argv [i]) + 1]; - strcpy (argv2 [i], argv [i]); +std::string generate_uuid_v4() { + std::stringstream ss; + int i; + ss << std::hex; + for (i = 0; i < 8; i++) { + ss << dis(gen); + } + ss << "-"; + for (i = 0; i < 4; i++) { + ss << dis(gen); + } + ss << "-4"; + for (i = 0; i < 3; i++) { + ss << dis(gen); + } + ss << "-"; + ss << dis2(gen); + for (i = 0; i < 3; i++) { + ss << dis(gen); + } + ss << "-"; + for (i = 0; i < 12; i++) { + ss << dis(gen); + }; + return ss.str(); +} +} + +CWebBrowserContext::CWebBrowserContext (WallpaperEngine::Application::CWallpaperApplication& wallpaperApplication) : + m_browserApplication (nullptr), + m_wallpaperApplication (wallpaperApplication) { + CefMainArgs main_args (this->m_wallpaperApplication.getContext ().getArgc (), this->m_wallpaperApplication.getContext ().getArgv ()); + + // only care about app if the process is the main process + // we should maybe use a better lib for handling command line arguments instead + // or using C's version on some places and CefCommandLine on others + // TODO: ANOTHER THING TO TAKE CARE OF BEFORE MERGING + CefRefPtr commandLine = CefCommandLine::CreateCommandLine(); + + commandLine->InitFromArgv (main_args.argc, main_args.argv); + + if (!commandLine->HasSwitch("type")) { + this->m_browserApplication = new CEF::CBrowserApp(wallpaperApplication); + } else { + this->m_browserApplication = new CEF::CSubprocessApp(wallpaperApplication); } - CefMainArgs args (argc, argv2); - + // this blocks for anything not-main-thread int exit_code = CefExecuteProcess ( - args, nullptr, nullptr); // Spawned processes will terminate here(see CefIninitilize below). Maybe implementing - // settings.browser_subprocess_path will allow it to work not in main function. + main_args, this->m_browserApplication, nullptr); + + // this is needed to kill subprocesses after they're done if (exit_code >= 0) { // Sub proccess has endend, so exit exit (exit_code); - } else if (exit_code == -1) { - // If called for the browser process (identified by no "type" command-line value) - // it will return immediately with a value of -1 } // Configurate Chromium @@ -35,13 +80,14 @@ CWebBrowserContext::CWebBrowserContext (int argc, char** argv) : m_stopped (fals // CefString(&settings.framework_dir_path) = "OffScreenCEF/godot/"; // CefString(&settings.cache_path) = "OffScreenCEF/godot/"; // CefString(&settings.browser_subprocess_path) = "path/to/client" + CefString(&settings.root_cache_path) = std::filesystem::temp_directory_path() / uuid::generate_uuid_v4(); settings.windowless_rendering_enabled = true; #if defined(CEF_NO_SANDBOX) settings.no_sandbox = true; #endif // spawns two new processess - bool result = CefInitialize (args, settings, nullptr, nullptr); + bool result = CefInitialize (main_args, settings, this->m_browserApplication, nullptr); if (!result) { sLog.exception ("CefInitialize: failed"); @@ -49,25 +95,6 @@ CWebBrowserContext::CWebBrowserContext (int argc, char** argv) : m_stopped (fals } CWebBrowserContext::~CWebBrowserContext () { - this->stop (); -} - -void CWebBrowserContext::markAsUsed () { - this->m_inUse = true; -} - -bool CWebBrowserContext::isUsed () { - return this->m_inUse; -} - -void CWebBrowserContext::stop () { - if (this->m_stopped) { - return; - } - sLog.out ("Shutting down CEF"); - - this->m_stopped = true; - CefShutdown (); -} \ No newline at end of file +} diff --git a/src/WallpaperEngine/WebBrowser/CWebBrowserContext.h b/src/WallpaperEngine/WebBrowser/CWebBrowserContext.h index d689ff1..42c4fdc 100644 --- a/src/WallpaperEngine/WebBrowser/CWebBrowserContext.h +++ b/src/WallpaperEngine/WebBrowser/CWebBrowserContext.h @@ -1,17 +1,26 @@ #pragma once +#include "WallpaperEngine/Application/CApplicationContext.h" +#include "WallpaperEngine/Application/CWallpaperApplication.h" +#include "include/cef_app.h" +#include "include/cef_browser_process_handler.h" +#include "include/wrapper/cef_helpers.h" + +#define WPENGINE_SCHEME "wp" + +namespace WallpaperEngine::WebBrowser::CEF { +class CBrowserApp; +} + namespace WallpaperEngine::WebBrowser { class CWebBrowserContext { public: - CWebBrowserContext (int argc, char** argv); + explicit CWebBrowserContext (WallpaperEngine::Application::CWallpaperApplication& wallpaperApplication); ~CWebBrowserContext(); - void markAsUsed(); - bool isUsed(); - void stop(); - private: - bool m_stopped; - bool m_inUse; + CefRefPtr m_browserApplication = nullptr; + CefRefPtr m_commandLine = nullptr; + WallpaperEngine::Application::CWallpaperApplication& m_wallpaperApplication; }; } // namespace WallpaperEngine::WebBrowser diff --git a/src/common.h b/src/common.h deleted file mode 100644 index d8481f9..0000000 --- a/src/common.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once - -#include "WallpaperEngine/Core/Wallpapers/CWeb.h" -#include "WallpaperEngine/Logging/CLog.h" diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..068579f --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,66 @@ +#include +#include + +#include "WallpaperEngine/Application/CApplicationContext.h" +#include "WallpaperEngine/Application/CWallpaperApplication.h" +#include "WallpaperEngine/Logging/CLog.h" + +WallpaperEngine::Application::CWallpaperApplication* app; + +void signalhandler(int sig) { + if (app == nullptr) + return; + + app->signal (sig); +} + +void initLogging () { + sLog.addOutput (new std::ostream (std::cout.rdbuf ())); + sLog.addError (new std::ostream (std::cerr.rdbuf ())); +} + +int main (int argc, char* argv[]) { + // if type parameter is specified, this is a subprocess, so no logging should be enabled from our side + bool enableLogging = true; + std::string typeZygote = "--type=zygote"; + std::string typeUtility = "--type=utility"; + + for (int i = 1; i < argc; i ++) { + if (strncmp (typeZygote.c_str(), argv[i], typeZygote.size()) == 0) { + enableLogging = false; + break; + } else if (strncmp (typeUtility.c_str(), argv[i], typeUtility.size()) == 0) { + enableLogging = false; + break; + } + } + + if (enableLogging) { + initLogging (); + } + + WallpaperEngine::Application::CApplicationContext appContext (argc, argv); + + // halt if the list-properties option was specified + if (appContext.settings.general.onlyListProperties) + return 0; + + app = new WallpaperEngine::Application::CWallpaperApplication (appContext); + + // attach signals to gracefully stop + std::signal (SIGINT, signalhandler); + std::signal (SIGTERM, signalhandler); + std::signal (SIGKILL, signalhandler); + + // show the wallpaper application + app->show (); + + // remove signal handlers before destroying app + std::signal (SIGINT, SIG_DFL); + std::signal (SIGTERM, SIG_DFL); + std::signal (SIGKILL, SIG_DFL); + + delete app; + + return 0; +} \ No newline at end of file diff --git a/src/recording.cpp b/src/recording.cpp new file mode 100644 index 0000000..2c10296 --- /dev/null +++ b/src/recording.cpp @@ -0,0 +1,193 @@ +#if DEMOMODE + +// this file is horrible, but doesn't need to be anything good as it's only used internally + +#include "recording.h" + +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +#include +#include +#include +#include +} + +const int FPS = 30; +const int FRAME_COUNT = FPS * 5; +int WIDTH = 0; +int HEIGHT = 0; +int SOURCE_WIDTH = 0; +int SOURCE_HEIGHT = 0; + +int64_t frame_count = 0; + +// Global variables to hold encoder context and output stream +const AVCodec *video_codec = nullptr; +AVCodecContext *video_codec_context = nullptr; +AVFormatContext *format_context = nullptr; +AVStream *video_stream = nullptr; +SwsContext *sws_context = nullptr; +AVFrame *video_frame = nullptr; +AVFrame* rgb_frame = nullptr; + +int init_encoder(const char *output_file, int sourceWidth, int sourceHeight) { + float factor = 512.0f / (float) sourceWidth; + SOURCE_WIDTH = sourceWidth; + SOURCE_HEIGHT = sourceHeight; + WIDTH = (float) sourceWidth * factor; + HEIGHT = (float) sourceHeight * factor; + + avformat_network_init(); + + // Initialize the output format context + if (avformat_alloc_output_context2(&format_context, nullptr, "webm", output_file) < 0) { + std::cerr << "Error initializing format context" << std::endl; + return -1; + } + + // Video codec: VP8 + video_codec = avcodec_find_encoder(AV_CODEC_ID_VP9); + if (!video_codec) { + std::cerr << "VP8 codec not found!" << std::endl; + return -1; + } + + video_codec_context = avcodec_alloc_context3(video_codec); + if (!video_codec_context) { + std::cerr << "Error allocating video codec context" << std::endl; + return -1; + } + + video_codec_context->bit_rate = 4000000; + video_codec_context->width = WIDTH; + video_codec_context->height = HEIGHT; + video_codec_context->pix_fmt = AV_PIX_FMT_YUV420P; + video_codec_context->time_base = (AVRational){1, FPS}; + video_codec_context->framerate = (AVRational){FPS, 1}; + video_codec_context->gop_size = 12; + video_codec_context->max_b_frames = 1; + video_codec_context->qmin = 10; + video_codec_context->qmax = 40; + + if (avcodec_open2(video_codec_context, video_codec, nullptr) < 0) { + std::cerr << "Error opening VP8 codec" << std::endl; + return -1; + } + + // Create the video stream in the format context + video_stream = avformat_new_stream(format_context, video_codec); + if (!video_stream) { + std::cerr << "Error creating video stream" << std::endl; + return -1; + } + + // Copy codec parameters from the codec context to the stream + if (avcodec_parameters_from_context(video_stream->codecpar, video_codec_context) < 0) { + std::cerr << "Error copying codec parameters to stream" << std::endl; + return -1; + } + + video_stream->time_base = video_codec_context->time_base; + + // Open output file for writing + if (avio_open(&format_context->pb, output_file, AVIO_FLAG_WRITE) < 0) { + std::cerr << "Error opening output file" << std::endl; + return -1; + } + + // Write file header + if (avformat_write_header(format_context, nullptr) < 0) { + std::cerr << "Error writing file header" << std::endl; + return -1; + } + + // Allocate video frame + video_frame = av_frame_alloc(); + video_frame->format = AV_PIX_FMT_YUV420P; + video_frame->width = WIDTH; + video_frame->height = HEIGHT; + av_frame_get_buffer(video_frame, 0); + + rgb_frame = av_frame_alloc(); + + rgb_frame->format = AV_PIX_FMT_RGB24; + rgb_frame->width = SOURCE_WIDTH; + rgb_frame->height = SOURCE_HEIGHT; + + // Set up YUV conversion context (RGB to YUV) + sws_context = sws_getContext(SOURCE_WIDTH, SOURCE_HEIGHT, AV_PIX_FMT_RGB24, + WIDTH, HEIGHT, AV_PIX_FMT_YUV420P, + SWS_BICUBIC, nullptr, nullptr, nullptr); + + return 0; +} + +int write_video_frame(const uint8_t *rgb_data) { + av_image_fill_arrays(rgb_frame->data, rgb_frame->linesize, rgb_data, AV_PIX_FMT_RGB24, SOURCE_WIDTH, SOURCE_HEIGHT, 1); + + sws_scale(sws_context, rgb_frame->data, rgb_frame->linesize, 0, SOURCE_HEIGHT, video_frame->data, video_frame->linesize); + + // Send the frame to the encoder + int ret = avcodec_send_frame(video_codec_context, video_frame); + if (ret < 0) { + std::cerr << "Error sending video frame: " << ret << std::endl; + return -1; + } + + AVPacket packet; + av_init_packet(&packet); + packet.data = nullptr; + packet.size = 0; + + // Receive the encoded packet from the encoder + ret = avcodec_receive_packet(video_codec_context, &packet); + if (ret < 0) { + std::cerr << "Error receiving video packet: " << ret << std::endl; + return -1; + } + + packet.stream_index = video_stream->index; + // Set the PTS and DTS values + packet.pts = av_rescale_q(frame_count, video_codec_context->time_base, video_stream->time_base); + packet.dts = packet.pts; // For simplicity, you can set DTS equal to PTS for now + packet.duration = av_rescale_q(1, video_codec_context->time_base, video_stream->time_base); + + // Increment frame counter + frame_count++; + // Write the encoded video packet to the file + ret = av_interleaved_write_frame(format_context, &packet); + if (ret < 0) { + std::cerr << "Error writing video packet: " << ret << std::endl; + return -1; + } + + // Ensure that the packet is freed + av_packet_unref(&packet); + + return 0; +} + +int close_encoder() { + // Write any remaining frames (flush encoder) + avcodec_flush_buffers(video_codec_context); + + // Write the trailer + av_write_trailer(format_context); + + // Clean up + avcodec_free_context(&video_codec_context); + avformat_free_context(format_context); + av_frame_free(&video_frame); + sws_freeContext(sws_context); + + return 0; +} + +#endif /* DEMOMODE */ \ No newline at end of file diff --git a/src/recording.h b/src/recording.h new file mode 100644 index 0000000..a84438c --- /dev/null +++ b/src/recording.h @@ -0,0 +1,16 @@ +#pragma once + +#if DEMOMODE + +#include +#include +#include + +extern const int FPS; +extern const int FRAME_COUNT; + +int init_encoder(const char *output_file, int sourceWidth, int sourceHeight); +int write_video_frame(const uint8_t *rgb_data); +int close_encoder(); + +#endif /* DEMOMODE */ \ No newline at end of file diff --git a/tools/reversing/README.md b/tools/reversing/README.md new file mode 100644 index 0000000..4c40adf --- /dev/null +++ b/tools/reversing/README.md @@ -0,0 +1,14 @@ +# Reverse Engineering Tools +These are the tools and binaries that I use for understanding what's going behind the scenes: + +## d3dcompiler_47 +A small shim to debug interactions with the d3dcompiler. +It's used to add extra information to wallpaper's themselves, like include processed shader before It's compiled +by d3d. Especially useful when something shader-related doesn't work so It can be inspected either manually +(with the logfile it creates) or in RenderDoc with shader names, source... + +For it to work it has to live alongside the real d3dcompiler_74 dll renamed to d3dcompiler_47original.dll + +## RenderDoc.cap +A base capture file that allows for Wallpaper Engine to run backgrounds, when used in conjunction with the +d3dcompiler_47 shim allows for taking captures of rendering, inspecting all the rendering performed by Wallpaper Engine. diff --git a/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim.sln b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim.sln new file mode 100644 index 0000000..54b32ec --- /dev/null +++ b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30204.135 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "d3dcompiler_47_shim", "d3dcompiler_47_shim\d3dcompiler_47_shim.vcxproj", "{44B2FA3F-952A-4661-B31D-4683CD500A8C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Debug|x64.ActiveCfg = Debug|x64 + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Debug|x64.Build.0 = Debug|x64 + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Debug|x86.ActiveCfg = Debug|Win32 + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Debug|x86.Build.0 = Debug|Win32 + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Release|x64.ActiveCfg = Release|x64 + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Release|x64.Build.0 = Release|x64 + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Release|x86.ActiveCfg = Release|Win32 + {44B2FA3F-952A-4661-B31D-4683CD500A8C}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A062B42E-282C-4165-903B-C528ACDA9BF1} + EndGlobalSection +EndGlobal diff --git a/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/Source.def b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/Source.def new file mode 100644 index 0000000..a9ee971 --- /dev/null +++ b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/Source.def @@ -0,0 +1,4 @@ +LIBRARY +EXPORTS +D3DCompile=D3DCompile +D3DReflect=D3DReflect \ No newline at end of file diff --git a/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/d3dcompiler_47_shim.vcxproj b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/d3dcompiler_47_shim.vcxproj new file mode 100644 index 0000000..471b5e2 --- /dev/null +++ b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/d3dcompiler_47_shim.vcxproj @@ -0,0 +1,177 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {44b2fa3f-952a-4661-b31d-4683cd500a8c} + d3dcompiler47shim + 10.0 + d3dcompiler_47 + + + + DynamicLibrary + true + v143 + Unicode + + + DynamicLibrary + false + v143 + true + Unicode + + + DynamicLibrary + true + v143 + Unicode + + + DynamicLibrary + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + false + + + true + + + false + + + + Level3 + true + WIN32;_DEBUG;D3DCOMPILER47SHIM_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + false + false + Source.def + + + + + Level3 + true + true + true + WIN32;NDEBUG;D3DCOMPILER47SHIM_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + true + true + false + Source.def + + + + + Level3 + true + _DEBUG;D3DCOMPILER47SHIM_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + false + Source.def + + + + + Level3 + true + true + true + NDEBUG;D3DCOMPILER47SHIM_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + + + Windows + true + true + true + false + Source.def + + + + + + + + + + Create + Create + Create + Create + + + + + + + + + \ No newline at end of file diff --git a/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/dllmain.cpp b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/dllmain.cpp new file mode 100644 index 0000000..064f103 --- /dev/null +++ b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/dllmain.cpp @@ -0,0 +1,137 @@ +// dllmain.cpp : Define el punto de entrada de la aplicación DLL. +#include "pch.h" +#include +#include +#include + +#pragma warning(disable:4996) + +typedef HRESULT (*OriginalD3DCompile)( + LPCVOID pSrcData, + SIZE_T SrcDataSize, + LPCSTR pSourceName, + const void* pDefines, + void* pInclude, + LPCSTR pEntrypoint, + LPCSTR pTarget, + UINT Flags1, + UINT Flags2, + void** ppCode, + void** ppErrorMsgs +); + +typedef HRESULT (*OriginalD3DReflect)( + LPCVOID pSrcData, + SIZE_T SrcDataSize, + REFIID pInterface, + void** ppReflector +); + +HMODULE original_lib = NULL; +OriginalD3DCompile ExternalD3DCompile = NULL; +OriginalD3DReflect ExternalD3DReflect = NULL; +FILE* fp = NULL; + +extern "C" +{ +__declspec(dllexport) HRESULT WINAPI D3DCompile( + LPCVOID pSrcData, + SIZE_T SrcDataSize, + LPCSTR pSourceName, + const void* pDefines, + void* pInclude, + LPCSTR pEntrypoint, + LPCSTR pTarget, + UINT Flags1, + UINT Flags2, + void** ppCode, + void** ppErrorMsgs +) +{ + if (fp != NULL) + { + fprintf(fp, "////////////////////////////////////////////////////////////////////////////\r\n"); + fprintf(fp, "Shader: %s\n", pSourceName); + fprintf(fp, "////////////////////////////////////////////////////////////////////////////\r\n"); + fwrite(pSrcData, SrcDataSize, 1, fp); + fflush (fp); + } + + // includes D3DCOMPILE_DEBUG + Flags1 |= (1 << 0) | (1 << 2); + + return ExternalD3DCompile(pSrcData, SrcDataSize, pSourceName, pDefines, pInclude, pEntrypoint, pTarget, Flags1, Flags2, ppCode, ppErrorMsgs); +} + +__declspec(dllexport) HRESULT WINAPI D3DReflect( + LPCVOID pSrcData, + SIZE_T SrcDataSize, + REFIID pInterface, + void** ppReflector +) +{ + return ExternalD3DReflect(pSrcData, SrcDataSize, pInterface, ppReflector); +} + +} + +BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) +{ + char shadersFile[256]; + memset(shadersFile, 0, 256); + sprintf(shadersFile, "C:\\development\\shaders_%lld_%i.log", time(NULL), rand()); + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hModule); + fp = fopen(shadersFile, "ab+"); + + if (fp == NULL) { + return FALSE; + } + + fprintf(fp, "=====================================================================================\n"); + fputs("Booting up shader compiler shim!", fp); + + original_lib = LoadLibrary(TEXT("d3dcompiler_47original.dll")); + if (!original_lib) + original_lib = LoadLibraryEx(TEXT("d3dcompiler_47original.dll"), 0, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (!original_lib) + { + fputs("Could not resolve DLL!\r\n", fp); + fclose(fp); + fp = NULL; + return FALSE; + } + + ExternalD3DCompile = (OriginalD3DCompile) GetProcAddress(original_lib, "D3DCompile"); + ExternalD3DReflect = (OriginalD3DReflect) GetProcAddress(original_lib, "D3DReflect"); + + if (!ExternalD3DReflect) { + fputs("Could not locate D3DReflect in d3dcompiler_47original.dll\r\n", fp); + } else { + fputs("Located D3DReflect in d3dcompiler_47original.dll\r\n", fp); + } + + if (!ExternalD3DCompile) { + fputs("Could not locate D3DCompile in d3dcompiler_47original.dll\r\n", fp); + } else { + fputs("Located D3DCompile in d3dcompiler_47original.dll\r\n", fp); + } + break; + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + break; + + case DLL_PROCESS_DETACH: + fputs("Closing...\r\n", fp); + fclose(fp); + fp = NULL; + break; + } + return TRUE; +} + diff --git a/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/framework.h b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/framework.h new file mode 100644 index 0000000..f24153d --- /dev/null +++ b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/framework.h @@ -0,0 +1,5 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN // Excluir material rara vez utilizado de encabezados de Windows +// Archivos de encabezado de Windows +#include diff --git a/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.cpp b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.cpp new file mode 100644 index 0000000..a6ccf92 --- /dev/null +++ b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.cpp @@ -0,0 +1,5 @@ +// pch.cpp: el archivo de código fuente correspondiente al encabezado precompilado + +#include "pch.h" + +// Cuando se utilizan encabezados precompilados, se requiere este archivo de código fuente para que la compilación se realice correctamente. diff --git a/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.h b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.h new file mode 100644 index 0000000..8e034b6 --- /dev/null +++ b/tools/reversing/d3dcompiler_47/d3dcompiler_47_shim/pch.h @@ -0,0 +1,13 @@ +// pch.h: este es un archivo de encabezado precompilado. +// Los archivos que se muestran a continuación se compilan solo una vez, lo que mejora el rendimiento de la compilación en futuras compilaciones. +// Esto también afecta al rendimiento de IntelliSense, incluida la integridad del código y muchas funciones de exploración del código. +// Sin embargo, los archivos que se muestran aquí se vuelven TODOS a compilar si alguno de ellos se actualiza entre compilaciones. +// No agregue aquí los archivos que se vayan a actualizar con frecuencia, ya que esto invalida la ventaja de rendimiento. + +#ifndef PCH_H +#define PCH_H + +// agregue aquí los encabezados que desea precompilar +#include "framework.h" + +#endif //PCH_H diff --git a/tools/reversing/renderdoc.cap b/tools/reversing/renderdoc.cap new file mode 100644 index 0000000..f369c35 --- /dev/null +++ b/tools/reversing/renderdoc.cap @@ -0,0 +1,28 @@ +{ + "rdocCaptureSettings": 1, + "settings": { + "autoStart": false, + "commandLine": "-showbrowse -language spanish -updateuicmd -showbrowse ", + "environment": [ + ], + "executable": "C:\\Program Files (x86)\\Steam\\steamapps\\common\\wallpaper_engine\\wallpaper64.exe", + "inject": false, + "numQueuedFrames": 0, + "options": { + "allowFullscreen": true, + "allowVSync": true, + "apiValidation": false, + "captureAllCmdLists": false, + "captureCallstacks": false, + "captureCallstacksOnlyDraws": false, + "debugOutputMute": true, + "delayForDebugger": 0, + "hookIntoChildren": false, + "refAllResources": false, + "softMemoryLimit": 0, + "verifyBufferAccess": false + }, + "queuedFrameCap": 0, + "workingDir": "" + } +} diff --git a/tools/run-over-all-backgrounds.sh b/tools/run-over-all-backgrounds.sh new file mode 100755 index 0000000..392dd95 --- /dev/null +++ b/tools/run-over-all-backgrounds.sh @@ -0,0 +1,25 @@ +#!/bin/bash +if [ $# -eq 0 ] + then + echo "Please provide the current build's executable path. You might want to run this script off the same folder." +fi + +# ensure the output and images directory exists +[ -d "output" ] || mkdir output + +for folder in ~/.steam/steam/steamapps/workshop/content/431960/*; do + # only directories matter + if [ -d "$folder" ]; then + bgid=$(basename "$folder") + + echo "Running wallpaperengine for background $bgid and waiting for it to finish" + # run and wait for it to finish + $1 $bgid + # move output.webm to the output folder with the right name + mv output.webm output/$bgid.webm + # take a screenshot + ffmpeg -ss 00:00:03 -i output/$bgid.webm -frames:v 1 output/$bgid.jpg + # copy over the project.json so we have it on hand + cp $folder/project.json output/$bgid.json + fi +done \ No newline at end of file