فهرست منبع

tons of changes

UwU 1 ماه پیش
والد
کامیت
3ba4523fc7
83فایلهای تغییر یافته به همراه8720 افزوده شده و 2046 حذف شده
  1. 6 0
      CMakeLists.txt
  2. 4 1
      README.md
  3. 34 3
      docs/rendering/MDL_FILES.md
  4. 67 1
      src/WallpaperEngine/Application/ApplicationContext.cpp
  5. 8 0
      src/WallpaperEngine/Application/ApplicationContext.h
  6. 79 10
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  7. 5 0
      src/WallpaperEngine/Application/WallpaperApplication.h
  8. 8 0
      src/WallpaperEngine/Assets/AssetLocator.cpp
  9. 1 0
      src/WallpaperEngine/Assets/AssetLocator.h
  10. 11 1
      src/WallpaperEngine/Audio/AudioContext.cpp
  11. 11 1
      src/WallpaperEngine/Audio/AudioContext.h
  12. 35 1
      src/WallpaperEngine/Audio/AudioStream.cpp
  13. 13 1
      src/WallpaperEngine/Audio/AudioStream.h
  14. 17 1
      src/WallpaperEngine/Audio/Drivers/AudioDriver.h
  15. 76 4
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  16. 8 1
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.h
  17. 3 2
      src/WallpaperEngine/Audio/SpectrumAnalyzer.cpp
  18. 2 0
      src/WallpaperEngine/Data/Assets/Texture.h
  19. 2 0
      src/WallpaperEngine/Data/Model/Material.h
  20. 92 19
      src/WallpaperEngine/Data/Model/Object.h
  21. 4 0
      src/WallpaperEngine/Data/Parsers/MaterialParser.cpp
  22. 157 28
      src/WallpaperEngine/Data/Parsers/ObjectParser.cpp
  23. 5 2
      src/WallpaperEngine/Data/Parsers/ObjectParser.h
  24. 113 0
      src/WallpaperEngine/Render/CFBO.cpp
  25. 7 0
      src/WallpaperEngine/Render/CFBO.h
  26. 34 10
      src/WallpaperEngine/Render/CWallpaper.cpp
  27. 9 0
      src/WallpaperEngine/Render/CWallpaper.h
  28. 34 33
      src/WallpaperEngine/Render/Camera.cpp
  29. 13 3
      src/WallpaperEngine/Render/Camera.h
  30. 310 0
      src/WallpaperEngine/Render/ModelData.cpp
  31. 128 0
      src/WallpaperEngine/Render/ModelData.h
  32. 91 776
      src/WallpaperEngine/Render/Objects/CImage.cpp
  33. 24 75
      src/WallpaperEngine/Render/Objects/CImage.h
  34. 612 64
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  35. 41 2
      src/WallpaperEngine/Render/Objects/CMesh.h
  36. 504 265
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  37. 75 30
      src/WallpaperEngine/Render/Objects/CParticle.h
  38. 425 34
      src/WallpaperEngine/Render/Objects/CSound.cpp
  39. 62 9
      src/WallpaperEngine/Render/Objects/CSound.h
  40. 313 81
      src/WallpaperEngine/Render/Objects/CText.cpp
  41. 18 1
      src/WallpaperEngine/Render/Objects/CText.h
  42. 120 25
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  43. 12 1
      src/WallpaperEngine/Render/Objects/Effects/CPass.h
  44. 1193 0
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  45. 194 0
      src/WallpaperEngine/Render/Objects/PuppetRig.h
  46. 436 55
      src/WallpaperEngine/Render/Objects/TextLayout.cpp
  47. 54 17
      src/WallpaperEngine/Render/Objects/TextLayout.h
  48. 61 54
      src/WallpaperEngine/Render/Shaders/GLSLContext.cpp
  49. 14 5
      src/WallpaperEngine/Render/Shaders/GLSLContext.h
  50. 24 0
      src/WallpaperEngine/Render/Shaders/Shader.cpp
  51. 5 0
      src/WallpaperEngine/Render/Shaders/Shader.h
  52. 253 137
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  53. 10 1
      src/WallpaperEngine/Render/Shaders/ShaderUnit.h
  54. 288 0
      src/WallpaperEngine/Render/ShadowMapping.cpp
  55. 58 0
      src/WallpaperEngine/Render/ShadowMapping.h
  56. 169 13
      src/WallpaperEngine/Render/Volumetrics.cpp
  57. 19 2
      src/WallpaperEngine/Render/Volumetrics.h
  58. 106 91
      src/WallpaperEngine/Render/WallpaperState.cpp
  59. 27 3
      src/WallpaperEngine/Render/WallpaperState.h
  60. 739 93
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  61. 114 9
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  62. 28 2
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  63. 491 2
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp
  64. 7 0
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h
  65. 80 59
      src/WallpaperEngine/Scripting/EngineObject.cpp
  66. 6 0
      src/WallpaperEngine/Scripting/EngineObject.h
  67. 7 9
      src/WallpaperEngine/Scripting/InputObject.cpp
  68. 477 3
      src/WallpaperEngine/Scripting/SceneObject.cpp
  69. 5 0
      src/WallpaperEngine/Scripting/SceneObject.h
  70. 91 1
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  71. 29 0
      src/WallpaperEngine/Scripting/ScriptEngine.h
  72. 68 0
      src/WallpaperEngine/Testing/Cases/ScalingModes.cpp
  73. 2 0
      tools/headless_render.sh
  74. BIN
      tools/regression/__pycache__/regress.cpython-313.pyc
  75. 4 1
      tools/regression/regress.py
  76. BIN
      tools/wecompare/__pycache__/render_we.cpython-313.pyc
  77. 16 4
      tools/wecompare/render_ours.sh
  78. 4 0
      tools/wecompare/render_we.py
  79. 35 0
      tools/wecompare/wine/rdscripts/rd_depthpass.py
  80. 10 0
      tools/wecompare/wine/rdscripts/rd_texdata.py
  81. 1 0
      tools/wecompare/wine/we_capture.sh
  82. 1 0
      tools/wecompare/wine/we_cursor.sh
  83. 1 0
      tools/wecompare/wine/we_full.sh

+ 6 - 0
CMakeLists.txt

@@ -495,6 +495,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Objects/CImage.cpp
     src/WallpaperEngine/Render/Objects/PuppetPhysics.h
     src/WallpaperEngine/Render/Objects/PuppetPhysics.cpp
+    src/WallpaperEngine/Render/Objects/PuppetRig.h
+    src/WallpaperEngine/Render/Objects/PuppetRig.cpp
     src/WallpaperEngine/Render/Objects/CSound.h
     src/WallpaperEngine/Render/Objects/CSound.cpp
     src/WallpaperEngine/Render/Objects/CParticle.h
@@ -509,6 +511,10 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Objects/CCamera.cpp
     src/WallpaperEngine/Render/Volumetrics.h
     src/WallpaperEngine/Render/Volumetrics.cpp
+    src/WallpaperEngine/Render/ShadowMapping.h
+    src/WallpaperEngine/Render/ShadowMapping.cpp
+    src/WallpaperEngine/Render/ModelData.h
+    src/WallpaperEngine/Render/ModelData.cpp
     src/WallpaperEngine/Render/Objects/CMesh.h
     src/WallpaperEngine/Render/Objects/CMesh.cpp
 

+ 4 - 1
README.md

@@ -124,8 +124,11 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--screen-span <screen-1>,<screen-2>,...` | Stretch a single wallpaper across multiple screens |
 | `--bg <id/path>` | Assign a background to a screen (used after `--screen-root`/`--screen-span`) |
 | `--playlist <file>` | Cycle through a Wallpaper Engine playlist from `config.json` |
-| `--scaling <mode>` | `stretch`, `fit`, `fill`, `center`, or `default` |
+| `--scaling <mode>` | `stretch`, `fit`, `fill`, `center`, `free`, or `default` |
 | `--zoom <factor>` | Manual zoom on top of `--scaling`, e.g. `1.5` in, `0.5` out |
+| `--alignment-position <0-100>` | Wallpaper Engine's alignment position: where `fill`/`default` crop and `fit` letterboxes (default 50) |
+| `--alignment-x <0-100>`, `--alignment-y <0-100>` | Placement for `center` and `free` (default 50, 0 = left/top) |
+| `--alignment-zoom <0-200>` | Zoom for `free` (default 100 = native size) |
 | `--clamp <mode>` | Texture clamping: `clamp` (edge), `border`, `repeat`. Default `border` |
 | `--corner-color <hex>` | Color outside the wallpaper's bounds when `--clamp border`, as `RRGGBB`/`RRGGBBAA`. Default `000000` |
 | `--layer <layer>` | Wayland only: `wlr-layer-shell` layer (`background`, `bottom`, `top`, `overlay`) |

+ 34 - 3
docs/rendering/MDL_FILES.md

@@ -125,8 +125,9 @@ typedef struct {
     BYTE   vertices[vertexByteLength];
     DWORD  indexByteLength;
     BYTE   indices[indexByteLength];  // triangle list
-    // version 23 only (the 2.4 engine reads up to 19): BYTE a, BYTE b, [DWORD n, BYTE[n] if b], DWORD m, BYTE[m]
-    // static models write six zero bytes here, puppets fill it
+    // version 21+: BYTE f1, [DWORD, DWORD n, BYTE[n] if f1], BYTE f2, [DWORD n, BYTE[n] if f2] (puppets: per bone
+    // index ranges, 16 bytes each). Version 23+: DWORD records, each QWORD, CHAR name[], DWORD flags, DWORD n,
+    // DWORD[n], DWORD m, DWORD[m]. Static models write six zero bytes here (wallpaper64.exe 2.8.42 sub_140261880)
 } MESH;
 ```
 
@@ -281,4 +282,34 @@ Reverse-engineered by cross-referencing multiple real puppet `.mdl` files pulled
 (`ahriarm_puppet.mdl`, `ahritailbottom_puppet.mdl`, `spiritblossomahribase_puppet.mdl`) - matching decoded bind
 translations/keyframe values against scene.json, and validating that decoded byte offsets exactly consume every
 byte up to the known MDLA/EOF boundary. No official documentation or decompilation was available for this part
-of the format.
+of the format.
+## Sections after MDLV and morph targets (MDMP)
+
+Every section after the meshes is `"TAGnnnn\0"` followed by the absolute file offset of the next one; 2.8.42 walks
+them in any order until an empty tag or the end of the file: MDLS, MDAT, MDLA, MDMP (morph targets), MDLE. One
+puppet stores them as MDLS, MDAT, MDLA, MDMP, MDLE.
+
+```
+CHAR   header[9]       // "MDMP0001\0"
+DWORD  nextSection
+// for every mesh of the MDLV section, in file order:
+WORD   targetCount
+// only with targets:
+FLOAT  scale           // the deltas are multiplied by it (g_MorphWeights[0])
+DWORD  vertexCount
+TARGET targets[targetCount]
+```
+```
+typedef struct {
+    QWORD  id;
+    CHAR   name[];
+    DWORD  bytes; SHORT positions[bytes / 2];   // 3 per vertex, signed normalized (R16G16B16A16_SNORM texture)
+    // mesh flags 0x400: the same again for normals; 0x800 and 0x1000: one more sized block each;
+    // 0x2000: DWORD, DWORD, FLOAT, FLOAT
+} TARGET;
+```
+
+The engine packs every target of a mesh one after another into a square texture (positions only, or positions and
+normals interleaved per vertex with flag 0x400) that the vertex shader reads with `gl_VertexID`. MDLA version 4+
+clips can drive the weights: after the other tracks a flag byte, then per mesh a DWORD whose bit 0 enables tracks,
+a FLOAT (1.0), a WORD count and per track a WORD target index and a sized block of one float per sample.

+ 67 - 1
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -501,6 +501,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 
 	    group.scaling = this->settings.render.window.scalingMode;
 	    group.clamp = this->settings.render.window.clamp;
+	    group.alignment = this->settings.render.window.alignment;
 	    this->settings.general.spanGroups.push_back (std::move (group));
 	    // synthetic "span:" name lets --bg/--scaling/--clamp target this group
 	    lastScreen = "span:" + value;
@@ -547,7 +548,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    "Scaling mode to use when rendering the background, this applies to the previous --window, --screen-root, "
 	    "or --screen-span output, or the default background if no other background is specified"
 	)
-	.choices ("stretch", "fit", "fill", "center", "default")
+	.choices ("stretch", "fit", "fill", "center", "free", "default")
 	.action ([this, &lastScreen] (const std::string& value) -> void {
 	    const auto parsed = WallpaperEngine::Render::WallpaperState::parseScalingMode (value);
 
@@ -660,6 +661,71 @@ void ApplicationContext::loadSettingsFromArgv () {
 	})
 	.append ();
 
+    // WE's alignment settings in its own units (sub_140181F30 divides them by 100)
+    const auto addAlignmentArgument
+	= [this, &backgroundGroup, &lastScreen] (
+	      const char* name, const char* help, const float maximum,
+	      float WallpaperEngine::Render::WallpaperState::Alignment::* field
+	  ) {
+	      backgroundGroup.add_argument (name)
+		  .help (help)
+		  .action ([this, &lastScreen, name, maximum, field] (const std::string& value) -> void {
+		      float parsed;
+
+		      try {
+			  parsed = std::stof (value);
+		      } catch (const std::exception&) {
+			  sLog.exception ("Invalid ", name, " value: ", value);
+		      }
+
+		      if (parsed < 0.0f || parsed > maximum) {
+			  sLog.exception (name, " must be between 0 and ", maximum, ": ", value);
+		      }
+
+		      parsed /= 100.0f;
+
+		      if (this->settings.render.mode == DESKTOP_BACKGROUND) {
+			  auto& alignment = this->settings.general.screenAlignments
+					       .try_emplace (lastScreen, this->settings.render.window.alignment)
+					       .first->second;
+			  alignment.*field = parsed;
+
+			  if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+			      this->settings.general.spanGroups.back ().alignment.*field = parsed;
+			  }
+		      } else {
+			  this->settings.render.window.alignment.*field = parsed;
+		      }
+		  })
+		  .append ();
+	  };
+
+    addAlignmentArgument (
+	"--alignment-position",
+	"Wallpaper Engine's alignment position, 0-100 (default 50): where --scaling fill/default crops (0 keeps the "
+	"right or top edge) and --scaling fit places the letterboxed wallpaper (0 = left or top). This applies to the "
+	"previous --window, --screen-root, or --screen-span output, or the default background",
+	100.0f, &WallpaperEngine::Render::WallpaperState::Alignment::position
+    );
+    addAlignmentArgument (
+	"--alignment-x",
+	"Wallpaper Engine's horizontal alignment for --scaling center and free, 0-100 (default 50, 0 = left). This "
+	"applies to the previous --window, --screen-root, or --screen-span output, or the default background",
+	100.0f, &WallpaperEngine::Render::WallpaperState::Alignment::x
+    );
+    addAlignmentArgument (
+	"--alignment-y",
+	"Wallpaper Engine's vertical alignment for --scaling center and free, 0-100 (default 50, 0 = top). This "
+	"applies to the previous --window, --screen-root, or --screen-span output, or the default background",
+	100.0f, &WallpaperEngine::Render::WallpaperState::Alignment::y
+    );
+    addAlignmentArgument (
+	"--alignment-zoom",
+	"Wallpaper Engine's zoom for --scaling free, 0-200 (default 100 = native size, higher zooms in). This applies "
+	"to the previous --window, --screen-root, or --screen-span output, or the default background",
+	200.0f, &WallpaperEngine::Render::WallpaperState::Alignment::zoom
+    );
+
     backgroundGroup.add_argument ("--corner-color")
 	.help (
 	    "Color to show outside the wallpaper's bounds (Center/Fit letterboxing, zoomed-out scaling) when "

+ 8 - 0
src/WallpaperEngine/Application/ApplicationContext.h

@@ -99,6 +99,8 @@ public:
 	float zoom = 1.0f;
 	/** Re-centers a cropping scaling mode/zoom's visible window, see --offset */
 	glm::vec2 offset = { 0.0f, 0.0f };
+	/** WE's alignment position, x, y and zoom, see --alignment-position */
+	WallpaperEngine::Render::WallpaperState::Alignment alignment = {};
 	/** Color shown outside the wallpaper's bounds when clamp is border, see --corner-color */
 	glm::vec4 cornerColor = { 0.0f, 0.0f, 0.0f, 1.0f };
 	/** Image filter, color options and flip, see --image-filter */
@@ -143,6 +145,8 @@ public:
 	    std::map<std::string, float> screenZooms;
 	    /** Re-centers a cropping scaling mode/zoom's visible window for different screens, see --offset */
 	    std::map<std::string, glm::vec2> screenOffsets;
+	    /** WE's alignment settings for different screens, see --alignment-position */
+	    std::map<std::string, WallpaperEngine::Render::WallpaperState::Alignment> screenAlignments;
 	    /** Corner color for different screens, shown outside the wallpaper's bounds when clamp is border */
 	    std::map<std::string, glm::vec4> screenCornerColors;
 	    /** Image filter, color options and flip for different screens, see --image-filter */
@@ -207,6 +211,8 @@ public:
 		float zoom;
 		/** Re-centers a cropping scaling mode/zoom's visible window, see --offset */
 		glm::vec2 offset;
+		/** WE's alignment position, x, y and zoom, see --alignment-position */
+		WallpaperEngine::Render::WallpaperState::Alignment alignment;
 		/** Corner color shown outside the wallpaper's bounds when clamp is border, see --corner-color */
 		glm::vec4 cornerColor;
 		/** Image filter, color options and flip, see --image-filter */
@@ -264,6 +270,7 @@ public:
             .screenClamps = {},
             .screenZooms = {},
             .screenOffsets = {},
+            .screenAlignments = {},
             .screenCornerColors = {},
             .screenImageAdjustments = {},
             .screenPlaylists = {},
@@ -300,6 +307,7 @@ public:
                 .scalingMode = WallpaperEngine::Render::WallpaperState::TextureUVsScaling::DefaultUVs,
                 .zoom = 1.0f,
                 .offset = { 0.0f, 0.0f },
+                .alignment = {},
                 .cornerColor = { 0.0f, 0.0f, 0.0f, 1.0f },
                 .imageAdjustments = {},
             },

+ 79 - 10
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -202,7 +202,8 @@ WallpaperApplication::setupAssetLocator (const std::string& bg, const std::files
     );
 
     // Wastes a render pass on an image element that exists only to host the bloom material above
-    vfs.add ("models/wpenginelinux.json", { { "material", "materials/wpenginelinux.json" } });
+    // fullscreen, so it covers the whole scene buffer whatever part of the scene the output shows
+    vfs.add ("models/wpenginelinux.json", { { "material", "materials/wpenginelinux.json" }, { "fullscreen", true } });
 
     vfs.add (
 	"materials/wpenginelinux.json",
@@ -659,6 +660,7 @@ void WallpaperApplication::advancePlaylist (
 		wallpaper->setZoom (this->resolveScreenZoom (screen));
 		const auto offset = this->resolveScreenOffset (screen);
 		wallpaper->setOffset (offset.x, offset.y);
+		wallpaper->setAlignment (this->resolveScreenAlignment (screen));
 		wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
 		wallpaper->setImageAdjustments (
 		    this->resolveScreenImageAdjustments (screen, *this->m_backgrounds[screen])
@@ -742,6 +744,7 @@ struct HotswapRequest {
     std::optional<std::string> zoom;
     /** "X,Y" offset re-center, each axis in [-1, 1], e.g. "0.5,-1" */
     std::optional<std::string> offset;
+    std::optional<std::string> alignment;
     /** "on"/"off"/"toggle" (also "1"/"0"/"true"/"false" for on/off) */
     std::optional<std::string> disableParallax;
     /** "on"/"off" (also "1"/"0"/"true"/"false"), see --expand-canvas. Baked in at scene build, so it reloads */
@@ -843,6 +846,8 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.zoom = value;
 	} else if (key == "offset") {
 	    request.offset = value;
+	} else if (key == "alignment") {
+	    request.alignment = value;
 	} else if (key == "disable-parallax") {
 	    request.disableParallax = value;
 	} else if (key == "expand-canvas") {
@@ -953,7 +958,8 @@ void WallpaperApplication::checkHotswapRequest () {
 
     if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
 	&& !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
-	&& !request.offset.has_value () && !request.disableParallax.has_value () && !request.expandCanvas.has_value ()
+	&& !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
+	&& !request.expandCanvas.has_value ()
 	&& !request.cornerColor.has_value () && !request.imageAdjustmentsProvided && !request.speed.has_value ()
 	&& !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
 	&& !request.audioSensitivityProvided && !request.soundVolumeProvided) {
@@ -1008,6 +1014,10 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->applyOffsetHotswap (*request.offset);
     }
 
+    if (request.alignment.has_value ()) {
+	this->applyAlignmentHotswap (*request.alignment);
+    }
+
     if (request.disableParallax.has_value ()) {
 	this->applyParallaxHotswap (*request.disableParallax);
     }
@@ -1128,6 +1138,7 @@ void WallpaperApplication::checkHotswapRequest () {
 		    wallpaper->setZoom (this->resolveScreenZoom (screen));
 		    const auto offset = this->resolveScreenOffset (screen);
 		    wallpaper->setOffset (offset.x, offset.y);
+		    wallpaper->setAlignment (this->resolveScreenAlignment (screen));
 		    wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
 		    wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, *background));
 		    this->m_renderContext->setWallpaper (screen, std::move (wallpaper));
@@ -1201,6 +1212,16 @@ glm::vec2 WallpaperApplication::resolveScreenOffset (const std::string& screen)
 								       : this->m_context.settings.render.window.offset;
 }
 
+WallpaperEngine::Render::WallpaperState::Alignment WallpaperApplication::resolveScreenAlignment (
+    const std::string& screen
+) const {
+    const auto it = this->m_context.settings.general.screenAlignments.find (screen);
+
+    return it != this->m_context.settings.general.screenAlignments.end ()
+	? it->second
+	: this->m_context.settings.render.window.alignment;
+}
+
 glm::vec4 WallpaperApplication::resolveScreenCornerColor (const std::string& screen) const {
     const auto it = this->m_context.settings.general.screenCornerColors.find (screen);
 
@@ -1383,6 +1404,52 @@ void WallpaperApplication::applyOffsetHotswap (const std::string& value) {
     sLog.out ("Hotswap: applied offset ", offset.x, ",", offset.y, " live");
 }
 
+void WallpaperApplication::applyAlignmentHotswap (const std::string& value) {
+    // "position,x,y,zoom" in WE's units (0-100, zoom 0-200)
+    std::array<float, 4> values {};
+    std::stringstream stream (value);
+    std::string part;
+    size_t count = 0;
+
+    try {
+	while (count < values.size () && std::getline (stream, part, ',')) {
+	    values[count++] = std::stof (part);
+	}
+    } catch (const std::exception&) {
+	count = 0;
+    }
+
+    if (count != values.size ()) {
+	sLog.error ("Hotswap: ignoring malformed alignment value (expected position,x,y,zoom): ", value);
+	return;
+    }
+
+    const WallpaperEngine::Render::WallpaperState::Alignment alignment {
+	.position = std::clamp (values[0], 0.0f, 100.0f) / 100.0f,
+	.x = std::clamp (values[1], 0.0f, 100.0f) / 100.0f,
+	.y = std::clamp (values[2], 0.0f, 100.0f) / 100.0f,
+	.zoom = std::clamp (values[3], 0.0f, 200.0f) / 100.0f,
+    };
+
+    this->m_context.settings.render.window.alignment = alignment;
+
+    for (auto& [screen, screenAlignment] : this->m_context.settings.general.screenAlignments) {
+	screenAlignment = alignment;
+    }
+
+    for (auto& spanGroup : this->m_context.settings.general.spanGroups) {
+	spanGroup.alignment = alignment;
+    }
+
+    if (this->m_renderContext) {
+	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
+	    wallpaper->setAlignment (alignment);
+	}
+    }
+
+    sLog.out ("Hotswap: applied alignment ", value, " live");
+}
+
 void WallpaperApplication::applyParallaxHotswap (const std::string& value) {
     bool newState;
 
@@ -2032,8 +2099,8 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	// errors left over from rendering (e.g. a uniform type mismatch) would otherwise fail the readback below
 	while (glGetError () != GL_NO_ERROR) {}
 
-	const int readWidth = wallpaper->getCanvasWidth ();
-	const int readHeight = wallpaper->getCanvasHeight ();
+	const int readWidth = wallpaper->getFramebufferWidth ();
+	const int readHeight = wallpaper->getFramebufferHeight ();
 	const auto bufferSize = readWidth * readHeight * 3;
 	auto* buffer = new uint8_t[bufferSize];
 
@@ -2053,10 +2120,10 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	}
 
 	// Get the UV coordinates which define the visible portion based on scaling mode
-	const auto [ustart, uend, vstart, vend] = wallpaper->getState ().getTextureUVs ();
+	const glm::vec4 uvs = wallpaper->getOutputUVs ();
 
 	captures.push_back (
-	    { buffer, readWidth, readHeight, vpWidth, vpHeight, currentXOffset, ustart, uend, vstart, vend }
+	    { buffer, readWidth, readHeight, vpWidth, vpHeight, currentXOffset, uvs.x, uvs.y, uvs.z, uvs.w }
 	);
 
 	if (viewport->single) {
@@ -2203,6 +2270,7 @@ void WallpaperApplication::prepareOutputs () {
 	wallpaper->setZoom (this->resolveScreenZoom (background));
 	const auto offset = this->resolveScreenOffset (background);
 	wallpaper->setOffset (offset.x, offset.y);
+	wallpaper->setAlignment (this->resolveScreenAlignment (background));
 	wallpaper->setCornerColor (this->resolveScreenCornerColor (background));
 	wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (background, *info));
 	m_renderContext->setWallpaper (background, std::move (wallpaper));
@@ -2265,6 +2333,7 @@ void WallpaperApplication::prepareOutputs () {
 	);
 	sharedWallpaper->setZoom (spanGroup.zoom);
 	sharedWallpaper->setOffset (spanGroup.offset.x, spanGroup.offset.y);
+	sharedWallpaper->setAlignment (spanGroup.alignment);
 	sharedWallpaper->setCornerColor (spanGroup.cornerColor);
 	sharedWallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (groupKey, *bgIt->second));
 
@@ -2324,8 +2393,8 @@ void WallpaperApplication::setup () {
 	sLog.exception ("Demo mode only supports one background");
     }
 
-    int width = this->m_renderContext->getWallpapers ().begin ()->second->getCanvasWidth ();
-    int height = this->m_renderContext->getWallpapers ().begin ()->second->getCanvasHeight ();
+    int width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
+    int height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
     std::vector<uint8_t> pixels (width * height * 3);
     bool initialized = false;
     int frame = 0;
@@ -2399,8 +2468,8 @@ void WallpaperApplication::render () {
 	// wait a full render cycle before starting, giving video/web decoders time to set up
 	if (m_videoDriver->getFrameCounter () > (uint32_t)this->m_context.settings.render.maximumFPS) {
 	    if (!initialized) {
-		width = this->m_renderContext->getWallpapers ().begin ()->second->getCanvasWidth ();
-		height = this->m_renderContext->getWallpapers ().begin ()->second->getCanvasHeight ();
+		width = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferWidth ();
+		height = this->m_renderContext->getWallpapers ().begin ()->second->getFramebufferHeight ();
 		pixels.reserve (width * height * 3);
 		init_encoder ("output.webm", width, height);
 		initialized = true;

+ 5 - 0
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -153,6 +153,8 @@ private:
 
     /** Pushes an offset re-center (e.g. "0.5,-1") live to every currently rendered wallpaper */
     void applyOffsetHotswap (const std::string& value);
+    /** Pushes WE's alignment settings ("position,x,y,zoom" in its 0-100/0-200 units) live to every wallpaper */
+    void applyAlignmentHotswap (const std::string& value);
 
     /**
      * Pushes a force-disable-parallax toggle live. This is a straight passthrough to
@@ -210,6 +212,9 @@ private:
     [[nodiscard]] std::string resolveScreenBackgroundPath (const std::string& screen) const;
     [[nodiscard]] float resolveScreenZoom (const std::string& screen) const;
     [[nodiscard]] glm::vec2 resolveScreenOffset (const std::string& screen) const;
+    [[nodiscard]] WallpaperEngine::Render::WallpaperState::Alignment resolveScreenAlignment (
+	const std::string& screen
+    ) const;
     [[nodiscard]] glm::vec4 resolveScreenCornerColor (const std::string& screen) const;
     /** Command line and control file settings for this screen (or span group) over what the preset carries */
     [[nodiscard]] ImageAdjustments

+ 8 - 0
src/WallpaperEngine/Assets/AssetLocator.cpp

@@ -52,6 +52,14 @@ std::string AssetLocator::vertexShader (const std::filesystem::path& filename) c
     return this->shader (final);
 }
 
+std::string AssetLocator::geometryShader (const std::filesystem::path& filename) const {
+    auto final = filename;
+
+    final.replace_extension ("geom");
+
+    return this->shader (final);
+}
+
 std::string AssetLocator::includeShader (const std::filesystem::path& filename) const {
     auto final = filename;
 

+ 1 - 0
src/WallpaperEngine/Assets/AssetLocator.h

@@ -11,6 +11,7 @@ public:
 
     std::string vertexShader (const std::filesystem::path& filename) const;
     std::string fragmentShader (const std::filesystem::path& filename) const;
+    std::string geometryShader (const std::filesystem::path& filename) const;
     std::string includeShader (const std::filesystem::path& filename) const;
     ReadStreamSharedPtr texture (const std::filesystem::path& filename) const;
     std::string readString (const std::filesystem::path& filename) const;

+ 11 - 1
src/WallpaperEngine/Audio/AudioContext.cpp

@@ -4,13 +4,23 @@
 namespace WallpaperEngine::Audio {
 AudioContext::AudioContext (Drivers::AudioDriver& driver) : m_driver (driver) { }
 
-int AudioContext::addStream (AudioStream* stream) const { return this->m_driver.addStream (stream); }
+int AudioContext::addStream (AudioStream* stream, int volume, float left, float right) const {
+    return this->m_driver.addStream (stream, volume, left, right);
+}
 void AudioContext::removeStream (int streamId) const { this->m_driver.removeStream (streamId); }
 
 void AudioContext::setStreamVolume (int streamId, int volume) const {
     this->m_driver.setStreamVolume (streamId, volume);
 }
 
+void AudioContext::setStreamGains (int streamId, float left, float right) const {
+    this->m_driver.setStreamGains (streamId, left, right);
+}
+
+void AudioContext::setStreamPaused (int streamId, bool paused) const {
+    this->m_driver.setStreamPaused (streamId, paused);
+}
+
 AVSampleFormat AudioContext::getFormat () const { return this->m_driver.getFormat (); }
 
 int AudioContext::getSampleRate () const { return this->m_driver.getSampleRate (); }

+ 11 - 1
src/WallpaperEngine/Audio/AudioContext.h

@@ -31,7 +31,7 @@ namespace Audio {
 	 *
 	 * @param stream
 	 */
-	int addStream (AudioStream* stream) const;
+	int addStream (AudioStream* stream, int volume = -1, float left = 1.0f, float right = 1.0f) const;
 
 	/**
 	 * @param streamId The stream to stop playing
@@ -46,6 +46,16 @@ namespace Audio {
 	 */
 	void setStreamVolume (int streamId, int volume) const;
 
+	/**
+	 * Scales the left and right channel of a stream on top of its volume
+	 */
+	void setStreamGains (int streamId, float left, float right) const;
+
+	/**
+	 * Pauses or resumes a stream where it is
+	 */
+	void setStreamPaused (int streamId, bool paused) const;
+
 	/**
 	 * TODO: MAYBE THIS SHOULD BE OUR OWN DEFINITIONS INSTEAD OF LIBRARY SPECIFIC ONES?
 	 *

+ 35 - 1
src/WallpaperEngine/Audio/AudioStream.cpp

@@ -106,7 +106,8 @@ AudioStream::AudioStream (AudioContext& context, const std::string& filename) :
     this->loadCustomContent (filename.c_str ());
 }
 
-AudioStream::AudioStream (AudioContext& context, const ReadStreamSharedPtr& buffer) : m_audioContext (context) {
+AudioStream::AudioStream (AudioContext& context, const ReadStreamSharedPtr& buffer, bool repeat) :
+    m_audioContext (context), m_repeat (repeat) {
     this->m_formatContext = avformat_alloc_context ();
 
     if (this->m_formatContext == nullptr) {
@@ -277,6 +278,13 @@ void AudioStream::initialize () {
 	sLog.exception ("Cannot initialize swrctx for audio resampling");
     }
 
+    // mono goes to both channels unchanged, the mixer pans it with per channel gains like OpenAL does for WE
+    if (this->getSourceChannels () == 1 && this->m_audioContext.getChannels () == 2) {
+	constexpr double duplicate[2] = { 1.0, 1.0 };
+
+	swr_set_matrix (this->m_swrctx, duplicate, 1);
+    }
+
     if (swr_init (this->m_swrctx) < 0) {
 	sLog.exception ("Failed to initialize the resampling context.");
     }
@@ -409,6 +417,32 @@ int AudioStream::getAudioStream () const { return this->m_audioStream; }
 
 bool AudioStream::isInitialized () const { return this->m_initialized; }
 
+double AudioStream::getDuration () const {
+    if (this->m_formatContext == nullptr) {
+	return 0.0;
+    }
+
+    if (this->m_formatContext->duration > 0) {
+	return static_cast<double> (this->m_formatContext->duration) / AV_TIME_BASE;
+    }
+
+    if (this->m_audioStream == NO_AUDIO_STREAM) {
+	return 0.0;
+    }
+
+    const AVStream* stream = this->m_formatContext->streams[this->m_audioStream];
+
+    return stream->duration > 0 ? static_cast<double> (stream->duration) * av_q2d (stream->time_base) : 0.0;
+}
+
+int AudioStream::getSourceChannels () const {
+#if FF_API_OLD_CHANNEL_LAYOUT
+    return this->m_context->channels;
+#else
+    return this->m_context->ch_layout.nb_channels;
+#endif
+}
+
 void AudioStream::setRepeat (const bool newRepeat) { this->m_repeat = newRepeat; }
 
 bool AudioStream::isRepeat () const { return this->m_repeat; }

+ 13 - 1
src/WallpaperEngine/Audio/AudioStream.h

@@ -39,7 +39,11 @@ using namespace WallpaperEngine::FileSystem;
 class AudioStream {
 public:
     AudioStream (AudioContext& context, const std::string& filename);
-    AudioStream (AudioContext& context, const ReadStreamSharedPtr& buffer);
+    /**
+     * @param repeat Set before the reader thread starts, a short file could otherwise be read to its end before a later
+     * setRepeat () call
+     */
+    AudioStream (AudioContext& context, const ReadStreamSharedPtr& buffer, bool repeat = false);
     AudioStream (AudioContext& audioContext, AVCodecContext* context);
     ~AudioStream ();
 
@@ -87,6 +91,14 @@ public:
      * @return If the audio stream can be played or not
      */
     [[nodiscard]] bool isInitialized () const;
+    /**
+     * @return Length of the file in seconds, 0 if the container doesn't say
+     */
+    [[nodiscard]] double getDuration () const;
+    /**
+     * @return Channel count of the file itself, before resampling to the driver's layout
+     */
+    [[nodiscard]] int getSourceChannels () const;
     /**
      * @param newRepeat true = repeat, false = no repeat
      */

+ 17 - 1
src/WallpaperEngine/Audio/Drivers/AudioDriver.h

@@ -39,8 +39,11 @@ namespace Audio {
 	     * Registers the given stream in the driver for playing
 	     *
 	     * @param stream
+	     * @param volume Initial volume override (0-128), -1 = the global volume
+	     * @param left Initial gain of the left channel
+	     * @param right Initial gain of the right channel
 	     */
-	    virtual int addStream (AudioStream* stream) = 0;
+	    virtual int addStream (AudioStream* stream, int volume = -1, float left = 1.0f, float right = 1.0f) = 0;
 
 	    /**
 	     *
@@ -56,6 +59,19 @@ namespace Audio {
 	     */
 	    virtual void setStreamVolume (int streamId, int volume) = 0;
 
+	    /**
+	     * Scales each output channel of a stream, on top of its volume
+	     *
+	     * @param left Gain of the left channel
+	     * @param right Gain of the right channel
+	     */
+	    virtual void setStreamGains (int streamId, float left, float right) = 0;
+
+	    /**
+	     * A paused stream keeps its position and isn't decoded until it is resumed
+	     */
+	    virtual void setStreamPaused (int streamId, bool paused) = 0;
+
 	    /**
 	     * Updates status of the different audio settings
 	     *

+ 76 - 4
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -7,6 +7,47 @@
 using namespace WallpaperEngine::Audio;
 using namespace WallpaperEngine::Audio::Drivers;
 
+namespace {
+template <typename T> void scaleSamples (uint8_t* data, int bytes, int channels, int firstChannel, float left, float right) {
+    auto* samples = reinterpret_cast<T*> (data);
+    const int count = bytes / static_cast<int> (sizeof (T));
+
+    for (int i = 0; i < count; i++) {
+	const int channel = (firstChannel + i) % channels;
+	const float gain = channel == 0 ? left : channel == 1 ? right : (left + right) * 0.5f;
+
+	samples[i] = static_cast<T> (static_cast<float> (samples[i]) * gain);
+    }
+}
+
+/** Copies a chunk of decoded audio with each channel scaled, false when the device format isn't handled */
+bool scaleChunk (
+    std::vector<uint8_t>& out, const uint8_t* data, int bytes, const SDL_AudioSpec& spec, int byteOffset, float left,
+    float right
+) {
+    const int sampleSize = SDL_AUDIO_BITSIZE (spec.format) / 8;
+    const int firstChannel = (byteOffset / sampleSize) % spec.channels;
+
+    out.assign (data, data + bytes);
+
+    if (SDL_AUDIO_ISBIGENDIAN (spec.format) != (SDL_BYTEORDER == SDL_BIG_ENDIAN)) {
+	return false;
+    }
+
+    if (SDL_AUDIO_ISFLOAT (spec.format) && sampleSize == 4) {
+	scaleSamples<float> (out.data (), bytes, spec.channels, firstChannel, left, right);
+    } else if (SDL_AUDIO_ISSIGNED (spec.format) && sampleSize == 2) {
+	scaleSamples<int16_t> (out.data (), bytes, spec.channels, firstChannel, left, right);
+    } else if (SDL_AUDIO_ISSIGNED (spec.format) && sampleSize == 4) {
+	scaleSamples<int32_t> (out.data (), bytes, spec.channels, firstChannel, left, right);
+    } else {
+	return false;
+    }
+
+    return true;
+}
+} // namespace
+
 void audio_callback (void* userdata, uint8_t* streamData, int length) {
     auto* driver = static_cast<SDLAudioDriver*> (userdata);
 
@@ -23,7 +64,7 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) {
 	uint8_t* streamDataPointer = streamData;
 	int streamLength = length;
 
-	if (!buffer->stream->isInitialized ()) {
+	if (!buffer->stream->isInitialized () || buffer->paused.load (std::memory_order_relaxed)) {
 	    continue;
 	}
 
@@ -55,9 +96,20 @@ void audio_callback (void* userdata, uint8_t* streamData, int length) {
 
 	    // mix the audio, using this stream's own volume override if it has one
 	    const int streamVolume = buffer->volume.load (std::memory_order_relaxed);
+	    const float left = buffer->gainLeft.load (std::memory_order_relaxed);
+	    const float right = buffer->gainRight.load (std::memory_order_relaxed);
+	    const uint8_t* source = &buffer->audio_buf[buffer->audio_buf_index];
+	    static std::vector<uint8_t> scaled;
+
+	    if ((left != 1.0f || right != 1.0f)
+		&& scaleChunk (
+		    scaled, source, len1, driver->getSpec (), static_cast<int> (buffer->audio_buf_index), left, right
+		)) {
+		source = scaled.data ();
+	    }
 
 	    SDL_MixAudioFormat (
-		streamDataPointer, &buffer->audio_buf[buffer->audio_buf_index], driver->getSpec ().format, len1,
+		streamDataPointer, source, driver->getSpec ().format, len1,
 		streamVolume >= 0 ? streamVolume : driver->getApplicationContext ().state.audio.volume
 	    );
 
@@ -116,13 +168,19 @@ SDLAudioDriver::~SDLAudioDriver () {
     SDL_QuitSubSystem (SDL_INIT_AUDIO);
 }
 
-int SDLAudioDriver::addStream (AudioStream* stream) {
+int SDLAudioDriver::addStream (AudioStream* stream, int volume, float left, float right) {
     const int newStreamId = this->m_lastStreamID;
     this->m_lastStreamID++;
 
+    auto* buffer = new SDLAudioBuffer { stream };
+
+    buffer->volume = volume;
+    buffer->gainLeft = left;
+    buffer->gainRight = right;
+
     SDL_LockMutex (this->m_streamListMutex);
 
-    this->m_streams.insert_or_assign (newStreamId, new SDLAudioBuffer { stream });
+    this->m_streams.insert_or_assign (newStreamId, buffer);
 
     SDL_UnlockMutex (this->m_streamListMutex);
 
@@ -153,6 +211,20 @@ void SDLAudioDriver::setStreamVolume (int streamId, int volume) {
     }
 }
 
+void SDLAudioDriver::setStreamGains (int streamId, float left, float right) {
+    // same reasoning as setStreamVolume, the gains are atomics read by the callback
+    if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end ()) {
+	it->second->gainLeft.store (left, std::memory_order_relaxed);
+	it->second->gainRight.store (right, std::memory_order_relaxed);
+    }
+}
+
+void SDLAudioDriver::setStreamPaused (int streamId, bool paused) {
+    if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end ()) {
+	it->second->paused.store (paused, std::memory_order_relaxed);
+    }
+}
+
 const std::map<int, SDLAudioBuffer*>& SDLAudioDriver::getStreams () { return this->m_streams; }
 
 AVSampleFormat SDLAudioDriver::getFormat () const {

+ 8 - 1
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.h

@@ -22,6 +22,9 @@ struct SDLAudioBuffer {
     unsigned int audio_buf_index = 0;
     /** Per-stream volume override (0-128), -1 = use the driver's global volume */
     std::atomic<int> volume { -1 };
+    std::atomic<float> gainLeft { 1.0f };
+    std::atomic<float> gainRight { 1.0f };
+    std::atomic<bool> paused { false };
 };
 
 /**
@@ -36,11 +39,15 @@ public:
     ~SDLAudioDriver () override;
 
     /** @inheritdoc */
-    int addStream (AudioStream* stream) override;
+    int addStream (AudioStream* stream, int volume, float left, float right) override;
     /** @inheritdoc */
     void removeStream (int streamId) override;
     /** @inheritdoc */
     void setStreamVolume (int streamId, int volume) override;
+    /** @inheritdoc */
+    void setStreamGains (int streamId, float left, float right) override;
+    /** @inheritdoc */
+    void setStreamPaused (int streamId, bool paused) override;
     /**
      * @return All the registered audio streams
      */

+ 3 - 2
src/WallpaperEngine/Audio/SpectrumAnalyzer.cpp

@@ -7,9 +7,10 @@
 using namespace WallpaperEngine::Audio;
 
 namespace {
-// wallpaper64.exe's capture thread settings (processor constructor sub_1400A9130)
+// wallpaper64.exe 2.8.42's capture thread settings (processor constructor sub_1400C0C80)
 constexpr float BAND_EXPONENT = 0.25f;
-constexpr float TILT = 0.5f;
+// 0x3F004189, 2.4.82 had 0x3F000089
+constexpr float TILT = 0.501f;
 constexpr float SIZE_FACTOR = 30.0f;
 constexpr float BIN_FACTOR = 10.0f;
 // "audioinputvolume" (default 50) * 0.02

+ 2 - 0
src/WallpaperEngine/Data/Assets/Texture.h

@@ -83,6 +83,8 @@ enum TextureFormat {
     TextureFormat_RGBa1010102 = 13,
     TextureFormat_RGBA16161616f = 14,
     TextureFormat_RGB161616f = 15,
+    /** Not a .tex format: a depth only render target with 32 bit float depth (WE's shadow atlas, R32_TYPELESS) */
+    TextureFormat_D32f = 100,
 };
 
 enum TextureFlags {

+ 2 - 0
src/WallpaperEngine/Data/Model/Material.h

@@ -14,6 +14,8 @@ enum BlendingMode {
     BlendingMode_Normal = 1,
     BlendingMode_Translucent = 2,
     BlendingMode_Additive = 3,
+    /** Drawn like normal; shadow casters test their albedo's alpha (sub_140224C70, sub_140155FC0) */
+    BlendingMode_AlphaToCoverage = 4,
 };
 
 enum CullingMode { CullingMode_Unknown = 0, CullingMode_Normal = 1, CullingMode_Disable = 2 };

+ 92 - 19
src/WallpaperEngine/Data/Model/Object.h

@@ -22,10 +22,20 @@
 namespace WallpaperEngine::Data::Model {
 using namespace WallpaperEngine::Data::Utils;
 
+/** A 2.7+ particle dependency record: the object a component of the given type reads (wallpaper64.exe sub_14022AF30) */
+struct ObjectComponentDependency {
+    int id;
+    /** "emitterimage" or "collisionmodel" */
+    std::string type;
+    /** Which of the particle's components of that type uses it, in file order */
+    int index;
+};
+
 struct ObjectData {
     int id;
     std::string name;
     std::vector<int> dependencies;
+    std::vector<ObjectComponentDependency> componentDependencies;
     std::optional<int> parent;
     /** Name of a named attachment point on the parent's puppet rig to follow, if any */
     std::optional<std::string> attachment;
@@ -45,12 +55,17 @@ struct ObjectData {
     /** Drawn with a perspective camera in 2D scenes (general.perspectiveoverridefov), only the object's own flag counts
      */
     UserSettingUniquePtr perspective;
+    /** Drawn into the planar reflection (_rt_Reflection), only a JSON false turns it off (sub_14018FF60) */
+    bool reflected = true;
 };
 
 class Object : public TypeCaster, public ObjectData {
 public:
     explicit Object (ObjectData data) noexcept : TypeCaster (), ObjectData (std::move (data)) { };
     ~Object () override = default;
+
+    /** The JSON the object was created from without its "id" (object +432 in WE), thisScene.getInitialLayerConfig */
+    std::string initialConfig;
 };
 
 struct ImageEffectPassOverride {
@@ -82,6 +97,14 @@ struct ImageAnimationLayer {
     UserSettingUniquePtr animation;
     /** adds its difference from the rest pose instead of blending towards the clip's pose */
     bool additive = false;
+    /** fade the weight in from the start / out towards the end over blendTime seconds (sub_14026C8B0) */
+    bool blendIn = false;
+    bool blendOut = false;
+    float blendTime = 0.5f;
+    /** insert after the last non-additive layer instead of at the end (sub_1401FCC20) */
+    bool autosort = false;
+    /** insert at this position of the layer list, clamped to the last one */
+    std::optional<int64_t> index = std::nullopt;
 };
 
 enum ImageAlignment {
@@ -133,6 +156,13 @@ struct SoundData {
     UserSettingUniquePtr volume;
     /** Sound stays muted until a script calls play() on its layer */
     std::optional<bool> startsilent;
+    /** random mode: seconds of silence after a sound, picked between these */
+    float mintime;
+    float maxtime;
+    /** AL_ROLLOFF_FACTOR / AL_REFERENCE_DISTANCE of spatialized sounds */
+    float attenuation;
+    float mindistance;
+    bool spatialization;
 };
 
 class Sound : public Object, public SoundData {
@@ -186,6 +216,11 @@ struct ParticleEmitter {
     float maxPeriodicDelay;
     float minPeriodicDuration;
     float maxPeriodicDuration;
+    int maxToEmitPerPeriod;
+    /** layerimage: random offset added to the pixel's position with flags 0x80000, null when not set (2D and 3D
+     *  defaults differ) */
+    std::optional<glm::vec3> offsetMin;
+    std::optional<glm::vec3> offsetMax;
 };
 
 /**
@@ -232,18 +267,21 @@ public:
 
 class VelocityRandomInitializer : public ParticleInitializerBase {
 public:
-    VelocityRandomInitializer (UserSettingUniquePtr min, UserSettingUniquePtr max) :
-	min (std::move (min)), max (std::move (max)) { }
+    VelocityRandomInitializer (UserSettingUniquePtr min, UserSettingUniquePtr max, UserSettingUniquePtr exponent) :
+	min (std::move (min)), max (std::move (max)), exponent (std::move (exponent)) { }
+    /** null when not set, the default depends on the scene being 2D or 3D */
     UserSettingUniquePtr min;
     UserSettingUniquePtr max;
+    UserSettingUniquePtr exponent;
 };
 
 class RotationRandomInitializer : public ParticleInitializerBase {
 public:
-    RotationRandomInitializer (UserSettingUniquePtr min, UserSettingUniquePtr max) :
-	min (std::move (min)), max (std::move (max)) { }
+    RotationRandomInitializer (UserSettingUniquePtr min, UserSettingUniquePtr max, UserSettingUniquePtr exponent) :
+	min (std::move (min)), max (std::move (max)), exponent (std::move (exponent)) { }
     UserSettingUniquePtr min;
     UserSettingUniquePtr max;
+    UserSettingUniquePtr exponent;
 };
 
 class AngularVelocityRandomInitializer : public ParticleInitializerBase {
@@ -293,15 +331,20 @@ public:
 class MapSequenceAroundControlPointInitializer : public ParticleInitializerBase {
 public:
     MapSequenceAroundControlPointInitializer (
-	UserSettingUniquePtr controlPoint, UserSettingUniquePtr count, UserSettingUniquePtr speedMin,
-	UserSettingUniquePtr speedMax
+	float count, glm::vec2 bounds, bool mirror, int controlPoint, glm::vec3 speedMin, glm::vec3 speedMax,
+	glm::vec3 axis
     ) :
-	controlPoint (std::move (controlPoint)), count (std::move (count)), speedMin (std::move (speedMin)),
-	speedMax (std::move (speedMax)) { }
-    UserSettingUniquePtr controlPoint;
-    UserSettingUniquePtr count;
-    UserSettingUniquePtr speedMin;
-    UserSettingUniquePtr speedMax;
+	count (count), bounds (bounds), mirror (mirror), controlPoint (controlPoint), speedMin (speedMin),
+	speedMax (speedMax), axis (axis) { }
+    float count;
+    glm::vec2 bounds;
+    /** limitbehavior "mirror", anything else repeats */
+    bool mirror;
+    int controlPoint;
+    /** x along the circle, y outwards, z along the axis */
+    glm::vec3 speedMin;
+    glm::vec3 speedMax;
+    glm::vec3 axis;
 };
 
 /** What inheritvaluefromevent/inheritinitialvaluefromevent take from the event's particle (WE's order) */
@@ -402,7 +445,10 @@ public:
     bool mirror;
     int controlPointStart;
     int controlPointEnd;
-    /** 1 shrink the offset from the line, 2 slow down, 4 shrink, 8 arc, 0x10 count follows instanceoverride count */
+    /**
+     * 1 shrink the offset from the line, 2 slow down, 4 shrink, 8 arc, 0x10 count follows instanceoverride count,
+     * 0x20 starts over with every new emitter period
+     */
     uint32_t flags;
     UserSettingUniquePtr arcAmount;
     UserSettingUniquePtr arcDirection;
@@ -656,34 +702,38 @@ class OscillateAlphaOperator : public ParticleOperatorBase {
 public:
     OscillateAlphaOperator (
 	UserSettingUniquePtr frequencyMin, UserSettingUniquePtr frequencyMax, UserSettingUniquePtr scaleMin,
-	UserSettingUniquePtr scaleMax, UserSettingUniquePtr phaseMin, UserSettingUniquePtr phaseMax
+	UserSettingUniquePtr scaleMax, UserSettingUniquePtr phaseMin, UserSettingUniquePtr phaseMax,
+	ParticleBlendWindow blend
     ) :
 	frequencyMin (std::move (frequencyMin)), frequencyMax (std::move (frequencyMax)),
 	scaleMin (std::move (scaleMin)), scaleMax (std::move (scaleMax)), phaseMin (std::move (phaseMin)),
-	phaseMax (std::move (phaseMax)) { }
+	phaseMax (std::move (phaseMax)), blend (blend) { }
     UserSettingUniquePtr frequencyMin;
     UserSettingUniquePtr frequencyMax;
     UserSettingUniquePtr scaleMin;
     UserSettingUniquePtr scaleMax;
     UserSettingUniquePtr phaseMin;
     UserSettingUniquePtr phaseMax;
+    ParticleBlendWindow blend;
 };
 
 class OscillateSizeOperator : public ParticleOperatorBase {
 public:
     OscillateSizeOperator (
 	UserSettingUniquePtr frequencyMin, UserSettingUniquePtr frequencyMax, UserSettingUniquePtr scaleMin,
-	UserSettingUniquePtr scaleMax, UserSettingUniquePtr phaseMin, UserSettingUniquePtr phaseMax
+	UserSettingUniquePtr scaleMax, UserSettingUniquePtr phaseMin, UserSettingUniquePtr phaseMax,
+	ParticleBlendWindow blend
     ) :
 	frequencyMin (std::move (frequencyMin)), frequencyMax (std::move (frequencyMax)),
 	scaleMin (std::move (scaleMin)), scaleMax (std::move (scaleMax)), phaseMin (std::move (phaseMin)),
-	phaseMax (std::move (phaseMax)) { }
+	phaseMax (std::move (phaseMax)), blend (blend) { }
     UserSettingUniquePtr frequencyMin;
     UserSettingUniquePtr frequencyMax;
     UserSettingUniquePtr scaleMin;
     UserSettingUniquePtr scaleMax;
     UserSettingUniquePtr phaseMin;
     UserSettingUniquePtr phaseMax;
+    ParticleBlendWindow blend;
 };
 
 class OscillatePositionOperator : public ParticleOperatorBase {
@@ -691,18 +741,20 @@ public:
     OscillatePositionOperator (
 	UserSettingUniquePtr frequencyMin, UserSettingUniquePtr frequencyMax, UserSettingUniquePtr scaleMin,
 	UserSettingUniquePtr scaleMax, UserSettingUniquePtr phaseMin, UserSettingUniquePtr phaseMax,
-	UserSettingUniquePtr mask
+	UserSettingUniquePtr mask, ParticleBlendWindow blend
     ) :
 	frequencyMin (std::move (frequencyMin)), frequencyMax (std::move (frequencyMax)),
 	scaleMin (std::move (scaleMin)), scaleMax (std::move (scaleMax)), phaseMin (std::move (phaseMin)),
-	phaseMax (std::move (phaseMax)), mask (std::move (mask)) { }
+	phaseMax (std::move (phaseMax)), mask (std::move (mask)), blend (blend) { }
     UserSettingUniquePtr frequencyMin;
     UserSettingUniquePtr frequencyMax;
     UserSettingUniquePtr scaleMin;
+    /** null when not set, the default depends on the scene being 2D or 3D */
     UserSettingUniquePtr scaleMax;
     UserSettingUniquePtr phaseMin;
     UserSettingUniquePtr phaseMax;
     UserSettingUniquePtr mask;
+    ParticleBlendWindow blend;
 };
 
 /** blendinstart, blendinend, blendoutstart, blendoutend: how much of an operator applies over the particle's life */
@@ -830,6 +882,15 @@ struct ParticleRenderer {
     bool uvSmoothing; // rope only: reduces flickering when lifetimes are identical
     bool fadeAlpha; // ropetrail: fade alpha along trail
     bool fadeSize; // ropetrail: fade size along trail
+    /** "orientation" (sub_1401C22E0): screen 0, upright 1, fixed 2 */
+    int orientation = 0;
+    /** "axis" normalized, (0, 1, 0) when zero (+12) */
+    glm::vec3 axis = { 0.0f, 1.0f, 0.0f };
+    /** normalize (axis x normalize (y x axis)) (+36), the fixed orientation's up */
+    glm::vec3 axisUp = { 0.0f, 0.0f, -1.0f };
+    /** "flags" bit 0: up from the camera (screen), world y (upright) or the raw axes (fixed) instead of the system's
+     *  own frame */
+    bool orientationFlag = false;
 };
 
 enum class ParticleChildType {
@@ -994,6 +1055,8 @@ struct TextData {
     UserSettingUniquePtr dropShadowOpacity;
     UserSettingUniquePtr dropShadowOffset;
     UserSettingUniquePtr dropShadowColor;
+    /** "enabled" draws with the depth tested font materials in 3D scenes, any other value is "disabled" */
+    UserSettingUniquePtr depthTest;
 };
 
 class Text : public Object, public TextData {
@@ -1029,6 +1092,10 @@ struct LightData {
     /** Spot lights projecting a texture ("cookie", WE falls back to cookie/flashlight1) */
     bool useCookie = false;
     std::string cookie;
+    /** Directional light shadow cascades: how far each one reaches (light +768/+772/+776) */
+    UserSettingUniquePtr cascadeDistance[3];
+    /** Point light shadows: the near plane of the cube faces is at least this (light +780) */
+    UserSettingUniquePtr lightSourceSize;
 };
 
 class Light : public Object, public LightData {
@@ -1075,6 +1142,12 @@ public:
 /** A 3D model object ("model" pointing at a .mdl), placed with the base object's origin/scale/angles */
 struct MeshData {
     std::string model;
+    /** "model" given as a number: a script's IModelData token (thisScene.createModelData) */
+    std::optional<int> modelData;
+    /** "skin": which of a mesh's material names to use, clamped to the last one (sub_140224C70) */
+    uint32_t skin = 0;
+    /** played on the model's skeleton like a puppet's (sub_14021AD10 -> sub_1402230C0) */
+    std::vector<ImageAnimationLayerUniquePtr> animationLayers;
 };
 
 class Mesh : public Object, public MeshData {

+ 4 - 0
src/WallpaperEngine/Data/Parsers/MaterialParser.cpp

@@ -107,6 +107,10 @@ BlendingMode MaterialParser::parseBlendMode (const std::string& mode) {
 	return BlendingMode_Translucent;
     }
 
+    if (mode == "alphatocoverage") {
+	return BlendingMode_AlphaToCoverage;
+    }
+
     sLog.error ("Unknown blending mode: ", mode, " defaulting to normal");
     return BlendingMode_Normal;
 }

+ 157 - 28
src/WallpaperEngine/Data/Parsers/ObjectParser.cpp

@@ -259,6 +259,23 @@ std::pair<glm::vec3, bool> deriveColorReference (const JSON& particle) {
 } // namespace
 
 ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
+    auto object = parseObject (it, project);
+
+    if (object != nullptr) {
+	// WE keeps the creation JSON on the object and hands it out without the id (sub_14018C5C0)
+	JSON config = it;
+
+	if (config.is_object ()) {
+	    config.erase ("id");
+	}
+
+	object->initialConfig = config.dump ();
+    }
+
+    return object;
+}
+
+ObjectUniquePtr ObjectParser::parseObject (const JSON& it, const Project& project) {
     const auto imageIt = it.find ("image");
     const auto soundIt = it.find ("sound");
     const auto particleIt = it.find ("particle");
@@ -268,6 +285,9 @@ ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
     // "shape" refers to VolumeLight
     const auto shapeIt = it.find ("shape");
     const auto cameraIt = it.find ("camera");
+    // anything but a JSON false leaves the object in the planar reflection (sub_14018FF60)
+    const auto reflectedIt = it.find ("reflected");
+    const bool reflected = reflectedIt == it.end () || !reflectedIt->is_boolean () || reflectedIt->get<bool> ();
 
     // some particle objects have numeric 'name' fields, so handle type mismatches gracefully
     ObjectData basedata;
@@ -276,6 +296,7 @@ ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
 	    .id = it.require<int> ("id", "Object must have an id"),
 	    .name = it.require<std::string> ("name", "Object must have a name"),
 	    .dependencies = parseDependencies (it),
+	    .componentDependencies = parseComponentDependencies (it),
 	    .parent = it.optional<int> ("parent"),
 	    .attachment = it.optional<std::string> ("attachment"),
 	    .sortOrder = it.optional<int> ("sortorder"),
@@ -287,6 +308,7 @@ ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
 	    .solid = it.user ("solid", project.properties, true),
 	    .disablePropagation = it.user ("disablepropagation", project.properties, false),
 	    .perspective = it.user ("perspective", project.properties, false),
+	    .reflected = reflected,
 	};
     } catch (const std::exception& e) {
 	sLog.error ("Error parsing object base data: ", e.what ());
@@ -305,6 +327,7 @@ ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
 	    .id = id,
 	    .name = name,
 	    .dependencies = parseDependencies (it),
+	    .componentDependencies = parseComponentDependencies (it),
 	    .parent = it.optional<int> ("parent"),
 	    .attachment = it.optional<std::string> ("attachment"),
 	    .sortOrder = it.optional<int> ("sortorder"),
@@ -316,12 +339,13 @@ ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
 	    .solid = it.user ("solid", project.properties, true),
 	    .disablePropagation = it.user ("disablepropagation", project.properties, false),
 	    .perspective = it.user ("perspective", project.properties, false),
+	    .reflected = reflected,
 	};
     }
 
     if (imageIt != it.end () && imageIt->is_string ()) {
 	return parseImage (it, project, std::move (basedata), *imageIt);
-    } else if (soundIt != it.end () && soundIt->is_array ()) {
+    } else if (soundIt != it.end () && !soundIt->is_null ()) {
 	return parseSound (it, project, std::move (basedata));
     } else if (particleIt != it.end () && !particleIt->is_null ()) {
 	return parseParticle (it, project, std::move (basedata));
@@ -329,8 +353,10 @@ ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
 	return parseText (it, project, std::move (basedata));
     } else if (lightIt != it.end () && lightIt->is_string ()) {
 	return parseLight (it, project, std::move (basedata));
-    } else if (modelIt != it.end () && modelIt->is_string ()) {
-	return parseMesh (it, std::move (basedata));
+    } else if (modelIt != it.end () && (modelIt->is_string () || modelIt->is_number () || modelIt->is_object ())) {
+	// sub_14018FF60 makes a model object for a string, number or object "model", sub_14021AD10 only loads strings
+	// (a .mdl) and numbers (script model data)
+	return parseMesh (it, project, std::move (basedata));
     } else if (cameraIt != it.end () && cameraIt->is_string ()) {
 	return parseCamera (it, project, std::move (basedata));
     } else if (shapeIt != it.end () && !shapeIt->is_null ()) {
@@ -500,13 +526,28 @@ LightUniquePtr ObjectParser::parseLight (const JSON& it, const Project& project,
 	    .controlPoint = it.user ("controlpoint", project.properties, glm::vec3 (2.0f, 0.0f, 0.0f)),
 	    .useCookie = it.optional ("usecookie", false),
 	    .cookie = it.optional ("cookie", std::string ()),
+	    .cascadeDistance = {
+		it.user ("cascadedistance0", project.properties, 3.0f),
+		it.user ("cascadedistance1", project.properties, 10.0f),
+		it.user ("cascadedistance2", project.properties, 100.0f),
+	    },
+	    .lightSourceSize = it.user ("lightsourcesize", project.properties, 0.0f),
 	}
     );
 }
 
-MeshUniquePtr ObjectParser::parseMesh (const JSON& it, ObjectData base) {
+MeshUniquePtr ObjectParser::parseMesh (const JSON& it, const Project& project, ObjectData base) {
+    const auto& model = it.at ("model");
+    const auto skinIt = it.find ("skin");
+    const auto& animationLayers = it.optional ("animationlayers");
+
     return std::make_unique<Mesh> (
-	std::move (base), MeshData { .model = it.require<std::string> ("model", "Model object must have a model") }
+	std::move (base),
+	MeshData { .model = model.is_string () ? model.get<std::string> () : std::string (),
+		   .modelData = model.is_number () ? std::optional<int> (model.get<int> ()) : std::nullopt,
+		   .skin = skinIt != it.end () && skinIt->is_number_integer () ? skinIt->get<uint32_t> () : 0,
+		   .animationLayers = animationLayers.has_value () ? parseAnimationLayers (*animationLayers, project)
+								  : std::vector<ImageAnimationLayerUniquePtr> {} }
     );
 }
 
@@ -519,8 +560,36 @@ std::vector<int> ObjectParser::parseDependencies (const JSON& it) {
 
     std::vector<int> result = {};
 
+    // plain ids, or (2.7+ particles) {"id", "type", "index", "mask"} records naming the object an emitterimage or a
+    // collisionmodel component reads (wallpaper64.exe sub_14022AF30)
+    for (const auto& cur : *dependenciesIt) {
+	if (cur.is_number ()) {
+	    result.push_back (cur);
+	} else if (cur.is_object () && cur.contains ("id") && cur["id"].is_number ()) {
+	    result.push_back (cur["id"]);
+	}
+    }
+
+    return result;
+}
+
+std::vector<ObjectComponentDependency> ObjectParser::parseComponentDependencies (const JSON& it) {
+    std::vector<ObjectComponentDependency> result;
+    const auto dependenciesIt = it.find ("dependencies");
+
+    if (dependenciesIt == it.end () || !dependenciesIt->is_array ()) {
+	return result;
+    }
+
+    // sub_14022AF30 takes a record when "id" is an integer, "index" a number and "type" a string
     for (const auto& cur : *dependenciesIt) {
-	result.push_back (cur);
+	if (!cur.is_object () || !cur.contains ("id") || !cur["id"].is_number_integer () || !cur.contains ("index")
+	    || !cur["index"].is_number () || !cur.contains ("type") || !cur["type"].is_string ()) {
+	    continue;
+	}
+	result.push_back (
+	    { .id = cur["id"].get<int> (), .type = cur["type"].get<std::string> (), .index = cur["index"].get<int> () }
+	);
     }
 
     return result;
@@ -530,31 +599,41 @@ SoundUniquePtr ObjectParser::parseSound (const JSON& it, const Project& project,
     const auto soundIt = it.require ("sound", "Object must have a sound");
     std::vector<std::string> sounds = {};
 
+    // WE takes "sound" as one string or an array, non-string entries are skipped (sub_1401F5980)
     for (const auto& cur : soundIt) {
-	sounds.push_back (cur);
+	if (cur.is_string ()) {
+	    sounds.push_back (cur);
+	}
     }
 
+    // defaults from the sound object's constructor in sub_14018FF60
     return std::make_unique<Sound> (
 	std::move (base),
 	SoundData {
-	    .playbackmode = parsePlaybackMode (it.optional ("playbackmode", std::string ("single"))),
+	    .playbackmode = parsePlaybackMode (it.optional ("playbackmode", std::string ("loop"))),
 	    .sounds = sounds,
 	    .volume = it.user<float> ("volume", project.properties, 1.0f),
 	    .startsilent = it.optional<bool> ("startsilent"),
+	    .mintime = it.optional ("mintime", 1.0f),
+	    .maxtime = it.optional ("maxtime", 5.0f),
+	    .attenuation = it.optional ("attenuation", 1.0f),
+	    .mindistance = it.optional ("mindistance", 1.0f),
+	    .spatialization = it.optional ("spatialization", false),
 	}
     );
 }
 
 SoundPlaybackMode ObjectParser::parsePlaybackMode (const std::string& mode) {
-    if (mode == "loop") {
-	return PlaybackMode_Loop;
-    }
-
+    // anything WE's table (loop, random, single) doesn't know ends up as its first entry, loop (sub_1401F7D00)
     if (mode == "random") {
 	return PlaybackMode_Random;
     }
 
-    return PlaybackMode_Single;
+    if (mode == "single") {
+	return PlaybackMode_Single;
+    }
+
+    return PlaybackMode_Loop;
 }
 
 uint32_t ObjectParser::parseAlignment (const std::string& alignment) {
@@ -635,6 +714,7 @@ TextUniquePtr ObjectParser::parseText (const JSON& it, const Project& project, O
 	    .dropShadowOpacity = it.user ("dropshadowopacity", properties, 1.0f),
 	    .dropShadowOffset = it.user ("dropshadowoffset", properties, glm::vec2 (4.0f)),
 	    .dropShadowColor = it.color ("dropshadowcolor", properties, Builders::ColorBuilder::Black),
+	    .depthTest = it.user ("depthtest", properties, std::string ("enabled")),
 	}
     );
 }
@@ -784,14 +864,22 @@ std::vector<ImageAnimationLayerUniquePtr> ObjectParser::parseAnimationLayers (co
 ImageAnimationLayerUniquePtr ObjectParser::parseAnimationLayer (const JSON& it, const Project& project) {
     const auto& properties = project.properties;
 
+    // defaults are the layer constructor's (sub_14026C680): visible, rate and blend 1, blendtime 0.5
+    const auto index = it.find ("index");
+
     return std::make_unique<ImageAnimationLayer> (ImageAnimationLayer {
 	.id = it.require<int> ("id", "Animation layer must have an id"),
 	.name = it.optional<std::string> ("name", ""),
 	.rate = it.user ("rate", properties, 1.0f),
-	.visible = it.user ("visible", properties, false),
+	.visible = it.user ("visible", properties, true),
 	.blend = it.user ("blend", properties, 1.0f),
 	.animation = it.user ("animation", properties, 0),
 	.additive = it.optional ("additive", false),
+	.blendIn = it.optional ("blendin", false),
+	.blendOut = it.optional ("blendout", false),
+	.blendTime = it.optional ("blendtime", 0.5f),
+	.autosort = it.optional ("autosort", false),
+	.index = index != it.end () && index->is_number () ? std::optional (index->get<int64_t> ()) : std::nullopt,
     });
 }
 
@@ -1110,6 +1198,12 @@ ParticleEmitter ObjectParser::parseParticleEmitter (const JSON& it) {
 	return defaultValue;
     };
 
+    // layerimage defaults (sub_1401B9930): colour from the image, speed 0.1..0.2 of the pixel's motion
+    const bool image = name == "layerimage";
+    const auto optionalVec3 = [&it, &parseVec3] (const char* field) -> std::optional<glm::vec3> {
+	return it.find (field) != it.end () ? std::optional (parseVec3 (field, glm::vec3 (0.0f))) : std::nullopt;
+    };
+
     try {
 	return ParticleEmitter {
 	    .id = it.optional ("id", -1),
@@ -1120,11 +1214,11 @@ ParticleEmitter ObjectParser::parseParticleEmitter (const JSON& it) {
 	    .origin = parseVec3 ("origin", glm::vec3 (0.0f)),
 	    .sign = parseVec3 ("sign", glm::vec3 (0.0f)),
 	    .instantaneous = it.optional ("instantaneous", 0u),
-	    .speedMin = it.optional ("speedmin", 0.0f),
-	    .speedMax = it.optional ("speedmax", 0.0f),
+	    .speedMin = it.optional ("speedmin", image ? 0.1f : 0.0f),
+	    .speedMax = it.optional ("speedmax", image ? 0.2f : 0.0f),
 	    .rate = it.optional ("rate", 10.0f),
 	    .controlPoint = it.optional ("controlpoint", 0),
-	    .flags = it.optional ("flags", 0u),
+	    .flags = it.optional ("flags", image ? 0x10000u : 0u),
 	    .cone = it.optional ("cone", 0.0f),
 	    .delay = it.optional ("delay", 0.0f),
 	    .duration = it.optional ("duration", 0.0f),
@@ -1137,6 +1231,9 @@ ParticleEmitter ObjectParser::parseParticleEmitter (const JSON& it) {
 	    .maxPeriodicDelay = it.optional ("maxperiodicdelay", 2.0f),
 	    .minPeriodicDuration = it.optional ("minperiodicduration", 2.0f),
 	    .maxPeriodicDuration = it.optional ("maxperiodicduration", 3.0f),
+	    .maxToEmitPerPeriod = it.optional ("maxtoemitperperiod", 0),
+	    .offsetMin = optionalVec3 ("offsetmin"),
+	    .offsetMax = optionalVec3 ("offsetmax"),
 	};
     } catch (nlohmann::json::exception& e) {
 	sLog.error ("Error parsing emitter: ", e.what ());
@@ -1168,13 +1265,15 @@ ParticleInitializerUniquePtr ObjectParser::parseParticleInitializer (const JSON&
 	    it.user ("min", properties, 0.0f), it.user ("max", properties, 1.0f)
 	);
     } else if (name == "velocityrandom") {
+	// defaults (sub_1401BAC50) differ between 2D and 3D scenes, CParticle picks them
 	return std::make_unique<VelocityRandomInitializer> (
-	    it.user ("min", properties, glm::vec3 (-32.0f)), it.user ("max", properties, glm::vec3 (32.0f))
+	    userIfSet (it, "min", properties), userIfSet (it, "max", properties), it.user ("exponent", properties, 1.0f)
 	);
     } else if (name == "rotationrandom") {
 	return std::make_unique<RotationRandomInitializer> (
 	    rotationBound (it, "min", properties, glm::vec3 (0.0f)),
-	    rotationBound (it, "max", properties, glm::vec3 (0.0f, 0.0f, glm::two_pi<float> ()))
+	    rotationBound (it, "max", properties, glm::vec3 (0.0f, 0.0f, glm::two_pi<float> ())),
+	    it.user ("exponent", properties, 1.0f)
 	);
     } else if (name == "angularvelocityrandom") {
 	return std::make_unique<AngularVelocityRandomInitializer> (
@@ -1202,9 +1301,17 @@ ParticleInitializerUniquePtr ObjectParser::parseParticleInitializer (const JSON&
 	    it.optional ("controlpoint", 0), it.user ("min", properties, 0.1f), it.user ("max", properties, 0.2f)
 	);
     } else if (name == "mapsequencearoundcontrolpoint") {
+	// sub_1401C5490 with the defaults of sub_1401BBC90. "flags" is never read for this one
+	const auto vector = [&it] (const std::string& key, glm::vec3 fallback) {
+	    const auto value = it.optional (key);
+	    return value.has_value () && value->is_string () ? parseFloats (value->get<std::string> ()) : fallback;
+	};
+	const glm::vec3 bounds = vector ("bounds", glm::vec3 (0.0f, 1.0f, 0.0f));
 	return std::make_unique<MapSequenceAroundControlPointInitializer> (
-	    it.user ("controlpoint", properties, 0), it.user ("count", properties, 1),
-	    it.user ("speedmin", properties, glm::vec3 (0.0f)), it.user ("speedmax", properties, glm::vec3 (100.0f))
+	    it.optional ("count", 32.0f), glm::vec2 (bounds),
+	    it.optional<std::string> ("limitbehavior", "repeat") == "mirror", controlPointIndex (it, "controlpoint", 0),
+	    vector ("speedmin", glm::vec3 (0.0f)), vector ("speedmax", glm::vec3 (0.0f)),
+	    vector ("axis", glm::vec3 (0.0f, 0.0f, 1.0f))
 	);
     } else if (name == "hsvcolorrandom") {
 	// defaults from wallpaper64.exe sub_1401BA3E0
@@ -1322,23 +1429,28 @@ ParticleOperatorUniquePtr ObjectParser::parseParticleOperator (const JSON& it, c
 	    userIfSet (it, "threshold", properties), userIfSet (it, "deletethreshold", properties)
 	);
     } else if (name == "oscillatealpha") {
+	// defaults from sub_1401BD910
 	return std::make_unique<OscillateAlphaOperator> (
-	    it.user ("frequencymin", properties, 0.0f), it.user ("frequencymax", properties, 10.0f),
+	    it.user ("frequencymin", properties, 1.0f), it.user ("frequencymax", properties, 10.0f),
 	    it.user ("scalemin", properties, 0.0f), it.user ("scalemax", properties, 1.0f),
-	    it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ())
+	    it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ()),
+	    parseBlendWindow (it)
 	);
     } else if (name == "oscillatesize") {
+	// defaults from sub_1401BDBF0
 	return std::make_unique<OscillateSizeOperator> (
-	    it.user ("frequencymin", properties, 0.0f), it.user ("frequencymax", properties, 10.0f),
+	    it.user ("frequencymin", properties, 1.0f), it.user ("frequencymax", properties, 10.0f),
 	    it.user ("scalemin", properties, 0.8f), it.user ("scalemax", properties, 1.2f),
-	    it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ())
+	    it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ()),
+	    parseBlendWindow (it)
 	);
     } else if (name == "oscillateposition") {
+	// defaults from sub_1401BD5D0
 	return std::make_unique<OscillatePositionOperator> (
-	    it.user ("frequencymin", properties, 0.0f), it.user ("frequencymax", properties, 5.0f),
-	    it.user ("scalemin", properties, 0.0f), it.user ("scalemax", properties, 10.0f),
+	    it.user ("frequencymin", properties, 1.0f), it.user ("frequencymax", properties, 5.0f),
+	    it.user ("scalemin", properties, 0.0f), userIfSet (it, "scalemax", properties),
 	    it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ()),
-	    it.user ("mask", properties, glm::vec3 (1.0f, 1.0f, 0.0f))
+	    it.user ("mask", properties, glm::vec3 (1.0f, 1.0f, 0.0f)), parseBlendWindow (it)
 	);
     } else if (name == "capvelocity") {
 	return std::make_unique<CapVelocityOperator> (userIfSet (it, "maxspeed", properties), parseBlendWindow (it));
@@ -1419,6 +1531,19 @@ ParticleRenderer ObjectParser::parseParticleRenderer (const JSON& it) {
     float subdivisionDefault = (name == "rope") ? 4.0f : 1.0f;
     float lengthDefault = (name == "ropetrail") ? 1.0f : 0.05f;
 
+    // sub_1401C22E0, read for every renderer type: "orientation" defaults to "screen", anything but "upright" and
+    // "fixed" is screen too; "axis" "0 0 0" becomes y up
+    const std::string orientation = it.optional<std::string> ("orientation", "screen");
+    const auto axisIt = it.find ("axis");
+    glm::vec3 axis = axisIt != it.end () && axisIt->is_string () ? parseFloats (axisIt->get<std::string> ()) : glm::vec3 (0.0f);
+    glm::vec3 axisUp (0.0f, 0.0f, -1.0f);
+
+    axis = axis == glm::vec3 (0.0f) ? glm::vec3 (0.0f, 1.0f, 0.0f) : glm::normalize (axis);
+
+    if (axis.x != 0.0f || axis.z != 0.0f) {
+	axisUp = glm::normalize (glm::cross (axis, glm::vec3 (axis.z, 0.0f, -axis.x)));
+    }
+
     return ParticleRenderer {
 	.name = name,
 	.length = it.optional ("length", lengthDefault),
@@ -1431,6 +1556,10 @@ ParticleRenderer ObjectParser::parseParticleRenderer (const JSON& it) {
 	.uvSmoothing = it.optional ("uvsmoothing", true),
 	.fadeAlpha = it.optional ("fadealpha", false),
 	.fadeSize = it.optional ("fadesize", false),
+	.orientation = orientation == "upright" ? 1 : orientation == "fixed" ? 2 : 0,
+	.axis = axis,
+	.axisUp = axisUp,
+	.orientationFlag = (it.optional ("flags", 0) & 1) != 0,
     };
 }
 

+ 5 - 2
src/WallpaperEngine/Data/Parsers/ObjectParser.h

@@ -18,9 +18,13 @@ public:
     /** ImageAlignment flags from an alignment name, images re-read it when a script changes it */
     static uint32_t parseAlignment (const std::string& alignment);
     static ObjectUniquePtr parse (const JSON& it, const Project& project);
+    /** one animationlayers[] entry, also what createAnimationLayer() builds from its config */
+    static ImageAnimationLayerUniquePtr parseAnimationLayer (const JSON& it, const Project& project);
 
 private:
+    static ObjectUniquePtr parseObject (const JSON& it, const Project& project);
     static std::vector<int> parseDependencies (const JSON& it);
+    static std::vector<ObjectComponentDependency> parseComponentDependencies (const JSON& it);
     static SoundUniquePtr parseSound (const JSON& it, const Project& project, ObjectData base);
     static SoundPlaybackMode parsePlaybackMode (const std::string& mode);
     static ImageUniquePtr
@@ -28,7 +32,7 @@ private:
     static ParticleUniquePtr parseParticle (const JSON& it, const Project& project, ObjectData base, int depth = 0);
     static TextUniquePtr parseText (const JSON& it, const Project& project, ObjectData base);
     static LightUniquePtr parseLight (const JSON& it, const Project& project, ObjectData base);
-    static MeshUniquePtr parseMesh (const JSON& it, ObjectData base);
+    static MeshUniquePtr parseMesh (const JSON& it, const Project& project, ObjectData base);
     static SceneCameraUniquePtr parseCamera (const JSON& it, const Project& project, ObjectData base);
     static std::vector<ImageEffectUniquePtr> parseEffects (const JSON& it, const Project& project);
     static ImageEffectUniquePtr parseEffect (const JSON& it, const Project& project);
@@ -37,7 +41,6 @@ private:
     static ImageEffectPassOverrideUniquePtr parseEffectPass (const JSON& it, const Project& project);
     static ComboMap parseComboMap (const JSON& it);
     static std::vector<ImageAnimationLayerUniquePtr> parseAnimationLayers (const JSON& it, const Project& project);
-    static ImageAnimationLayerUniquePtr parseAnimationLayer (const JSON& it, const Project& project);
 
     static ParticleEmitter parseParticleEmitter (const JSON& it);
     static ParticleInitializerUniquePtr parseParticleInitializer (const JSON& it, const Properties& properties);

+ 113 - 0
src/WallpaperEngine/Render/CFBO.cpp

@@ -41,6 +41,23 @@ CFBO::CFBO (
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer);
     glGenTextures (1, &this->m_texture);
     glBindTexture (GL_TEXTURE_2D, this->m_texture);
+
+    if (format == TextureFormat_D32f) {
+	this->setupDepthOnly (textureWidth, textureHeight);
+	this->m_resolution = { textureWidth, textureHeight, realWidth, realHeight };
+	this->m_frames.push_back (std::make_shared<Frame> (Frame {
+	    .frameNumber = 0,
+	    .frametime = 0,
+	    .x = 0,
+	    .y = 0,
+	    .width1 = static_cast<float> (textureWidth),
+	    .width2 = static_cast<float> (realWidth),
+	    .height1 = static_cast<float> (textureHeight),
+	    .height2 = static_cast<float> (realHeight),
+	}));
+	return;
+    }
+
     for (uint32_t level = 0; level < this->m_mipLevels; level++) {
 	glTexImage2D (
 	    GL_TEXTURE_2D, level, internalFormat (format), std::max (textureWidth >> level, 1u),
@@ -123,6 +140,40 @@ CFBO::CFBO (
     this->m_frames.push_back (frame);
 }
 
+void CFBO::setupDepthOnly (const uint32_t width, const uint32_t height) {
+    // what WE's comparison sampler for the atlas does (sub_140099980, texture flags 0x8000008): linear filtered
+    // compare, GREATER (reversed depth), border address with a zero border, so outside the atlas counts as lit
+    constexpr GLfloat border[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
+
+    glTexImage2D (
+	GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, static_cast<GLsizei> (width), static_cast<GLsizei> (height), 0,
+	GL_DEPTH_COMPONENT, GL_FLOAT, nullptr
+    );
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
+    glTexParameterfv (GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_GREATER);
+#if !NDEBUG
+    glObjectLabel (GL_TEXTURE, this->m_texture, -1, this->m_name.c_str ());
+#endif /* DEBUG */
+    glFramebufferTexture2D (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, this->m_texture, 0);
+    glDrawBuffer (GL_NONE);
+    glReadBuffer (GL_NONE);
+
+    if (glCheckFramebufferStatus (GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
+	sLog.exception ("Depth framebuffer ", this->m_name, " is not complete");
+    }
+
+    glDepthMask (GL_TRUE);
+    glClearDepth (0.0);
+    glClear (GL_DEPTH_BUFFER_BIT);
+    glClearDepth (1.0);
+}
+
 CFBO::~CFBO () {
     if (this->m_depthbuffer != GL_NONE) {
 	glDeleteRenderbuffers (1, &this->m_depthbuffer);
@@ -161,6 +212,68 @@ void CFBO::attachDepthBuffer () {
     glBindFramebuffer (GL_FRAMEBUFFER, previous);
 }
 
+void CFBO::resize (uint32_t width, uint32_t height, const uint32_t mipLevels) {
+    width = std::max (width, 1u);
+    height = std::max (height, 1u);
+    const uint32_t levels = mipLevels > 0 ? mipLevels : this->m_mipLevels;
+
+    if (width == this->getRealWidth () && height == this->getRealHeight () && levels == this->m_mipLevels) {
+	return;
+    }
+
+    this->m_mipLevels = levels;
+
+    GLint previous = 0;
+    glGetIntegerv (GL_FRAMEBUFFER_BINDING, &previous);
+
+    if (this->m_format == TextureFormat_D32f) {
+	glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer);
+	glBindTexture (GL_TEXTURE_2D, this->m_texture);
+	this->setupDepthOnly (width, height);
+	glBindFramebuffer (GL_FRAMEBUFFER, previous);
+	this->m_resolution = { width, height, width, height };
+
+	for (const auto& frame : this->m_frames) {
+	    frame->width1 = frame->width2 = width;
+	    frame->height1 = frame->height2 = height;
+	}
+
+	return;
+    }
+
+    glBindTexture (GL_TEXTURE_2D, this->m_texture);
+    for (uint32_t level = 0; level < this->m_mipLevels; level++) {
+	glTexImage2D (
+	    GL_TEXTURE_2D, level, internalFormat (this->m_format), std::max (width >> level, 1u),
+	    std::max (height >> level, 1u), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
+	);
+    }
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, this->m_mipLevels - 1);
+
+    if (this->m_depthbuffer != GL_NONE) {
+	glBindRenderbuffer (GL_RENDERBUFFER, this->m_depthbuffer);
+	glRenderbufferStorage (
+	    GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, static_cast<GLsizei> (width), static_cast<GLsizei> (height)
+	);
+	glBindRenderbuffer (GL_RENDERBUFFER, 0);
+    }
+
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer);
+    GLfloat previousClearColor[4] = {};
+    glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
+    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
+    glClear (GL_COLOR_BUFFER_BIT);
+    glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
+    glBindFramebuffer (GL_FRAMEBUFFER, previous);
+
+    this->m_resolution = { width, height, width, height };
+
+    for (const auto& frame : this->m_frames) {
+	frame->width1 = frame->width2 = width;
+	frame->height1 = frame->height2 = height;
+    }
+}
+
 void CFBO::generateMipmaps () const {
     if (this->m_mipLevels < 2) {
 	return;

+ 7 - 0
src/WallpaperEngine/Render/CFBO.h

@@ -32,6 +32,10 @@ public:
     /** Adds a depth buffer, only 3D scenes draw into the scene buffer with depth testing */
     void attachDepthBuffer ();
 
+    /** Reallocates the storage at a new size (and mip count, 0 keeps it), cleared. Whoever holds the buffer keeps
+     *  the same object */
+    void resize (uint32_t width, uint32_t height, uint32_t mipLevels = 0);
+
     /** Rebuilds mip levels 1 and up from level 0, only for buffers created with more than one level */
     void generateMipmaps () const;
     [[nodiscard]] uint32_t getMipLevels () const;
@@ -57,6 +61,9 @@ public:
     bool isReady () const override;
 
 private:
+    /** The bound texture becomes the depth attachment of the bound framebuffer (TextureFormat_D32f) */
+    void setupDepthOnly (uint32_t width, uint32_t height);
+
     GLuint m_framebuffer = GL_NONE;
     GLuint m_depthbuffer = GL_NONE;
     GLuint m_texture = GL_NONE;

+ 34 - 10
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -267,6 +267,24 @@ void CWallpaper::updateUVs (const glm::ivec4& viewport, const bool vflip) {
     }
 }
 
+glm::vec4 CWallpaper::getOutputUVs () const {
+    if (this->rendersAtOutputSize ()) {
+	return this->m_state.isVFlipped () ? glm::vec4 { 0.0f, 1.0f, 0.0f, 1.0f } : glm::vec4 { 0.0f, 1.0f, 1.0f, 0.0f };
+    }
+
+    const auto uvs = this->m_state.getTextureUVs ();
+    return { uvs.ustart, uvs.uend, uvs.vstart, uvs.vend };
+}
+
+int CWallpaper::getFramebufferWidth () const {
+    return this->m_sceneFBO != nullptr ? static_cast<int> (this->m_sceneFBO->getRealWidth ()) : this->getCanvasWidth ();
+}
+
+int CWallpaper::getFramebufferHeight () const {
+    return this->m_sceneFBO != nullptr ? static_cast<int> (this->m_sceneFBO->getRealHeight ())
+				       : this->getCanvasHeight ();
+}
+
 void CWallpaper::render (
     const glm::ivec4& viewport, const bool vflip, const glm::ivec2& globalPosition, const glm::ivec2& logicalSize
 ) {
@@ -277,6 +295,8 @@ void CWallpaper::render (
 	: viewport;
 
     this->m_screenSize = { sceneViewport.z, sceneViewport.w };
+    // the scene reads the visible region from these while it renders
+    this->updateUVs (this->m_spanInfo.has_value () ? this->m_spanInfo->totalBounds : viewport, vflip);
 
 #if !NDEBUG
     glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, "Rendering scene");
@@ -301,8 +321,11 @@ void CWallpaper::render (
 	const float spanX = static_cast<float> (span.totalBounds.x);
 	const float spanY = static_cast<float> (span.totalBounds.y);
 
-	this->updateUVs (span.totalBounds, vflip);
-	auto [baseUstart, baseUend, baseVstart, baseVend] = this->m_state.getTextureUVs ();
+	const glm::vec4 base = this->getOutputUVs ();
+	const float baseUstart = base.x;
+	const float baseUend = base.y;
+	const float baseVstart = base.z;
+	const float baseVend = base.w;
 
 	// this viewport's relative position within the bounding box [0..1]; logicalSize is in the
 	// same coordinate space as globalPosition and totalBounds
@@ -335,16 +358,15 @@ void CWallpaper::render (
 	    );
 	}
     } else {
-	updateUVs (viewport, vflip);
-	auto uvs = this->m_state.getTextureUVs ();
-	ustart = uvs.ustart;
-	uend = uvs.uend;
+	const glm::vec4 uvs = this->getOutputUVs ();
+	ustart = uvs.x;
+	uend = uvs.y;
+	vstart = uvs.z;
+	vend = uvs.w;
 
 	if (this->m_flipHorizontal) {
 	    std::swap (ustart, uend);
 	}
-	vstart = uvs.vstart;
-	vend = uvs.vend;
     }
 
     const GLfloat texCoords[] = {
@@ -447,6 +469,8 @@ void CWallpaper::setZoom (float zoom) { this->m_state.setZoom (zoom); }
 
 void CWallpaper::setOffset (float offsetX, float offsetY) { this->m_state.setOffset (offsetX, offsetY); }
 
+void CWallpaper::setAlignment (const WallpaperState::Alignment& alignment) { this->m_state.setAlignment (alignment); }
+
 void CWallpaper::setCornerColor (const glm::vec4& color) {
     this->m_cornerColor = color;
 
@@ -491,8 +515,8 @@ GLuint CWallpaper::renderAdjustedFramebuffer () {
 	return this->getWallpaperFramebuffer ();
     }
 
-    const auto width = static_cast<uint32_t> (this->getCanvasWidth ());
-    const auto height = static_cast<uint32_t> (this->getCanvasHeight ());
+    const auto width = static_cast<uint32_t> (this->getFramebufferWidth ());
+    const auto height = static_cast<uint32_t> (this->getFramebufferHeight ());
 
     if (this->m_adjustedFBO == nullptr || this->m_adjustedFBO->getRealWidth () != width
 	|| this->m_adjustedFBO->getRealHeight () != height) {

+ 9 - 0
src/WallpaperEngine/Render/CWallpaper.h

@@ -73,6 +73,9 @@ public:
 
     /** Re-centers a cropping scaling mode's visible window live (see WallpaperState::setOffset) */
     void setOffset (float offsetX, float offsetY);
+    [[nodiscard]] const glm::vec4& getCornerColor () const { return this->m_cornerColor; }
+    /** WE's alignment position, x, y and zoom live (see WallpaperState::setAlignment) */
+    void setAlignment (const WallpaperState::Alignment& alignment);
 
     /**
      * Changes the color shown outside the wallpaper's bounds (Center/Fit letterboxing, zoomed-out
@@ -111,6 +114,12 @@ public:
     /** Size of the framebuffer the wallpaper renders into, only a scene can make this bigger than getWidth/getHeight */
     [[nodiscard]] virtual int getCanvasWidth () const { return this->getWidth (); }
     [[nodiscard]] virtual int getCanvasHeight () const { return this->getHeight (); }
+    /** Scenes render at the output's size with the scaling mode folded into their projection, like WE does */
+    [[nodiscard]] virtual bool rendersAtOutputSize () const { return false; }
+    /** The part of the framebuffer the output shows as ustart, uend, vstart, vend */
+    [[nodiscard]] glm::vec4 getOutputUVs () const;
+    [[nodiscard]] int getFramebufferWidth () const;
+    [[nodiscard]] int getFramebufferHeight () const;
     /** Size of the output the wallpaper was last rendered to, zero until the first frame */
     [[nodiscard]] const glm::ivec2& getScreenSize () const { return this->m_screenSize; }
 

+ 34 - 33
src/WallpaperEngine/Render/Camera.cpp

@@ -30,11 +30,13 @@ const glm::mat4& Camera::getProjection () const { return this->m_projection; }
 const glm::mat4& Camera::getLookAt () const { return this->m_lookat; }
 
 const glm::mat4& Camera::getFullscreenProjection () const {
-    return this->m_isOrthogonal ? this->m_orthogonal : this->m_projection;
+    return this->m_isOrthogonal ? this->m_fullscreen : this->m_projection;
 }
 
 const glm::mat4& Camera::getWorldView () const { return this->m_worldView; }
 
+float Camera::getViewFov () const { return this->m_viewFov; }
+
 const glm::mat4& Camera::getPerspectiveLayerViewProjection () const { return this->m_perspectiveLayer; }
 
 bool Camera::isOrthogonal () const { return this->m_isOrthogonal; }
@@ -70,14 +72,13 @@ void Camera::setOrthogonalProjection (
     this->m_canvasHeight = canvasHeight > 0.0f ? canvasHeight : height;
 
     // WE's 2D projection keeps -2000..2000 in depth (sub_140183A70), rotated layers and particles poke out of z = 0
-    this->m_orthogonal = glm::ortho<float> (
+    this->m_fullscreen = glm::ortho<float> (
 	-this->m_canvasWidth / 2.0f, this->m_canvasWidth / 2.0f, -this->m_canvasHeight / 2.0f,
 	this->m_canvasHeight / 2.0f, -2000.0f, 2000.0f
     );
     this->m_isOrthogonal = true;
-    this->setZoom (1.0f);
     this->setWorldView (glm::mat4 (1.0f));
-    this->updatePerspectiveLayers ({ 0.0f, 1.0f, 0.0f, 1.0f }, this->m_canvasWidth / this->m_canvasHeight);
+    this->setVisibleRegion ({}, this->m_canvasWidth / this->m_canvasHeight);
 }
 
 void Camera::setPerspectiveProjection (const float width, const float height) {
@@ -123,10 +124,11 @@ void Camera::setPerspectiveView (const glm::mat4& view, const float fov) {
     const float radians = glm::radians (glm::clamp (fov, 0.1f, 179.9f));
 
     this->m_worldView = view;
+    this->m_viewFov = fov;
     this->m_eye = glm::vec3 (glm::inverse (view)[3]);
     this->m_view = view;
-    this->m_perspective
-	= kFlipY * glm::perspective (radians, this->m_width / this->m_height, this->getNearZ (), this->getFarZ ());
+    const float aspect = this->m_outputAspect > 0.0f ? this->m_outputAspect : this->m_width / this->m_height;
+    this->m_perspective = kFlipY * glm::perspective (radians, aspect, this->getNearZ (), this->getFarZ ());
 
     // "perspective" layers in 3D scenes: sub_140183A70 sets the renderer fov to 2 atan (tan (fov / 2) / 2000), so
     // sub_1401E5B60 always backs off to 2000, keeps the view's rotation and x/y (the visible region offsets are 0 in
@@ -134,33 +136,41 @@ void Camera::setPerspectiveView (const glm::mat4& view, const float fov) {
     glm::mat4 layerView = view;
     layerView[3][2] = -2000.0f;
     this->m_perspectiveLayer = kFlipY
-	* glm::perspective (
-	    2.0f * std::atan (std::tan (radians / 2.0f) / 2000.0f), this->m_width / this->m_height, 5.0f, 15000.0f
-	)
+	* glm::perspective (2.0f * std::atan (std::tan (radians / 2.0f) / 2000.0f), aspect, 5.0f, 15000.0f)
 	* layerView;
 }
 
-void Camera::updatePerspectiveLayers (const glm::vec4& uvs, const float viewportAspect) {
+void Camera::setVisibleRegion (const glm::vec4& margins, const float outputAspect) {
+    this->m_margins = margins;
+    this->m_outputAspect = outputAspect;
+
     if (!this->m_isOrthogonal) {
 	return;
     }
 
-    const float width = this->m_width;
-    const float height = this->m_height;
-    const float canvasWidth = this->m_canvasWidth;
-    const float canvasHeight = this->m_canvasHeight;
+    const float halfWidth = this->m_canvasWidth / 2.0f;
+    const float halfHeight = this->m_canvasHeight / 2.0f;
 
-    // the visible window of the scene in WE's world units: what WE's own ortho projection covers on screen
-    float visibleWidth = std::abs (uvs.y - uvs.x) * canvasWidth;
-    float visibleHeight = std::abs (uvs.w - uvs.z) * canvasHeight;
+    this->m_orthogonal = glm::ortho<float> (
+	-halfWidth + margins.x, halfWidth - margins.y, -halfHeight + margins.z, halfHeight - margins.w, -2000.0f,
+	2000.0f
+    );
+    this->setZoom (this->m_zoom);
+}
 
-    if (visibleWidth <= 0.0f || visibleHeight <= 0.0f) {
-	visibleWidth = canvasWidth;
-	visibleHeight = canvasHeight;
+void Camera::updatePerspectiveLayers () {
+    if (!this->m_isOrthogonal) {
+	return;
     }
 
-    const float centerX = width / 2.0f + ((uvs.x + uvs.y) / 2.0f - 0.5f) * canvasWidth;
-    const float centerY = height / 2.0f - ((uvs.z + uvs.w) / 2.0f - 0.5f) * canvasHeight;
+    const float width = this->m_width;
+    const float height = this->m_height;
+    const glm::vec4& margins = this->m_margins;
+    const float visibleHeight = std::max (this->m_canvasHeight - margins.z - margins.w, 1.0f);
+
+    // renderer +248/+252: the visible region's center, where the layer camera moves to
+    const float centerX = width / 2.0f + (margins.x - margins.y) / 2.0f;
+    const float centerY = height / 2.0f + (margins.z - margins.w) / 2.0f;
 
     // sub_1401E5B60: the camera backs off until the visible height fills the fov, near 5, far max (15000, d + 1000)
     const float fov = glm::radians (
@@ -168,7 +178,6 @@ void Camera::updatePerspectiveLayers (const glm::vec4& uvs, const float viewport
     );
     // the zoom is part of the ortho projection WE derives the distance from
     const float distance = visibleHeight / (2.0f * this->m_zoom * std::tan (fov / 2.0f));
-    const float nearZ = 5.0f;
     const float farZ = std::max (15000.0f, distance + 1000.0f);
 
     glm::mat4 view = this->m_worldView;
@@ -176,16 +185,8 @@ void Camera::updatePerspectiveLayers (const glm::vec4& uvs, const float viewport
     view[3][1] -= centerY;
     view[3][2] = -distance;
 
-    // WE's frustum covers the output only, with the output's aspect; this one covers the whole scene buffer the
-    // output window is cut from later, scaled so the visible part lands where WE puts it
-    const float aspectScale = viewportAspect * visibleHeight / visibleWidth;
-    const float scale = nearZ / (distance * this->m_zoom);
-    const glm::mat4 projection = glm::frustum (
-	(width / 2.0f - canvasWidth / 2.0f - centerX) * aspectScale * scale,
-	(width / 2.0f + canvasWidth / 2.0f - centerX) * aspectScale * scale,
-	(height / 2.0f - canvasHeight / 2.0f - centerY) * scale,
-	(height / 2.0f + canvasHeight / 2.0f - centerY) * scale, nearZ, farZ
-    );
+    const float aspect = this->m_outputAspect > 0.0f ? this->m_outputAspect : this->m_canvasWidth / this->m_canvasHeight;
+    const glm::mat4 projection = glm::perspective (fov, aspect, 5.0f, farZ);
 
     const glm::vec3 center (width / 2.0f, height / 2.0f, 0.0f);
     this->m_perspectiveLayer = kFlipY * projection * view * glm::translate (glm::mat4 (1.0f), center) * kFlipY;

+ 13 - 3
src/WallpaperEngine/Render/Camera.h

@@ -65,11 +65,17 @@ public:
     /** 3D scenes: a camera object replaces the scene.json eye and fov */
     void setPerspectiveView (const glm::mat4& view, float fov);
     [[nodiscard]] const glm::mat4& getWorldView () const;
+    /** The fov the last setPerspectiveView used */
+    [[nodiscard]] float getViewFov () const;
     /**
-     * Rebuilds the camera of layers with "perspective" set (sub_1401E5B60) for the part of the scene that ends up
-     * on screen: uvs are the output's texture window over the scene buffer (ustart, uend, vstart, vend)
+     * The part of the canvas the output shows, as margins cut off each side (left, right, bottom, top, y up, negative
+     * for letterboxing), and the output's aspect. 2D scenes project that region onto the whole scene buffer
+     * (sub_140183A70), 3D scenes take the aspect for their perspective. Also rebuilds the camera of layers with
+     * "perspective" set (sub_1401E5B60)
      */
-    void updatePerspectiveLayers (const glm::vec4& uvs, float viewportAspect);
+    void setVisibleRegion (const glm::vec4& margins, float outputAspect);
+    /** After the view and zoom of a frame are set */
+    void updatePerspectiveLayers ();
     /** View projection of "perspective" layers, same space as getProjection () * getLookAt () in 2D scenes, WE's world
      *  in 3D ones */
     [[nodiscard]] const glm::mat4& getPerspectiveLayerViewProjection () const;
@@ -89,7 +95,11 @@ private:
     glm::mat4 m_lookat = {};
     glm::mat4 m_worldView = glm::mat4 (1.0f);
     glm::mat4 m_orthogonal = {};
+    glm::mat4 m_fullscreen = {};
+    glm::vec4 m_margins = {};
+    float m_outputAspect = 0.0f;
     float m_zoom = 1.0f;
+    float m_viewFov = 0.0f;
     glm::mat4 m_perspectiveLayer = {};
     const SceneData::Camera& m_camera;
     Wallpapers::CScene& m_scene;

+ 310 - 0
src/WallpaperEngine/Render/ModelData.cpp

@@ -0,0 +1,310 @@
+#include "ModelData.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <limits>
+
+using namespace WallpaperEngine::Render::ModelData;
+
+namespace {
+// format bit and size of every vertex component, the tables at 0x140484A20 / 0x1404849B0 (sub_1400EA5B0)
+constexpr std::pair<uint32_t, uint32_t> COMPONENTS[] = {
+    { 0x1, 12 },      { 0x10000, 16 },  { 0x2000000, 12 }, { 0x2, 12 },       { 0x4, 16 },      { 0x800000, 16 },
+    { 0x1000000, 16 }, { 0x8, 8 },       { 0x10, 12 },      { 0x20, 16 },      { 0x40, 8 },      { 0x80, 12 },
+    { 0x100, 16 },    { 0x200, 8 },     { 0x400, 12 },     { 0x800, 16 },     { 0x1000, 8 },    { 0x2000, 12 },
+    { 0x4000, 16 },   { 0x20000, 8 },   { 0x40000, 12 },   { 0x80000, 16 },   { 0x100000, 8 },  { 0x200000, 12 },
+    { 0x400000, 16 }, { 0x8000, 16 },
+};
+
+uint32_t vertexStride (uint32_t format) {
+    uint32_t stride = 0;
+
+    for (const auto& [bit, size] : COMPONENTS) {
+	if (format & bit) {
+	    stride += size;
+	}
+    }
+
+    return stride;
+}
+
+template <typename T> std::vector<char> bytesOf (const std::vector<T>& values) {
+    std::vector<char> result (values.size () * sizeof (T));
+
+    if (!values.empty ()) {
+	std::memcpy (result.data (), values.data (), result.size ());
+    }
+
+    return result;
+}
+
+/** sub_1401C2F10: the mesh and its buffers from a shape, false (error set) when the data doesn't fit the format */
+bool buildMesh (Mesh& mesh, const ShapeConfig& shape, Error& error) {
+    mesh.format = shape.format;
+    mesh.stride = vertexStride (shape.format);
+
+    const auto bytes = static_cast<uint32_t> (shape.vertices.size () * sizeof (float));
+
+    // WE divides by the stride unchecked, a format without components would crash it
+    if (mesh.stride == 0 || bytes % mesh.stride != 0) {
+	error = Error::InconsistentVertexBufferSize;
+	return false;
+    }
+
+    mesh.vertexDynamic = shape.vertexDynamic;
+    mesh.indexDynamic = shape.indexDynamic;
+    mesh.vertexFloats = static_cast<uint32_t> (shape.vertices.size ());
+    mesh.indexCount = shape.indexCount ();
+    mesh.indexed = shape.hasIndices ();
+    mesh.wideIndices = shape.hasIndices32;
+    mesh.vertices = bytesOf (shape.vertices);
+    mesh.indices = shape.hasIndices32 ? bytesOf (shape.indices32) : bytesOf (shape.indices16);
+    mesh.revision++;
+    return true;
+}
+
+// WE takes the bounds with fminf/fmaxf per component
+glm::vec3 lower (const glm::vec3& a, const glm::vec3& b) {
+    return { std::fmin (a.x, b.x), std::fmin (a.y, b.y), std::fmin (a.z, b.z) };
+}
+
+glm::vec3 upper (const glm::vec3& a, const glm::vec3& b) {
+    return { std::fmax (a.x, b.x), std::fmax (a.y, b.y), std::fmax (a.z, b.z) };
+}
+
+/** Copies new data over a dynamic buffer, WE copies as many bytes as the buffer was created with */
+void writeInPlace (std::vector<char>& target, const std::vector<char>& source) {
+    std::memcpy (target.data (), source.data (), std::min (target.size (), source.size ()));
+}
+} // namespace
+
+const char* WallpaperEngine::Render::ModelData::errorMessage (Error error) {
+    // scenescript64 sub_1816361F0: index 0 is an empty string
+    switch (error) {
+	case Error::InvalidMaterial: return "Invalid material";
+	case Error::ShaderExpectingMoreVertexData: return "Shader expecting more vertex data.";
+	case Error::InconsistentVertexBufferSize: return "Inconsistent vertex buffer size";
+	case Error::InvalidToken: return "Invalid model data token";
+	case Error::VertexBufferSizeCannotIncrease: return "Vertex buffer size cannot increase";
+	case Error::IndexBufferSizeCannotIncrease: return "Index buffer size cannot increase";
+	case Error::NotCreatedAsDynamic: return "Model data not created as dynamic";
+	case Error::BufferLockFailed: return "Buffer lock failed";
+	case Error::IncorrectIndexBufferType: return "Incorrect index buffer type";
+	case Error::CannotAddShapes: return "Cannot add shapes in IModelData.update";
+	case Error::CannotDeleteShapes: return "Cannot delete shape or buffers in IModelData.update";
+	case Error::CannotChangeMaterial: return "Material cannot be changed in IModelData.update";
+	case Error::CannotChangeVertexFormat: return "Vertex format cannot be changed in IModelData.update";
+	case Error::None: break;
+    }
+
+    return "";
+}
+
+uint32_t Store::create (const Config& config, const MaterialCheck& check, Error& error) {
+    constexpr float MAX = std::numeric_limits<float>::max ();
+    auto model = std::make_shared<Model> ();
+    glm::vec3 boundsMin (MAX);
+    glm::vec3 boundsMax (-MAX);
+
+    error = Error::None;
+
+    for (const auto& shape : config.shapes) {
+	Mesh& mesh = model->meshes.emplace_back ();
+
+	// a shape that doesn't fit still gets its material checked, the last error wins
+	buildMesh (mesh, shape, error);
+
+	if (const Error materialError = check (shape.material, mesh.format); materialError != Error::None) {
+	    error = materialError;
+	}
+
+	mesh.material = shape.material;
+
+	glm::vec3 meshMin (MAX);
+	glm::vec3 meshMax (-MAX);
+
+	if (config.boundsMin.has_value () && config.boundsMax.has_value ()) {
+	    meshMin = *config.boundsMin;
+	    meshMax = *config.boundsMax;
+	} else {
+	    // every three floats of the buffer count as a position, whatever the vertex format is
+	    const auto& floats = shape.vertices;
+
+	    for (size_t i = 0; i + 2 < floats.size (); i += 3) {
+		meshMin = lower (meshMin, glm::vec3 (floats[i], floats[i + 1], floats[i + 2]));
+		meshMax = upper (meshMax, glm::vec3 (floats[i], floats[i + 1], floats[i + 2]));
+	    }
+	}
+
+	boundsMin = lower (boundsMin, meshMin);
+	boundsMax = upper (boundsMax, meshMax);
+    }
+
+    if (error != Error::None) {
+	return 0;
+    }
+
+    model->boundsMin = boundsMin;
+    model->boundsMax = boundsMax;
+    model->token = ++this->m_counter;
+    this->m_models.emplace (model->token, model);
+
+    return model->token;
+}
+
+void Store::apply (uint32_t token, const Config& config, bool replace, const MaterialCheck& check, Error& error) {
+    error = Error::None;
+
+    const auto found = this->m_models.find (token);
+
+    if (found == this->m_models.end ()) {
+	error = Error::InvalidToken;
+	return;
+    }
+
+    Model& model = *found->second;
+    auto& meshes = model.meshes;
+    bool changed = false;
+    bool completed = true;
+
+    const auto notify = [&model] () { model.structure++; };
+
+    if (!replace && config.shapes.size () > meshes.size ()) {
+	error = Error::CannotAddShapes;
+	return;
+    }
+
+    for (size_t index = 0; index < config.shapes.size (); index++) {
+	const ShapeConfig& shape = config.shapes[index];
+
+	if (shape.deleteShape || shape.deleteIndices) {
+	    if (!replace) {
+		error = Error::CannotDeleteShapes;
+		completed = false;
+		break;
+	    }
+
+	    // null shapes go after the loop
+	    if (shape.deleteShape) {
+		continue;
+	    }
+	}
+
+	if (replace && index >= meshes.size ()) {
+	    meshes.emplace_back ();
+	}
+
+	Mesh& mesh = meshes[index];
+
+	if (!shape.material.empty () && shape.material != mesh.material) {
+	    if (!replace) {
+		error = Error::CannotChangeMaterial;
+		completed = false;
+		break;
+	    }
+
+	    changed = true;
+	    mesh.material = shape.material;
+	}
+
+	const bool formatChanged = shape.format != 0 && mesh.format != shape.format;
+
+	if (formatChanged && !replace) {
+	    error = Error::CannotChangeVertexFormat;
+	    completed = false;
+	    break;
+	}
+
+	const bool vertices = shape.hasVertices;
+	const bool indices = shape.hasIndices ();
+	const bool vertexGrows = vertices && shape.vertices.size () > mesh.vertexFloats;
+	const bool indexGrows = indices && shape.indexCount () > mesh.indexCount;
+	bool rebuildVertices = vertexGrows || formatChanged;
+	bool rebuildIndices = formatChanged || indexGrows;
+
+	if (vertices && !mesh.vertexDynamic) {
+	    rebuildVertices = true;
+	}
+
+	if (indices && !mesh.indexDynamic) {
+	    rebuildIndices = true;
+	}
+
+	if (shape.deleteIndices && mesh.indexed) {
+	    rebuildIndices = true;
+	}
+
+	if (rebuildVertices || rebuildIndices) {
+	    // applyData checks this before the growth, so its own messages for growing buffers never come up
+	    if (!replace) {
+		error = Error::NotCreatedAsDynamic;
+		completed = false;
+		break;
+	    }
+
+	    changed = true;
+	    buildMesh (mesh, shape, error);
+
+	    if (!shape.material.empty ()) {
+		if (const Error materialError = check (shape.material, mesh.format); materialError != Error::None) {
+		    error = materialError;
+		    notify ();
+		    return;
+		}
+	    }
+
+	    continue;
+	}
+
+	if (vertices) {
+	    writeInPlace (mesh.vertices, bytesOf (shape.vertices));
+	    mesh.revision++;
+	}
+
+	if (shape.hasIndices32 && mesh.wideIndices) {
+	    writeInPlace (mesh.indices, bytesOf (shape.indices32));
+	    mesh.revision++;
+	} else if (shape.hasIndices16 && !mesh.wideIndices) {
+	    writeInPlace (mesh.indices, bytesOf (shape.indices16));
+	    mesh.revision++;
+	} else if (indices) {
+	    error = Error::IncorrectIndexBufferType;
+	    completed = false;
+	    break;
+	}
+    }
+
+    if (completed) {
+	for (size_t index = 0, mesh = 0; index < config.shapes.size (); index++, mesh++) {
+	    if (config.shapes[index].deleteShape && mesh < meshes.size ()) {
+		meshes.erase (meshes.begin () + static_cast<std::ptrdiff_t> (mesh));
+		mesh--;
+		changed = true;
+	    }
+	}
+    }
+
+    if (changed) {
+	notify ();
+    }
+}
+
+void Store::release (uint32_t token) {
+    const auto found = this->m_models.find (token);
+
+    if (found != this->m_models.end () && found->second->references-- == 1) {
+	this->m_models.erase (found);
+    }
+}
+
+std::shared_ptr<Model> Store::acquire (int token) {
+    const auto found = this->m_models.find (static_cast<uint32_t> (token));
+
+    if (found == this->m_models.end ()) {
+	return nullptr;
+    }
+
+    found->second->references++;
+    return found->second;
+}

+ 128 - 0
src/WallpaperEngine/Render/ModelData.h

@@ -0,0 +1,128 @@
+#pragma once
+
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include <glm/vec3.hpp>
+
+namespace WallpaperEngine::Render {
+/**
+ * Script generated geometry (thisScene.createModelData, wallpaper64.exe 2.8.42 engine interface slots 10-12:
+ * sub_14018C720, sub_1401D6400, sub_14018D8B0). Every shape becomes a mesh like the ones of a .mdl, model layers
+ * created with the token draw them (sub_14021AD10)
+ */
+namespace ModelData {
+/** Vertex format bits a script can use (scenescript64 sub_18162FD40) */
+constexpr uint32_t FORMAT_POSITION = 0x1;
+constexpr uint32_t FORMAT_NORMAL = 0x2;
+constexpr uint32_t FORMAT_TANGENT_SIGNED = 0x4;
+constexpr uint32_t FORMAT_UV = 0x8;
+constexpr uint32_t FORMAT_COLOR = 0x8000;
+
+/** The error codes of the engine calls, scenescript64 turns them into these SyntaxError messages */
+enum class Error : int {
+    None = 0,
+    InvalidMaterial = 1,
+    ShaderExpectingMoreVertexData = 2,
+    InconsistentVertexBufferSize = 3,
+    InvalidToken = 4,
+    VertexBufferSizeCannotIncrease = 5,
+    IndexBufferSizeCannotIncrease = 6,
+    NotCreatedAsDynamic = 7,
+    BufferLockFailed = 8,
+    IncorrectIndexBufferType = 9,
+    CannotAddShapes = 10,
+    CannotDeleteShapes = 11,
+    CannotChangeMaterial = 12,
+    CannotChangeVertexFormat = 13,
+};
+
+[[nodiscard]] const char* errorMessage (Error error);
+
+/** One shape of a script configuration (scenescript64's 304 byte shape record, sub_181630720) */
+struct ShapeConfig {
+    std::vector<float> vertices;
+    bool hasVertices = false;
+    std::vector<uint32_t> indices32;
+    std::vector<uint16_t> indices16;
+    bool hasIndices32 = false;
+    bool hasIndices16 = false;
+    /** indexBuffer: null */
+    bool deleteIndices = false;
+    uint32_t format = 0;
+    std::string material;
+    bool vertexDynamic = false;
+    bool indexDynamic = false;
+    /** the shape itself was null (replaceData deletes it) */
+    bool deleteShape = false;
+
+    [[nodiscard]] bool hasIndices () const { return this->hasIndices32 || this->hasIndices16; }
+    [[nodiscard]] uint32_t indexCount () const {
+	return static_cast<uint32_t> (this->hasIndices32 ? this->indices32.size () : this->indices16.size ());
+    }
+};
+
+struct Config {
+    std::vector<ShapeConfig> shapes;
+    std::optional<glm::vec3> boundsMin;
+    std::optional<glm::vec3> boundsMax;
+};
+
+/** A mesh with its GPU buffer record: the 200 byte mesh (sub_1401C2F10) and the 32 byte buffer entry of WE's model */
+struct Mesh {
+    std::string material;
+    uint32_t format = 0;
+    uint32_t stride = 0;
+    /** buffer +18 */
+    bool indexed = false;
+    /** mesh flag 1, 32 bit indices */
+    bool wideIndices = false;
+    /** buffer +16 / +17 */
+    bool vertexDynamic = false;
+    bool indexDynamic = false;
+    /** buffer +8 / +12: float and index counts the buffers were created with */
+    uint32_t vertexFloats = 0;
+    uint32_t indexCount = 0;
+    std::vector<char> vertices;
+    std::vector<char> indices;
+    /** bumped whenever applyData writes into the buffers */
+    uint64_t revision = 0;
+};
+
+struct Model {
+    uint32_t token = 0;
+    /** +560: the script handle and every layer using it hold one */
+    int references = 1;
+    std::vector<Mesh> meshes;
+    glm::vec3 boundsMin = glm::vec3 (0.0f);
+    glm::vec3 boundsMax = glm::vec3 (0.0f);
+    /** bumped when replaceData changes meshes, the layers using it rebuild (the listeners sub_1401D6400 calls) */
+    uint64_t structure = 0;
+};
+
+/** Checks a shape's material against its vertex format: InvalidMaterial / ShaderExpectingMoreVertexData or None */
+using MaterialCheck = std::function<Error (const std::string& material, uint32_t format)>;
+
+class Store {
+public:
+    /** sub_14018C720, 0 and error set on failure */
+    uint32_t create (const Config& config, const MaterialCheck& check, Error& error);
+    /** sub_1401D6400: applyData (replace false) or replaceData */
+    void apply (uint32_t token, const Config& config, bool replace, const MaterialCheck& check, Error& error);
+    /** sub_14018D8B0: drops one reference */
+    void release (uint32_t token);
+    /** A layer takes a reference (sub_14021AD10), nullptr for an unknown token */
+    std::shared_ptr<Model> acquire (int token);
+
+private:
+    std::map<uint32_t, std::shared_ptr<Model>> m_models;
+    /** scene +7224, zeroed with the scene, the first token is 1 */
+    uint32_t m_counter = 0;
+};
+} // namespace ModelData
+} // namespace WallpaperEngine::Render

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 91 - 776
src/WallpaperEngine/Render/Objects/CImage.cpp


+ 24 - 75
src/WallpaperEngine/Render/Objects/CImage.h

@@ -5,10 +5,11 @@
 #include "WallpaperEngine/Render/Objects/Effects/CPass.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 
+#include "WallpaperEngine/Data/JSON.h"
 #include "WallpaperEngine/Render/Shaders/Shader.h"
 
 #include "../TextureProvider.h"
-#include "PuppetPhysics.h"
+#include "PuppetRig.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 
 #include <glm/gtc/quaternion.hpp>
@@ -29,54 +30,6 @@ class CPass;
 } // namespace WallpaperEngine::Render::Objects::Effects
 
 namespace WallpaperEngine::Render::Objects {
-/** A puppet skeleton bone, parsed from the MDLS section of the puppet .mdl */
-struct PuppetBone {
-    std::string name;
-    int parent = -1;
-    /** Local bind-pose transform, relative to the parent bone (identity for a root bone's "world" reference) */
-    glm::mat4 bindLocal { 1.0f };
-    /** Inverse of the bone's bind-pose world transform, derived by walking the parent chain */
-    glm::mat4 inverseBindWorld { 1.0f };
-    PuppetBonePhysics physics {};
-};
-
-/** A single sampled TRS pose for one bone at one point in time, from the MDLA section */
-struct PuppetKeyframe {
-    glm::vec3 position {};
-    glm::vec3 rotation {};
-    glm::vec3 scale { 1.0f };
-    /** rotation as WE blends it, Rz * Ry * Rx */
-    glm::quat orientation { 1.0f, 0.0f, 0.0f, 0.0f };
-};
-
-/** A baked animation clip: one keyframe track per bone, sampled at a fixed rate */
-struct PuppetAnimationClip {
-    /** what animationlayers[].animation refers to */
-    uint64_t id = 0;
-    std::string name;
-    std::string mode;
-    float fps = 30.0f;
-    uint32_t frameCount = 0;
-    /** [boneIndex][sampleIndex], each track has frameCount+1 samples */
-    std::vector<std::vector<PuppetKeyframe>> boneTracks;
-    /** per bone, false when its track flags have bit 0 set: the clip leaves that bone alone */
-    std::vector<bool> boneAnimated;
-};
-
-/** A named point on a puppet's rig that other objects can follow via scene.json's "attachment" field */
-struct PuppetAttachmentPoint {
-    std::string name;
-    int boneIndex = -1;
-    /** Transform of the point relative to its bone, in the same convention as PuppetBone::bindLocal */
-    glm::mat4 localTransform { 1.0f };
-};
-
-/** One of a puppet's animationlayers[] entries, paired with the baked clip it plays */
-struct PuppetActiveAnimation {
-    PuppetAnimationClip clip;
-    const WallpaperEngine::Data::Model::ImageAnimationLayer* layer = nullptr;
-};
-
 class CImage final : public CRenderable, public ScriptableObject {
     friend CObject;
 
@@ -146,7 +99,8 @@ public:
      * local ones relative to the parent bone. Only valid while hasPuppetPose(), for bones below the bone count.
      */
     [[nodiscard]] bool hasPuppetPose () const;
-    [[nodiscard]] const std::vector<PuppetBone>& getPuppetBones () const { return this->m_puppetBones; }
+    [[nodiscard]] const std::vector<PuppetBone>& getPuppetBones () const { return this->m_rig.bones; }
+    [[nodiscard]] PuppetRig& getRig () { return this->m_rig; }
     [[nodiscard]] int findPuppetBone (const std::string& name) const;
     [[nodiscard]] const glm::mat4& getPuppetBoneTransform (int bone) const;
     void setPuppetBoneTransform (int bone, const glm::mat4& transform);
@@ -154,10 +108,29 @@ public:
     void setPuppetLocalBoneTransform (int bone, const glm::mat4& transform);
     void applyPuppetBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees);
     void resetPuppetBonePhysics (int bone);
+    /** The animation layer with this serial for IAnimationLayer scripts, null once destroyed or when a scene layer
+     *  plays no clip (WE never creates such a layer) */
+    [[nodiscard]] PuppetActiveAnimation* findPuppetAnimationLayer (size_t serial);
+    /**
+     * IImageLayer animation layer calls (wallpaper64 2.8.42 sub_14020E910..sub_14020EF80), on the layer list in blend
+     * order. Serials identify layers, nullopt when there is none
+     */
+    [[nodiscard]] size_t getPuppetAnimationLayerCount () const;
+    [[nodiscard]] std::optional<size_t> getPuppetAnimationLayerAt (int64_t index) const;
+    [[nodiscard]] std::optional<size_t> findPuppetAnimationLayerByName (const std::string& name) const;
+    /** animation is a clip name (string) or a layer config (object); config's keys go over it */
+    std::optional<size_t> createPuppetAnimationLayer (
+	const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove
+    );
+    /** removes every layer called name */
+    bool destroyPuppetAnimationLayersByName (const std::string& name);
+    bool destroyPuppetAnimationLayer (size_t serial);
 
 protected:
     void setupPasses ();
     void rebuildActivePasses ();
+    /** Fullscreen layers over the scene buffer keep their buffers at the output's size */
+    [[nodiscard]] bool followsOutputSize () const;
     void addEffectPasses (const ImageEffect& effect);
     [[nodiscard]] bool effectVisibilityChanged () const;
 
@@ -192,7 +165,6 @@ public:
 private:
     bool loadPuppetMesh (const glm::vec2& size);
     void updatePuppetPositionBuffer (const glm::vec2& size);
-    void composePuppetPose (const std::vector<int>& parents, const std::vector<glm::mat4>& locals);
     [[nodiscard]] glm::mat4 puppetObjectWorld () const;
     /** Skins the puppet vertices with the current bone matrices and re-uploads them */
     void updatePuppetSkinning ();
@@ -235,32 +207,9 @@ private:
     std::vector<glm::uvec4> m_puppetBlendIndices = {};
     std::vector<glm::vec4> m_puppetBlendWeights = {};
 
-    std::vector<PuppetBone> m_puppetBones = {};
-    /**
-     * Every animationlayers[] entry that matched a baked clip. Wallpaper Engine puppets almost always
-     * declare several "additive" layers (idle sway, blinking, hand movement, ...) that all play at once
-     * on top of each other rather than one layer replacing another - see updatePuppetSkinning for how
-     * they're composed.
-     */
-    std::vector<PuppetActiveAnimation> m_puppetActiveAnimations = {};
+    PuppetRig m_rig;
     std::vector<GLfloat> m_puppetSkinnedPositions = {};
 
-    std::vector<PuppetAttachmentPoint> m_puppetAttachmentPoints = {};
-    /** Per-bone current animated world transform, in the puppet's own local mesh space; starts out equal
-     *  to the bind pose and is refreshed every frame by updatePuppetPose */
-    std::vector<glm::mat4> m_puppetBoneWorldAnimated = {};
-    /** the bones' local matrices this frame (WE P+784) and their scene matrices (P+832), empty until the first update */
-    std::vector<glm::mat4> m_puppetBoneLocal = {};
-    std::vector<glm::mat4> m_puppetBoneScene = {};
-    /** Bone physics state and last frame's scene transforms, empty until the first frame */
-    std::vector<PuppetBonePhysicsState> m_puppetPhysicsState = {};
-    std::vector<glm::mat4> m_puppetPhysicsPreviousWorld = {};
-    bool m_puppetHasPhysics = false;
-    /** a script wrote bone matrices, the mesh has to be skinned from then on */
-    bool m_puppetPoseScripted = false;
-    /** the pose differs from the bind pose (animation, physics or scripts), so render skins the mesh */
-    bool m_puppetPoseAnimated = false;
-
     glm::mat4 m_modelViewProjectionScreen = {};
     glm::mat4 m_modelViewProjectionPass = {};
     /** effect passes: their buffer's geometry mapped to where the layer is on screen */

+ 612 - 64
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -1,5 +1,8 @@
 #include "CMesh.h"
 
+#include <bit>
+#include <map>
+
 #include <algorithm>
 #include <cstring>
 #include <limits>
@@ -10,10 +13,14 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Objects/CRenderable.h"
 #include "WallpaperEngine/Render/Objects/Effects/CPass.h"
+#include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
+#include "WallpaperEngine/Scripting/ScriptEngine.h"
 
 using namespace WallpaperEngine::Render::Objects;
 using namespace WallpaperEngine::Data::Parsers;
 
+extern float g_Time;
+
 namespace {
 // vertex attributes in the order they're packed, bit in the mesh's format and size in bytes (sub_1401D9860)
 struct VertexComponent {
@@ -22,7 +29,7 @@ struct VertexComponent {
 };
 
 constexpr VertexComponent VERTEX_COMPONENTS[] = {
-    { 0x1, 12 },       { 0x10000, 16 }, { 0x2, 12 },      { 0x4, 16 },      { 0x800000, 16 },
+    { 0x1, 12 },       { 0x10000, 16 }, { 0x2000000, 12 }, { 0x2, 12 },     { 0x4, 16 },      { 0x800000, 16 },
     { 0x1000000, 16 }, { 0x8, 8 },      { 0x10, 12 },     { 0x20, 16 },     { 0x40, 8 },
     { 0x80, 12 },      { 0x100, 16 },   { 0x200, 8 },     { 0x400, 12 },    { 0x800, 16 },
     { 0x1000, 8 },     { 0x2000, 12 },  { 0x4000, 16 },   { 0x20000, 8 },   { 0x40000, 12 },
@@ -31,6 +38,8 @@ constexpr VertexComponent VERTEX_COMPONENTS[] = {
 
 constexpr uint32_t FORMAT_POSITION = 0x1;
 constexpr uint32_t FORMAT_POSITION4 = 0x10000;
+constexpr uint32_t FORMAT_POSITION_C1 = 0x2000000;
+constexpr uint32_t FORMAT_COLOR = 0x8000;
 constexpr uint32_t FORMAT_NORMAL = 0x2;
 constexpr uint32_t FORMAT_TANGENT = 0x4;
 constexpr uint32_t FORMAT_TEXCOORD2 = 0x8;
@@ -40,9 +49,19 @@ constexpr uint32_t FORMAT_BLENDINDICES = 0x800000;
 constexpr uint32_t FORMAT_BLENDWEIGHTS = 0x1000000;
 
 constexpr uint32_t MESH_FLAG_WIDE_INDICES = 0x1;
+} // namespace
 
-struct MdlMesh {
+struct CMesh::MdlMesh {
     std::string material;
+    /** every material name the file lists for this mesh, "skin" picks one */
+    std::vector<std::string> materials;
+    /** position in the file, what the morph targets and clips' morph tracks refer to */
+    uint32_t index = 0;
+    /** MDMP: the deltas' scale (g_MorphWeights[0]) and the targets packed into a texture (sub_1401D7760) */
+    float morphScale = 0.0f;
+    std::shared_ptr<const TextureProvider> morphTexture = nullptr;
+    /** script model data can leave the index buffer out, the vertices are then drawn as a list */
+    bool indexed = true;
     uint32_t flags = 0;
     uint32_t format = 0;
     uint32_t stride = 0;
@@ -50,6 +69,10 @@ struct MdlMesh {
     std::vector<char> indices;
 };
 
+namespace {
+using MdlMesh = CMesh::MdlMesh;
+
+
 class MdlReader {
 public:
     explicit MdlReader (const std::vector<char>& data) : m_data (data) { }
@@ -106,14 +129,73 @@ public:
 
     void skip (size_t count) { this->m_offset += count; }
 
+    [[nodiscard]] size_t offset () const { return this->m_offset; }
+
+    void seek (size_t offset) { this->m_offset = offset; }
+
+    uint16_t u16 () {
+	uint16_t value = 0;
+
+	if (this->has (sizeof (value))) {
+	    std::memcpy (&value, this->m_data.data () + this->m_offset, sizeof (value));
+	}
+
+	this->m_offset += sizeof (value);
+	return value;
+    }
+
 private:
     const std::vector<char>& m_data;
     size_t m_offset = 0;
 };
 
+// the morph texture WE creates per mesh (format 19 = DXGI R16G16B16A16_SNORM, sub_1400D2A20), read by the vertex shader
+// at texel centers
+class MorphTexture final : public TextureProvider {
+public:
+    MorphTexture (int side, const std::vector<uint16_t>& halfs) : m_side (side), m_resolution (side, side, side, side) {
+	GLint previous = 0;
+	glGetIntegerv (GL_TEXTURE_BINDING_2D, &previous);
+	glGenTextures (1, &this->m_texture);
+	glBindTexture (GL_TEXTURE_2D, this->m_texture);
+	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA16_SNORM, side, side, 0, GL_RGBA, GL_SHORT, halfs.data ());
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+	glBindTexture (GL_TEXTURE_2D, previous);
+    }
+
+    ~MorphTexture () override { glDeleteTextures (1, &this->m_texture); }
+
+    [[nodiscard]] GLuint getTextureID (uint32_t) const override { return this->m_texture; }
+    [[nodiscard]] uint32_t getTextureWidth (uint32_t) const override { return this->m_side; }
+    [[nodiscard]] uint32_t getTextureHeight (uint32_t) const override { return this->m_side; }
+    [[nodiscard]] uint32_t getRealWidth () const override { return this->m_side; }
+    [[nodiscard]] uint32_t getRealHeight () const override { return this->m_side; }
+    [[nodiscard]] TextureFormat getFormat () const override { return TextureFormat_UNKNOWN; }
+    [[nodiscard]] uint32_t getFlags () const override { return TextureFlags_ClampUVs; }
+    [[nodiscard]] const std::vector<FrameSharedPtr>& getFrames () const override { return this->m_frames; }
+    [[nodiscard]] const glm::vec4* getResolution () const override { return &this->m_resolution; }
+    [[nodiscard]] bool isAnimated () const override { return false; }
+    bool isReady () const override { return true; }
+    void incrementUsageCount () const override { }
+    void decrementUsageCount () const override { }
+    void update () const override { }
+
+private:
+    GLuint m_texture = GL_NONE;
+    uint32_t m_side;
+    glm::vec4 m_resolution;
+    std::vector<FrameSharedPtr> m_frames = {};
+};
+
 // bounds is the union of every mesh's box (sub_1402617C0), what the cursor hit test uses; files before version 17 have
 // no boxes and leave it empty (min > max)
-std::vector<MdlMesh> readMdlMeshes (const std::vector<char>& data, glm::vec3& boundsMin, glm::vec3& boundsMax) {
+std::vector<MdlMesh> readMdlMeshes (
+    const std::vector<char>& data, glm::vec3& boundsMin, glm::vec3& boundsMax, size_t& end, uint32_t& meshCount,
+    std::vector<uint32_t>& meshFlags
+) {
     MdlReader reader (data);
     const std::string magic = reader.string ();
 
@@ -124,7 +206,7 @@ std::vector<MdlMesh> readMdlMeshes (const std::vector<char>& data, glm::vec3& bo
     const int version = std::stoi (magic.substr (4));
     const uint32_t defaultFormat = reader.u32 ();
     const uint32_t materialsPerMesh = reader.u32 ();
-    const uint32_t meshCount = reader.u32 ();
+    meshCount = reader.u32 ();
     std::vector<MdlMesh> meshes;
 
     boundsMin = glm::vec3 (std::numeric_limits<float>::max ());
@@ -132,15 +214,14 @@ std::vector<MdlMesh> readMdlMeshes (const std::vector<char>& data, glm::vec3& bo
 
     for (uint32_t index = 0; index < meshCount; index++) {
 	MdlMesh mesh;
+	mesh.index = index;
 
 	for (uint32_t material = 0; material < materialsPerMesh; material++) {
-	    const std::string name = reader.string ();
-
-	    if (material == 0) {
-		mesh.material = name;
-	    }
+	    mesh.materials.push_back (reader.string ());
 	}
 
+	mesh.material = mesh.materials.empty () ? std::string () : mesh.materials.front ();
+
 	mesh.format = defaultFormat;
 
 	if (version >= 4) {
@@ -176,6 +257,7 @@ std::vector<MdlMesh> readMdlMeshes (const std::vector<char>& data, glm::vec3& bo
 	    }
 	}
 
+	meshFlags.push_back (mesh.flags);
 	mesh.vertices = reader.bytes (reader.u32 ());
 	mesh.indices = reader.bytes (reader.u32 ());
 
@@ -187,29 +269,29 @@ std::vector<MdlMesh> readMdlMeshes (const std::vector<char>& data, glm::vec3& bo
 	    );
 	}
 
-	// version 23 files (the 2.4 engine only reads up to 19) close every mesh with a small block: two flag bytes, an
-	// optional sized blob and another sized blob. Static meshes write six zero bytes, puppets fill it
-	if (version >= 23) {
-	    const uint8_t first = reader.u8 ();
-	    const uint8_t second = reader.u8 ();
-
-	    if (first != 0) {
-		if (usable) {
-		    meshes.push_back (std::move (mesh));
-		}
-
-		if (index + 1 < meshCount) {
-		    sLog.error ("Unknown mesh trailer in model, only the first ", index + 1, " meshes are read");
-		}
-
-		break;
+	// sub_140261880 from version 21: a flag byte with a u32 and a sized blob, a flag byte with a sized blob (puppets'
+	// per bone index ranges); from 23 a count of records (u64, string, u32 flags, two u32 counted u32 lists)
+	if (version >= 21) {
+	    if (reader.u8 () != 0) {
+		reader.u32 ();
+		reader.skip (reader.u32 ());
 	    }
 
-	    if (second != 0) {
+	    if (reader.u8 () != 0) {
 		reader.skip (reader.u32 ());
 	    }
+	}
 
-	    reader.skip (reader.u32 ());
+	if (version >= 23) {
+	    const uint32_t records = reader.u32 ();
+
+	    for (uint32_t record = 0; record < records && reader.has (1); record++) {
+		reader.skip (sizeof (uint64_t));
+		reader.string ();
+		reader.u32 ();
+		reader.skip (sizeof (uint32_t) * reader.u32 ());
+		reader.skip (sizeof (uint32_t) * reader.u32 ());
+	    }
 	}
 
 	if (usable) {
@@ -217,15 +299,113 @@ std::vector<MdlMesh> readMdlMeshes (const std::vector<char>& data, glm::vec3& bo
 	}
     }
 
+    end = reader.offset ();
     return meshes;
 }
+
+// MDMP (sub_140261880): per mesh of the file a u16 target count, and with targets the deltas' scale, the vertex count
+// and per target a u64, a name and blobs of 16 bit signed normalized values: positions (3 per vertex), normals with
+// mesh flag 0x400, more with 0x800/0x1000, four values with 0x2000. sub_1401D7760 packs every target's deltas one after
+// another into a square texture: positions only, or positions and normals interleaved per vertex; with 0x800 it stays
+// empty. The shader scales them by g_MorphWeights[0]
+void loadMorphTargets (
+    const std::vector<char>& data, size_t section, const std::vector<uint32_t>& meshFlags, std::vector<MdlMesh>& meshes
+) {
+    MdlReader reader (data);
+    reader.seek (section);
+    reader.string ();
+    reader.u32 ();
+
+    for (uint32_t index = 0; index < meshFlags.size () && reader.has (2); index++) {
+	const uint16_t targets = reader.u16 ();
+
+	if (targets == 0) {
+	    continue;
+	}
+
+	const uint32_t flags = meshFlags[index];
+	const float scale = reader.f32 ();
+	reader.u32 ();
+
+	std::vector<std::vector<char>> positions;
+	std::vector<std::vector<char>> normals;
+
+	for (uint16_t target = 0; target < targets; target++) {
+	    reader.skip (sizeof (uint64_t));
+	    reader.string ();
+	    positions.push_back (reader.bytes (reader.u32 ()));
+
+	    if (flags & 0x400) {
+		normals.push_back (reader.bytes (reader.u32 ()));
+	    }
+	    if (flags & 0x800) {
+		reader.skip (reader.u32 ());
+	    }
+	    if (flags & 0x1000) {
+		reader.skip (reader.u32 ());
+	    }
+	    if (flags & 0x2000) {
+		reader.skip (sizeof (uint32_t) * 4);
+	    }
+	}
+
+	const auto mesh = std::ranges::find (meshes, index, &MdlMesh::index);
+
+	if (mesh == meshes.end () || mesh->stride == 0) {
+	    continue;
+	}
+
+	const uint32_t vertices = static_cast<uint32_t> (mesh->vertices.size () / mesh->stride);
+	const uint32_t perTarget = vertices * targets;
+	uint32_t units = (flags & 0x400) ? perTarget * 2 : perTarget;
+
+	if (flags & 0x800) {
+	    units += perTarget;
+	}
+
+	const uint32_t texels = (3 * units) / 4 + ((3 * units) % 4 != 0 ? 1 : 0);
+	auto side = static_cast<int> (std::sqrt (static_cast<float> (texels)));
+
+	if (static_cast<uint32_t> (side * side) < texels) {
+	    side++;
+	}
+
+	std::vector<uint16_t> halfs (static_cast<size_t> (side) * side * 4, 0);
+	size_t out = 0;
+
+	for (uint16_t target = 0; target < targets && (flags & 0x800) == 0; target++) {
+	    const auto* position = reinterpret_cast<const uint16_t*> (positions[target].data ());
+	    const size_t available = positions[target].size () / sizeof (uint16_t);
+
+	    if ((flags & 0x400) == 0) {
+		std::copy_n (position, std::min<size_t> (available, 3 * vertices), halfs.begin () + static_cast<long> (out));
+		out += 3 * vertices;
+		continue;
+	    }
+
+	    const auto* normal = reinterpret_cast<const uint16_t*> (normals[target].data ());
+	    const size_t normalsAvailable = normals[target].size () / sizeof (uint16_t);
+
+	    for (size_t i = 0; i + 2 < 3 * vertices && i + 2 < available && i + 2 < normalsAvailable; i += 3) {
+		std::copy_n (position + i, 3, halfs.begin () + static_cast<long> (out + 2 * i));
+		std::copy_n (normal + i, 3, halfs.begin () + static_cast<long> (out + 2 * i + 3));
+	    }
+
+	    out += 6 * vertices;
+	}
+
+	mesh->morphScale = scale;
+	mesh->morphTexture = std::make_shared<MorphTexture> (side, halfs);
+    }
+}
 } // namespace
 
 class CMesh::Part final : public CRenderable {
 public:
-    Part (CMesh& owner, const Material& material, MdlMesh mesh) :
+    Part (CMesh& owner, const Material& material, MdlMesh mesh, const ModelData::Mesh* source = nullptr) :
 	CObject (owner.getScene (), owner.getObject ()), CRenderable (owner.getScene (), owner.getObject (), material),
-	m_owner (owner), m_mesh (std::move (mesh)) { }
+	m_owner (owner), m_mesh (std::move (mesh)), m_source (source),
+	m_sourceRevision (source != nullptr ? source->revision : 0) { }
 
     ~Part () override {
 	for (const auto* pass : this->m_passes) {
@@ -236,6 +416,10 @@ public:
 	    glDeleteVertexArrays (1, &vao);
 	}
 
+	if (this->m_casterVAO != GL_NONE) {
+	    glDeleteVertexArrays (1, &this->m_casterVAO);
+	}
+
 	glDeleteBuffers (1, &this->m_vbo);
 	glDeleteBuffers (1, &this->m_ebo);
     }
@@ -254,8 +438,11 @@ public:
 	glBindBuffer (GL_ARRAY_BUFFER, this->m_vbo);
 	glBufferData (
 	    GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (this->m_mesh.vertices.size ()), this->m_mesh.vertices.data (),
-	    GL_STATIC_DRAW
+	    this->m_source != nullptr && this->m_source->vertexDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW
 	);
+	this->m_vertexCount = this->m_mesh.stride != 0
+	    ? static_cast<GLsizei> (this->m_mesh.vertices.size () / this->m_mesh.stride)
+	    : 0;
 
 	GLint previousVAO = 0;
 	glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVAO);
@@ -269,13 +456,36 @@ public:
 
 	this->m_fboProvider = std::make_shared<FBOProvider> (this);
 
+	// sub_140224C70: SKINNING when the model has bones and the mesh blend indices, BONECOUNT with it
+	this->m_skinned = this->m_owner.getBoneCount () > 0 && (this->m_mesh.format & FORMAT_BLENDINDICES) != 0;
+	this->m_skinning.combos = {
+	    { "SKINNING", this->m_skinned ? 1 : 0 },
+	    { "BONECOUNT", this->m_owner.getBoneCount () },
+	};
+
+	if (this->m_mesh.morphTexture != nullptr) {
+	    this->m_skinning.combos["MORPHING"] = 1;
+	}
+
+	if (this->m_mesh.flags & 0x400) {
+	    this->m_skinning.combos["MORPHING_NORMALS"] = 1;
+	}
+
 	for (const auto& materialPass : this->m_material.passes) {
-	    auto* pass = new Effects::CPass (
-		*this, this->m_fboProvider, *materialPass, std::nullopt, std::nullopt, std::nullopt
-	    );
+	    std::optional<std::reference_wrapper<const ImageEffectPassOverride>> skinning = std::nullopt;
+
+	    if (this->m_owner.getBoneCount () > 0) {
+		skinning = std::cref (this->m_skinning);
+	    }
+
+	    auto* pass = new Effects::CPass (*this, this->m_fboProvider, *materialPass, skinning, std::nullopt, std::nullopt);
 
 	    pass->setDestination (this->getScene ().getFBO ());
 	    pass->setInput (this->getTexture ());
+
+	    if (this->m_mesh.morphTexture != nullptr && this->m_owner.getBoneCount () > 0) {
+		pass->setTexture (5, this->m_mesh.morphTexture);
+	    }
 	    pass->setModelMatrix (&this->m_owner.getModelMatrix ());
 	    pass->setViewProjectionMatrix (&this->m_owner.getViewProjectionMatrix ());
 	    pass->setModelViewProjectionMatrix (&this->m_owner.getModelViewProjectionMatrix ());
@@ -296,10 +506,17 @@ public:
 		[this, vao] () {
 		    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &this->m_previousVAO);
 		    glBindVertexArray (vao);
+		    this->uploadBones ();
+
+		    if (this->m_mesh.morphTexture != nullptr && this->m_owner.getBoneCount () > 0) {
+			GLint program = 0;
+			glGetIntegerv (GL_CURRENT_PROGRAM, &program);
+			this->uploadMorphWeights (program);
+		    }
 		    // WE is D3D: front faces wind clockwise on screen, and the scene buffer is drawn upside down here
 		    glFrontFace (GL_CW);
 		},
-		[this] () { glDrawElements (GL_TRIANGLES, this->m_indexCount, this->m_indexType, nullptr); },
+		[this] () { this->draw (); },
 		[this] () {
 		    glFrontFace (GL_CCW);
 		    glBindVertexArray (this->m_previousVAO);
@@ -315,7 +532,8 @@ public:
 	    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_ebo);
 	    glBufferData (
 		GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (this->m_mesh.indices.size ()),
-		this->m_mesh.indices.data (), GL_STATIC_DRAW
+		this->m_mesh.indices.data (),
+		this->m_source != nullptr && this->m_source->indexDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW
 	    );
 	}
 
@@ -327,11 +545,48 @@ public:
     }
 
     void render () override {
+	// applyData wrote new data into the model's buffers
+	if (this->m_source != nullptr && this->m_source->revision != this->m_sourceRevision) {
+	    this->m_sourceRevision = this->m_source->revision;
+	    this->upload ();
+	}
+
 	for (auto* pass : this->m_passes) {
 	    pass->render ();
 	}
     }
 
+    void renderShadowCaster (const GLuint program, const GLint alphaTest) {
+	const BlendingMode blending
+	    = this->m_material.passes.empty () ? BlendingMode_Normal : this->m_material.passes.front ()->blending;
+
+	if (blending != BlendingMode_Normal && blending != BlendingMode_AlphaToCoverage) {
+	    return;
+	}
+
+	if (this->m_casterVAO == GL_NONE) {
+	    glGenVertexArrays (1, &this->m_casterVAO);
+	    glBindVertexArray (this->m_casterVAO);
+	    glBindBuffer (GL_ARRAY_BUFFER, this->m_vbo);
+	    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_ebo);
+	    this->bindAttributes (program);
+	}
+
+	const bool alphaToCoverage = blending == BlendingMode_AlphaToCoverage && this->getTexture () != nullptr;
+
+	glUniform1i (alphaTest, alphaToCoverage ? 1 : 0);
+	glUniform1i (glGetUniformLocation (program, "u_Skinning"), this->m_skinned ? 1 : 0);
+	this->uploadBones ();
+
+	if (alphaToCoverage) {
+	    glActiveTexture (GL_TEXTURE0);
+	    glBindTexture (GL_TEXTURE_2D, this->getTexture ()->getTextureID (0));
+	}
+
+	glBindVertexArray (this->m_casterVAO);
+	this->draw ();
+    }
+
     [[nodiscard]] const float& getBrightness () const override { return this->m_one; }
     [[nodiscard]] const float& getUserAlpha () const override { return this->m_one; }
     [[nodiscard]] const float& getAlpha () const override { return this->m_one; }
@@ -340,6 +595,84 @@ public:
     [[nodiscard]] const glm::vec3& getCompositeColor () const override { return this->m_white; }
 
 private:
+    void uploadBones () {
+	if (!this->m_skinned) {
+	    return;
+	}
+
+	GLint program = 0;
+	glGetIntegerv (GL_CURRENT_PROGRAM, &program);
+
+	auto location = this->m_boneLocations.find (program);
+
+	if (location == this->m_boneLocations.end ()) {
+	    location = this->m_boneLocations.emplace (program, glGetUniformLocation (program, "g_Bones")).first;
+	}
+
+	if (location->second >= 0) {
+	    glUniformMatrix4x3fv (
+		location->second, this->m_owner.getBoneCount (), GL_FALSE, this->m_owner.getBones ().data ()
+	    );
+	}
+    }
+
+    // sub_1402222A0: the mesh's active targets in index order (at most 11), sorted by weight from the largest down
+    // (stable), g_MorphOffsets = (count, vertex count * target, ...), g_MorphWeights = (the deltas' scale, weights...)
+    void uploadMorphWeights (GLint program) const {
+	std::vector<std::pair<uint32_t, float>> active;
+	const auto& morphs = this->m_owner.getRig ().morphWeights;
+
+	if (this->m_mesh.index < morphs.size ()) {
+	    const auto& state = morphs[this->m_mesh.index];
+
+	    for (uint32_t target = 0; target < state.weights.size () && target < 64 && active.size () < 11; target++) {
+		if (state.active & (uint64_t (1) << target)) {
+		    active.emplace_back (target, state.weights[target]);
+		}
+	    }
+	}
+
+	std::ranges::stable_sort (active, std::ranges::greater {}, &std::pair<uint32_t, float>::second);
+
+	GLuint offsets[12] = {};
+	GLfloat weights[12] = {};
+	offsets[0] = static_cast<GLuint> (active.size ());
+	weights[0] = this->m_mesh.morphScale;
+
+	for (size_t i = 0; i < active.size (); i++) {
+	    offsets[1 + i] = this->m_owner.getMorphVertexCount () * active[i].first;
+	    weights[1 + i] = active[i].second;
+	}
+
+	glUniform1uiv (glGetUniformLocation (program, "g_MorphOffsets"), 12, offsets);
+	glUniform1fv (glGetUniformLocation (program, "g_MorphWeights"), 12, weights);
+    }
+
+    void draw () const {
+	if (this->m_mesh.indexed) {
+	    glDrawElements (GL_TRIANGLES, this->m_indexCount, this->m_indexType, nullptr);
+	} else {
+	    glDrawArrays (GL_TRIANGLES, 0, this->m_vertexCount);
+	}
+    }
+
+    void upload () const {
+	const auto& vertices = this->m_source->vertices;
+	const auto& indices = this->m_source->indices;
+
+	glBindBuffer (GL_ARRAY_BUFFER, this->m_vbo);
+	glBufferSubData (GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr> (vertices.size ()), vertices.data ());
+
+	if (this->m_mesh.indexed && !this->m_vaos.empty ()) {
+	    GLint previousVAO = 0;
+
+	    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVAO);
+	    glBindVertexArray (this->m_vaos.front ());
+	    glBufferSubData (GL_ELEMENT_ARRAY_BUFFER, 0, static_cast<GLsizeiptr> (indices.size ()), indices.data ());
+	    glBindVertexArray (previousVAO);
+	}
+    }
+
     void bindAttributes (const GLuint program) const {
 	const auto stride = static_cast<GLsizei> (this->m_mesh.stride);
 	uint32_t offset = 0;
@@ -357,6 +690,12 @@ private:
 		case FORMAT_POSITION4:
 		    name = "a_Position";
 		    break;
+		case FORMAT_POSITION_C1:
+		    name = "a_PositionC1";
+		    break;
+		case FORMAT_COLOR:
+		    name = "a_Color";
+		    break;
 		case FORMAT_NORMAL:
 		    name = "a_Normal";
 		    break;
@@ -398,9 +737,18 @@ private:
 
     CMesh& m_owner;
     MdlMesh m_mesh;
+    /** the SKINNING/BONECOUNT combos of models with a skeleton */
+    ImageEffectPassOverride m_skinning {};
+    bool m_skinned = false;
+    std::map<GLint, GLint> m_boneLocations = {};
+    /** script model data this part draws, re-uploaded when applyData changes it */
+    const ModelData::Mesh* m_source = nullptr;
+    uint64_t m_sourceRevision = 0;
+    GLsizei m_vertexCount = 0;
     std::shared_ptr<FBOProvider> m_fboProvider = nullptr;
     std::vector<Effects::CPass*> m_passes = {};
     std::vector<GLuint> m_vaos = {};
+    GLuint m_casterVAO = GL_NONE;
     GLuint m_vbo = GL_NONE;
     GLuint m_ebo = GL_NONE;
     GLint m_previousVAO = 0;
@@ -412,49 +760,104 @@ private:
 };
 
 CMesh::CMesh (Wallpapers::CScene& scene, const Mesh& mesh) :
-    CObject (scene, mesh), ScriptableObject (scene, mesh), m_mesh (mesh) { }
+    CObject (scene, mesh), ScriptableObject (scene, mesh), m_mesh (mesh) {
+    // animation layer property scripts run with the layer as thisObject, like an image's (sub_1402230C0)
+    for (size_t layerIndex = 0; layerIndex < mesh.animationLayers.size (); layerIndex++) {
+	const auto& layer = mesh.animationLayers[layerIndex];
+	const std::string prefix = "animationlayers[" + std::to_string (layerIndex) + "].";
+
+	for (const auto& [name, setting] :
+	     { std::pair { "visible", &layer->visible }, std::pair { "rate", &layer->rate },
+	       std::pair { "blend", &layer->blend } }) {
+	    if (*setting == nullptr) {
+		continue;
+	    }
+
+	    this->registerProperty (prefix + name, *(*setting)->value);
+	    scene.getScriptEngine ().setThisObjectFactory (
+		this->getProperties ().at (prefix + name).key,
+		[this, layerIndex] (Scripting::ScriptEngine& engine) {
+		    return Scripting::Adapters::makeAnimationLayerHandle (engine, *this, layerIndex);
+		}
+	    );
+	}
+    }
+}
 
-CMesh::~CMesh () = default;
+CMesh::~CMesh () {
+    this->m_parts.clear ();
+
+    if (this->m_modelData != nullptr) {
+	this->getScene ().releaseModelData (this->m_modelData->token);
+    }
+}
 
 void CMesh::setup () {
+    // sub_14021AD10: a number is a script's model data, which the layer keeps a reference to
+    if (this->m_mesh.modelData.has_value ()) {
+	this->m_modelData = this->getScene ().acquireModelData (*this->m_mesh.modelData);
+
+	if (this->m_modelData != nullptr) {
+	    this->buildModelDataParts ();
+	}
+
+	this->updateMatrices ();
+	return;
+    }
+
+    // "model" given as an object makes a model layer without a model
+    if (this->m_mesh.model.empty ()) {
+	this->updateMatrices ();
+	return;
+    }
+
     const auto& project = this->getScene ().getScene ().project;
     const auto stream = project.assetLocator->read (this->m_mesh.model);
     const std::vector<char> data { std::istreambuf_iterator<char> (*stream), std::istreambuf_iterator<char> () };
 
-    for (auto& mesh : readMdlMeshes (data, this->m_boundsMin, this->m_boundsMax)) {
-	auto material = MaterialParser::load (project, mesh.material);
+    size_t end = 0;
+    uint32_t meshCount = 0;
+    std::vector<uint32_t> meshFlags;
+    auto meshes = readMdlMeshes (data, this->m_boundsMin, this->m_boundsMax, end, meshCount, meshFlags);
 
-	if (material == nullptr || material->passes.empty ()) {
-	    sLog.error ("Skipping a mesh of ", this->m_mesh.model, " without a usable material ", mesh.material);
-	    continue;
+    // version 13+ files name the next section after the last mesh, a skeleton (MDLS) and its clips are loaded the same
+    // way as a puppet's (sub_140261880)
+    if (end + 4 <= data.size () && std::memcmp (data.data () + end, "MDLS", 4) == 0) {
+	try {
+	    this->m_rig.load (data, end, meshCount, this->m_mesh.model);
+	    this->m_rig.addSceneLayers (this->m_mesh.animationLayers);
+	} catch (const std::exception& e) {
+	    sLog.error ("Could not load the skeleton of ", this->m_mesh.model, ": ", e.what ());
+	    this->m_rig.clear ();
 	}
+    }
 
-	// a model that doesn't say otherwise is solid, the church in 3777414605 relies on it
-	for (const auto& pass : material->passes) {
-	    if (pass->depthtest == DepthtestMode_Unknown) {
-		pass->depthtest = DepthtestMode_Enabled;
-	    }
-
-	    if (pass->depthwrite == DepthwriteMode_Unknown) {
-		pass->depthwrite = DepthwriteMode_Enabled;
-	    }
+    // sub_140224C70: BONECOUNT is the bone count rounded up to a power of two, at least 16 and at most 128. Morph
+    // targets only take effect on models with bones, their offsets all use the vertex count of the last mesh with a
+    // morph texture (model +736)
+    if (!this->m_rig.bones.empty ()) {
+	if (this->m_rig.getMorphSection () != 0) {
+	    loadMorphTargets (data, this->m_rig.getMorphSection (), meshFlags, meshes);
+	}
 
-	    if (pass->cullmode == CullingMode_Unknown) {
-		pass->cullmode = CullingMode_Normal;
+	for (const auto& mesh : meshes) {
+	    if (mesh.morphTexture != nullptr) {
+		this->m_morphVertexCount = static_cast<uint32_t> (mesh.vertices.size () / mesh.stride);
 	    }
 	}
 
-	auto part = std::make_unique<Part> (*this, *material, std::move (mesh));
-	this->m_materials.push_back (std::move (material));
+	const auto bones = static_cast<uint32_t> (std::max<size_t> (this->m_rig.bones.size (), 16));
+	this->m_boneCount = static_cast<int> (std::min<uint32_t> (std::bit_ceil (bones), 128));
+	this->updateBones ();
+    }
 
-	try {
-	    part->setup ();
-	} catch (const std::exception& e) {
-	    sLog.error ("Cannot set up a mesh of ", this->m_mesh.model, ": ", e.what ());
-	    continue;
+    for (auto& mesh : meshes) {
+	// "skin" picks one of the mesh's material names, the last one when it's past them
+	if (!mesh.materials.empty ()) {
+	    mesh.material = mesh.materials[std::min<size_t> (this->m_mesh.skin, mesh.materials.size () - 1)];
 	}
 
-	this->m_parts.push_back (std::move (part));
+	this->addPart (std::move (mesh), nullptr);
     }
 
     if (this->m_parts.empty ()) {
@@ -464,11 +867,115 @@ void CMesh::setup () {
     this->updateMatrices ();
 }
 
+void CMesh::buildModelDataParts () {
+    this->m_parts.clear ();
+    this->m_materials.clear ();
+    this->m_modelStructure = this->m_modelData->structure;
+    this->m_boundsMin = this->m_modelData->boundsMin;
+    this->m_boundsMax = this->m_modelData->boundsMax;
+
+    for (const auto& source : this->m_modelData->meshes) {
+	if (source.stride == 0 || source.vertices.empty ()) {
+	    continue;
+	}
+
+	MdlMesh mesh;
+
+	mesh.material = source.material;
+	mesh.indexed = source.indexed;
+	mesh.flags = source.wideIndices ? MESH_FLAG_WIDE_INDICES : 0;
+	mesh.format = source.format;
+	mesh.stride = source.stride;
+	mesh.vertices = source.vertices;
+	mesh.indices = source.indices;
+
+	this->addPart (std::move (mesh), &source);
+    }
+}
+
+void CMesh::addPart (MdlMesh mesh, const ModelData::Mesh* source) {
+    const auto& project = this->getScene ().getScene ().project;
+    const std::string name = source != nullptr ? "script model data" : this->m_mesh.model;
+    auto material = MaterialParser::load (project, mesh.material);
+
+    if (material == nullptr || material->passes.empty ()) {
+	sLog.error ("Skipping a mesh of ", name, " without a usable material ", mesh.material);
+	return;
+    }
+
+    // a model that doesn't say otherwise is solid, the church in 3777414605 relies on it
+    for (const auto& pass : material->passes) {
+	if (pass->depthtest == DepthtestMode_Unknown) {
+	    pass->depthtest = DepthtestMode_Enabled;
+	}
+
+	if (pass->depthwrite == DepthwriteMode_Unknown) {
+	    pass->depthwrite = DepthwriteMode_Enabled;
+	}
+
+	if (pass->cullmode == CullingMode_Unknown) {
+	    pass->cullmode = CullingMode_Normal;
+	}
+    }
+
+    auto part = std::make_unique<Part> (*this, *material, std::move (mesh), source);
+    this->m_materials.push_back (std::move (material));
+
+    try {
+	part->setup ();
+    } catch (const std::exception& e) {
+	sLog.error ("Cannot set up a mesh of ", name, ": ", e.what ());
+	return;
+    }
+
+    this->m_parts.push_back (std::move (part));
+}
+
+void CMesh::updateAnimation () {
+    if (this->m_rig.bones.empty ()) {
+	return;
+    }
+
+    // sub_14021C480 leaves hidden models alone, their layer clocks don't run either
+    if (!this->m_mesh.groupVisible->value->getBool () || this->getScene ().isHiddenByAncestor (*this)) {
+	this->m_rig.clockTime = g_Time;
+	return;
+    }
+
+    this->m_rig.updatePose (this->getScene ().objectWorldMatrix (this->m_mesh));
+    this->m_rig.finishEndedLayers ([this] (size_t serial) {
+	this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
+    });
+    this->updateBones ();
+}
+
+void CMesh::updateBones () {
+    // g_Bones is a float4x3 array (its own constant buffer in WE, sub_1402222A0): the first three columns of every skin
+    // matrix, model space bone times inverse bind
+    const auto skin = this->m_rig.skinMatrices ();
+    const size_t count = std::min<size_t> (skin.size (), static_cast<size_t> (this->m_boneCount));
+
+    this->m_bones.assign (static_cast<size_t> (this->m_boneCount) * 12, 0.0f);
+
+    for (size_t bone = 0; bone < count; bone++) {
+	for (int column = 0; column < 4; column++) {
+	    for (int row = 0; row < 3; row++) {
+		this->m_bones[bone * 12 + column * 3 + row] = skin[bone][column][row];
+	    }
+	}
+    }
+}
+
 void CMesh::render () {
     if (!this->m_mesh.groupVisible->value->getBool ()) {
 	return;
     }
 
+    // replaceData changed the shapes (the model data's listeners, sub_1401D6400)
+    if (this->m_modelData != nullptr && this->m_modelData->structure != this->m_modelStructure) {
+	this->buildModelDataParts ();
+    }
+
     this->updateMatrices ();
 
     for (const auto& part : this->m_parts) {
@@ -498,9 +1005,50 @@ void CMesh::updateMatrices () {
     if (camera.isPerspective ()) {
 	this->m_eyePosition = camera.getEye ();
     } else {
-	// 2D scenes keep their camera 2000 units out (end of sub_1401891A0), same as particles see it
-	const glm::vec2 eye = scene.getCameraEye ();
-	this->m_eyePosition = glm::vec3 (eye.x, -eye.y, 2000.0f);
+	// the renderer eye like every pass gets it, in 2D scenes 2000 units out over the scene center plus the camera
+	// (end of sub_1401891A0)
+	this->m_eyePosition = scene.getFog ().eyeWorld;
+    }
+}
+
+void CMesh::renderShadowCaster (
+    const GLuint program, const GLint modelViewProjection, const GLint alphaTest, const glm::mat4& viewProjection,
+    const glm::mat4& cullViewProjection
+) {
+    this->updateMatrices ();
+
+    // perspective scenes (renderer +284 & 1) skip a shadow viewport whose frustum (sub_1401849E0: x, y and z against
+    // w, planes normalized) has the model's bounding sphere fully outside one plane. The sphere spans the world
+    // corners of the .mdl bounds (sub_1402222A0)
+    if (this->getScene ().getCamera ().isPerspective () && this->m_boundsMax.x > this->m_boundsMin.x) {
+	const glm::vec3 low (this->m_modelMatrix * glm::vec4 (this->m_boundsMin, 1.0f));
+	const glm::vec3 high (this->m_modelMatrix * glm::vec4 (this->m_boundsMax, 1.0f));
+	const glm::vec3 half = (high - low) * 0.5f;
+	const glm::vec3 center = low + half;
+	const float radius = glm::length (half);
+	const glm::mat4& m = cullViewProjection;
+	const glm::vec4 rows[4] = {
+	    { m[0][0], m[1][0], m[2][0], m[3][0] },
+	    { m[0][1], m[1][1], m[2][1], m[3][1] },
+	    { m[0][2], m[1][2], m[2][2], m[3][2] },
+	    { m[0][3], m[1][3], m[2][3], m[3][3] },
+	};
+
+	for (const glm::vec4& plane : { rows[3] + rows[0], rows[3] - rows[0], rows[3] + rows[1], rows[3] - rows[1],
+					rows[3] + rows[2], rows[3] - rows[2] }) {
+	    const glm::vec4 normalized = plane / glm::length (glm::vec3 (plane));
+
+	    if (-radius > glm::dot (glm::vec3 (normalized), center) + normalized.w) {
+		return;
+	    }
+	}
+    }
+
+    const glm::mat4 matrix = viewProjection * this->m_modelMatrix;
+    glUniformMatrix4fv (modelViewProjection, 1, GL_FALSE, &matrix[0][0]);
+
+    for (const auto& part : this->m_parts) {
+	part->renderShadowCaster (program, alphaTest);
     }
 }
 

+ 41 - 2
src/WallpaperEngine/Render/Objects/CMesh.h

@@ -1,7 +1,11 @@
 #pragma once
 
+#include "PuppetRig.h"
+#include "WallpaperEngine/Render/ModelData.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 
+#include <GL/glew.h>
+
 #include <glm/mat3x3.hpp>
 #include <glm/mat4x4.hpp>
 #include <optional>
@@ -10,8 +14,9 @@ namespace WallpaperEngine::Render::Objects {
 using namespace WallpaperEngine::Data::Model;
 
 /**
- * A static 3D model ("model" objects), in 3D scenes or placed in a 2D one. Every mesh in the .mdl has its own material
- * and is drawn straight into the scene buffer with depth testing, the bind pose only (no skinning or animation yet)
+ * A 3D model ("model" objects), in 3D scenes or placed in a 2D one. Every mesh in the .mdl has its own material and is
+ * drawn straight into the scene buffer with depth testing. Models with a skeleton play their animation layers like
+ * puppets and are skinned on the GPU (SKINNING, g_Bones)
  */
 class CMesh final : public Scripting::ScriptableObject {
 public:
@@ -22,24 +27,52 @@ public:
     void render () override;
 
     [[nodiscard]] const Mesh& getMesh () const;
+    /** The skeleton's pose for this frame (sub_14021C480), before cursor events and scripts like every object update */
+    void updateAnimation ();
+    [[nodiscard]] PuppetRig& getRig () { return this->m_rig; }
+    [[nodiscard]] const PuppetRig& getRig () const { return this->m_rig; }
+    /** model +736: what g_MorphOffsets multiplies the target indices with */
+    [[nodiscard]] uint32_t getMorphVertexCount () const { return this->m_morphVertexCount; }
+    /** BONECOUNT, 0 without a skeleton */
+    [[nodiscard]] int getBoneCount () const { return this->m_boneCount; }
+    /** g_Bones: getBoneCount () float4x3 matrices, column major */
+    [[nodiscard]] const std::vector<float>& getBones () const { return this->m_bones; }
     [[nodiscard]] const glm::mat4& getModelMatrix () const;
     [[nodiscard]] const glm::mat3& getNormalMatrix () const;
     [[nodiscard]] const glm::mat4& getViewProjectionMatrix () const;
     [[nodiscard]] const glm::mat4& getModelViewProjectionMatrix () const;
     [[nodiscard]] const glm::mat4& getModelViewProjectionMatrixInverse () const;
     [[nodiscard]] const glm::vec3& getEyePosition () const;
+    /** The .mdl's bounds in model space (MDLV 17+), max not above min when the file has none */
+    [[nodiscard]] const glm::vec3& getBoundsMin () const { return this->m_boundsMin; }
+    [[nodiscard]] const glm::vec3& getBoundsMax () const { return this->m_boundsMax; }
     /** Cursor hit test (sub_140185520): the line through the cursor against the model's bounds in model space, a box
      *  from 0 to the bounds' extent (WE doesn't offset it by the minimum). ndc is in the scene buffer's clip space */
     [[nodiscard]] bool hitTest (const glm::vec2& ndc) const;
     /** A cursor event's localPosition: where the line enters that box, relative to the box's center, zero on a miss */
     [[nodiscard]] glm::vec3 cursorLocalPosition (const glm::vec2& ndc) const;
+    /**
+     * Draws the meshes whose material blends "normal" or "alphatocoverage" into the bound shadow map through
+     * viewProjection (GL clip space) with the caster program, the others don't cast (sub_1402222A0 in mode 0).
+     * cullViewProjection is the same viewport in WE's clip space, what its frustum culling tests against
+     */
+    void renderShadowCaster (
+	GLuint program, GLint modelViewProjection, GLint alphaTest, const glm::mat4& viewProjection,
+	const glm::mat4& cullViewProjection
+    );
 
     class Part;
+    /** One mesh of a .mdl or of script model data */
+    struct MdlMesh;
 
 private:
+    void addPart (MdlMesh mesh, const ModelData::Mesh* source);
+    void buildModelDataParts ();
+
     /** The model space point where the line through ndc enters the hit box, see hitTest */
     [[nodiscard]] std::optional<glm::vec3> boxEntry (const glm::vec2& ndc) const;
     void updateMatrices ();
+    void updateBones ();
 
     const Mesh& m_mesh;
     std::vector<MaterialUniquePtr> m_materials;
@@ -53,5 +86,11 @@ private:
     glm::vec3 m_eyePosition = glm::vec3 (0.0f);
     glm::vec3 m_boundsMin = glm::vec3 (0.0f);
     glm::vec3 m_boundsMax = glm::vec3 (0.0f);
+    std::shared_ptr<ModelData::Model> m_modelData = nullptr;
+    PuppetRig m_rig;
+    int m_boneCount = 0;
+    uint32_t m_morphVertexCount = 0;
+    std::vector<float> m_bones = {};
+    uint64_t m_modelStructure = 0;
 };
 } // namespace WallpaperEngine::Render::Objects

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 504 - 265
src/WallpaperEngine/Render/Objects/CParticle.cpp


+ 75 - 30
src/WallpaperEngine/Render/Objects/CParticle.h

@@ -6,6 +6,7 @@
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 
+#include <deque>
 #include <functional>
 #include <glm/mat4x4.hpp>
 #include <glm/vec3.hpp>
@@ -20,6 +21,7 @@ using namespace WallpaperEngine::Render;
 using namespace WallpaperEngine::Data::Model;
 
 namespace WallpaperEngine::Render::Objects {
+class CImage;
 
 constexpr uint32_t DEFAULT_MAX_PARTICLES = 1000;
 
@@ -42,23 +44,6 @@ struct ParticleInstance {
     float lifetime { 1.0f }; // Total lifetime in seconds
     float age { 0.0f }; // Current age in seconds
 
-    // Oscillator state (per-particle random values)
-    // base is updated by alphafade/sizechange operators so oscillation combines properly
-    struct {
-	float frequency { 0.0f };
-	float scale { 1.0f };
-	float phase { 0.0f };
-	float base { 1.0f };
-	bool initialized { false };
-    } oscillateAlpha, oscillateSize;
-
-    struct {
-	glm::vec3 frequency { 0.0f };
-	glm::vec3 scale { 1.0f };
-	glm::vec3 phase { 0.0f };
-	bool initialized { false };
-    } oscillatePosition;
-
     // Initial values for resets/multipliers
     struct {
 	glm::vec3 color { 1.0f };
@@ -107,6 +92,19 @@ struct ControlPointData {
 
 using EmitterFunc = std::function<void (std::vector<ParticleInstance>&, uint32_t&, float)>;
 
+/** An emitter's timers, the runtime part of its record in wallpaper64.exe sub_1402378A0 */
+struct EmitterClock {
+    float delay { 0.0f };
+    /** Counts down while > 0, -1 once it ran out */
+    float duration { 0.0f };
+    float accumulator { 0.0f };
+    /** Periodic emitters: > 0 emitting for that long, < 0 waiting */
+    float period { 0.0f };
+    int emittedInPeriod { 0 };
+    uint32_t pendingBurst { 0 };
+    bool finished { false };
+};
+
 using InitializerFunc = std::function<void (ParticleInstance&)>;
 
 using OperatorFunc = std::function<
@@ -140,6 +138,8 @@ protected:
 
     EmitterFunc createBoxEmitter (const ParticleEmitter& emitter);
     EmitterFunc createSphereEmitter (const ParticleEmitter& emitter);
+    /** How many particles an emitter spawns this frame, advances its timers */
+    uint32_t emitCount (EmitterClock& clock, const ParticleEmitter& emitter, float dt);
     /** Spawn position from the emitter's shape offset and control point, sets m_emitOrientation */
     void placeSpawn (
 	ParticleInstance& p, const ControlPointData* cp, int controlPointIndex, const glm::vec3& origin,
@@ -212,12 +212,49 @@ protected:
     /** REFRACT: fills the _rt_FullFrameBuffer copy right before drawing, like WE's copy of the bound target */
     void copyRefractSource () const;
     void buildRopeTrail (uint32_t& vertexIndex, uint32_t& indexOffset);
+    void buildRopeSegments (uint32_t& vertexIndex, uint32_t& indexOffset);
+
+    /** A collisionmodel capsule in the system's space: the segment from start along direction, and its radius */
+    struct CollisionCapsule {
+	glm::vec3 start;
+	glm::vec3 direction;
+	float length;
+	float radius;
+    };
+    [[nodiscard]] std::vector<CollisionCapsule> collisionCapsules (int index) const;
+    /** WE's world to the space particles are simulated in */
+    [[nodiscard]] glm::mat4 worldToParticles () const;
+    /** The object the index-th component of that type reads, from the particle's dependency records */
+    [[nodiscard]] const CObject* componentDependency (const char* type, int index) const;
+
+    /** A layerimage pixel: its colour and its place in layer units around the layer's center, y down */
+    struct ImagePixel {
+	uint8_t r, g, b;
+	int16_t x, y;
+    };
+    struct ImageEmitter {
+	/** Which emitterimage dependency record it reads */
+	int index;
+	std::vector<ImagePixel> pixels;
+	bool built { false };
+	float refreshTimer { 0.0f };
+	glm::ivec2 size { 0 };
+	glm::mat4 previousWorld { 1.0f };
+    };
+    std::vector<ImageEmitter> m_imageEmitters;
+    EmitterFunc createImageEmitter (const ParticleEmitter& emitter);
+    void buildImagePixels (ImageEmitter& state, const CImage& image);
+    OperatorFunc createCollisionModelOperator (const CollisionOperator& op);
+    /** collisionmodel components set up so far, each one reads the dependency record with its index */
+    int m_collisionModels { 0 };
     [[nodiscard]] float ropeUVScale () const;
     void setupPass ();
     void setupGeometryCallbacks ();
     void setupParticleUniforms ();
     void updateMatrices ();
     void updateParticleViewProjection ();
+    /** g_OrientationForward/Right/Up from the renderer's orientation (sub_1402298B0) */
+    void updateOrientation ();
     void updateParticleRenderVars ();
 
     void prewarm (double now);
@@ -247,6 +284,10 @@ protected:
     void passControlPoints (CParticle& child, const ParticleChild& definition) const;
     /** Starts over as a freshly spawned system, for pooled event children */
     void restart ();
+    /** sub_14022F6C0 + sub_14022F5B0: timers, sequences and emitters back to their start, particles are kept */
+    void restartEmission ();
+    /** sub_14022F790, a periodic emitter starts a new period */
+    void startEmitterPeriod ();
     [[nodiscard]] bool isFinished () const;
     [[nodiscard]] bool emittersExhausted () const;
 
@@ -266,12 +307,6 @@ private:
     std::vector<float> m_vertices;
     std::vector<uint32_t> m_indices;
 
-    // Reused across frames (resized, not reallocated) so renderRope() doesn't heap-allocate every frame
-    std::vector<glm::vec3> m_splinePositions;
-    std::vector<float> m_splineSizes;
-    std::vector<glm::vec4> m_splineColors;
-    std::vector<float> m_cumulativeArcLength;
-
     double m_time { 0.0 };
     bool m_prewarmed { false };
 
@@ -297,6 +332,8 @@ private:
     glm::mat4 m_modelMatrix { 1.0f };
     /** 2D scenes: vertices are uploaded in WE's y-up particle frame, m_modelMatrix carries the flip */
     bool m_drawFlipY = false;
+    /** g_ModelMatrix: m_modelMatrix in WE's world space, see updateMatrices () */
+    glm::mat4 m_worldModelMatrix { 1.0f };
     glm::mat4 m_modelMatrixInverse { 1.0f };
     glm::mat4 m_mvpMatrix { 1.0f };
     glm::mat4 m_mvpMatrixInverse { 1.0f };
@@ -325,8 +362,6 @@ private:
     int m_ropeSegments { 4 }; // ropetrail: historical position snapshots per particle
     float m_ropeUVScale { 1.0f };
     bool m_ropeUVScrolling { false };
-    bool m_ropeUVSmoothing { true }; // rope only
-    bool m_uniformLifetimes { false }; // true when lifetime min==max (enables UV smoothing)
     bool m_trailFadeAlpha { false };
     bool m_trailFadeSize { false };
     /** ropetrail: m_ropeSegments past positions per particle slot, newest first, compacted with the particles */
@@ -340,6 +375,8 @@ private:
 
     static constexpr int SPRITE_FLOATS_PER_VERTEX = 17;
     static constexpr int ROPE_FLOATS_PER_VERTEX = 26;
+    /** Ropes go through genericropeparticle.geom, a point per segment */
+    bool m_geometryStage { false };
 
     std::mt19937 m_rng;
     /** Only drawn when an operator needs it, so systems without one keep the same random sequence */
@@ -374,8 +411,17 @@ private:
     bool m_hasEventParticle { false };
     bool m_following { false };
     bool m_emissionStopped { false };
-    /** Emission time since (re)start, for telling when every emitter is done */
-    float m_emitterTime { 0.0f };
+    /** One per entry of m_emitters, same order */
+    std::vector<EmitterClock> m_emitterClocks;
+
+    /** Where a mapsequence initializer is in its sequence, WE keeps it in the initializer's record (+4, +8) */
+    struct SequenceCounter {
+	float step;
+	float sequence { 0.0f };
+	/** Starts over with every new emitter period (mapsequencebetweencontrolpoints flag 0x20) */
+	bool periodReset { false };
+    };
+    std::deque<SequenceCounter> m_sequences;
 
     std::vector<std::unique_ptr<CParticle>> m_staticChildren;
     std::vector<EventChildSlot> m_eventChildren;
@@ -402,10 +448,9 @@ private:
     float m_systemTime { 0.0f };
     /** Top level systems only, see layerTime () */
     float m_layerTime { 0.0f };
-    /** Real time between the last two rendered frames and the frame count, for frameScaledDelta and boids */
+    /** Real time between the last two rendered frames, for frameScaledDelta */
     float m_frameDelta { 0.0f };
     float m_lastRealTime { 0.0f };
-    uint32_t m_frameCounter { 0 };
     struct ColorOverride {
 	/** override color given and further than 0.9/255 from the particle file's reference color */
 	bool active = false;
@@ -419,7 +464,7 @@ private:
     /** System flag 2 in wallpaper64.exe: angularvelocityrandom or angularmovement, angular speed means something */
     bool m_hasAngularVelocity { false };
     /** sub_14023FBC0 restores these from the spawn values before the operators when a remapvalue writes them */
-    bool m_resetSizeFromBase { false };
+    bool m_resetSizeFromBase { true };
     bool m_resetAlphaFromBase { false };
     bool m_resetColorFromBase { false };
     /** collisionquad needs where particles were before this frame's operators */

+ 425 - 34
src/WallpaperEngine/Render/Objects/CSound.cpp

@@ -3,70 +3,461 @@
 #include "CSound.h"
 
 #include "WallpaperEngine/FileSystem/Container.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <glm/gtc/constants.hpp>
+#include <glm/gtc/matrix_access.hpp>
 
 #include <algorithm>
+#include <cfloat>
+#include <cmath>
+#include <random>
 
 using namespace WallpaperEngine::Render::Objects;
 
+namespace {
+std::mt19937& generator () {
+    static std::mt19937 engine { std::random_device {}() };
+    return engine;
+}
+
+/** 0..32767 like the CRT rand () WE picks the file with (sub_1402C97A0) */
+int crtRand () { return static_cast<int> (generator () () >> 17); }
+
+/** [0, 1) from a Mersenne twister draw, sub_1401F4BC0 with the renderer's range 0..1 */
+float uniform01 () { return static_cast<float> (generator () () >> 8) * 5.9604645e-8f; }
+
+/** OpenAL Soft 1.21.1 alu.cpp: pulls azimuths in front towards the sides */
+float scaleAzimuthFront (float azimuth, float scale) {
+    const float absolute = std::fabs (azimuth);
+
+    if (!(absolute >= glm::half_pi<float> ())) {
+	return std::copysign (std::min (absolute * scale, glm::half_pi<float> ()), azimuth);
+    }
+
+    return azimuth;
+}
+
+/**
+ * Speaker gains of a mono source for OpenAL Soft 1.21.1's stereo output without HRTF (pairwise render mode, alu.cpp
+ * CalcPanningAndFilters): first order ambisonic coefficients of the direction through panning.cpp's StereoConfig
+ * decoder. A source at the listener takes the channel's own angle, 0 for mono
+ */
+glm::vec2 stereoPan (const glm::vec3& direction, float distance) {
+    float azimuth = 0.0f;
+    float elevation = 0.0f;
+
+    if (distance > FLT_EPSILON) {
+	elevation = std::asin (std::clamp (direction.y, -1.0f, 1.0f));
+	azimuth = scaleAzimuthFront (std::atan2 (direction.x, -direction.z), 1.5f);
+    }
+
+    const float acn1 = 1.732050808f * -std::sin (azimuth) * std::cos (elevation);
+    const float acn3 = 1.732050808f * std::cos (azimuth) * std::cos (elevation);
+
+    return { 5.00000000e-1f + 2.88675135e-1f * acn1 + 5.52305643e-2f * acn3,
+	     5.00000000e-1f - 2.88675135e-1f * acn1 + 5.52305643e-2f * acn3 };
+}
+} // namespace
+
 CSound::CSound (Wallpapers::CScene& scene, const Sound& sound) :
-    CObject (scene, sound), m_sound (sound),
-    m_playing (scene.getSoundPlayRequest (sound.id).value_or (!sound.startsilent.value_or (false))) {
-    if (this->getContext ().getApp ().getContext ().settings.audio.enabled) {
-	this->load ();
+    CObject (scene, sound), m_sound (sound), m_startSilent (sound.startsilent.value_or (false)) {
+    this->m_lastVolume = this->m_sound.volume && this->m_sound.volume->value
+	? this->m_sound.volume->value->getFloat ()
+	: 1.0f;
+    this->m_lastMaster = this->masterVolume ();
+
+    // sub_1401F4F20, when the object is added to the scene
+    if (!this->m_startSilent) {
+	this->play ();
+    }
+
+    // a script asked for this sound before it existed
+    if (const auto request = scene.getSoundPlayRequest (sound.id); request.has_value ()) {
+	if (request.value ()) {
+	    this->play ();
+	} else {
+	    this->stop ();
+	}
     }
 }
 
 CSound::~CSound () {
-    for (const auto& stream : this->m_audioStreams) {
-	this->getScene ().getAudioContext ().removeStream (stream.first);
-	delete stream.second;
+    for (auto& voice : this->m_voices) {
+	this->stopVoice (voice);
+    }
+}
+
+void CSound::loadVoices () {
+    if (!this->getContext ().getApp ().getContext ().settings.audio.enabled) {
+	return;
+    }
+
+    // WE loads every file the first time it plays and drops the ones that fail (sub_1401F5980)
+    for (const auto& file : this->m_sound.sounds) {
+	try {
+	    const Audio::AudioStream probe (this->getScene ().getAudioContext (), this->getAssetLocator ().read (file));
+
+	    this->m_voices.push_back ({ .file = file,
+					.duration = static_cast<float> (probe.getDuration ()),
+					.mono = probe.getSourceChannels () == 1 });
+	} catch (const std::exception& e) {
+	    sLog.error ("Cannot load sound ", file, ": ", e.what ());
+	}
+    }
+}
+
+void CSound::playVoice (Voice& voice, bool loop) {
+    auto& audio = this->getScene ().getAudioContext ();
+
+    if (voice.state == VoiceState::Paused && voice.streamId >= 0) {
+	voice.stream->setRepeat (loop);
+	audio.setStreamPaused (voice.streamId, false);
+	voice.state = VoiceState::Playing;
+	return;
+    }
+
+    this->stopVoice (voice);
+
+    try {
+	voice.stream = std::make_unique<Audio::AudioStream> (audio, this->getAssetLocator ().read (voice.file), loop);
+    } catch (const std::exception& e) {
+	sLog.error ("Cannot play sound ", voice.file, ": ", e.what ());
+	return;
+    }
+
+    const glm::vec2 gains = this->outputGains (voice);
+
+    voice.streamId = audio.addStream (voice.stream.get (), SDL_MIX_MAXVOLUME, gains.x, gains.y);
+    voice.state = VoiceState::Playing;
+}
+
+void CSound::pauseVoice (Voice& voice) {
+    if (voice.streamId >= 0) {
+	this->getScene ().getAudioContext ().setStreamPaused (voice.streamId, true);
     }
 
-    this->m_audioStreams.clear ();
+    voice.state = VoiceState::Paused;
 }
 
-void CSound::load () {
-    for (const auto& cur : this->m_sound.sounds) {
-	auto stream
-	    = new Audio::AudioStream (this->getScene ().getAudioContext (), this->getAssetLocator ().read (cur));
+void CSound::stopVoice (Voice& voice) {
+    if (voice.streamId >= 0) {
+	this->getScene ().getAudioContext ().removeStream (voice.streamId);
+    }
+
+    voice.stream.reset ();
+    voice.streamId = -1;
+    voice.state = VoiceState::Stopped;
+}
 
-	stream->setRepeat (this->m_sound.playbackmode == PlaybackMode_Loop);
+void CSound::stopAllVoices () {
+    // sub_1401F58E0
+    this->m_paused = false;
+    this->m_stopped = true;
+    this->m_timer = 0.0f;
 
-	this->m_audioStreams.insert_or_assign (this->getScene ().getAudioContext ().addStream (stream), stream);
+    for (auto& voice : this->m_voices) {
+	if (voice.state != VoiceState::Stopped) {
+	    this->stopVoice (voice);
+	}
     }
 }
 
-void CSound::render () { this->applyEffectiveVolume (); }
+CSound::Voice& CSound::pickVoice () {
+    const int count = static_cast<int> (this->m_voices.size ());
+    const int index = static_cast<int> (static_cast<float> (crtRand ()) / 32767.0f * static_cast<float> (count) + 0.0f);
+
+    return this->m_voices[std::max (std::min (count - 1, index), 0)];
+}
+
+bool CSound::hasActiveVoice () const {
+    return std::ranges::any_of (this->m_voices, [] (const Voice& voice) {
+	return voice.state != VoiceState::Stopped;
+    });
+}
 
 void CSound::play () {
-    this->m_playing = true;
-    this->applyEffectiveVolume ();
+    // sub_1401F5980
+    if (this->sourceGain () <= 0.0f) {
+	this->m_paused = false;
+	this->m_stopped = false;
+	this->m_startSilent = false;
+	return;
+    }
+
+    if (this->m_voices.empty ()) {
+	this->loadVoices ();
+    }
+
+    if (this->m_sound.spatialization) {
+	this->m_position = this->spatialPosition ();
+    }
+
+    const bool loop = this->m_voices.size () <= 1 && this->m_sound.playbackmode == PlaybackMode_Loop;
+
+    if (this->m_paused) {
+	this->m_paused = false;
+
+	const auto paused = std::ranges::find_if (this->m_voices, [] (const Voice& voice) {
+	    return voice.state == VoiceState::Paused;
+	});
+
+	if (paused != this->m_voices.end ()) {
+	    this->playVoice (*paused, loop);
+	}
+
+	return;
+    }
+
+    if (!this->m_voices.empty ()) {
+	switch (this->m_sound.playbackmode) {
+	    case PlaybackMode_Random:
+		if (this->m_timer != 0.0f) {
+		    break;
+		}
+
+		this->stopAllVoices ();
+		{
+		    Voice& voice = this->pickVoice ();
+
+		    this->playVoice (voice, false);
+		    this->m_remaining = voice.duration;
+		}
+		this->m_timer = uniform01 () * (this->m_sound.maxtime - this->m_sound.mintime) + this->m_sound.mintime
+		    + this->m_remaining;
+		break;
+	    case PlaybackMode_Single: {
+		this->stopAllVoices ();
+		this->m_timer = 0.0f;
+
+		Voice& voice = this->pickVoice ();
+
+		this->playVoice (voice, false);
+		this->m_remaining = voice.duration;
+		break;
+	    }
+	    case PlaybackMode_Loop: {
+		this->stopAllVoices ();
+
+		Voice& voice = this->pickVoice ();
+
+		this->playVoice (voice, loop);
+		// several files: the next random one starts when this one is over
+		this->m_timer = this->m_voices.size () > 1 ? voice.duration : 0.0f;
+		break;
+	    }
+	}
+    }
+
+    this->m_stopped = false;
+    this->m_startSilent = false;
 }
 
 void CSound::stop () {
-    this->m_playing = false;
-    this->applyEffectiveVolume ();
+    // sub_1401F6E60
+    this->m_paused = false;
+    this->m_stopped = true;
+    this->m_timer = 0.0f;
+
+    for (auto& voice : this->m_voices) {
+	if (voice.state != VoiceState::Stopped) {
+	    this->stopVoice (voice);
+	}
+    }
+}
+
+void CSound::pause () {
+    // sub_1401F6F00
+    if (this->m_paused || this->m_stopped) {
+	return;
+    }
+
+    this->m_paused = true;
+
+    for (auto& voice : this->m_voices) {
+	if (voice.state == VoiceState::Playing) {
+	    this->pauseVoice (voice);
+	}
+    }
+}
+
+bool CSound::isPlaying () const {
+    // sub_1401F6FB0
+    if (this->m_sound.playbackmode == PlaybackMode_Single && this->m_remaining <= 0.0f) {
+	return false;
+    }
+
+    if (this->m_sound.playbackmode == PlaybackMode_Random && this->m_timer <= 0.0f) {
+	return false;
+    }
+
+    return this->hasActiveVoice () && !this->m_paused;
+}
+
+void CSound::volumeChanged () {
+    // sub_1401F4C20, also what a master volume change does to every sound (sub_1401816D0)
+    const auto mode = this->m_sound.playbackmode;
+
+    if (mode != PlaybackMode_Single) {
+	const bool active = !(mode == PlaybackMode_Random && this->m_timer <= 0.0f) && this->hasActiveVoice ()
+	    && !this->m_paused;
+
+	if (!active && !this->m_paused && !this->m_startSilent && !this->m_stopped) {
+	    this->play ();
+	}
+    }
+
+    const bool audible = this->masterVolume () > 0.0f;
+
+    for (auto& voice : this->m_voices) {
+	this->applyOutput (voice);
+
+	if (audible) {
+	    if (!this->m_paused && voice.state == VoiceState::Paused) {
+		this->playVoice (voice, mode == PlaybackMode_Loop);
+		return;
+	    }
+	} else if (voice.state == VoiceState::Playing) {
+	    this->pauseVoice (voice);
+
+	    if (mode != PlaybackMode_Loop && this->m_remaining <= 0.0f) {
+		this->stopVoice (voice);
+	    }
+	}
+    }
 }
 
-void CSound::setVolumeOverride (std::optional<int> volume) {
-    this->m_screenVolumeOverride = volume;
-    this->applyEffectiveVolume ();
+void CSound::update (float dt) {
+    const float volume
+	= this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
+    const float master = this->masterVolume ();
+
+    if (volume != this->m_lastVolume || master != this->m_lastMaster) {
+	this->m_lastVolume = volume;
+	this->m_lastMaster = master;
+	this->volumeChanged ();
+    }
+
+    // sub_1401F4F50, dt / renderer +340, which stays 1
+    if (!this->m_paused && !this->m_stopped) {
+	if (this->sourceGain () > 0.0f && this->m_timer > 0.0f) {
+	    this->m_timer -= dt;
+
+	    if (this->m_timer <= 0.0f) {
+		this->m_timer = 0.0f;
+		this->play ();
+	    }
+	}
+
+	if (master > 0.0f && this->m_remaining > 0.0f) {
+	    this->m_remaining -= dt;
+	}
+
+	if (this->m_sound.spatialization) {
+	    this->m_position = this->spatialPosition ();
+	}
+    }
+
+    this->applyOutput ();
 }
 
-void CSound::applyEffectiveVolume () {
-    // The screen-level policy (mute/ambient-volume, set via setVolumeOverride from
-    // CScene::setAudioPolicy) and the wallpaper author's own per-object "volume" property (e.g.
-    // picking which of several alternate music tracks plays) are independent inputs that have to
-    // combine, not overwrite each other - otherwise picking a track would undo screen muting, or
-    // muting a screen would make track selection pointless.
+void CSound::setVolumeOverride (std::optional<int> volume) { this->m_screenVolumeOverride = volume; }
+
+float CSound::masterVolume () const {
     const int base
 	= this->m_screenVolumeOverride.value_or (this->getContext ().getApp ().getContext ().state.audio.volume);
-    const float fraction = this->m_sound.volume && this->m_sound.volume->value
-	? std::clamp (this->m_sound.volume->value->getFloat (), 0.0f, 1.0f)
-	: 1.0f;
-    const int effective = this->m_playing ? static_cast<int> (static_cast<float> (base) * fraction) : 0;
 
-    for (const auto& entry : this->m_audioStreams) {
-	this->getScene ().getAudioContext ().setStreamVolume (entry.first, effective);
+    return static_cast<float> (base) / static_cast<float> (SDL_MIX_MAXVOLUME);
+}
+
+float CSound::sourceGain () const {
+    const float volume
+	= this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
+
+    // the voice volume call (+208) gets volume * volume * renderer +728, mediaextensions64 turns it into AL_GAIN as is
+    return volume * volume * this->masterVolume ();
+}
+
+glm::vec3 CSound::spatialPosition () const {
+    const auto& scene = this->getScene ();
+
+    // renderer +324 is the frame counter, 0 while the scene is still loading
+    if (scene.getFrameCounter () == 0) {
+	return { 0.0f, 0.0f, 99999.0f };
+    }
+
+    const auto& camera = scene.getCamera ();
+    const glm::vec3 origin (scene.objectWorldMatrix (this->m_sound)[3]);
+    const glm::mat4& view = camera.isPerspective () ? camera.getView () : camera.getWorldView ();
+    // renderer +364 / +376 / +352: rows 0 and 1 of the view and minus row 2 (sub_14017FA70), the eye is +104
+    const glm::vec3 right (glm::row (view, 0));
+    const glm::vec3 up (glm::row (view, 1));
+    const glm::vec3 forward = -glm::vec3 (glm::row (view, 2));
+    const glm::vec3 offset = origin - scene.getFog ().eyeWorld;
+    glm::vec3 position (glm::dot (offset, right), -glm::dot (offset, up), glm::dot (offset, forward));
+
+    // orthographic scenes only keep the direction, scaled down by the sound's depth over a quarter of the scene size
+    if (camera.isOrthogonal ()) {
+	const float length = std::sqrt (glm::dot (position, position));
+	const float reach = static_cast<float> (static_cast<int> (camera.getWidth ()) + static_cast<int> (camera.getHeight ()))
+	    * 0.25f;
+
+	position *= 1.0f / length;
+	position *= std::max (reach - origin.z, 0.0f) / reach;
+    }
+
+    return position;
+}
+
+glm::vec2 CSound::outputGains (const Voice& voice) const {
+    float gain = this->sourceGain ();
+    glm::vec2 channels (1.0f);
+
+    // OpenAL Soft only spatializes mono sources (AL_SOURCE_SPATIALIZE_SOFT defaults to auto), the others go straight
+    // to their speakers; the source gain is clamped to AL_MAX_GAIN 1 on both paths
+    if (voice.mono && this->getScene ().getAudioContext ().getChannels () == 2) {
+	// WE only sets the reference distance and rolloff on spatialized sounds, the others keep OpenAL's 1 and 1 and sit
+	// on the listener
+	const float reference = this->m_sound.spatialization ? this->m_sound.mindistance : 1.0f;
+	const float rolloff = this->m_sound.spatialization ? this->m_sound.attenuation : 1.0f;
+	const float limit = std::max (reference / 1024.0f, FLT_EPSILON);
+	glm::vec3 direction = this->m_position;
+	float distance = 0.0f;
+
+	if (glm::dot (direction, direction) > limit * limit) {
+	    distance = std::sqrt (glm::dot (direction, direction));
+	    direction *= 1.0f / distance;
+	}
+
+	// AL_INVERSE_DISTANCE_CLAMPED, WE never changes the distance model or AL_MAX_DISTANCE
+	const float clamped = std::clamp (distance, reference, FLT_MAX);
+
+	if (reference > 0.0f) {
+	    const float scaled = reference + (clamped - reference) * rolloff;
+
+	    if (scaled > 0.0f) {
+		gain *= reference / scaled;
+	    }
+	}
+
+	channels = stereoPan (direction, distance);
+    }
+
+    return std::clamp (gain, 0.0f, 1.0f) * channels;
+}
+
+void CSound::applyOutput (const Voice& voice) const {
+    if (voice.streamId < 0) {
+	return;
+    }
+
+    const glm::vec2 gains = this->outputGains (voice);
+
+    this->getScene ().getAudioContext ().setStreamGains (voice.streamId, gains.x, gains.y);
+}
+
+void CSound::applyOutput () const {
+    for (const auto& voice : this->m_voices) {
+	this->applyOutput (voice);
     }
 }

+ 62 - 9
src/WallpaperEngine/Render/Objects/CSound.h

@@ -1,7 +1,11 @@
 #pragma once
 
+#include <memory>
 #include <optional>
 
+#include <glm/vec2.hpp>
+#include <glm/vec3.hpp>
+
 #include "WallpaperEngine/Audio/AudioStream.h"
 #include "WallpaperEngine/Render/CObject.h"
 
@@ -14,32 +18,81 @@ class CScene;
 namespace WallpaperEngine::Render::Objects {
 using namespace WallpaperEngine::Data::Model;
 
+/**
+ * WE's sound object (wallpaper64.exe 2.8.42, vtable off_140490AE8). Every file of the object is a voice, only one plays
+ * at a time: play() stops them all and starts a random one. Loop mode loops a single file and otherwise moves on to
+ * another random file when the current one is over, random mode waits mintime..maxtime between files, single plays
+ * one file once. WE plays them through OpenAL Soft 1.21.1 (mediaextensions64.dll), whose speaker panning and distance
+ * attenuation are reproduced here for mono files.
+ */
 class CSound final : public CObject {
 public:
     CSound (Wallpapers::CScene& scene, const Sound& sound);
     ~CSound () override;
 
-    void render () override;
+    /** Timers, volume changes and the spatial position, every frame for visible and hidden sounds (sub_1401F4F50) */
+    void update (float dt);
 
     /** Overrides the volume (0-128) this sound's streams mix at instead of the global volume; nullopt = global */
     void setVolumeOverride (std::optional<int> volume);
 
-    /** Script-facing playback control (thisScene.getLayer(<sound name>).play()/stop()/pause()) */
+    /** Script-facing playback control, thisScene.getLayer(<sound name>).play()/stop()/pause()/isPlaying() */
     void play ();
     void stop ();
-    [[nodiscard]] bool isPlaying () const { return this->m_playing; }
-
-protected:
-    void load ();
+    void pause ();
+    [[nodiscard]] bool isPlaying () const;
 
 private:
-    void applyEffectiveVolume ();
+    enum class VoiceState { Stopped, Paused, Playing };
+
+    struct Voice {
+	std::string file;
+	std::unique_ptr<Audio::AudioStream> stream;
+	int streamId = -1;
+	float duration = 0.0f;
+	bool mono = false;
+	VoiceState state = VoiceState::Stopped;
+    };
+
+    void loadVoices ();
+    void playVoice (Voice& voice, bool loop);
+    void pauseVoice (Voice& voice);
+    void stopVoice (Voice& voice);
+    void stopAllVoices ();
+    /** Random voice, like WE's rand () / 32767 * count clamped to the last one */
+    [[nodiscard]] Voice& pickVoice ();
+    [[nodiscard]] bool hasActiveVoice () const;
+    void volumeChanged ();
 
-    std::map<int, Audio::AudioStream*> m_audioStreams = {};
+    /** WE's master volume (renderer +728), 0-1 */
+    [[nodiscard]] float masterVolume () const;
+    /** AL_GAIN WE gives every voice: volume squared times the master volume */
+    [[nodiscard]] float sourceGain () const;
+    /** Where WE puts the sound in OpenAL's listener space (sub_1401F5460) */
+    [[nodiscard]] glm::vec3 spatialPosition () const;
+    /** Left and right gain of a voice: AL_GAIN, and for mono files OpenAL's distance attenuation and panning */
+    [[nodiscard]] glm::vec2 outputGains (const Voice& voice) const;
+    void applyOutput (const Voice& voice) const;
+    void applyOutput () const;
+
+    std::vector<Voice> m_voices = {};
 
     const Sound& m_sound;
     /** Screen-level mute/ambient-volume policy from CScene::setAudioPolicy; nullopt = no override */
     std::optional<int> m_screenVolumeOverride;
-    bool m_playing = true;
+
+    /** +764: countdown to the next play () (next file in loop mode, next play after the random delay) */
+    float m_timer = 0.0f;
+    /** +768: time left of the file that was started last */
+    float m_remaining = 0.0f;
+    /** +784 flags 0x40000000, 0x80000000 and 2 */
+    bool m_paused = false;
+    bool m_stopped = true;
+    bool m_startSilent = false;
+
+    float m_lastVolume = 0.0f;
+    float m_lastMaster = 0.0f;
+    /** OpenAL source position, the origin (the listener) until spatialization moves it */
+    glm::vec3 m_position = glm::vec3 (0.0f);
 };
 } // namespace WallpaperEngine::Render::Objects

+ 313 - 81
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -5,6 +5,8 @@
 #include <cstdio>
 #include <filesystem>
 #include <sstream>
+#include <strings.h>
+#include <unordered_map>
 #include <vector>
 
 #include <glm/gtc/matrix_transform.hpp>
@@ -16,6 +18,7 @@
 #include "WallpaperEngine/Data/Model/UserSetting.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Assets/AssetLocator.h"
 #include "WallpaperEngine/Render/CFBO.h"
 #include "WallpaperEngine/Render/Camera.h"
 #include "WallpaperEngine/Render/TextureProvider.h"
@@ -76,6 +79,112 @@ std::string fontconfigMatch (const std::string& font) {
     return !path.empty () && std::filesystem::exists (path) ? path : std::string ();
 }
 
+// The first of these families fontconfig has installed under that very name (fc-match always answers with something)
+std::string installedFamily (const std::vector<std::string>& families) {
+    static std::unordered_map<std::string, std::string> cache;
+
+    for (const auto& family : families) {
+	if (const auto it = cache.find (family); it != cache.end ()) {
+	    if (!it->second.empty ()) {
+		return it->second;
+	    }
+
+	    continue;
+	}
+
+	const std::string command = "fc-match -f '%{family}\\n%{file}' '" + family + "' 2>/dev/null";
+	FILE* pipe = popen (command.c_str (), "r");
+	std::string output;
+
+	if (pipe != nullptr) {
+	    char buffer[512];
+
+	    while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
+		output += buffer;
+	    }
+
+	    pclose (pipe);
+	}
+
+	std::string path;
+	const size_t newline = output.find ('\n');
+
+	if (newline != std::string::npos) {
+	    std::stringstream names (output.substr (0, newline));
+	    std::string name;
+
+	    while (std::getline (names, name, ',')) {
+		if (strcasecmp (name.c_str (), family.c_str ()) == 0) {
+		    path = output.substr (newline + 1);
+		    break;
+		}
+	    }
+	}
+
+	if (!path.empty () && !std::filesystem::exists (path)) {
+	    path.clear ();
+	}
+
+	cache.emplace (family, path);
+
+	if (!path.empty ()) {
+	    return path;
+	}
+    }
+
+    return {};
+}
+
+// wallpaper64.exe's fallback fonts (off_140484C40, tried per character by sub_1401AD670): Windows fonts from the
+// system font folder and the assets' Twemoji. Here the Windows fonts count when they are installed under their own
+// family, arial.ttf also through its metric compatible clones like the systemfont_arial match
+std::vector<TextFontSource> weFallbackFonts (const WallpaperEngine::Assets::AssetLocator& assets) {
+    static std::shared_ptr<const std::vector<uint8_t>> twemoji;
+    static bool twemojiRead = false;
+
+    if (!twemojiRead) {
+	twemojiRead = true;
+
+	try {
+	    auto stream = assets.read ("fonts/TwemojiMozilla.ttf");
+	    stream->seekg (0, std::ios::end);
+	    const auto size = stream->tellg ();
+	    stream->seekg (0, std::ios::beg);
+	    std::vector<uint8_t> data (static_cast<size_t> (size));
+	    stream->read (reinterpret_cast<char*> (data.data ()), size);
+	    twemoji = std::make_shared<const std::vector<uint8_t>> (std::move (data));
+	} catch (const std::exception& e) {
+	    sLog.error ("CText: cannot read fonts/TwemojiMozilla.ttf: ", e.what ());
+	}
+    }
+
+    const std::vector<std::vector<std::string>> before = {
+	{ "Arial", "Liberation Sans", "Arimo" }, { "Segoe UI Emoji" }, { "Arial Unicode MS" }, { "Segoe UI" },
+    };
+    const std::vector<std::vector<std::string>> after = {
+	{ "Segoe UI Symbol" }, { "Microsoft YaHei" }, { "Malgun Gothic" },
+    };
+    std::vector<TextFontSource> fonts;
+
+    for (const auto& families : before) {
+	if (std::string path = installedFamily (families); !path.empty ()) {
+	    fonts.push_back ({ nullptr, std::move (path) });
+	}
+    }
+
+    if (twemoji != nullptr) {
+	fonts.push_back ({ twemoji, "fonts/TwemojiMozilla.ttf" });
+    }
+
+    for (const auto& families : after) {
+	if (std::string path = installedFamily (families); !path.empty ()) {
+	    fonts.push_back ({ nullptr, std::move (path) });
+	}
+    }
+
+    return fonts;
+}
+
 // The glyph atlas as a TextureProvider: R8 coverage for plain glyphs, RGBA for MSDF ones
 class TextAtlasTexture final : public WallpaperEngine::Render::TextureProvider {
 public:
@@ -225,6 +334,7 @@ CText::CText (Wallpapers::CScene& scene, const Text& text) :
 	{ "dropshadowopacity", text.dropShadowOpacity },
 	{ "dropshadowoffset", text.dropShadowOffset },
 	{ "dropshadowcolor", text.dropShadowColor },
+	{ "depthtest", text.depthTest },
     };
 
     for (const auto& [name, setting] : properties) {
@@ -241,8 +351,9 @@ CText::~CText () {
 
     this->destroyPasses ();
 
-    for (GLuint* buffer : { &m_glyphPositions, &m_glyphTexcoords, &m_backgroundPositions, &m_passSpacePosition,
-			    &m_compositePosition, &m_quadTexcoords }) {
+    for (GLuint* buffer : { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords,
+			    &m_backgroundPositions, &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords,
+			    &m_compositeTexcoords }) {
 	if (*buffer != 0) {
 	    glDeleteBuffers (1, buffer);
 	}
@@ -268,15 +379,26 @@ void CText::setup () {
 	return;
     }
 
+    // sub_140186C90 flags a text (object type 4) that another object lists in its dependencies once every object
+    // exists, before the first frame
+    m_isDependency = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
+	return object->id != m_text.id && std::ranges::find (object->dependencies, m_text.id) != object->dependencies.end ();
+    });
+
+    m_layout.setFallbackFonts (weFallbackFonts (this->getAssetLocator ()));
+
     if (!loadFont ()) {
 	return;
     }
 
     m_atlas = std::make_shared<TextAtlasTexture> ();
+    m_colorAtlas = std::make_shared<TextAtlasTexture> ();
+    m_colorTexture = std::make_shared<TextAtlasTexture> ();
     this->m_texture = m_atlas;
 
-    for (GLuint* buffer : { &m_glyphPositions, &m_glyphTexcoords, &m_backgroundPositions, &m_passSpacePosition,
-			    &m_compositePosition, &m_quadTexcoords }) {
+    for (GLuint* buffer : { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords,
+			    &m_backgroundPositions, &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords,
+			    &m_compositeTexcoords }) {
 	glGenBuffers (1, buffer);
     }
 
@@ -288,6 +410,10 @@ void CText::setup () {
     glBufferData (GL_ARRAY_BUFFER, sizeof (passSpacePosition), passSpacePosition, GL_STATIC_DRAW);
     glBindBuffer (GL_ARRAY_BUFFER, m_quadTexcoords);
     glBufferData (GL_ARRAY_BUFFER, sizeof (quadTexcoords), quadTexcoords, GL_STATIC_DRAW);
+    // the text buffer's rows run top down like WE's (v 0 at the top of the box), the composite quad's y runs down
+    const GLfloat compositeTexcoords[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
+    glBindBuffer (GL_ARRAY_BUFFER, m_compositeTexcoords);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (compositeTexcoords), compositeTexcoords, GL_STATIC_DRAW);
 
     // scripted text may start out empty, a space keeps the layout alive until the script produces a value
     this->relayout (text.empty () ? std::string (" ") : text);
@@ -405,17 +531,14 @@ glm::vec2 CText::screenAnchorOffset () const {
     }
 
     const auto& camera = this->getScene ().getCamera ();
-    const auto uvs = state.getTextureUVs ();
-    const float canvasWidth = camera.getCanvasWidth ();
-    const float canvasHeight = camera.getCanvasHeight ();
+    const glm::vec4 margins = this->getScene ().getVisibleMargins ();
     // --expand-canvas grows the canvas evenly around the scene
-    const float overhangX = (canvasWidth - camera.getWidth ()) * 0.5f;
-    const float overhangY = (canvasHeight - camera.getHeight ()) * 0.5f;
-    const float left = uvs.ustart * canvasWidth - overhangX;
-    const float right = (1.0f - uvs.uend) * canvasWidth - overhangX;
-    // v runs top down in a flipped state, bottom up otherwise
-    const float top = (state.isVFlipped () ? uvs.vstart : 1.0f - uvs.vstart) * canvasHeight - overhangY;
-    const float bottom = (state.isVFlipped () ? 1.0f - uvs.vend : uvs.vend) * canvasHeight - overhangY;
+    const float overhangX = (camera.getCanvasWidth () - camera.getWidth ()) * 0.5f;
+    const float overhangY = (camera.getCanvasHeight () - camera.getHeight ()) * 0.5f;
+    const float left = margins.x - overhangX;
+    const float right = margins.y - overhangX;
+    const float bottom = margins.z - overhangY;
+    const float top = margins.w - overhangY;
 
     const auto axis = [] (int side, float low, float high) {
 	// low is the left/bottom margin, high the right/top one; y is up
@@ -434,15 +557,21 @@ CText::PassLayout CText::currentPassLayout () const {
 	.blur = m_params.msdf && m_text.blur->value->getBool (),
 	.dropShadow = m_params.msdf && dropShadow,
 	.background = m_text.opaqueBackground->value->getBool (),
+	.color = !m_result.colorQuads.empty (),
+	// the _depth materials outside orthographic scenes (renderer flag 0x400) unless depthtest is "disabled" (+1440,
+	// enum table "disabled" 1 / "enabled" 0, any other string is the first entry)
+	.depth = this->getScene ().getCamera ().isPerspective () && m_text.depthTest->value->getString () == "enabled",
 	.blendMode = m_text.colorBlendMode->value->getInt (),
     };
 
     // sub_1401E6F50: a blend mode other than 0 and 31 (additive) makes the text composite through
-    // effectpassthrough, like having effects
-    // fog too (renderer flags 0x1800000)
+    // effectpassthrough, like having effects, and so does fog (renderer flags 0x1800000 = scene fog flags 0x4000
+    // and 0x8000, sub_140186440). Its other trigger, image flag 0x100, is never set in 2.8.42. The scene loader adds
+    // 0x1010 to a text another object lists in its dependencies (sub_140186C90), the buffer is what it reads
     const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
-    layout.buffered
-	= (!m_text.effects.empty () || (layout.blendMode != 0 && layout.blendMode != 31) || fog) && !debug.baseOnly;
+    layout.buffered = (!m_text.effects.empty () || (layout.blendMode != 0 && layout.blendMode != 31) || fog
+		       || m_isDependency)
+	&& !debug.baseOnly;
 
     // sub_140258900: text with effects renders into a buffer of its box plus padding on every side
     if (layout.buffered && m_result.valid) {
@@ -466,38 +595,57 @@ void CText::relayout (const std::string& text) {
 	    ->upload (m_layout.getAtlasSize (), m_layout.getAtlasChannels (), m_layout.getAtlasPixels ().data ());
     }
 
+    if (m_layout.takeColorAtlasChanged ()) {
+	static_cast<TextAtlasTexture*> (m_colorAtlas.get ())
+	    ->upload (m_layout.getColorAtlasSize (), 4, m_layout.getColorAtlasPixels ().data ());
+
+	if (m_layout.getColorScale () > 0) {
+	    static_cast<TextAtlasTexture*> (m_colorTexture.get ())
+		->upload (
+		    m_layout.getColorAtlasSize () * m_layout.getColorScale (), 4,
+		    m_layout.getColorTexturePixels ().data ()
+		);
+	}
+    }
+
     this->uploadGeometry ();
 }
 
 void CText::uploadGeometry () {
-    std::vector<GLfloat> positions;
-    std::vector<GLfloat> texcoords;
-    positions.reserve (m_result.quads.size () * 18);
-    texcoords.reserve (m_result.quads.size () * 12);
-
-    // two triangles per glyph, WE's index order 0 2 1 / 1 2 3 over top left, top right, bottom left, bottom right
-    for (const auto& quad : m_result.quads) {
-	const auto [x0, y0, x1, y1] = std::array { quad.rect.x, quad.rect.y, quad.rect.z, quad.rect.w };
-	const auto [u0, v0, u1, v1] = std::array { quad.uv.x, quad.uv.y, quad.uv.z, quad.uv.w };
-
-	positions.insert (
-	    positions.end (), { x0, y1, 0.0f, x0, y0, 0.0f, x1, y1, 0.0f, x1, y1, 0.0f, x0, y0, 0.0f, x1, y0, 0.0f }
+    const auto upload = [] (const std::vector<TextGlyphQuad>& quads, GLuint positionBuffer, GLuint texcoordBuffer) {
+	std::vector<GLfloat> positions;
+	std::vector<GLfloat> texcoords;
+	positions.reserve (quads.size () * 18);
+	texcoords.reserve (quads.size () * 12);
+
+	// two triangles per glyph, WE's index order 0 2 1 / 1 2 3 over top left, top right, bottom left, bottom right
+	for (const auto& quad : quads) {
+	    const auto [x0, y0, x1, y1] = std::array { quad.rect.x, quad.rect.y, quad.rect.z, quad.rect.w };
+	    const auto [u0, v0, u1, v1] = std::array { quad.uv.x, quad.uv.y, quad.uv.z, quad.uv.w };
+
+	    positions.insert (
+		positions.end (),
+		{ x0, y1, 0.0f, x0, y0, 0.0f, x1, y1, 0.0f, x1, y1, 0.0f, x0, y0, 0.0f, x1, y0, 0.0f }
+	    );
+	    texcoords.insert (texcoords.end (), { u0, v0, u0, v1, u1, v0, u1, v0, u0, v1, u1, v1 });
+	}
+
+	glBindBuffer (GL_ARRAY_BUFFER, positionBuffer);
+	glBufferData (
+	    GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (positions.size () * sizeof (GLfloat)), positions.data (),
+	    GL_DYNAMIC_DRAW
+	);
+	glBindBuffer (GL_ARRAY_BUFFER, texcoordBuffer);
+	glBufferData (
+	    GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (texcoords.size () * sizeof (GLfloat)), texcoords.data (),
+	    GL_DYNAMIC_DRAW
 	);
-	texcoords.insert (texcoords.end (), { u0, v0, u0, v1, u1, v0, u1, v0, u0, v1, u1, v1 });
-    }
 
-    m_glyphVertexCount = static_cast<GLsizei> (m_result.quads.size () * 6);
+	return static_cast<GLsizei> (quads.size () * 6);
+    };
 
-    glBindBuffer (GL_ARRAY_BUFFER, m_glyphPositions);
-    glBufferData (
-	GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (positions.size () * sizeof (GLfloat)), positions.data (),
-	GL_DYNAMIC_DRAW
-    );
-    glBindBuffer (GL_ARRAY_BUFFER, m_glyphTexcoords);
-    glBufferData (
-	GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (texcoords.size () * sizeof (GLfloat)), texcoords.data (),
-	GL_DYNAMIC_DRAW
-    );
+    m_glyphVertexCount = upload (m_result.quads, m_glyphPositions, m_glyphTexcoords);
+    m_colorGlyphVertexCount = upload (m_result.colorQuads, m_colorGlyphPositions, m_colorGlyphTexcoords);
 
     // the opaque background covers the text box plus padding (sub_140258050)
     const glm::vec2 padding = this->currentPadding ();
@@ -549,20 +697,35 @@ void CText::updateRenderVars () {
     }
 }
 
-CPass* CText::createFontPass (const std::shared_ptr<const CFBO>& destination, const glm::mat4* mvp) {
+CPass* CText::createFontPass (const std::shared_ptr<const CFBO>& destination, const glm::mat4* mvp, bool color) {
+    const Material& material = color ? *m_colorFontMaterial : *m_fontMaterial;
     auto* pass = new CPass (
-	*this, std::make_shared<FBOProvider> (this), **m_fontMaterial->passes.begin (), m_fontOverride, std::nullopt,
+	*this, std::make_shared<FBOProvider> (this), **material.passes.begin (), m_fontOverride, std::nullopt,
 	std::nullopt
     );
     pass->setDestination (destination);
-    pass->setInput (m_atlas);
-    pass->setPosition (m_glyphPositions);
-    pass->setTexCoord (m_glyphTexcoords);
+    pass->setInput (color ? m_colorAtlas : m_atlas);
+    pass->setPosition (color ? m_colorGlyphPositions : m_glyphPositions);
+    pass->setTexCoord (color ? m_colorGlyphTexcoords : m_glyphTexcoords);
     pass->setModelMatrix (&m_modelMatrix);
     pass->setViewProjectionMatrix (&m_viewProjectionMatrix);
     pass->setModelViewProjectionMatrix (mvp);
     pass->setModelViewProjectionMatrixInverse (mvp);
-    pass->setGeometryCallback (nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_glyphVertexCount); }, nullptr);
+
+    if (color) {
+	// sub_1401B3430: the MSDF colour material samples the colours from g_Texture1 (the atlas' +48 texture)
+	if (m_passLayout.msdf) {
+	    pass->setTexture (1, m_colorTexture);
+	}
+
+	pass->setGeometryCallback (
+	    nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_colorGlyphVertexCount); }, nullptr
+	);
+    } else {
+	pass->setGeometryCallback (
+	    nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_glyphVertexCount); }, nullptr
+	);
+    }
 
     for (int i = 0; i < 4; i++) {
 	pass->addUniform ("g_RenderVar" + std::to_string (i), &m_renderVars[i]);
@@ -577,13 +740,19 @@ void CText::buildPasses () {
     const auto& project = this->getScene ().getScene ().project;
     const PassLayout& layout = m_passLayout;
 
-    // sub_1401B3430 picks the material by atlas kind, the effect combos come from sub_1401B3B60
+    // sub_1401B3430 picks the material by atlas kind and the depth flag (params +25), colour glyphs get the rgba
+    // variants; the effect combos come from sub_1401B3B60
+    const std::string depthSuffix = layout.depth ? "_depth" : "";
+    const std::string msdfSuffix = layout.msdf ? "_msdf" : "";
+
     try {
-	m_fontMaterial = MaterialParser::load (
-	    project, layout.msdf ? "materials/fonts/basefont_msdf.json" : "materials/fonts/basefont.json"
-	);
-	m_backgroundMaterial
-	    = layout.background ? MaterialParser::load (project, "materials/fonts/fontbackground.json") : nullptr;
+	m_fontMaterial = MaterialParser::load (project, "materials/fonts/basefont" + msdfSuffix + depthSuffix + ".json");
+	m_colorFontMaterial = layout.color
+	    ? MaterialParser::load (project, "materials/fonts/basefontrgba" + msdfSuffix + depthSuffix + ".json")
+	    : nullptr;
+	m_backgroundMaterial = layout.background
+	    ? MaterialParser::load (project, "materials/fonts/fontbackground" + depthSuffix + ".json")
+	    : nullptr;
 	m_clearAlphaMaterial = layout.buffered && !layout.background
 	    ? MaterialParser::load (project, "materials/util/composelayer_clearalpha.json")
 	    : nullptr;
@@ -602,6 +771,15 @@ void CText::buildPasses () {
 	return;
     }
 
+    // sub_140257840: in 3D scenes the composite's material gets depthtest "enabled" unless the text disables it
+    if (m_passthroughMaterial != nullptr && layout.depth) {
+	for (const auto& pass : m_passthroughMaterial->passes) {
+	    pass->depthtest = DepthtestMode_Enabled;
+	}
+    }
+
+    m_compositePassCount = 0;
+
     m_fontOverride.combos.clear ();
 
     if (layout.outline) {
@@ -642,13 +820,25 @@ void CText::buildPasses () {
 	    m_passes.push_back (background);
 	}
 
-	auto* glyphs = this->createFontPass (this->getScene ().getFBO (), &m_glyphSceneMatrix);
+	auto* glyphs = this->createFontPass (this->getScene ().getFBO (), &m_glyphSceneMatrix, false);
 
 	if (layout.blendMode == 31) {
 	    glyphs->setBlendingMode (BlendingMode_Additive);
 	}
 
 	m_passes.push_back (glyphs);
+
+	// sub_1401B3430 draws the colour glyphs' buffer after the others
+	if (layout.color) {
+	    auto* colorGlyphs = this->createFontPass (this->getScene ().getFBO (), &m_glyphSceneMatrix, true);
+
+	    if (layout.blendMode == 31) {
+		colorGlyphs->setBlendingMode (BlendingMode_Additive);
+	    }
+
+	    m_passes.push_back (colorGlyphs);
+	}
+
 	return;
     }
 
@@ -658,20 +848,28 @@ void CText::buildPasses () {
 
     const glm::vec2 fboSize = { static_cast<float> (layout.bufferSize.x), static_cast<float> (layout.bufferSize.y) };
 
-    std::ostringstream nameA, nameB;
-    nameA << "_rt_textComposite_" << this->getId () << "_a";
-    nameB << "_rt_textComposite_" << this->getId () << "_b";
-
-    // the same buffer setup as image layers (text and image vtables share slot 23, sub_1401EA500): 16 bit float in HDR
-    // scene rendering
+    // the same buffer setup as image layers (text and image vtables share slot 23, sub_1401EA500): scene buffers named
+    // _rt_imageLayerComposite_<id>_a/_b, which layers depending on the text sample, 16 bit float in HDR scene rendering.
+    // They keep their identity when the text box changes size, whoever resolved them keeps a working buffer
     const TextureFormat format = this->getScene ().isHDR () ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
-    this->m_currentMainFBO = this->m_mainFBO
-	= this->create (nameA.str (), format, TextureFlags_ClampUVs, 1.0f, fboSize, fboSize);
-    this->m_currentSubFBO = this->m_subFBO = this->create (nameB.str (), format, TextureFlags_ClampUVs, 1.0f, fboSize, fboSize);
+    const auto sceneBuffer = [this, format, fboSize] (const std::string& suffix) {
+	auto& scene = this->getScene ();
+	const std::string name = "_rt_imageLayerComposite_" + std::to_string (this->getId ()) + suffix;
+
+	if (auto existing = scene.find (name); existing != nullptr && existing->getFormat () == format) {
+	    existing->resize (static_cast<uint32_t> (fboSize.x), static_cast<uint32_t> (fboSize.y));
+	    return existing;
+	}
+
+	return scene.create (name, format, TextureFlags_ClampUVs, 1.0f, fboSize, fboSize);
+    };
+
+    this->m_currentMainFBO = this->m_mainFBO = sceneBuffer ("_a");
+    this->m_currentSubFBO = this->m_subFBO = sceneBuffer ("_b");
 
     // sub_140257C30: the buffer starts out as the opaque background, or as the scene behind the text with alpha 0
     // (composelayer_clearalpha), so the glyphs' translucent edges blend towards what they will be drawn over
-    auto* base = this->createFontPass (m_currentMainFBO, &m_glyphBufferMatrix);
+    auto* base = this->createFontPass (m_currentMainFBO, &m_glyphBufferMatrix, false);
 
     if (layout.background) {
 	base->setClearColor (&m_backgroundColor4);
@@ -683,7 +881,7 @@ void CText::buildPasses () {
 	clear->setDestination (m_currentMainFBO);
 	clear->setInput (this->getScene ().getFBO ());
 	clear->setPosition (m_compositePosition);
-	clear->setTexCoord (m_quadTexcoords);
+	clear->setTexCoord (m_compositeTexcoords);
 	clear->setModelMatrix (&m_modelMatrix);
 	clear->setViewProjectionMatrix (&m_viewProjectionMatrix);
 	clear->setModelViewProjectionMatrix (&m_compositeMatrix);
@@ -697,6 +895,12 @@ void CText::buildPasses () {
 
     m_passes.push_back (base);
 
+    if (layout.color) {
+	auto* colorGlyphs = this->createFontPass (m_currentMainFBO, &m_glyphBufferMatrix, true);
+	colorGlyphs->setKeepDestination (true);
+	m_passes.push_back (colorGlyphs);
+    }
+
     std::shared_ptr<const TextureProvider> asInput = m_currentMainFBO;
 
     for (const auto& effect : m_text.effects) {
@@ -812,13 +1016,14 @@ void CText::buildPasses () {
 	cpass->setDestination (this->getScene ().getFBO ());
 	cpass->setInput (asInput);
 	cpass->setPosition (m_compositePosition);
-	cpass->setTexCoord (m_quadTexcoords);
+	cpass->setTexCoord (m_compositeTexcoords);
 	// the fog of the composite measures where the text is in the scene
 	cpass->setModelMatrix (m_passthroughMaterial != nullptr ? &m_compositeModel : &m_modelMatrix);
 	cpass->setViewProjectionMatrix (&m_viewProjectionMatrix);
 	cpass->setModelViewProjectionMatrix (&m_compositeMatrix);
 	cpass->setModelViewProjectionMatrixInverse (&m_compositeMatrixInverse);
 	m_passes.push_back (cpass);
+	m_compositePassCount++;
     }
 }
 
@@ -828,7 +1033,10 @@ void CText::render () {
     }
     const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
     const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
-    if (!visibility.value_or (m_text.visible->value->getBool ())) {
+    const bool visible = visibility.value_or (m_text.visible->value->getBool ());
+
+    // like images, a hidden text other layers depend on still fills its buffer, only the composite is left out
+    if (!visible && (visibility.has_value () || !m_isDependency)) {
 	return;
     }
 
@@ -897,8 +1105,10 @@ void CText::render () {
     glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
 #endif /* DEBUG */
 
-    for (auto* pass : m_passes) {
-	pass->render ();
+    const size_t passCount = visible ? m_passes.size () : m_passes.size () - std::min (m_passes.size (), m_compositePassCount);
+
+    for (size_t i = 0; i < passCount; i++) {
+	m_passes[i]->render ();
     }
 
 #if !NDEBUG
@@ -943,10 +1153,32 @@ void CText::updateTransform () {
 
     world = glm::translate (world, glm::vec3 (anchor, 0.0f));
 
-    // WE's world is y up from the bottom left, this space is centered and y down; the layout below is y up too
-    const float scene_w = getScene ().getCamera ().getWidth ();
-    const float scene_h = getScene ().getCamera ().getHeight ();
+    const auto& camera = getScene ().getCamera ();
+    // layout space is y up, first baseline at 0; sub_140258050 centers the box: x - w/2 - min(minX, 0), y + h/2 - top
+    const glm::vec3 center
+	= { -boxWidth * 0.5f - std::min (m_result.minX, 0.0f), boxHeight * 0.5f - m_result.top, 0.0f };
     const glm::mat4 flipY = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
+
+    // 3D scenes: the world matrix goes through the scene camera like models and image layers (sub_1401E8AA0),
+    // "perspective" texts through the perspective layer camera. WE's camera parallax only exists in orthographic scenes
+    if (camera.isPerspective ()) {
+	const glm::mat4 viewProjection = m_text.perspective->value->getBool ()
+	    ? camera.getPerspectiveLayerViewProjection ()
+	    : getScene ().getWorldViewProjection ();
+
+	m_glyphSceneMatrix = viewProjection * glm::translate (world, center);
+	m_glyphSceneMatrixInverse = glm::inverse (m_glyphSceneMatrix);
+	// the composite quad runs y down like in 2D
+	m_compositeModel = world * flipY;
+	m_compositeMatrix = viewProjection * m_compositeModel;
+	m_compositeMatrixInverse = glm::inverse (m_compositeMatrix);
+	this->updateBufferMatrix ();
+	return;
+    }
+
+    // WE's world is y up from the bottom left, this space is centered and y down; the layout below is y up too
+    const float scene_w = camera.getWidth ();
+    const float scene_h = camera.getHeight ();
     glm::mat4 model = flipY * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene_w * 0.5f, -scene_h * 0.5f, 0.0f))
 	* world * flipY;
 
@@ -974,28 +1206,28 @@ void CText::updateTransform () {
 	model = glm::translate (glm::mat4 (1.0f), glm::vec3 (parallaxOffset, 0.0f)) * model;
     }
 
-    const auto& camera = getScene ().getCamera ();
     // "perspective" text gets the perspective layer camera (sub_14025FAF0 -> sub_1401E5B60)
-    const glm::mat4 viewProjection = camera.isOrthogonal () && m_text.perspective->value->getBool ()
+    const glm::mat4 viewProjection = m_text.perspective->value->getBool ()
 	? camera.getPerspectiveLayerViewProjection ()
 	: camera.getProjection () * camera.getLookAt ();
-    // layout space is y up, first baseline at 0; sub_140258050 centers the box: x - w/2 - min(minX, 0), y + h/2 - top
-    const glm::vec3 center
-	= { -boxWidth * 0.5f - std::min (m_result.minX, 0.0f), boxHeight * 0.5f - m_result.top, 0.0f };
 
     m_glyphSceneMatrix = viewProjection * glm::translate (glm::scale (model, glm::vec3 (1.0f, -1.0f, 1.0f)), center);
     m_glyphSceneMatrixInverse = glm::inverse (m_glyphSceneMatrix);
     m_compositeMatrix = viewProjection * model;
     m_compositeModel = model;
     m_compositeMatrixInverse = glm::inverse (m_compositeMatrix);
+    this->updateBufferMatrix ();
+}
 
+void CText::updateBufferMatrix () {
     if (m_passLayout.buffered) {
-	// sub_140257D70: inside the buffer the box starts at the padding
+	// sub_140257D70: inside the buffer the box starts at the padding, its top on the buffer's first row like any
+	// layer buffer (what dependent layers and orientation dependent effects sample)
 	const glm::vec2 padding = this->currentPadding ();
 	const glm::vec2 size = m_passLayout.bufferSize;
 
 	m_glyphBufferMatrix = glm::translate (
-	    glm::ortho<float> (0.0f, size.x, 0.0f, size.y),
+	    glm::ortho<float> (0.0f, size.x, size.y, 0.0f),
 	    glm::vec3 (padding.x - std::min (m_result.minX, 0.0f), padding.y - m_result.bottom, 0.0f)
 	);
 	m_glyphBufferMatrixInverse = glm::inverse (m_glyphBufferMatrix);

+ 18 - 1
src/WallpaperEngine/Render/Objects/CText.h

@@ -62,6 +62,10 @@ private:
 	bool blur = false;
 	bool dropShadow = false;
 	bool background = false;
+	/** there are colour glyphs, drawn from the colour atlas with the basefontrgba materials */
+	bool color = false;
+	/** the depth tested materials (3D scenes, depthtest "enabled") */
+	bool depth = false;
 	/** effects or a blend mode: the text goes through a buffer of its box plus padding first */
 	bool buffered = false;
 	int blendMode = 0;
@@ -76,12 +80,13 @@ private:
     [[nodiscard]] glm::vec2 screenAnchorOffset () const;
     /** Scene and buffer matrices of the glyphs and the composite for this frame's transform */
     void updateTransform ();
+    void updateBufferMatrix ();
     void relayout (const std::string& text);
     void uploadGeometry ();
     void updateRenderVars ();
     void buildPasses ();
     void destroyPasses ();
-    Effects::CPass* createFontPass (const std::shared_ptr<const CFBO>& destination, const glm::mat4* mvp);
+    Effects::CPass* createFontPass (const std::shared_ptr<const CFBO>& destination, const glm::mat4* mvp, bool color);
 
     bool loadFont ();
     void initScriptLayer ();
@@ -99,7 +104,11 @@ private:
     std::string m_loadedFont;
 
     std::shared_ptr<TextureProvider> m_atlas;
+    std::shared_ptr<TextureProvider> m_colorAtlas;
+    /** MSDF mode: the colour glyphs' colours at the layout's colour scale, g_Texture1 of the colour pass */
+    std::shared_ptr<TextureProvider> m_colorTexture;
     MaterialUniquePtr m_fontMaterial;
+    MaterialUniquePtr m_colorFontMaterial;
     MaterialUniquePtr m_backgroundMaterial;
     MaterialUniquePtr m_clearAlphaMaterial;
     MaterialUniquePtr m_passthroughMaterial;
@@ -109,13 +118,21 @@ private:
     GLuint m_glyphPositions = 0;
     GLuint m_glyphTexcoords = 0;
     GLsizei m_glyphVertexCount = 0;
+    GLuint m_colorGlyphPositions = 0;
+    GLuint m_colorGlyphTexcoords = 0;
+    GLsizei m_colorGlyphVertexCount = 0;
     GLuint m_backgroundPositions = 0;
     // effect passes run FBO -> FBO with an identity matrix like CImage, the composite quad is the buffer's size
     GLuint m_passSpacePosition = 0;
     GLuint m_compositePosition = 0;
     GLuint m_quadTexcoords = 0;
+    GLuint m_compositeTexcoords = 0;
 
     std::vector<Effects::CPass*> m_passes = {};
+    /** the last passes, the ones putting the buffer onto the scene */
+    size_t m_compositePassCount = 0;
+    /** another object lists this text in its dependencies: it renders through its buffer, even while hidden */
+    bool m_isDependency = false;
 
     std::shared_ptr<const CFBO> m_mainFBO = nullptr;
     std::shared_ptr<const CFBO> m_subFBO = nullptr;

+ 120 - 25
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -274,6 +274,10 @@ std::shared_ptr<const CFBO> CPass::resolveFBO (const std::string& name) const {
 	fbo = this->m_renderable.getScene ().requireMipMappedFrameBuffer ();
     }
 
+    if (fbo == nullptr && name == "_rt_Reflection") {
+	fbo = this->m_renderable.getScene ().requireReflectionFrameBuffer ();
+    }
+
     if (fbo == nullptr) {
 	sLog.exception ("Tried to resolve and FBO without any luck: ", name);
     }
@@ -346,6 +350,8 @@ void CPass::setupRenderFramebuffer () const {
     switch (this->m_pass.cullmode) {
 	case CullingMode_Normal:
 	    glEnable (GL_CULL_FACE);
+	    // the mirrored reflection pass flips every triangle's winding
+	    glCullFace (this->m_renderable.getScene ().isRenderingReflection () ? GL_FRONT : GL_BACK);
 	    break;
 
 	case CullingMode_Disable:
@@ -729,6 +735,13 @@ void CPass::render () {
 
     this->setupRenderFramebuffer ();
     this->setupRenderTexture ();
+
+    for (const auto& [slot, resolution] : this->m_texelSources) {
+	if (resolution->x > 0.0f && resolution->y > 0.0f) {
+	    this->m_texels[slot] = glm::vec4 (1.0f / resolution->x, 1.0f / resolution->y, resolution->x, resolution->y);
+	}
+    }
+
     this->setupRenderUniforms ();
     this->setupRenderReferenceUniforms ();
 
@@ -773,6 +786,24 @@ void CPass::setPreviousInput (std::shared_ptr<const TextureProvider> input) {
     this->m_previousInput = std::move (input);
 }
 
+void CPass::setTexture (int index, std::shared_ptr<const TextureProvider> texture) {
+    const auto it = this->m_textures.find (index);
+
+    // the uniforms were set up with the pass, a texture set afterwards brings its own size
+    if (texture != nullptr) {
+	this->addUniform ("g_Texture" + std::to_string (index) + "Resolution", texture->getResolution ());
+
+	if (index > 0) {
+	    this->m_texelSources[index] = texture->getResolution ();
+	}
+    }
+
+    this->m_textures[index] = std::make_shared<TextureChainEntry> (TextureChainEntry {
+	.texture = std::move (texture),
+	.next = it != this->m_textures.end () ? it->second : nullptr,
+    });
+}
+
 void CPass::setEffectModelViewProjectionMatrix (const glm::mat4* projection) {
     this->m_effectModelViewProjectionOverride = projection;
 }
@@ -836,6 +867,8 @@ std::optional<std::reference_wrapper<std::string>> CPass::getTarget () const { r
 
 Render::Shaders::Shader* CPass::getShader () const { return this->m_shader; }
 
+bool CPass::hasGeometryStage () const { return this->m_compiled != nullptr && !this->m_compiled->geometry.empty (); }
+
 GLuint CPass::getProgramID () const { return this->m_programID; }
 
 void CPass::setGeometryCallback (
@@ -1011,8 +1044,8 @@ void CPass::setupShaders () {
 	return 0;
     };
 
-    // same for LIGHTING: the light counts of the scene's lightconfig, which the LightingV1 module is generated from.
-    // Without shadow mapping the shadow counts stay 0, like WE with its shadow setting off
+    // same for LIGHTING: the light counts of the scene's lightconfig, which the LightingV1 module is generated from
+    // (sub_1401A5C40). The shadow counts are 0 with WE's shadow setting off
     if (comboValue ("LIGHTING") != 0) {
 	const auto& lighting = scene.getLightingV1 ();
 
@@ -1020,16 +1053,25 @@ void CPass::setupShaders () {
 	this->m_combos.insert_or_assign ("LIGHTS_SPOT", lighting.spots);
 	this->m_combos.insert_or_assign ("LIGHTS_TUBE", lighting.tubes);
 	this->m_combos.insert_or_assign ("LIGHTS_DIRECTIONAL", lighting.directionals);
-	this->m_combos.insert_or_assign ("LIGHTS_SPOT_SHADOW_COOKIE", 0);
-	this->m_combos.insert_or_assign ("LIGHTS_SPOT_SHADOW", 0);
+	this->m_combos.insert_or_assign ("LIGHTS_SPOT_SHADOW_COOKIE", lighting.spotShadowCookies);
+	this->m_combos.insert_or_assign ("LIGHTS_SPOT_SHADOW", lighting.spotShadows);
 	this->m_combos.insert_or_assign ("LIGHTS_SPOT_COOKIE", lighting.spotCookies);
-	this->m_combos.insert_or_assign ("LIGHTS_DIRECTIONAL_SHADOW", 0);
-	this->m_combos.insert_or_assign ("LIGHTS_POINT_SHADOW", 0);
+	this->m_combos.insert_or_assign ("LIGHTS_DIRECTIONAL_SHADOW", lighting.directionalShadows);
+	this->m_combos.insert_or_assign ("LIGHTS_POINT_SHADOW", lighting.pointShadows);
+
+	if (lighting.spotShadowCookies + lighting.spotShadows + lighting.directionalShadows + lighting.pointShadows) {
+	    this->m_combos.insert_or_assign ("LIGHTS_SHADOW_MAPPING", 1);
+	    this->m_combos.insert_or_assign ("LIGHTS_SHADOW_MAPPING_QUALITY", scene.getShadowQuality ());
+	}
 
-	if (lighting.spotCookies != 0) {
+	if (lighting.spotShadowCookies + lighting.spotCookies != 0) {
 	    this->m_combos.insert_or_assign ("LIGHTS_COOKIE", 1);
 	}
 
+	// WE's renderer always has flag 0x1000 (sub_140110630), so every pass gets REVERSEDEPTH. Of the shaders drawn
+	// through here only the shadow cascades of common_pbr_2.h read it, the shadow matrices do use reversed depth
+	this->m_combos.insert_or_assign ("REVERSEDEPTH", 1);
+
 	this->m_compiled = this->compileShaderSources (shaderName, passTextures, overrideTextures);
 	this->m_shader = this->m_compiled->shader.get ();
     }
@@ -1065,12 +1107,12 @@ void CPass::setupShaders () {
     // passes with the same sources share one program (every particle system instance of a child would link its own
     // otherwise, hundreds in the first seconds of a rain wallpaper). Uniforms are uploaded on every draw, the sampler
     // units below are the same for all of them
-    this->m_programKey = vertex + '\0' + fragment;
+    this->m_programKey = vertex + '\0' + fragment + '\0' + this->m_compiled->geometry;
     if (const auto cached = sharedPrograms ().find (this->m_programKey); cached != sharedPrograms ().end ()) {
 	this->m_programID = cached->second.program;
 	cached->second.users++;
     } else {
-	this->m_programID = this->linkProgram (vertex, fragment, shaderName);
+	this->m_programID = this->linkProgram (vertex, fragment, this->m_compiled->geometry, shaderName);
 	sharedPrograms ().emplace (this->m_programKey, SharedProgram { this->m_programID, 1 });
     }
 
@@ -1143,10 +1185,12 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
 	compiled->passTextures, compiled->overrideTextures, shareable ? noConstants : this->m_override.constants
     );
 
-    auto [vertex, fragment]
-	= Shaders::GLSLContext::get ().toGlsl (compiled->shader->vertex (), compiled->shader->fragment (), shaderName);
-    compiled->vertex = std::move (vertex);
-    compiled->fragment = std::move (fragment);
+    auto sources = Shaders::GLSLContext::get ().toGlsl (
+	compiled->shader->vertex (), compiled->shader->fragment (), shaderName, compiled->shader->geometry ()
+    );
+    compiled->vertex = std::move (sources.vertex);
+    compiled->fragment = std::move (sources.fragment);
+    compiled->geometry = std::move (sources.geometry);
 
     if (shareable) {
 	std::erase_if (sharedShaders (), [] (const auto& entry) { return entry.second.expired (); });
@@ -1175,12 +1219,18 @@ bool CPass::releaseSharedProgram () {
     return true;
 }
 
-GLuint CPass::linkProgram (const std::string& vertex, const std::string& fragment, const std::string& shaderName) {
+GLuint CPass::linkProgram (
+    const std::string& vertex, const std::string& fragment, const std::string& geometry, const std::string& shaderName
+) {
     const GLuint vertexShaderID = compileShader (vertex.c_str (), GL_VERTEX_SHADER);
     const GLuint fragmentShaderID = compileShader (fragment.c_str (), GL_FRAGMENT_SHADER);
+    const GLuint geometryShaderID = geometry.empty () ? 0 : compileShader (geometry.c_str (), GL_GEOMETRY_SHADER);
     const GLuint program = glCreateProgram ();
     glAttachShader (program, vertexShaderID);
     glAttachShader (program, fragmentShaderID);
+    if (geometryShaderID != 0) {
+	glAttachShader (program, geometryShaderID);
+    }
     glLinkProgram (program);
     GLint result = GL_FALSE;
     int infoLogLength = 0;
@@ -1213,6 +1263,10 @@ GLuint CPass::linkProgram (const std::string& vertex, const std::string& fragmen
 
     glDeleteShader (vertexShaderID);
     glDeleteShader (fragmentShaderID);
+    if (geometryShaderID != 0) {
+	glDetachShader (program, geometryShaderID);
+	glDeleteShader (geometryShaderID);
+    }
 
     return program;
 }
@@ -1439,18 +1493,36 @@ void CPass::setupTextureUniforms () {
     this->addUniform ("g_Texture6", 6);
     this->addUniform ("g_Texture7", 7);
     this->addUniform ("g_TextureReductionScale", 1.0f);
-    this->m_texture0Resolution = *texture->getResolution ();
+    // a particle whose material failed to load has no texture at all
+    if (texture != nullptr) {
+	this->m_texture0Resolution = *texture->getResolution ();
+    }
     this->addUniform ("g_Texture0Resolution", &this->m_texture0Resolution);
 
+    // g_TextureNTexel (uniforms 71..80, sub_1400D8300): (1 / width, 1 / height, width, height) of the bound texture,
+    // (0.5, 0.5, 2, 2) for an empty slot. Sizes can change (the shadow atlas grows), so it's refreshed every draw
+    for (int slot = 0; slot < 10; slot++) {
+	this->m_texels[slot] = glm::vec4 (0.5f, 0.5f, 2.0f, 2.0f);
+	this->addUniform ("g_Texture" + std::to_string (slot) + "Texel", &this->m_texels[slot]);
+    }
+
+    this->m_texelSources[0] = &this->m_texture0Resolution;
+
     for (const auto& [textureIndex, expectedTexture] : this->m_textures) {
 	std::ostringstream namestream;
 
 	namestream << "g_Texture" << textureIndex << "Resolution";
 
 	texture = this->resolveTexture (expectedTexture->texture, textureIndex, texture);
-	const glm::vec4* res = texture->getResolution ();
+	if (texture == nullptr) {
+	    continue;
+	}
 
-	this->addUniform (namestream.str (), res);
+	this->addUniform (namestream.str (), texture->getResolution ());
+
+	if (textureIndex != 0) {
+	    this->m_texelSources[textureIndex] = texture->getResolution ();
+	}
 
 	// the mip count of a mipmapped frame buffer, REFLECTION scales its roughness LOD by it
 	if (const auto fbo = std::dynamic_pointer_cast<const CFBO> (texture);
@@ -1462,6 +1534,22 @@ void CPass::setupTextureUniforms () {
     }
 
     this->addUniform ("g_Texture0Resolution", &this->m_texture0Resolution);
+
+    // WE ORs the requirement of every texture slot the compiled program uses into the pass (sub_1401515B0); a sampled
+    // _rt_Reflection turns on the scene's reflection pass and keeps this object out of it (object flag 8)
+    auto& scene = this->m_renderable.getScene ();
+    const auto reflection = scene.find ("_rt_Reflection");
+
+    for (const auto& [index, chain] : this->m_textures) {
+	if (reflection == nullptr || chain == nullptr
+	    || chain->texture.get () != static_cast<const TextureProvider*> (reflection.get ())) {
+	    continue;
+	}
+
+	if (glGetUniformLocation (this->m_programID, ("g_Texture" + std::to_string (index)).c_str ()) != -1) {
+	    scene.addReflectionReceiver (this->m_renderable.getId ());
+	}
+    }
 }
 
 void CPass::setupUniforms () {
@@ -1496,12 +1584,19 @@ void CPass::setupUniforms () {
     addLights ("g_LTube_OriginB", lighting.tubeOriginB, lighting.tubes);
     addLights ("g_LDirectional_Color", lighting.directionalColor, lighting.directionals);
     addLights ("g_LDirectional_Direction", lighting.directionalDirection, lighting.directionals);
-    if (lighting.spotCookies > 0) {
-	this->addUniform (
-	    "g_LFeature_ShadowProjection", UniformType::Matrix4, lighting.featureProjection, lighting.spotCookies
-	);
-	addLights ("g_LFeature_ShadowProjectionTransform", lighting.featureProjectionTransform, lighting.spotCookies);
-    }
+    // WE binds the renderer's eye (+104) for every pass; lit ones get it here in the world their lighting works in
+    // (models, particles and text set their own afterwards), without it the view vector points at the origin
+    if (this->m_combos.contains ("LIGHTS_POINT")) {
+	this->addUniform ("g_EyePosition", &scene.getFog ().eyeWorld);
+    }
+    if (const int features = lighting.features (); features > 0) {
+	this->addUniform ("g_LFeature_ShadowProjection", UniformType::Matrix4, lighting.featureProjection, features);
+	addLights ("g_LFeature_ShadowProjectionTransform", lighting.featureProjectionTransform, features);
+    }
+    addLights ("g_LFeature_ShadowPointProjection", lighting.pointShadowProjection, lighting.pointShadows);
+    addLights (
+	"g_LFeature_ShadowPointProjectionTransform", lighting.pointShadowProjectionTransform, lighting.pointShadows
+    );
     this->addUniform ("g_FogDistanceColor", &scene.getFog ().distanceColor);
     this->addUniform ("g_FogDistanceParams", &scene.getFog ().distanceParams);
     this->addUniform ("g_FogHeightColor", &scene.getFog ().heightColor);
@@ -1545,8 +1640,8 @@ void CPass::setupUniforms () {
     this->addUniform ("g_LayerModelMatrix", &this->m_layerModelMatrix);
     this->addUniform ("g_NormalModelMatrix", glm::identity<glm::mat3> ());
     this->addUniform ("g_ViewProjectionMatrix", &this->m_viewProjectionMatrix);
-    this->addUniform ("g_PointerPosition", scene.getMousePosition ());
-    this->addUniform ("g_PointerPositionLast", scene.getMousePositionLast ());
+    this->addUniform ("g_PointerPosition", scene.getPointerPosition ());
+    this->addUniform ("g_PointerPositionLast", scene.getPointerPositionLast ());
     this->addUniform ("g_ParallaxPosition", scene.getParallaxPosition ());
     this->addUniform ("g_EffectTextureProjectionMatrix", &this->m_effectTextureProjectionMatrix);
     this->addUniform ("g_EffectTextureProjectionMatrixInverse", &this->m_effectTextureProjectionMatrixInverse);

+ 12 - 1
src/WallpaperEngine/Render/Objects/Effects/CPass.h

@@ -44,6 +44,8 @@ public:
     void setDestination (std::shared_ptr<const CFBO> drawTo);
     void setInput (std::shared_ptr<const TextureProvider> input);
     void setPreviousInput (std::shared_ptr<const TextureProvider> input);
+    /** Binds a texture to g_Texture<index> ahead of whatever the material or shader names for that slot */
+    void setTexture (int index, std::shared_ptr<const TextureProvider> texture);
     void setTexCoord (GLuint texcoord);
     void setPosition (GLuint position);
     void setModelViewProjectionMatrix (const glm::mat4* projection);
@@ -83,6 +85,8 @@ public:
     [[nodiscard]] const std::shared_ptr<const CFBO>& getDestination () const { return this->m_drawTo; }
     [[nodiscard]] Render::Shaders::Shader* getShader () const;
     [[nodiscard]] GLuint getProgramID () const;
+    /** The shader has a geometry stage (GS_ENABLED and a .geom, WE's particle shaders) */
+    [[nodiscard]] bool hasGeometryStage () const;
 
     // Custom geometry rendering support (for particles, etc.)
     using GeometryCallback = std::function<void ()>;
@@ -161,7 +165,10 @@ private:
     };
 
     static GLuint compileShader (const char* shader, GLuint type);
-    static GLuint linkProgram (const std::string& vertex, const std::string& fragment, const std::string& shaderName);
+    static GLuint linkProgram (
+	const std::string& vertex, const std::string& fragment, const std::string& geometry,
+	const std::string& shaderName
+    );
 
     struct SharedProgram {
 	GLuint program;
@@ -181,6 +188,7 @@ private:
 	std::unique_ptr<Render::Shaders::Shader> shader;
 	std::string vertex;
 	std::string fragment;
+	std::string geometry;
     };
     /** Compiled shaders by their inputs, alive while a pass uses them */
     static std::unordered_map<std::string, std::weak_ptr<CompiledShader>>& sharedShaders ();
@@ -308,6 +316,9 @@ private:
     std::shared_ptr<const TextureProvider> m_input = nullptr;
     std::shared_ptr<const TextureProvider> m_previousInput = nullptr;
     glm::vec4 m_texture0Resolution = {};
+    /** g_TextureNTexel values and the resolution each one follows */
+    std::map<int, glm::vec4> m_texels = {};
+    std::map<int, const glm::vec4*> m_texelSources = {};
 
     GLuint m_programID;
     /** Key of m_programID in the shared program cache (identical sources link once, see setupShaders) */

+ 1193 - 0
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -0,0 +1,1193 @@
+#include "PuppetRig.h"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstring>
+#include <limits>
+#include <set>
+#include <strings.h>
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include "WallpaperEngine/Data/Model/Project.h"
+#include "WallpaperEngine/Data/Parsers/ObjectParser.h"
+#include "WallpaperEngine/Data/Utils/BinaryReader.h"
+#include "WallpaperEngine/Data/Utils/MemoryStream.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+using namespace WallpaperEngine;
+using namespace WallpaperEngine::Render::Objects;
+using namespace WallpaperEngine::Data::Model;
+using namespace WallpaperEngine::Data::Parsers;
+using namespace WallpaperEngine::Data::Utils;
+
+extern float g_Time;
+extern float g_TimeLast;
+
+namespace {
+constexpr uint32_t PuppetClockMirror = 1;
+constexpr uint32_t PuppetClockSingle = 2;
+constexpr uint32_t PuppetClockFrameSet = 0x2000000;
+constexpr uint32_t PuppetClockPaused = 0x20000000;
+constexpr uint32_t PuppetClockStopped = 0x40000000;
+constexpr uint32_t PuppetClockBackwards = 0x80000000;
+
+// WE's timeline step (2.8.42 sub_1401A9F60, fmodf results taken from the asm): loops wrap, mirrors turn around at
+// either end, single clips stop on their end
+void stepPuppetClock (PuppetActiveAnimation& clock, float duration, float delta) {
+    if ((clock.flags & (PuppetClockPaused | PuppetClockStopped)) != 0
+	|| ((clock.flags & PuppetClockSingle) != 0 && clock.time >= duration) || duration <= 0.0f) {
+	return;
+    }
+
+    if ((clock.flags & PuppetClockBackwards) != 0) {
+	delta = -delta;
+    }
+
+    const float time = clock.time + delta;
+    clock.time = time;
+
+    if ((clock.flags & PuppetClockSingle) != 0) {
+	if (time >= duration) {
+	    clock.flags |= PuppetClockStopped;
+	    clock.time = duration;
+	}
+	return;
+    }
+
+    if ((clock.flags & PuppetClockMirror) == 0) {
+	if (time < 0.0f) {
+	    clock.time = std::fmod (time + duration, duration);
+	}
+	if (clock.time >= duration) {
+	    clock.time = std::fmod (clock.time, duration);
+	}
+	return;
+    }
+
+    if ((clock.flags & PuppetClockBackwards) != 0) {
+	if (time <= 0.0f) {
+	    clock.time = -std::fmod (time, duration);
+	    clock.flags &= ~PuppetClockBackwards;
+	}
+	return;
+    }
+
+    if (time >= duration) {
+	clock.flags |= PuppetClockBackwards;
+	clock.time = duration - std::fmod (time, duration);
+    }
+}
+
+// sub_14026C8B0: blend, faded in over the first min(duration / 2, blendtime) seconds and out over the last ones. A
+// clip that doesn't stop on its end drops the fade in once it is done
+float puppetLayerWeight (PuppetActiveAnimation& layer, float duration) {
+    const float blendTime = layer.layer->blendTime;
+    const float ramp = std::min (duration * 0.5f, blendTime);
+    const bool canFade = std::min (duration, blendTime) > std::numeric_limits<float>::epsilon ();
+    float weight = layer.layer->blend->value->getFloat ();
+
+    if (layer.blendIn) {
+	const float fade = canFade ? std::min (layer.time / ramp, 1.0f) : 1.0f;
+	weight *= fade;
+
+	if ((layer.flags & PuppetClockSingle) == 0 && fade >= 1.0f) {
+	    layer.blendIn = false;
+	}
+    }
+
+    if (layer.blendOut && canFade) {
+	weight *= std::min ((duration - layer.time) / ramp, 1.0f);
+    }
+
+    return weight;
+}
+
+struct PuppetBoneSet {
+    std::vector<PuppetBone> bones;
+    // Points at whatever section comes right after MDLS's second bone array: MDLA directly for
+    // puppets with no attachment points, or MDAT (attachment points) otherwise - the caller has to
+    // check which one it actually is.
+    size_t nextSectionOffset = 0;
+    // MDLS v2+ records after the bones, every MDLA clip carries one track per entry of each
+    uint32_t extraCount = 0;
+    uint32_t constraintCount = 0;
+};
+
+// Parses the MDLS bones (local bind-pose transforms, parent hierarchy and the per-bone physics JSON) and the
+// counts of the records after them that size the MDLA tracks. Inverse-bind matrices are derived from the bind
+// pose by walking the parent chain; the file's own copy is skipped.
+PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
+    reader.base ().seekg (static_cast<std::streamoff> (mdlsOffset), std::ios::beg);
+
+    char header[9];
+    reader.next (header, sizeof (header));
+
+    const uint32_t nextSectionOffset = reader.nextUInt32 ();
+    const uint32_t boneCount = reader.nextUInt32 ();
+
+    // A bone count this large can only be a garbage read (wrong mdlsOffset or an unrecognized MDLS
+    // layout), not a real rig
+    constexpr uint32_t maxPlausibleBoneCount = 512;
+    if (boneCount > maxPlausibleBoneCount) {
+	sLog.error ("Puppet bone count (", boneCount, ") looks implausible, skipping puppet mesh skinning");
+	return {};
+    }
+
+    PuppetBoneSet result;
+    result.nextSectionOffset = nextSectionOffset;
+    result.bones.reserve (boneCount);
+
+    for (uint32_t i = 0; i < boneCount; i++) {
+	// records start with a null-terminated name, empty for most rigs
+	std::string name = reader.nextNullTerminatedString ();
+	(void)reader.nextUInt32 (); // type, unused
+	const int parent = reader.nextInt ();
+	const uint32_t matrixBytes = reader.nextUInt32 ();
+
+	glm::mat4 bindLocal (1.0f);
+	if (matrixBytes == sizeof (float) * 16) {
+	    float m[16];
+	    for (float& value : m) {
+		value = reader.nextFloat ();
+	    }
+	    // the file stores a row-vector-convention, row-major matrix; feeding the 16 values straight
+	    // into glm's column-major constructor produces exactly its transpose, which is the
+	    // column-vector matrix glm needs to compute M * v
+	    bindLocal = glm::mat4 (
+		m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
+	    );
+	} else {
+	    // an implausible byte count here means this bone record wasn't decoded correctly; bail out
+	    // rather than seeking by an untrusted amount and reading whatever garbage follows as bones
+	    constexpr uint32_t maxPlausibleMatrixBytes = 4096;
+	    if (matrixBytes > maxPlausibleMatrixBytes) {
+		sLog.error (
+		    "Puppet bone ", i, " has an implausible matrix byte count (", matrixBytes, "), stopping here (",
+		    result.bones.size (), " bone(s) kept)"
+		);
+		break;
+	    }
+	    reader.base ().seekg (static_cast<std::streamoff> (matrixBytes), std::ios::cur);
+	}
+
+	// trailing per-bone string, jiggle/physics JSON for some rigs
+	const std::string physics = reader.nextNullTerminatedString ();
+
+	result.bones.push_back (
+	    PuppetBone { .name = std::move (name),
+			 .parent = parent,
+			 .bindLocal = bindLocal,
+			 .physics = PuppetBonePhysics::parse (physics) }
+	);
+    }
+
+    // the rest of MDLS as 2.8.42 reads it (sub_140261880), only the two counts matter here
+    const int version = std::atoi (header + 4);
+
+    if (version < 2 || result.bones.size () != boneCount) {
+	return result;
+    }
+
+    uint16_t extraCount = 0;
+    reader.next (reinterpret_cast<char*> (&extraCount), sizeof (extraCount));
+
+    for (uint16_t i = 0; i < extraCount; i++) {
+	(void)reader.nextNullTerminatedString ();
+	reader.base ().seekg (sizeof (uint32_t) * 2 + sizeof (float) * 16, std::ios::cur);
+    }
+
+    // a flag byte and then a matrix per bone and per extra record. Not the inverse bind matrices: bone 0 holds its bind
+    // world and the others their bind locals (makima.body_puppet.mdl), what WE does with them isn't traced
+    if (reader.next () != 0) {
+	reader.base ().seekg (static_cast<std::streamoff> ((boneCount + extraCount) * sizeof (float) * 16), std::ios::cur);
+    }
+
+    const uint32_t constraintCount = reader.nextUInt32 ();
+
+    for (uint32_t i = 0; i < constraintCount && reader.base ().good (); i++) {
+	reader.base ().seekg (sizeof (uint32_t) * 3, std::ios::cur);
+	const uint32_t flags = version >= 4 ? reader.nextUInt32 () : 0;
+
+	if (flags & 2) {
+	    reader.base ().seekg (sizeof (uint32_t) + sizeof (float), std::ios::cur);
+	}
+    }
+
+    if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
+	reader.base ().clear ();
+	sLog.error ("Puppet MDLS records after the bones don't fit the section, animation tracks may not line up");
+	return result;
+    }
+
+    result.extraCount = extraCount;
+    result.constraintCount = constraintCount;
+
+    // sub_140261880 goes on with two more blocks before the per bone collision capsules
+    const auto skip = [&reader] (std::streamoff bytes) { reader.base ().seekg (bytes, std::ios::cur); };
+    const auto nextUInt16 = [&reader] () {
+	uint16_t value = 0;
+	reader.next (reinterpret_cast<char*> (&value), sizeof (value));
+	return value;
+    };
+
+    const uint16_t groups = nextUInt16 ();
+    skip (sizeof (uint32_t) * groups);
+    for (uint16_t i = 0; i < groups && reader.base ().good (); i++) {
+	skip ((sizeof (uint32_t) + sizeof (float) * 3) * nextUInt16 ());
+    }
+
+    const uint16_t chains = nextUInt16 ();
+    for (uint16_t i = 0; i < chains && reader.base ().good (); i++) {
+	(void)reader.nextUInt32 ();
+	skip (sizeof (uint32_t) * reader.nextUInt32 ());
+	const uint16_t links = nextUInt16 ();
+	for (uint16_t j = 0; j < links && reader.base ().good (); j++) {
+	    (void)reader.nextUInt32 ();
+	    const uint16_t entries = nextUInt16 ();
+	    for (uint16_t k = 0; k < entries && reader.base ().good (); k++) {
+		skip (sizeof (uint32_t) * 4);
+		skip (sizeof (uint32_t) * nextUInt16 ());
+	    }
+	}
+    }
+
+    if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset
+	|| reader.next () == 0) {
+	reader.base ().clear ();
+	return result;
+    }
+
+    // a vec3 of extents and the capsule's frame in bone space (row-vector, row-major like the bind matrices)
+    for (auto& bone : result.bones) {
+	for (int axis = 0; axis < 3; axis++) {
+	    bone.capsuleExtents[axis] = reader.nextFloat ();
+	}
+	float m[16];
+	for (float& value : m) {
+	    value = reader.nextFloat ();
+	}
+	bone.capsule = glm::mat4 (
+	    m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
+	);
+	bone.hasCapsule = true;
+    }
+
+    if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
+	reader.base ().clear ();
+	sLog.error ("Puppet MDLS collision capsules don't fit the section, ignoring them");
+	for (auto& bone : result.bones) {
+	    bone.hasCapsule = false;
+	}
+    }
+
+    return result;
+}
+
+// Resolves each bone's world transform by walking up the parent chain: the MDL format doesn't
+// guarantee parents come before their children, and some rigs (puppet eyes/eyebrows) break that order
+void resolveBoneWorldTransform (
+    size_t index, const std::vector<int>& parents, const std::vector<glm::mat4>& locals, std::vector<glm::mat4>& world,
+    std::vector<bool>& resolved, std::vector<bool>& visiting
+) {
+    if (resolved[index]) {
+	return;
+    }
+
+    const int parent = parents[index];
+    // a missing parent, an out-of-range index, or a cycle back onto a bone still being resolved are
+    // all treated the same way a genuine root bone would be: no parent transform to fold in
+    if (parent < 0 || static_cast<size_t> (parent) >= parents.size () || visiting[index]) {
+	world[index] = locals[index];
+    } else {
+	visiting[index] = true;
+	resolveBoneWorldTransform (static_cast<size_t> (parent), parents, locals, world, resolved, visiting);
+	visiting[index] = false;
+	world[index] = world[static_cast<size_t> (parent)] * locals[index];
+    }
+
+    resolved[index] = true;
+}
+
+std::vector<glm::mat4>
+composeBoneWorldTransforms (const std::vector<int>& parents, const std::vector<glm::mat4>& locals) {
+    std::vector<glm::mat4> world (locals.size ());
+    std::vector<bool> resolved (locals.size (), false);
+    std::vector<bool> visiting (locals.size (), false);
+
+    for (size_t i = 0; i < locals.size (); i++) {
+	resolveBoneWorldTransform (i, parents, locals, world, resolved, visiting);
+    }
+
+    return world;
+}
+
+struct PuppetAttachmentPointSet {
+    std::vector<PuppetAttachmentPoint> points;
+    size_t mdlaOffset = 0;
+};
+
+// Parses the optional MDAT section (named attachment points other objects can follow, e.g.
+// scene.json's "attachment": "orb" - see docs/rendering/MDL_FILES.md). Keeps the points parsed so far
+// and stops at the first implausible entry, the tail of this section isn't fully understood
+PuppetAttachmentPointSet
+parsePuppetAttachmentPoints (const BinaryReader& reader, size_t mdatOffset, uint32_t boneCount) {
+    reader.base ().seekg (static_cast<std::streamoff> (mdatOffset), std::ios::beg);
+
+    char header[9];
+    reader.next (header, sizeof (header));
+
+    PuppetAttachmentPointSet result;
+    result.mdlaOffset = reader.nextUInt32 ();
+
+    uint16_t pointCount = 0;
+    reader.next (reinterpret_cast<char*> (&pointCount), sizeof (pointCount));
+
+    // The WORD trailing every point's matrix is the NEXT point's bone index: point 0's comes right
+    // after pointCount and the last point has no trailing WORD, which consumes exactly the section's
+    // declared length
+    uint16_t nextBoneIndex = 0;
+    reader.next (reinterpret_cast<char*> (&nextBoneIndex), sizeof (nextBoneIndex));
+
+    constexpr uint16_t maxPlausiblePointCount = 256;
+    if (pointCount > maxPlausiblePointCount) {
+	sLog.error ("Puppet attachment point count (", pointCount, ") looks implausible, ignoring attachment points");
+	return result;
+    }
+
+    for (uint16_t i = 0; i < pointCount; i++) {
+	const std::string name = reader.nextNullTerminatedString ();
+
+	float m[16];
+	for (float& value : m) {
+	    value = reader.nextFloat ();
+	}
+
+	const uint16_t boneIndex = nextBoneIndex;
+	if (i + 1 < pointCount) {
+	    reader.next (reinterpret_cast<char*> (&nextBoneIndex), sizeof (nextBoneIndex));
+	}
+
+	if (name.empty () || boneIndex >= boneCount) {
+	    sLog.error (
+		"Puppet attachment point ", i, " (name=", name, ", bone=", boneIndex,
+		") looks implausible, stopping here (", result.points.size (), " point(s) kept)"
+	    );
+	    break;
+	}
+
+	// same row-major-to-column-major transpose trick used for PuppetBone::bindLocal
+	const glm::mat4 localTransform (
+	    m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]
+	);
+
+	result.points.push_back (
+	    PuppetAttachmentPoint { .name = name, .boneIndex = boneIndex, .localTransform = localTransform }
+	);
+    }
+
+    return result;
+}
+
+// Parses every baked animation clip out of the MDLA section (see docs/rendering/MDL_FILES.md), laid out like
+// 2.8.42 reads it (sub_140261880). Only the bone tracks are used, everything after them is skipped by its size.
+std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
+    const BinaryReader& reader, size_t mdlaOffset, uint32_t expectedBoneCount, const PuppetBoneSet& rig,
+    uint32_t meshCount
+) {
+    reader.base ().seekg (static_cast<std::streamoff> (mdlaOffset), std::ios::beg);
+
+    char header[9];
+    reader.next (header, sizeof (header));
+    const int version = std::atoi (header + 4);
+
+    const uint32_t sectionEnd = reader.nextUInt32 ();
+    const uint32_t clipCount = reader.nextUInt32 ();
+
+    constexpr uint32_t maxPlausibleClipCount = 64;
+    if (clipCount > maxPlausibleClipCount) {
+	sLog.error ("Puppet animation clip count (", clipCount, ") looks implausible, skipping animation entirely");
+	return {};
+    }
+
+    std::vector<PuppetAnimationClip> clips;
+    clips.reserve (clipCount);
+
+    for (uint32_t clipIndex = 0; clipIndex < clipCount; clipIndex++) {
+	PuppetAnimationClip clip;
+	reader.next (reinterpret_cast<char*> (&clip.id), sizeof (clip.id));
+	clip.name = reader.nextNullTerminatedString ();
+	clip.mode = reader.nextNullTerminatedString ();
+	clip.fps = reader.nextFloat ();
+	clip.frameCount = reader.nextUInt32 ();
+	const uint32_t flags = reader.nextUInt32 ();
+	const uint32_t boneCount = reader.nextUInt32 ();
+
+	constexpr uint32_t maxPlausibleFrameCount = 100000;
+	if (clip.frameCount > maxPlausibleFrameCount || boneCount != expectedBoneCount) {
+	    sLog.error (
+		"Puppet animation clip ", clipIndex, " has an implausible frame/bone count (frames=", clip.frameCount,
+		", bones=", boneCount, ", expected ", expectedBoneCount, "), stopping here"
+	    );
+	    break;
+	}
+
+	const uint32_t sampleCount = clip.frameCount + 1;
+	bool valid = true;
+
+	// every track is a length-prefixed block of one value (or one 9-float transform) per sample
+	const auto skipTrack = [&] (uint32_t sampleBytes) {
+	    const uint32_t trackBytes = reader.nextUInt32 ();
+	    if (trackBytes != sampleCount * sampleBytes) {
+		valid = false;
+		return;
+	    }
+	    reader.base ().seekg (static_cast<std::streamoff> (trackBytes), std::ios::cur);
+	};
+	const auto skipFlaggedTracks = [&] (uint32_t count, uint32_t sampleBytes) {
+	    for (uint32_t i = 0; i < count && valid; i++) {
+		(void)reader.nextUInt32 ();
+		skipTrack (sampleBytes);
+	    }
+	};
+
+	clip.boneTracks.resize (boneCount);
+	clip.boneAnimated.assign (boneCount, true);
+
+	for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
+	    // bit 0 keeps the bone out of this clip, the blend masks it (2.8.42 sub_140261880)
+	    clip.boneAnimated[boneIndex] = (reader.nextUInt32 () & 1) == 0;
+	    const uint32_t trackBytes = reader.nextUInt32 ();
+
+	    if (trackBytes != sampleCount * 9 * sizeof (float)) {
+		valid = false;
+		break;
+	    }
+
+	    auto& track = clip.boneTracks[boneIndex];
+	    track.reserve (sampleCount);
+
+	    for (uint32_t sample = 0; sample < sampleCount; sample++) {
+		PuppetKeyframe keyframe;
+		keyframe.position = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
+		keyframe.rotation = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
+		keyframe.scale = { reader.nextFloat (), reader.nextFloat (), reader.nextFloat () };
+		// the loader turns the euler angles into a quaternion right away, same order as the matrices
+		keyframe.orientation = glm::angleAxis (keyframe.rotation.z, glm::vec3 (0.0f, 0.0f, 1.0f))
+		    * glm::angleAxis (keyframe.rotation.y, glm::vec3 (0.0f, 1.0f, 0.0f))
+		    * glm::angleAxis (keyframe.rotation.x, glm::vec3 (1.0f, 0.0f, 0.0f));
+		track.push_back (keyframe);
+	    }
+	}
+
+	if (version >= 2) {
+	    skipFlaggedTracks (rig.extraCount, 9 * sizeof (float));
+	    skipFlaggedTracks (rig.constraintCount, sizeof (float));
+	}
+
+	if (version >= 3 && valid) {
+	    skipFlaggedTracks (reader.nextUInt32 (), sizeof (float));
+
+	    if (valid && reader.next () != 0) {
+		skipFlaggedTracks (boneCount, sizeof (float));
+	    }
+	}
+
+	// per mesh morph weight tracks: a u32 whose bit 0 enables them, a u32, a u16 count and per track the target
+	// and its samples
+	if (version >= 4 && valid && reader.next () != 0) {
+	    clip.morphTracks.resize (meshCount);
+
+	    for (uint32_t mesh = 0; mesh < meshCount && valid; mesh++) {
+		if ((reader.nextUInt32 () & 1) == 0) {
+		    continue;
+		}
+
+		auto& meshTracks = clip.morphTracks[mesh];
+		meshTracks.enabled = true;
+		(void)reader.nextUInt32 ();
+		uint16_t count = 0;
+		reader.next (reinterpret_cast<char*> (&count), sizeof (count));
+
+		for (uint16_t i = 0; i < count && valid; i++) {
+		    PuppetAnimationClip::MorphTrack track;
+		    reader.next (reinterpret_cast<char*> (&track.target), sizeof (track.target));
+		    const uint32_t trackBytes = reader.nextUInt32 ();
+
+		    if (trackBytes != sampleCount * sizeof (float)) {
+			valid = false;
+			break;
+		    }
+
+		    track.samples.resize (sampleCount);
+		    for (float& sample : track.samples) {
+			sample = reader.nextFloat ();
+		    }
+
+		    meshTracks.tracks.push_back (std::move (track));
+		}
+	    }
+	}
+
+	if (version >= 5 && valid) {
+	    reader.base ().seekg (sizeof (uint32_t) * 6, std::ios::cur);
+	}
+
+	if (version >= 6 && valid && reader.next () != 0) {
+	    skipFlaggedTracks (boneCount, sizeof (float));
+	}
+
+	if ((flags & 1) && valid) {
+	    reader.base ().seekg (sizeof (uint16_t) + sizeof (uint32_t) * 4, std::ios::cur);
+	}
+
+	if (valid) {
+	    const uint32_t eventCount = reader.nextUInt32 ();
+
+	    for (uint32_t i = 0; i < eventCount && reader.base ().good (); i++) {
+		(void)reader.nextUInt32 (); // frame
+		(void)reader.nextNullTerminatedString ();
+	    }
+	}
+
+	if (!valid || !reader.base ().good ()) {
+	    reader.base ().clear ();
+	    sLog.error ("Puppet animation clip ", clip.name, " doesn't match the MDLA layout, stopping here");
+	    if (!valid) {
+		break;
+	    }
+	}
+
+	clips.push_back (std::move (clip));
+    }
+
+    if (clips.size () == clipCount && static_cast<size_t> (reader.base ().tellg ()) != sectionEnd) {
+	sLog.error (
+	    "Puppet MDLA clips end at ", static_cast<size_t> (reader.base ().tellg ()), " but the section ends at ",
+	    sectionEnd
+	);
+    }
+
+    return clips;
+}
+glm::vec3 lerp (const glm::vec3& a, const glm::vec3& b, float alpha) { return a + (b - a) * alpha; }
+} // namespace
+
+void PuppetRig::clear () {
+    *this = PuppetRig ();
+}
+
+void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t meshCount, const std::string& name) {
+    this->clear ();
+
+    auto buffer = std::make_unique<char[]> (data.size ());
+    std::copy (data.begin (), data.end (), buffer.get ());
+    const BinaryReader reader (std::make_shared<MemoryStream> (std::move (buffer), data.size ()));
+
+    auto boneSet = parsePuppetBones (reader, mdlsOffset);
+
+    std::vector<int> bindParents (boneSet.bones.size ());
+    std::vector<glm::mat4> bindLocals (boneSet.bones.size ());
+    for (size_t i = 0; i < boneSet.bones.size (); i++) {
+	bindParents[i] = boneSet.bones[i].parent;
+	bindLocals[i] = boneSet.bones[i].bindLocal;
+    }
+
+    const std::vector<glm::mat4> worldBind = composeBoneWorldTransforms (bindParents, bindLocals);
+    for (size_t i = 0; i < boneSet.bones.size (); i++) {
+	boneSet.bones[i].inverseBindWorld = glm::inverse (worldBind[i]);
+    }
+
+    this->bones = std::move (boneSet.bones);
+    this->boneModel = worldBind;
+    this->physicsState.assign (this->bones.size (), {});
+    this->hasPhysics
+	= std::ranges::any_of (this->bones, [] (const PuppetBone& bone) { return bone.physics.simulated (); });
+
+    // sub_140261880 walks the sections after MDLS in whatever order they come: every one is "TAGnnnn\0" and the absolute
+    // offset of the next one, an empty tag or the end of the file ends it. MDAT holds attachment points, MDMP morph
+    // targets (read by the model), MDLA the clips
+    size_t offset = boneSet.nextSectionOffset;
+    std::set<size_t> visited;
+
+    while (offset + 13 <= data.size () && data[offset] != 0 && visited.insert (offset).second) {
+	const std::string tag (data.data () + offset, 4);
+	uint32_t next = 0;
+	std::memcpy (&next, data.data () + offset + 9, sizeof (next));
+
+	if (tag == "MDAT") {
+	    auto attachmentSet = parsePuppetAttachmentPoints (reader, offset, static_cast<uint32_t> (this->bones.size ()));
+	    this->attachmentPoints = std::move (attachmentSet.points);
+	} else if (tag == "MDMP") {
+	    this->morphSection = offset;
+	} else if (tag == "MDLA") {
+	    this->clips
+		= parsePuppetAnimationClips (reader, offset, static_cast<uint32_t> (this->bones.size ()), boneSet, meshCount);
+	}
+
+	if (next <= offset) {
+	    sLog.error ("Section ", tag, " of ", name, " doesn't point past itself, the sections after it are skipped");
+	    break;
+	}
+
+	offset = next;
+    }
+
+    if (!this->attachmentPoints.empty ()) {
+	std::string names;
+	for (const auto& point : this->attachmentPoints) {
+	    names += (names.empty () ? "" : ", ") + point.name;
+	}
+	sLog.out ("Found ", this->attachmentPoints.size (), " attachment point(s) on ", name, ": ", names);
+    }
+}
+
+void PuppetRig::addSceneLayers (const std::vector<ImageAnimationLayerUniquePtr>& sceneLayers) {
+    // a layer plays the clip whose id is its "animation" value, layers without a match are dropped (2.8.42
+    // sub_1401FCC20); layer and clip names don't have to agree (3521337568's "j" plays "动画 1")
+    for (size_t index = 0; index < sceneLayers.size (); index++) {
+	this->addLayer (*sceneLayers[index], nullptr, index, false);
+    }
+
+    this->nextLayerSerial = sceneLayers.size ();
+
+    for (const auto& active : this->layers) {
+	sLog.out (
+	    "Playing animation ", active.clip.name, " (", active.clip.mode, ", ", active.clip.fps, " fps, ",
+	    active.clip.frameCount, " frames)"
+	);
+    }
+}
+
+std::vector<glm::mat4> PuppetRig::skinMatrices () const {
+    std::vector<glm::mat4> skin (this->bones.size ());
+
+    for (size_t i = 0; i < this->bones.size (); i++) {
+	skin[i] = (i < this->boneModel.size () ? this->boneModel[i] : glm::mat4 (1.0f)) * this->bones[i].inverseBindWorld;
+    }
+
+    return skin;
+}
+
+PuppetActiveAnimation* PuppetRig::findLayer (size_t serial) {
+    const auto it = std::ranges::find (this->layers, serial, &PuppetActiveAnimation::serial);
+
+    return it == this->layers.end () ? nullptr : &*it;
+}
+
+// sub_1401FCC20: the layer plays the clip whose id is its "animation", without one it isn't created. autosort puts it
+// after the last non-additive layer, "index" at that position (never past the last one), otherwise it goes last
+bool PuppetRig::addLayer (
+    const ImageAnimationLayer& layer, ImageAnimationLayerUniquePtr owned, size_t serial, bool autoRemove
+) {
+    if (!layer.animation) {
+	return false;
+    }
+
+    const auto id = static_cast<uint64_t> (layer.animation->value->getInt ());
+    const auto match = std::ranges::find (this->clips, id, &PuppetAnimationClip::id);
+
+    if (match == this->clips.end ()) {
+	return false;
+    }
+
+    // sub_1401A8C10: "mirror" sets flag 1, "single" flag 2, anything else loops; starts at 0, playing
+    uint32_t flags = 0;
+    if (strcasecmp (match->mode.c_str (), "mirror") == 0) {
+	flags |= PuppetClockMirror;
+    } else if (strcasecmp (match->mode.c_str (), "single") == 0) {
+	flags |= PuppetClockSingle;
+    }
+
+    PuppetActiveAnimation entry {
+	.clip = *match,
+	.layer = &layer,
+	.ownedLayer = std::move (owned),
+	.serial = serial,
+	.blendIn = layer.blendIn,
+	// only a clip that stops on its end fades out
+	.blendOut = layer.blendOut && (flags & PuppetClockSingle) != 0,
+	.autoRemove = autoRemove,
+	.flags = flags,
+    };
+
+    auto& list = this->layers;
+    auto position = list.end ();
+
+    if (layer.autosort) {
+	position = std::find_if (list.rbegin (), list.rend (), [] (const PuppetActiveAnimation& other) {
+		       return !other.layer->additive;
+		   }).base ();
+    } else if (layer.index.has_value () && !list.empty ()) {
+	const auto index = std::clamp<int64_t> (*layer.index, 0, static_cast<int64_t> (list.size ()) - 1);
+	position = list.begin () + index;
+    }
+
+    list.insert (position, std::move (entry));
+    return true;
+}
+
+size_t PuppetRig::getLayerCount () const { return this->layers.size (); }
+
+std::optional<size_t> PuppetRig::getLayerAt (int64_t index) const {
+    if (index < 0 || index >= static_cast<int64_t> (this->layers.size ())) {
+	return std::nullopt;
+    }
+
+    return this->layers[static_cast<size_t> (index)].serial;
+}
+
+std::optional<size_t> PuppetRig::findLayerByName (const std::string& name) const {
+    // sub_14020E910 keeps the last layer with that name
+    std::optional<size_t> result = std::nullopt;
+
+    if (name.empty ()) {
+	return result;
+    }
+
+    for (const auto& layer : this->layers) {
+	if (layer.layer->name == name) {
+	    result = layer.serial;
+	}
+    }
+
+    return result;
+}
+
+// sub_14020EA30: a config without blendin/blendout fades both ways. A clip name looks the clip up by name and puts its
+// id into the config, an object is the layer JSON itself with the config's keys written over it
+std::optional<size_t> PuppetRig::createLayer (
+    const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove, const Project& project
+) {
+    if (this->clips.empty ()) {
+	return std::nullopt;
+    }
+
+    auto settings = config.is_object () ? config : Data::JSON::JSON::object ();
+
+    if (!settings.contains ("blendin")) {
+	settings["blendin"] = true;
+    }
+    if (!settings.contains ("blendout")) {
+	settings["blendout"] = true;
+    }
+
+    Data::JSON::JSON layerJson;
+
+    if (animation.is_string ()) {
+	const auto name = animation.get<std::string> ();
+	const auto clip = std::ranges::find (this->clips, name, &PuppetAnimationClip::name);
+
+	if (name.empty () || clip == this->clips.end () || clip->id == 0) {
+	    return std::nullopt;
+	}
+
+	layerJson = std::move (settings);
+	layerJson["animation"] = clip->id;
+    } else if (animation.is_object ()) {
+	layerJson = animation;
+
+	for (const auto& [key, value] : settings.items ()) {
+	    layerJson[key] = value;
+	}
+    } else {
+	return std::nullopt;
+    }
+
+    if (!layerJson.contains ("animation") || !layerJson["animation"].is_number ()) {
+	return std::nullopt;
+    }
+
+    const size_t serial = this->nextLayerSerial++;
+
+    // sub_1401A38F0 hands out a fresh id when the config has none
+    if (!layerJson.contains ("id") || !layerJson["id"].is_number ()) {
+	layerJson["id"] = static_cast<int> (serial);
+    }
+
+    ImageAnimationLayerUniquePtr owned;
+
+    try {
+	owned = ObjectParser::parseAnimationLayer (layerJson, project);
+    } catch (const std::exception& ex) {
+	sLog.error ("createAnimationLayer: invalid layer config: ", ex.what ());
+	return std::nullopt;
+    }
+
+    const auto& layer = *owned;
+
+    if (!this->addLayer (layer, std::move (owned), serial, autoRemove)) {
+	return std::nullopt;
+    }
+
+    return serial;
+}
+
+bool PuppetRig::destroyLayersByName (const std::string& name) {
+    if (name.empty ()) {
+	return false;
+    }
+
+    return std::erase_if (this->layers, [&name] (const PuppetActiveAnimation& layer) {
+	       return layer.layer->name == name;
+	   })
+	> 0;
+}
+
+bool PuppetRig::destroyLayer (size_t serial) {
+    return std::erase_if (this->layers, [serial] (const PuppetActiveAnimation& layer) {
+	       return layer.serial == serial;
+	   })
+	> 0;
+}
+
+// sub_1401FDF90, after the pose: a layer that ended runs its ended callbacks, a playSingleAnimation() one is removed
+void PuppetRig::finishEndedLayers (const std::function<void (size_t)>& dispatch) {
+    std::vector<size_t> ended;
+
+    for (const auto& layer : this->layers) {
+	if (layer.ended) {
+	    ended.push_back (layer.serial);
+	}
+    }
+
+    // callbacks may create or destroy layers, so layers are looked up again by serial
+    for (const size_t serial : ended) {
+	dispatch (serial);
+    }
+
+    std::erase_if (this->layers, [&ended] (const PuppetActiveAnimation& layer) {
+	return layer.autoRemove && std::ranges::find (ended, layer.serial) != ended.end ();
+    });
+}
+
+void PuppetRig::updateMorphWeights (const std::vector<PuppetLayerSample>& samples) {
+    // sub_14021C480: every mesh's weights start at zero each frame, then the layers apply theirs in order. A layer at
+    // full weight sets them (a weight of about 0 switches the target off), additive ones add theirs kept between
+    // the two values, the others blend towards theirs and clamp to 0..1. Layers at zero weight are skipped
+    for (auto& mesh : this->morphWeights) {
+	mesh.active = 0;
+	std::ranges::fill (mesh.weights, 0.0f);
+    }
+
+    constexpr float epsilon = 1.1920929e-7f;
+
+    for (const auto& sample : samples) {
+	if (sample.weight == 0.0f) {
+	    continue;
+	}
+
+	const bool direct = sample.weight == 1.0f && !sample.additive;
+	const auto& meshes = sample.clip->morphTracks;
+
+	if (this->morphWeights.size () < meshes.size ()) {
+	    this->morphWeights.resize (meshes.size ());
+	}
+
+	for (size_t mesh = 0; mesh < meshes.size (); mesh++) {
+	    if (!meshes[mesh].enabled) {
+		continue;
+	    }
+
+	    auto& state = this->morphWeights[mesh];
+
+	    for (const auto& track : meshes[mesh].tracks) {
+		if (track.target >= 64 || track.samples.size () <= sample.frame1) {
+		    continue;
+		}
+
+		if (state.weights.size () <= track.target) {
+		    state.weights.resize (track.target + 1, 0.0f);
+		}
+
+		const float value = (1.0f - sample.alpha) * track.samples[sample.frame0] + sample.alpha * track.samples[sample.frame1];
+		const uint64_t bit = uint64_t (1) << track.target;
+		float& weight = state.weights[track.target];
+
+		if (direct) {
+		    if (std::abs (value) < epsilon) {
+			state.active &= ~bit;
+		    } else {
+			state.active |= bit;
+			weight = value;
+		    }
+		} else if (sample.additive) {
+		    if (std::abs (value) >= epsilon) {
+			const float added = value * sample.weight;
+			state.active |= bit;
+			weight = std::clamp (weight + added, std::min (weight, added), std::max (weight, added));
+		    }
+		} else {
+		    if (std::abs (value) >= epsilon) {
+			state.active |= bit;
+		    }
+
+		    weight = std::clamp ((1.0f - sample.weight) * weight + sample.weight * value, 0.0f, 1.0f);
+		}
+	    }
+	}
+    }
+}
+
+void PuppetRig::updatePose (const glm::mat4& objectWorld) {
+    if (this->bones.empty ()) {
+	return;
+    }
+
+    // WE's layer blend (2.8.42 sub_1401FDF90): each bone starts from its rest pose (the MDLS bind matrix as
+    // position, rotation and scale) and every visible layer in order blends towards its clip's sample
+    // (sub_1401F9020) or, when additive, adds the sample's difference from the rest pose (sub_1401F9820).
+    // Bones whose track is flagged off in a clip keep what they have.
+    // every layer runs its own clock, stepped by dt * rate while the layer is visible (sub_1401FDF90)
+    const float dt = this->clockTime < 0.0f ? 0.0f : std::max (g_Time - this->clockTime, 0.0f);
+    this->clockTime = g_Time;
+
+    std::vector<PuppetLayerSample> samples;
+    for (auto& candidate : this->layers) {
+	candidate.ended = false;
+
+	if (candidate.layer == nullptr || !candidate.layer->visible->value->getBool ()) {
+	    continue;
+	}
+
+	const auto& clip = candidate.clip;
+	if (clip.fps <= 0.0f || clip.frameCount == 0) {
+	    continue;
+	}
+
+	const float frameTime = 1.0f / clip.fps;
+	const float duration = static_cast<float> (clip.frameCount) * frameTime;
+
+	const uint32_t previousFlags = candidate.flags;
+	const float previousTime = candidate.time;
+	stepPuppetClock (candidate, duration, dt * candidate.layer->rate->value->getFloat ());
+
+	// a layer ends when a single clip stops, a mirror turns around or a loop wraps, unless it was paused, stopped
+	// or moved by setFrame() since the last step
+	if ((previousFlags & (PuppetClockFrameSet | PuppetClockPaused | PuppetClockStopped)) == 0) {
+	    if ((candidate.flags & PuppetClockSingle) != 0) {
+		candidate.ended = (candidate.flags & PuppetClockStopped) != 0;
+	    } else if ((candidate.flags & PuppetClockMirror) != 0) {
+		candidate.ended = (previousFlags & PuppetClockBackwards) != (candidate.flags & PuppetClockBackwards);
+	    } else {
+		candidate.ended = previousTime > candidate.time;
+	    }
+	}
+	candidate.flags &= ~PuppetClockFrameSet;
+
+	const float time = candidate.time;
+
+	// sub_140170580
+	const int lastFrame = static_cast<int> (clip.frameCount) - 1;
+	const int frame0 = std::clamp (static_cast<int> (time / frameTime), 0, lastFrame);
+	samples.push_back (
+	    PuppetLayerSample { .clip = &clip,
+				.frame0 = static_cast<uint32_t> (frame0),
+				.frame1 = std::min (static_cast<uint32_t> (frame0 + 1), clip.frameCount),
+				.alpha = std::fmod (time, frameTime) / frameTime,
+				.weight = puppetLayerWeight (candidate, duration),
+				.additive = candidate.layer->additive }
+	);
+    }
+
+    this->poseAnimated = !samples.empty () || this->hasPhysics || this->poseScripted;
+
+    // q and -q are the same rotation, blends take the one on the same side
+    const auto nlerp = [] (const glm::quat& a, glm::quat b, float t) {
+	if (glm::dot (a, b) < 0.0f) {
+	    b = -b;
+	}
+	return glm::normalize (a * (1.0f - t) + b * t);
+    };
+
+    std::vector<int> animatedParents (this->bones.size ());
+    std::vector<glm::mat4> animatedLocals (this->bones.size ());
+
+    for (size_t i = 0; i < this->bones.size (); i++) {
+	const auto& bone = this->bones[i];
+	animatedParents[i] = bone.parent;
+
+	// no animation layer playing, physics runs on the bind pose like WE
+	if (samples.empty ()) {
+	    animatedLocals[i] = bone.bindLocal;
+	    continue;
+	}
+
+	const glm::vec3 restPosition (bone.bindLocal[3]);
+	const glm::vec3 restScale (
+	    glm::length (glm::vec3 (bone.bindLocal[0])), glm::length (glm::vec3 (bone.bindLocal[1])),
+	    glm::length (glm::vec3 (bone.bindLocal[2]))
+	);
+	const glm::quat restOrientation = glm::normalize (glm::quat_cast (glm::mat3 (
+	    glm::vec3 (bone.bindLocal[0]) / restScale.x, glm::vec3 (bone.bindLocal[1]) / restScale.y,
+	    glm::vec3 (bone.bindLocal[2]) / restScale.z
+	)));
+
+	glm::vec3 position = restPosition;
+	glm::vec3 scale = restScale;
+	glm::quat orientation = restOrientation;
+
+	for (const auto& sample : samples) {
+	    const auto& clip = *sample.clip;
+	    if (i >= clip.boneTracks.size () || clip.boneTracks[i].size () <= sample.frame1
+		|| (i < clip.boneAnimated.size () && !clip.boneAnimated[i])) {
+		continue;
+	    }
+
+	    const auto& from = clip.boneTracks[i][sample.frame0];
+	    const auto& to = clip.boneTracks[i][sample.frame1];
+	    const glm::vec3 samplePosition = lerp (from.position, to.position, sample.alpha);
+	    const glm::vec3 sampleScale = lerp (from.scale, to.scale, sample.alpha);
+	    const glm::quat sampleOrientation = nlerp (from.orientation, to.orientation, sample.alpha);
+	    const float weight = sample.weight;
+
+	    if (sample.additive) {
+		position += (samplePosition - restPosition) * weight;
+		scale += (sampleScale - restScale) * weight;
+		const glm::quat delta = glm::conjugate (restOrientation) * sampleOrientation;
+		orientation = orientation * nlerp (glm::quat (1.0f, 0.0f, 0.0f, 0.0f), delta, weight);
+	    } else {
+		position = position * (1.0f - weight) + samplePosition * weight;
+		scale = scale * (1.0f - weight) + sampleScale * weight;
+		orientation = nlerp (orientation, sampleOrientation, weight);
+	    }
+	}
+
+	animatedLocals[i] = glm::translate (glm::mat4 (1.0f), position) * glm::mat4_cast (orientation)
+	    * glm::scale (glm::mat4 (1.0f), scale);
+    }
+
+    this->composePose (animatedParents, animatedLocals, objectWorld);
+    this->updateMorphWeights (samples);
+}
+
+void PuppetRig::composePose (
+    const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld
+) {
+    const size_t count = parents.size ();
+    const float dt = std::max (g_Time - g_TimeLast, 0.0f);
+
+    // sub_1401FDF90 swaps the current and previous scene matrices first, so whatever a script wrote into the current
+    // ones last frame is what the physics compares against
+    const bool hasPrevious = this->boneScene.size () == count;
+    if (hasPrevious) {
+	this->physicsPreviousScene = this->boneScene;
+    }
+
+    // WE runs the physics on the bones' scene transforms (object world * bone)
+    const glm::mat4& object = objectWorld;
+    const float objectScale
+	= (glm::length (glm::vec3 (object[0])) + glm::length (glm::vec3 (object[1])) + glm::length (glm::vec3 (object[2])))
+	/ 3.0f;
+
+    std::vector<glm::mat4> model (count);
+    std::vector<glm::mat4> scene (count);
+    std::vector<uint8_t> resolved (count, 0);
+
+    // parents first, a simulated parent moves its children
+    const auto resolve = [&] (const auto& self, size_t index) -> void {
+	if (resolved[index] != 0) {
+	    return;
+	}
+
+	resolved[index] = 1;
+	const int parent = parents[index];
+
+	if (parent >= 0 && static_cast<size_t> (parent) < count && resolved[parent] != 1) {
+	    self (self, static_cast<size_t> (parent));
+	    model[index] = model[parent] * locals[index];
+	} else {
+	    model[index] = locals[index];
+	}
+
+	scene[index] = object * model[index];
+	const auto& physics = this->bones[index].physics;
+
+	// the first frame has nothing to compare against and only records where the bones are
+	if (physics.simulated () && hasPrevious) {
+	    model[index] = model[index]
+		* stepPuppetBonePhysics (
+			       physics, this->physicsState[index], scene[index],
+			       this->physicsPreviousScene[index], dt, objectScale
+		);
+	    scene[index] = object * model[index];
+	}
+
+	resolved[index] = 2;
+    };
+
+    for (size_t i = 0; i < count; i++) {
+	resolve (resolve, i);
+    }
+
+    this->boneLocal = locals;
+    this->boneModel = std::move (model);
+    this->boneScene = std::move (scene);
+}
+
+bool PuppetRig::hasPose () const {
+    return !this->bones.empty () && this->boneScene.size () == this->bones.size ();
+}
+
+int PuppetRig::findBone (const std::string& name) const {
+    for (size_t i = 0; i < this->bones.size (); i++) {
+	if (this->bones[i].name == name) {
+	    return static_cast<int> (i);
+	}
+    }
+
+    return -1;
+}
+
+const glm::mat4& PuppetRig::getBoneTransform (int bone) const { return this->boneScene[bone]; }
+
+void PuppetRig::setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld) {
+    // sub_14020F350: only this bone, its children keep their matrices until the next update
+    this->boneScene[bone] = transform;
+    this->boneModel[bone] = glm::inverse (objectWorld) * transform;
+    this->poseScripted = true;
+    this->poseAnimated = true;
+}
+
+const glm::mat4& PuppetRig::getLocalBoneTransform (int bone) const { return this->boneLocal[bone]; }
+
+void PuppetRig::setLocalBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld) {
+    this->boneLocal[bone] = transform;
+
+    // sub_14020DB40: the bone and every later bone whose parent was touched, in index order
+    const glm::mat4& object = objectWorld;
+    std::set<int> touched;
+
+    const int count = static_cast<int> (this->bones.size ());
+
+    for (int index = bone; index < count; index++) {
+	const int parent = this->bones[index].parent;
+
+	if (index != bone && !touched.contains (parent)) {
+	    continue;
+	}
+
+	touched.insert (index);
+	this->boneModel[index] = parent < 0 || parent >= count
+	    ? this->boneLocal[index]
+	    : this->boneModel[parent] * this->boneLocal[index];
+	this->boneScene[index] = object * this->boneModel[index];
+    }
+
+    this->poseScripted = true;
+    this->poseAnimated = true;
+}
+
+void PuppetRig::applyBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees) {
+    if (bone >= 0 && static_cast<size_t> (bone) < this->physicsState.size ()) {
+	applyPuppetBoneImpulse (this->physicsState[bone], directional, angularDegrees);
+    }
+}
+
+void PuppetRig::resetBonePhysics (int bone) {
+    // sub_140210E10
+    if (bone >= 0 && static_cast<size_t> (bone) < this->physicsState.size ()) {
+	this->physicsState[bone] = {};
+    }
+}

+ 194 - 0
src/WallpaperEngine/Render/Objects/PuppetRig.h

@@ -0,0 +1,194 @@
+#pragma once
+
+#include "PuppetPhysics.h"
+
+#include "WallpaperEngine/Data/JSON.h"
+#include "WallpaperEngine/Data/Model/Object.h"
+
+#include <functional>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include <glm/glm.hpp>
+#include <glm/gtc/quaternion.hpp>
+
+namespace WallpaperEngine::Data::Model {
+struct Project;
+}
+
+namespace WallpaperEngine::Render::Objects {
+/** A skeleton bone, parsed from the MDLS section of a .mdl */
+struct PuppetBone {
+    std::string name;
+    int parent = -1;
+    /** Local bind-pose transform, relative to the parent bone (identity for a root bone's "world" reference) */
+    glm::mat4 bindLocal { 1.0f };
+    /** Inverse of the bone's bind-pose world transform, derived by walking the parent chain */
+    glm::mat4 inverseBindWorld { 1.0f };
+    PuppetBonePhysics physics {};
+    /** The bone's collision capsule (MDLS, what collisionmodel particles hit): extents, and its frame in bone space */
+    bool hasCapsule = false;
+    glm::vec3 capsuleExtents { 0.0f };
+    glm::mat4 capsule { 1.0f };
+};
+
+/** A single sampled TRS pose for one bone at one point in time, from the MDLA section */
+struct PuppetKeyframe {
+    glm::vec3 position {};
+    glm::vec3 rotation {};
+    glm::vec3 scale { 1.0f };
+    /** rotation as WE blends it, Rz * Ry * Rx */
+    glm::quat orientation { 1.0f, 0.0f, 0.0f, 0.0f };
+};
+
+/** A baked animation clip: one keyframe track per bone, sampled at a fixed rate */
+struct PuppetAnimationClip {
+    /** what animationlayers[].animation refers to */
+    uint64_t id = 0;
+    std::string name;
+    std::string mode;
+    float fps = 30.0f;
+    uint32_t frameCount = 0;
+    /** [boneIndex][sampleIndex], each track has frameCount+1 samples */
+    std::vector<std::vector<PuppetKeyframe>> boneTracks;
+    /** per bone, false when its track flags have bit 0 set: the clip leaves that bone alone */
+    std::vector<bool> boneAnimated;
+
+    /** a morph target's weight over the clip, one sample per frame like the bone tracks */
+    struct MorphTrack {
+	uint16_t target = 0;
+	std::vector<float> samples;
+    };
+    /** MDLA v4+, per mesh of the model: whether the clip drives its morph weights and the tracks doing it */
+    struct MeshMorphTracks {
+	bool enabled = false;
+	std::vector<MorphTrack> tracks;
+    };
+    std::vector<MeshMorphTracks> morphTracks;
+};
+
+/** One mesh's morph target weights this frame (WE model state +96: a bit per active target and the weights) */
+struct PuppetMorphWeights {
+    uint64_t active = 0;
+    std::vector<float> weights;
+};
+
+/** A named point on a puppet's rig that other objects can follow via scene.json's "attachment" field */
+struct PuppetAttachmentPoint {
+    std::string name;
+    int boneIndex = -1;
+    /** Transform of the point relative to its bone, in the same convention as PuppetBone::bindLocal */
+    glm::mat4 localTransform { 1.0f };
+};
+
+/** One of an object's animationlayers[] entries, paired with the baked clip it plays and its own clock (WE's layer
+ *  timeline, sub_1401A8C10 / sub_1401A9F60) */
+struct PuppetActiveAnimation {
+    PuppetAnimationClip clip;
+    const WallpaperEngine::Data::Model::ImageAnimationLayer* layer = nullptr;
+    /** layers made by createAnimationLayer()/playSingleAnimation() own their settings */
+    WallpaperEngine::Data::Model::ImageAnimationLayerUniquePtr ownedLayer = nullptr;
+    /** stable handle for scripts: the index in the object's animationlayers[] for scene layers, counted on from
+     *  there for created ones */
+    size_t serial = 0;
+    /** fade flags (+208 bits 4 and 8), blendin drops once a non-single clip has faded in */
+    bool blendIn = false;
+    bool blendOut = false;
+    /** playSingleAnimation(): removed once it ends (0x8000000) */
+    bool autoRemove = false;
+    /** seconds into the clip */
+    float time = 0.0f;
+    /** 1 mirror, 2 single, 0x2000000 frame set by a script, 0x20000000 paused, 0x40000000 stopped, sign bit mirror
+     *  playing backwards */
+    uint32_t flags = 0;
+    /** reached its end in this frame's update, for IAnimationLayer.addEndedCallback() */
+    bool ended = false;
+};
+
+/** A visible layer's place in its clip this frame: the two frames around it and how far between them */
+struct PuppetLayerSample {
+    const PuppetAnimationClip* clip;
+    uint32_t frame0;
+    uint32_t frame1;
+    float alpha;
+    float weight;
+    bool additive;
+};
+
+/**
+ * The skeleton, animation layers and bone physics of a puppet image or a 3D model. Both run the same pose update in
+ * wallpaper64.exe 2.8.42 (images sub_1401FDF90, models sub_14021C480): every bone starts at its rest pose, visible
+ * layers blend their clips in, physics runs on the bones' scene transforms
+ */
+class PuppetRig {
+public:
+    /** Reads MDLS at mdlsOffset and the MDAT/MDLA sections it leads to (sub_140261880). Throws on a broken file */
+    void load (const std::vector<char>& data, size_t mdlsOffset, uint32_t meshCount, const std::string& name);
+    void clear ();
+
+    [[nodiscard]] PuppetActiveAnimation* findLayer (size_t serial);
+    /** sub_1401FCC20: plays the clip whose id is the layer's "animation", false without one */
+    bool addLayer (
+	const Data::Model::ImageAnimationLayer& layer, Data::Model::ImageAnimationLayerUniquePtr owned, size_t serial,
+	bool autoRemove
+    );
+    /** The object's animationlayers[], serials are their indices */
+    void addSceneLayers (const std::vector<Data::Model::ImageAnimationLayerUniquePtr>& layers);
+    [[nodiscard]] size_t getLayerCount () const;
+    [[nodiscard]] std::optional<size_t> getLayerAt (int64_t index) const;
+    [[nodiscard]] std::optional<size_t> findLayerByName (const std::string& name) const;
+    std::optional<size_t> createLayer (
+	const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove,
+	const Data::Model::Project& project
+    );
+    bool destroyLayersByName (const std::string& name);
+    bool destroyLayer (size_t serial);
+    /** After the pose: every layer that ended runs dispatch (its ended callbacks), playSingleAnimation() ones go */
+    void finishEndedLayers (const std::function<void (size_t)>& dispatch);
+
+    /** Steps the layer clocks and builds this frame's pose, objectWorld is the object's world matrix */
+    void updatePose (const glm::mat4& objectWorld);
+    void updateMorphWeights (const std::vector<PuppetLayerSample>& samples);
+    void composePose (
+	const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld
+    );
+
+    [[nodiscard]] bool hasPose () const;
+    [[nodiscard]] int findBone (const std::string& name) const;
+    [[nodiscard]] const glm::mat4& getBoneTransform (int bone) const;
+    void setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
+    [[nodiscard]] const glm::mat4& getLocalBoneTransform (int bone) const;
+    void setLocalBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
+    void applyBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees);
+    void resetBonePhysics (int bone);
+    /** model space bone matrices times the inverse bind ones, what the vertices are skinned with */
+    [[nodiscard]] std::vector<glm::mat4> skinMatrices () const;
+    /** Where the file's MDMP section (morph targets) starts, 0 without one */
+    [[nodiscard]] size_t getMorphSection () const { return this->morphSection; }
+
+    std::vector<PuppetBone> bones = {};
+    std::vector<PuppetAnimationClip> clips = {};
+    std::vector<PuppetAttachmentPoint> attachmentPoints = {};
+    std::vector<PuppetActiveAnimation> layers = {};
+    /** per mesh, rebuilt by every updatePose () (sub_14021C480) */
+    std::vector<PuppetMorphWeights> morphWeights = {};
+    size_t morphSection = 0;
+    /** the bones in model space (WE images P+712), starts at the bind pose */
+    std::vector<glm::mat4> boneModel = {};
+    /** this frame's local matrices (P+784) and scene matrices (P+832), empty until the first update */
+    std::vector<glm::mat4> boneLocal = {};
+    std::vector<glm::mat4> boneScene = {};
+    /** Bone physics state and last frame's scene transforms, empty until the first frame */
+    std::vector<PuppetBonePhysicsState> physicsState = {};
+    std::vector<glm::mat4> physicsPreviousScene = {};
+    bool hasPhysics = false;
+    size_t nextLayerSerial = 0;
+    /** g_Time of the last clock step, so a scene drawn on several outputs steps once per frame */
+    float clockTime = -1.0f;
+    /** a script wrote bone matrices, the mesh has to be skinned from then on */
+    bool poseScripted = false;
+    /** the pose differs from the bind pose (animation, physics or scripts) */
+    bool poseAnimated = false;
+};
+} // namespace WallpaperEngine::Render::Objects

+ 436 - 55
src/WallpaperEngine/Render/Objects/TextLayout.cpp

@@ -188,6 +188,118 @@ int outlineCubicTo (const FT_Vector* control1, const FT_Vector* control2, const
 
     return 0;
 }
+
+constexpr float kDistanceInfinity = 1e20f;
+
+// sub_1401AC130: Felzenszwalb's 1D squared distance transform of f in place (float, like WE's)
+void distanceTransform1D (std::vector<float>& f, std::vector<float>& d, std::vector<int>& v, std::vector<float>& z) {
+    const int n = static_cast<int> (f.size ());
+
+    if (n <= 0) {
+	return;
+    }
+
+    int k = 0;
+    v[0] = 0;
+    z[0] = -kDistanceInfinity;
+    z[1] = kDistanceInfinity;
+
+    for (int q = 1; q < n; q++) {
+	const float fq = static_cast<float> (q) * static_cast<float> (q) + f[q];
+	float s = (fq - (static_cast<float> (v[k]) * static_cast<float> (v[k]) + f[v[k]]))
+	    / static_cast<float> (2 * (q - v[k]));
+
+	while (s <= z[k]) {
+	    k--;
+	    s = (fq - (static_cast<float> (v[k]) * static_cast<float> (v[k]) + f[v[k]]))
+		/ static_cast<float> (2 * (q - v[k]));
+	}
+
+	k++;
+	v[k] = q;
+	z[k] = s;
+	z[k + 1] = kDistanceInfinity;
+    }
+
+    k = 0;
+
+    for (int q = 0; q < n; q++) {
+	while (static_cast<float> (q) > z[k + 1]) {
+	    k++;
+	}
+
+	d[q] = static_cast<float> ((q - v[k]) * (q - v[k])) + f[v[k]];
+    }
+
+    f = d;
+}
+
+// sub_1401AC3B0: squared distances to the nearest 0 cell, columns first, then rows
+void distanceTransform2D (std::vector<float>& grid, int width, int height) {
+    const int longest = std::max (width, height);
+    std::vector<float> line;
+    std::vector<float> scratch (longest);
+    std::vector<int> v (longest);
+    std::vector<float> z (longest + 1);
+
+    for (int x = 0; x < width; x++) {
+	line.resize (height);
+	scratch.resize (height);
+
+	for (int y = 0; y < height; y++) {
+	    line[y] = grid[x + y * width];
+	}
+
+	distanceTransform1D (line, scratch, v, z);
+
+	for (int y = 0; y < height; y++) {
+	    grid[x + y * width] = line[y];
+	}
+    }
+
+    for (int y = 0; y < height; y++) {
+	line.assign (grid.begin () + static_cast<long> (y) * width, grid.begin () + static_cast<long> (y + 1) * width);
+	scratch.resize (width);
+	distanceTransform1D (line, scratch, v, z);
+	std::ranges::copy (line, grid.begin () + static_cast<long> (y) * width);
+    }
+}
+
+// sub_1401AC4E0: bilinear sample of a BGRA bitmap at pixel coordinates, RGBA out, transparent outside it
+void sampleBitmapBGRA (const FT_Bitmap& bitmap, float x, float y, uint8_t* out) {
+    const int maxX = static_cast<int> (bitmap.width) - 1;
+    const int maxY = static_cast<int> (bitmap.rows) - 1;
+
+    if (x < 0.0f || x > static_cast<float> (maxX) || y < 0.0f || y > static_cast<float> (maxY)) {
+	out[0] = out[1] = out[2] = out[3] = 0;
+	return;
+    }
+
+    const float floorX = std::floor (x);
+    const float floorY = std::floor (y);
+    const float fx = x - floorX;
+    const float fy = y - floorY;
+    const int x0 = static_cast<int> (floorX);
+    const int y0 = static_cast<int> (floorY);
+    const int x1 = std::min (x0 + 1, maxX);
+    const int y1 = std::min (y0 + 1, maxY);
+    const uint8_t* row0 = bitmap.buffer + static_cast<long> (y0) * bitmap.pitch;
+    const uint8_t* row1 = bitmap.buffer + static_cast<long> (y1) * bitmap.pitch;
+    uint8_t texel[4];
+
+    for (int channel = 0; channel < 4; channel++) {
+	const float value = static_cast<float> (row0[x1 * 4 + channel]) * ((1.0f - fy) * fx)
+	    + static_cast<float> (row0[x0 * 4 + channel]) * ((1.0f - fy) * (1.0f - fx))
+	    + static_cast<float> (row1[x0 * 4 + channel]) * ((1.0f - fx) * fy)
+	    + static_cast<float> (row1[x1 * 4 + channel]) * (fy * fx);
+	texel[channel] = static_cast<uint8_t> (std::clamp (static_cast<int> (value + 0.5f), 0, 255));
+    }
+
+    out[0] = texel[2];
+    out[1] = texel[1];
+    out[2] = texel[0];
+    out[3] = texel[3];
+}
 } // namespace
 
 TextLayout::TextLayout () {
@@ -196,7 +308,8 @@ TextLayout::TextLayout () {
 	sLog.error ("TextLayout: FT_Init_FreeType failed");
     }
 
-    m_atlasPixels.assign (static_cast<size_t> (m_atlasSize) * m_atlasSize, 0);
+    m_colorAtlas.channels = 4;
+    this->resetAtlases ();
 }
 
 TextLayout::~TextLayout () {
@@ -218,18 +331,25 @@ void TextLayout::clearFaces () {
     }
 
     m_faces.clear ();
+    m_fallbacksLoaded = false;
     m_fallbackTried.clear ();
     m_boxes.clear ();
     m_glyphs.clear ();
-    this->resetAtlas ();
+    this->resetAtlases ();
 }
 
 bool TextLayout::setPrimaryFont (std::vector<uint8_t> data, const std::string& path) {
     this->clearFaces ();
-    return this->addFace (std::move (data), path);
+    return this->addFace (
+	data.empty () ? nullptr : std::make_shared<const std::vector<uint8_t>> (std::move (data)), path
+    );
 }
 
-bool TextLayout::addFace (std::vector<uint8_t> data, const std::string& path) {
+void TextLayout::setFallbackFonts (std::vector<TextFontSource> fonts) {
+    m_fallbackSources = std::move (fonts);
+}
+
+bool TextLayout::addFace (std::shared_ptr<const std::vector<uint8_t>> data, const std::string& path) {
     if (m_library == nullptr) {
 	return false;
     }
@@ -238,9 +358,11 @@ bool TextLayout::addFace (std::vector<uint8_t> data, const std::string& path) {
     face->data = std::move (data);
     face->path = path;
 
-    const FT_Error error = face->data.empty ()
+    const FT_Error error = face->data == nullptr
 	? FT_New_Face (m_library, path.c_str (), 0, &face->face)
-	: FT_New_Memory_Face (m_library, face->data.data (), static_cast<FT_Long> (face->data.size ()), 0, &face->face);
+	: FT_New_Memory_Face (
+	      m_library, face->data->data (), static_cast<FT_Long> (face->data->size ()), 0, &face->face
+	  );
 
     if (error != 0) {
 	sLog.error ("TextLayout: cannot load font '", path, "' (FreeType error ", error, ")");
@@ -254,6 +376,7 @@ bool TextLayout::addFace (std::vector<uint8_t> data, const std::string& path) {
     }
 
     FT_Select_Charmap (face->face, FT_ENCODING_UNICODE);
+    face->color = FT_HAS_COLOR (face->face);
 
     if (m_size > 0.0f) {
 	FT_Set_Char_Size (face->face, 0, static_cast<FT_F26Dot6> (m_size * 64.0f), 300, 300);
@@ -278,17 +401,42 @@ void TextLayout::applySize (float size) {
 
     m_boxes.clear ();
     m_glyphs.clear ();
-    this->resetAtlas ();
+    this->resetAtlases ();
 }
 
 int TextLayout::faceFor (char32_t codepoint) {
-    for (size_t i = 0; i < m_faces.size (); i++) {
-	if (FT_Get_Char_Index (m_faces[i]->face, codepoint) != 0) {
-	    return static_cast<int> (i);
+    const auto findLoaded = [this, codepoint] () {
+	for (size_t i = 0; i < m_faces.size (); i++) {
+	    if (FT_Get_Char_Index (m_faces[i]->face, codepoint) != 0) {
+		return static_cast<int> (i);
+	    }
+	}
+
+	return -1;
+    };
+
+    if (const int face = findLoaded (); face >= 0) {
+	return face;
+    }
+
+    if (codepoint < 0x20) {
+	return -1;
+    }
+
+    // WE's fixed fallback list (sub_1401AD670) comes right after the primary font, fontconfig's picks after that
+    if (!m_fallbacksLoaded) {
+	m_fallbacksLoaded = true;
+
+	for (const auto& source : m_fallbackSources) {
+	    this->addFace (source.data, source.path);
+	}
+
+	if (const int face = findLoaded (); face >= 0) {
+	    return face;
 	}
     }
 
-    if (codepoint < 0x20 || !m_fallbackTried.insert (codepoint).second) {
+    if (!m_fallbackTried.insert (codepoint).second) {
 	return -1;
     }
 
@@ -364,12 +512,21 @@ std::vector<TextLayout::ShapedGlyph> TextLayout::shape (const std::u32string& li
 	    const uint32_t glyph = infos[i].codepoint;
 
 	    // WE's glyph fetch fails on .notdef, which leaves the character out without advancing the pen
-	    if (glyph == 0 || this->atlasGlyph (run.face, glyph) == nullptr) {
+	    const AtlasGlyph* entry = glyph == 0 ? nullptr : this->atlasGlyph (run.face, glyph);
+
+	    if (entry == nullptr) {
 		continue;
 	    }
 
+	    // the quad comes from the outline's box (sub_1401ADDB0, loaded without bitmaps). Segoe UI Emoji, the colour
+	    // font WE finds first on Windows, has monochrome outlines under its colour layers, Twemoji (the fallback left
+	    // on Linux) has none, which would give its emoji an empty quad: their bitmap's box stands in there
 	    const GlyphBox* box = this->glyphBox (run.face, glyph);
-	    const GlyphBox bounds = box != nullptr ? *box : GlyphBox {};
+	    GlyphBox bounds = box != nullptr ? *box : GlyphBox {};
+
+	    if (entry->color && bounds.x0 == bounds.x1 && bounds.y0 == bounds.y1) {
+		bounds = entry->bitmapBox;
+	    }
 	    const int xOffset = positions[i].x_offset >> 6;
 	    const int yOffset = positions[i].y_offset >> 6;
 	    const uint32_t cluster = infos[i].cluster + static_cast<uint32_t> (run.start);
@@ -386,6 +543,7 @@ std::vector<TextLayout::ShapedGlyph> TextLayout::shape (const std::u32string& li
 		    .x1 = static_cast<float> (xOffset + bounds.x1),
 		    .y1 = static_cast<float> (yOffset + bounds.y1),
 		    .pad = pad,
+		    .color = entry->color,
 		}
 	    );
 	}
@@ -461,15 +619,27 @@ TextLayout::AtlasGlyph* TextLayout::atlasGlyph (size_t face, uint32_t glyph) {
     }
 
     AtlasGlyph entry;
-    FT_Face ftFace = m_faces[face]->face;
+    const Face& source = *m_faces[face];
+
+    // sub_1401AE080: plain glyphs are rendered with FT_LOAD_RENDER | FT_LOAD_COLOR, in MSDF mode fonts with colour
+    // glyphs are too (their BGRA bitmaps become distance fields), the rest are outlines
+    bool rendered;
+
+    if (!m_msdf) {
+	rendered = this->renderPlainGlyph (source.face, glyph, entry);
+    } else if (source.color) {
+	rendered = this->renderColorMsdfGlyph (source.face, glyph, entry);
+    } else {
+	rendered = this->renderMsdfGlyph (source.face, glyph, entry);
+    }
 
-    if (!(m_atlasMsdf ? this->renderMsdfGlyph (ftFace, glyph, entry) : this->renderPlainGlyph (ftFace, glyph, entry))) {
+    if (!rendered) {
 	return nullptr;
     }
 
     auto& stored = m_glyphs.emplace (key, std::move (entry)).first->second;
 
-    if (!this->pack (key, stored)) {
+    if (!this->pack (stored.color ? m_colorAtlas : m_atlas, key, stored)) {
 	m_atlasFull = true;
     }
 
@@ -477,13 +647,37 @@ TextLayout::AtlasGlyph* TextLayout::atlasGlyph (size_t face, uint32_t glyph) {
 }
 
 bool TextLayout::renderPlainGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out) {
-    if (FT_Load_Glyph (face, glyph, FT_LOAD_RENDER) != 0) {
+    if (FT_Load_Glyph (face, glyph, FT_LOAD_RENDER | FT_LOAD_COLOR) != 0) {
 	return false;
     }
 
-    const FT_Bitmap& bitmap = face->glyph->bitmap;
+    const FT_GlyphSlot slot = face->glyph;
+    const FT_Bitmap& bitmap = slot->bitmap;
     out.width = static_cast<int> (bitmap.width);
     out.height = static_cast<int> (bitmap.rows);
+
+    // colour bitmaps go to the RGBA atlas as they are, premultiplied, with red and blue swapped
+    if (bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
+	out.color = true;
+	out.bitmapBox = { slot->bitmap_left, slot->bitmap_top - out.height, slot->bitmap_left + out.width,
+			  slot->bitmap_top };
+	out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
+
+	for (int row = 0; row < out.height; row++) {
+	    const uint8_t* src = bitmap.buffer + static_cast<long> (row) * bitmap.pitch;
+	    uint8_t* dst = &out.pixels[static_cast<size_t> (row) * out.width * 4];
+
+	    for (int col = 0; col < out.width; col++) {
+		dst[col * 4 + 0] = src[col * 4 + 2];
+		dst[col * 4 + 1] = src[col * 4 + 1];
+		dst[col * 4 + 2] = src[col * 4 + 0];
+		dst[col * 4 + 3] = src[col * 4 + 3];
+	    }
+	}
+
+	return true;
+    }
+
     out.pixels.assign (static_cast<size_t> (out.width) * out.height, 0);
 
     if (bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) {
@@ -495,6 +689,158 @@ bool TextLayout::renderPlainGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out
     return true;
 }
 
+// sub_1401AE080 for a colour glyph in MSDF mode: the bitmap's alpha (inside from 128 on) becomes a signed distance
+// field laid out like the MSDF glyphs (32 px per em, 12 px of range around it), stored in all four channels, and the
+// colours are resampled at the colour atlas' scale into its colour texture
+bool TextLayout::renderColorMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out) {
+    if (FT_Load_Glyph (face, glyph, FT_LOAD_RENDER | FT_LOAD_COLOR) != 0) {
+	return false;
+    }
+
+    const FT_GlyphSlot slot = face->glyph;
+    const FT_Bitmap& bitmap = slot->bitmap;
+
+    // a glyph of a colour font without colour layers: WE copies its grey bitmap into the RGBA atlas as if it had one
+    // byte per pixel, which leaves the glyph's own cell empty
+    if (bitmap.pixel_mode != FT_PIXEL_MODE_BGRA) {
+	out.width = static_cast<int> (bitmap.width);
+	out.height = static_cast<int> (bitmap.rows);
+	out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
+	return true;
+    }
+
+    const int bitmapWidth = static_cast<int> (bitmap.width);
+    const int bitmapHeight = static_cast<int> (bitmap.rows);
+    // FT_Glyph_Get_CBox of a bitmap glyph in pixels
+    const int boxX0 = slot->bitmap_left;
+    const int boxY0 = slot->bitmap_top - bitmapHeight;
+    const int boxWidth = bitmapWidth;
+    const int boxHeight = bitmapHeight;
+    int width = 0;
+    int height = 0;
+
+    out.color = true;
+    out.bitmapBox = { boxX0, boxY0, boxX0 + boxWidth, boxY0 + boxHeight };
+
+    // sub_1401ADF30: the first colour glyph picks the colour texture's scale for the whole font set
+    if (m_colorAtlas.colorScale == 0) {
+	m_colorAtlas.colorScale = std::max (1, (std::max (boxWidth, boxHeight) + 31) / 32);
+	m_colorAtlas.colorPixels.assign (
+	    static_cast<size_t> (m_colorAtlas.size) * m_colorAtlas.colorScale * m_colorAtlas.size
+		* m_colorAtlas.colorScale * 4,
+	    0
+	);
+    }
+
+    if (boxWidth > 0 && boxHeight > 0) {
+	const float toAtlas = 32.0f / static_cast<float> (std::max<int> (face->size->metrics.y_ppem, 1));
+	width = std::max (1, static_cast<int> (static_cast<float> (boxWidth) * toAtlas));
+	height = std::max (1, static_cast<int> (static_cast<float> (boxHeight) * toAtlas));
+    }
+
+    out.width = width + 24;
+    out.height = height + 24;
+    out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
+
+    const int colorScale = m_colorAtlas.colorScale;
+    out.colorPixels.assign (static_cast<size_t> (out.width) * colorScale * out.height * colorScale * 4, 0);
+
+    if (width <= 0 || height <= 0 || bitmap.buffer == nullptr) {
+	return true;
+    }
+
+    const float scale = static_cast<float> (std::max (width, height))
+	/ std::max (static_cast<float> (boxHeight), static_cast<float> (boxWidth));
+    const float range = 24.0f / scale;
+    const double translateX = static_cast<double> (12.0f / scale - static_cast<float> (boxX0));
+    const double translateY = static_cast<double> (12.0f / scale - static_cast<float> (boxY0));
+
+    // sub_1401AB9C0: squared distances to the nearest inside and outside texels, signed distance at texel centers
+    std::vector<float> toInside (static_cast<size_t> (bitmapWidth) * bitmapHeight);
+    std::vector<float> toOutside (toInside.size ());
+
+    for (int y = 0; y < bitmapHeight; y++) {
+	for (int x = 0; x < bitmapWidth; x++) {
+	    const bool inside = bitmap.buffer[static_cast<long> (y) * bitmap.pitch + x * 4 + 3] >= 0x80;
+	    toInside[x + y * bitmapWidth] = inside ? 0.0f : kDistanceInfinity;
+	    toOutside[x + y * bitmapWidth] = inside ? kDistanceInfinity : 0.0f;
+	}
+    }
+
+    distanceTransform2D (toInside, bitmapWidth, bitmapHeight);
+    distanceTransform2D (toOutside, bitmapWidth, bitmapHeight);
+
+    std::vector<float> field (toInside.size ());
+
+    for (int y = 0; y < bitmapHeight; y++) {
+	for (int x = 0; x < bitmapWidth; x++) {
+	    const size_t i = x + y * bitmapWidth;
+	    const bool inside = bitmap.buffer[static_cast<long> (y) * bitmap.pitch + x * 4 + 3] >= 0x80;
+	    field[i] = inside ? std::sqrt (toOutside[i]) - 0.5f : 0.5f - std::sqrt (toInside[i]);
+	}
+    }
+
+    const float inverseRange = 1.0f / range;
+    const auto toByte = [] (float value) {
+	return static_cast<uint8_t> (std::clamp (static_cast<int> (value * 256.0f), 0, 255));
+    };
+
+    for (int y = 0; y < out.height; y++) {
+	const float glyphY = static_cast<float> ((static_cast<float> (y) + 0.5) / scale - translateY);
+	const float bitmapY = static_cast<float> (slot->bitmap_top) - glyphY;
+
+	for (int x = 0; x < out.width; x++) {
+	    const float glyphX = static_cast<float> ((static_cast<float> (x) + 0.5) / scale - translateX);
+	    const float bitmapX = glyphX - static_cast<float> (slot->bitmap_left);
+	    // outside the bitmap the distance to its edge adds on
+	    const float clampedX = bitmapX >= static_cast<float> (bitmapWidth - 1)
+		? static_cast<float> (bitmapWidth - 1)
+		: (bitmapX <= 0.0f ? 0.0f : bitmapX);
+	    const float clampedY = bitmapY >= static_cast<float> (bitmapHeight - 1)
+		? static_cast<float> (bitmapHeight - 1)
+		: (bitmapY <= 0.0f ? 0.0f : bitmapY);
+	    const float dx = bitmapX - clampedX;
+	    const float dy = bitmapY - clampedY;
+	    const float outside = std::sqrt (dy * dy + dx * dx);
+	    const float floorX = std::floor (clampedX);
+	    const float floorY = std::floor (clampedY);
+	    const float fx = clampedX - floorX;
+	    const float fy = clampedY - floorY;
+	    const int x0 = static_cast<int> (floorX);
+	    const int y0 = static_cast<int> (floorY);
+	    const int x1 = std::min (x0 + 1, bitmapWidth - 1);
+	    const int y1 = std::min (y0 + 1, bitmapHeight - 1);
+	    const float top = (1.0f - fx) * field[x0 + y0 * bitmapWidth] + fx * field[x1 + y0 * bitmapWidth];
+	    const float bottom = (1.0f - fx) * field[x0 + y1 * bitmapWidth] + fx * field[x1 + y1 * bitmapWidth];
+	    const float value = ((top * (1.0f - fy) + bottom * fy) - outside) * inverseRange + 0.5f;
+
+	    // rows go bottom up here, the atlas is stored top down
+	    uint8_t* dst = &out.pixels[(static_cast<size_t> (out.height - y - 1) * out.width + x) * 4];
+	    dst[0] = dst[1] = dst[2] = dst[3] = toByte (value);
+	}
+    }
+
+    const int colorWidth = out.width * colorScale;
+    const int colorHeight = out.height * colorScale;
+    const double colorToGlyph = static_cast<double> (static_cast<float> (colorScale) * scale);
+
+    for (int row = 0; row < colorHeight; row++) {
+	const float glyphY
+	    = static_cast<float> ((static_cast<float> (colorHeight - row - 1) + 0.5) / colorToGlyph - translateY);
+	const float bitmapY = static_cast<float> (slot->bitmap_top) - glyphY;
+
+	for (int col = 0; col < colorWidth; col++) {
+	    const float glyphX = static_cast<float> ((static_cast<float> (col) + 0.5) / colorToGlyph - translateX);
+	    sampleBitmapBGRA (
+		bitmap, glyphX - static_cast<float> (slot->bitmap_left), bitmapY,
+		&out.colorPixels[(static_cast<size_t> (row) * colorWidth + col) * 4]
+	    );
+	}
+    }
+
+    return true;
+}
+
 // sub_1401AE080: an MSDF of the glyph at 32 pixels per em with 12 pixels of distance range around it
 bool TextLayout::renderMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out) {
     FT_Glyph ftGlyph = nullptr;
@@ -601,76 +947,109 @@ bool TextLayout::renderMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out)
     return true;
 }
 
-void TextLayout::resetAtlas () {
-    m_atlasSize = 512;
-    m_atlasPixels.assign (static_cast<size_t> (m_atlasSize) * m_atlasSize * this->getAtlasChannels (), 0);
-    m_packOrder.clear ();
-    m_shelfX = m_shelfY = m_shelfHeight = 0;
+void TextLayout::resetAtlases () {
+    for (Atlas* atlas : { &m_atlas, &m_colorAtlas }) {
+	atlas->size = 512;
+	atlas->pixels.assign (static_cast<size_t> (atlas->size) * atlas->size * atlas->channels, 0);
+	atlas->colorScale = 0;
+	atlas->colorPixels.clear ();
+	atlas->packOrder.clear ();
+	atlas->shelfX = atlas->shelfY = atlas->shelfHeight = 0;
+	atlas->changed = true;
+    }
+
     m_atlasFull = false;
-    m_atlasChanged = true;
 }
 
-bool TextLayout::pack (uint64_t key, AtlasGlyph& glyph) {
+bool TextLayout::pack (Atlas& atlas, uint64_t key, AtlasGlyph& glyph) {
     // one pixel between glyphs so linear filtering never picks up a neighbour
     const int width = glyph.width + 1;
     const int height = glyph.height + 1;
 
     while (true) {
-	if (m_shelfX + width > m_atlasSize) {
-	    m_shelfY += m_shelfHeight;
-	    m_shelfX = 0;
-	    m_shelfHeight = 0;
+	if (atlas.shelfX + width > atlas.size) {
+	    atlas.shelfY += atlas.shelfHeight;
+	    atlas.shelfX = 0;
+	    atlas.shelfHeight = 0;
 	}
 
-	if (width <= m_atlasSize && m_shelfY + height <= m_atlasSize) {
+	if (width <= atlas.size && atlas.shelfY + height <= atlas.size) {
 	    break;
 	}
 
 	// the atlas doubles up to 4096 like WE's
-	if (m_atlasSize >= kMaxAtlasSize) {
+	if (atlas.size >= kMaxAtlasSize) {
 	    return false;
 	}
 
-	this->repackAtlas (m_atlasSize * 2);
+	this->repackAtlas (atlas, atlas.size * 2);
     }
 
-    glyph.x = m_shelfX;
-    glyph.y = m_shelfY;
-    m_shelfX += width;
-    m_shelfHeight = std::max (m_shelfHeight, height);
+    glyph.x = atlas.shelfX;
+    glyph.y = atlas.shelfY;
+    atlas.shelfX += width;
+    atlas.shelfHeight = std::max (atlas.shelfHeight, height);
 
-    const int channels = this->getAtlasChannels ();
+    const int channels = atlas.channels;
 
     for (int row = 0; row < glyph.height; row++) {
 	std::copy_n (
 	    glyph.pixels.begin () + static_cast<long> (row) * glyph.width * channels, glyph.width * channels,
-	    m_atlasPixels.begin () + (static_cast<long> (glyph.y + row) * m_atlasSize + glyph.x) * channels
+	    atlas.pixels.begin () + (static_cast<long> (glyph.y + row) * atlas.size + glyph.x) * channels
 	);
     }
 
-    m_packOrder.push_back (key);
-    m_atlasChanged = true;
+    // the colour texture holds the same cell at colorScale times the resolution
+    if (atlas.colorScale > 0 && !glyph.colorPixels.empty ()) {
+	const int scale = atlas.colorScale;
+	const int rowLength = glyph.width * scale * 4;
+	const long stride = static_cast<long> (atlas.size) * scale * 4;
+
+	for (int row = 0; row < glyph.height * scale; row++) {
+	    std::copy_n (
+		glyph.colorPixels.begin () + static_cast<long> (row) * rowLength, rowLength,
+		atlas.colorPixels.begin () + (static_cast<long> (glyph.y) * scale + row) * stride
+		    + static_cast<long> (glyph.x) * scale * 4
+	    );
+	}
+    }
+
+    atlas.packOrder.push_back (key);
+    atlas.changed = true;
     return true;
 }
 
-void TextLayout::repackAtlas (int size) {
-    const std::vector<uint64_t> order = std::move (m_packOrder);
+void TextLayout::repackAtlas (Atlas& atlas, int size) {
+    const std::vector<uint64_t> order = std::move (atlas.packOrder);
+
+    atlas.size = size;
+    atlas.pixels.assign (static_cast<size_t> (size) * size * atlas.channels, 0);
+
+    if (atlas.colorScale > 0) {
+	atlas.colorPixels.assign (
+	    static_cast<size_t> (size) * atlas.colorScale * size * atlas.colorScale * 4, 0
+	);
+    }
 
-    m_atlasSize = size;
-    m_atlasPixels.assign (static_cast<size_t> (size) * size * this->getAtlasChannels (), 0);
-    m_packOrder.clear ();
-    m_shelfX = m_shelfY = m_shelfHeight = 0;
+    atlas.packOrder.clear ();
+    atlas.shelfX = atlas.shelfY = atlas.shelfHeight = 0;
 
     for (const uint64_t key : order) {
 	if (auto it = m_glyphs.find (key); it != m_glyphs.end ()) {
-	    this->pack (key, it->second);
+	    this->pack (atlas, key, it->second);
 	}
     }
 }
 
 bool TextLayout::takeAtlasChanged () {
-    const bool changed = m_atlasChanged;
-    m_atlasChanged = false;
+    const bool changed = m_atlas.changed;
+    m_atlas.changed = false;
+    return changed;
+}
+
+bool TextLayout::takeColorAtlasChanged () {
+    const bool changed = m_colorAtlas.changed;
+    m_colorAtlas.changed = false;
     return changed;
 }
 
@@ -681,10 +1060,11 @@ TextLayoutResult TextLayout::layout (const std::string& utf8, const TextLayoutPa
 	return result;
     }
 
-    if (params.msdf != m_atlasMsdf) {
-	m_atlasMsdf = params.msdf;
+    if (params.msdf != m_msdf) {
+	m_msdf = params.msdf;
+	m_atlas.channels = m_msdf ? 4 : 1;
 	m_glyphs.clear ();
-	this->resetAtlas ();
+	this->resetAtlases ();
     }
 
     this->applySize (params.size);
@@ -870,7 +1250,7 @@ TextLayoutResult TextLayout::layout (const std::string& utf8, const TextLayoutPa
 
 	if (m_atlasFull && attempt == 0) {
 	    m_glyphs.clear ();
-	    this->resetAtlas ();
+	    this->resetAtlases ();
 	    continue;
 	}
 
@@ -889,7 +1269,6 @@ TextLayoutResult TextLayout::layout (const std::string& utf8, const TextLayoutPa
 	result.ascender = ascender;
 	result.descender = static_cast<float> (metrics.descender >> 6);
 
-	const float atlasSize = static_cast<float> (m_atlasSize);
 	float lineY = 0.0f;
 
 	for (const auto& line : finished) {
@@ -908,8 +1287,10 @@ TextLayoutResult TextLayout::layout (const std::string& utf8, const TextLayoutPa
 
 		if (it != m_glyphs.end () && it->second.x >= 0) {
 		    const AtlasGlyph& entry = it->second;
+		    // sub_1401B0410 puts colour glyphs into a vertex buffer of their own
+		    const float atlasSize = static_cast<float> (entry.color ? m_colorAtlas.size : m_atlas.size);
 
-		    result.quads.push_back (
+		    (entry.color ? result.colorQuads : result.quads).push_back (
 			{
 			    .rect = { pen + glyph.x0 - glyph.pad + shift, lineY + glyph.y0 - glyph.pad,
 				      pen + glyph.x1 + glyph.pad + shift, lineY + glyph.y1 + glyph.pad },

+ 54 - 17
src/WallpaperEngine/Render/Objects/TextLayout.h

@@ -45,6 +45,8 @@ struct TextGlyphQuad {
 
 struct TextLayoutResult {
     std::vector<TextGlyphQuad> quads;
+    /** colour glyphs (emoji), drawn after the others from the colour atlas */
+    std::vector<TextGlyphQuad> colorQuads;
     float minX = 0.0f;
     float bottom = 0.0f;
     float maxX = 0.0f;
@@ -56,10 +58,17 @@ struct TextLayoutResult {
     bool valid = false;
 };
 
+/** A font file WE falls back to, either read into memory (the assets' Twemoji) or a path on disk */
+struct TextFontSource {
+    std::shared_ptr<const std::vector<uint8_t>> data;
+    std::string path;
+};
+
 /**
  * Text layout of wallpaper64.exe 2.8.42 (sub_1401B0410): HarfBuzz shaped runs per font, wrapping, row limit with
  * ellipsis, justification, and a glyph atlas of either plain coverage (R8) or MSDF glyphs (RGBA, msdfgen, 32 px per em
- * plus 12 px of range on every side). Everything is in raster pixels, before the object's scale.
+ * plus 12 px of range on every side). Colour glyphs (FreeType's BGRA bitmaps) go to a second RGBA atlas, as distance
+ * fields plus a colour texture in MSDF mode (sub_1401AE080). Everything is in raster pixels, before the object's scale.
  */
 class TextLayout {
 public:
@@ -71,22 +80,32 @@ public:
 
     /** Replaces every loaded face. An empty data vector loads the file at path instead */
     bool setPrimaryFont (std::vector<uint8_t> data, const std::string& path);
+    /** The fonts tried in order for characters the primary font lacks, before asking fontconfig */
+    void setFallbackFonts (std::vector<TextFontSource> fonts);
     [[nodiscard]] bool hasFont () const { return !m_faces.empty (); }
 
     TextLayoutResult layout (const std::string& text, const TextLayoutParams& params);
 
-    [[nodiscard]] int getAtlasSize () const { return m_atlasSize; }
-    [[nodiscard]] int getAtlasChannels () const { return m_atlasMsdf ? 4 : 1; }
-    [[nodiscard]] const std::vector<uint8_t>& getAtlasPixels () const { return m_atlasPixels; }
+    [[nodiscard]] int getAtlasSize () const { return m_atlas.size; }
+    [[nodiscard]] int getAtlasChannels () const { return m_atlas.channels; }
+    [[nodiscard]] const std::vector<uint8_t>& getAtlasPixels () const { return m_atlas.pixels; }
     /** true once after the atlas pixels changed */
     bool takeAtlasChanged ();
 
+    [[nodiscard]] int getColorAtlasSize () const { return m_colorAtlas.size; }
+    [[nodiscard]] const std::vector<uint8_t>& getColorAtlasPixels () const { return m_colorAtlas.pixels; }
+    /** MSDF mode only: the glyphs' colours at getColorScale () times the colour atlas' resolution */
+    [[nodiscard]] int getColorScale () const { return m_colorAtlas.colorScale; }
+    [[nodiscard]] const std::vector<uint8_t>& getColorTexturePixels () const { return m_colorAtlas.colorPixels; }
+    bool takeColorAtlasChanged ();
+
 private:
     struct Face {
 	FT_Face face = nullptr;
 	hb_font_t* font = nullptr;
-	std::vector<uint8_t> data;
+	std::shared_ptr<const std::vector<uint8_t>> data;
 	std::string path;
+	bool color = false;
     };
 
     struct GlyphBox {
@@ -100,8 +119,27 @@ private:
 	int width = 0;
 	int height = 0;
 	std::vector<uint8_t> pixels;
+	/** colour glyphs in MSDF mode: the colours of the cell at the atlas' colour scale */
+	std::vector<uint8_t> colorPixels;
 	int x = -1;
 	int y = -1;
+	bool color = false;
+	/** the bitmap's own box, for colour glyphs whose outline is empty */
+	GlyphBox bitmapBox;
+    };
+
+    struct Atlas {
+	int size = 512;
+	int channels = 1;
+	/** colour texture size = size * colorScale, 0 when there is none */
+	int colorScale = 0;
+	std::vector<uint8_t> pixels;
+	std::vector<uint8_t> colorPixels;
+	std::vector<uint64_t> packOrder;
+	int shelfY = 0;
+	int shelfHeight = 0;
+	int shelfX = 0;
+	bool changed = true;
     };
 
     struct ShapedGlyph {
@@ -115,6 +153,7 @@ private:
 	float x1 = 0.0f;
 	float y1 = 0.0f;
 	float pad = 0.0f;
+	bool color = false;
     };
 
     struct Run {
@@ -123,7 +162,7 @@ private:
 	std::u32string text;
     };
 
-    bool addFace (std::vector<uint8_t> data, const std::string& path);
+    bool addFace (std::shared_ptr<const std::vector<uint8_t>> data, const std::string& path);
     void clearFaces ();
     void applySize (float size);
     int faceFor (char32_t codepoint);
@@ -135,26 +174,24 @@ private:
     AtlasGlyph* atlasGlyph (size_t face, uint32_t glyph);
     bool renderPlainGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out);
     bool renderMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out);
-    bool pack (uint64_t key, AtlasGlyph& glyph);
-    void repackAtlas (int size);
-    void resetAtlas ();
+    bool renderColorMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out);
+    bool pack (Atlas& atlas, uint64_t key, AtlasGlyph& glyph);
+    void repackAtlas (Atlas& atlas, int size);
+    void resetAtlases ();
 
     FT_Library m_library = nullptr;
     std::vector<std::unique_ptr<Face>> m_faces;
+    std::vector<TextFontSource> m_fallbackSources;
+    bool m_fallbacksLoaded = false;
     std::set<char32_t> m_fallbackTried;
     float m_size = 0.0f;
-    bool m_atlasMsdf = false;
+    bool m_msdf = false;
 
     std::unordered_map<uint64_t, GlyphBox> m_boxes;
     std::unordered_map<uint64_t, AtlasGlyph> m_glyphs;
-    std::vector<uint64_t> m_packOrder;
 
-    int m_atlasSize = 512;
-    std::vector<uint8_t> m_atlasPixels;
-    int m_shelfY = 0;
-    int m_shelfHeight = 0;
-    int m_shelfX = 0;
+    Atlas m_atlas;
+    Atlas m_colorAtlas;
     bool m_atlasFull = false;
-    bool m_atlasChanged = true;
 };
 } // namespace WallpaperEngine::Render::Objects

+ 61 - 54
src/WallpaperEngine/Render/Shaders/GLSLContext.cpp

@@ -196,15 +196,56 @@ describeFailure (const std::string& name, const std::string& stage, const std::s
 }
 } // namespace
 
-std::pair<std::string, std::string>
-GLSLContext::toGlsl (const std::string& vertex, const std::string& fragment, const std::string& name) {
-    // pure function of the two sources, and passes get rebuilt often
+namespace {
+/** Parses one stage, throwing the report describeFailure builds when glslang rejects it */
+std::unique_ptr<glslang::TShader> parseStage (
+    EShLanguage stage, const std::string& source, const std::string& name, const char* stageName
+) {
+    auto shader = std::make_unique<glslang::TShader> (stage);
+
+    const char* text = source.c_str ();
+    shader->setStrings (&text, 1);
+    shader->setEntryPoint ("main");
+    shader->setEnvInput (glslang::EShSourceGlsl, stage, glslang::EShClientOpenGL, 330);
+    shader->setEnvClient (glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450);
+    shader->setEnvTarget (glslang::EShTargetSpv, glslang::EShTargetSpv_1_5);
+    shader->setAutoMapLocations (true);
+    shader->setAutoMapBindings (true);
+
+    if (!shader->parse (&BuiltInResource, 100, false, EShMsgDefault)) {
+	throw std::runtime_error (describeFailure (name, stageName, source, shader->getInfoLog ()));
+    }
+
+    return shader;
+}
+
+std::string crossCompile (glslang::TProgram& program, EShLanguage stage) {
+    std::vector<uint32_t> spirv;
+    glslang::GlslangToSpv (*program.getIntermediate (stage), spirv);
+
+    spirv_cross::CompilerGLSL compiler (spirv);
+    spirv_cross::CompilerGLSL::Options options;
+    options.version = 330;
+    options.es = false;
+    options.force_zero_initialized_variables = true;
+    compiler.set_common_options (options);
+
+    return compiler.compile ();
+}
+} // namespace
+
+GLSLContext::Sources GLSLContext::toGlsl (
+    const std::string& vertex, const std::string& fragment, const std::string& name, const std::string& geometry
+) {
+    // pure function of the sources, and passes get rebuilt often
     static std::mutex cacheMutex;
-    static std::unordered_map<std::string, std::pair<std::string, std::string>> cache;
+    static std::unordered_map<std::string, Sources> cache;
 
     std::string cacheKey = vertex;
     cacheKey += '\0';
     cacheKey += fragment;
+    cacheKey += '\0';
+    cacheKey += geometry;
 
     {
 	std::lock_guard lock (cacheMutex);
@@ -214,37 +255,19 @@ GLSLContext::toGlsl (const std::string& vertex, const std::string& fragment, con
 	}
     }
 
-    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)) {
-	throw std::runtime_error (describeFailure (name, "vertex", vertex, vertexShader.getInfoLog ()));
-    }
-    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)) {
-	throw std::runtime_error (describeFailure (name, "fragment", fragment, fragmentShader.getInfoLog ()));
+    const auto vertexShader = parseStage (EShLangVertex, vertex, name, "vertex");
+    const auto fragmentShader = parseStage (EShLangFragment, fragment, name, "fragment");
+    std::unique_ptr<glslang::TShader> geometryShader;
+    if (!geometry.empty ()) {
+	geometryShader = parseStage (EShLangGeometry, geometry, name, "geometry");
     }
+
     glslang::TProgram program;
-    program.addShader (&vertexShader);
-    program.addShader (&fragmentShader);
+    program.addShader (vertexShader.get ());
+    if (geometryShader) {
+	program.addShader (geometryShader.get ());
+    }
+    program.addShader (fragmentShader.get ());
 
     if (!program.link (EShMsgDefault)) {
 	throw std::runtime_error (
@@ -253,27 +276,11 @@ GLSLContext::toGlsl (const std::string& vertex, const std::string& fragment, con
 	);
     }
 
-    std::vector<uint32_t> spirv;
-    glslang::GlslangToSpv (*program.getIntermediate (EShLangVertex), spirv);
-
-    spirv_cross::CompilerGLSL vertexCompiler (spirv);
-    spirv_cross::CompilerGLSL::Options options;
-    options.version = 330;
-    options.es = false;
-    options.force_zero_initialized_variables = true;
-    vertexCompiler.set_common_options (options);
-
-    spirv.clear ();
-    glslang::GlslangToSpv (*program.getIntermediate (EShLangFragment), spirv);
-
-    spirv_cross::CompilerGLSL fragmentCompiler (spirv);
-    options.version = 330;
-    options.es = false;
-    options.force_zero_initialized_variables = true;
-    fragmentCompiler.set_common_options (options);
-
-    std::pair<std::string, std::string> result = { vertexCompiler.compile () + "#if 0\n" + vertex + "\n#endif",
-						   fragmentCompiler.compile () + "#if 0\n" + fragment + "\n#endif" };
+    Sources result = {
+	.vertex = crossCompile (program, EShLangVertex) + "#if 0\n" + vertex + "\n#endif",
+	.fragment = crossCompile (program, EShLangFragment) + "#if 0\n" + fragment + "\n#endif",
+	.geometry = geometryShader ? crossCompile (program, EShLangGeometry) + "#if 0\n" + geometry + "\n#endif" : "",
+    };
 
     {
 	std::lock_guard lock (cacheMutex);

+ 14 - 5
src/WallpaperEngine/Render/Shaders/GLSLContext.h

@@ -9,15 +9,24 @@
 namespace WallpaperEngine::Render::Shaders {
 class GLSLContext {
 public:
-    enum UnitType { UnitType_Vertex = 0, UnitType_Fragment = 1 };
+    enum UnitType { UnitType_Vertex = 0, UnitType_Fragment = 1, UnitType_Geometry = 2 };
+
+    struct Sources {
+	std::string vertex;
+	std::string fragment;
+	/** empty when the shader has no geometry stage */
+	std::string geometry;
+    };
 
     GLSLContext ();
     ~GLSLContext ();
 
-    /** Throws with the error and the offending source lines when glslang rejects either unit, `name` is only
-     *  used for that report. */
-    [[nodiscard]] std::pair<std::string, std::string>
-    toGlsl (const std::string& vertex, const std::string& fragment, const std::string& name = "");
+    /** Throws with the error and the offending source lines when glslang rejects a unit, `name` is only used for
+     *  that report. An empty `geometry` means no geometry stage. */
+    [[nodiscard]] Sources toGlsl (
+	const std::string& vertex, const std::string& fragment, const std::string& name = "",
+	const std::string& geometry = ""
+    );
 
     [[nodiscard]] static GLSLContext& get ();
 

+ 24 - 0
src/WallpaperEngine/Render/Shaders/Shader.cpp

@@ -30,12 +30,36 @@ Shader::Shader (
     m_file (std::move (filename)), m_combos (combos), m_passTextures (textures) {
     this->m_vertex.linkToUnit (&this->m_fragment);
     this->m_fragment.linkToUnit (&this->m_vertex);
+
+    const auto enabled = [] (const ComboMap& map) {
+	const auto it = map.find ("GS_ENABLED");
+	return it != map.end () && it->second != 0;
+    };
+    if (!enabled (overrideCombos) && !enabled (combos)) {
+	return;
+    }
+
+    try {
+	this->m_geometry = std::make_unique<ShaderUnit> (
+	    GLSLContext::UnitType_Geometry, this->m_file, assetLocator.geometryShader (this->m_file), assetLocator,
+	    constants, textures, overrideTextures, combos, overrideCombos
+	);
+    } catch (AssetLoadException&) {
+	return;
+    }
+    this->m_geometry->linkToUnit (&this->m_vertex);
+    this->m_vertex.feedGeometryStage ();
 }
 
 const std::string& Shader::vertex () { return this->m_vertex.compile (); }
 
 const std::string& Shader::fragment () { return this->m_fragment.compile (); }
 
+const std::string& Shader::geometry () {
+    static const std::string none;
+    return this->m_geometry ? this->m_geometry->compile () : none;
+}
+
 const ShaderUnit& Shader::getVertex () const { return this->m_vertex; }
 
 const ShaderUnit& Shader::getFragment () const { return this->m_fragment; }

+ 5 - 0
src/WallpaperEngine/Render/Shaders/Shader.h

@@ -2,6 +2,7 @@
 
 #include <iostream>
 #include <map>
+#include <memory>
 #include <vector>
 
 #include "../TextureProvider.h"
@@ -32,6 +33,8 @@ public:
     );
     const std::string& vertex ();
     const std::string& fragment ();
+    /** Empty when there is no geometry stage */
+    const std::string& geometry ();
     [[nodiscard]] const ShaderUnit& getVertex () const;
     [[nodiscard]] const ShaderUnit& getFragment () const;
     [[nodiscard]] const std::map<std::string, int>& getCombos () const;
@@ -41,6 +44,8 @@ public:
 private:
     ShaderUnit m_vertex;
     ShaderUnit m_fragment;
+    /** GS_ENABLED shaders with a .geom, like WE's particle shaders (its renderer always sets that define) */
+    std::unique_ptr<ShaderUnit> m_geometry;
     std::string m_file;
     std::vector<Variables::ShaderVariable*> m_parameters = {};
     const ComboMap& m_combos;

+ 253 - 137
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -5,6 +5,7 @@
 #include <charconv>
 #include <cmath>
 #include <exception>
+#include <functional>
 #include <mutex>
 #include <optional>
 #include <regex>
@@ -38,6 +39,10 @@
 	  "#define max(x, y) max (y, x)\n"                                                                             \
 	  "#define lerp mix\n"                                                                                         \
 	  "#define frac fract\n"                                                                                       \
+	  "#define CASTI(x) (int(x))\n"                                                                               \
+	  "#define CASTU(x) (uint(x))\n"                                                                              \
+	  "#define CASTF(x) (float(x))\n"                                                                             \
+	  "#define CAST4U(x) (uvec4(x))\n"                                                                            \
 	  "#define CAST2(x) (vec2(x))\n"                                                                               \
 	  "#define CAST3(x) (vec3(x))\n"                                                                               \
 	  "#define CAST4(x) (vec4(x))\n"                                                                               \
@@ -51,6 +56,8 @@
 	  "#define saturate(x) (clamp(x, 0.0, 1.0))\n"                                                                 \
 	  "#define texSample2D texture\n"                                                                              \
 	  "#define texSample2DLod textureLod\n"                                                                        \
+	  "#define sampler2DComparison sampler2DShadow\n"                                                             \
+	  "#define texSample2DCompare(s, u, d) vec4 (texture (s, vec3 (u, d)))\n"                                     \
 	  "#define atan2 atan\n"                                                                                       \
 	  "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n"                                                              \
 	  "#define ddx dFdx\n"                                                                                         \
@@ -59,6 +66,8 @@
 #define FRAGMENT_SHADER_DEFINES                                                                                        \
     "out vec4 out_FragColor;\n"                                                                                        \
     "#define varying in\n"
+#define GEOMETRY_SHADER_DEFINES "#define GEOMETRY 1\n"
+#define GEOMETRY_INPUT_PREFIX "wpeGs_"
 #define VERTEX_SHADER_DEFINES                                                                                          \
     "#define attribute in\n"                                                                                           \
     "#define varying out\n"
@@ -114,7 +123,6 @@ ShaderUnit::ShaderUnit (
 
 void ShaderUnit::preprocess () {
     this->m_preprocessed = this->m_content;
-    this->m_includes = "";
 
     this->preprocessIncludes ();
     this->preprocessRequires ();
@@ -171,163 +179,95 @@ void ShaderUnit::preprocessVariables () {
 }
 
 void ShaderUnit::preprocessIncludes () {
-    size_t start = 0, end = 0;
-    while ((start = this->m_preprocessed.find ("#include", end)) != std::string::npos) {
-	const auto parsed = includeFilename (this->m_preprocessed, start);
-
-	// comment out just the "#i" so the string length/offsets are unaffected
-	this->m_preprocessed = this->m_preprocessed.replace (start, 2, "//");
-	end = start;
-
-	if (!parsed.has_value ()) {
-	    sLog.error ("Malformed #include directive in shader ", this->m_file);
-	    continue;
-	}
+    // wallpaper64.exe sub_140162100: line by line, a line starting with #include is replaced by the file between its
+    // quotes (shaders/<name>, expanded the same way) where it stands, every file only once per unit. A file that was
+    // already included, or a line without the quotes, leaves an empty line. WE's translator (sub_1400F5CB0) then
+    // takes every attribute/varying/uniform line out of the code and declares it up front, so included functions see
+    // uniforms the file only declares after the #include. Here the file's own declarations outside any #if move up to
+    // where its first include starts, conditional ones stay where they are
+    std::set<std::string> included;
+    std::string out;
+    std::string hoisted;
+    size_t firstInclude = std::string::npos;
+    int depth = 0;
+    const std::string& source = this->m_preprocessed;
+    size_t start = 0;
 
-	const std::string& filename = *parsed;
-
-	// a missing include isn't necessarily an error - it may come from commented-out content
-	std::string content;
-
-	try {
-	    content += "// begin of include from file ";
-	    content += filename;
-	    content += "\n";
-	    content += this->m_assetLocator.includeShader (filename);
-	    content += "\n// end of included from file ";
-	    content += filename;
-	    content += "\n";
-	} catch (AssetLoadException&) {
-	    content += "// tried including file ";
-	    content += filename;
-	    content += " but was not found\n";
+    while (start < source.size ()) {
+	size_t end = source.find ('\n', start);
+	if (end == std::string::npos) {
+	    end = source.size ();
 	}
 
-	this->m_includes += content;
-    }
-
-    // resolve #include directives found inside already-included content too
-    end = 0;
-
-    while ((start = this->m_includes.find ("#include", end)) != std::string::npos) {
-	const size_t lineEnd = this->m_includes.find_first_of ('\n', start);
-	const auto parsed = includeFilename (this->m_includes, start);
-	end = start;
+	const std::string line = source.substr (start, end - start);
+	const size_t first = line.find_first_not_of (" \t");
+	const std::string trimmed = first == std::string::npos ? "" : line.substr (first);
 
-	if (!parsed.has_value ()) {
-	    sLog.error ("Malformed #include directive in an include of shader ", this->m_file);
-	    this->m_includes = this->m_includes.replace (start, 2, "//");
-	    continue;
+	if (trimmed.starts_with ("#if")) {
+	    depth++;
+	} else if (trimmed.starts_with ("#endif")) {
+	    depth = std::max (depth - 1, 0);
 	}
 
-	const std::string& filename = *parsed;
-
-	// a missing include isn't necessarily an error - it may come from commented-out content
-	std::string content;
-
-	try {
-	    content = "// begin of include from file ";
-	    content += filename;
-	    content += "\n";
-	    content += this->m_assetLocator.includeShader (filename);
-	    content += "\n// end of included from file ";
-	    content += filename;
-	    content += "\n";
-	} catch (AssetLoadException&) {
-	    content = "// tried including file ";
-	    content += filename;
-	    content += " but was not found\n";
+	if (line.starts_with ("#include")) {
+	    if (firstInclude == std::string::npos) {
+		firstInclude = out.size ();
+	    }
+
+	    out += this->expandIncludes (line, included);
+	} else if (
+	    firstInclude != std::string::npos && depth == 0
+	    && (trimmed.starts_with ("uniform ") || trimmed.starts_with ("varying ") || trimmed.starts_with ("attribute "))
+	) {
+	    hoisted += line + '\n';
+	    out += '\n';
+	} else {
+	    out += line + '\n';
 	}
 
-	this->m_includes = this->m_includes.replace (start, lineEnd - start, content);
+	start = end + 1;
     }
 
-    // place the accumulated include contents right before the main function
-    end = 0;
-    bool includesAdded = false;
-
-    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;
-	}
+    if (!hoisted.empty ()) {
+	out.insert (firstInclude, hoisted);
+    }
 
-	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;
+    this->m_preprocessed = out;
+}
 
-	if (latest == std::string::npos) {
-	    latest = lastVarying;
-	} else if (latest < lastVarying && lastVarying != std::string::npos) {
-	    latest = lastVarying;
-	}
+std::string ShaderUnit::expandIncludes (const std::string& source, std::set<std::string>& included) const {
+    std::string out;
+    size_t start = 0;
 
-	if (latest == std::string::npos) {
-	    latest = lastUniform;
-	} else if (latest < lastUniform && lastUniform != std::string::npos) {
-	    latest = lastUniform;
+    while (start < source.size ()) {
+	size_t end = source.find ('\n', start);
+	if (end == std::string::npos) {
+	    end = source.size ();
 	}
 
-	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);
+	if (source.compare (start, 8, "#include") != 0) {
+	    out.append (source, start, end - start + (end < source.size () ? 1 : 0));
+	    start = end + 1;
+	    continue;
 	}
 
-	// start points at the end of the previous line, used below to place the includes
-	start = this->m_preprocessed.rfind ('\n', start);
-
-	// tracks nested #if/#endif so the includes can be moved before the start of the enclosing chain
-	std::stack<size_t> ifdefStack;
-
-	const 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 (this->m_preprocessed.substr (current, 3) == "#if") {
-		ifdefStack.push (current++); // advance past this match so regex_search doesn't rematch it
-		continue;
-	    }
-
-	    current++; // same reason: advance past this match
+	const auto filename = includeFilename (source, start);
 
-	    // an unmatched #endif is most likely a syntax error; ignored for now
-	    if (ifdefStack.empty ()) {
-		continue;
-	    }
-
-	    size_t stackStart = ifdefStack.top ();
-	    ifdefStack.pop ();
-
-	    if (latest > stackStart && latest <= current) {
-		// insertion point is inside a conditional block - move before the #if so includes are
-		// available to all branches (e.g. genericropeparticle.vert has #if GS_ENABLED wrapping two main()s)
-		size_t beforeIfdef = this->m_preprocessed.rfind ('\n', stackStart);
-		latest = (beforeIfdef != std::string::npos) ? beforeIfdef : 0;
+	if (!filename.has_value ()) {
+	    sLog.error ("Malformed #include directive in shader ", this->m_file);
+	} else if (included.insert (*filename).second) {
+	    try {
+		out += this->expandIncludes (this->m_assetLocator.includeShader (*filename), included);
+	    } catch (AssetLoadException&) {
+		sLog.error ("Shader include ", *filename, " of ", this->m_file, " was not found");
 	    }
 	}
 
-	// TODO: IS THIS GOOD ENOUGH? MAYBE WE SHOULD BE GETTING THE FIRST #IF BLOCK INSTEAD?
-	latest = std::min (latest, start);
-
-	this->m_preprocessed.insert (latest + 1, this->m_includes + '\n');
-	includesAdded = true;
-	break;
+	out += '\n';
+	start = end + 1;
     }
 
-    if (!includesAdded) {
-	sLog.exception ("Could not find where to place includes for shader unit ", this->m_file);
-    }
+    return out;
 }
 
 void ShaderUnit::preprocessRequires () {
@@ -363,7 +303,6 @@ void ShaderUnit::preprocessRequires () {
 	this->m_preprocessed = this->m_preprocessed.replace (start, 2, "//");
 
 	if (!moduleCode.empty ()) {
-	    // inserted directly here, not appended to m_includes - that was already consumed by preprocessIncludes
 	    this->m_preprocessed.insert (start, moduleCode);
 	    end = start + moduleCode.length ();
 	} else {
@@ -1226,6 +1165,171 @@ std::string ShaderUnit::applyNonConstantGlobalConstCompatibility (std::string so
     return result;
 }
 
+int ShaderUnit::defineValue (const std::string& name, const std::string& source) const {
+    for (const ComboMap* combos : { &this->m_overrideCombos, &this->m_combos, &this->m_discoveredCombos }) {
+	for (const auto& [comboName, value] : *combos) {
+	    std::string uppercase;
+	    std::ranges::transform (comboName, std::back_inserter (uppercase), ::toupper);
+	    if (uppercase == name) {
+		return value;
+	    }
+	}
+    }
+
+    // the shader's own fallback, like "#ifndef TRAILSUBDIVISION #define TRAILSUBDIVISION 0"
+    std::smatch match;
+    if (std::regex_search (source, match, std::regex ("#define\\s+" + name + "\\s+(-?\\d+)"))) {
+	return std::stoi (match[1].str ());
+    }
+
+    return 0;
+}
+
+namespace {
+/** + - * / and parentheses over integers, what WE's [maxvertexcount(...)] expressions use */
+int evaluateCount (const std::string& text, size_t& at) {
+    const auto skip = [&] () {
+	while (at < text.size () && std::isspace (static_cast<unsigned char> (text[at]))) {
+	    at++;
+	}
+    };
+    const std::function<int ()> sum = [&] () -> int {
+	const std::function<int ()> factor = [&] () -> int {
+	    skip ();
+	    if (at < text.size () && text[at] == '(') {
+		at++;
+		const int value = sum ();
+		skip ();
+		at++;
+		return value;
+	    }
+	    if (at < text.size () && text[at] == '-') {
+		at++;
+		return -factor ();
+	    }
+	    int value = 0;
+	    while (at < text.size () && std::isdigit (static_cast<unsigned char> (text[at]))) {
+		value = value * 10 + (text[at++] - '0');
+	    }
+	    return value;
+	};
+	const auto product = [&] () {
+	    int value = factor ();
+	    for (skip (); at < text.size () && (text[at] == '*' || text[at] == '/'); skip ()) {
+		const char op = text[at++];
+		const int right = factor ();
+		value = op == '*' ? value * right : (right != 0 ? value / right : 0);
+	    }
+	    return value;
+	};
+	int value = product ();
+	for (skip (); at < text.size () && (text[at] == '+' || text[at] == '-'); skip ()) {
+	    const char op = text[at++];
+	    const int right = product ();
+	    value = op == '+' ? value + right : value - right;
+	}
+	return value;
+    };
+
+    return sum ();
+}
+} // namespace
+
+std::string ShaderUnit::applyGeometryOutputNames (std::string source) const {
+    if (this->m_type != GLSLContext::UnitType_Vertex || !this->m_feedsGeometry) {
+	return source;
+    }
+
+    static const std::regex varyingDecl (R"(\bvarying\s+\w+\s+([A-Za-z_]\w*)\s*;)");
+    std::set<std::string> names;
+    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), varyingDecl); it != std::sregex_iterator ();
+	 ++it) {
+	names.insert ((*it)[1].str ());
+    }
+    for (const auto& name : names) {
+	source = std::regex_replace (source, std::regex ("\\b" + name + "\\b"), GEOMETRY_INPUT_PREFIX + name);
+    }
+
+    return source;
+}
+
+std::string ShaderUnit::applyGeometryDialect (std::string source) const {
+    // [maxvertexcount(N)] -> the input and output layouts, N worked out with the combos this unit gets
+    static const std::regex maxVertexCount (R"(\[\s*maxvertexcount\s*\(([^\]]*)\)\s*\])");
+    std::smatch match;
+    if (std::regex_search (source, match, maxVertexCount)) {
+	std::string expression = match[1].str ();
+	static const std::regex identifier (R"([A-Za-z_]\w*)");
+	std::string resolved;
+	auto last = expression.cbegin ();
+	for (auto it = std::sregex_iterator (expression.cbegin (), expression.cend (), identifier);
+	     it != std::sregex_iterator (); ++it) {
+	    resolved.append (last, (*it)[0].first);
+	    resolved += std::to_string (this->defineValue ((*it)[0].str (), source));
+	    last = (*it)[0].second;
+	}
+	resolved.append (last, expression.cend ());
+	size_t at = 0;
+	const int count = std::max (1, evaluateCount (resolved, at));
+
+	source.replace (
+	    match.position (0), match.length (0),
+	    "layout(points) in;\nlayout(triangle_strip, max_vertices = " + std::to_string (count) + ") out;\n"
+	);
+    }
+
+    // the vertex stage's outputs arrive as arrays under the names applyGeometryOutputNames gave them (the same
+    // names are often outputs here too, v_Color), gl_Position is a builtin on both sides
+    source = std::regex_replace (source, std::regex (R"(\b(in|out)\s+vec4\s+gl_Position\s*;)"), "");
+    source = std::regex_replace (
+	source, std::regex (R"((^|\n)(\s*)in\s+(\w+)\s+(\w+)\s*;)"), "$1$2in $3 " GEOMETRY_INPUT_PREFIX "$4[];"
+    );
+
+    source = std::regex_replace (
+	source, std::regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*gl_Position\b)"), "gl_in[$1].gl_Position"
+    );
+    source = std::regex_replace (
+	source, std::regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*(\w+))"), GEOMETRY_INPUT_PREFIX "$2[$1]"
+    );
+
+    // "PS_INPUT v;" is the vertex being written: its fields are the outputs themselves
+    static const std::regex vertexDecl (R"(\bPS_INPUT\s+(\w+)\s*;)");
+    if (std::regex_search (source, match, vertexDecl)) {
+	const std::string name = match[1].str ();
+	source = std::regex_replace (source, vertexDecl, "");
+	source = std::regex_replace (source, std::regex ("(^|[^\\w.])" + name + "\\s*\\.\\s*(\\w+)"), "$1$2");
+	source = std::regex_replace (
+	    source, std::regex ("\\bOUT\\s*\\.\\s*Append\\s*\\(\\s*" + name + "\\s*\\)\\s*;"), "EmitVertex();"
+	);
+    }
+    source = std::regex_replace (source, std::regex (R"(\bOUT\s*\.\s*RestartStrip\s*\(\s*\)\s*;)"), "EndPrimitive();");
+
+    // HLSL lets a loop body redeclare its counter ("for (int s ...) { float s = ...") and use the new one from then
+    // on, GLSL doesn't: the counter gets another name in the loop header
+    static const std::regex loopHeader (R"(for\s*\(\s*int\s+(\w+)\s*=[^;]*;[^;]*;[^)]*\))");
+    std::string result;
+    auto last = source.cbegin ();
+    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), loopHeader); it != std::sregex_iterator ();
+	 ++it) {
+	const std::string counter = (*it)[1].str ();
+	const size_t bodyStart = static_cast<size_t> ((*it)[0].second - source.cbegin ());
+	const size_t bodyEnd = std::min (source.size (), source.find ('}', bodyStart));
+	const std::string body = source.substr (bodyStart, bodyEnd - bodyStart);
+	std::string header = (*it)[0].str ();
+
+	if (std::regex_search (body, std::regex ("\\b(?:float|int|uint|vec[234])\\s+" + counter + "\\s*="))) {
+	    header = std::regex_replace (header, std::regex ("\\b" + counter + "\\b"), "wpeLoop_" + counter);
+	}
+
+	result.append (last, (*it)[0].first);
+	result += header;
+	last = (*it)[0].second;
+    }
+    result.append (last, source.cend ());
+
+    return result;
+}
+
 void ShaderUnit::parseComboConfiguration (const std::string& content, const int defaultValue) {
     // "require"/"requireany" on a combo are editor-only, they decide whether the editor shows the
     // option. wallpaper64.exe (sub_140133B60) never reads them, it just takes the default
@@ -1425,6 +1529,8 @@ const ComboMap& ShaderUnit::getDiscoveredCombos () const { return this->m_discov
 
 void ShaderUnit::linkToUnit (const ShaderUnit* unit) { this->m_link = unit; }
 
+void ShaderUnit::feedGeometryStage () { this->m_feedsGeometry = true; }
+
 const ShaderUnit* ShaderUnit::getLinkedUnit () const { return this->m_link; }
 
 const std::string& ShaderUnit::compile () {
@@ -1462,8 +1568,14 @@ const std::string& ShaderUnit::compile () {
 	this->m_final += "#define log10(x) (log2(x) * 0.301029995663981)\n";
     }
 
+    if (this->m_feedsGeometry) {
+	this->m_final += "// outputs renamed for the geometry stage\n";
+    }
+
     if (this->m_type == GLSLContext::UnitType_Fragment) {
 	this->m_final += FRAGMENT_SHADER_DEFINES;
+    } else if (this->m_type == GLSLContext::UnitType_Geometry) {
+	this->m_final += GEOMETRY_SHADER_DEFINES;
     } else {
 	this->m_final += VERTEX_SHADER_DEFINES;
     }
@@ -1553,7 +1665,11 @@ const std::string& ShaderUnit::compile () {
 	this->applyVectorTruncationCompatibility (this->applyFragmentVaryingShadowCompatibility (
 	    this->applyFragmentTexCoordCompatibility (this->applyNarrowFragmentVaryingCompatibility (
 		this->applyLinkedVaryingCompatibility (this->applyNonConstantGlobalConstCompatibility (
-		    this->applyDirectiveSemicolonCompatibility (this->applyHlslAttributeCompatibility (this->m_preprocessed))
+		    this->applyDirectiveSemicolonCompatibility (this->applyHlslAttributeCompatibility (
+			this->m_type == GLSLContext::UnitType_Geometry
+			    ? this->applyGeometryDialect (this->m_preprocessed)
+			    : this->applyGeometryOutputNames (this->m_preprocessed)
+		    ))
 		))
 	    ))
 	))

+ 10 - 1
src/WallpaperEngine/Render/Shaders/ShaderUnit.h

@@ -29,6 +29,8 @@ public:
 
     /** Links this shader unit with another unit so they're treated as one */
     void linkToUnit (const ShaderUnit* unit);
+    /** This vertex unit feeds a geometry stage, see applyGeometryOutputNames */
+    void feedGeometryStage ();
     [[nodiscard]] const ShaderUnit* getLinkedUnit () const;
 
     [[nodiscard]] const std::string& compile ();
@@ -47,6 +49,7 @@ protected:
 private:
     void preprocessVariables ();
     void preprocessIncludes ();
+    [[nodiscard]] std::string expandIncludes (const std::string& source, std::set<std::string>& included) const;
     void preprocessRequires ();
     /**
      * Some workshop shaders ship with unbalanced #if/#endif blocks (usually a stray extra #endif).
@@ -94,6 +97,12 @@ private:
     /** HLSL flow control attributes (`[loop]`, `[unroll(4)]`, `[branch]`...) in front of a statement pass through
      *  WE's HLSL translation, glslang rejects them. Strips them. */
     [[nodiscard]] std::string applyHlslAttributeCompatibility (std::string source) const;
+    /** WE's geometry shader dialect (IN[0].x, PS_INPUT + OUT.Append, [maxvertexcount]) as a GLSL geometry shader */
+    [[nodiscard]] std::string applyGeometryDialect (std::string source) const;
+    /** A vertex unit feeding a geometry stage gives its outputs the names that stage reads them under */
+    [[nodiscard]] std::string applyGeometryOutputNames (std::string source) const;
+    /** Value of a combo or #define for the geometry shader's vertex count, 0 when unknown */
+    [[nodiscard]] int defineValue (const std::string& name, const std::string& source) const;
 
     void parseComboConfiguration (const std::string& content, int defaultValue = 0);
     void parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content);
@@ -101,8 +110,8 @@ private:
     GLSLContext::UnitType m_type;
     std::string m_file;
     std::string m_content;
-    std::string m_includes;
     std::string m_preprocessed;
+    bool m_feedsGeometry { false };
     std::string m_final;
     std::vector<Variables::ShaderVariable*> m_parameters = {};
     const ComboMap& m_combos;

+ 288 - 0
src/WallpaperEngine/Render/ShadowMapping.cpp

@@ -0,0 +1,288 @@
+#include "ShadowMapping.h"
+
+#include <algorithm>
+#include <cmath>
+#include <string>
+
+#include "WallpaperEngine/Application/ApplicationContext.h"
+#include "WallpaperEngine/Application/WallpaperApplication.h"
+#include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/CFBO.h"
+#include "WallpaperEngine/Render/Objects/CMesh.h"
+#include "WallpaperEngine/Render/RenderContext.h"
+#include "WallpaperEngine/Render/Wallpapers/CScene.h"
+
+using namespace WallpaperEngine::Render;
+
+namespace {
+// assets/shaders/shadowcaster.vert/.frag. WE copies a mesh's SKINNING combo onto the caster material (sub_140155FC0),
+// here one program switches it with u_Skinning (g_Bones sized for the largest BONECOUNT, 128). Morphing isn't
+// ported. With ALPHATOCOVERAGE the GLSL path of the fragment shader discards below 0.5
+const char* kCasterVertex = R"(#version 330
+uniform mat4 u_ModelViewProjection;
+uniform bool u_Skinning;
+uniform mat4x3 g_Bones[128];
+in vec3 a_Position;
+in vec2 a_TexCoord;
+in uvec4 a_BlendIndices;
+in vec4 a_BlendWeights;
+out vec2 v_TexCoord;
+
+void main () {
+    vec3 position = a_Position;
+
+    if (u_Skinning) {
+	position = (g_Bones[a_BlendIndices.x] * a_BlendWeights.x + g_Bones[a_BlendIndices.y] * a_BlendWeights.y
+		    + g_Bones[a_BlendIndices.z] * a_BlendWeights.z + g_Bones[a_BlendIndices.w] * a_BlendWeights.w)
+	    * vec4 (position, 1.0);
+    }
+
+    v_TexCoord = a_TexCoord;
+    gl_Position = u_ModelViewProjection * vec4 (position, 1.0);
+}
+)";
+
+const char* kCasterFragment = R"(#version 330
+uniform sampler2D g_Texture0;
+uniform int u_AlphaTest;
+in vec2 v_TexCoord;
+
+void main () {
+    if (u_AlphaTest != 0) {
+	float alpha = texture (g_Texture0, v_TexCoord).a;
+	alpha = (alpha - 0.5) / max (fwidth (alpha), 0.0001) + 0.5;
+
+	if (alpha < 0.5) {
+	    discard;
+	}
+    }
+}
+)";
+
+GLuint compile (const GLenum type, const char* source) {
+    const GLuint shader = glCreateShader (type);
+    glShaderSource (shader, 1, &source, nullptr);
+    glCompileShader (shader);
+
+    GLint compiled = GL_FALSE;
+    glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled);
+
+    if (compiled == GL_FALSE) {
+	char log[2048] = {};
+	glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
+	sLog.error ("Shadow caster shader failed to compile: ", log);
+    }
+
+    return shader;
+}
+
+// WE's matrices put Direct3D's depth 0..1 into z and its viewport maps y = +1 to the first row of the target. The
+// same memory layout in GL: y flipped and z moved to -w..w, the window depth is then WE's depth value
+glm::mat4 toGL (const glm::mat4& direct3D) {
+    glm::mat4 convert (1.0f);
+    convert[1][1] = -1.0f;
+    convert[2][2] = 2.0f;
+    convert[3][2] = -1.0f;
+    return convert * direct3D;
+}
+} // namespace
+
+ShadowMapping::ShadowMapping (Wallpapers::CScene& scene, std::shared_ptr<const CFBO> atlas) :
+    m_scene (scene), m_atlas (std::move (atlas)) { }
+
+ShadowMapping::~ShadowMapping () {
+    if (this->m_program != GL_NONE) {
+	glDeleteProgram (this->m_program);
+    }
+}
+
+int ShadowMapping::tileSize (const int quality) {
+    switch (quality) {
+	case 3:
+	    return 512;
+	case 4:
+	    return 1024;
+	default:
+	    return 256;
+    }
+}
+
+glm::mat4 ShadowMapping::perspective (const float fovRadians, const float aspect, const float near, const float far) {
+    // sub_14009A360 is XMMatrixPerspectiveFovRH with near and far swapped: 1 at the near plane, 0 at the far one
+    const float height = 1.0f / std::tan (fovRadians * 0.5f);
+    glm::mat4 projection (0.0f);
+
+    projection[0][0] = height / aspect;
+    projection[1][1] = height;
+    projection[2][2] = near / (far - near);
+    projection[2][3] = -1.0f;
+    projection[3][2] = far * near / (far - near);
+
+    return projection;
+}
+
+void ShadowMapping::setup () {
+    const GLuint vertex = compile (GL_VERTEX_SHADER, kCasterVertex);
+    const GLuint fragment = compile (GL_FRAGMENT_SHADER, kCasterFragment);
+
+    this->m_program = glCreateProgram ();
+    glAttachShader (this->m_program, vertex);
+    glAttachShader (this->m_program, fragment);
+    glLinkProgram (this->m_program);
+    glDeleteShader (vertex);
+    glDeleteShader (fragment);
+
+    this->m_modelViewProjection = glGetUniformLocation (this->m_program, "u_ModelViewProjection");
+    this->m_alphaTest = glGetUniformLocation (this->m_program, "u_AlphaTest");
+    glUseProgram (this->m_program);
+    glUniform1i (glGetUniformLocation (this->m_program, "g_Texture0"), 0);
+}
+
+glm::ivec2 ShadowMapping::pack (std::vector<Entry>& entries) {
+    // sub_140190C80 0x1401936f8: rows of free space (x from, x to, y top, y bottom), the first one 8192 wide. A tile
+    // goes into the first row with room for it, which then also leaves a column below it as a row of its own. Every
+    // row it passes without room makes a new full width row below that one
+    struct Row {
+	uint16_t x0;
+	uint16_t x1;
+	uint16_t y0;
+	uint16_t y1;
+    };
+    std::vector<Row> rows = { { 0, 0x2000, 0, 0 } };
+    int width = 0;
+    int height = 0;
+
+    for (auto& entry : entries) {
+	const int size = entry.size;
+
+	for (size_t i = 0; i < rows.size (); i++) {
+	    Row& row = rows[i];
+	    row.y1 = static_cast<uint16_t> (std::max<int> (row.y1, row.y0 + size));
+
+	    const auto rowHeight = static_cast<uint16_t> (row.y1 - row.y0);
+
+	    if (static_cast<uint16_t> (row.x1 - row.x0) >= size && rowHeight >= size) {
+		entry.x = row.x0;
+		entry.y = row.y0;
+		width = std::max (width, size + row.x0);
+		height = std::max (height, row.y0 + size);
+		row.x0 = static_cast<uint16_t> (row.x0 + size);
+
+		if (rowHeight > 0) {
+		    const Row below = { static_cast<uint16_t> (row.x0 - size), row.x0,
+					static_cast<uint16_t> (row.y0 + size), row.y1 };
+		    rows.push_back (below);
+		}
+		break;
+	    }
+
+	    const uint16_t top = row.y1;
+	    rows.push_back ({ 0, 0x2000, top, top });
+	}
+    }
+
+    return { width, height };
+}
+
+void ShadowMapping::render (std::vector<Entry>& entries) {
+    if (entries.empty ()) {
+	return;
+    }
+
+    if (this->m_program == GL_NONE) {
+	this->setup ();
+    }
+
+    // the atlas grows to at least 2x2 and is only reallocated when it's too small on either side, then to exactly
+    // the size the tiles need
+    const glm::ivec2 needed = glm::max (pack (entries), glm::ivec2 (2));
+    auto atlas = std::const_pointer_cast<CFBO> (this->m_atlas);
+
+    if (static_cast<int> (atlas->getRealWidth ()) < needed.x || static_cast<int> (atlas->getRealHeight ()) < needed.y) {
+	atlas->resize (needed.x, needed.y);
+    }
+
+    const auto atlasWidth = static_cast<float> (atlas->getRealWidth ());
+    const auto atlasHeight = static_cast<float> (atlas->getRealHeight ());
+
+    GLint previousFramebuffer = 0;
+    GLint previousVAO = 0;
+    GLint previousViewport[4] = {};
+    glGetIntegerv (GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
+    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVAO);
+    glGetIntegerv (GL_VIEWPORT, previousViewport);
+
+    // sub_140196530: the first batch clears the atlas to WE's reversed far depth, then the casters draw with depth
+    // GREATER and the shadow rasterizer state (device +37 bit 2) of sub_140099050: slope scaled bias -4 (towards
+    // the far side) and no culling, the cull mode of the previous state creation is never reset for it (RenderDoc of
+    // live WE: NoCull, slope -4, D32)
+    glBindFramebuffer (GL_FRAMEBUFFER, atlas->getFramebuffer ());
+    glDepthMask (GL_TRUE);
+    glClearDepth (0.0);
+    glClear (GL_DEPTH_BUFFER_BIT);
+    glClearDepth (1.0);
+    glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
+    glDisable (GL_BLEND);
+    glEnable (GL_DEPTH_TEST);
+    glDepthFunc (GL_GREATER);
+    glDisable (GL_CULL_FACE);
+    glEnable (GL_POLYGON_OFFSET_FILL);
+    glPolygonOffset (-4.0f, 0.0f);
+    glUseProgram (this->m_program);
+
+    for (auto& entry : entries) {
+	*entry.transform = glm::vec4 (
+	    static_cast<float> (entry.x) / atlasWidth, static_cast<float> (entry.y) / atlasHeight,
+	    static_cast<float> (entry.size) / atlasWidth, static_cast<float> (entry.size) / atlasHeight
+	);
+
+	if (entry.point) {
+	    // six faces two across, three down, each half and a third of the tile (integer sizes like WE). The cube
+	    // faces' projection gets [3][2] - 0.00333 (0x140193b4c), pulling the depth away from the light
+	    const int faceWidth = entry.size >> 1;
+	    const int faceHeight = entry.size / 3;
+
+	    for (int face = 0; face < 6; face++) {
+		glm::mat4 biased = entry.viewProjection[face];
+		biased[3][2] -= 0.00333f;
+
+		glViewport (
+		    entry.x + (face & 1) * faceWidth, entry.y + (face >> 1) * faceHeight, faceWidth, faceHeight
+		);
+		this->drawCasters (toGL (biased), biased);
+	    }
+	    continue;
+	}
+
+	// every other shadow gets its depth pulled 0.0005 away from the light in clip space (0x14019632a: the
+	// viewport matrix's [3][2] - 0.0005), the lit materials compare against the matrix without it
+	glm::mat4 biased = entry.viewProjection[0];
+	biased[3][2] -= 0.0005f;
+
+	glViewport (entry.x, entry.y, entry.size, entry.size);
+	this->drawCasters (toGL (biased), biased);
+    }
+
+    glDisable (GL_POLYGON_OFFSET_FILL);
+    glPolygonOffset (0.0f, 0.0f);
+    glDepthFunc (GL_LESS);
+    glDisable (GL_DEPTH_TEST);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+    glBindVertexArray (previousVAO);
+    glBindFramebuffer (GL_FRAMEBUFFER, previousFramebuffer);
+    glViewport (previousViewport[0], previousViewport[1], previousViewport[2], previousViewport[3]);
+}
+
+void ShadowMapping::drawCasters (const glm::mat4& viewProjection, const glm::mat4& direct3D) const {
+    // sub_14018AAC0 mode 2: the scene's render list, objects with flags 0xC00 (models with a normal or
+    // alphatocoverage material, sub_140224C70), visible and not drawn by a passthrough layer
+    for (auto* object : this->m_scene.getLayers ()) {
+	if (!object->is<Objects::CMesh> () || !this->m_scene.isShadowCasterVisible (*object)) {
+	    continue;
+	}
+
+	object->as<Objects::CMesh> ()->renderShadowCaster (
+	    this->m_program, this->m_modelViewProjection, this->m_alphaTest, viewProjection, direct3D
+	);
+    }
+}

+ 58 - 0
src/WallpaperEngine/Render/ShadowMapping.h

@@ -0,0 +1,58 @@
+#pragma once
+
+#include <GL/glew.h>
+#include <glm/glm.hpp>
+#include <memory>
+#include <vector>
+
+namespace WallpaperEngine::Render::Wallpapers {
+class CScene;
+}
+
+namespace WallpaperEngine::Render {
+class CFBO;
+
+/**
+ * LightingV1 shadow maps, wallpaper64.exe 2.8.42 sub_140190C80 (atlas layout, per light matrices) and sub_140196530
+ * (the caster pass). Every shadow is a square tile of one depth atlas (_rt_shadowAtlas, 32 bit float), rendered with
+ * WE's reversed depth (1 at the near plane) so the stored values are exactly what its lit materials compare against
+ */
+class ShadowMapping {
+public:
+    /** One shadow of a light: a spot, one cascade of a directional light or the six cube faces of a point light */
+    struct Entry {
+	/** Direct3D clip space of WE (depth 0..1, reversed), one per viewport */
+	glm::mat4 viewProjection[6] = {};
+	bool point = false;
+	int size = 0;
+	/** Where the tile ends up in the atlas, (x, y, size, size) / atlas size, what the lit materials read */
+	glm::vec4* transform = nullptr;
+	int x = 0;
+	int y = 0;
+    };
+
+    explicit ShadowMapping (Wallpapers::CScene& scene, std::shared_ptr<const CFBO> atlas);
+    ~ShadowMapping ();
+
+    /** Places the entries in the atlas, grows it if needed and draws every shadow caster into their tiles */
+    void render (std::vector<Entry>& entries);
+
+    /** Size of one shadow tile for WE's shadow quality 1..4 (sub_14025D3E0) */
+    [[nodiscard]] static int tileSize (int quality);
+    /** Right handed PerspectiveFov with Direct3D's reversed depth, like WE's device (sub_14009A360) */
+    [[nodiscard]] static glm::mat4 perspective (float fovRadians, float aspect, float near, float far);
+
+private:
+    void setup ();
+    /** The row packing of sub_140190C80, returns the space the tiles take */
+    static glm::ivec2 pack (std::vector<Entry>& entries);
+    /** viewProjection in GL clip space, direct3D the same one as WE has it (for its culling) */
+    void drawCasters (const glm::mat4& viewProjection, const glm::mat4& direct3D) const;
+
+    Wallpapers::CScene& m_scene;
+    std::shared_ptr<const CFBO> m_atlas;
+    GLuint m_program = GL_NONE;
+    GLint m_modelViewProjection = -1;
+    GLint m_alphaTest = -1;
+};
+} // namespace WallpaperEngine::Render

+ 169 - 13
src/WallpaperEngine/Render/Volumetrics.cpp

@@ -1,5 +1,6 @@
 #include "Volumetrics.h"
 
+#include <bit>
 #include <cmath>
 #include <string>
 
@@ -41,10 +42,12 @@ void main () {
 }
 )";
 
-// assets/shaders/volumetricsfront.frag without cookies: from the near side of the volume to the far one (or the scene's
-// depth in front of it), the light's falloff summed over a few samples. The shadow atlas has nothing in it (no shadow
-// casters), so every sample is lit
+// assets/shaders/volumetricsfront.frag: from the near side of the volume to the far one (or the scene's depth in front
+// of it), the light's falloff summed over a few samples. With SHADOW each sample is compared against the light's tile of
+// _rt_shadowAtlas (g_Texture0), spots through the light's matrix scaled by 0.525 like the cookie, point lights through
+// common_pbr_2.h's CalculateProjectedCoordsPoint (copied below)
 const char* kFrontFragment = R"(
+#define mul(x, y) ((y) * (x))
 uniform sampler2D u_Back;
 uniform sampler2D u_SceneDepth;
 uniform mat4 u_InverseViewProjection;
@@ -65,9 +68,122 @@ uniform vec3 g_FogDistanceColor;
 uniform vec4 g_FogDistanceParams;
 uniform vec3 g_FogHeightColor;
 uniform vec4 g_FogHeightParams;
+uniform sampler2DShadow u_ShadowAtlas;
+uniform bool u_ShadowValid;
+uniform mat4 u_ShadowMatrix;
+uniform vec4 u_ShadowTransform;
+uniform vec4 u_PointProjection;
 in vec4 v_ScreenPos;
 out vec4 fragColor;
 
+#if SHADOW && POINTLIGHT
+vec4 CalculateProjectedCoordsPoint(vec3 worldPos, vec3 lightOrigin, vec4 projectionInfo, vec4 atlasTransform)
+{
+	vec3 lightDelta = worldPos - lightOrigin;
+	vec3 lightDeltaAbs = abs(lightDelta);
+	vec2 viewportScale = vec2(0.5, 0.3333);
+
+#if LIGHTS_SHADOW_MAPPING_QUALITY == 2 || LIGHTS_SHADOW_MAPPING_QUALITY == 1
+	vec2 viewportPointCompensation = vec2(0.47, -0.47);
+#elif LIGHTS_SHADOW_MAPPING_QUALITY == 3
+	vec2 viewportPointCompensation = vec2(0.48, -0.48);
+#else
+	vec2 viewportPointCompensation = vec2(0.49, -0.49);
+#endif
+
+	vec2 viewportOffset;
+	vec2 viewportOffsetSteps = atlasTransform.zw * viewportScale;
+	mat4 viewMatrix;
+
+	if (lightDeltaAbs.x >= lightDeltaAbs.y && lightDeltaAbs.x >= lightDeltaAbs.z)
+	{
+		if (lightDelta.x >= 0.0)
+		{
+			viewMatrix = mat4(
+				0, 0, -1, 0,
+				0, 1, 0, 0,
+				1, 0, 0, 0,
+				-lightOrigin.z, -lightOrigin.y, lightOrigin.x, 1
+			);
+			viewportOffset = vec2(0.0, 0.0);
+		}
+		else
+		{
+			viewMatrix = mat4(
+				0, 0, 1, 0,
+				0, 1, 0, 0,
+				-1, 0, 0, 0,
+				lightOrigin.z, -lightOrigin.y, -lightOrigin.x, 1
+			);
+			viewportOffset = vec2(viewportOffsetSteps.x, 0.0);
+		}
+	}
+	else if (lightDeltaAbs.y >= lightDeltaAbs.x && lightDeltaAbs.y >= lightDeltaAbs.z)
+	{
+		if (lightDelta.y >= 0.0)
+		{
+			viewMatrix = mat4(
+				1, 0, 0, 0,
+				0, 0, -1, 0,
+				0, 1, 0, 0,
+				-lightOrigin.x, -lightOrigin.z, lightOrigin.y, 1
+			);
+			viewportOffset = vec2(0.0, viewportOffsetSteps.y);
+		}
+		else
+		{
+			viewMatrix = mat4(
+				1, 0, 0, 0,
+				0, 0, 1, 0,
+				0, -1, 0, 0,
+				-lightOrigin.x, lightOrigin.z, -lightOrigin.y, 1
+			);
+			viewportOffset = vec2(viewportOffsetSteps.x, viewportOffsetSteps.y);
+		}
+	}
+	else
+	{
+		if (lightDelta.z >= 0.0)
+		{
+			viewMatrix = mat4(
+				-1, 0, 0, 0,
+				0, 1, 0, 0,
+				0, 0, -1, 0,
+				lightOrigin.x, -lightOrigin.y, lightOrigin.z, 1
+			);
+			viewportOffset = vec2(0.0, viewportOffsetSteps.y * 2);
+		}
+		else
+		{
+			viewMatrix = mat4(
+				1, 0, 0, 0,
+				0, 1, 0, 0,
+				0, 0, 1, 0,
+				-lightOrigin.x, -lightOrigin.y, -lightOrigin.z, 1
+			);
+			viewportOffset = vec2(viewportOffsetSteps.x, viewportOffsetSteps.y * 2);
+		}
+	}
+
+	mat4 project = mat4(
+		1, 0, 0, 0,
+		0, 1, 0, 0,
+		0, 0, projectionInfo.x, projectionInfo.z,
+		0, 0, projectionInfo.y, projectionInfo.w
+	);
+
+	vec4 projectedCoords = mul(mul(vec4(worldPos, 1.0), viewMatrix), project);
+	projectedCoords.xyz /= projectedCoords.w;
+
+	projectedCoords.xy = projectedCoords.xy	* viewportPointCompensation + vec2(0.5);
+	projectedCoords.y = mix(projectedCoords.y, 2.0, step(projectedCoords.w, 0.0));
+
+	projectedCoords.xy *= atlasTransform.zw * viewportScale;
+	projectedCoords.xy += atlasTransform.xy + viewportOffset;
+	return projectedCoords;
+}
+#endif
+
 float hash12 (vec2 p) {
     vec3 p3 = fract (vec3 (p.xyx) * 43758.5453);
     p3 += vec3 (dot (p3, p3.yzx + 19.19));
@@ -129,6 +245,18 @@ void main () {
 	worldStart.xyz += worldStep;
 	vec3 lightDelta = worldStart.xyz - u_LightOrigin;
 	float sampleValue = pow (clamp (1.0 - length (lightDelta) * invRadius, 0.0, 1.0), u_Exponent);
+#if SHADOW
+	if (u_ShadowValid) {
+#if POINTLIGHT
+	    vec4 shadowCoords = CalculateProjectedCoordsPoint (worldStart.xyz, u_LightOrigin, u_PointProjection, u_ShadowTransform);
+#else
+	    vec4 shadowCoords = u_ShadowMatrix * vec4 (worldStart.xyz, 1.0);
+	    shadowCoords.xyz /= shadowCoords.w;
+	    shadowCoords.xy = (shadowCoords.xy * vec2 (0.525, -0.525) + vec2 (0.5)) * u_ShadowTransform.zw + u_ShadowTransform.xy;
+#endif
+	    sampleValue *= texture (u_ShadowAtlas, shadowCoords.xyz);
+	}
+#endif
 #if COOKIE
 	// the cookie is projected through the light's own camera, a little bigger than its frustum
 	vec4 uvs = u_LightViewProjection * vec4 (worldStart.xyz, 1.0);
@@ -395,8 +523,10 @@ void Volumetrics::setup () {
     }
 
     const std::string samples = "#define SAMPLES " + std::to_string (plain[quality - 1]) + "\n";
-    const std::string shadowSamples
-	= "#define SHADOW 1\n#define SAMPLES " + std::to_string (shadowed[quality - 1]) + "\n";
+    // LIGHTS_SHADOW_MAPPING_QUALITY only goes to point lights (renderer +428), the other shaders don't read it
+    const std::string shadowSamples = "#define SHADOW 1\n#define SAMPLES " + std::to_string (shadowed[quality - 1])
+	+ "\n#define LIGHTS_SHADOW_MAPPING_QUALITY "
+	+ std::to_string (this->m_scene.getContext ().getApp ().getContext ().settings.general.shadowQuality) + "\n";
 
     this->m_backProgram = compile ("", kVolumeVertex, kBackFragment);
 
@@ -461,15 +591,23 @@ void Volumetrics::release () {
     this->m_backDepth = GL_NONE;
 }
 
+glm::vec3 Volumetrics::approximateNormalize (const glm::vec3& vector) {
+    const float lengthSquared = glm::dot (vector, vector);
+    const float guess = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (lengthSquared) >> 1));
+    const float inverse = (1.5f - lengthSquared * 0.5f * guess * guess) * guess;
+
+    return vector * inverse;
+}
+
 glm::mat4 Volumetrics::spotViewProjection (
     const Data::Model::Light& light, const glm::mat4& world, const bool orthographic
 ) {
     // sub_14025D420: the light looks down its x axis (view rows z, y, -x of the normalized world axes) through a
     // right handed PerspectiveFov (sub_14009A360) of twice the outer cone, aspect 1, near 0.05 (1 in orthographic
     // scenes), far the radius. Depth runs 0..1 like Direct3D, the cone mesh is built in that space
-    const glm::vec3 x = glm::normalize (glm::vec3 (world[0]));
-    const glm::vec3 y = glm::normalize (glm::vec3 (world[1]));
-    const glm::vec3 z = glm::normalize (glm::vec3 (world[2]));
+    const glm::vec3 x = approximateNormalize (glm::vec3 (world[0]));
+    const glm::vec3 y = approximateNormalize (glm::vec3 (world[1]));
+    const glm::vec3 z = approximateNormalize (glm::vec3 (world[2]));
     const glm::vec3 origin (world[3]);
     glm::mat4 view (1.0f);
 
@@ -566,7 +704,7 @@ void Volumetrics::copySceneDepth (const GLint framebuffer) {
 }
 
 void Volumetrics::renderLight (
-    const Data::Model::Light& light, const glm::mat4& world, const glm::mat4& viewProjection
+    const Data::Model::Light& light, const glm::mat4& world, const glm::mat4& viewProjection, const Shadow* shadow
 ) {
     if (this->m_quality <= 0) {
 	return;
@@ -603,7 +741,7 @@ void Volumetrics::renderLight (
 	? glm::vec3 (0.0f, 0.0f, -1.0f)
 	: -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
     const glm::vec3 probe = fog.eyeWorld + forward * 0.2f - origin;
-    const bool shadow
+    const bool shadowed
 	= light.castShadow && this->m_scene.getContext ().getApp ().getContext ().settings.general.shadowQuality > 0;
     glm::mat4 volume;
     bool inside;
@@ -612,12 +750,14 @@ void Volumetrics::renderLight (
 	= spot ? spotViewProjection (light, world, camera.isOrthogonal ()) : glm::mat4 (1.0f);
 
     if (cookie) {
-	// the eye is inside the frustum's planes (sub_1401849E0: |x|, |y|, |z| <= w of the light's clip space)
+	// the eye is inside the frustum's planes (sub_1401849E0: x+w, w-x, y+w, w-y, z+w, w-z all >= 0) of the light's
+	// +824 matrix, which has reversed depth (z' = w - z here). That gives 0 <= z <= 2w: the near plane counts, the
+	// far one practically never does (2w lies past the camera's infinite distance once far > 2 near)
 	volume = glm::inverse (lightViewProjection);
 
 	const glm::vec4 clip = lightViewProjection * glm::vec4 (fog.eyeWorld + forward * 0.1f, 1.0f);
 
-	inside = std::abs (clip.x) <= clip.w && std::abs (clip.y) <= clip.w && std::abs (clip.z) <= clip.w;
+	inside = std::abs (clip.x) <= clip.w && std::abs (clip.y) <= clip.w && clip.z >= 0.0f && clip.z <= 2.0f * clip.w;
     } else if (spot) {
 	// the cone is drawn from the light's clip space, whose inverse also gives the cone's radius at the far plane.
 	// The eye is inside when it's in front of the light, no further than the radius and within the cone there
@@ -685,7 +825,7 @@ void Volumetrics::renderLight (
     glBlendEquation (GL_FUNC_ADD);
     glBlendFunc (GL_ONE, GL_ONE);
 
-    const GLuint program = this->m_frontPrograms[cookie ? 2 : spot ? 1 : 0][shadow][inside];
+    const GLuint program = this->m_frontPrograms[cookie ? 2 : spot ? 1 : 0][shadowed][inside];
     const glm::mat4 inverse = glm::inverse (viewProjection);
     const glm::vec3 color = light.color->value->getVec3 ();
     const glm::vec3 spotForward (world[0]);
@@ -712,6 +852,22 @@ void Volumetrics::renderLight (
 	glActiveTexture (GL_TEXTURE0);
 	glUniform1i (glGetUniformLocation (program, "u_Cookie"), 2);
     }
+    // g_RenderVar0 = the tile's atlas transform, g_RenderVar3 = the point projection, g_AltModelMatrix = the spot's
+    // matrix, the atlas on g_Texture0 with WE's comparison sampler (CFBO::setupDepthOnly)
+    const bool shadowValid = shadowed && shadow != nullptr && shadow->atlasTransform != nullptr;
+
+    glUniform1i (glGetUniformLocation (program, "u_ShadowValid"), shadowValid ? 1 : 0);
+
+    if (shadowValid) {
+	glActiveTexture (GL_TEXTURE3);
+	glBindTexture (GL_TEXTURE_2D, this->m_scene.getShadowAtlas ()->getTextureID (0));
+	glActiveTexture (GL_TEXTURE0);
+	glUniform1i (glGetUniformLocation (program, "u_ShadowAtlas"), 3);
+	glUniformMatrix4fv (glGetUniformLocation (program, "u_ShadowMatrix"), 1, GL_FALSE, &shadow->matrix[0][0]);
+	glUniform4fv (glGetUniformLocation (program, "u_ShadowTransform"), 1, &(*shadow->atlasTransform)[0]);
+	glUniform4fv (glGetUniformLocation (program, "u_PointProjection"), 1, &shadow->pointProjection[0]);
+    }
+
     glUniformMatrix4fv (glGetUniformLocation (program, "u_ViewProjection"), 1, GL_FALSE, &viewProjection[0][0]);
     glUniformMatrix4fv (glGetUniformLocation (program, "u_Volume"), 1, GL_FALSE, &volume[0][0]);
     glUniformMatrix4fv (glGetUniformLocation (program, "u_InverseViewProjection"), 1, GL_FALSE, &inverse[0][0]);

+ 19 - 2
src/WallpaperEngine/Render/Volumetrics.h

@@ -19,17 +19,34 @@ namespace WallpaperEngine::Render {
  */
 class Volumetrics {
 public:
+    /** What a light with castshadow hands its volume when shadows are on (sub_140196CE0 with the light's +824 matrix,
+     *  +784 atlas transform and +800 point projection, all three written by sub_140190C80) */
+    struct Shadow {
+	/** Direct3D clip space of the light, reversed depth: a spot's view projection (unused for point lights) */
+	glm::mat4 matrix {};
+	/** (x, y, size, size) / atlas size of its tile, filled in when the atlas is laid out */
+	const glm::vec4* atlasTransform = nullptr;
+	/** (m22, m32, m23, m33) of a point light's cube face projection */
+	glm::vec4 pointProjection {};
+    };
+
     explicit Volumetrics (Wallpapers::CScene& scene);
     ~Volumetrics ();
 
     /** Raymarches the light's volume into the light buffer, the first light after a composite clears it. Point
-     *  lights use a sphere (their world matrix scaled by the radius), spot lights a cone */
-    void renderLight (const Data::Model::Light& light, const glm::mat4& world, const glm::mat4& viewProjection);
+     *  lights use a sphere (their world matrix scaled by the radius), spot lights a cone. With a shadow every sample is
+     *  tested against the light's tile of the shadow atlas */
+    void renderLight (
+	const Data::Model::Light& light, const glm::mat4& world, const glm::mat4& viewProjection, const Shadow* shadow
+    );
     /** Adds the light buffer onto the scene buffer if a light went into it since the last time */
     void composite ();
     /** A spot light's view projection (sub_14025D420), Direct3D depth 0..1, what its volume and cookie use */
     [[nodiscard]] static glm::mat4
     spotViewProjection (const Data::Model::Light& light, const glm::mat4& world, bool orthographic);
+    /** WE's normalize for light bases (sub_14025D420, sub_1400DC250): the 0x5F375A86 inverse square root with one
+     *  Newton step, up to 0.17% short of unit length */
+    [[nodiscard]] static glm::vec3 approximateNormalize (const glm::vec3& vector);
 
 private:
     struct Target {

+ 106 - 91
src/WallpaperEngine/Render/WallpaperState.cpp

@@ -2,6 +2,7 @@
 #include "TextureProvider.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include <algorithm>
+#include <cmath>
 
 using namespace WallpaperEngine::Render;
 
@@ -21,6 +22,9 @@ std::optional<WallpaperState::TextureUVsScaling> WallpaperState::parseScalingMod
     if (value == "center") {
 	return TextureUVsScaling::CenterUVs;
     }
+    if (value == "free") {
+	return TextureUVsScaling::FreeUVs;
+    }
     if (value == "default") {
 	return TextureUVsScaling::DefaultUVs;
     }
@@ -49,36 +53,92 @@ void WallpaperState::resetUVs () {
     }
 }
 
-void WallpaperState::updateUs (const int& projectionWidth, const int& projectionHeight) {
-    const float viewportWidth = this->getViewportWidth ();
-    const float viewportHeight = this->getViewportHeight ();
-    const int newWidth = viewportHeight / projectionHeight * projectionWidth;
-    const float newCenter = newWidth / 2.0f;
-    const float viewportCenter = viewportWidth / 2.0;
-
-    const float left = newCenter - viewportCenter;
-    const float right = newCenter + viewportCenter;
+glm::vec4 WallpaperState::alignmentMargins (const int mode) const {
+    const float width = static_cast<float> (this->getProjectionWidth ());
+    const float height = static_cast<float> (this->getProjectionHeight ());
+    const float outputWidth = static_cast<float> (this->getViewportWidth ());
+    const float outputHeight = static_cast<float> (this->getViewportHeight ());
+    const float sceneAspect = width / height;
+    const float outputAspect = outputWidth / outputHeight;
+    const float position = this->m_alignment.position;
+    const float x = this->m_alignment.x;
+    const float y = this->m_alignment.y;
+    float left = 0.0f;
+    float right = 0.0f;
+    float bottom = 0.0f;
+    float top = 0.0f;
+
+    switch (mode) {
+	case 0:
+	    // cover: the axis that sticks out is cut, position 0 keeps the right or the top edge
+	    if (sceneAspect > outputAspect) {
+		const float half = (width - height / outputHeight * outputWidth) * 0.5f;
+		left = 2.0f * (1.0f - position) * half;
+		right = 2.0f * position * half;
+	    } else {
+		const float half = (height - width / outputWidth * outputHeight) * 0.5f;
+		top = 2.0f * position * half;
+		bottom = 2.0f * (1.0f - position) * half;
+	    }
+	    break;
+	case 1:
+	    // fit: the other axis gets bars, position 0 puts the scene on the left or the top
+	    if (outputAspect > sceneAspect) {
+		const float half = (width - height / outputHeight * outputWidth) * 0.5f;
+		left = 2.0f * position * half;
+		right = 2.0f * (1.0f - position) * half;
+	    } else {
+		const float half = (height - width / outputWidth * outputHeight) * 0.5f;
+		top = 2.0f * position * half;
+		bottom = 2.0f * (1.0f - position) * half;
+	    }
+	    break;
+	case 3:
+	    // center: native size, x/y 0 keep the left and top edges
+	    left = x * (width - outputWidth);
+	    right = (1.0f - x) * (width - outputWidth);
+	    top = y * (height - outputHeight);
+	    bottom = (1.0f - y) * (height - outputHeight);
+	    break;
+	case 4: {
+	    // free: x/y slide the native size scene from past one edge to past the other, the zoom scales the shown
+	    // region by (2 - zoom)^4, no smaller than 1% of it
+	    const float baseLeft = width - x * (outputWidth + width);
+	    const float baseTop = height - y * (outputHeight + height);
+	    const float baseRight = width - (1.0f - x) * (outputWidth + width);
+	    const float baseBottom = height - (1.0f - y) * (outputHeight + height);
+	    const float scale = std::max (-0.99f, std::pow (2.0f - this->m_alignment.zoom, 4.0f) - 1.0f);
+	    const float growY = (height - baseTop - baseBottom) * scale;
+	    const float growX = (width - baseRight - baseLeft) * scale;
+
+	    left = baseLeft - growX * x;
+	    right = baseRight - growX * (1.0f - x);
+	    top = baseTop - growY * y;
+	    bottom = baseBottom - growY * (1.0f - y);
+	    break;
+	}
+	default:
+	    break;
+    }
 
-    this->m_UVs.ustart = left / newWidth;
-    this->m_UVs.uend = right / newWidth;
+    return { left, right, bottom, top };
 }
 
-void WallpaperState::updateVs (const int& projectionWidth, const int& projectionHeight) {
-    const float viewportWidth = this->getViewportWidth ();
-    const float viewportHeight = this->getViewportHeight ();
-    const int newHeight = viewportWidth / projectionWidth * projectionHeight;
-    const float newCenter = newHeight / 2.0f;
-    const float viewportCenter = viewportHeight / 2.0;
+void WallpaperState::setMargins (const glm::vec4& margins) {
+    const float width = static_cast<float> (this->getProjectionWidth ());
+    const float height = static_cast<float> (this->getProjectionHeight ());
 
-    const float down = newCenter - viewportCenter;
-    const float up = newCenter + viewportCenter;
+    this->m_UVs.ustart = margins.x / width;
+    this->m_UVs.uend = 1.0f - margins.y / width;
 
-    if (m_vflip) {
-	this->m_UVs.vstart = down / newHeight;
-	this->m_UVs.vend = up / newHeight;
+    // v runs top down in a flipped state, bottom up otherwise. The scene is laid out y down here, so WE's top margin
+    // (y up) is the one at the v origin of the canvas
+    if (this->m_vflip) {
+	this->m_UVs.vstart = margins.z / height;
+	this->m_UVs.vend = 1.0f - margins.w / height;
     } else {
-	this->m_UVs.vstart = up / newHeight;
-	this->m_UVs.vend = down / newHeight;
+	this->m_UVs.vstart = 1.0f - margins.z / height;
+	this->m_UVs.vend = margins.w / height;
     }
 }
 
@@ -87,55 +147,11 @@ template <> void WallpaperState::updateTextureUVs<WallpaperState::TextureUVsScal
 }
 
 template <> void WallpaperState::updateTextureUVs<WallpaperState::TextureUVsScaling::ZoomFillUVs> () {
-    this->resetUVs ();
-
-    const int viewportWidth = this->getViewportWidth ();
-    const int viewportHeight = this->getViewportHeight ();
-    int projectionWidth = this->getProjectionWidth ();
-    int projectionHeight = this->getProjectionHeight ();
-
-    const float m1 = static_cast<float> (viewportWidth) / projectionWidth;
-    const float m2 = static_cast<float> (viewportHeight) / projectionHeight;
-    const float m = std::max (m1, m2);
-    projectionWidth *= m;
-    projectionHeight *= m;
-
-    // the scaled size is truncated, so compare the ratios: comparing the truncated width with the viewport
-    // picked the wrong axis whenever it came out a pixel short (2875x2999 on 1920x1058 showed u -0.44..1.44)
-    if (m1 == m2) {
-	return;
-    }
-    if (m == m1) {
-	this->updateVs (projectionWidth, projectionHeight);
-    } else {
-	this->updateUs (projectionWidth, projectionHeight);
-    }
+    this->setMargins (this->alignmentMargins (0));
 }
 
 template <> void WallpaperState::updateTextureUVs<WallpaperState::TextureUVsScaling::ZoomFitUVs> () {
-    this->resetUVs ();
-
-    const int viewportWidth = this->getViewportWidth ();
-    const int viewportHeight = this->getViewportHeight ();
-    int projectionWidth = this->getProjectionWidth ();
-    int projectionHeight = this->getProjectionHeight ();
-
-    const float m1 = static_cast<float> (viewportWidth) / projectionWidth;
-    const float m2 = static_cast<float> (viewportHeight) / projectionHeight;
-    const float m = std::min (m1, m2);
-    projectionWidth *= m;
-    projectionHeight *= m;
-
-    // the scaled size is truncated, so compare the ratios: comparing the truncated width with the viewport
-    // picked the wrong axis whenever it came out a pixel short (2875x2999 on 1920x1058 showed u -0.44..1.44)
-    if (m1 == m2) {
-	return;
-    }
-    if (m == m1) {
-	this->updateVs (projectionWidth, projectionHeight);
-    } else {
-	this->updateUs (projectionWidth, projectionHeight);
-    }
+    this->setMargins (this->alignmentMargins (1));
 }
 
 template <> void WallpaperState::updateTextureUVs<WallpaperState::TextureUVsScaling::DefaultUVs> () {
@@ -145,28 +161,13 @@ template <> void WallpaperState::updateTextureUVs<WallpaperState::TextureUVsScal
 }
 
 template <> void WallpaperState::updateTextureUVs<WallpaperState::TextureUVsScaling::CenterUVs> () {
-    this->resetUVs ();
-
-    const float viewportWidth = static_cast<float> (this->getViewportWidth ());
-    const float viewportHeight = static_cast<float> (this->getViewportHeight ());
-    const float projectionWidth = static_cast<float> (this->getProjectionWidth ());
-    const float projectionHeight = static_cast<float> (this->getProjectionHeight ());
-
-    // No scale factor applied at all: crop to native size if the wallpaper is bigger than the viewport,
-    // or overflow past [0,1] (relying on border clamping) to letterbox it if it's smaller.
-    const float uMargin = (1.0f - viewportWidth / projectionWidth) / 2.0f;
-    this->m_UVs.ustart = uMargin;
-    this->m_UVs.uend = 1.0f - uMargin;
-
-    const float vMargin = (1.0f - viewportHeight / projectionHeight) / 2.0f;
+    // no scale factor at all: crops to native size if the wallpaper is bigger than the viewport, overflows past [0,1]
+    // (relying on border clamping) to letterbox it if it's smaller
+    this->setMargins (this->alignmentMargins (3));
+}
 
-    if (m_vflip) {
-	this->m_UVs.vstart = vMargin;
-	this->m_UVs.vend = 1.0f - vMargin;
-    } else {
-	this->m_UVs.vstart = 1.0f - vMargin;
-	this->m_UVs.vend = vMargin;
-    }
+template <> void WallpaperState::updateTextureUVs<WallpaperState::TextureUVsScaling::FreeUVs> () {
+    this->setMargins (this->alignmentMargins (4));
 }
 
 template <WallpaperState::TextureUVsScaling T> void WallpaperState::updateTextureUVs () {
@@ -262,6 +263,17 @@ void WallpaperState::setOffset (float offsetX, float offsetY) {
     this->m_uvsDirty = true;
 }
 
+const WallpaperState::Alignment& WallpaperState::getAlignment () const { return this->m_alignment; }
+
+void WallpaperState::setAlignment (const Alignment& alignment) {
+    if (this->m_alignment == alignment) {
+	return;
+    }
+
+    this->m_alignment = alignment;
+    this->m_uvsDirty = true;
+}
+
 int WallpaperState::getViewportWidth () const { return this->m_viewport.width; }
 
 int WallpaperState::getViewportHeight () const { return this->m_viewport.height; }
@@ -293,6 +305,9 @@ void WallpaperState::updateState (
 	case WallpaperState::TextureUVsScaling::CenterUVs:
 	    this->updateTextureUVs<WallpaperState::TextureUVsScaling::CenterUVs> ();
 	    break;
+	case WallpaperState::TextureUVsScaling::FreeUVs:
+	    this->updateTextureUVs<WallpaperState::TextureUVsScaling::FreeUVs> ();
+	    break;
 	case WallpaperState::TextureUVsScaling::DefaultUVs:
 	    this->updateTextureUVs<WallpaperState::TextureUVsScaling::DefaultUVs> ();
 	    break;

+ 27 - 3
src/WallpaperEngine/Render/WallpaperState.h

@@ -19,10 +19,25 @@ public:
 	StretchUVs,
 	// Native resolution, centered, no scaling - crops if bigger than the viewport, letterboxes if smaller
 	CenterUVs,
+	// WE's "free" alignment: native size scaled by the alignment zoom, placed by the alignment x/y
+	FreeUVs,
+    };
+
+    /** WE's alignment settings (alignmentposition, alignmentx/y/z) as fractions, their UI values divided by 100 */
+    struct Alignment {
+	/** Where cover crops and fit letterboxes, 0..1 */
+	float position = 0.5f;
+	/** Center and free placement, 0..1 */
+	float x = 0.5f;
+	float y = 0.5f;
+	/** Free zoom, 0..2, 1 is the native size */
+	float zoom = 1.0f;
+
+	bool operator== (const Alignment&) const = default;
     };
 
     /**
-     * Maps the CLI/hotswap scaling names ("stretch", "fit", "fill", "center", "default") to their enum value,
+     * Maps the CLI/hotswap scaling names ("stretch", "fit", "fill", "center", "free", "default") to their enum value,
      * or std::nullopt if value isn't a known scaling name
      */
     static std::optional<TextureUVsScaling> parseScalingMode (const std::string& value);
@@ -34,8 +49,12 @@ public:
     ) const;
 
     void resetUVs ();
-    void updateUs (const int& projectionWidth, const int& projectionHeight);
-    void updateVs (const int& projectionWidth, const int& projectionHeight);
+    /**
+     * The canvas units the output leaves out on each side (left, right, bottom, top, negative where it letterboxes)
+     * for WE's alignment mode (0 cover, 1 fit, 2 stretch, 3 center, 4 free), sub_140183A70
+     */
+    [[nodiscard]] glm::vec4 alignmentMargins (int mode) const;
+    void setMargins (const glm::vec4& margins);
 
     [[nodiscard]] auto getTextureUVs () const { return m_UVs; };
     /** Whether the texture's first row is the top of the screen (the UVs' v runs top down then) */
@@ -73,6 +92,10 @@ public:
      */
     void setOffset (float offsetX, float offsetY);
 
+    [[nodiscard]] const Alignment& getAlignment () const;
+    /** WE's alignment position, x, y and zoom, takes effect on the next frame like setZoom () */
+    void setAlignment (const Alignment& alignment);
+
     [[nodiscard]] int getViewportWidth () const;
     [[nodiscard]] int getViewportHeight () const;
     [[nodiscard]] int getProjectionWidth () const;
@@ -104,6 +127,7 @@ private:
     float m_zoom = 1.0f;
     float m_offsetX = 0.0f;
     float m_offsetY = 0.0f;
+    Alignment m_alignment = {};
     // set when scaling mode, zoom or offset change live, forces the UVs to be recomputed
     bool m_uvsDirty = false;
 };

+ 739 - 93
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -14,7 +14,10 @@
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
+#include "WallpaperEngine/Data/Parsers/MaterialParser.h"
 #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
+#include "WallpaperEngine/Render/Shaders/GLSLContext.h"
+#include "WallpaperEngine/Render/Shaders/Shader.h"
 
 #include <algorithm>
 #include <bit>
@@ -23,6 +26,7 @@
 #include <cstdlib>
 #include <limits>
 #include <ranges>
+#include <regex>
 
 extern float g_Time;
 extern float g_TimeLast;
@@ -85,14 +89,24 @@ CScene::CScene (
 	&& scene->camera.bloom.enabled->value->getBool () && scene->camera.bloom.hdr->value->getBool ();
     this->m_volumetrics = std::make_unique<Volumetrics> (*this);
 
-    // lightconfig as the scene constructor packs it with WE's shadow setting off: spotshadowcookie folds into
-    // spotcookie, the other shadow counts are dropped. Passes read these when they're built
+    // lightconfig as the scene constructor packs it (sub_140186C90): with WE's shadow setting off spotshadowcookie
+    // folds into spotcookie and the other shadow counts are dropped. Passes read these when they're built
     const auto& lightConfig = this->getScene ().lightConfig;
+    this->m_shadowQuality = this->getContext ().getApp ().getContext ().settings.general.shadowQuality;
     this->m_lightingV1.points = lightConfig.point;
     this->m_lightingV1.spots = lightConfig.spot;
     this->m_lightingV1.tubes = lightConfig.tube;
     this->m_lightingV1.directionals = lightConfig.directional;
-    this->m_lightingV1.spotCookies = lightConfig.spotCookie | lightConfig.spotShadowCookie;
+
+    if (this->m_shadowQuality > 0) {
+	this->m_lightingV1.spotCookies = lightConfig.spotCookie;
+	this->m_lightingV1.spotShadowCookies = lightConfig.spotShadowCookie;
+	this->m_lightingV1.spotShadows = lightConfig.spotShadow;
+	this->m_lightingV1.directionalShadows = lightConfig.directionalShadow;
+	this->m_lightingV1.pointShadows = lightConfig.pointShadow;
+    } else {
+	this->m_lightingV1.spotCookies = lightConfig.spotCookie | lightConfig.spotShadowCookie;
+    }
 
     // models depth test against each other, 2D scenes can hold some too
     const bool hasModels
@@ -103,22 +117,16 @@ CScene::CScene (
 	perspective || hasModels, this->m_hdr ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888
     );
 
+    this->followOutputSize (this->find ("_rt_FullFrameBuffer"), 1);
+
     const uint32_t sceneWidth = this->m_camera->getCanvasWidth ();
     const uint32_t sceneHeight = this->m_camera->getCanvasHeight ();
 
-    this->_rt_shadowAtlas = this->create (
-	"_rt_shadowAtlas", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { sceneWidth, sceneHeight },
-	{ sceneWidth, sceneHeight }
-    );
+    // WE creates it on the first frame with shadows at the size the tiles need (sub_140190C80), it only grows
+    this->_rt_shadowAtlas
+	= this->create ("_rt_shadowAtlas", TextureFormat_D32f, TextureFlags_ClampUVsBorder, 1.0, { 2, 2 }, { 2, 2 });
     this->alias ("_alias_lightCookie", "_rt_shadowAtlas");
-
-    // generic2's REFLECTION samples the planar reflection target, not rendered here, so reflections stay black
-    if (perspective) {
-	this->create (
-	    "_rt_Reflection", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { sceneWidth / 2, sceneHeight / 2 },
-	    { sceneWidth / 2, sceneHeight / 2 }
-	);
-    }
+    this->m_shadowMapping = std::make_unique<ShadowMapping> (*this, this->_rt_shadowAtlas);
 
     const glm::vec3 clearColor = scene->colors.clear->value->getVec3 ();
 
@@ -143,19 +151,25 @@ CScene::CScene (
 	this->addObjectToRenderOrder (*object);
     }
 
-    // for the bloom effect below
-    this->_rt_4FrameBuffer = this->create (
+    // for the bloom effect below. WE sizes them from the output like _rt_FullFrameBuffer (sub_14017F1B0)
+    const auto quarter = this->create (
 	"_rt_4FrameBuffer", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { sceneWidth / 4, sceneHeight / 4 },
 	{ sceneWidth / 4, sceneHeight / 4 }
     );
-    this->_rt_8FrameBuffer = this->create (
+    const auto eighth = this->create (
 	"_rt_8FrameBuffer", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { sceneWidth / 8, sceneHeight / 8 },
 	{ sceneWidth / 8, sceneHeight / 8 }
     );
-    this->_rt_Bloom = this->create (
+    const auto bloomBuffer = this->create (
 	"_rt_Bloom", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { sceneWidth / 8, sceneHeight / 8 },
 	{ sceneWidth / 8, sceneHeight / 8 }
     );
+    this->followOutputSize (quarter, 4);
+    this->followOutputSize (eighth, 8);
+    this->followOutputSize (bloomBuffer, 8);
+    this->_rt_4FrameBuffer = quarter;
+    this->_rt_8FrameBuffer = eighth;
+    this->_rt_Bloom = bloomBuffer;
 
     // Bloom is achieved without any custom code by synthesizing a fake image object that loads
     // effect files from the virtual container - this costs two extra draw calls versus official WPE,
@@ -418,6 +432,10 @@ void CScene::renderFrame (const glm::ivec4& viewport) {
 
 void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     this->m_outputSize = { viewport.z, viewport.w };
+    this->resizeOutputBuffers (this->m_outputSize);
+    // wallpaper64.exe sub_14017FA70 counts every frame (scene render object +340, zeroed by sub_14017C6D0) before
+    // anything is simulated, boids pick their sample block with it
+    this->m_frameCounter++;
     timeStep ("updateMouse", [&] { this->updateMouse (viewport); });
 
     // WE updates every object before cursor events and scripts (sub_1401891A0 from sub_14017FA70), so scripts read
@@ -425,18 +443,26 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     for (const auto& cur : this->m_objectsByRenderOrder) {
 	if (cur->is<Objects::CImage> ()) {
 	    cur->as<Objects::CImage> ()->updatePuppetPose ();
+	} else if (cur->is<Objects::CMesh> ()) {
+	    cur->as<Objects::CMesh> ()->updateAnimation ();
+	} else if (cur->is<Objects::CSound> ()) {
+	    // every object, hidden ones too, and sounds nothing draws
+	    cur->as<Objects::CSound> ()->update (this->getDeltaTime ());
 	}
     }
 
     // after the tick, so a layer a script moves this frame (e.g. onto input.cursorWorldPosition) is hit tested where it
     // is now
     timeStep ("script tick", [&] { this->getScriptEngine ().tick (); });
+    // the first tick runs the objects' init (), which WE does before its loader sets the static camera
+    this->loadStaticCamera ();
     // WE runs the object updates first, then the camera, then the parallax camera
     this->updateCamera ();
     this->updateParallax ();
     timeStep ("cursor events", [&] { this->dispatchCursorEvents (); });
     this->updateLights ();
     this->updateLightingV1 ();
+    timeStep ("shadows", [&] { this->m_shadowMapping->render (this->m_shadowEntries); });
 
     // only image objects need their texture (e.g. video/gif frame) refreshed before drawing
     for (const auto& cur : this->m_objectsByRenderOrder) {
@@ -460,6 +486,7 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     }
 
     glBindVertexArray (this->m_vaoBuffer);
+    this->renderReflection ();
     glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ());
     glViewport (0, 0, this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ());
 
@@ -471,6 +498,7 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     const glm::vec3 clearColor = this->getScene ().colors.clear->value->getVec3 ();
     glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
     glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+    this->paintLetterbox ();
 
     // transparentsorting only does something in 3D scenes (render flags & 0x1008 == 0x1000, sub_14018AAC0): the rest
     // goes first in list order, then the transparent objects back to front
@@ -509,6 +537,81 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     }
 }
 
+void CScene::paintLetterbox () const {
+    // the bars a fit/center/free alignment leaves are part of WE's scene buffer (sub_140183A70 widens the projection
+    // over them) and only get the clear color, whatever is drawn there shows (text screen anchors move into them).
+    // --corner-color (with the border clamp) takes the clear color's place there, right after the clear
+    if (this->getState ().getClampingMode () != TextureFlags_ClampUVsBorder || this->m_camera->isPerspective ()) {
+	return;
+    }
+
+    glm::vec4 margins = this->getVisibleMargins ();
+
+    if (margins.x >= 0.0f && margins.y >= 0.0f && margins.z >= 0.0f && margins.w >= 0.0f) {
+	return;
+    }
+
+    // alignmentfliph mirrors the projection, the left bar ends up on the right
+    if (this->isFlippedHorizontally ()) {
+	std::swap (margins.x, margins.y);
+    }
+
+    const float width = static_cast<float> (this->getCanvasWidth ());
+    const float height = static_cast<float> (this->getCanvasHeight ());
+    const float visibleWidth = width - margins.x - margins.y;
+    const float visibleHeight = height - margins.z - margins.w;
+    const auto bufferWidth = static_cast<float> (this->m_sceneFBO->getRealWidth ());
+    const auto bufferHeight = static_cast<float> (this->m_sceneFBO->getRealHeight ());
+    // scene units to buffer pixels, the buffer's rows run from the bottom of the scene up
+    const auto columnOf = [&] (const float x) {
+	return static_cast<GLint> (std::lround ((x - margins.x) / visibleWidth * bufferWidth));
+    };
+    const auto rowOf = [&] (const float y) {
+	return static_cast<GLint> (std::lround ((y - margins.z) / visibleHeight * bufferHeight));
+    };
+    const GLint left = std::clamp (columnOf (0.0f), 0, static_cast<GLint> (bufferWidth));
+    const GLint right = std::clamp (columnOf (width), 0, static_cast<GLint> (bufferWidth));
+    const GLint bottom = std::clamp (rowOf (0.0f), 0, static_cast<GLint> (bufferHeight));
+    const GLint top = std::clamp (rowOf (height), 0, static_cast<GLint> (bufferHeight));
+    const glm::vec4& color = this->getCornerColor ();
+
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+    glClearColor (color.r, color.g, color.b, color.a);
+    glEnable (GL_SCISSOR_TEST);
+
+    const auto fill = [] (const GLint x, const GLint y, const GLint w, const GLint h) {
+	if (w > 0 && h > 0) {
+	    glScissor (x, y, w, h);
+	    glClear (GL_COLOR_BUFFER_BIT);
+	}
+    };
+
+    fill (0, 0, left, static_cast<GLint> (bufferHeight));
+    fill (right, 0, static_cast<GLint> (bufferWidth) - right, static_cast<GLint> (bufferHeight));
+    fill (left, 0, right - left, bottom);
+    fill (left, top, right - left, static_cast<GLint> (bufferHeight) - top);
+
+    glDisable (GL_SCISSOR_TEST);
+}
+
+bool CScene::isShadowCasterVisible (const CObject& object) const {
+    // the object's visible check (vtable +104) and flag 2 (under a passthrough layer), like renderSceneObject
+    const auto visibility
+	= this->getContext ().getApp ().getContext ().resolveObjectVisibility (object.getId (), object.getObject ().name);
+
+    if (visibility.has_value () && !visibility.value ()) {
+	return false;
+    }
+
+    if (this->isHiddenByAncestor (object) || this->isDrawnByPassthroughLayer (object)) {
+	return false;
+    }
+
+    return !object.is<Objects::CMesh> ()
+	|| object.as<Objects::CMesh> ()->getMesh ().groupVisible->value->getBool ();
+}
+
 void CScene::renderSceneObject (CObject* cur) {
     const auto& debug = this->getContext ().getApp ().getContext ().settings.render.debug;
     if (debug.objectFilter.has_value () && cur->getId () != debug.objectFilter.value ()) {
@@ -541,7 +644,7 @@ void CScene::renderSceneObject (CObject* cur) {
 
     this->m_volumetrics->composite ();
 
-    if (cur == this->m_bloomObject) {
+    if (cur == this->m_bloomObject && !this->m_renderingReflection) {
 	this->updateMipMappedFrameBuffer ();
     }
 
@@ -693,27 +796,156 @@ void releaseLevel (auto& level) {
 }
 } // namespace
 
+namespace {
+// sub_1400D2C60 with flag 0x10: max (1, min (log2 (np2 (w) / 2), log2 (np2 (h) / 2)) - 2) levels, np2 = the next power
+// of two, 8 for a 1920x1058 buffer
+uint32_t mipMappedLevels (const uint32_t width, const uint32_t height) {
+    const auto halfPowerOfTwo
+	= [] (const uint32_t value) { return std::bit_width (std::bit_ceil (std::max (value, 2u)) >> 1) - 1; };
+
+    return static_cast<uint32_t> (
+	std::max (1, static_cast<int> (std::min (halfPowerOfTwo (width), halfPowerOfTwo (height))) - 2)
+    );
+}
+} // namespace
+
+void CScene::followOutputSize (const std::shared_ptr<CFBO>& fbo, const float divisor) {
+    if (fbo == nullptr) {
+	return;
+    }
+
+    this->m_outputSizedBuffers.push_back ({ fbo, divisor });
+
+    if (this->m_outputBufferSize.x > 0) {
+	fbo->resize (
+	    static_cast<uint32_t> (this->m_outputBufferSize.x / divisor),
+	    static_cast<uint32_t> (this->m_outputBufferSize.y / divisor)
+	);
+    }
+}
+
+void CScene::resizeOutputBuffers (const glm::ivec2 size) {
+    if (size == this->m_outputBufferSize || size.x <= 0 || size.y <= 0) {
+	return;
+    }
+
+    this->m_outputBufferSize = size;
+    std::erase_if (this->m_outputSizedBuffers, [] (const auto& buffer) { return buffer.fbo.expired (); });
+
+    for (const auto& [weak, divisor] : this->m_outputSizedBuffers) {
+	weak.lock ()->resize (static_cast<uint32_t> (size.x / divisor), static_cast<uint32_t> (size.y / divisor));
+    }
+
+    if (this->_rt_MipMappedFrameBuffer != nullptr) {
+	const auto width = static_cast<uint32_t> (size.x);
+	const auto height = static_cast<uint32_t> (size.y);
+	this->find ("_rt_MipMappedFrameBuffer")->resize (width, height, mipMappedLevels (width, height));
+    }
+}
+
 std::shared_ptr<const CFBO> CScene::requireMipMappedFrameBuffer () {
     if (this->_rt_MipMappedFrameBuffer != nullptr) {
 	return this->_rt_MipMappedFrameBuffer;
     }
 
-    // sub_1400D2C60 with flag 0x10: max (1, min (log2 (np2 (w) / 2), log2 (np2 (h) / 2)) - 2) levels,
-    // np2 = the next power of two, 8 for a 1920x1058 buffer
-    const auto halfPowerOfTwo
-	= [] (const uint32_t value) { return std::bit_width (std::bit_ceil (std::max (value, 2u)) >> 1) - 1; };
     const uint32_t width = this->m_sceneFBO->getRealWidth ();
     const uint32_t height = this->m_sceneFBO->getRealHeight ();
-    const int levels = std::max (1, static_cast<int> (std::min (halfPowerOfTwo (width), halfPowerOfTwo (height))) - 2);
 
     this->_rt_MipMappedFrameBuffer = this->create (
 	"_rt_MipMappedFrameBuffer", this->m_sceneFBO->getFormat (), TextureFlags_ClampUVs, 1.0, { width, height },
-	{ width, height }, { 0.0f, 0.0f, 0.0f, 1.0f }, static_cast<uint32_t> (levels)
+	{ width, height }, { 0.0f, 0.0f, 0.0f, 1.0f }, mipMappedLevels (width, height)
     );
 
     return this->_rt_MipMappedFrameBuffer;
 }
 
+std::shared_ptr<const CFBO> CScene::requireReflectionFrameBuffer () {
+    if (this->_rt_Reflection != nullptr) {
+	return this->_rt_Reflection;
+    }
+
+    // output size, format 1 (8 bit even in HDR scenes), a depth buffer, no mips (sub_140181AF0)
+    const uint32_t width = this->m_sceneFBO->getRealWidth ();
+    const uint32_t height = this->m_sceneFBO->getRealHeight ();
+
+    this->_rt_Reflection = this->create (
+	"_rt_Reflection", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0, { width, height }, { width, height }
+    );
+    this->_rt_Reflection->attachDepthBuffer ();
+    this->followOutputSize (this->_rt_Reflection, 1);
+
+    return this->_rt_Reflection;
+}
+
+void CScene::addReflectionReceiver (const int id) { this->m_reflectionReceivers.insert (id); }
+
+void CScene::renderReflection () {
+    // sub_14017FA70, when something samples _rt_Reflection (scene flag 1) and the reflection setting (renderer flag
+    // 0x80, on by default) is on: before the main pass the scene is drawn again into it, mirrored on the world's y = 0
+    // plane (view * diag (1, -1, 1, 1), eye and camera axes mirrored with it). WE also negates the projection's y
+    // there (renderer flag 1, always set on its Direct3D renderer), which only makes up for Direct3D's top down
+    // render target rows; here the target already lines up with the shader's clip space lookup, and the mirror
+    // alone flips the winding, so culling is inverted instead
+    if (this->m_reflectionReceivers.empty () || this->_rt_Reflection == nullptr) {
+	return;
+    }
+
+    auto& camera = this->getCamera ();
+    const glm::mat4 view = camera.getWorldView ();
+    const glm::mat4 mirrored = view * glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
+
+    if (camera.isPerspective ()) {
+	camera.setPerspectiveView (mirrored, camera.getViewFov ());
+    } else {
+	camera.setWorldView (mirrored);
+	camera.updatePerspectiveLayers ();
+    }
+
+    glBindFramebuffer (GL_FRAMEBUFFER, this->_rt_Reflection->getFramebuffer ());
+    glViewport (0, 0, this->_rt_Reflection->getRealWidth (), this->_rt_Reflection->getRealHeight ());
+    glDepthMask (GL_TRUE);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+    const glm::vec3 clearColor = this->getScene ().colors.clear->value->getVec3 ();
+    glClearColor (clearColor.r, clearColor.g, clearColor.b, 1.0f);
+    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+    // everything the scene draws goes into the reflection target, like a passthrough layer's buffer
+    this->m_layerTargets.push_back ({
+	.fbo = this->_rt_Reflection,
+	.transform = glm::mat4 (1.0f),
+	.alphaMax = false,
+	.viewProjection = this->getWorldViewProjection (),
+	.viewProjectionApplied = true,
+    });
+    this->m_renderingReflection = true;
+
+    // scene +456 (sub_14018FF60): images, models, text and particles in creation order, minus the ones that sample the
+    // reflection themselves and the ones with "reflected" false; no lights, sounds, cameras or groups
+    for (auto* cur : this->m_objectsByRenderOrder) {
+	// the bloom layer stands in for WE's bloom post processing, it's no scene object there
+	if (cur == this->m_bloomObject || cur->is<Objects::CLight> () || cur->is<Objects::CSound> ()
+	    || cur->is<Objects::CCamera> ()) {
+	    continue;
+	}
+
+	if (!cur->getObject ().reflected || this->m_reflectionReceivers.contains (cur->getId ())) {
+	    continue;
+	}
+
+	this->renderSceneObject (cur);
+    }
+
+    this->m_renderingReflection = false;
+    this->m_layerTargets.pop_back ();
+
+    if (camera.isPerspective ()) {
+	camera.setPerspectiveView (view, camera.getViewFov ());
+    } else {
+	camera.setWorldView (view);
+	camera.updatePerspectiveLayers ();
+    }
+}
+
 void CScene::updateMipMappedFrameBuffer () const {
     if (this->_rt_MipMappedFrameBuffer == nullptr) {
 	return;
@@ -742,14 +974,7 @@ void CScene::releaseHDRBloom () {
 }
 
 glm::ivec2 CScene::getOutputResolution () const {
-    const auto [ustart, uend, vstart, vend] = this->getState ().getTextureUVs ();
-    const int viewportWidth = std::max (this->getState ().getViewportWidth (), 1);
-    const int viewportHeight = std::max (this->getState ().getViewportHeight (), 1);
-    const float coverU = std::abs (uend - ustart) > 0.0f ? std::abs (uend - ustart) : 1.0f;
-    const float coverV = std::abs (vend - vstart) > 0.0f ? std::abs (vend - vstart) : 1.0f;
-
-    return { std::max (1, static_cast<int> (static_cast<float> (viewportWidth) / coverU)),
-	     std::max (1, static_cast<int> (static_cast<float> (viewportHeight) / coverV)) };
+    return { std::max (this->getFramebufferWidth (), 1), std::max (this->getFramebufferHeight (), 1) };
 }
 
 glm::mat4 CScene::getWorldViewProjection () const {
@@ -774,16 +999,13 @@ void CScene::renderHDRBloom () {
 	this->m_bloomCombine = buildProgram ("", kCombine);
     }
 
-    // WE renders at the output's resolution and its chain starts at half of that: here the scene buffer is cut
-    // down to the output later, so the chain is sized by what the whole scene measures in output pixels
+    // the chain starts at half the output's resolution
     const glm::ivec2 resolution = this->getOutputResolution ();
-    const int viewportWidth = std::max (this->getState ().getViewportWidth (), 1);
-    const int viewportHeight = std::max (this->getState ().getViewportHeight (), 1);
 
     // levels: halvings of the output's smaller side, at most "bloomhdriterations" and the 8 buffers WE creates
     int levels = 0;
 
-    for (int side = std::min (viewportWidth, viewportHeight) / 2; side > 0; side /= 2) {
+    for (int side = std::min (resolution.x, resolution.y) / 2; side > 0; side /= 2) {
 	levels++;
     }
 
@@ -1124,13 +1346,14 @@ void CScene::updateCamera () {
 
     const float dt = std::max (g_Time - g_TimeLast, 0.0f);
 
-    // 2D scenes start from the reset camera WE uses without a camera object, 3D ones from scene.json
+    // without a camera object or path the camera is the static one, which scripts can move
     const bool perspective = this->m_camera->isPerspective ();
-    glm::vec3 eye = perspective ? this->m_camera->getConfiguredEye () : glm::vec3 (0.0f);
-    glm::vec3 center = perspective ? this->m_camera->getCenter () : glm::vec3 (0.0f, 0.0f, -1.0f);
-    glm::vec3 up = perspective ? this->m_camera->getUp () : glm::vec3 (0.0f, 1.0f, 0.0f);
+    const StaticCamera& base = this->getStaticCamera ();
+    glm::vec3 eye = base.eye;
+    glm::vec3 center = base.center;
+    glm::vec3 up = base.up;
     float fov = this->m_camera->getFov ();
-    float zoom = 1.0f;
+    float zoom = base.zoom;
     this->m_cameraFade = 0.0f;
 
     if (active != nullptr) {
@@ -1185,6 +1408,7 @@ void CScene::updateCamera () {
     this->updateFog (eye);
 
     if (perspective) {
+	this->m_camera->setVisibleRegion ({}, this->getOutputAspect ());
 	this->m_camera->setPerspectiveView (view, fov);
 	return;
     }
@@ -1192,14 +1416,8 @@ void CScene::updateCamera () {
     this->m_camera->setWorldView (view);
     this->m_camera->setZoom (this->getScene ().camera.projection.zoom->value->getFloat () * zoom);
 
-    const auto [ustart, uend, vstart, vend] = this->getState ().getTextureUVs ();
-    const int viewportWidth = this->getState ().getViewportWidth ();
-    const int viewportHeight = this->getState ().getViewportHeight ();
-    const float aspect = viewportWidth > 0 && viewportHeight > 0
-	? static_cast<float> (viewportWidth) / static_cast<float> (viewportHeight)
-	: static_cast<float> (this->getCanvasWidth ()) / static_cast<float> (this->getCanvasHeight ());
-
-    this->m_camera->updatePerspectiveLayers ({ ustart, uend, vstart, vend }, aspect);
+    this->m_camera->setVisibleRegion (this->getVisibleMargins (), this->getOutputAspect ());
+    this->m_camera->updatePerspectiveLayers ();
 }
 
 void CScene::dispatchCursorEvents () {
@@ -1228,7 +1446,7 @@ void CScene::dispatchCursorEvents () {
     const bool dragging = down && !this->m_cursorPressed.empty ();
     // scene buffer clip space, what the objects' matrices project to; the buffer is stored upside down, clip y grows
     // towards the bottom of the screen like the cursor's
-    const glm::vec2 ndc = this->m_mousePositionNormalized * 2.0f - 1.0f;
+    const glm::vec2 ndc = this->m_cursorScreen * 2.0f - 1.0f;
 
     // topmost first, like WE. Hidden objects are hit tested and get events too, they just can't stop propagation.
     // Images and text (object types 1 and 4) test their quad, models (type 5) their bounds
@@ -1342,7 +1560,7 @@ void CScene::dispatchCursorEvents () {
 void CScene::updateMouse (const glm::ivec4& viewport) {
     const glm::dvec2 position = this->getContext ().getInputContext ().getMouseInput ().position ();
 
-    this->m_mousePositionLast = this->m_mousePosition;
+    this->m_pointerPositionLast = this->m_pointerPosition;
     this->m_mousePositionViewport = glm::vec2 (position.x - viewport.x, position.y - viewport.y);
 
     double mouseX = glm::clamp ((position.x - viewport.x) / viewport.z, 0.0, 1.0);
@@ -1355,17 +1573,47 @@ void CScene::updateMouse (const glm::ivec4& viewport) {
     // OpenGL convention (0=bottom, 1=top) - particle code expects 0=bottom as negative Y (down)
     double normalizedMouseY = glm::clamp ((position.y - viewport.y) / viewport.w, 0.0, 1.0);
 
-    // fill/fit scaling modes can render the scene larger than the viewport and crop via UVs
-    const auto uvs = this->getState ().getTextureUVs ();
+    // the scene buffer holds what the output shows, the visible region maps the cursor onto the scene
+    const glm::vec4 output = this->getOutputUVs ();
+    const glm::vec4 visible = this->getVisibleUVs ();
 
-    this->m_mousePositionNormalized.x = uvs.ustart + mouseX * (uvs.uend - uvs.ustart);
-    this->m_mousePositionNormalized.y = uvs.vstart + normalizedMouseY * (uvs.vend - uvs.vstart);
+    this->m_cursorScreen.x = output.x + mouseX * (output.y - output.x);
+    this->m_cursorScreen.y = output.z + normalizedMouseY * (output.w - output.z);
+    this->m_mousePositionNormalized.x = visible.x + mouseX * (visible.y - visible.x);
+    this->m_mousePositionNormalized.y = visible.z + normalizedMouseY * (visible.w - visible.z);
 
     // invert the Y normalization above to match what the shader expects
     double mouseY = 1.0 - normalizedMouseY;
 
-    this->m_mousePosition.x = this->m_mousePositionNormalized.x;
-    this->m_mousePosition.y = uvs.vstart + mouseY * (uvs.vend - uvs.vstart);
+    this->m_mousePosition.x = this->m_cursorScreen.x;
+    this->m_mousePosition.y = output.z + mouseY * (output.w - output.z);
+    // g_PointerPosition is ScreenToClient over the client size, never mirrored by alignmentfliph (sub_140110630,
+    // uniform 105 reads renderer +140 in sub_1400D8300)
+    const float pointerX = this->isFlippedHorizontally () ? 1.0f - this->m_mousePosition.x : this->m_mousePosition.x;
+    this->m_pointerPosition = { pointerX, this->m_mousePosition.y };
+}
+
+glm::vec4 CScene::getVisibleUVs () const {
+    const auto& state = this->getState ();
+
+    // 3D scenes keep the whole view, the perspective takes the output's aspect instead
+    if (this->m_camera->isPerspective () || state.getViewportWidth () <= 0 || state.getViewportHeight () <= 0) {
+	return this->getOutputUVs ();
+    }
+
+    const auto uvs = state.getTextureUVs ();
+    return { uvs.ustart, uvs.uend, uvs.vstart, uvs.vend };
+}
+
+glm::vec4 CScene::getVisibleMargins () const {
+    const glm::vec4 uvs = this->getVisibleUVs ();
+    const float width = this->getCanvasWidth ();
+    const float height = this->getCanvasHeight ();
+    const bool vflip = this->getState ().isVFlipped ();
+
+    // v runs top down in a flipped state, bottom up otherwise
+    return { uvs.x * width, (1.0f - uvs.y) * width, (vflip ? 1.0f - uvs.w : uvs.w) * height,
+	     (vflip ? uvs.z : 1.0f - uvs.z) * height };
 }
 
 const Data::Model::Properties& CScene::getUserProperties () const {
@@ -1441,6 +1689,8 @@ float CScene::getSceneClock () const {
     return std::fmod (std::max (g_Time - this->m_startTime, 0.0f), 432000.0f);
 }
 
+uint32_t CScene::getFrameCounter () const { return this->m_frameCounter; }
+
 float CScene::getFps () const {
     const float dt = g_Time - g_TimeLast;
     // avoids a division by zero / bogus fps on the first frame, where g_TimeLast is still 0
@@ -1450,12 +1700,63 @@ float CScene::getFps () const {
     return 1.0f / dt;
 }
 
-const glm::vec2* CScene::getMousePosition () const { return &this->m_mousePosition; }
+const glm::vec2* CScene::getPointerPosition () const { return &this->m_pointerPosition; }
 
-const glm::vec2* CScene::getMousePositionLast () const { return &this->m_mousePositionLast; }
+const glm::vec2* CScene::getPointerPositionLast () const { return &this->m_pointerPositionLast; }
 
 const glm::vec2* CScene::getMousePositionNormalized () const { return &this->m_mousePositionNormalized; }
 
+const glm::vec2* CScene::getCursorScreenPosition () const { return &this->m_cursorScreen; }
+
+glm::vec3 CScene::unprojectCursor () const {
+    // WE unprojects the cursor (x, 1 - y) through the view and projection on top of the renderer's stacks, with glm's
+    // unProject (depth 0.5 -> NDC 0) for scripts (sub_14018E070 -> sub_14019DF90) and NDC depth 0 for particle control
+    // points (sub_14022E3E0). Its projections are Direct3D ones, so NDC depth 0 is the near plane
+    const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f, (1.0f - this->m_cursorScreen.y) * 2.0f - 1.0f };
+    const auto& camera = this->getCamera ();
+
+    if (camera.isPerspective ()) {
+	const glm::vec4 world
+	    = glm::inverse (camera.getPerspective () * camera.getView ()) * glm::vec4 (ndc, -1.0f, 1.0f);
+
+	return glm::vec3 (world) / world.w;
+    }
+
+    return glm::vec3 (glm::inverse (camera.getProjection () * camera.getLookAt ()) * glm::vec4 (ndc, 0.0f, 1.0f));
+}
+
+glm::vec3 CScene::getCursorWorldPosition () const {
+    const glm::vec3 position = this->unprojectCursor ();
+
+    if (this->getCamera ().isPerspective ()) {
+	return position;
+    }
+
+    // the 2D layout is WE's world moved to the scene center and flipped vertically (Camera::setWorldView); WE zeroes z
+    // in orthographic scenes (renderer flag 0x400)
+    return { position.x + static_cast<float> (this->getWidth ()) / 2.0f,
+	     static_cast<float> (this->getHeight ()) / 2.0f - position.y, 0.0f };
+}
+
+glm::vec2 CScene::getCursorPixelPosition () const {
+    // sub_14018E070 with its screen flag: g_PointerPosition times the window client size, x mirrored on renderer flag
+    // 0x800 (horizontal flip). m_mousePosition is already mirrored
+    const auto& state = this->getState ();
+
+    return { this->m_mousePosition.x * static_cast<float> (state.getViewportWidth ()),
+	     this->m_mousePosition.y * static_cast<float> (state.getViewportHeight ()) };
+}
+
+float CScene::getOutputAspect () const {
+    const auto& state = this->getState ();
+
+    if (state.getViewportWidth () <= 0 || state.getViewportHeight () <= 0) {
+	return static_cast<float> (this->getCanvasWidth ()) / static_cast<float> (this->getCanvasHeight ());
+    }
+
+    return static_cast<float> (state.getViewportWidth ()) / static_cast<float> (state.getViewportHeight ());
+}
+
 const glm::vec2* CScene::getParallaxPosition () const { return &this->m_parallaxPosition; }
 
 glm::vec2 CScene::getParallaxOffset (const Object& object) const {
@@ -1681,6 +1982,36 @@ std::shared_ptr<const TextureProvider> CScene::getLightCookie () const {
     );
 }
 
+namespace {
+// point light cube faces as assets/shaders/common_pbr_2.h picks them (CalculateProjectedCoordsPoint), the same
+// matrices sub_140190C80 renders the six viewports with: +x, -x, +y, -y, +z, -z
+glm::mat4 pointFaceView (const int face, const glm::vec3& o) {
+    switch (face) {
+	case 0:
+	    return { { 0, 0, -1, 0 }, { 0, 1, 0, 0 }, { 1, 0, 0, 0 }, { -o.z, -o.y, o.x, 1 } };
+	case 1:
+	    return { { 0, 0, 1, 0 }, { 0, 1, 0, 0 }, { -1, 0, 0, 0 }, { o.z, -o.y, -o.x, 1 } };
+	case 2:
+	    return { { 1, 0, 0, 0 }, { 0, 0, -1, 0 }, { 0, 1, 0, 0 }, { -o.x, -o.z, o.y, 1 } };
+	case 3:
+	    return { { 1, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, -1, 0, 0 }, { -o.x, o.z, -o.y, 1 } };
+	case 4:
+	    return { { -1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, -1, 0 }, { o.x, -o.y, o.z, 1 } };
+	default:
+	    return { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { -o.x, -o.y, -o.z, 1 } };
+    }
+}
+
+// WE's device projections have 1 at the near plane (sub_14009A360); Volumetrics::spotViewProjection keeps the usual
+// 0 there, this turns one into the other (depth' = 1 - depth)
+glm::mat4 reverseDepth (const glm::mat4& projection) {
+    glm::mat4 reverse (1.0f);
+    reverse[2][2] = -1.0f;
+    reverse[3][2] = 1.0f;
+    return reverse * projection;
+}
+} // namespace
+
 void CScene::updateLightingV1 () {
     auto& lighting = this->m_lightingV1;
     const LightingV1 counts = lighting;
@@ -1691,21 +2022,48 @@ void CScene::updateLightingV1 () {
     lighting.tubes = counts.tubes;
     lighting.directionals = counts.directionals;
     lighting.spotCookies = counts.spotCookies;
+    lighting.spotShadowCookies = counts.spotShadowCookies;
+    lighting.spotShadows = counts.spotShadows;
+    lighting.directionalShadows = counts.directionalShadows;
+    lighting.pointShadows = counts.pointShadows;
+    this->m_shadowEntries.clear ();
+    this->m_volumeShadows.clear ();
 
     if (lighting.points + lighting.spots + lighting.tubes + lighting.directionals == 0) {
 	return;
     }
 
     const auto& camera = this->getCamera ();
+    const bool orthographic = camera.isOrthogonal ();
     const std::vector<const Light*> lights = this->sortedLightingV1Lights ();
-
-    // one slot per light until its type's count runs out; cookie spots come first, the others after them
-    int point = 0;
-    int cookieSpot = 0;
-    int plainSpot = lighting.spotCookies;
+    const bool shadows = this->m_shadowQuality > 0;
+    const int tile = ShadowMapping::tileSize (this->m_shadowQuality);
+    // renderer +104 (eye) and +352 (camera forward) as sub_14017FA70 leaves them
+    const glm::vec3 eye = this->m_fog.eyeWorld;
+    const glm::vec3 forward = orthographic
+	? glm::vec3 (0.0f, 0.0f, -1.0f)
+	: -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
+    const int ssc = lighting.spotShadowCookies;
+    const int sc = lighting.spotCookies;
+    const int ss = lighting.spotShadows;
+
+    // where each class of a light type writes next (sub_140190C80 keeps a pointer per class): points with a
+    // shadow first, spots shadow+cookie / cookie / shadow / plain indexed by castshadow | usecookie << 1,
+    // directional lights with a shadow first. The ShadowProjection matrices go by the spot classes too and the
+    // cascades continue after them. Every light with a shadow or cookie takes one of the features, a directional
+    // light one for its three cascades
+    int pointsLeft = lighting.points;
+    int pointSlot[2] = { lighting.pointShadows, 0 };
+    int pointShadowsLeft = lighting.pointShadows;
+    int pointShadow = 0;
     int spotsLeft = lighting.spots;
+    int spotSlot[4] = { ssc + sc + ss, ssc + sc, ssc, 0 };
+    int featureSlot[4] = { ssc + sc + ss, ssc + sc, ssc, 0 };
+    int featuresLeft = lighting.features ();
     int tube = 0;
-    int directional = 0;
+    int directionalsLeft = lighting.directionals;
+    int directionalSlot[2] = { lighting.directionalShadows, 0 };
+    const int featureCapacity = static_cast<int> (std::size (lighting.featureProjection));
 
     for (const Light* entry : lights) {
 	const Light& light = *entry;
@@ -1714,15 +2072,50 @@ void CScene::updateLightingV1 () {
 	const float radius = light.radius->value->getFloat ();
 	const float exponent = light.exponent->value->getFloat ();
 	const glm::vec3 origin (world[3]);
+	const bool shadowed = shadows && light.castShadow;
 
 	switch (light.type) {
-	    case LightType::Point:
-		if (point < lighting.points) {
-		    lighting.pointColor[point] = glm::vec4 (color, radius);
-		    lighting.pointOrigin[point] = glm::vec4 (origin, exponent);
-		    point++;
+	    case LightType::Point: {
+		if (pointsLeft == 0) {
+		    break;
 		}
+
+		pointsLeft--;
+
+		if (const int slot = pointSlot[shadowed ? 1 : 0]++; slot < lighting.points) {
+		    lighting.pointColor[slot] = glm::vec4 (color, radius);
+		    lighting.pointOrigin[slot] = glm::vec4 (origin, exponent);
+		}
+
+		if (!shadowed || pointShadowsLeft == 0) {
+		    break;
+		}
+
+		// sub_14025D420: a fov a bit over 90 degrees per quality, aspect 1, near the light source size (1 in
+		// orthographic scenes), far the radius
+		pointShadowsLeft--;
+
+		const int quality = this->m_shadowQuality;
+		const float fov = quality <= 2 ? 94.0f : quality == 3 ? 92.0f : 91.2f;
+		const float near = orthographic ? 1.0f : std::max (0.05f, light.lightSourceSize->value->getFloat ());
+		const float far = std::max (radius, near + 0.01f);
+		const glm::mat4 projection = ShadowMapping::perspective (fov * 0.017453292f, 1.0f, near, far);
+		ShadowMapping::Entry shadow { .point = true, .size = tile };
+
+		lighting.pointShadowProjection[pointShadow]
+		    = glm::vec4 (projection[2][2], projection[3][2], projection[2][3], projection[3][3]);
+		shadow.transform = &lighting.pointShadowProjectionTransform[pointShadow];
+		pointShadow++;
+
+		for (int face = 0; face < 6; face++) {
+		    shadow.viewProjection[face] = projection * pointFaceView (face, origin);
+		}
+
+		this->m_volumeShadows[&light] = { .atlasTransform = shadow.transform,
+						  .pointProjection = lighting.pointShadowProjection[pointShadow - 1] };
+		this->m_shadowEntries.push_back (shadow);
 		break;
+	    }
 	    case LightType::Spot: {
 		if (spotsLeft == 0) {
 		    break;
@@ -1730,26 +2123,41 @@ void CScene::updateLightingV1 () {
 
 		spotsLeft--;
 
-		int& slot = light.useCookie ? cookieSpot : plainSpot;
+		const int type = (light.castShadow ? 1 : 0) | (light.useCookie ? 2 : 0);
+		const int kind = type & (shadows ? 3 : 2);
 
-		if (slot >= lighting.spots) {
+		// cosines of the cone angles in the .w, the direction is the world matrix's x column as it is
+		if (const int slot = spotSlot[kind]++; slot < lighting.spots) {
+		    lighting.spotColor[slot] = glm::vec4 (color, radius);
+		    lighting.spotOrigin[slot]
+			= glm::vec4 (origin, std::cos (light.innerCone->value->getFloat () * 0.017453292f));
+		    lighting.spotDirection[slot]
+			= glm::vec4 (glm::vec3 (world[0]), std::cos (light.outerCone->value->getFloat () * 0.017453292f));
+		    lighting.spotExponent[slot] = glm::vec4 (exponent, 0.0f, 0.0f, 0.0f);
+		}
+
+		if ((!shadowed && !light.useCookie) || featuresLeft == 0) {
 		    break;
 		}
 
-		// cosines of the cone angles in the .w, the direction is the world matrix's x column as it is
-		lighting.spotColor[slot] = glm::vec4 (color, radius);
-		lighting.spotOrigin[slot]
-		    = glm::vec4 (origin, std::cos (light.innerCone->value->getFloat () * 0.017453292f));
-		lighting.spotDirection[slot]
-		    = glm::vec4 (glm::vec3 (world[0]), std::cos (light.outerCone->value->getFloat () * 0.017453292f));
-		lighting.spotExponent[slot] = glm::vec4 (exponent, 0.0f, 0.0f, 0.0f);
-
-		if (light.useCookie && slot < 3) {
-		    lighting.featureProjection[slot]
-			= Volumetrics::spotViewProjection (light, world, camera.isOrthogonal ());
+		featuresLeft--;
+
+		const int feature = featureSlot[kind]++;
+
+		if (feature >= featureCapacity) {
+		    break;
 		}
 
-		slot++;
+		lighting.featureProjection[feature]
+		    = reverseDepth (Volumetrics::spotViewProjection (light, world, orthographic));
+
+		if (shadowed) {
+		    ShadowMapping::Entry shadow { .size = tile, .transform = &lighting.featureProjectionTransform[feature] };
+		    shadow.viewProjection[0] = lighting.featureProjection[feature];
+		    this->m_volumeShadows[&light]
+			= { .matrix = lighting.featureProjection[feature], .atlasTransform = shadow.transform };
+		    this->m_shadowEntries.push_back (shadow);
+		}
 		break;
 	    }
 	    case LightType::Tube:
@@ -1761,13 +2169,89 @@ void CScene::updateLightingV1 () {
 		    tube++;
 		}
 		break;
-	    case LightType::Directional:
-		if (directional < lighting.directionals) {
-		    lighting.directionalColor[directional] = glm::vec4 (color, 1.0f);
-		    lighting.directionalDirection[directional] = glm::vec4 (-glm::vec3 (world[0]), 0.0f);
-		    directional++;
+	    case LightType::Directional: {
+		if (directionalsLeft == 0) {
+		    break;
+		}
+
+		directionalsLeft--;
+
+		if (const int slot = directionalSlot[shadowed ? 1 : 0]++; slot < lighting.directionals) {
+		    lighting.directionalColor[slot] = glm::vec4 (color, 1.0f);
+		    lighting.directionalDirection[slot] = glm::vec4 (-glm::vec3 (world[0]), 0.0f);
+		}
+
+		if (!shadowed || featuresLeft == 0) {
+		    break;
+		}
+
+		featuresLeft--;
+
+		// sub_14025D370: each cascade covers a square of its distance and a depth range around the view,
+		// sub_140190C80 0x14019128b: centered half the distance ahead of the eye (the forward's part along the
+		// light only half counted, z 0 in 2D), snapped to shadow texels along the light's y and z axes. The view
+		// looks down the light's x axis (rows z, y, -x like a spot), the projection is an orthographic box
+		// (sub_14009A630) of +-distance/2 and depth +-range/2
+		const float cascade0 = light.cascadeDistance[0]->value->getFloat ();
+		const float cascade1 = light.cascadeDistance[1]->value->getFloat ();
+		const float cascade2 = light.cascadeDistance[2]->value->getFloat ();
+		const glm::vec2 ranges[3] = {
+		    { cascade0, cascade1 * 4.0f },
+		    { cascade1, cascade1 * 4.0f },
+		    { cascade2, std::max (cascade2 * 1.5f, cascade1 * 4.0f) },
+		};
+		const glm::vec3 direction = glm::normalize (glm::vec3 (world[0]));
+		const glm::vec3 y (world[1]);
+		const glm::vec3 z (world[2]);
+		const glm::vec3 rows[3] = { Volumetrics::approximateNormalize (z), Volumetrics::approximateNormalize (y),
+					    Volumetrics::approximateNormalize (-glm::vec3 (world[0])) };
+		const glm::vec3 ahead = forward - direction * (glm::dot (forward, direction) * 0.5f);
+
+		for (const glm::vec2& range : ranges) {
+		    const float half = range.x * 0.5f;
+		    glm::vec3 center = eye + ahead * half;
+
+		    if (orthographic) {
+			center.z = 0.0f;
+		    }
+
+		    const float texel = range.x / static_cast<float> (tile);
+		    const float alongZ = glm::dot (z, center);
+		    const float alongY = glm::dot (y, center);
+
+		    center -= y * std::fmod (alongY, texel);
+		    center -= z * std::fmod (alongZ, texel);
+
+		    glm::mat4 view (1.0f);
+
+		    for (int row = 0; row < 3; row++) {
+			for (int column = 0; column < 3; column++) {
+			    view[column][row] = rows[row][column];
+			}
+
+			view[3][row] = -glm::dot (rows[row], center);
+		    }
+
+		    glm::mat4 projection (1.0f);
+		    projection[0][0] = 1.0f / half;
+		    projection[1][1] = 1.0f / half;
+		    projection[2][2] = 1.0f / range.y;
+		    projection[3][2] = 0.5f;
+
+		    const int feature = featureSlot[0]++;
+
+		    if (feature >= featureCapacity) {
+			continue;
+		    }
+
+		    lighting.featureProjection[feature] = projection * view;
+
+		    ShadowMapping::Entry shadow { .size = tile, .transform = &lighting.featureProjectionTransform[feature] };
+		    shadow.viewProjection[0] = lighting.featureProjection[feature];
+		    this->m_shadowEntries.push_back (shadow);
 		}
 		break;
+	    }
 	    default:
 		break;
 	}
@@ -1893,7 +2377,12 @@ void CScene::renderLightVolume (const Objects::CLight& object, const glm::mat4&
     }
 
     timeStep ("volumetrics " + light.name, [&] {
-	this->m_volumetrics->renderLight (light, this->objectWorldMatrix (light), viewProjection);
+	const auto shadow = this->m_volumeShadows.find (&light);
+
+	this->m_volumetrics->renderLight (
+	    light, this->objectWorldMatrix (light), viewProjection,
+	    shadow != this->m_volumeShadows.end () ? &shadow->second : nullptr
+	);
     });
 }
 
@@ -2081,6 +2570,20 @@ void CScene::setSoundPlaying (int id, bool playing) {
     }
 }
 
+void CScene::pauseSound (int id) {
+    if (auto* sound = this->getObject (id); sound != nullptr && sound->is<Objects::CSound> ()) {
+	sound->as<Objects::CSound> ()->pause ();
+    }
+}
+
+bool CScene::isSoundPlaying (int id, bool startSilent) const {
+    if (const auto* sound = this->getObject (id); sound != nullptr && sound->is<Objects::CSound> ()) {
+	return sound->as<Objects::CSound> ()->isPlaying ();
+    }
+
+    return this->getSoundPlayRequest (id).value_or (!startSilent);
+}
+
 std::optional<bool> CScene::getSoundPlayRequest (int id) const {
     const auto request = this->m_soundPlayRequests.find (id);
 
@@ -2237,6 +2740,149 @@ void CScene::sortLayer (CObject* object, int index) {
     this->m_objectsByRenderOrder.insert (before, object);
 }
 
+void CScene::loadStaticCamera () {
+    if (this->m_staticCameraLoaded) {
+	return;
+    }
+
+    this->m_staticCameraLoaded = true;
+
+    // 2D scenes without camera paths get the reset camera, the others scene.json's (sub_140186C90); zoom stays
+    if (!this->m_camera->isPerspective () && this->getScene ().camera.paths.empty ()) {
+	this->m_staticCamera.eye = glm::vec3 (0.0f);
+	this->m_staticCamera.center = glm::vec3 (0.0f, 0.0f, -1.0f);
+	this->m_staticCamera.up = glm::vec3 (0.0f, 1.0f, 0.0f);
+    } else {
+	this->m_staticCamera.eye = this->m_camera->getConfiguredEye ();
+	this->m_staticCamera.center = this->m_camera->getCenter ();
+	this->m_staticCamera.up = this->m_camera->getUp ();
+    }
+}
+
+uint32_t CScene::createModelData (const ModelData::Config& config, ModelData::Error& error) {
+    return this->m_modelData.create (
+	config, [this] (const std::string& material, uint32_t format) {
+	    return this->checkModelDataMaterial (material, format);
+	},
+	error
+    );
+}
+
+void CScene::applyModelData (
+    uint32_t token, const ModelData::Config& config, bool replace, ModelData::Error& error
+) {
+    this->m_modelData.apply (
+	token, config, replace,
+	[this] (const std::string& material, uint32_t format) {
+	    return this->checkModelDataMaterial (material, format);
+	},
+	error
+    );
+}
+
+void CScene::destroyModelData (uint32_t token) { this->m_modelData.release (token); }
+
+std::shared_ptr<ModelData::Model> CScene::acquireModelData (int token) { return this->m_modelData.acquire (token); }
+
+void CScene::releaseModelData (uint32_t token) { this->m_modelData.release (token); }
+
+ModelData::Error CScene::checkModelDataMaterial (const std::string& material, uint32_t format) {
+    const auto key = std::make_pair (material, format);
+
+    if (const auto cached = this->m_modelDataMaterialChecks.find (key); cached != this->m_modelDataMaterialChecks.end ()) {
+	return cached->second;
+    }
+
+    // semantic of every vertex format bit and of every attribute name WE's shader translation knows (0x140482AF0,
+    // 0x140484A90), sub_1400D7B60 only compares semantic names
+    static const std::pair<uint32_t, const char*> formatSemantics[] = {
+	{ 0x1, "POSITION" },	  { 0x10000, "POSITION" }, { 0x2000000, "POSITION" }, { 0x2, "NORMAL" },
+	{ 0x4, "TANGENT" },	  { 0x800000, "BLENDINDICES" }, { 0x1000000, "BLENDWEIGHT" }, { 0x8, "TEXCOORD" },
+	{ 0x10, "TEXCOORD" },	  { 0x20, "TEXCOORD" },    { 0x40, "TEXCOORD" },      { 0x80, "TEXCOORD" },
+	{ 0x100, "TEXCOORD" },	  { 0x200, "TEXCOORD" },   { 0x400, "TEXCOORD" },     { 0x800, "TEXCOORD" },
+	{ 0x1000, "TEXCOORD" },	  { 0x2000, "TEXCOORD" },  { 0x4000, "TEXCOORD" },    { 0x20000, "TEXCOORD" },
+	{ 0x40000, "TEXCOORD" },  { 0x80000, "TEXCOORD" }, { 0x100000, "TEXCOORD" },  { 0x200000, "TEXCOORD" },
+	{ 0x400000, "TEXCOORD" }, { 0x8000, "COLOR" },
+    };
+    static const std::map<std::string, std::string> attributeSemantics = {
+	{ "a_Position", "POSITION" },	      { "a_PositionVec4", "POSITION" },   { "a_PositionC1", "POSITION" },
+	{ "a_Normal", "NORMAL" },	      { "a_Tangent4", "TANGENT" },	  { "a_BlendIndices", "BLENDINDICES" },
+	{ "a_BlendWeights", "BLENDWEIGHT" }, { "a_TexCoord", "TEXCOORD" },	  { "a_TexCoordVec3", "TEXCOORD" },
+	{ "a_TexCoordVec4", "TEXCOORD" },    { "a_TexCoordC1", "TEXCOORD" },	  { "a_TexCoordVec3C1", "TEXCOORD" },
+	{ "a_TexCoordVec4C1", "TEXCOORD" },  { "a_TexCoordC2", "TEXCOORD" },	  { "a_TexCoordVec3C2", "TEXCOORD" },
+	{ "a_TexCoordVec4C2", "TEXCOORD" },  { "a_TexCoordC3", "TEXCOORD" },	  { "a_TexCoordVec3C3", "TEXCOORD" },
+	{ "a_TexCoordVec4C3", "TEXCOORD" },  { "a_TexCoordC4", "TEXCOORD" },	  { "a_TexCoordVec3C4", "TEXCOORD" },
+	{ "a_TexCoordVec4C4", "TEXCOORD" },  { "a_TexCoordC5", "TEXCOORD" },	  { "a_TexCoordVec3C5", "TEXCOORD" },
+	{ "a_TexCoordVec4C5", "TEXCOORD" },  { "a_Color", "COLOR" },
+    };
+    static const std::regex input (R"(\bin\s+\w+\s+(a_\w+)\s*;)");
+
+    ModelData::Error result = ModelData::Error::None;
+    const auto& project = this->getScene ().project;
+    const auto loaded = Data::Parsers::MaterialParser::load (project, material);
+
+    if (loaded == nullptr || loaded->passes.empty ()) {
+	result = ModelData::Error::InvalidMaterial;
+    } else {
+	// the program WE compiles for the material by itself (sub_1401A5C40): the pass's combos plus the scene wide
+	// defines every pass gets
+	const auto& pass = *loaded->passes.front ();
+	ComboMap combos = pass.combos;
+	const ComboMap overrideCombos;
+	const TextureMap overrideTextures;
+	static const ShaderConstantMap noConstants;
+
+	if (this->getCamera ().isOrthogonal ()) {
+	    combos.insert_or_assign ("SCENE_ORTHO", 1);
+	}
+
+	if (this->isHDR ()) {
+	    combos.insert_or_assign ("HDR", 1);
+	}
+
+	try {
+	    Shaders::Shader shader (
+		*project.assetLocator, pass.shader, combos, overrideCombos, pass.textures, overrideTextures, noConstants
+	    );
+	    const auto sources = Shaders::GLSLContext::get ().toGlsl (shader.vertex (), shader.fragment (), pass.shader);
+	    std::set<std::string> provided;
+
+	    for (const auto& [bit, semantic] : formatSemantics) {
+		if (format & bit) {
+		    provided.insert (semantic);
+		}
+	    }
+
+	    // the translation keeps the original source in an "#if 0" block at the end, that doesn't count
+	    const std::string code = sources.vertex.substr (0, sources.vertex.rfind ("\n#if 0"));
+
+	    for (std::sregex_iterator it (code.begin (), code.end (), input), end; it != end; ++it) {
+		const std::string name = (*it)[1].str ();
+		const auto semantic = attributeSemantics.find (name);
+		const std::regex use ("\\b" + name + "\\b");
+		const auto uses = std::distance (std::sregex_iterator (code.begin (), code.end (), use), std::sregex_iterator ());
+
+		// the D3D input signature only has the inputs the shader reads: live WE takes a position-only shape with
+		// util/flat.json, whose flat.vert declares a_Color but only reads it with VERTEXCOLOR
+		if (uses < 2) {
+		    continue;
+		}
+
+		if (semantic != attributeSemantics.end () && !provided.contains (semantic->second)) {
+		    result = ModelData::Error::ShaderExpectingMoreVertexData;
+		    break;
+		}
+	    }
+	} catch (const std::exception& e) {
+	    sLog.error ("Model data material ", material, " has no usable shader: ", e.what ());
+	    result = ModelData::Error::InvalidMaterial;
+	}
+    }
+
+    this->m_modelDataMaterialChecks.emplace (key, result);
+    return result;
+}
+
 void CScene::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
     const std::optional<int> volume = muted ? std::optional<int> (0) : ambientVolume;
 

+ 114 - 9
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -2,12 +2,15 @@
 
 #include "WallpaperEngine/Data/JSON.h"
 #include "WallpaperEngine/Render/Camera.h"
+#include "WallpaperEngine/Render/ModelData.h"
 
 #include "WallpaperEngine/Render/CWallpaper.h"
+#include "WallpaperEngine/Render/ShadowMapping.h"
 #include "WallpaperEngine/Render/Volumetrics.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 
 #include <set>
+#include <unordered_map>
 
 namespace WallpaperEngine::Render {
 class Camera;
@@ -42,6 +45,17 @@ public:
      * Holds the previous frame's scene with mips, what REFLECTION reads with a roughness based LOD
      */
     std::shared_ptr<const CFBO> requireMipMappedFrameBuffer ();
+    /**
+     * _rt_Reflection, the planar reflection: output sized with depth, created on the first material that samples it
+     * (sub_140181AF0, scene flag 1)
+     */
+    std::shared_ptr<const CFBO> requireReflectionFrameBuffer ();
+    /** An object whose program samples _rt_Reflection, it stays out of the reflection pass (object flag 8) */
+    void addReflectionReceiver (int id);
+    /** While the mirrored reflection pass draws, culling is inverted */
+    [[nodiscard]] bool isRenderingReflection () const { return this->m_renderingReflection; }
+    /** Keeps fbo at the output's size / divisor, like the buffers WE makes from the window client size */
+    void followOutputSize (const std::shared_ptr<CFBO>& fbo, float divisor);
 
     [[nodiscard]] int getWidth () const override;
     [[nodiscard]] int getHeight () const override;
@@ -54,10 +68,30 @@ public:
     [[nodiscard]] float getFps () const;
     /** Seconds since the scene was loaded, what wallpaper64.exe keeps in its renderer (+320) and resets past 432000 */
     [[nodiscard]] float getSceneClock () const;
+    /** Frames rendered since the scene was loaded, the first one is 1 */
+    [[nodiscard]] uint32_t getFrameCounter () const;
 
-    const glm::vec2* getMousePosition () const;
-    const glm::vec2* getMousePositionLast () const;
+    /** g_PointerPosition: the cursor over the output (y from the top), not mirrored by a horizontal flip */
+    const glm::vec2* getPointerPosition () const;
+    const glm::vec2* getPointerPositionLast () const;
     const glm::vec2* getMousePositionNormalized () const;
+    /** The cursor over the scene buffer (and the output), same orientation as getMousePositionNormalized */
+    const glm::vec2* getCursorScreenPosition () const;
+    /**
+     * The cursor unprojected through the scene camera's view and projection: the layout space of 2D scenes, WE's world
+     * in 3D ones (on the near plane there, like WE)
+     */
+    [[nodiscard]] glm::vec3 unprojectCursor () const;
+    /** Script input.cursorWorldPosition: unprojectCursor in WE's world (y up from the bottom left, z 0 in 2D) */
+    [[nodiscard]] glm::vec3 getCursorWorldPosition () const;
+    /** Script input.cursorScreenPosition: output pixels from the top left, mirrored like the projection when flipped */
+    [[nodiscard]] glm::vec2 getCursorPixelPosition () const;
+    /** The part of the canvas the output shows as ustart, uend, vstart, vend (the whole canvas in 3D scenes) */
+    [[nodiscard]] glm::vec4 getVisibleUVs () const;
+    /** getVisibleUVs as the canvas units cut off each side: left, right, bottom, top (y up) */
+    [[nodiscard]] glm::vec4 getVisibleMargins () const;
+    [[nodiscard]] float getOutputAspect () const;
+    [[nodiscard]] bool rendersAtOutputSize () const override { return true; }
     /** Pixel size of the output being drawn, what WE's window client area (and _rt_FullFrameBuffer) would be */
     [[nodiscard]] glm::ivec2 getOutputSize () const { return this->m_outputSize; }
     [[nodiscard]] bool isCursorLeftDown () const { return this->m_cursorLeftDown; }
@@ -97,9 +131,6 @@ public:
     [[nodiscard]] glm::ivec2 getOutputResolution () const;
     /** WE's world (scene units, y up from the bottom left in 2D) to clip space of the scene buffer */
     [[nodiscard]] glm::mat4 getWorldViewProjection () const;
-    /** Position of the active camera object in WE world units (y up, relative to the default camera), zero without one
-     */
-    [[nodiscard]] const glm::vec2& getCameraEye () const { return this->m_cameraEye; }
     [[nodiscard]] const CObject* getObject (int id) const;
     [[nodiscard]] CObject* getObject (int id);
     /** Whether the quad (-half..half, z 0) drawn through mvp covers the clip space point ndc. A planar quad stays
@@ -139,7 +170,7 @@ public:
     [[nodiscard]] const glm::vec4* getLightsColorRadius () const { return this->m_lightsColorRadius; }
     /**
      * LightingV1 uniforms (sub_140190C80): up to 15 lights per type in the order lit materials index them, and the
-     * counts their LIGHTS_* defines get. Shadow mapping isn't there, so this is WE with its shadow setting off
+     * counts their LIGHTS_* defines get. The shadow counts stay 0 with shadows off (--shadows disabled)
      */
     struct LightingV1 {
 	int points = 0;
@@ -147,6 +178,10 @@ public:
 	int tubes = 0;
 	int directionals = 0;
 	int spotCookies = 0;
+	int spotShadowCookies = 0;
+	int spotShadows = 0;
+	int directionalShadows = 0;
+	int pointShadows = 0;
 	glm::vec4 pointColor[15] = {};
 	glm::vec4 pointOrigin[15] = {};
 	glm::vec4 spotColor[15] = {};
@@ -158,10 +193,23 @@ public:
 	glm::vec4 tubeOriginB[15] = {};
 	glm::vec4 directionalColor[15] = {};
 	glm::vec4 directionalDirection[15] = {};
-	glm::mat4 featureProjection[3] = {};
-	glm::vec4 featureProjectionTransform[3] = {};
+	/** spot shadow+cookie, cookie, shadow, then three cascades per shadowed directional light */
+	glm::mat4 featureProjection[18] = {};
+	glm::vec4 featureProjectionTransform[18] = {};
+	glm::vec4 pointShadowProjection[3] = {};
+	glm::vec4 pointShadowProjectionTransform[3] = {};
+
+	[[nodiscard]] int features () const {
+	    return spotShadowCookies + spotCookies + spotShadows + 3 * directionalShadows;
+	}
     };
     [[nodiscard]] const LightingV1& getLightingV1 () const { return this->m_lightingV1; }
+    /** WE's shadow setting (renderer +428): 0 off, 1 low .. 4 ultra, LIGHTS_SHADOW_MAPPING_QUALITY */
+    [[nodiscard]] int getShadowQuality () const { return this->m_shadowQuality; }
+    /** _rt_shadowAtlas, the depth atlas every shadow is drawn into */
+    [[nodiscard]] const std::shared_ptr<const CFBO>& getShadowAtlas () const { return this->_rt_shadowAtlas; }
+    /** Whether the shadow pass draws this object: visible, not under a hidden group or a passthrough layer */
+    [[nodiscard]] bool isShadowCasterVisible (const CObject& object) const;
     /** The texture lit materials sample for cookie spots ("_alias_lightCookie"), null without a cookie spot */
     [[nodiscard]] std::shared_ptr<const TextureProvider> getLightCookie () const;
     /** The render order as scripts see it: without the synthesized bloom layer */
@@ -173,6 +221,9 @@ public:
     /** Script play()/stop() request for a Sound object, remembered because scripts can ask before the CSound exists */
     void setSoundPlaying (int id, bool playing);
     [[nodiscard]] std::optional<bool> getSoundPlayRequest (int id) const;
+    void pauseSound (int id);
+    /** The sound's own answer once it exists, otherwise what the script asked for */
+    [[nodiscard]] bool isSoundPlaying (int id, bool startSilent) const;
 
     /** Creates a new image layer from a model json at runtime, appended to the render order. Backs
      *  the scripting API's thisScene.createLayer(). Returns nullptr if the model couldn't be set up. */
@@ -184,8 +235,35 @@ public:
     /** Moves an existing layer to the given render-order slot. Backs thisScene.sortLayer(). */
     void sortLayer (CObject* object, int index);
 
+    /**
+     * WE's static scene camera (scene +280 eye, +292 center, +304 up, +316 zoom), what thisScene.getCameraTransforms /
+     * setCameraTransforms (engine slots 13 / 14) read and write and the camera whenever no camera object or path drives
+     * it (sub_1401891A0). It starts with the scene constructor's values; the loader (sub_140186C90) runs the objects'
+     * init () first and only then sets eye, center and up from scene.json, or the reset camera in 2D scenes without
+     * camera paths, so an init () sees the defaults and only its zoom survives
+     */
+    struct StaticCamera {
+	glm::vec3 eye { 2.0f };
+	glm::vec3 center { 0.0f };
+	glm::vec3 up { 0.0f, 1.0f, 0.0f };
+	float zoom = 1.0f;
+    };
+    StaticCamera& getStaticCamera () { return this->m_staticCamera; }
+
+    /** thisScene.createModelData / IModelData.applyData / replaceData / destroyModelData (engine slots 10-12) */
+    uint32_t createModelData (const ModelData::Config& config, ModelData::Error& error);
+    void applyModelData (uint32_t token, const ModelData::Config& config, bool replace, ModelData::Error& error);
+    void destroyModelData (uint32_t token);
+    /** A model layer's reference (sub_14021AD10), released with releaseModelData */
+    std::shared_ptr<ModelData::Model> acquireModelData (int token);
+    void releaseModelData (uint32_t token);
+
 protected:
     void appendLayer (CObject* object);
+    /** The program check of sub_14018C720 / sub_1401D6400: the material's first pass shader against a vertex format */
+    ModelData::Error checkModelDataMaterial (const std::string& material, uint32_t format);
+    /** The loader's part of the static camera, once the objects' init () ran */
+    void loadStaticCamera ();
     void renderFrame (const glm::ivec4& viewport) override;
     void renderFrameSteps (const glm::ivec4& viewport);
     void updateMouse (const glm::ivec4& viewport);
@@ -221,6 +299,10 @@ private:
     void releaseHDRBloom ();
     /** Copies the finished scene into _rt_MipMappedFrameBuffer and rebuilds its mips, WE does it before bloom */
     void updateMipMappedFrameBuffer () const;
+    /** The scene mirrored on the world's y = 0 plane into _rt_Reflection, before the main pass */
+    void renderReflection ();
+    /** --corner-color over the parts of the output a letterboxing alignment leaves uncovered */
+    void paintLetterbox () const;
     void updateFog (const glm::vec3& eye);
     /** Mouse parallax smoothing, after updateCamera () since a camera object moves the parallax camera too */
     void updateParallax ();
@@ -249,6 +331,11 @@ private:
     std::set<int> m_objectsInCreation = {};
     std::set<int> m_objectsInRenderOrderWalk = {};
     std::map<int, bool> m_soundPlayRequests = {};
+    ModelData::Store m_modelData;
+    StaticCamera m_staticCamera;
+    bool m_staticCameraLoaded = false;
+    /** checkModelDataMaterial results, compiling the material's shader every time would be slow */
+    std::map<std::pair<std::string, uint32_t>, ModelData::Error> m_modelDataMaterialChecks = {};
     std::vector<CObject*> m_objectsByRenderOrder = {};
     /** Camera objects in creation order, the last visible one wins */
     std::vector<CObject*> m_sceneCameras = {};
@@ -285,8 +372,10 @@ private:
     int m_nextDynamicLayerId = 2000000000;
     std::map<std::string, std::string> m_createLayerAliases = {};
     glm::vec2 m_mousePosition = {};
-    glm::vec2 m_mousePositionLast = {};
+    glm::vec2 m_pointerPosition = {};
+    glm::vec2 m_pointerPositionLast = {};
     glm::vec2 m_mousePositionNormalized = {};
+    glm::vec2 m_cursorScreen = {};
     /** Cursor in output pixels from the viewport's top left, unclamped and unflipped (WE's ScreenToClient point) */
     glm::vec2 m_mousePositionViewport = {};
     glm::ivec2 m_outputSize = {};
@@ -297,10 +386,16 @@ private:
     glm::vec2 m_parallaxBias = {};
     bool m_cursorLeftDown = false;
     float m_startTime = 0.0f;
+    uint32_t m_frameCounter { 0 };
     glm::vec3 m_lightsPosition[4] = {};
     glm::vec4 m_lightsColorPremultiplied[3] = {};
     glm::vec4 m_lightsColorRadius[4] = {};
     LightingV1 m_lightingV1;
+    int m_shadowQuality = 0;
+    std::vector<ShadowMapping::Entry> m_shadowEntries = {};
+    /** this frame's shadow of every light that got one, for its volumetrics */
+    std::unordered_map<const Data::Model::Light*, Volumetrics::Shadow> m_volumeShadows = {};
+    std::unique_ptr<ShadowMapping> m_shadowMapping;
     glm::vec2 m_cursorLastScenePosition = {};
     // object ids the pointer is over / that the current press started on
     std::set<int> m_cursorInside = {};
@@ -312,5 +407,15 @@ private:
     std::shared_ptr<const CFBO> _rt_Bloom = nullptr;
     std::shared_ptr<const CFBO> _rt_shadowAtlas = nullptr;
     std::shared_ptr<const CFBO> _rt_MipMappedFrameBuffer = nullptr;
+    std::shared_ptr<CFBO> _rt_Reflection = nullptr;
+    std::set<int> m_reflectionReceivers = {};
+    bool m_renderingReflection = false;
+    struct OutputSizedBuffer {
+	std::weak_ptr<CFBO> fbo;
+	float divisor;
+    };
+    std::vector<OutputSizedBuffer> m_outputSizedBuffers = {};
+    glm::ivec2 m_outputBufferSize = {};
+    void resizeOutputBuffers (glm::ivec2 size);
 };
 } // namespace WallpaperEngine::Render::Wallpaper

+ 28 - 2
src/WallpaperEngine/Render/Wallpapers/CWeb.cpp

@@ -37,6 +37,31 @@ void closeInheritedFds () {
     syscall (SYS_close_range, 3u, ~0u, 0u);
 #endif
 }
+
+// When the engine binary gets reinstalled while we're running, /proc/self/exe points at
+// "<path> (deleted)". exec'ing /proc/self/exe still works, but CEF resolves its own executable
+// through that link to start the zygote and aborts on the nonexistent path. The shared libs are
+// loaded from disk by the host anyway, so running the new binary at the original path is no less
+// consistent than running the deleted one.
+std::string hostExecutable () {
+    constexpr std::string_view deletedSuffix = " (deleted)";
+    std::error_code error;
+    const std::string target = std::filesystem::read_symlink ("/proc/self/exe", error).string ();
+
+    if (error || !target.ends_with (deletedSuffix)) {
+	return "/proc/self/exe";
+    }
+
+    std::string original = target.substr (0, target.size () - deletedSuffix.size ());
+
+    if (access (original.c_str (), X_OK) != 0) {
+	sLog.error ("CWeb: engine executable ", original, " was removed, the web host will likely fail to start");
+	return "/proc/self/exe";
+    }
+
+    sLog.out ("CWeb: engine executable was replaced on disk, starting the web host from ", original);
+    return original;
+}
 } // namespace
 
 CWeb::CWeb (
@@ -80,6 +105,7 @@ CWeb::CWeb (
 
 void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
     auto& appContext = this->getContext ().getApp ().getContext ();
+    const std::string executable = hostExecutable ();
 
     const pid_t pid = fork ();
 
@@ -121,7 +147,7 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
 	std::vector<char*> argv;
 	argv.reserve (args.size () + 2);
 	// cosmetic only (what the child sees as its own argv[0]) - the executable actually run is
-	// /proc/self/exe below, not this string, so it doesn't matter whether the original argv[0]
+	// hostExecutable(), not this string, so it doesn't matter whether the original argv[0]
 	// was absolute, relative, or PATH-resolved by the shell that launched us
 	argv.push_back (appContext.getArgv ()[0]);
 
@@ -131,7 +157,7 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
 
 	argv.push_back (nullptr);
 
-	execv ("/proc/self/exe", argv.data ());
+	execv (executable.c_str (), argv.data ());
 
 	// only reached if execv() itself failed
 	_exit (127);

+ 491 - 2
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -6,13 +6,21 @@
 #include <cmath>
 #include <cstring>
 #include <ranges>
+#include <string_view>
 #include <utility>
+#include <vector>
 
+#include "WallpaperEngine/Data/JSON.h"
 #include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Utils/ScopeGuard.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Objects/CCamera.h"
 #include "WallpaperEngine/Render/Objects/CImage.h"
+#include "WallpaperEngine/Render/Objects/CLight.h"
+#include "WallpaperEngine/Render/Objects/CMesh.h"
+#include "WallpaperEngine/Render/Objects/CParticle.h"
+#include "WallpaperEngine/Render/Objects/CText.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
@@ -328,6 +336,311 @@ JSValue videotexture_instantiate (
     return handle;
 }
 
+namespace {
+enum AnimationLayerCall {
+    LayerPlay,
+    LayerPause,
+    LayerStop,
+    LayerIsPlaying,
+    LayerGetFrame,
+    LayerSetFrame,
+    LayerAddEndedCallback,
+    LayerGetFps,
+    LayerGetFrameCount,
+    LayerGetDuration,
+    LayerGetName,
+    LayerGetVisible,
+    LayerSetVisible,
+    LayerGetRate,
+    LayerSetRate,
+    LayerGetBlend,
+    LayerSetBlend,
+};
+
+constexpr const char* AnimationLayerSerialKey = "__animationLayerSerial";
+constexpr uint32_t LayerFrameSet = 0x2000000;
+constexpr uint32_t LayerPaused = 0x20000000;
+constexpr uint32_t LayerStopped = 0x40000000;
+
+// the skeleton whose animation layers scripts reach: puppet images and models
+WallpaperEngine::Render::Objects::PuppetRig* animationRig (WallpaperEngine::Scripting::ScriptableObject& object) {
+    if (object.is<WallpaperEngine::Render::Objects::CImage> ()) {
+	return &object.as<WallpaperEngine::Render::Objects::CImage> ()->getRig ();
+    }
+
+    if (object.is<WallpaperEngine::Render::Objects::CMesh> ()) {
+	return &object.as<WallpaperEngine::Render::Objects::CMesh> ()->getRig ();
+    }
+
+    return nullptr;
+}
+
+// func_data is [engine address, object address, layer index]; the methods are sub_14026C420..sub_14026C4F0, the
+// read only numbers sub_14026C3E0/C400/C410 (fps, frameCount, duration)
+JSValue animation_layer_call (
+    JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic, JSValueConst* func_data
+) {
+    int64_t engineAddress = 0;
+    int64_t objectAddress = 0;
+    int64_t serial = 0;
+    JS_ToInt64 (ctx, &engineAddress, func_data[0]);
+    JS_ToInt64 (ctx, &objectAddress, func_data[1]);
+    JS_ToInt64 (ctx, &serial, func_data[2]);
+
+    auto* engine = reinterpret_cast<WallpaperEngine::Scripting::ScriptEngine*> (static_cast<intptr_t> (engineAddress));
+    auto* object
+	= reinterpret_cast<WallpaperEngine::Scripting::ScriptableObject*> (static_cast<intptr_t> (objectAddress));
+    auto* rig = animationRig (*object);
+    auto* clock = rig == nullptr ? nullptr : rig->findLayer (static_cast<size_t> (serial));
+
+    // destroyed, or a scene layer without a clip (WE never creates one)
+    if (clock == nullptr || clock->clip.fps <= 0.0f) {
+	return magic == LayerIsPlaying ? JS_FALSE : JS_UNDEFINED;
+    }
+
+    const auto& layer = *clock->layer;
+
+    switch (magic) {
+	case LayerGetName:
+	    return JS_NewString (ctx, layer.name.c_str ());
+	case LayerGetVisible:
+	    return engine->propertyToJs (*layer.visible->value, "");
+	case LayerSetVisible:
+	    if (argc > 0) {
+		engine->assignPropertyJsValue (argv[0], *layer.visible->value, "");
+	    }
+	    return JS_UNDEFINED;
+	case LayerGetRate:
+	    return engine->propertyToJs (*layer.rate->value, "");
+	case LayerSetRate:
+	    if (argc > 0) {
+		engine->assignPropertyJsValue (argv[0], *layer.rate->value, "");
+	    }
+	    return JS_UNDEFINED;
+	case LayerGetBlend:
+	    return engine->propertyToJs (*layer.blend->value, "");
+	case LayerSetBlend:
+	    if (argc > 0) {
+		engine->assignPropertyJsValue (argv[0], *layer.blend->value, "");
+	    }
+	    return JS_UNDEFINED;
+	default:
+	    break;
+    }
+
+    const float frameTime = 1.0f / clock->clip.fps;
+
+    switch (magic) {
+	case LayerPlay:
+	    if ((clock->flags & LayerStopped) != 0) {
+		clock->time = 0.0f;
+	    }
+	    clock->flags &= ~(LayerPaused | LayerStopped);
+	    return JS_UNDEFINED;
+	case LayerPause:
+	    clock->flags |= LayerPaused;
+	    return JS_UNDEFINED;
+	case LayerStop:
+	    // sub_14026C460 leaves it paused at 0, the stopped and backwards bits cleared
+	    clock->time = 0.0f;
+	    clock->flags = (clock->flags | LayerPaused) & 0x3FFFFFFF;
+	    return JS_UNDEFINED;
+	case LayerIsPlaying:
+	    return JS_NewBool (ctx, (clock->flags & (LayerPaused | LayerStopped)) == 0);
+	case LayerGetFrame:
+	    return JS_NewFloat64 (ctx, clock->time / frameTime);
+	case LayerSetFrame: {
+	    double frame = 0.0;
+	    if (argc > 0 && JS_IsNumber (argv[0]) && JS_ToFloat64 (ctx, &frame, argv[0]) == 0) {
+		clock->time = frameTime * static_cast<float> (frame);
+		clock->flags |= LayerFrameSet;
+	    }
+	    return JS_UNDEFINED;
+	}
+	case LayerAddEndedCallback:
+	    if (argc > 0) {
+		engine->addAnimationLayerEndedCallback (*object, static_cast<size_t> (serial), argv[0]);
+	    }
+	    return JS_UNDEFINED;
+	case LayerGetFps:
+	    return JS_NewFloat64 (ctx, 1.0f / frameTime);
+	case LayerGetFrameCount:
+	    return JS_NewInt32 (ctx, static_cast<int32_t> (clock->clip.frameCount));
+	case LayerGetDuration:
+	    return JS_NewFloat64 (ctx, static_cast<float> (clock->clip.frameCount) * frameTime);
+	default:
+	    return JS_UNDEFINED;
+    }
+}
+} // namespace
+
+JSValue WallpaperEngine::Scripting::Adapters::makeAnimationLayerHandle (
+    ScriptEngine& engine, ScriptableObject& object, size_t serial
+) {
+    JSContext* ctx = engine.getContext ();
+    JSValue handle = JS_NewObject (ctx);
+    JSValue data[] = {
+	JS_NewInt64 (ctx, static_cast<int64_t> (reinterpret_cast<intptr_t> (&engine))),
+	JS_NewInt64 (ctx, static_cast<int64_t> (reinterpret_cast<intptr_t> (&object))),
+	JS_NewInt64 (ctx, static_cast<int64_t> (serial)),
+    };
+
+    const auto method = [&] (const char* name, int magic, int length) {
+	JS_SetPropertyStr (ctx, handle, name, JS_NewCFunctionData (ctx, animation_layer_call, length, magic, 3, data));
+    };
+    const auto accessor = [&] (const char* name, int getter, int setter) {
+	JSAtom atom = JS_NewAtom (ctx, name);
+	JSValue get = JS_NewCFunctionData (ctx, animation_layer_call, 0, getter, 3, data);
+	JSValue set = setter < 0 ? JS_UNDEFINED : JS_NewCFunctionData (ctx, animation_layer_call, 1, setter, 3, data);
+	JS_DefinePropertyGetSet (ctx, handle, atom, get, set, JS_PROP_ENUMERABLE);
+	JS_FreeAtom (ctx, atom);
+    };
+
+    method ("play", LayerPlay, 0);
+    method ("pause", LayerPause, 0);
+    method ("stop", LayerStop, 0);
+    method ("isPlaying", LayerIsPlaying, 0);
+    method ("getFrame", LayerGetFrame, 0);
+    method ("setFrame", LayerSetFrame, 1);
+    method ("addEndedCallback", LayerAddEndedCallback, 1);
+    accessor ("fps", LayerGetFps, -1);
+    accessor ("frameCount", LayerGetFrameCount, -1);
+    accessor ("duration", LayerGetDuration, -1);
+    accessor ("name", LayerGetName, -1);
+    accessor ("visible", LayerGetVisible, LayerSetVisible);
+    accessor ("rate", LayerGetRate, LayerSetRate);
+    accessor ("blend", LayerGetBlend, LayerSetBlend);
+
+    // lets destroyAnimationLayer() take the object back
+    JS_DefinePropertyValueStr (ctx, handle, AnimationLayerSerialKey, JS_NewInt64 (ctx, static_cast<int64_t> (serial)), 0);
+
+    for (const auto& value : data) {
+	JS_FreeValue (ctx, value);
+    }
+
+    return handle;
+}
+
+namespace {
+enum ImageAnimationLayerCall {
+    GetAnimationLayerCount,
+    GetAnimationLayer,
+    CreateAnimationLayer,
+    PlaySingleAnimation,
+    DestroyAnimationLayer,
+};
+
+// scenescript64 hands objects over as JSON text; a string in the config slot is parsed as JSON text too
+WallpaperEngine::Data::JSON::JSON animationLayerArgument (JSContext* ctx, JSValueConst value, bool parseStrings) {
+    using WallpaperEngine::Data::JSON::JSON;
+
+    if (JS_IsString (value) && !parseStrings) {
+	const char* text = JS_ToCString (ctx, value);
+	JSON result = text == nullptr ? JSON () : JSON (std::string (text));
+	JS_FreeCString (ctx, text);
+	return result;
+    }
+
+    std::string text;
+
+    if (JS_IsString (value)) {
+	const char* raw = JS_ToCString (ctx, value);
+	text = raw == nullptr ? "" : raw;
+	JS_FreeCString (ctx, raw);
+    } else if (JS_IsObject (value)) {
+	JSValue json = JS_JSONStringify (ctx, value, JS_UNDEFINED, JS_UNDEFINED);
+	const char* raw = JS_IsString (json) ? JS_ToCString (ctx, json) : nullptr;
+	text = raw == nullptr ? "" : raw;
+	JS_FreeCString (ctx, raw);
+	JS_FreeValue (ctx, json);
+    }
+
+    return JSON::parse (text, nullptr, false);
+}
+
+// IImageLayer animation layer calls, wallpaper64 2.8.42 sub_14020E910 (get), sub_14020E9F0 (count), sub_14020EA30
+// (create), sub_14020EF40 (playSingle = create + removed once it ends), sub_14020EF80 (destroy)
+JSValue scriptableobject_animation_layer_call (
+    JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic, JSValueConst* func_data
+) {
+    using WallpaperEngine::Render::Objects::CImage;
+
+    int64_t objectAddress = 0;
+    int64_t engineAddress = 0;
+    JS_ToInt64 (ctx, &objectAddress, func_data[0]);
+    JS_ToInt64 (ctx, &engineAddress, func_data[1]);
+    auto* object
+	= reinterpret_cast<WallpaperEngine::Scripting::ScriptableObject*> (static_cast<intptr_t> (objectAddress));
+    auto* engine = reinterpret_cast<WallpaperEngine::Scripting::ScriptEngine*> (static_cast<intptr_t> (engineAddress));
+
+    auto* rig = animationRig (*object);
+    const auto handleFor = [&] (std::optional<size_t> serial) {
+	return serial.has_value () ? makeAnimationLayerHandle (*engine, *object, *serial) : JS_NULL;
+    };
+
+    switch (magic) {
+	case GetAnimationLayerCount:
+	    return JS_NewInt32 (ctx, rig == nullptr ? 0 : static_cast<int32_t> (rig->getLayerCount ()));
+	case GetAnimationLayer: {
+	    if (rig == nullptr || argc < 1) {
+		return JS_NULL;
+	    }
+	    if (JS_IsNumber (argv[0])) {
+		int64_t index = -1;
+		JS_ToInt64 (ctx, &index, argv[0]);
+		return handleFor (rig->getLayerAt (index));
+	    }
+	    if (JS_IsString (argv[0])) {
+		const char* name = JS_ToCString (ctx, argv[0]);
+		const auto serial = rig->findLayerByName (name == nullptr ? "" : name);
+		JS_FreeCString (ctx, name);
+		return handleFor (serial);
+	    }
+	    return JS_NULL;
+	}
+	case CreateAnimationLayer:
+	case PlaySingleAnimation: {
+	    if (rig == nullptr || argc < 1) {
+		return JS_NULL;
+	    }
+	    const auto animation = animationLayerArgument (ctx, argv[0], false);
+	    const auto config = argc > 1 ? animationLayerArgument (ctx, argv[1], true)
+					 : WallpaperEngine::Data::JSON::JSON ();
+	    return handleFor (rig->createLayer (
+		animation, config, magic == PlaySingleAnimation, object->getScene ().getScene ().project
+	    ));
+	}
+	case DestroyAnimationLayer: {
+	    if (rig == nullptr || argc < 1) {
+		return JS_FALSE;
+	    }
+	    if (JS_IsNumber (argv[0])) {
+		int64_t index = -1;
+		JS_ToInt64 (ctx, &index, argv[0]);
+		const auto serial = rig->getLayerAt (index);
+		return JS_NewBool (ctx, serial.has_value () && rig->destroyLayer (*serial));
+	    }
+	    if (JS_IsString (argv[0])) {
+		const char* name = JS_ToCString (ctx, argv[0]);
+		const bool destroyed = rig->destroyLayersByName (name == nullptr ? "" : name);
+		JS_FreeCString (ctx, name);
+		return JS_NewBool (ctx, destroyed);
+	    }
+	    if (JS_IsObject (argv[0])) {
+		JSValue serialValue = JS_GetPropertyStr (ctx, argv[0], AnimationLayerSerialKey);
+		int64_t serial = -1;
+		const bool isLayer = JS_IsNumber (serialValue) && JS_ToInt64 (ctx, &serial, serialValue) == 0;
+		JS_FreeValue (ctx, serialValue);
+		return JS_NewBool (ctx, isLayer && rig->destroyLayer (static_cast<size_t> (serial)));
+	    }
+	    return JS_FALSE;
+	}
+	default:
+	    return JS_UNDEFINED;
+    }
+}
+} // namespace
+
 // scripts call this on image layers whose material is a video (mp4 texture), everything else gets null
 JSValue scriptableobject_video_texture_call (
     JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic, JSValueConst* func_data
@@ -618,6 +931,142 @@ JSValue scriptableobject_bone_call (
     return JS_UNDEFINED;
 }
 
+namespace {
+// The members WE's layer objects have: scenescript64 builds each layer object from the object's property and method
+// lists, parents included, plus getAnimation (sub_181652380). The lists are wallpaper64 2.8.42's static tables,
+// object (sub_1401E0530) under renderable (sub_1401EE520) under image (sub_140211070) and text (sub_140258CA0);
+// particles (sub_14024CB00), models (sub_140227470), lights (sub_14025DA80) and cameras (sub_1401F3460) sit
+// directly on the object one. Plain groups only have the object's
+constexpr std::string_view ObjectMembers[] = {
+    "origin", "scale", "angles", "parallaxDepth", "sortorder", "name", "solid", "disablepropagation",
+    "getTransformMatrix", "rotateObjectSpace", "lookAt", "lookAtYaw", "setParent", "getParent", "getChildren",
+    "getAttachmentIndex", "getAttachmentMatrix", "getAttachmentOrigin", "getAttachmentAngles", "getAnimation",
+};
+constexpr std::string_view RenderableMembers[] = {
+    "size", "color", "alpha", "brightness", "visible", "perspective", "castshadow", "copybackground",
+    "nointerpolation", "clampuvs", "ledsource", "colorBlendMode", "getEffect", "getEffectCount",
+    "transformAttachmentToTexture",
+};
+constexpr std::string_view ImageMembers[] = {
+    "alignment", "getTextureAnimation", "getVideoTexture", "getAnimationLayer", "getAnimationLayerCount",
+    "createAnimationLayer", "playSingleAnimation", "destroyAnimationLayer", "getBoneCount", "getBoneTransform",
+    "setBoneTransform", "getLocalBoneTransform", "setLocalBoneTransform", "getLocalBoneAngles", "setLocalBoneAngles",
+    "getLocalBoneOrigin", "setLocalBoneOrigin", "getBlendShapeIndex", "getBlendShapeWeight", "setBlendShapeWeight",
+    "getBoneIndex", "getBoneParentIndex", "applyBonePhysicsImpulse", "resetBonePhysicsSimulation",
+};
+constexpr std::string_view TextMembers[] = {
+    "backgroundbrightness", "opaquebackground", "limitwidth", "limitrows", "limituseellipsis", "blockalign",
+    "backgroundcolor", "pointsize", "padding", "spacing", "maxwidth", "maxrows", "msdf", "outline", "blur",
+    "dropshadow", "outlinethickness", "outlinecolor", "blursize", "dropshadowsize", "dropshadowopacity",
+    "dropshadowcolor", "dropshadowoffset", "depthtest", "horizontalalign", "verticalalign", "anchor", "text", "font",
+};
+constexpr std::string_view ParticleMembers[] = {
+    "visible", "play", "pause", "stop", "isPlaying", "emitParticles",
+};
+constexpr std::string_view ModelMembers[] = {
+    "visible", "perspective", "castshadow", "rootmotion", "getAnimationLayer", "getAnimationLayerCount",
+    "createAnimationLayer", "playSingleAnimation", "destroyAnimationLayer",
+};
+constexpr std::string_view LightMembers[] = {
+    "color", "intensity", "radius", "exponent", "innercone", "outercone", "density", "volumetricsexponent",
+    "cascadedistance0", "cascadedistance1", "cascadedistance2", "lightsourcesize", "controlpoint", "light",
+    "visible", "castshadow", "usecookie", "castvolumetrics",
+};
+constexpr std::string_view CameraMembers[] = { "visible", "fov", "zoom", "queuemode" };
+
+// parents first, like the object's property list scenescript64 walks
+std::vector<std::string_view> layerMembers (const WallpaperEngine::Scripting::ScriptableObject& object) {
+    using namespace WallpaperEngine::Render::Objects;
+
+    std::vector<std::string_view> members (std::begin (ObjectMembers), std::end (ObjectMembers));
+    const auto add = [&members] (const auto& list) { members.insert (members.end (), std::begin (list), std::end (list)); };
+
+    if (object.is<CImage> ()) {
+	add (RenderableMembers);
+	add (ImageMembers);
+    } else if (object.is<CText> ()) {
+	add (RenderableMembers);
+	add (TextMembers);
+    } else if (object.is<CParticle> ()) {
+	add (ParticleMembers);
+    } else if (object.is<CMesh> ()) {
+	add (ModelMembers);
+    } else if (object.is<CLight> ()) {
+	add (LightMembers);
+    } else if (object.is<CCamera> ()) {
+	add (CameraMembers);
+    }
+
+    return members;
+}
+
+bool isLayerMember (const WallpaperEngine::Scripting::ScriptableObject& object, JSContext* ctx, JSAtom atom) {
+    const char* name = JS_AtomToCString (ctx, atom);
+
+    if (name == nullptr) {
+	JS_FreeValue (ctx, JS_GetException (ctx));
+	return false;
+    }
+
+    const auto members = layerMembers (object);
+    const bool member = std::ranges::find (members, std::string_view (name)) != members.end ();
+    JS_FreeCString (ctx, name);
+
+    return member;
+}
+
+WallpaperEngine::Scripting::ScriptableObject* layerOf (JSValueConst obj) {
+    JSClassID classId = 0;
+    auto* container = static_cast<OpaqueScriptableObjectAdapter*> (JS_GetAnyOpaque (obj, &classId));
+
+    return container != nullptr && container->magic == SCRIPTABLE_OPAQUE_MAGIC ? &container->object : nullptr;
+}
+} // namespace
+
+// The members are own, enumerable properties of WE's layers (template accessors and functions without DontEnum), so
+// `in`, hasOwnProperty, getOwnPropertyDescriptor and Object.keys see them next to whatever scripts stored on the layer.
+// QuickJS finds those stored ones before asking these hooks, then goes on to the prototype
+int scriptableobject_property_own (JSContext* ctx, JSPropertyDescriptor* desc, JSValueConst obj, JSAtom atom) {
+    auto* object = layerOf (obj);
+
+    if (object == nullptr || !isLayerMember (*object, ctx, atom)) {
+	return false;
+    }
+
+    if (desc != nullptr) {
+	JSValue value = JS_GetProperty (ctx, obj, atom);
+
+	if (JS_IsException (value)) {
+	    return -1;
+	}
+
+	desc->flags = JS_PROP_C_W_E;
+	desc->value = value;
+	desc->getter = JS_UNDEFINED;
+	desc->setter = JS_UNDEFINED;
+    }
+
+    return true;
+}
+
+int scriptableobject_property_names (JSContext* ctx, JSPropertyEnum** tab, uint32_t* length, JSValueConst obj) {
+    auto* object = layerOf (obj);
+    const auto members = object == nullptr ? std::vector<std::string_view> {} : layerMembers (*object);
+
+    *tab = static_cast<JSPropertyEnum*> (js_mallocz (ctx, sizeof (JSPropertyEnum) * std::max<size_t> (members.size (), 1)));
+    *length = 0;
+
+    if (*tab == nullptr) {
+	return -1;
+    }
+
+    for (const auto& member : members) {
+	(*tab)[(*length)++].atom = JS_NewAtomLen (ctx, member.data (), member.size ());
+    }
+
+    return 0;
+}
+
 JSValue scriptableobject_property_get (JSContext* ctx, JSValueConst obj_val, JSAtom atom, JSValueConst receiver) {
     JSClassID classId = 0;
 
@@ -705,6 +1154,29 @@ JSValue scriptableobject_property_get (JSContext* ctx, JSValueConst obj_val, JSA
 	{ "resetBonePhysicsSimulation", ResetBonePhysicsSimulation, 1 },
     };
 
+    static constexpr struct {
+	const char* name;
+	int magic;
+	int length;
+    } animationLayerCalls[] = {
+	{ "getAnimationLayerCount", GetAnimationLayerCount, 0 },
+	{ "getAnimationLayer", GetAnimationLayer, 1 },
+	{ "createAnimationLayer", CreateAnimationLayer, 2 },
+	{ "playSingleAnimation", PlaySingleAnimation, 2 },
+	{ "destroyAnimationLayer", DestroyAnimationLayer, 1 },
+    };
+
+    for (const auto& call : animationLayerCalls) {
+	if (std::strcmp (name, call.name) == 0) {
+	    JSValue data[] = {
+		JS_NewInt64 (ctx, static_cast<int64_t> (reinterpret_cast<intptr_t> (&container->object))),
+		JS_NewInt64 (ctx, static_cast<int64_t> (reinterpret_cast<intptr_t> (&container->adapter.getEngine ()))),
+	    };
+
+	    return JS_NewCFunctionData (ctx, scriptableobject_animation_layer_call, call.length, call.magic, 2, data);
+	}
+    }
+
     for (const auto& call : boneCalls) {
 	if (std::strcmp (name, call.name) == 0) {
 	    JSValue data[] = {
@@ -758,7 +1230,18 @@ JSValue scriptableobject_property_get (JSContext* ctx, JSValueConst obj_val, JSA
 	}
     }
 
-    return JS_UNDEFINED;
+    // QuickJS doesn't look at the prototype once an exotic getter exists
+    JSValue prototype = JS_GetPrototype (ctx, obj_val);
+
+    if (!JS_IsObject (prototype)) {
+	JS_FreeValue (ctx, prototype);
+	return JS_UNDEFINED;
+    }
+
+    JSValue inherited = JS_GetProperty (ctx, prototype, atom);
+    JS_FreeValue (ctx, prototype);
+
+    return inherited;
 }
 
 int scriptableobject_property_set (
@@ -802,7 +1285,10 @@ int scriptableobject_property_set (
 
 ScriptableObjectAdapter::ScriptableObjectAdapter (ScriptEngine& engine, std::string name) :
     ObjectAdapter (engine),
-    m_exoticMethods ({ .get_property = scriptableobject_property_get, .set_property = scriptableobject_property_set }),
+    m_exoticMethods ({ .get_own_property = scriptableobject_property_own,
+		       .get_own_property_names = scriptableobject_property_names,
+		       .get_property = scriptableobject_property_get,
+		       .set_property = scriptableobject_property_set }),
     m_name (std::move (name)) {
     this->registerType (
 	{
@@ -810,6 +1296,9 @@ ScriptableObjectAdapter::ScriptableObjectAdapter (ScriptEngine& engine, std::str
 	    .exotic = &m_exoticMethods,
 	}
     );
+
+    // WE's layers are V8 template instances, so they inherit Object.prototype (hasOwnProperty, toString, ...)
+    JS_SetClassProto (engine.getContext (), this->m_classId, JS_NewObject (engine.getContext ()));
 }
 
 JSValue ScriptableObjectAdapter::instantiate (ScriptableObject& object) {

+ 7 - 0
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h

@@ -4,7 +4,14 @@
 
 #include <unordered_map>
 
+namespace WallpaperEngine::Render::Objects {
+class CImage;
+}
+
 namespace WallpaperEngine::Scripting::Adapters {
+/** IAnimationLayer (wallpaper64 2.8.42 sub_14026C980) for the puppet animation layer with that serial */
+JSValue makeAnimationLayerHandle (ScriptEngine& engine, ScriptableObject& object, size_t serial);
+
 class ScriptableObjectAdapter : public ObjectAdapter {
 public:
     explicit ScriptableObjectAdapter (ScriptEngine& engine, std::string name);

+ 80 - 59
src/WallpaperEngine/Scripting/EngineObject.cpp

@@ -9,9 +9,11 @@
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 
+#include <algorithm>
 #include <chrono>
 #include <map>
 #include <ranges>
+#include <vector>
 
 using namespace WallpaperEngine::Scripting;
 
@@ -250,78 +252,30 @@ JSValue engine_set_interval (JSContext* ctx, JSValueConst this_val, int argc, JS
     return JS_NewCFunctionData (ctx, engine_stop_interval, 2, magic, 1, args);
 }
 
-// Backs the "left"/"right"/"average" getters on the object returned by registerAudioBuffers(). WE hands out
-// Float32Array views into its [left | right | average] buffer, these copy the same part on every read.
-JSValue audio_buffer_get_values (
-    JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic, JSValueConst* func_data
-) {
-    int engineInstanceId = 0;
-    int resolution = 32;
-    int section = 0;
-
-    JS_ToInt32 (ctx, &engineInstanceId, func_data[0]);
-    JS_ToInt32 (ctx, &resolution, func_data[1]);
-    JS_ToInt32 (ctx, &section, func_data[2]);
-
-    JSValue result = JS_NewArray (ctx);
-
-    const auto it = engineInstances.find (engineInstanceId);
+// engine.registerAudioBuffers(resolution), scenescript64 2.8.42 sub_181655170: only from a module's top level
+// code, no number argument means 16, anything but 16/32/64 throws. Both errors are SyntaxErrors in live WE.
+JSValue engine_register_audio_buffers (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic) {
+    const auto it = engineInstances.find (magic);
 
     if (it == engineInstances.end ()) {
-	sLog.error (
-	    "registerAudioBuffers: no EngineObject found for instance ", engineInstanceId, " - returning zeros"
-	);
-	return result;
+	return JS_ThrowTypeError (ctx, "registerAudioBuffers: engine instance is gone");
     }
 
-    const auto& recorder = it->second.getScene ().getAudioContext ().getDriver ().getRecorder ();
-    const float* data = recorder.audio32;
-
-    if (resolution == 16) {
-	data = recorder.audio16;
-    } else if (resolution == 64) {
-	data = recorder.audio64;
+    if (!it->second.getEngine ().isEvaluatingModuleBody ()) {
+	return JS_ThrowSyntaxError (ctx, "registerAudioBuffers can only be called from global scope.");
     }
 
-    data += section * resolution;
-
-    for (int i = 0; i < resolution; i++) {
-	JS_SetPropertyUint32 (ctx, result, i, JS_NewFloat64 (ctx, data[i]));
-    }
-
-    return result;
-}
-
-// engine.registerAudioBuffers(resolution): resolution must be 16, 32 or 64 (falls back to 32
-// otherwise), matching the AUDIO_RESOLUTION_* constants below. Returns an object whose
-// left/right/average properties are re-read from the live spectrum every access, so scripts
-// that poll them from an update() callback see current values each frame.
-JSValue engine_register_audio_buffers (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic) {
-    int resolution = 32;
+    int resolution = 16;
 
-    if (argc > 0) {
+    if (argc > 0 && JS_IsNumber (argv[0])) {
 	JS_ToInt32 (ctx, &resolution, argv[0]);
     }
 
     if (resolution != 16 && resolution != 32 && resolution != 64) {
-	resolution = 32;
-    }
-
-    JSValue result = JS_NewObject (ctx);
-    // same order as the sections of the recorder's buffers
-    static constexpr const char* properties[] = { "left", "right", "average" };
-
-    for (int section = 0; section < 3; section++) {
-	JSValue closureData[] = { JS_NewInt32 (ctx, magic), JS_NewInt32 (ctx, resolution), JS_NewInt32 (ctx, section) };
-
-	JS_DefinePropertyGetSet (
-	    ctx, result, JS_NewAtom (ctx, properties[section]),
-	    JS_NewCFunctionData (ctx, audio_buffer_get_values, 0, 0, 3, closureData),
-	    JS_NewCFunction (ctx, engine_set_value, "set", 1), JS_PROP_ENUMERABLE
-	);
+	return JS_ThrowSyntaxError (ctx, "Resolution must be either 16, 32 or 64.");
     }
 
-    return result;
+    return it->second.registerAudioBuffers (resolution);
 }
 
 JSValue engine_set_timeout (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic) {
@@ -508,9 +462,63 @@ EngineObject::~EngineObject () {
     this->m_intervals.clear ();
     this->m_timeouts.clear ();
 
+    for (const auto& buffer : this->m_audioBuffers) {
+	JS_FreeValue (this->m_engine.getContext (), buffer);
+    }
+
     JS_FreeValue (this->m_engine.getContext (), this->m_instance);
 }
 
+float* EngineObject::audioBufferData (int index) {
+    auto* ctx = this->m_engine.getContext ();
+    const size_t size = (16u << (index / 3)) * sizeof (float);
+    size_t length = 0;
+
+    if (!JS_IsUndefined (this->m_audioBuffers[index])) {
+	if (auto* data = JS_GetArrayBuffer (ctx, &length, this->m_audioBuffers[index]); data != nullptr) {
+	    return reinterpret_cast<float*> (data);
+	}
+
+	// a script detached it with transfer(), WE's memory would still be there so start a new one
+	JS_FreeValue (ctx, JS_GetException (ctx));
+	JS_FreeValue (ctx, this->m_audioBuffers[index]);
+    }
+
+    const std::vector<uint8_t> zeros (size);
+    this->m_audioBuffers[index] = JS_NewArrayBufferCopy (ctx, zeros.data (), zeros.size ());
+
+    return reinterpret_cast<float*> (JS_GetArrayBuffer (ctx, &length, this->m_audioBuffers[index]));
+}
+
+// WE keeps nine buffers per script context and wraps them in new Float32Arrays on every call, so all
+// registrations of a resolution share their memory. Ours also share the ArrayBuffer object: one over
+// memory we own would be reallocated by ArrayBuffer.prototype.transfer()
+JSValue EngineObject::registerAudioBuffers (int resolution) {
+    auto* ctx = this->m_engine.getContext ();
+    const int first = 3 * (resolution >> 5);
+
+    for (int index = 0; index < 9; index++) {
+	this->audioBufferData (index);
+    }
+
+    JSValue result = JS_NewObject (ctx);
+    static constexpr const char* sections[] = { "left", "right", "average" };
+
+    for (int section = 0; section < 3; section++) {
+	JSValue args[] = { this->m_audioBuffers[first + section], JS_NewInt32 (ctx, 0), JS_NewInt32 (ctx, resolution) };
+	JSValue array = JS_NewTypedArray (ctx, 3, args, JS_TYPED_ARRAY_FLOAT32);
+
+	if (JS_IsException (array)) {
+	    JS_FreeValue (ctx, result);
+	    return array;
+	}
+
+	JS_SetPropertyStr (ctx, result, sections[section], array);
+    }
+
+    return result;
+}
+
 uint32_t EngineObject::reserveNextTimeoutId (JSValue function, uint64_t duration) {
     const auto id = ++this->m_nextTimeoutId;
 
@@ -570,6 +578,19 @@ void EngineObject::tick () {
     const auto now = std::chrono::steady_clock::now ();
     auto* ctx = this->m_engine.getContext ();
 
+    // scenescript64 sub_18164F800 copies [left | right | average] into the registered buffers before any
+    // callback runs, so what scripts write there lasts until the next frame
+    if (!JS_IsUndefined (this->m_audioBuffers[0])) {
+	const auto& recorder = this->m_scene.getAudioContext ().getDriver ().getRecorder ();
+	const float* sources[] = { recorder.audio16, recorder.audio32, recorder.audio64 };
+
+	for (int index = 0; index < 9; index++) {
+	    const int bands = 16 << (index / 3);
+
+	    std::copy_n (sources[index / 3] + (index % 3) * bands, bands, this->audioBufferData (index));
+	}
+    }
+
     // only ids are collected up front, callbacks may clearInterval()/setTimeout() from inside themselves
     std::vector<uint32_t> dueIntervals;
 

+ 6 - 0
src/WallpaperEngine/Scripting/EngineObject.h

@@ -24,8 +24,11 @@ public:
     void clearInterval (uint32_t id);
 
     void tick ();
+    JSValue registerAudioBuffers (int resolution);
 
 protected:
+    float* audioBufferData (int index);
+
     struct Timeout {
 	JSValue callback;
 	std::chrono::milliseconds duration;
@@ -43,5 +46,8 @@ protected:
     JSClassID m_classId;
     JSClassDef m_definition;
     JSValue m_instance;
+    // left, right and average for 16, 32 and 64 bands, created by the first registerAudioBuffers call
+    JSValue m_audioBuffers[9] = { JS_UNDEFINED, JS_UNDEFINED, JS_UNDEFINED, JS_UNDEFINED, JS_UNDEFINED,
+				  JS_UNDEFINED, JS_UNDEFINED, JS_UNDEFINED, JS_UNDEFINED };
 };
 }

+ 7 - 9
src/WallpaperEngine/Scripting/InputObject.cpp

@@ -11,14 +11,12 @@ JSValue get_cursor_world_position (JSContext* ctx, JSValueConst this_val, int ar
     auto* input = static_cast<InputObject*> (JS_GetAnyOpaque (this_val, &classId));
 
     auto& scene = input->getScene ();
-    const auto position = scene.getMousePositionNormalized ();
-
-    // same scene space as layer origins (y up from the bottom), and the point the cursor event hit test uses
+    const glm::vec3 position = scene.getCursorWorldPosition ();
     JSValue result = scene.getScriptEngine ().getAdapters ().vec3->instantiate ();
 
-    JS_SetPropertyStr (ctx, result, "x", JS_NewFloat64 (ctx, position->x * static_cast<float> (scene.getWidth ())));
-    JS_SetPropertyStr (ctx, result, "y", JS_NewFloat64 (ctx, position->y * static_cast<float> (scene.getHeight ())));
-    JS_SetPropertyStr (ctx, result, "z", JS_NewFloat64 (ctx, 0.0));
+    JS_SetPropertyStr (ctx, result, "x", JS_NewFloat64 (ctx, position.x));
+    JS_SetPropertyStr (ctx, result, "y", JS_NewFloat64 (ctx, position.y));
+    JS_SetPropertyStr (ctx, result, "z", JS_NewFloat64 (ctx, position.z));
 
     return result;
 }
@@ -26,12 +24,12 @@ JSValue get_cursor_world_position (JSContext* ctx, JSValueConst this_val, int ar
 JSValue get_cursor_screen_position (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
     JSClassID classId;
     auto* input = static_cast<InputObject*> (JS_GetAnyOpaque (this_val, &classId));
-    auto position = input->getScene ().getMousePositionNormalized ();
+    const glm::vec2 position = input->getScene ().getCursorPixelPosition ();
 
     JSValue result = input->getScene ().getScriptEngine ().getAdapters ().vec2->instantiate ();
 
-    JS_SetPropertyStr (ctx, result, "x", JS_NewFloat64 (ctx, position->x));
-    JS_SetPropertyStr (ctx, result, "y", JS_NewFloat64 (ctx, position->y));
+    JS_SetPropertyStr (ctx, result, "x", JS_NewFloat64 (ctx, position.x));
+    JS_SetPropertyStr (ctx, result, "y", JS_NewFloat64 (ctx, position.y));
 
     return result;
 }

+ 477 - 3
src/WallpaperEngine/Scripting/SceneObject.cpp

@@ -6,6 +6,10 @@
 #include "WallpaperEngine/Data/Utils/ScopeGuard.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 
+#include <array>
+#include <cmath>
+#include <cstring>
+#include <map>
 #include <optional>
 
 using namespace WallpaperEngine::Scripting;
@@ -156,8 +160,11 @@ JSValue sound_layer_call (
 	case 1:
 	    scene->setSoundPlaying (id, false);
 	    return JS_UNDEFINED;
+	case 3:
+	    scene->pauseSound (id);
+	    return JS_UNDEFINED;
 	default:
-	    return JS_NewBool (ctx, scene->getSoundPlayRequest (id).value_or (startsilent == 0));
+	    return JS_NewBool (ctx, scene->isSoundPlaying (id, startsilent != 0));
     }
 }
 
@@ -169,7 +176,7 @@ instantiate_sound_layer (JSContext* ctx, WallpaperEngine::Render::Wallpapers::CS
     static constexpr struct {
 	const char* name;
 	int magic;
-    } calls[] = { { "play", 0 }, { "stop", 1 }, { "pause", 1 }, { "isPlaying", 2 } };
+    } calls[] = { { "play", 0 }, { "stop", 1 }, { "pause", 3 }, { "isPlaying", 2 } };
 
     for (const auto& call : calls) {
 	JS_SetPropertyStr (ctx, handle, call.name, JS_NewCFunctionData (ctx, sound_layer_call, 0, call.magic, 3, data));
@@ -335,6 +342,432 @@ std::optional<JSON> stringify_layer_config (JSContext* ctx, JSValueConst config)
     return parsed;
 }
 
+// IModelData, scenescript64 2.8.42: config parsing sub_18162FD40 / sub_181630720, createModelData sub_1816361F0,
+// applyData / replaceData sub_181636B60 / sub_181636EF0, destroyModelData sub_181636890. Every error is a SyntaxError
+namespace ModelDataScript {
+using namespace WallpaperEngine::Render;
+
+struct Handle {
+    SceneObject* scene;
+    uint32_t token;
+};
+
+JSValue property (JSContext* ctx, JSValueConst object, const char* name) { return JS_GetPropertyStr (ctx, object, name); }
+
+template <typename T> bool readTypedArray (JSContext* ctx, JSValueConst value, int type, std::vector<T>& out) {
+    if (JS_GetTypedArrayType (value) != type) {
+	return false;
+    }
+
+    size_t offset = 0;
+    size_t length = 0;
+    size_t elementSize = 0;
+    JSValue buffer = JS_GetTypedArrayBuffer (ctx, value, &offset, &length, &elementSize);
+    size_t size = 0;
+    const uint8_t* data = JS_GetArrayBuffer (ctx, &size, buffer);
+
+    out.resize (length / sizeof (T));
+
+    if (data != nullptr && !out.empty () && offset + length <= size) {
+	std::memcpy (out.data (), data + offset, out.size () * sizeof (T));
+    }
+
+    JS_FreeValue (ctx, buffer);
+    return true;
+}
+
+/** false with a pending exception */
+bool parseShape (JSContext* ctx, JSValueConst value, bool create, ModelData::ShapeConfig& shape) {
+    static const std::map<std::string, uint32_t> formats = {
+	{ "position", ModelData::FORMAT_POSITION },	  { "normal", ModelData::FORMAT_NORMAL },
+	{ "tangentSigned", ModelData::FORMAT_TANGENT_SIGNED }, { "uv", ModelData::FORMAT_UV },
+	{ "color", ModelData::FORMAT_COLOR },
+    };
+
+    if (!JS_IsObject (value)) {
+	shape.deleteShape = JS_IsNull (value);
+	return true;
+    }
+
+    JSValue vertexBuffer = property (ctx, value, "vertexBuffer");
+    shape.hasVertices = readTypedArray (ctx, vertexBuffer, JS_TYPED_ARRAY_FLOAT32, shape.vertices);
+    JS_FreeValue (ctx, vertexBuffer);
+
+    if (!shape.hasVertices && create) {
+	JS_ThrowSyntaxError (ctx, "Vertex buffer missing.");
+	return false;
+    }
+
+    JSValue indexBuffer = property (ctx, value, "indexBuffer");
+
+    if (readTypedArray (ctx, indexBuffer, JS_TYPED_ARRAY_UINT16, shape.indices16)) {
+	shape.hasIndices16 = true;
+    } else if (readTypedArray (ctx, indexBuffer, JS_TYPED_ARRAY_UINT32, shape.indices32)) {
+	shape.hasIndices32 = true;
+    } else {
+	shape.deleteIndices = JS_IsNull (indexBuffer);
+    }
+
+    JS_FreeValue (ctx, indexBuffer);
+
+    JSValue vertexFormat = property (ctx, value, "vertexFormat");
+
+    if (JS_IsArray (vertexFormat)) {
+	int64_t length = 0;
+	JS_GetLength (ctx, vertexFormat, &length);
+
+	for (int64_t i = 0; i < length; i++) {
+	    JSValue entry = JS_GetPropertyInt64 (ctx, vertexFormat, i);
+
+	    if (!JS_IsString (entry)) {
+		JS_FreeValue (ctx, entry);
+		break;
+	    }
+
+	    const char* name = JS_ToCString (ctx, entry);
+
+	    if (const auto format = formats.find (name != nullptr ? name : ""); format != formats.end ()) {
+		shape.format |= format->second;
+	    }
+
+	    JS_FreeCString (ctx, name);
+	    JS_FreeValue (ctx, entry);
+	}
+    }
+
+    JS_FreeValue (ctx, vertexFormat);
+
+    if (create && shape.format == 0) {
+	JS_ThrowSyntaxError (ctx, "Vertex format missing.");
+	return false;
+    }
+
+    JSValue material = property (ctx, value, "material");
+
+    if (JS_IsString (material)) {
+	const char* path = JS_ToCString (ctx, material);
+	// written into a 256 byte buffer
+	shape.material = std::string (path != nullptr ? path : "").substr (0, 255);
+	JS_FreeCString (ctx, path);
+    } else if (create) {
+	JS_FreeValue (ctx, material);
+	JS_ThrowSyntaxError (ctx, "Material missing.");
+	return false;
+    }
+
+    JS_FreeValue (ctx, material);
+
+    for (const auto& [name, target] : { std::pair<const char*, bool*> { "isVertexBufferDynamic", &shape.vertexDynamic },
+					std::pair<const char*, bool*> { "isIndexBufferDynamic", &shape.indexDynamic } }) {
+	JSValue flag = property (ctx, value, name);
+
+	if (JS_IsBool (flag)) {
+	    *target = JS_ToBool (ctx, flag);
+	}
+
+	JS_FreeValue (ctx, flag);
+    }
+
+    return true;
+}
+
+std::optional<glm::vec3> readVec3 (JSContext* ctx, JSValueConst object, const char* name) {
+    JSValue value = property (ctx, object, name);
+    std::optional<glm::vec3> result;
+
+    if (JS_IsObject (value)) {
+	glm::vec3 vector (0.0f);
+
+	for (int axis = 0; axis < 3; axis++) {
+	    JSValue component = property (ctx, value, std::array { "x", "y", "z" }[axis]);
+	    double number = 0.0;
+
+	    JS_ToFloat64 (ctx, &number, component);
+	    vector[axis] = static_cast<float> (number);
+	    JS_FreeValue (ctx, component);
+	}
+
+	result = vector;
+    }
+
+    JS_FreeValue (ctx, value);
+    return result;
+}
+
+bool parseConfig (JSContext* ctx, JSValueConst value, bool create, ModelData::Config& config) {
+    JSValue shapes = property (ctx, value, "shapes");
+    bool ok = true;
+
+    // an object without a shapes array is a single shape
+    if (JS_IsArray (shapes)) {
+	int64_t length = 0;
+	JS_GetLength (ctx, shapes, &length);
+
+	for (int64_t i = 0; i < length && ok; i++) {
+	    JSValue entry = JS_GetPropertyInt64 (ctx, shapes, i);
+	    ok = parseShape (ctx, entry, create, config.shapes.emplace_back ());
+	    JS_FreeValue (ctx, entry);
+	}
+    } else {
+	ok = parseShape (ctx, value, create, config.shapes.emplace_back ());
+    }
+
+    JS_FreeValue (ctx, shapes);
+
+    if (!ok) {
+	return false;
+    }
+
+    const auto boundsMin = readVec3 (ctx, value, "boundingBoxMins");
+    const auto boundsMax = readVec3 (ctx, value, "boundingBoxMaxs");
+
+    if (boundsMin.has_value () && boundsMax.has_value ()) {
+	config.boundsMin = boundsMin;
+	config.boundsMax = boundsMax;
+    }
+
+    if (config.shapes.empty ()) {
+	JS_ThrowSyntaxError (ctx, "Shapes missing.");
+	return false;
+    }
+
+    return true;
+}
+
+JSValue throwError (JSContext* ctx, ModelData::Error error) {
+    return JS_ThrowSyntaxError (ctx, "%s", ModelData::errorMessage (error));
+}
+
+JSValue applyOrReplace (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv, int magic) {
+    JSClassID classId = 0;
+    auto* handle = static_cast<Handle*> (JS_GetAnyOpaque (this_val, &classId));
+
+    if (handle == nullptr || classId != handle->scene->getModelDataClassId () || argc < 1) {
+	return JS_UNDEFINED;
+    }
+
+    const bool replace = magic == 1;
+
+    if (replace && handle->scene->getEngine ().isRunningUpdate ()) {
+	return JS_ThrowSyntaxError (ctx, "IModelData.replace cannot be called in update.");
+    }
+
+    ModelData::Config config;
+
+    if (!parseConfig (ctx, argv[0], false, config)) {
+	return JS_EXCEPTION;
+    }
+
+    ModelData::Error error = ModelData::Error::None;
+    handle->scene->getScene ().applyModelData (handle->token, config, replace, error);
+
+    return error == ModelData::Error::None ? JS_UNDEFINED : throwError (ctx, error);
+}
+
+JSValue instantiate (JSContext* ctx, SceneObject& scene, uint32_t token) {
+    // prototype: baseclasses.js IModelData (constants, toConfigString returning __modelDataToken)
+    JSValue global = JS_GetGlobalObject (ctx);
+    JSValue constructor = JS_GetPropertyStr (ctx, global, "IModelData");
+    JSValue prototype = JS_IsObject (constructor) ? JS_GetPropertyStr (ctx, constructor, "prototype") : JS_NULL;
+    JSValue object = JS_NewObjectProtoClass (ctx, prototype, scene.getModelDataClassId ());
+
+    JS_FreeValue (ctx, prototype);
+    JS_FreeValue (ctx, constructor);
+    JS_FreeValue (ctx, global);
+
+    JS_SetOpaque (object, new Handle { &scene, token });
+    JS_DefinePropertyValueStr (
+	ctx, object, "applyData", JS_NewCFunctionMagic (ctx, applyOrReplace, "applyData", 1, JS_CFUNC_generic_magic, 0),
+	JS_PROP_C_W_E
+    );
+    JS_DefinePropertyValueStr (
+	ctx, object, "replaceData",
+	JS_NewCFunctionMagic (ctx, applyOrReplace, "replaceData", 1, JS_CFUNC_generic_magic, 1), JS_PROP_C_W_E
+    );
+    // ReadOnly | DontEnum | DontDelete
+    JS_DefinePropertyValueStr (ctx, object, "__modelDataToken", JS_NewUint32 (ctx, token), 0);
+
+    return object;
+}
+} // namespace ModelDataScript
+
+// scenescript64 sub_1816372D0: a string is a name (the first layer with it), falling back to strtol as an id, a
+// number is an index, a layer object is itself
+WallpaperEngine::Render::CObject* resolve_layer_object (JSContext* ctx, SceneObject& container, JSValueConst value) {
+    const auto layers = container.getScene ().getLayers ();
+
+    if (JS_IsString (value)) {
+	const char* text = JS_ToCString (ctx, value);
+
+	if (text == nullptr) {
+	    return nullptr;
+	}
+
+	ScopeGuard guard ([=] { JS_FreeCString (ctx, text); });
+
+	for (auto* layer : layers) {
+	    if (layer->getObject ().name == text) {
+		return layer;
+	    }
+	}
+
+	const long id = std::strtol (text, nullptr, 10);
+
+	for (auto* layer : layers) {
+	    if (layer->getId () == id) {
+		return layer;
+	    }
+	}
+
+	return nullptr;
+    }
+
+    if (JS_IsNumber (value)) {
+	int32_t index = 0;
+	JS_ToInt32 (ctx, &index, value);
+
+	return static_cast<uint32_t> (index) < layers.size () ? layers[static_cast<uint32_t> (index)] : nullptr;
+    }
+
+    if (auto* object = WallpaperEngine::Scripting::Adapters::ScriptableObjectAdapter::getObject (value);
+	object != nullptr) {
+	return object;
+    }
+
+    return nullptr;
+}
+
+// sub_181634980: the object's creation JSON without its id, parsed again. The global scope message really names
+// destroyLayer in WE
+JSValue get_initial_layer_config (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
+    auto* container = get_opaque (this_val);
+
+    if (container->getEngine ().isEvaluatingModuleBody ()) {
+	return JS_ThrowSyntaxError (ctx, "destroyLayer cannot be called from global scope.");
+    }
+
+    const auto* object = argc < 1 ? nullptr : resolve_layer_object (ctx, *container, argv[0]);
+
+    if (object == nullptr) {
+	return JS_NULL;
+    }
+
+    const std::string& config = object->getObject ().initialConfig;
+    JSValue parsed = JS_ParseJSON (ctx, config.c_str (), config.size (), "<config>");
+
+    if (JS_IsException (parsed)) {
+	JS_FreeValue (ctx, JS_GetException (ctx));
+	return JS_NULL;
+    }
+
+    return parsed;
+}
+
+// sub_181635540: the static scene camera as {eye, center, up, zoom}, a plain object with Vec3s
+JSValue get_camera_transforms (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
+    auto* container = get_opaque (this_val);
+
+    if (container->getEngine ().isEvaluatingModuleBody ()) {
+	return JS_ThrowSyntaxError (ctx, "getCameraTransforms cannot be called from global scope.");
+    }
+
+    const auto& camera = container->getScene ().getStaticCamera ();
+    const auto& adapters = container->getEngine ().getAdapters ();
+    const auto vector = [&adapters] (const glm::vec3& value) {
+	WallpaperEngine::Data::Model::DynamicValue dynamic (value);
+
+	return adapters.vec3->instantiate (dynamic);
+    };
+    JSValue result = JS_NewObject (ctx);
+
+    JS_SetPropertyStr (ctx, result, "eye", vector (camera.eye));
+    JS_SetPropertyStr (ctx, result, "center", vector (camera.center));
+    JS_SetPropertyStr (ctx, result, "up", vector (camera.up));
+    JS_SetPropertyStr (ctx, result, "zoom", JS_NewFloat64 (ctx, static_cast<double> (camera.zoom)));
+
+    return result;
+}
+
+// sub_1816359E0: sets whichever of eye, center, up (objects) and zoom (a number) are there, true when given an object
+JSValue set_camera_transforms (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
+    auto* container = get_opaque (this_val);
+
+    if (container->getEngine ().isEvaluatingModuleBody ()) {
+	return JS_ThrowSyntaxError (ctx, "setCameraTransforms cannot be called from global scope.");
+    }
+
+    if (argc < 1 || !JS_IsObject (argv[0])) {
+	return JS_FALSE;
+    }
+
+    auto& camera = container->getScene ().getStaticCamera ();
+
+    for (const auto& [name, target] : { std::pair<const char*, glm::vec3*> { "eye", &camera.eye },
+					std::pair<const char*, glm::vec3*> { "center", &camera.center },
+					std::pair<const char*, glm::vec3*> { "up", &camera.up } }) {
+	if (const auto value = ModelDataScript::readVec3 (ctx, argv[0], name); value.has_value ()) {
+	    *target = *value;
+	}
+    }
+
+    JSValue zoom = JS_GetPropertyStr (ctx, argv[0], "zoom");
+    double number = 0.0;
+
+    if (JS_IsNumber (zoom) && JS_ToFloat64 (ctx, &number, zoom) == 0) {
+	camera.zoom = static_cast<float> (number);
+    }
+
+    JS_FreeValue (ctx, zoom);
+    return JS_TRUE;
+}
+
+JSValue create_model_data (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
+    auto* container = get_opaque (this_val);
+
+    if (container->getEngine ().isEvaluatingModuleBody ()) {
+	return JS_ThrowSyntaxError (ctx, "createModelData cannot be called from global scope.");
+    }
+
+    // no configuration object gives null (sub_1816361F0 returns the isolate's null root)
+    if (argc < 1 || !JS_IsObject (argv[0])) {
+	return JS_NULL;
+    }
+
+    WallpaperEngine::Render::ModelData::Config config;
+
+    if (!ModelDataScript::parseConfig (ctx, argv[0], true, config)) {
+	return JS_EXCEPTION;
+    }
+
+    auto error = WallpaperEngine::Render::ModelData::Error::None;
+    const uint32_t token = container->getScene ().createModelData (config, error);
+
+    if (error != WallpaperEngine::Render::ModelData::Error::None) {
+	return ModelDataScript::throwError (ctx, error);
+    }
+
+    return ModelDataScript::instantiate (ctx, *container, token);
+}
+
+// takes the token as a number (V8 IsUint32 + Int32Value), anything else does nothing
+JSValue destroy_model_data (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
+    auto* container = get_opaque (this_val);
+
+    if (container->getEngine ().isEvaluatingModuleBody ()) {
+	return JS_ThrowSyntaxError (ctx, "destroyModelData cannot be called from global scope.");
+    }
+
+    double number = 0.0;
+
+    if (argc < 1 || !JS_IsNumber (argv[0]) || JS_ToFloat64 (ctx, &number, argv[0]) != 0 || number < 0.0
+	|| number > 4294967295.0 || number != std::floor (number)) {
+	return JS_UNDEFINED;
+    }
+
+    container->getScene ().destroyModelData (static_cast<uint32_t> (static_cast<int64_t> (number)));
+    return JS_UNDEFINED;
+}
+
 JSValue create_layer (JSContext* ctx, JSValueConst this_val, int argc, JSValueConst* argv) {
     if (argc != 1) {
 	return JS_UNDEFINED;
@@ -343,7 +776,17 @@ JSValue create_layer (JSContext* ctx, JSValueConst this_val, int argc, JSValueCo
     auto* container = get_opaque (this_val);
 
     if (JS_IsObject (argv[0])) {
-	const auto config = stringify_layer_config (ctx, argv[0]);
+	JSValue configuration = JS_DupValue (ctx, argv[0]);
+
+	// an IModelData on its own is a model layer of it (scenescript64 sub_181633290 checks the handle's tag)
+	if (JS_GetOpaque (argv[0], container->getModelDataClassId ()) != nullptr) {
+	    JS_FreeValue (ctx, configuration);
+	    configuration = JS_NewObject (ctx);
+	    JS_SetPropertyStr (ctx, configuration, "model", JS_DupValue (ctx, argv[0]));
+	}
+
+	const auto config = stringify_layer_config (ctx, configuration);
+	JS_FreeValue (ctx, configuration);
 
 	if (!config.has_value ()) {
 	    return JS_UNDEFINED;
@@ -464,6 +907,16 @@ SceneObject::SceneObject (ScriptEngine& engine, Render::Wallpapers::CScene& scen
     JS_NewClass (this->m_engine.getRuntime (), this->m_classId, &this->m_definition);
     this->m_instance = JS_NewObjectClass (this->m_engine.getContext (), this->m_classId);
 
+    this->m_modelDataDefinition = {
+	.class_name = "IModelData",
+	.finalizer = [] (JSRuntime*, JSValueConst value) {
+	    JSClassID classId = 0;
+	    delete static_cast<ModelDataScript::Handle*> (JS_GetAnyOpaque (value, &classId));
+	},
+    };
+    JS_NewClassID (this->m_engine.getRuntime (), &this->m_modelDataClassId);
+    JS_NewClass (this->m_engine.getRuntime (), this->m_modelDataClassId, &this->m_modelDataDefinition);
+
     JS_DupValue (this->m_engine.getContext (), this->m_instance);
 
     JS_SetOpaque (this->m_instance, this);
@@ -614,6 +1067,27 @@ SceneObject::SceneObject (ScriptEngine& engine, Render::Wallpapers::CScene& scen
 	this->m_engine.getContext (), this->m_instance, "sortLayer",
 	JS_NewCFunction (this->m_engine.getContext (), sort_layer, "sortLayer", 2), JS_PROP_ENUMERABLE
     );
+    JS_DefinePropertyValueStr (
+	this->m_engine.getContext (), this->m_instance, "getInitialLayerConfig",
+	JS_NewCFunction (this->m_engine.getContext (), get_initial_layer_config, "getInitialLayerConfig", 1),
+	JS_PROP_ENUMERABLE
+    );
+    JS_DefinePropertyValueStr (
+	this->m_engine.getContext (), this->m_instance, "getCameraTransforms",
+	JS_NewCFunction (this->m_engine.getContext (), get_camera_transforms, "getCameraTransforms", 0), JS_PROP_ENUMERABLE
+    );
+    JS_DefinePropertyValueStr (
+	this->m_engine.getContext (), this->m_instance, "setCameraTransforms",
+	JS_NewCFunction (this->m_engine.getContext (), set_camera_transforms, "setCameraTransforms", 1), JS_PROP_ENUMERABLE
+    );
+    JS_DefinePropertyValueStr (
+	this->m_engine.getContext (), this->m_instance, "createModelData",
+	JS_NewCFunction (this->m_engine.getContext (), create_model_data, "createModelData", 1), JS_PROP_ENUMERABLE
+    );
+    JS_DefinePropertyValueStr (
+	this->m_engine.getContext (), this->m_instance, "destroyModelData",
+	JS_NewCFunction (this->m_engine.getContext (), destroy_model_data, "destroyModelData", 1), JS_PROP_ENUMERABLE
+    );
 }
 
 SceneObject::~SceneObject () { JS_FreeValue (this->m_engine.getContext (), this->m_instance); }

+ 5 - 0
src/WallpaperEngine/Scripting/SceneObject.h

@@ -15,6 +15,8 @@ public:
     const Render::Wallpapers::CScene& getScene () const { return m_scene; }
     JSValue getInstance () const { return m_instance; }
     ScriptEngine& getEngine () const { return m_engine; }
+    /** IModelData handles (thisScene.createModelData) are objects of this class */
+    JSClassID getModelDataClassId () const { return m_modelDataClassId; }
 
 private:
     Render::Wallpapers::CScene& m_scene;
@@ -23,5 +25,8 @@ private:
     JSClassID m_classId;
     JSClassDef m_definition;
     JSValue m_instance;
+    // JS_NewClassID only hands out an id while this is 0
+    JSClassID m_modelDataClassId = 0;
+    JSClassDef m_modelDataDefinition {};
 };
 }

+ 91 - 1
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -13,6 +13,7 @@
 #include "WallpaperEngine/Desktop/UserShortcut.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/CObject.h"
+#include "WallpaperEngine/Render/Objects/CImage.h"
 #include "WallpaperEngine/Render/Objects/CSound.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 #include "WallpaperEngine/Scripting/Builtins.generated.h"
@@ -314,7 +315,26 @@ JSValue ScriptEngine::propertyToJs (DynamicValue& value, std::string_view name)
     return this->dynamicToJs (degrees);
 }
 
+// scenescript64 (sub_181620E10, used for property scripts and layer setters) converts by the property's type and
+// drops a value of the wrong kind: bool properties only take IsBoolean, int/float ones only IsNumber.
+// 3509578940's battery fill returns a number from its visible script and stays visible in WE
+static bool matchesPropertyType (JSValue val, const DynamicValue& target) {
+    switch (target.getType ()) {
+	case DynamicValue::Boolean:
+	    return JS_IsBool (val);
+	case DynamicValue::Int:
+	case DynamicValue::Float:
+	    return JS_IsNumber (val);
+	default:
+	    return true;
+    }
+}
+
 void ScriptEngine::assignPropertyJsValue (JSValue val, DynamicValue& target, std::string_view name) const {
+    if (!matchesPropertyType (val, target)) {
+	return;
+    }
+
     // scenescript64 (sub_181620E10, string descriptors) stores ToString of whatever the script assigns, only
     // undefined/null are ignored: 3577513994 sets a text layer to getDate()'s number
     if (target.getType () == DynamicValue::String && !JS_IsString (val) && !JS_IsUndefined (val) && !JS_IsNull (val)
@@ -449,6 +469,10 @@ ScriptEngine::~ScriptEngine () {
 	JS_FreeValue (this->m_context, entry.callback);
     }
 
+    for (const auto& entry : this->m_animationLayerEndedCallbacks) {
+	JS_FreeValue (this->m_context, entry.callback);
+    }
+
     if (this->m_adapters.object) {
 	this->m_adapters.object->clear ();
     }
@@ -947,7 +971,10 @@ void ScriptEngine::queueScript (
     // await this resolves/rejects synchronously, so its state can be checked right away.
     // JS_IsException() on it is always false even if the module threw, since that exception gets
     // caught by the module machinery and stored as the promise's rejection reason instead.
+    const bool wasEvaluatingModuleBody = this->m_evaluatingModuleBody;
+    this->m_evaluatingModuleBody = true;
     JSValue evalResult = JS_EvalFunction (this->m_context, compiledModule);
+    this->m_evaluatingModuleBody = wasEvaluatingModuleBody;
 
     // 3378399626's weather widget stores its offsets in shared at the top level from the defaults and only
     // picks the user's location up in applyUserProperties
@@ -1185,7 +1212,8 @@ void ScriptEngine::bindThisLayer (ScriptableObject& object, LoadedModule* module
     }
 
     if (JS_IsUndefined (module->thisObject)) {
-	module->thisObject = this->makeThisObject (module->value, module->propertyName);
+	module->thisObject = module->thisObjectFactory ? module->thisObjectFactory (*this)
+						       : this->makeThisObject (module->value, module->propertyName);
     }
 
     JS_SetPropertyStr (
@@ -1357,6 +1385,65 @@ void ScriptEngine::addVideoEndedCallback (VideoPlayback::MPV::GLPlayer* player,
     this->m_videoEndedCallbacks.push_back ({ player, JS_DupValue (this->m_context, callback) });
 }
 
+void ScriptEngine::addAnimationLayerEndedCallback (const ScriptableObject& owner, size_t serial, JSValueConst callback) {
+    if (!JS_IsFunction (this->m_context, callback)) {
+	return;
+    }
+
+    this->m_animationLayerEndedCallbacks.push_back (
+	{ &owner, serial, JS_DupValue (this->m_context, callback), this->m_runningModule }
+    );
+}
+
+void ScriptEngine::dispatchAnimationLayerEnded (const ScriptableObject& owner, size_t serial) {
+    // index based, a callback is free to register more callbacks
+    for (size_t index = 0; index < this->m_animationLayerEndedCallbacks.size (); index++) {
+	const auto& entry = this->m_animationLayerEndedCallbacks[index];
+
+	if (entry.owner != &owner || entry.serial != serial) {
+	    continue;
+	}
+
+	// the registering module may have been retired since, only a live one gets rebound
+	LoadedModule* module = nullptr;
+	for (auto& candidate : this->m_scriptModules | std::views::values) {
+	    if (&candidate == entry.module && !candidate.dropped && candidate.object != nullptr) {
+		module = &candidate;
+		break;
+	    }
+	}
+
+	LoadedModule* previous = this->m_runningModule;
+	if (module != nullptr) {
+	    this->m_runningModule = module;
+	    this->bindThisLayer (*module->object, module);
+	}
+
+	JSValue callback = JS_DupValue (this->m_context, entry.callback);
+	JSValue result = JS_Call (this->m_context, callback, JS_UNDEFINED, 0, nullptr);
+
+	if (JS_IsException (result)) {
+	    logJSException (this->m_context, "animation layer ended callback");
+	}
+
+	JS_FreeValue (this->m_context, result);
+	JS_FreeValue (this->m_context, callback);
+	this->m_runningModule = previous;
+    }
+}
+
+void ScriptEngine::setThisObjectFactory (const std::string& key, std::function<JSValue (ScriptEngine&)> factory) {
+    const auto it = this->m_scriptModules.find (key);
+
+    if (it == this->m_scriptModules.end ()) {
+	return;
+    }
+
+    it->second.thisObjectFactory = std::move (factory);
+    JS_FreeValue (this->m_context, it->second.thisObject);
+    it->second.thisObject = JS_UNDEFINED;
+}
+
 void ScriptEngine::tick () {
     this->m_engineObject->tick ();
 
@@ -1434,7 +1521,10 @@ void ScriptEngine::tick () {
 	}
 
 	JSValue args[] = { this->propertyToJs (module.value, module.propertyName) };
+	// scenescript64 keeps the index of the export being called (+1580, 1 = update) for IModelData.replaceData
+	this->m_runningUpdate = true;
 	JSValue result = this->call (module.module, 1, args, "update");
+	this->m_runningUpdate = false;
 	ScopeGuard guard ([result, args, this] () {
 	    JS_FreeValue (this->m_context, result);
 	    JS_FreeValue (this->m_context, args[0]);

+ 29 - 0
src/WallpaperEngine/Scripting/ScriptEngine.h

@@ -8,6 +8,7 @@
 #include "SceneObject.h"
 
 #include <chrono>
+#include <functional>
 #include <future>
 #include <map>
 #include <memory>
@@ -34,6 +35,10 @@ namespace WallpaperEngine::Render::Wallpapers {
 class CScene;
 }
 
+namespace WallpaperEngine::Render::Objects {
+class CImage;
+}
+
 namespace WallpaperEngine::VideoPlayback::MPV {
 class GLPlayer;
 }
@@ -42,6 +47,7 @@ namespace WallpaperEngine::Scripting {
 void logJSException (JSContext* ctx, const char* context, const std::optional<std::string>& source = std::nullopt);
 
 class ScriptPropertiesObject;
+class ScriptableObject;
 namespace Adapters {
     class ScriptableObjectAdapter;
 }
@@ -64,6 +70,8 @@ public:
 	bool initialized = false;
 	// cached `thisObject` handle, see makeThisObject()
 	JSValue thisObject = JS_UNDEFINED;
+	// builds thisObject instead of makeThisObject() (animation layer scripts get the IAnimationLayer)
+	std::function<JSValue (ScriptEngine&)> thisObjectFactory;
 	// name of the property the script is attached to ("origin", an effect constant, ...)
 	std::string propertyName;
 	// -1 until checked, then whether the module exports any cursor* handler
@@ -89,6 +97,10 @@ public:
     JSContext* getContext () const { return m_context; }
     JSValue getGlobalThis () const { return m_globalThis; }
     LoadedModule* getRunningModule () const { return m_runningModule; }
+    // true while a module's top level code runs, WE calls that the global scope
+    bool isEvaluatingModuleBody () const { return m_evaluatingModuleBody; }
+    // true while a module's update() runs
+    bool isRunningUpdate () const { return m_runningUpdate; }
     JSValue dynamicToJs (DynamicValue& value) const;
     /** Same as dynamicToJs() but colour properties come out as Vec3 like they do in real scripts, not Vec4 */
     JSValue userPropertyToJs (Property& property) const;
@@ -190,6 +202,12 @@ public:
     /** Calls callback (once per playthrough) when player reaches the end of a non-looping video, for
      * IVideoTexture.addEndedCallback() */
     void addVideoEndedCallback (VideoPlayback::MPV::GLPlayer* player, JSValueConst callback);
+    /** Calls callback every time the puppet animation layer reaches its end, for IAnimationLayer.addEndedCallback() */
+    void addAnimationLayerEndedCallback (const ScriptableObject& owner, size_t serial, JSValueConst callback);
+    /** Runs the ended callbacks of that animation layer, from the puppet update like WE (sub_1401FDF90) */
+    void dispatchAnimationLayerEnded (const ScriptableObject& owner, size_t serial);
+    /** The script queued under key gets thisObject from factory instead of the property handle */
+    void setThisObjectFactory (const std::string& key, std::function<JSValue (ScriptEngine&)> factory);
 
     AnimationSystem& getAnimations () { return m_animations; }
     /** Whether a script module is currently running for this property value */
@@ -230,6 +248,8 @@ private:
     std::vector<std::string> m_retiredScriptKeys = {};
 
     LoadedModule* m_runningModule = nullptr;
+    bool m_evaluatingModuleBody = false;
+    bool m_runningUpdate = false;
 
     struct VideoEndedCallback {
 	VideoPlayback::MPV::GLPlayer* player;
@@ -239,6 +259,15 @@ private:
     };
     std::vector<VideoEndedCallback> m_videoEndedCallbacks = {};
 
+    struct AnimationLayerEndedCallback {
+	const ScriptableObject* owner;
+	size_t serial;
+	JSValue callback;
+	// the module that registered it, callbacks run with its thisLayer/thisObject
+	const LoadedModule* module;
+    };
+    std::vector<AnimationLayerEndedCallback> m_animationLayerEndedCallbacks = {};
+
     ScriptLayerHandle m_nextLayerId = 1;
     bool m_layerRegistryReady = false;
     std::map<ScriptLayerHandle, bool> m_layerInitialized;

+ 68 - 0
src/WallpaperEngine/Testing/Cases/ScalingModes.cpp

@@ -160,3 +160,71 @@ TEST_CASE ("Changing offset live is picked up even if the viewport hasn't change
 
     CHECK (state.hasChanged ({ 0, 0, 500, 500 }, false, 1000, 1000));
 }
+
+TEST_CASE ("parseScalingMode knows WE's free alignment") {
+    CHECK (WallpaperState::parseScalingMode ("free") == WallpaperState::TextureUVsScaling::FreeUVs);
+}
+
+TEST_CASE ("Alignment position 0 keeps the right edge when fill crops horizontally") {
+    WallpaperState state (WallpaperState::TextureUVsScaling::ZoomFillUVs, 0);
+
+    state.setAlignment ({ .position = 0.0f });
+    state.updateState ({ 0, 0, 1000, 1000 }, false, 2000, 1000);
+
+    const auto [ustart, uend, vstart, vend] = state.getTextureUVs ();
+
+    CHECK (ustart == Catch::Approx (0.5f));
+    CHECK (uend == Catch::Approx (1.0f));
+    CHECK (vstart == Catch::Approx (1.0f));
+    CHECK (vend == Catch::Approx (0.0f));
+}
+
+TEST_CASE ("Alignment position 0 puts a fit wallpaper at the top") {
+    WallpaperState state (WallpaperState::TextureUVsScaling::ZoomFitUVs, 0);
+
+    state.setAlignment ({ .position = 0.0f });
+    state.updateState ({ 0, 0, 1000, 2000 }, false, 1000, 1000);
+
+    const auto [ustart, uend, vstart, vend] = state.getTextureUVs ();
+
+    // the canvas is laid out y down: the bar below the scene sits past its v start
+    CHECK (ustart == Catch::Approx (0.0f));
+    CHECK (uend == Catch::Approx (1.0f));
+    CHECK (vstart == Catch::Approx (2.0f));
+    CHECK (vend == Catch::Approx (0.0f));
+}
+
+TEST_CASE ("Center alignment x/y 0 shows the top left corner") {
+    WallpaperState state (WallpaperState::TextureUVsScaling::CenterUVs, 0);
+
+    state.setAlignment ({ .x = 0.0f, .y = 0.0f });
+    state.updateState ({ 0, 0, 500, 500 }, false, 1000, 1000);
+
+    const auto [ustart, uend, vstart, vend] = state.getTextureUVs ();
+
+    CHECK (ustart == Catch::Approx (0.0f));
+    CHECK (uend == Catch::Approx (0.5f));
+    CHECK (vstart == Catch::Approx (0.5f));
+    CHECK (vend == Catch::Approx (0.0f));
+}
+
+TEST_CASE ("Free alignment zooms by (2 - zoom)^4 around the aligned point") {
+    WallpaperState state (WallpaperState::TextureUVsScaling::FreeUVs, 0);
+
+    // zoom 1 is the native size, like center
+    state.updateState ({ 0, 0, 500, 500 }, false, 1000, 1000);
+    CHECK (state.getTextureUVs ().ustart == Catch::Approx (0.25f));
+    CHECK (state.getTextureUVs ().uend == Catch::Approx (0.75f));
+
+    // zoom 0 shows 16 times the output's size
+    state.setAlignment ({ .zoom = 0.0f });
+    state.updateState ({ 0, 0, 500, 500 }, false, 1000, 1000);
+    CHECK (state.getTextureUVs ().ustart == Catch::Approx (-3.5f));
+    CHECK (state.getTextureUVs ().uend == Catch::Approx (4.5f));
+
+    // zoom 2 is clamped to 1% of it
+    state.setAlignment ({ .zoom = 2.0f });
+    state.updateState ({ 0, 0, 500, 500 }, false, 1000, 1000);
+    CHECK (state.getTextureUVs ().ustart == Catch::Approx (0.4975f));
+    CHECK (state.getTextureUVs ().uend == Catch::Approx (0.5025f));
+}

+ 2 - 0
tools/headless_render.sh

@@ -35,6 +35,8 @@ if [ "$#" -lt 2 ]; then
 fi
 
 BINARY="$1"; shift
+# the sandbox shares the desktop's user, a crashing test render would land in its crash handler (DrKonqi)
+ulimit -c 0
 OUTPUT="$1"; shift
 
 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

BIN
tools/regression/__pycache__/regress.cpython-313.pyc


+ 4 - 1
tools/regression/regress.py

@@ -33,6 +33,7 @@ import json
 import os
 import queue
 import re
+import resource
 import shutil
 import signal
 import subprocess
@@ -246,7 +247,9 @@ def render_once (args, env, folder, shot, log_path, properties):
 
     with open (log_path, 'wb') as log:
         process = subprocess.Popen (
-            command, env = env, stdin = subprocess.DEVNULL, stdout = log, stderr = subprocess.STDOUT, start_new_session = True
+            command, env = env, stdin = subprocess.DEVNULL, stdout = log, stderr = subprocess.STDOUT, start_new_session = True,
+            # no core files: the sandbox shares the desktop's user and its crash handler picks them up
+            preexec_fn = lambda: resource.setrlimit (resource.RLIMIT_CORE, (0, 0))
         )
         last_size = -1
 

BIN
tools/wecompare/__pycache__/render_we.cpython-313.pyc


+ 16 - 4
tools/wecompare/render_ours.sh

@@ -1,5 +1,5 @@
 #!/bin/bash
-# usage: render_ours.sh <outdir> [ids...]  (default: every item in the scan.py database)
+# usage: render_ours.sh <outdir> [ids...]  (default: every scene/preset item in the scan.py database)
 # headless GPU render at WE's window size (1920x1058), frame 600 @30fps -> <outdir>/<id>.png + .log
 # LWE=<dir with linux-wallpaperengine + its lib .so> picks the build (default: this checkout's build/output)
 # audio goes to dead sockets: the engine captures from the desktop's audio server even with --silent
@@ -11,10 +11,22 @@ LWE=${LWE:-$SRC/build/output}
 OUT=$1; shift; mkdir -p "$OUT"
 # a copy under another name so we_manager's shutdown pkill doesn't hit it
 cp -f $LWE/linux-wallpaperengine $LWE/lwe-regress-bin
-ids=("$@"); [ ${#ids[@]} -eq 0 ] && ids=($(python3 -c "import json;print(' '.join(sorted(json.load(open('$LIB/features.json')))))"))
-for id in "${ids[@]}"; do
+# web and video wallpapers can't be compared (see README) and only add CEF/mpv crashes, ALL_TYPES=1 keeps them
+ids=("$@"); [ ${#ids[@]} -eq 0 ] && ids=($(python3 -c "
+import json, os
+items = json.load(open('$LIB/features.json'))
+keep = os.environ.get('ALL_TYPES') == '1'
+print(' '.join(sorted(i for i, v in items.items() if keep or v['info'].get('type') not in ('web', 'video'))))"))
+# renders are paced at 30 fps (600 frames = 20 s of wall clock each), so they run JOBS at a time (default 6).
+# headless_render.sh gives every render its own runtime dir; its D-Bus shim is built once up front
+[ -f /tmp/dbus_noop_shim.so ] || gcc -shared -fPIC -o /tmp/dbus_noop_shim.so $SRC/tools/dbus_noop_shim.c -ldl
+render_one() {
+  local id=$1
   PULSE_SERVER=unix:/nonexistent-pulse PIPEWIRE_REMOTE=/nonexistent-pipewire \
   HEADLESS_RENDER_SIZE=1920x1058 HEADLESS_RENDER_DELAY=${DELAY:-600} HEADLESS_RENDER_TIMEOUT=90 LD_LIBRARY_PATH=$LWE \
     $SRC/tools/headless_render.sh $LWE/lwe-regress-bin "$OUT/$id.png" --assets-dir $A --fps 30 --silent $W/$id > "$OUT/$id.log" 2>&1 < /dev/null
   echo "ours $id rc=$? $( [ -f "$OUT/$id.png" ] && echo ok || echo NO-PNG)"
-done
+}
+export -f render_one
+export SRC LWE OUT A W DELAY
+printf '%s\n' "${ids[@]}" | xargs -P "${JOBS:-6}" -I{} bash -c 'render_one {}'

+ 4 - 0
tools/wecompare/render_we.py

@@ -12,6 +12,7 @@ Wine (it only brings the UI window back), hence one instance per item.
 Audio is pointed at dead sockets, see README.md. Setup of the Wine prefix: README.md.
 """
 import os, subprocess, sys, time
+import resource
 import numpy as np
 import mss
 from PIL import Image
@@ -38,6 +39,9 @@ we_proc = None
 log = None
 
 
+# no core files: the sandbox shares the desktop's user and its crash handler picks them up
+resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
+
 def winpath(p):
     return 'Z:' + p.replace('/', '\\')
 

+ 35 - 0
tools/wecompare/wine/rdscripts/rd_depthpass.py

@@ -0,0 +1,35 @@
+import os, traceback, renderdoc as rd
+# depth-only draws (shadow passes): rasterizer, depth state and viewports; env CAP, OUT
+out=open(os.environ['OUT'],'w')
+cap=rd.OpenCaptureFile(); cap.OpenFile(os.environ['CAP'],'',None)
+st,ctl=cap.OpenCapture(rd.ReplayOptions(),None)
+texs={t.resourceId:t for t in ctl.GetTextures()}
+draws=[]
+def walk(a):
+    for c in a:
+        if c.flags & rd.ActionFlags.Drawcall: draws.append(c)
+        walk(c.children)
+walk(ctl.GetRootActions())
+def fields(o):
+    return {k: str(getattr(o, k)) for k in dir(o) if not k.startswith('_') and not callable(getattr(o, k))}
+try:
+    n = 0
+    for c in draws:
+        ctl.SetFrameEvent(c.eventId, True)
+        vk = ctl.GetVulkanPipelineState()
+        p = ctl.GetPipelineState()
+        depth = p.GetDepthTarget()
+        outs = [o for o in p.GetOutputTargets() if o.resource != rd.ResourceId.Null()]
+        if depth.resource == rd.ResourceId.Null() or outs:
+            continue
+        t = texs.get(depth.resource)
+        out.write('eid %d idx %d inst %d depth %s %dx%d fmt %s\n' % (c.eventId, c.numIndices, c.numInstances, depth.resource, t.width, t.height, t.format.Name()))
+        out.write('  rast %s\n' % fields(vk.rasterizer))
+        out.write('  ds %s\n' % fields(vk.depthStencil))
+        out.write('  vps %s\n' % [(v.vp.x, v.vp.y, v.vp.width, v.vp.height) for v in vk.viewportScissor.viewportScissors][:6])
+        n += 1
+        if n > 8:
+            break
+except Exception:
+    out.write(traceback.format_exc())
+ctl.Shutdown(); cap.Shutdown(); out.close(); os._exit(0)

+ 10 - 0
tools/wecompare/wine/rdscripts/rd_texdata.py

@@ -0,0 +1,10 @@
+import os, renderdoc as rd
+# raw texture data of resource RES at event EID into OUT (a D32 atlas is little endian float32 rows); env CAP, EID, RES, OUT
+cap=rd.OpenCaptureFile(); cap.OpenFile(os.environ['CAP'],'',None)
+st,ctl=cap.OpenCapture(rd.ReplayOptions(),None)
+ctl.SetFrameEvent(int(os.environ['EID']),True)
+rid=[t for t in ctl.GetTextures() if int(t.resourceId)==int(os.environ['RES'])][0]
+data=ctl.GetTextureData(rid.resourceId, rd.Subresource(0,0,0))
+open(os.environ['OUT'],'wb').write(bytes(data))
+open(os.environ['OUT']+'.txt','w').write('%d %d %s %d\n'%(rid.width,rid.height,rid.format.Name(),len(data)))
+ctl.Shutdown(); cap.Shutdown(); os._exit(0)

+ 1 - 0
tools/wecompare/wine/we_capture.sh

@@ -2,6 +2,7 @@
 # usage: we_capture.sh <scene dir or scene.json/scene.pkg> [seconds before capture]
 # RenderDoc capture of one frame of real WE 2.8.42 (DXVK -> Vulkan on the GPU, isolated display :98).
 # Prints the .rdc path; inspect it with tools/rdc_dump.py using DISPLAY=:98 (Xvfb has no DRI3, replay output asserts there)
+ulimit -c 0
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1
 pgrep -f "Xvfb :97" >/dev/null || { Xvfb :97 -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 & sleep 1; }

+ 1 - 0
tools/wecompare/wine/we_cursor.sh

@@ -1,6 +1,7 @@
 #!/bin/bash
 # usage: we_cursor.sh <scene dir or scene.json/scene.pkg> <out dir> "x,y x,y ..." [settle seconds]
 # like we_full.sh, but warps the pointer (screen px on :98) before each grab: f<i>_<x>_<y>.png
+ulimit -c 0
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=:98
 bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1

+ 1 - 0
tools/wecompare/wine/we_full.sh

@@ -2,6 +2,7 @@
 # usage: we_full.sh <scene dir or scene.json/scene.pkg> <out dir> [count] [interval seconds]
 # runs on the GPU display :98 (DXVK); WE_DISPLAY=:97 WE_WINED3D=1 is the old Xvfb + wined3d (llvmpipe) path
 # full window captures (1920x1058 at +4+30 on :97) of real WE 2.8.42 under Wine, see README.md
+ulimit -c 0
 S=${WE_LIVE_DIR:-$HOME/.local/share/we_live}
 D=${WE_DISPLAY:-:98}
 [ "$D" = ":98" ] && { bash "$(dirname "$0")/we_display.sh" >/dev/null || exit 1; }

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است