Sfoglia il codice sorgente

added support for ik chains

added support for unpopular MDL and TEX

fixed some 3d scenes

added support for ssaa
UwU 1 mese fa
parent
commit
a3637ca8c7
41 ha cambiato i file con 3130 aggiunte e 205 eliminazioni
  1. 2 0
      CMakeLists.txt
  2. 7 1
      CMakeModules/FindV8.cmake
  3. 13 31
      src/WallpaperEngine/Application/ApplicationContext.cpp
  4. 2 0
      src/WallpaperEngine/Application/ApplicationContext.h
  5. 29 6
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  6. 0 1
      src/WallpaperEngine/Data/Assets/Texture.h
  7. 8 0
      src/WallpaperEngine/Data/Model/Wallpaper.h
  8. 12 32
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  9. 7 0
      src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp
  10. 57 4
      src/WallpaperEngine/Render/CWallpaper.cpp
  11. 9 2
      src/WallpaperEngine/Render/CWallpaper.h
  12. 1 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  13. 779 21
      src/WallpaperEngine/Render/Objects/CImage.cpp
  14. 53 0
      src/WallpaperEngine/Render/Objects/CImage.h
  15. 38 1
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  16. 4 0
      src/WallpaperEngine/Render/Objects/CMesh.h
  17. 8 6
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  18. 86 23
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  19. 7 0
      src/WallpaperEngine/Render/Objects/Effects/CPass.h
  20. 910 0
      src/WallpaperEngine/Render/Objects/PuppetIK.cpp
  21. 129 0
      src/WallpaperEngine/Render/Objects/PuppetIK.h
  22. 44 16
      src/WallpaperEngine/Render/Objects/PuppetPhysics.cpp
  23. 6 1
      src/WallpaperEngine/Render/Objects/PuppetPhysics.h
  24. 479 48
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  25. 62 0
      src/WallpaperEngine/Render/Objects/PuppetRig.h
  26. 7 0
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  27. 19 3
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  28. 3 0
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  29. 33 0
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp
  30. 3 0
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h
  31. 4 0
      src/WallpaperEngine/Scripting/AnimationSystem.cpp
  32. 93 0
      src/WallpaperEngine/Scripting/JS.cpp
  33. 5 0
      src/WallpaperEngine/Scripting/JS.h
  34. 96 0
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  35. 7 0
      src/WallpaperEngine/Scripting/ScriptEngine.h
  36. 17 6
      src/WallpaperEngine/WebBrowser/CEF/WPSchemeHandler.cpp
  37. 2 2
      src/WallpaperEngine/WebBrowser/CEF/WPSchemeHandler.h
  38. 3 0
      src/main.cpp
  39. BIN
      tools/__pycache__/mdl_scan.cpython-313.pyc
  40. 85 0
      tools/mdl_chains.py
  41. 1 1
      tools/wecompare/render_ours.sh

+ 2 - 0
CMakeLists.txt

@@ -497,6 +497,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Objects/CImage.cpp
     src/WallpaperEngine/Render/Objects/PuppetClipping.h
     src/WallpaperEngine/Render/Objects/PuppetClipping.cpp
+    src/WallpaperEngine/Render/Objects/PuppetIK.h
+    src/WallpaperEngine/Render/Objects/PuppetIK.cpp
     src/WallpaperEngine/Render/Objects/PuppetPhysics.h
     src/WallpaperEngine/Render/Objects/PuppetPhysics.cpp
     src/WallpaperEngine/Render/Objects/PuppetRootMotion.h

+ 7 - 1
CMakeModules/FindV8.cmake

@@ -6,7 +6,7 @@
 # V8_INCLUDE_DIR
 # V8_LIBRARY
 # V8_VERSION
-# V8_DEFINITIONS - defines the library was built with that change V8's object layout, embedders must use the same
+# V8_DEFINITIONS - defines that change V8's object layout, plus V8_ICU_DEFAULT_DATA_DIR when node has one
 # V8::V8 - imported target carrying all of the above
 
 find_package(PkgConfig QUIET)
@@ -66,6 +66,12 @@ if(V8_INCLUDE_DIR AND EXISTS "${V8_INCLUDE_DIR}/v8-version.h")
   _v8_flag(v8_enable_pointer_compression_shared_cage V8_COMPRESS_POINTERS_IN_SHARED_CAGE)
   _v8_flag(v8_enable_31bit_smis_on_64bit_arch V8_31BIT_SMIS_ON_64BIT_ARCH)
   _v8_flag(v8_enable_sandbox V8_ENABLE_SANDBOX)
+
+  # Fedora's node embeds a small ICU and loads the full data (nodejs<N>-full-i18n) from here
+  string(REGEX MATCH "['\"]icu_default_data['\"]: *['\"]([^'\"]+)['\"]" _icu_default_data "${_V8_CONFIG}")
+  if(CMAKE_MATCH_1)
+    list(APPEND V8_DEFINITIONS "V8_ICU_DEFAULT_DATA_DIR=\"${CMAKE_MATCH_1}\"")
+  endif()
 endif()
 
 if(V8_INCLUDE_DIR AND NOT EXISTS "${V8_INCLUDE_DIR}/libplatform/libplatform.h")

+ 13 - 31
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -874,8 +874,8 @@ void ApplicationContext::loadSettingsFromArgv () {
     backgroundGroup.add_argument ("--layer")
 	.help (
 	    "Wayland-only: which wlr-layer-shell layer to anchor the wallpaper to "
-	    "(background, bottom, top, overlay). Default: background on KDE, bottom elsewhere. "
-	    "KDE defaults to 'background' because KWin's 'show desktop' (Super+D) hides 'bottom' surfaces. "
+	    "(background, bottom, top, overlay). Default: bottom. On KDE 'background' shares a layer with "
+	    "plasmashell's desktop window, which covers the wallpaper whenever it maps after it (e.g. at login). "
 	    "Use 'background' on niri to pair with the `place-within-backdrop` layer-rule, "
 	    "otherwise the wallpaper will be cloned to every workspace in the overview."
 	)
@@ -1117,6 +1117,17 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.general.msaaSamples = value == "x2" ? 2 : value == "x4" ? 4 : value == "x8" ? 8 : 0;
 	});
 
+    configurationGroup.add_argument ("--ssaa")
+	.help (
+	    "Supersampling for scenes: none (default), x2, x3 or x4. The scene renders at that many times the output "
+	    "size per axis and is averaged down, so it costs that factor squared in GPU time and memory. Effects "
+	    "measured in pixels (blur, bloom) cover the same pixels as on a screen that much bigger"
+	)
+	.choices ("none", "x2", "x3", "x4")
+	.action ([this] (const std::string& value) -> void {
+	    this->settings.general.supersampling = value == "x2" ? 2 : value == "x3" ? 3 : value == "x4" ? 4 : 1;
+	});
+
     configurationGroup.add_argument ("--disable-animations")
 	.help ("Freezes all scene animation (scripts, particles, effects and puppet meshes) at its current frame")
 	.flag ()
@@ -1332,35 +1343,6 @@ void ApplicationContext::loadSettingsFromArgv () {
     try {
 	program.parse_known_args (this->m_argc, this->m_argv);
 
-	if (!program.is_used ("--layer")) {
-	    const auto* desktopSession = std::getenv ("DESKTOP_SESSION");
-	    const auto* xdgDesktop = std::getenv ("XDG_SESSION_DESKTOP");
-	    const auto* kdeSession = std::getenv ("KDE_FULL_SESSION");
-
-	    bool onKDE = false;
-	    if (desktopSession) {
-		std::string_view s (desktopSession);
-		onKDE = s.find ("kde") != std::string_view::npos || s.find ("plasma") != std::string_view::npos;
-	    }
-	    if (!onKDE && xdgDesktop && std::string_view (xdgDesktop) == "KDE") {
-		onKDE = true;
-	    }
-	    if (!onKDE && kdeSession && std::string_view (kdeSession) == "true") {
-		onKDE = true;
-	    }
-
-	    if (onKDE) {
-		this->settings.render.wayland.layer = WAYLAND_LAYER_BACKGROUND;
-
-		if (!isHelperProcess (this->m_argc, this->m_argv, this->settings.general.webHost)) {
-		    sLog.out (
-			"KDE detected: using --layer background to prevent 'show desktop' from hiding the wallpaper "
-			"(use --layer bottom to override)"
-		    );
-		}
-	    }
-	}
-
 	if (this->settings.general.defaultBackground.empty ()) {
 	    throw std::runtime_error ("At least one background ID must be specified");
 	}

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

@@ -126,6 +126,8 @@ public:
 	    int shadowQuality = 2;
 	    /** WE's "msaa" setting as a sample count (0 off, 2, 4, 8), only scenes with models use it, see --msaa */
 	    int msaaSamples = 0;
+	    /** --ssaa factor per axis */
+	    int supersampling = 1;
 	    /** Objects/layers to force-hide, matched by id or name */
 	    std::vector<std::string> disabledObjects;
 	    /** Objects/layers to force-show, matched by id or name */

+ 29 - 6
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -2213,6 +2213,14 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	auto* bitmap = new uint8_t[width * height * 3] { 0 };
 
 	for (const auto& capture : captures) {
+	    // --ssaa: average the framebuffer pixels behind each output pixel
+	    const float spanX = std::abs (capture.uend - capture.ustart) * capture.readWidth / capture.vpWidth;
+	    const float spanY = std::abs (capture.vend - capture.vstart) * capture.readHeight / capture.vpHeight;
+	    const int samplesX = std::max (1, static_cast<int> (std::lround (spanX)));
+	    const int samplesY = std::max (1, static_cast<int> (std::lround (spanY)));
+	    const int stepX = capture.uend < capture.ustart ? -1 : 1;
+	    const int stepY = capture.vend < capture.vstart ? -1 : 1;
+
 	    // sample the bitmap from the UV-defined visible region
 	    for (int y = 0; y < capture.vpHeight; y++) {
 		for (int x = 0; x < capture.vpWidth; x++) {
@@ -2221,18 +2229,33 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 		    const float v = capture.vstart
 			+ (static_cast<float> (y) / capture.vpHeight) * (capture.vend - capture.vstart);
 
-		    const int srcX = std::clamp (static_cast<int> (u * capture.readWidth), 0, capture.readWidth - 1);
-		    const int srcY = std::clamp (static_cast<int> (v * capture.readHeight), 0, capture.readHeight - 1);
-		    const int srcIdx = (srcY * capture.readWidth + srcX) * 3;
+		    const int srcX = static_cast<int> (u * capture.readWidth) - (stepX < 0 ? 1 : 0) * (samplesX > 1);
+		    const int srcY = static_cast<int> (v * capture.readHeight) - (stepY < 0 ? 1 : 0) * (samplesY > 1);
+		    int sum[3] = { 0, 0, 0 };
+
+		    for (int sy = 0; sy < samplesY; sy++) {
+			const int row = std::clamp (srcY + sy * stepY, 0, capture.readHeight - 1);
 
+			for (int sx = 0; sx < samplesX; sx++) {
+			    const int column = std::clamp (srcX + sx * stepX, 0, capture.readWidth - 1);
+			    const int srcIdx = (row * capture.readWidth + column) * 3;
+
+			    sum[0] += capture.buffer[srcIdx];
+			    sum[1] += capture.buffer[srcIdx + 1];
+			    sum[2] += capture.buffer[srcIdx + 2];
+			}
+		    }
+
+		    const int count = samplesX * samplesY;
 		    const int xfinal = x + capture.xoffset;
 		    // FBO content is not flipped like default framebuffer, so invert vflip logic
 		    const int yfinal = vflip ? y : (capture.vpHeight - y - 1);
 
 		    if (yfinal >= 0 && yfinal < height && xfinal >= 0 && xfinal < width) {
-			bitmap[yfinal * width * 3 + xfinal * 3] = capture.buffer[srcIdx];
-			bitmap[yfinal * width * 3 + xfinal * 3 + 1] = capture.buffer[srcIdx + 1];
-			bitmap[yfinal * width * 3 + xfinal * 3 + 2] = capture.buffer[srcIdx + 2];
+			for (int channel = 0; channel < 3; channel++) {
+			    bitmap[yfinal * width * 3 + xfinal * 3 + channel]
+				= static_cast<uint8_t> ((sum[channel] + count / 2) / count);
+			}
 		    }
 		}
 	    }

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

@@ -130,7 +130,6 @@ struct Mipmap {
     int compressedSize = 0;
     std::unique_ptr<char[]> compressedData = nullptr;
     std::unique_ptr<char[]> uncompressedData = nullptr;
-    std::string json {};
     std::vector<MipmapPatch> patches {};
     /** RGBA pixels with the patches of the conditions that hold already applied, used instead of decoding the data */
     std::vector<unsigned char> composedPixels {};

+ 8 - 0
src/WallpaperEngine/Data/Model/Wallpaper.h

@@ -144,6 +144,14 @@ struct SceneData {
     } camera;
     /** 3D scenes: particles, text, lights and blended images draw after the rest, back to front */
     UserSettingUniquePtr transparentSorting;
+    /** Puppet rope gravity and wind (2.8.42 scene +996..+1024, flag 0x10000 of +224) */
+    struct {
+	UserSettingUniquePtr gravityDirection;
+	UserSettingUniquePtr gravityStrength;
+	UserSettingUniquePtr windEnabled;
+	UserSettingUniquePtr windDirection;
+	UserSettingUniquePtr windStrength;
+    } physics;
 
     ObjectList objects;
 };

+ 12 - 32
src/WallpaperEngine/Data/Parsers/TextureParser.cpp

@@ -52,16 +52,6 @@ TextureUniquePtr TextureParser::parse (const BinaryReader& file) {
 MipmapSharedPtr TextureParser::parseMipmap (const BinaryReader& file, const Texture& header) {
     auto result = std::make_shared<Mipmap> ();
 
-    // TEXB0004 has extra header data
-    if (header.containerVersion == ContainerVersion_TEXB0004) {
-	// two integers that only seem to affect the editor
-	std::ignore = file.nextUInt32 ();
-	std::ignore = file.nextUInt32 ();
-	// json blob, not parsed yet
-	result->json = file.nextNullTerminatedString ();
-	std::ignore = file.nextUInt32 ();
-    }
-
     result->width = file.nextUInt32 ();
     result->height = file.nextUInt32 ();
 
@@ -70,8 +60,7 @@ MipmapSharedPtr TextureParser::parseMipmap (const BinaryReader& file, const Text
 	result->depth = file.nextUInt32 ();
     }
 
-    if (header.containerVersion == ContainerVersion_TEXB0004 || header.containerVersion == ContainerVersion_TEXB0003
-	|| header.containerVersion == ContainerVersion_TEXB0002) {
+    if (header.containerVersion == ContainerVersion_TEXB0003 || header.containerVersion == ContainerVersion_TEXB0002) {
 	result->compression = file.nextUInt32 ();
 	result->uncompressedSize = file.nextInt ();
     }
@@ -258,30 +247,21 @@ void TextureParser::parseContainer (Texture& header, const BinaryReader& file) {
     header.imageCount = file.nextUInt32 ();
 
     if (strncmp (magic, "TEXB0004", 9) == 0) {
-	header.containerVersion = ContainerVersion_TEXB0004;
+	// sub_14015C8D0 (2.8.42): FIF, property conditions, then TEXB0003 mipmaps. Videos are detected by the texture
+	// flags, not this header
+	header.containerVersion = ContainerVersion_TEXB0003;
 	header.freeImageFormat = parseFIF (file.nextUInt32 ());
-	// wallpaper64.exe 2.8.42 sub_14015C8D0 reads this as the number of user property conditions
-	const uint32_t conditionCount = file.nextUInt32 ();
-	header.isVideoMp4 = conditionCount == 1;
-
-	if (header.freeImageFormat == FIF_UNKNOWN && header.isVideoMp4) {
-	    header.freeImageFormat = FIF_MP4;
-	}
 
-	// TEXB0004 behaves like TEXB0003 unless it's actually an MP4
-	if (header.freeImageFormat != FIF_MP4) {
-	    header.containerVersion = ContainerVersion_TEXB0003;
-	    header.isVideoMp4 = false;
+	const uint32_t conditionCount = file.nextUInt32 ();
 
-	    for (uint32_t index = 0; index < conditionCount; index++) {
-		TextureCondition condition;
+	for (uint32_t index = 0; index < conditionCount; index++) {
+	    TextureCondition condition;
 
-		condition.group = file.nextUInt32 ();
-		condition.key = file.nextUInt32 ();
-		condition.flags = file.nextUInt32 ();
-		condition.json = file.nextNullTerminatedString ();
-		header.conditions.push_back (std::move (condition));
-	    }
+	    condition.group = file.nextUInt32 ();
+	    condition.key = file.nextUInt32 ();
+	    condition.flags = file.nextUInt32 ();
+	    condition.json = file.nextNullTerminatedString ();
+	    header.conditions.push_back (std::move (condition));
 	}
     } else if (strncmp (magic, "TEXB0003", 9) == 0) {
 	header.containerVersion = ContainerVersion_TEXB0003;

+ 7 - 0
src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp

@@ -364,6 +364,13 @@ SceneUniquePtr WallpaperParser::parseScene (const JSON& file, Project& project)
                 }
             },
             .transparentSorting = general.user ("transparentsorting", properties, false),
+            .physics = {
+                .gravityDirection = general.user ("gravitydirection", properties, glm::vec3 (0.0f, -1.0f, 0.0f)),
+                .gravityStrength = general.user ("gravitystrength", properties, 1.0f),
+                .windEnabled = general.user ("windenabled", properties, false),
+                .windDirection = general.user ("winddirection", properties, glm::vec3 (0.70710677f, 0.70710677f, 0.0f)),
+                .windStrength = general.user ("windstrength", properties, 1.0f),
+            },
             .objects = parseObjects (objects, project),
         }
     );

+ 57 - 4
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -1,3 +1,4 @@
+#include <algorithm>
 #include <cmath>
 #include <tuple>
 #include <vector>
@@ -133,6 +134,7 @@ void CWallpaper::setupShaders () {
 	  "uniform bool u_LutEnabled;\n"
 	  "uniform bool u_InputLinear;\n"
 	  "uniform bool u_OutputPQ;\n"
+	  "uniform int u_Supersample;\n"
 	  "in vec2 v_TexCoord;\n"
 	  "out vec4 out_FragColor;\n"
 	  // BT.2408 reference white, what the PQ image description of HDR surfaces anchors SDR content to
@@ -171,7 +173,21 @@ void CWallpaper::setupShaders () {
 	  "return vec3 (H, C / (Q.x + 1e-10), Q.x);\n"
 	  "}\n"
 	  "void main () {\n"
-	  "vec4 albedo = texture (g_Texture0, v_TexCoord);\n"
+	  "vec4 albedo = vec4 (0.0);\n"
+	  // exact box filter: one tap per texel center, derivatives handle flipped and span UVs
+	  "if (u_Supersample > 1) {\n"
+	  "vec2 stepX = dFdx (v_TexCoord);\n"
+	  "vec2 stepY = dFdy (v_TexCoord);\n"
+	  "for (int y = 0; y < u_Supersample; y++) {\n"
+	  "for (int x = 0; x < u_Supersample; x++) {\n"
+	  "vec2 offset = (vec2 (x, y) + 0.5) / float (u_Supersample) - 0.5;\n"
+	  "albedo += texture (g_Texture0, v_TexCoord + offset.x * stepX + offset.y * stepY);\n"
+	  "}\n"
+	  "}\n"
+	  "albedo /= float (u_Supersample * u_Supersample);\n"
+	  "} else {\n"
+	  "albedo = texture (g_Texture0, v_TexCoord);\n"
+	  "}\n"
 	  "bool filtered = u_ColorEnabled || u_LutEnabled;\n"
 	  "vec3 overbright = vec3 (0.0);\n"
 	  // the filters work on SDR-encoded values like in Wallpaper Engine, what's past reference white is kept aside
@@ -253,6 +269,7 @@ void CWallpaper::setupShaders () {
     this->u_LutEnabled = glGetUniformLocation (this->m_shader, "u_LutEnabled");
     this->u_InputLinear = glGetUniformLocation (this->m_shader, "u_InputLinear");
     this->u_OutputPQ = glGetUniformLocation (this->m_shader, "u_OutputPQ");
+    this->u_Supersample = glGetUniformLocation (this->m_shader, "u_Supersample");
     this->a_Position = glGetAttribLocation (this->m_shader, "a_Position");
     this->a_TexCoord = glGetAttribLocation (this->m_shader, "a_TexCoord");
 }
@@ -300,6 +317,8 @@ void CWallpaper::render (
 	: viewport;
 
     this->m_screenSize = { sceneViewport.z, sceneViewport.w };
+    this->m_supersampling
+	= this->rendersAtOutputSize () ? this->supersamplingFor ({ sceneViewport.z, sceneViewport.w }) : 1;
     // the scene reads the visible region from these while it renders
     this->updateUVs (this->m_spanInfo.has_value () ? this->m_spanInfo->totalBounds : viewport, vflip);
 
@@ -394,7 +413,7 @@ void CWallpaper::render (
 	this->m_uploadedVend = vend;
     }
 
-    this->drawOutputQuad ();
+    this->drawOutputQuad (this->m_supersampling);
 
     if (this->getContext ().getApp ().getContext ().settings.render.debug.brightnessLog) {
 	static uint32_t brightnessFrameCounter = 0;
@@ -415,7 +434,39 @@ void CWallpaper::render (
 #endif /* !NDEBUG */
 }
 
-void CWallpaper::drawOutputQuad () {
+int CWallpaper::supersamplingFor (const glm::ivec2& outputSize) {
+    const int requested = this->getContext ().getApp ().getContext ().settings.general.supersampling;
+
+    if (requested <= 1 || outputSize.x <= 0 || outputSize.y <= 0) {
+	return 1;
+    }
+
+    GLint maxTexture = 0;
+    GLint maxRenderbuffer = 0;
+    GLint maxViewport[2] = { 0, 0 };
+    glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTexture);
+    glGetIntegerv (GL_MAX_RENDERBUFFER_SIZE, &maxRenderbuffer);
+    glGetIntegerv (GL_MAX_VIEWPORT_DIMS, maxViewport);
+
+    const int limit = std::min ({ maxTexture, maxRenderbuffer, maxViewport[0], maxViewport[1] });
+    int factor = requested;
+
+    while (factor > 1 && std::max (outputSize.x, outputSize.y) * factor > limit) {
+	factor--;
+    }
+
+    if (factor != requested && factor != this->m_supersamplingLogged) {
+	sLog.error (
+	    "SSAA x", requested, " would need a ", outputSize.x * requested, "x", outputSize.y * requested,
+	    " scene buffer, more than the GPU allows (", limit, "), using x", factor
+	);
+    }
+
+    this->m_supersamplingLogged = factor;
+    return factor;
+}
+
+void CWallpaper::drawOutputQuad (const int supersample) {
     glDisable (GL_BLEND);
     glDisable (GL_DEPTH_TEST);
     glDisable (GL_CULL_FACE);
@@ -449,6 +500,7 @@ void CWallpaper::drawOutputQuad () {
     glUniform1i (this->u_LutEnabled, lutEnabled);
     glUniform1i (this->u_InputLinear, this->m_linearInput);
     glUniform1i (this->u_OutputPQ, this->m_outputHDR);
+    glUniform1i (this->u_Supersample, supersample);
     glUniform4fv (this->g_Params, 1, &this->m_colorParams.x);
     glUniform1f (this->g_LutParams, this->m_lutStrength);
 
@@ -561,7 +613,8 @@ GLuint CWallpaper::renderAdjustedFramebuffer () {
     glBindVertexArray (this->m_vaoBuffer);
     glBindBuffer (GL_ARRAY_BUFFER, this->m_texCoordBuffer);
     glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (texCoords), texCoords);
-    this->drawOutputQuad ();
+    // screenshots do their own supersample averaging
+    this->drawOutputQuad (1);
 
     this->m_destFramebuffer = previousDestination;
     this->m_outputHDR = outputHDR;

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

@@ -128,6 +128,8 @@ public:
     [[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; }
+    /** This frame's --ssaa factor per axis */
+    [[nodiscard]] int getSupersampling () const { return this->m_supersampling; }
 
     // maxRenderSize is only meaningful for Web wallpapers (see CWeb) - the largest resolution this
     // wallpaper instance will ever be asked to render at: a single screen's size normally, or a span
@@ -197,9 +199,14 @@ private:
     bool m_linearInput = false;
     GLint u_InputLinear = GL_NONE;
     GLint u_OutputPQ = GL_NONE;
+    GLint u_Supersample = GL_NONE;
     void loadLut (const std::string& name);
-    /** Draws the wallpaper's texture with the image adjustments over the bound framebuffer, UVs already uploaded */
-    void drawOutputQuad ();
+    /** Draws the texture with the image adjustments, box filtering supersample texels per axis */
+    void drawOutputQuad (int supersample);
+    /** --ssaa factor reduced to fit the GL size limits */
+    [[nodiscard]] int supersamplingFor (const glm::ivec2& outputSize);
+    int m_supersampling = 1;
+    int m_supersamplingLogged = 0;
     std::optional<SpanInfo> m_spanInfo = std::nullopt;
     // Avoids redundant renderFrame calls when the same wallpaper is shared across viewports (span mode)
     uint32_t m_lastRenderedFrame = UINT32_MAX;

+ 1 - 0
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -305,6 +305,7 @@ void WaylandOutputViewport::setupLS () {
 	    break;
     }
 
+    // KWin treats the "desktop" namespace as a desktop window, so 'show desktop' leaves it alone
     layerSurface = zwlr_layer_shell_v1_get_layer_surface (
 	m_driver->getWaylandContext ()->layerShell, surface, output, wlrLayer, "desktop"
     );

+ 779 - 21
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -2,10 +2,12 @@
 #include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
 
+#include "CMesh.h"
 #include "CRenderable.h"
 
 #include <algorithm>
 #include <array>
+#include <cmath>
 #include <cstdio>
 #include <cstdlib>
 #include <cstring>
@@ -14,6 +16,7 @@
 #include <optional>
 #include <sstream>
 #include <strings.h>
+#include <tuple>
 #include <vector>
 
 #include <glm/glm.hpp>
@@ -330,6 +333,285 @@ resolvePuppetVertexLayout (const BinaryReader& reader, size_t markerSize, size_t
     return best;
 }
 
+// bounds-checked little endian reads for MDLV/MDMP (sub_140261880)
+class PuppetFileReader {
+public:
+    PuppetFileReader (const std::vector<char>& data, size_t offset) : m_data (data), m_offset (offset) { }
+
+    template <typename T> T next () {
+	if (this->m_offset + sizeof (T) > this->m_data.size ()) {
+	    throw std::runtime_error ("truncated puppet file");
+	}
+
+	T value;
+	std::memcpy (&value, this->m_data.data () + this->m_offset, sizeof (T));
+	this->m_offset += sizeof (T);
+	return value;
+    }
+
+    void string () {
+	while (this->next<char> () != '\0') { }
+    }
+
+    std::string text () {
+	std::string result;
+
+	for (char c = this->next<char> (); c != '\0'; c = this->next<char> ()) {
+	    result.push_back (c);
+	}
+
+	return result;
+    }
+
+    /** u32 size + bytes */
+    std::pair<size_t, uint32_t> blob () {
+	const auto bytes = this->next<uint32_t> ();
+	const size_t start = this->m_offset;
+
+	if (start + bytes > this->m_data.size ()) {
+	    throw std::runtime_error ("truncated puppet file");
+	}
+
+	this->m_offset += bytes;
+	return { start, bytes };
+    }
+
+    void skip (size_t bytes) { this->m_offset += bytes; }
+
+    [[nodiscard]] size_t offset () const { return this->m_offset; }
+
+private:
+    const std::vector<char>& m_data;
+    size_t m_offset;
+};
+
+struct PuppetMeshHeader {
+    uint32_t flags = 0;
+    uint32_t format = 0;
+    size_t vertices = 0;
+    uint32_t vertexBytes = 0;
+    uint32_t indexBytes = 0;
+};
+
+// first mesh header: tag, default format, materials per mesh, mesh count, then per mesh: material names, flags
+// (+u32 with flag 2), bounds (v17+), format (v15+)
+PuppetMeshHeader readPuppetMeshHeader (const std::vector<char>& data) {
+    PuppetFileReader reader (data, 0);
+    reader.string ();
+
+    const int version = std::atoi (data.data () + strlen ("MDLV"));
+    PuppetMeshHeader header;
+    header.format = reader.next<uint32_t> ();
+    const auto materials = reader.next<uint32_t> ();
+    (void)reader.next<uint32_t> ();
+
+    for (uint32_t material = 0; material < materials; material++) {
+	reader.string ();
+    }
+
+    if (version >= 4) {
+	header.flags = reader.next<uint32_t> ();
+
+	if (header.flags & 2) {
+	    (void)reader.next<uint32_t> ();
+	}
+
+	if (version >= 17) {
+	    reader.skip (sizeof (float) * 6);
+	}
+
+	if (version >= 15) {
+	    header.format = reader.next<uint32_t> ();
+	}
+    }
+
+    header.vertexBytes = reader.next<uint32_t> ();
+    header.vertices = reader.offset ();
+    reader.skip (header.vertexBytes);
+    header.indexBytes = reader.next<uint32_t> ();
+    return header;
+}
+
+// sub_140261880 layout of the first mesh; texcoords not last in the vertex fall back to the heuristic
+std::optional<PuppetVertexLayout> readPuppetVertexLayout (const std::vector<char>& data, size_t meshHeaderSize) {
+    const auto header = readPuppetMeshHeader (data);
+    const uint32_t stride = CMesh::vertexStride (header.format);
+    const auto texcoord = CMesh::vertexComponentOffset (header.format, 0x8);
+
+    if (stride == 0 || header.vertexBytes % stride != 0 || !texcoord.has_value ()
+	|| *texcoord != stride - sizeof (GLfloat) * 2 || header.vertices + header.vertexBytes > data.size ()) {
+	return std::nullopt;
+    }
+
+    return PuppetVertexLayout {
+	.block = PuppetMeshBlock { .headerOffset = header.vertices - meshHeaderSize,
+				   .vertexBytes = header.vertexBytes,
+				   .indexBytes = header.indexBytes },
+	.vertexStride = stride,
+	.uvOffset = *texcoord,
+    };
+}
+
+// first mesh with flag 2 (sub_1401FBAE0, puppet +912), BLENDROWCOUNT = the u32 after its flags (sub_140209540)
+std::optional<PuppetBlendMesh> readPuppetBlendMesh (const std::vector<char>& data) {
+    PuppetFileReader reader (data, 0);
+    reader.string ();
+
+    const int version = std::atoi (data.data () + strlen ("MDLV"));
+
+    if (version < 4) {
+	return std::nullopt;
+    }
+
+    const auto defaultFormat = reader.next<uint32_t> ();
+    const auto materials = reader.next<uint32_t> ();
+    const auto meshes = reader.next<uint32_t> ();
+
+    for (uint32_t mesh = 0; mesh < meshes; mesh++) {
+	PuppetBlendMesh result;
+
+	for (uint32_t material = 0; material < materials; material++) {
+	    const std::string name = reader.text ();
+
+	    if (material == 0) {
+		result.material = name;
+	    }
+	}
+
+	const auto flags = reader.next<uint32_t> ();
+
+	if (flags & 2) {
+	    result.rows = reader.next<uint32_t> ();
+	}
+
+	if (version >= 17) {
+	    reader.skip (sizeof (float) * 6);
+	}
+
+	result.format = version >= 15 ? reader.next<uint32_t> () : defaultFormat;
+	std::tie (result.vertices, result.vertexBytes) = reader.blob ();
+	std::tie (result.indices, result.indexBytes) = reader.blob ();
+
+	if (flags & 2) {
+	    return result;
+	}
+
+	if (version >= 21) {
+	    if (reader.next<uint8_t> () != 0) {
+		(void)reader.next<uint32_t> ();
+		(void)reader.blob ();
+	    }
+
+	    if (reader.next<uint8_t> () != 0) {
+		(void)reader.blob ();
+	    }
+	}
+
+	if (version >= 23) {
+	    const auto records = reader.next<uint32_t> ();
+
+	    for (uint32_t record = 0; record < records; record++) {
+		reader.skip (sizeof (uint64_t));
+		reader.string ();
+		(void)reader.next<uint32_t> ();
+		reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
+		reader.skip (sizeof (uint32_t) * reader.next<uint32_t> ());
+	    }
+	}
+    }
+
+    return std::nullopt;
+}
+
+// MDMP per mesh (sub_140261880): u16 targets, scale, vertex count, then per target u64, name and 16 bit blobs:
+// positions, normals (0x400), 3 more (0x800), alpha (0x1000), bone rule (0x2000, u32 u32 f32 f32)
+std::optional<PuppetMorphTargets>
+readPuppetMorphTargets (const std::vector<char>& data, size_t section, uint32_t flags) {
+    PuppetFileReader reader (data, section);
+    reader.string ();
+    (void)reader.next<uint32_t> ();
+
+    const auto targets = reader.next<uint16_t> ();
+
+    if (targets == 0) {
+	return std::nullopt;
+    }
+
+    PuppetMorphTargets morph;
+    morph.scale = reader.next<float> ();
+    morph.vertexCount = reader.next<uint32_t> ();
+
+    std::vector<size_t> positions;
+    std::vector<size_t> alphas;
+
+    for (uint16_t target = 0; target < targets; target++) {
+	(void)reader.next<uint64_t> ();
+	reader.string ();
+
+	const auto [position, positionBytes] = reader.blob ();
+	morph.vertexCount = std::min (morph.vertexCount, positionBytes / 6);
+
+	if (positionBytes != morph.vertexCount * 6) {
+	    throw std::runtime_error ("morph target positions don't match the vertex count");
+	}
+
+	positions.push_back (position);
+
+	for (const uint32_t flag : { 0x400u, 0x800u }) {
+	    if ((flags & flag) && reader.blob ().second != positionBytes) {
+		throw std::runtime_error ("morph target normals don't match the vertex count");
+	    }
+	}
+
+	if (flags & 0x1000) {
+	    const auto [alpha, alphaBytes] = reader.blob ();
+
+	    if (alphaBytes != morph.vertexCount * 2) {
+		throw std::runtime_error ("morph target alphas don't match the vertex count");
+	    }
+
+	    alphas.push_back (alpha);
+	}
+
+	if (flags & 0x2000) {
+	    reader.skip (sizeof (uint32_t) * 4);
+	}
+    }
+
+    // square of vertexCount * targets + 1 texels, texel 0 is (0, 0, 0, 1)
+    const uint32_t texels = morph.vertexCount * targets + 1;
+    auto side = static_cast<uint32_t> (std::sqrt (static_cast<float> (texels)));
+
+    if (side * side < texels) {
+	side++;
+    }
+
+    const auto snorm = [&data] (size_t offset) {
+	int16_t value;
+	std::memcpy (&value, data.data () + offset, sizeof (value));
+	return std::max (static_cast<float> (value) / 32767.0f, -1.0f);
+    };
+
+    morph.texels.assign (static_cast<size_t> (side) * side, glm::vec4 (0.0f));
+    morph.texels[0] = glm::vec4 (0.0f, 0.0f, 0.0f, 1.0f);
+    // without 0x1000 morphed vertices read alpha 0
+    morph.alpha = (flags & 0x1000) == 0;
+    size_t out = 1;
+
+    for (size_t target = 0; target < alphas.size (); target++) {
+	for (uint32_t vertex = 0; vertex < morph.vertexCount; vertex++) {
+	    const size_t position = positions[target] + vertex * 6;
+	    morph.texels[out] = glm::vec4 (
+		snorm (position), snorm (position + 2), snorm (position + 4), snorm (alphas[target] + vertex * 2)
+	    );
+	    morph.alpha = morph.alpha || morph.texels[out].w != 1.0f;
+	    out++;
+	}
+    }
+
+    return morph;
+}
+
 }
 
 CImage::ResolvedTransform CImage::localTransform (const Object& object) {
@@ -466,7 +748,10 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
 		continue;
 	    }
 
-	    this->registerProperty (prefix + name, *(*setting)->value);
+	    this->registerProperty (
+		prefix + name, *(*setting)->value,
+		Scripting::Adapters::animationLayerGroup (this->getId (), layerIndex), name
+	    );
 	    scene.getScriptEngine ().setThisObjectFactory (
 		this->getProperties ().at (prefix + name).key, [this, layerIndex] (Scripting::ScriptEngine& engine) {
 		    return Scripting::Adapters::makeAnimationLayerHandle (engine, *this, layerIndex);
@@ -805,11 +1090,18 @@ CImage::~CImage () {
     if (this->m_puppetTexCoord != GL_NONE) {
 	glDeleteBuffers (1, &this->m_puppetTexCoord);
     }
+    if (this->m_puppetVertexAlphaWeights != GL_NONE) {
+	glDeleteBuffers (1, &this->m_puppetVertexAlphaWeights);
+    }
     if (this->m_puppetIndices != GL_NONE) {
 	glDeleteBuffers (1, &this->m_puppetIndices);
     }
+    delete this->m_blendMap.copyPass;
+    delete this->m_blendMap.pass;
+
     for (const GLuint buffer :
-	 { this->m_puppetClipIndices, this->m_puppetClipComposePosition, this->m_puppetClipComposeTexCoord }) {
+	 { this->m_puppetClipIndices, this->m_puppetClipComposePosition, this->m_puppetClipComposeTexCoord,
+	   this->m_blendMap.vertices, this->m_blendMap.indices, this->m_blendMap.quad }) {
 	if (buffer != GL_NONE) {
 	    glDeleteBuffers (1, &buffer);
 	}
@@ -844,7 +1136,17 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	std::copy (data.begin (), data.end (), meshBuffer.get ());
 	const BinaryReader reader (std::make_shared<MemoryStream> (std::move (meshBuffer), data.size ()));
 
-	const auto layout = resolvePuppetVertexLayout (reader, markerSize, mdlsOffset, meshHeaderSize);
+	std::optional<PuppetVertexLayout> layout;
+
+	try {
+	    layout = readPuppetVertexLayout (data, meshHeaderSize);
+	} catch (const std::exception& ex) {
+	    sLog.error ("Could not read the first mesh of ", *this->getImage ().model->puppet, ": ", ex.what ());
+	}
+
+	if (!layout.has_value ()) {
+	    layout = resolvePuppetVertexLayout (reader, markerSize, mdlsOffset, meshHeaderSize);
+	}
 	if (!layout.has_value ()) {
 	    sLog.error ("Could not find a usable MDLV mesh block in ", *this->getImage ().model->puppet);
 	    return false;
@@ -875,6 +1177,8 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	this->m_puppetDrawBuffer = this->m_puppetIndices;
 	this->m_puppetDrawCount = this->m_puppetIndexCount;
 
+	this->loadPuppetBlendMesh (data);
+
 	// the part ranges and clipping records follow the index buffer (sub_140261880)
 	const int version
 	    = puppetVersion.size () > strlen ("MDLV") ? std::atoi (puppetVersion.c_str () + strlen ("MDLV")) : 0;
@@ -885,9 +1189,47 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	this->m_puppetPartOrder.clear ();
 	this->m_puppetMeshIndices.clear ();
 
-	// the mesh header's first field holds its flags, 8 animates the order the parts are drawn in
-	uint32_t meshFlags = 0;
-	std::memcpy (&meshFlags, data.data () + layout->block.headerOffset, sizeof (meshFlags));
+	// 4 bone alpha, 8 draw order, 0x1000 morph alpha
+	this->m_puppetMeshFlags = 0;
+	this->m_puppetMeshFormat = 0;
+
+	try {
+	    const auto header = readPuppetMeshHeader (data);
+
+	    if (header.vertices == layout->block.headerOffset + meshHeaderSize) {
+		this->m_puppetMeshFlags = header.flags;
+		this->m_puppetMeshFormat = header.format;
+	    } else {
+		sLog.error (
+		    "The first mesh header of ", *this->getImage ().model->puppet, " isn't where its vertices are"
+		);
+	    }
+	} catch (const std::exception& ex) {
+	    sLog.error ("Could not read the mesh header of ", *this->getImage ().model->puppet, ": ", ex.what ());
+	}
+
+	const uint32_t meshFlags = this->m_puppetMeshFlags;
+
+	// position.w is the morph texel, <= 0 means not morphed
+	this->m_puppetMorph.reset ();
+	this->m_puppetMorphIndices.clear ();
+
+	if (this->m_puppetMeshFormat & 0x10000) {
+	    const size_t vertexCount = layout->block.vertexBytes / layout->vertexStride;
+	    const size_t vertices = layout->block.headerOffset + meshHeaderSize;
+	    this->m_puppetMorphIndices.resize (vertexCount);
+
+	    for (size_t vertex = 0; vertex < vertexCount; vertex++) {
+		float w;
+		std::memcpy (
+		    &w, data.data () + vertices + vertex * layout->vertexStride + sizeof (float) * 3, sizeof (w)
+		);
+
+		if (w > 0.0f) {
+		    this->m_puppetMorphIndices[vertex] = static_cast<uint32_t> (w);
+		}
+	    }
+	}
 
 	if (meshFlags & 8) {
 	    try {
@@ -958,7 +1300,28 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 
 		this->m_rig.load (data, mdlsOffset, meshCount, *this->getImage ().model->puppet);
 		this->m_rig.drawOrderEnabled = !this->m_puppetParts.empty ();
+		this->m_rig.boneAlphaEnabled = (meshFlags & 4) != 0;
+		this->m_rig.morphBlendClamped = false;
 		this->m_rig.addSceneLayers (this->getImage ().animationLayers);
+
+		if ((this->m_puppetMeshFormat & 0x10000) && this->m_rig.getMorphSection () != 0) {
+		    try {
+			this->m_puppetMorph = readPuppetMorphTargets (data, this->m_rig.getMorphSection (), meshFlags);
+		    } catch (const std::exception& ex) {
+			sLog.error (
+			    "Ignoring the morph targets of ", *this->getImage ().model->puppet, ": ", ex.what ()
+			);
+		    }
+
+		    // MORPHING_MODIFIERS (0x2000) not ported
+		    if (this->m_puppetMorph.has_value () && (meshFlags & 0x2000)) {
+			sLog.error (
+			    "Puppet ", *this->getImage ().model->puppet,
+			    " has morph targets with bone rules, which aren't supported, drawing it without them"
+			);
+			this->m_puppetMorph.reset ();
+		    }
+		}
 	    } catch (const std::exception& ex) {
 		sLog.error (
 		    "Could not load puppet skeleton/animation from ", *this->getImage ().model->puppet, ": ",
@@ -968,6 +1331,14 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	    }
 	}
 
+	// vertex alpha via SKINNING_ALPHA (flag 4) or morph alpha < 1, both need the skinned material
+	this->m_puppetVertexAlpha = !this->m_rig.bones.empty ()
+	    && ((meshFlags & 4) != 0 || (this->m_puppetMorph.has_value () && this->m_puppetMorph->alpha));
+
+	if (this->m_puppetVertexAlpha) {
+	    this->updatePuppetVertexAlpha ({});
+	}
+
 	return true;
     } catch (const std::exception& ex) {
 	sLog.error ("Could not load puppet mesh ", *this->getImage ().model->puppet, ": ", ex.what ());
@@ -1076,8 +1447,12 @@ void CImage::updatePuppetPose () {
 	return;
     }
 
+    this->m_rig.ropeEnvironment = this->getScene ().getRopeEnvironment ();
     this->m_rig.updatePose (this->puppetObjectWorld ());
     this->updatePuppetDrawOrder ();
+    for (const auto& payload : this->m_rig.takeFiredEvents ()) {
+	this->getScene ().getScriptEngine ().dispatchClipEvent (*this, payload);
+    }
     this->m_rig.finishEndedLayers ([this] (size_t serial) {
 	this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
     });
@@ -1152,15 +1527,56 @@ void CImage::updatePuppetSkinning () {
 	skinMatrices[i] = worldAnimated[i] * this->m_rig.bones[i].inverseBindWorld;
     }
 
+    // sub_14020CFF0: up to 11 active targets, stable sorted by weight descending
+    std::vector<std::pair<uint32_t, float>> targets;
+
+    if (this->m_puppetMorph.has_value () && !this->m_rig.morphWeights.empty ()) {
+	const auto& state = this->m_rig.morphWeights.front ();
+
+	for (uint32_t target = 0; target < state.weights.size () && target < 64 && targets.size () < 11; target++) {
+	    if (state.active & (uint64_t (1) << target)) {
+		targets.emplace_back (target, state.weights[target]);
+	    }
+	}
+
+	std::ranges::stable_sort (targets, std::ranges::greater {}, &std::pair<uint32_t, float>::second);
+    }
+
     const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
+    std::vector<float> morphAlpha;
+
+    if (this->m_puppetVertexAlpha && !targets.empty ()) {
+	morphAlpha.assign (vertexCount, 1.0f);
+    }
+
     this->m_puppetSkinnedPositions.assign (this->m_puppetRawPositions.size (), 0.0f);
 
     for (size_t v = 0; v < vertexCount; v++) {
-	const glm::vec4 bindPos (
+	glm::vec4 bindPos (
 	    this->m_puppetRawPositions[v * 3], this->m_puppetRawPositions[v * 3 + 1],
 	    this->m_puppetRawPositions[v * 3 + 2], 1.0f
 	);
 
+	if (!targets.empty () && v < this->m_puppetMorphIndices.size () && this->m_puppetMorphIndices[v].has_value ()) {
+	    const auto& morph = *this->m_puppetMorph;
+	    glm::vec3 delta (0.0f);
+	    float alpha = 1.0f;
+
+	    for (const auto& [target, weight] : targets) {
+		const size_t texel = *this->m_puppetMorphIndices[v] + static_cast<size_t> (morph.vertexCount) * target;
+		const glm::vec4 value = texel < morph.texels.size () ? morph.texels[texel] : glm::vec4 (0.0f);
+
+		delta += glm::vec3 (value) * weight;
+		alpha *= value.w * weight + (1.0f - weight);
+	    }
+
+	    bindPos += glm::vec4 (delta * morph.scale, 0.0f);
+
+	    if (!morphAlpha.empty ()) {
+		morphAlpha[v] = alpha;
+	    }
+	}
+
 	glm::vec3 skinned (0.0f);
 	const glm::uvec4& indices
 	    = v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
@@ -1187,6 +1603,64 @@ void CImage::updatePuppetSkinning () {
     }
 
     this->updatePuppetPositionBuffer (this->m_size);
+
+    if (this->m_puppetVertexAlpha) {
+	this->updatePuppetVertexAlpha (morphAlpha);
+    }
+}
+
+void CImage::updatePuppetVertexAlpha (const std::vector<float>& morphAlpha) {
+    // morph alpha * saturate (sum of bone alpha * weight), sub_140206430
+    const size_t vertexCount = this->m_puppetRawPositions.size () / 3;
+    const auto& boneAlpha = this->m_rig.boneAlpha;
+    this->m_puppetVertexAlphaData.assign (vertexCount * 4, 0.0f);
+
+    for (size_t v = 0; v < vertexCount; v++) {
+	float alpha = v < morphAlpha.size () ? morphAlpha[v] : 1.0f;
+
+	if (this->m_puppetMeshFlags & 4) {
+	    const glm::uvec4& indices
+		= v < this->m_puppetBlendIndices.size () ? this->m_puppetBlendIndices[v] : glm::uvec4 (0);
+	    const glm::vec4& weights
+		= v < this->m_puppetBlendWeights.size () ? this->m_puppetBlendWeights[v] : glm::vec4 (0.0f);
+	    float bones = 0.0f;
+
+	    for (int influence = 0; influence < 4; influence++) {
+		if (indices[influence] < this->m_rig.bones.size ()) {
+		    bones += (indices[influence] < boneAlpha.size () ? boneAlpha[indices[influence]] : 1.0f)
+			* weights[influence];
+		}
+	    }
+
+	    alpha *= std::clamp (bones, 0.0f, 1.0f);
+	}
+
+	this->m_puppetVertexAlphaData[v * 4] = alpha;
+	this->m_puppetVertexAlphaData[v * 4 + 1] = 1.0f - alpha;
+    }
+
+    if (this->m_puppetVertexAlphaWeights == GL_NONE) {
+	glGenBuffers (1, &this->m_puppetVertexAlphaWeights);
+    }
+
+    glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetVertexAlphaWeights);
+    glBufferData (
+	GL_ARRAY_BUFFER, this->m_puppetVertexAlphaData.size () * sizeof (GLfloat),
+	this->m_puppetVertexAlphaData.data (), GL_DYNAMIC_DRAW
+    );
+}
+
+ComboMap CImage::puppetVertexAlphaCombos () const {
+    if (!this->m_puppetVertexAlpha) {
+	return {};
+    }
+
+    // sub_140209540; BONECOUNT at least 2 for the alpha trick below
+    return {
+	{ "SKINNING", 1 },
+	{ "BONECOUNT", std::max<int> (2, static_cast<int> (this->m_rig.bones.size ())) },
+	{ "SKINNING_ALPHA", 1 },
+    };
 }
 
 glm::mat4 CImage::worldMatrix () const {
@@ -1400,6 +1874,46 @@ void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
 		glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
 	    }
 
+	    // skinning is on the CPU; two identity bones with alpha 1 and 0, weighted (alpha, 1 - alpha), carry the
+	    // vertex alpha through SKINNING_ALPHA
+	    if (this->m_puppetVertexAlpha && this->m_puppetVertexAlphaWeights != GL_NONE) {
+		const GLuint program = pass->getProgramID ();
+		const GLint blendWeights = glGetAttribLocation (program, "a_BlendWeights");
+		const GLint blendIndices = glGetAttribLocation (program, "a_BlendIndices");
+		const GLint normal = glGetAttribLocation (program, "a_Normal");
+		const GLint tangent = glGetAttribLocation (program, "a_Tangent4");
+
+		if (blendWeights >= 0) {
+		    glEnableVertexAttribArray (blendWeights);
+		    glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetVertexAlphaWeights);
+		    glVertexAttribPointer (blendWeights, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
+		}
+		if (blendIndices >= 0) {
+		    glDisableVertexAttribArray (blendIndices);
+		    glVertexAttribI4ui (blendIndices, 0, 1, 0, 0);
+		}
+		if (normal >= 0) {
+		    glDisableVertexAttribArray (normal);
+		    glVertexAttrib3f (normal, 0.0f, 0.0f, 1.0f);
+		}
+		if (tangent >= 0) {
+		    glDisableVertexAttribArray (tangent);
+		    glVertexAttrib4f (tangent, 1.0f, 0.0f, 0.0f, 1.0f);
+		}
+
+		constexpr GLfloat bones[24]
+		    = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
+			1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f };
+		constexpr GLfloat bonesAlpha[2] = { 1.0f, 0.0f };
+
+		if (const GLint location = glGetUniformLocation (program, "g_Bones"); location >= 0) {
+		    glUniformMatrix4x3fv (location, 2, GL_FALSE, bones);
+		}
+		if (const GLint location = glGetUniformLocation (program, "g_BonesAlpha"); location >= 0) {
+		    glUniform1fv (location, 2, bonesAlpha);
+		}
+	    }
+
 	    // updatePuppetPositionBuffer flips Y when converting mesh-space positions to screen space,
 	    // which mirrors the mesh and reverses triangle winding relative to what the MDL file's index
 	    // buffer encodes - but not necessarily uniformly across the whole mesh, since real puppet
@@ -1464,15 +1978,10 @@ void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
 	    }
 	},
 	[pass] () {
-	    const GLint position = glGetAttribLocation (pass->getProgramID (), "a_Position");
-	    const GLint texCoord = glGetAttribLocation (pass->getProgramID (), "a_TexCoord");
-
-	    if (position >= 0) {
-		glDisableVertexAttribArray (position);
-	    }
-
-	    if (texCoord >= 0) {
-		glDisableVertexAttribArray (texCoord);
+	    for (const char* name : { "a_Position", "a_TexCoord", "a_BlendWeights" }) {
+		if (const GLint location = glGetAttribLocation (pass->getProgramID (), name); location >= 0) {
+		    glDisableVertexAttribArray (location);
+		}
 	    }
 	}
     );
@@ -1493,18 +2002,20 @@ void CImage::setupPuppetClipping () {
     overrides.push_back (
 	std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
 	    .id = -1,
-	    .combos = { { "CLIPPINGUVS", 1 }, { "CLIPPINGTARGET", 1 } },
+	    .combos = this->puppetVertexAlphaCombos (),
 	    .constants = {},
 	    .textures = {},
 	})
     );
+    overrides.back ()->combos.insert_or_assign ("CLIPPINGUVS", 1);
+    overrides.back ()->combos.insert_or_assign ("CLIPPINGTARGET", 1);
     this->m_puppetClipTargetPass = new CPass (
 	*this, fboProvider, this->m_puppetMeshPass->getPass (), *overrides.back (), std::nullopt, std::nullopt
     );
     this->m_puppetClipTargetPass->setTexture (8, this->getScene ().requireAlphaMaskFrameBuffer (false));
     this->setupPuppetGeometryCallback (this->m_puppetClipTargetPass);
 
-    ComboMap maskCombos;
+    ComboMap maskCombos = this->puppetVertexAlphaCombos ();
     const auto& imagePasses = this->getImage ().model->material->passes;
 
     if (!imagePasses.empty () && imagePasses.front ()->blending == BlendingMode_AlphaToCoverage) {
@@ -1606,6 +2117,223 @@ void CImage::setupPuppetClipping () {
     this->m_puppetClipComposePass = compose;
 }
 
+void CImage::loadPuppetBlendMesh (const std::vector<char>& data) {
+    std::optional<PuppetBlendMesh> mesh;
+
+    try {
+	mesh = readPuppetBlendMesh (data);
+    } catch (const std::exception& ex) {
+	sLog.error ("Could not read the blend map mesh of ", *this->getImage ().model->puppet, ": ", ex.what ());
+	return;
+    }
+
+    if (!mesh.has_value ()) {
+	return;
+    }
+
+    const uint32_t stride = CMesh::vertexStride (mesh->format);
+
+    if (stride == 0 || mesh->vertexBytes % stride != 0 || mesh->material.empty ()
+	|| !CMesh::vertexComponentOffset (mesh->format, 0x1).has_value ()) {
+	sLog.error (
+	    "Ignoring the blend map mesh of ", *this->getImage ().model->puppet, ": vertex format ", mesh->format,
+	    " doesn't match its data"
+	);
+	return;
+    }
+
+    glGenBuffers (1, &this->m_blendMap.vertices);
+    glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.vertices);
+    glBufferData (GL_ARRAY_BUFFER, mesh->vertexBytes, data.data () + mesh->vertices, GL_STATIC_DRAW);
+    glGenBuffers (1, &this->m_blendMap.indices);
+    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_blendMap.indices);
+    glBufferData (GL_ELEMENT_ARRAY_BUFFER, mesh->indexBytes, data.data () + mesh->indices, GL_STATIC_DRAW);
+
+    this->m_blendMap.indexCount = static_cast<GLsizei> (mesh->indexBytes / sizeof (GLushort));
+    this->m_blendMap.format = mesh->format;
+    this->m_blendMap.stride = stride;
+    // g_BlendMap rows from puppet +848
+    this->m_blendMap.rows = std::min<uint32_t> (mesh->rows, this->m_rig.blendMap.size () / 4);
+    this->m_blendMap.material = mesh->material;
+}
+
+// sub_140209540: texture + flag 2 mesh into _rt_imageLayerAlbedo_<id>, which the layer samples instead of its
+// texture. Only the pass flags 0x8/0x10 path is ported
+void CImage::setupPuppetBlendMap () {
+    if (this->m_blendMap.indexCount == 0 || this->m_passes.empty () || this->m_texture == nullptr) {
+	return;
+    }
+
+    const auto& project = this->getScene ().getScene ().project;
+    const auto fboProvider = std::make_shared<FBOProvider> (this);
+    const auto& texture = this->m_texture;
+
+    try {
+	this->m_materials.blendMap = MaterialParser::load (project, this->m_blendMap.material);
+    } catch (const std::exception& ex) {
+	sLog.error ("Cannot load the blend map material ", this->m_blendMap.material, ": ", ex.what ());
+	return;
+    }
+
+    if (this->m_materials.blendMap->passes.empty ()) {
+	return;
+    }
+
+    this->m_blendMap.albedo = std::make_shared<CFBO> (
+	"_rt_imageLayerAlbedo_" + std::to_string (this->getId ()), TextureFormat_ARGB8888, texture->getFlags (), 1.0f,
+	texture->getRealWidth (), texture->getRealHeight (), texture->getTextureWidth (0), texture->getTextureHeight (0)
+    );
+
+    const glm::vec2 albedoSize (texture->getTextureWidth (0), texture->getTextureHeight (0));
+    // mesh is in texture pixels, y up
+    this->m_blendMap.projection = glm::ortho (0.0f, albedoSize.x, albedoSize.y, 0.0f, -1.0f, 1.0f);
+
+    constexpr GLfloat quad[] = { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
+				 -1.0f, 1.0f,  0.0f, 0.0f, 1.0f, 1.0f, 1.0f,  0.0f, 1.0f, 1.0f };
+
+    glGenBuffers (1, &this->m_blendMap.quad);
+    glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.quad);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (quad), quad, GL_STATIC_DRAW);
+
+    const auto setMatrices = [this] (Effects::CPass* pass, const glm::mat4* projection) {
+	static const glm::mat3 identityNormal (1.0f);
+	pass->setModelViewProjectionMatrix (projection);
+	pass->setModelViewProjectionMatrixInverse (&this->m_puppetClipIdentity);
+	pass->setModelMatrix (&this->m_puppetClipIdentity);
+	pass->setViewProjectionMatrix (&this->m_puppetClipIdentity);
+	pass->setLightingTransform (&this->m_puppetClipIdentity, &identityNormal, &this->m_puppetClipIdentity);
+	pass->setEffectTextureProjectionMatrix (&this->m_puppetClipIdentity, &this->m_puppetClipIdentity);
+    };
+
+    // fullscreenlayer.json copy, normal blending
+    ComboMap copyCombos;
+
+    if (texture->isAnimated ()) {
+	copyCombos.emplace ("SPRITESHEET", 1);
+    }
+
+    const auto& copyConfig = *this->m_virtualPassess.emplace_back (
+	std::make_unique<MaterialPass> (MaterialPass {
+	    .blending = BlendingMode_Normal,
+	    .cullmode = CullingMode_Disable,
+	    .depthtest = DepthtestMode_Disabled,
+	    .depthwrite = DepthwriteMode_Disabled,
+	    .shader = "passthrough",
+	    .textures = {},
+	    .usertextures = {},
+	    .combos = copyCombos,
+	    .constants = {},
+	})
+    );
+
+    auto* copy = new CPass (*this, fboProvider, copyConfig, std::nullopt, std::nullopt, std::nullopt);
+    copy->setInput (texture);
+    copy->setDestination (this->m_blendMap.albedo);
+    setMatrices (copy, &this->m_puppetClipIdentity);
+    copy->setGeometryCallback (
+	[this, copy] () {
+	    const GLint position = glGetAttribLocation (copy->getProgramID (), "a_Position");
+	    const GLint texCoord = glGetAttribLocation (copy->getProgramID (), "a_TexCoord");
+
+	    glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.quad);
+
+	    if (position >= 0) {
+		glEnableVertexAttribArray (position);
+		glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 5, nullptr);
+	    }
+
+	    if (texCoord >= 0) {
+		glEnableVertexAttribArray (texCoord);
+		glVertexAttribPointer (
+		    texCoord, 2, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 5,
+		    reinterpret_cast<const void*> (sizeof (GLfloat) * 3)
+		);
+	    }
+	},
+	[] () { glDrawArrays (GL_TRIANGLE_STRIP, 0, 4); },
+	[copy] () {
+	    for (const char* name : { "a_Position", "a_TexCoord" }) {
+		if (const GLint location = glGetAttribLocation (copy->getProgramID (), name); location >= 0) {
+		    glDisableVertexAttribArray (location);
+		}
+	    }
+	}
+    );
+    this->m_blendMap.copyPass = copy;
+
+    this->m_materials.blendMapOverride = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
+	.id = -1,
+	.combos = { { "BLENDROWCOUNT", static_cast<int> (this->m_blendMap.rows) } },
+	.constants = {},
+	.textures = {},
+    });
+
+    auto* pass = new CPass (
+	*this, fboProvider, **this->m_materials.blendMap->passes.begin (), *this->m_materials.blendMapOverride,
+	std::nullopt, std::nullopt
+    );
+    pass->setInput (texture);
+    pass->setDestination (this->m_blendMap.albedo);
+    pass->setKeepDestination (true);
+    setMatrices (pass, &this->m_blendMap.projection);
+    pass->setGeometryCallback (
+	[this, pass] () {
+	    const GLuint program = pass->getProgramID ();
+	    const auto stride = static_cast<GLsizei> (this->m_blendMap.stride);
+	    const auto attribute = [&] (const char* name, uint32_t bit, GLint size, bool integer) {
+		const GLint location = glGetAttribLocation (program, name);
+		const auto offset = CMesh::vertexComponentOffset (this->m_blendMap.format, bit);
+
+		if (location < 0) {
+		    return;
+		}
+
+		if (!offset.has_value ()) {
+		    glDisableVertexAttribArray (location);
+		    return;
+		}
+
+		const auto* pointer = reinterpret_cast<const void*> (static_cast<uintptr_t> (*offset));
+		glEnableVertexAttribArray (location);
+
+		if (integer) {
+		    glVertexAttribIPointer (location, size, GL_UNSIGNED_INT, stride, pointer);
+		} else {
+		    glVertexAttribPointer (location, size, GL_FLOAT, GL_FALSE, stride, pointer);
+		}
+	    };
+
+	    glBindBuffer (GL_ARRAY_BUFFER, this->m_blendMap.vertices);
+	    attribute ("a_Position", 0x1, 3, false);
+	    attribute ("a_BlendIndices", 0x800000, 4, true);
+	    attribute ("a_TexCoordVec4", 0x20, 4, false);
+
+	    if (const GLint location = glGetUniformLocation (program, "g_BlendMap");
+		location >= 0 && this->m_blendMap.rows > 0) {
+		glUniform4fv (location, static_cast<GLsizei> (this->m_blendMap.rows), this->m_rig.blendMap.data ());
+	    }
+	},
+	[this] () {
+	    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_blendMap.indices);
+	    glDrawElements (GL_TRIANGLES, this->m_blendMap.indexCount, GL_UNSIGNED_SHORT, nullptr);
+	},
+	[pass] () {
+	    for (const char* name : { "a_Position", "a_BlendIndices", "a_TexCoordVec4" }) {
+		if (const GLint location = glGetAttribLocation (pass->getProgramID (), name); location >= 0) {
+		    glDisableVertexAttribArray (location);
+		}
+	    }
+	}
+    );
+    this->m_blendMap.pass = pass;
+
+    this->m_passes.front ()->setTexture (0, this->m_blendMap.albedo);
+
+    if (this->m_puppetClipTargetPass != nullptr && this->m_puppetMeshPass == this->m_passes.front ()) {
+	this->m_puppetClipTargetPass->setTexture (0, this->m_blendMap.albedo);
+    }
+}
+
 void CImage::selectPuppetDraw (const int draw) {
     if (draw < 0 || !this->m_puppetClipping.has_value ()
 	|| static_cast<size_t> (draw) >= this->m_puppetClipping->draws.size ()) {
@@ -1969,6 +2697,16 @@ void CImage::setup () {
     if (this->m_hasPuppetMesh && !this->m_passes.empty ()) {
 	this->m_puppetMeshPass = this->m_passes.front ();
 	this->m_puppetMeshLast = this->m_passes.size () == 1;
+	this->m_materials.puppetVertexAlpha = nullptr;
+
+	if (this->m_puppetVertexAlpha) {
+	    this->m_materials.puppetVertexAlpha = std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
+		.id = -1,
+		.combos = this->puppetVertexAlphaCombos (),
+		.constants = {},
+		.textures = {},
+	    });
+	}
 
 	// effect masks are laid out over the source texture, so effects run on the flat texture first
 	// and the warped mesh is drawn last, sampling their output
@@ -1992,15 +2730,30 @@ void CImage::setup () {
 		})
 	    );
 
-	    this->m_puppetMeshPass = new CPass (
-		*this, std::make_shared<FBOProvider> (this), config, std::nullopt, std::nullopt, std::nullopt
-	    );
+	    this->m_puppetMeshPass = this->m_materials.puppetVertexAlpha != nullptr
+		? new CPass (
+		      *this, std::make_shared<FBOProvider> (this), config, *this->m_materials.puppetVertexAlpha,
+		      std::nullopt, std::nullopt
+		  )
+		: new CPass (
+		      *this, std::make_shared<FBOProvider> (this), config, std::nullopt, std::nullopt, std::nullopt
+		  );
 	    this->m_passes.push_back (this->m_puppetMeshPass);
 	    this->m_puppetMeshLast = true;
+	} else if (this->m_materials.puppetVertexAlpha != nullptr) {
+	    // first pass draws the mesh, rebuilt with the combos
+	    auto* pass = new CPass (
+		*this, std::make_shared<FBOProvider> (this), this->m_passes.front ()->getPass (),
+		*this->m_materials.puppetVertexAlpha, std::nullopt, std::nullopt
+	    );
+	    delete this->m_passes.front ();
+	    this->m_passes.front () = pass;
+	    this->m_puppetMeshPass = pass;
 	}
     }
 
     this->setupPuppetClipping ();
+    this->setupPuppetBlendMap ();
 
     passVisibility.resize (this->m_passes.size (), nullptr);
     passFromEffect.resize (this->m_passes.size (), false);
@@ -2286,6 +3039,11 @@ void CImage::render () {
 	this->updatePuppetSkinning ();
     }
 
+    if (this->m_blendMap.pass != nullptr) {
+	this->m_blendMap.copyPass->render ();
+	this->m_blendMap.pass->render ();
+    }
+
 #if !NDEBUG
     std::string str = "Image ";
 

+ 53 - 0
src/WallpaperEngine/Render/Objects/CImage.h

@@ -31,6 +31,26 @@ class CPass;
 } // namespace WallpaperEngine::Render::Objects::Effects
 
 namespace WallpaperEngine::Render::Objects {
+/** File offsets of the first flag 2 mesh */
+struct PuppetBlendMesh {
+    std::string material;
+    uint32_t rows = 0;
+    uint32_t format = 0;
+    size_t vertices = 0;
+    uint32_t vertexBytes = 0;
+    size_t indices = 0;
+    uint32_t indexBytes = 0;
+};
+
+/** Morph texture of the first mesh (sub_1401FBAE0) */
+struct PuppetMorphTargets {
+    float scale = 0.0f;
+    uint32_t vertexCount = 0;
+    std::vector<glm::vec4> texels;
+    /** some target alpha is below 1 */
+    bool alpha = false;
+};
+
 class CImage final : public CRenderable, public ScriptableObject {
     friend CObject;
 
@@ -194,6 +214,8 @@ private:
     [[nodiscard]] glm::mat4 puppetObjectWorld () const;
     /** Skins the puppet vertices with the current bone matrices and re-uploads them */
     void updatePuppetSkinning ();
+    [[nodiscard]] ComboMap puppetVertexAlphaCombos () const;
+    void updatePuppetVertexAlpha (const std::vector<float>& morphAlpha);
     void setupPuppetGeometryCallback (Effects::CPass* pass) const;
     /** The mask and clipping target passes of a puppet with clipping records, once the mesh pass exists */
     void setupPuppetClipping ();
@@ -204,6 +226,9 @@ private:
     /** sub_14020D6A0: one record's mask into _rt_FullAlphaMask, or multiplied into it through the intermediate */
     void renderPuppetClipMask (const Effects::CPass& meshPass, int record, int draw, bool clear, bool intermediate);
     void selectPuppetDraw (int draw);
+    void loadPuppetBlendMesh (const std::vector<char>& data);
+    /** sub_140209540 albedo buffer */
+    void setupPuppetBlendMap ();
     ResolvedTransform updateGeometryBuffers ();
     [[nodiscard]] glm::vec2 resolveGeometrySize (float sceneWidth, float sceneHeight, glm::vec3& origin) const;
     void updateScenePosition (
@@ -254,6 +279,22 @@ private:
     glm::vec4 m_puppetClipClearColor { 0.0f };
     glm::mat4 m_puppetClipIdentity { 1.0f };
     float m_puppetClipComposeAlpha = 1.0f;
+    /** mesh flag 2 blend map */
+    struct {
+	GLuint vertices = GL_NONE;
+	GLuint indices = GL_NONE;
+	GLsizei indexCount = 0;
+	uint32_t format = 0;
+	uint32_t stride = 0;
+	/** BLENDROWCOUNT */
+	uint32_t rows = 0;
+	std::string material;
+	std::shared_ptr<CFBO> albedo = nullptr;
+	GLuint quad = GL_NONE;
+	glm::mat4 projection { 1.0f };
+	Effects::CPass* copyPass = nullptr;
+	Effects::CPass* pass = nullptr;
+    } m_blendMap;
     mutable bool m_puppetDrawDiagnosticLogged = false;
     mutable bool m_puppetDrawErrorChecked = false;
     bool m_puppetPositionDiagnosticLogged = false;
@@ -268,6 +309,15 @@ private:
 
     PuppetRig m_rig;
     std::vector<GLfloat> m_puppetSkinnedPositions = {};
+    uint32_t m_puppetMeshFlags = 0;
+    uint32_t m_puppetMeshFormat = 0;
+    std::optional<PuppetMorphTargets> m_puppetMorph = std::nullopt;
+    /** per vertex morph texel, nullopt if not morphed */
+    std::vector<std::optional<uint32_t>> m_puppetMorphIndices = {};
+    /** vertex alpha through SKINNING_ALPHA, see setupPuppetGeometryCallback */
+    bool m_puppetVertexAlpha = false;
+    GLuint m_puppetVertexAlphaWeights = GL_NONE;
+    std::vector<GLfloat> m_puppetVertexAlphaData = {};
 
     glm::mat4 m_modelViewProjectionScreen = {};
     glm::mat4 m_modelViewProjectionPass = {};
@@ -348,6 +398,9 @@ private:
 	MaterialUniquePtr clippingMask;
 	MaterialUniquePtr clippingCompose;
 	std::vector<ImageEffectPassOverrideUniquePtr> clippingOverrides = {};
+	ImageEffectPassOverrideUniquePtr puppetVertexAlpha;
+	MaterialUniquePtr blendMap;
+	ImageEffectPassOverrideUniquePtr blendMapOverride;
     } m_materials;
 };
 } // namespace WallpaperEngine::Render::Objects

+ 38 - 1
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -795,7 +795,10 @@ CMesh::CMesh (Wallpapers::CScene& scene, const Mesh& mesh) :
 		continue;
 	    }
 
-	    this->registerProperty (prefix + name, *(*setting)->value);
+	    this->registerProperty (
+		prefix + name, *(*setting)->value,
+		Scripting::Adapters::animationLayerGroup (this->getId (), layerIndex), name
+	    );
 	    scene.getScriptEngine ().setThisObjectFactory (
 		this->getProperties ().at (prefix + name).key, [this, layerIndex] (Scripting::ScriptEngine& engine) {
 		    return Scripting::Adapters::makeAnimationLayerHandle (engine, *this, layerIndex);
@@ -963,7 +966,11 @@ void CMesh::updateAnimation () {
 	return;
     }
 
+    this->m_rig.ropeEnvironment = this->getScene ().getRopeEnvironment ();
     this->m_rig.updatePose (this->getScene ().objectWorldMatrix (this->m_mesh), this);
+    for (const auto& payload : this->m_rig.takeFiredEvents ()) {
+	this->getScene ().getScriptEngine ().dispatchClipEvent (*this, payload);
+    }
     this->m_rig.finishEndedLayers ([this] (size_t serial) {
 	this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
     });
@@ -1144,6 +1151,36 @@ std::optional<glm::mat4> CMesh::getAttachmentMatrix (const std::string& name) co
     return this->m_rig.attachmentMatrix (this->m_rig.findAttachment (name));
 }
 
+uint32_t CMesh::vertexStride (const uint32_t format) {
+    uint32_t stride = 0;
+
+    for (const auto& component : VERTEX_COMPONENTS) {
+	if (format & component.bit) {
+	    stride += component.size;
+	}
+    }
+
+    return stride;
+}
+
+std::optional<uint32_t> CMesh::vertexComponentOffset (const uint32_t format, const uint32_t bit) {
+    uint32_t offset = 0;
+
+    for (const auto& component : VERTEX_COMPONENTS) {
+	if ((format & component.bit) == 0) {
+	    continue;
+	}
+
+	if (component.bit == bit) {
+	    return offset;
+	}
+
+	offset += component.size;
+    }
+
+    return std::nullopt;
+}
+
 const Mesh& CMesh::getMesh () const { return this->m_mesh; }
 
 const glm::mat4& CMesh::getModelMatrix () const { return this->m_modelMatrix; }

+ 4 - 0
src/WallpaperEngine/Render/Objects/CMesh.h

@@ -27,6 +27,10 @@ public:
     void render () override;
 
     [[nodiscard]] const Mesh& getMesh () const;
+    /** Bytes per vertex of an MDL vertex format (sub_1401D9860) */
+    [[nodiscard]] static uint32_t vertexStride (uint32_t format);
+    /** Byte offset of that format bit's component in a vertex */
+    [[nodiscard]] static std::optional<uint32_t> vertexComponentOffset (uint32_t format, uint32_t bit);
     /** 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; }

+ 8 - 6
src/WallpaperEngine/Render/Objects/CParticle.cpp

@@ -1231,8 +1231,9 @@ EmitterFunc CParticle::createBoxEmitter (const ParticleEmitter& emitter) {
 
 	    p.color = m_colorOverride.tint;
 	    p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
-	    p.size = 20.0f * m_particle.instanceOverride.size->value->getFloat ();
-	    p.lifetime = 1.0f * m_particle.instanceOverride.lifetime->value->getFloat ();
+	    // sub_14023B340: new slots start at size 0.5, lifetime 1; instanceoverride only scales the randoms
+	    p.size = 0.5f;
+	    p.lifetime = 1.0f;
 	    p.age = 0.0f;
 	    p.alive = true;
 	    p.frame = -1.0f;
@@ -1416,8 +1417,8 @@ EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
 		p.color *= glm::vec3 (pixel.r, pixel.g, pixel.b) / 255.0f;
 	    }
 	    p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
-	    p.size = 20.0f * m_particle.instanceOverride.size->value->getFloat ();
-	    p.lifetime = 1.0f * m_particle.instanceOverride.lifetime->value->getFloat ();
+	    p.size = 0.5f;
+	    p.lifetime = 1.0f;
 	    p.age = 0.0f;
 	    p.alive = true;
 	    p.frame = -1.0f;
@@ -1445,7 +1446,8 @@ EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
 EmitterFunc CParticle::createSphereEmitter (const ParticleEmitter& emitter) {
     DynamicValue* speedOverride
 	= (m_particle.flags & 0x10) == 0 ? m_particle.instanceOverride.speed->value.get () : nullptr;
-    float lifetime = 1.0f * m_particle.instanceOverride.lifetime->value->getFloat ();
+    // sub_14023B340: lifetime 1 unless lifetimerandom sets it
+    const float lifetime = 1.0f;
 
     // Convert emitter origin from screen space (Y down) to centered space (Y up)
     glm::vec3 transformedEmitterOrigin = emitter.origin;
@@ -1532,7 +1534,7 @@ EmitterFunc CParticle::createSphereEmitter (const ParticleEmitter& emitter) {
 
 	    p.color = m_colorOverride.tint;
 	    p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
-	    p.size = 20.0f * m_particle.instanceOverride.size->value->getFloat ();
+	    p.size = 0.5f;
 	    p.lifetime = lifetime;
 	    p.age = 0.0f;
 	    p.alive = true;

+ 86 - 23
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -1793,11 +1793,52 @@ template <typename T> void CPass::addUniform (const std::string& name, UniformTy
     );
 }
 
+namespace {
+int componentCount (const ShaderVariable& var) {
+    if (var.is<ShaderVariableVector4> ()) {
+	return 4;
+    }
+    if (var.is<ShaderVariableVector3> ()) {
+	return 3;
+    }
+    if (var.is<ShaderVariableVector2> ()) {
+	return 2;
+    }
+    return 1;
+}
+
+int componentCount (GLenum type) {
+    switch (type) {
+	case GL_FLOAT_VEC4:
+	    return 4;
+	case GL_FLOAT_VEC3:
+	    return 3;
+	case GL_FLOAT_VEC2:
+	    return 2;
+	default:
+	    return 1;
+    }
+}
+} // namespace
+
 void CPass::setupShaderVariables () {
+    // a uniform declared differently per stage takes the linked program's type
     for (const auto& cur : this->m_shader->getVertex ().getParameters ()) {
-	if (!this->m_uniforms.contains (cur->getName ())) {
-	    this->addUniform (cur);
+	if (this->m_uniforms.contains (cur->getName ())) {
+	    continue;
 	}
+
+	ShaderVariable* var = cur;
+
+	for (const auto& other : this->m_shader->getFragment ().getParameters ()) {
+	    if (other->getName () == cur->getName () && componentCount (*other) != componentCount (*cur)
+		&& componentCount (this->getDeclaredUniformType (cur->getName ())) == componentCount (*other)) {
+		var = other;
+		break;
+	    }
+	}
+
+	this->addUniform (var);
     }
 
     for (const auto& cur : this->m_shader->getFragment ().getParameters ()) {
@@ -1806,30 +1847,18 @@ void CPass::setupShaderVariables () {
 	}
     }
 
-    // apply material pass constants (e.g. constantshadervalues from the material JSON)
-    for (const auto& [name, value] : this->m_pass.constants) {
-	const auto [vertex, fragment] = this->m_shader->findParameter (name);
+    // material constants, then override constants, which win
+    for (const auto* constants : { &this->m_pass.constants, &this->m_override.constants }) {
+	for (const auto& [name, value] : *constants) {
+	    ShaderVariable* var = this->findActiveParameter (name);
 
-	if (vertex == nullptr && fragment == nullptr) {
-	    continue;
-	}
-
-	ShaderVariable* var = vertex == nullptr ? fragment : vertex;
-	this->addUniform (var, value->value.get ());
-	this->m_constantUniforms.insert (var->getName ());
-    }
-
-    // apply override constants (highest priority, overrides both defaults and pass constants)
-    for (const auto& [name, value] : this->m_override.constants) {
-	const auto [vertex, fragment] = this->m_shader->findParameter (name);
+	    if (var == nullptr) {
+		continue;
+	    }
 
-	if (vertex == nullptr && fragment == nullptr) {
-	    continue;
+	    this->addConstantUniform (var, *value);
+	    this->m_constantUniforms.insert (var->getName ());
 	}
-
-	ShaderVariable* var = vertex == nullptr ? fragment : vertex;
-	this->addUniform (var, value->value.get ());
-	this->m_constantUniforms.insert (var->getName ());
     }
 
     // bind the full-reveal bypass uniform injected by patchXrayFullRevealBypass() (see setupShaders());
@@ -1839,6 +1868,40 @@ void CPass::setupShaderVariables () {
     }
 }
 
+ShaderVariable* CPass::findActiveParameter (const std::string& name) const {
+    const auto [vertex, fragment] = this->m_shader->findParameter (name);
+
+    if (vertex == nullptr || fragment == nullptr || componentCount (*vertex) == componentCount (*fragment)) {
+	return vertex == nullptr ? fragment : vertex;
+    }
+
+    const GLenum declared = this->getDeclaredUniformType (fragment->getName ());
+
+    return declared != GL_NONE && componentCount (declared) == componentCount (*fragment) ? fragment : vertex;
+}
+
+void CPass::addConstantUniform (ShaderVariable* var, const UserSetting& setting) {
+    const DynamicValue& value = *setting.value;
+    const bool scalar = value.getType () == DynamicValue::UnderlyingType::Float
+	|| value.getType () == DynamicValue::UnderlyingType::Int;
+
+    // WE zero-pads constants ("0.7" on a vec4 is 0.7 0 0 0, tests/vecpad); bound user properties still spread
+    if (scalar && componentCount (*var) > 1 && setting.property == nullptr && value.getAnimation () == nullptr) {
+	auto& padded = this->m_paddedConstants.emplace_back (value.getFloat (), 0.0f, 0.0f, 0.0f);
+
+	if (var->is<ShaderVariableVector2> ()) {
+	    this->addUniform (var->getName (), reinterpret_cast<const glm::vec2*> (&padded));
+	} else if (var->is<ShaderVariableVector3> ()) {
+	    this->addUniform (var->getName (), reinterpret_cast<const glm::vec3*> (&padded));
+	} else {
+	    this->addUniform (var->getName (), static_cast<const glm::vec4*> (&padded));
+	}
+	return;
+    }
+
+    this->addUniform (var, &value);
+}
+
 void CPass::addUniform (ShaderVariable* value) {
     // delegates to the (ShaderVariable*, DynamicValue*) overload, which handles the casting
     this->addUniform (value, value);

+ 7 - 0
src/WallpaperEngine/Render/Objects/Effects/CPass.h

@@ -1,5 +1,6 @@
 #pragma once
 
+#include <deque>
 #include <set>
 #include <unordered_map>
 
@@ -206,6 +207,10 @@ private:
     void setupShaderVariables ();
     /** GL type the linked program declares for a uniform (GL_NONE if it has no such active uniform) */
     [[nodiscard]] GLenum getDeclaredUniformType (const std::string& name) const;
+    /** A parameter's declaration from a stage that actually uses it, like WE's reflection check (sub_1400DAB40) */
+    [[nodiscard]] ShaderVariable* findActiveParameter (const std::string& name) const;
+    /** Uploads a constant, a lone number fills only the first component like WE */
+    void addConstantUniform (ShaderVariable* var, const UserSetting& setting);
     void setupUniforms ();
     void setupTextureUniforms ();
     void setupAttributes ();
@@ -280,6 +285,8 @@ private:
     bool m_neutralColor = false;
     // uniforms the pass sets as material or override constants, the renderable values leave these alone
     std::set<std::string> m_constantUniforms;
+    // zero-padded constants, a deque so the uniform pointers stay valid
+    std::deque<glm::vec4> m_paddedConstants;
     std::map<std::string, ReferenceUniformEntry*> m_referenceUniforms = {};
     BlendingMode m_blendingmode = BlendingMode_Normal;
     std::optional<std::pair<DepthtestMode, DepthwriteMode>> m_depthState = std::nullopt;

+ 910 - 0
src/WallpaperEngine/Render/Objects/PuppetIK.cpp

@@ -0,0 +1,910 @@
+#include "PuppetIK.h"
+#include "PuppetPhysics.h"
+
+#include "WallpaperEngine/Data/JSON.h"
+#include "WallpaperEngine/Render/Utils/NoiseUtils.h"
+
+#include <algorithm>
+#include <bit>
+#include <cmath>
+
+#include <glm/gtc/quaternion.hpp>
+#include <glm/gtc/type_ptr.hpp>
+
+using JSON = WallpaperEngine::Data::JSON::JSON;
+
+// wallpaper64.exe 2.8.42 sub_140271910. glm columns hold WE's rows
+
+namespace WallpaperEngine::Render::Objects {
+namespace {
+    glm::vec3 position (const glm::mat4& m) { return glm::vec3 (m[3]); }
+
+    void setPosition (glm::mat4& m, const glm::vec3& p) { m[3] = glm::vec4 (p, m[3].w); }
+
+    // sub_140214EB0, fast inverse sqrt
+    glm::vec4 fastNormalize (const glm::vec4& row) {
+	const float squared = row.w * row.w + row.z * row.z + (row.y * row.y + row.x * row.x);
+	const float guess = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (squared) >> 1));
+	const float inverse = (1.5f - squared * 0.5f * guess * guess) * guess;
+
+	return row * inverse;
+    }
+
+    // shortest arc, w x y z
+    glm::vec4 arc (const glm::vec3& from, const glm::vec3& to) {
+	const float cosine = glm::dot (from, to);
+
+	if (cosine >= 0.99999988f) {
+	    return { 1.0f, 0.0f, 0.0f, 0.0f };
+	}
+
+	if (cosine < -0.99999988f) {
+	    return puppetRotationArc (from, to);
+	}
+
+	const float s = std::sqrt ((cosine + 1.0f) + (cosine + 1.0f));
+
+	return {
+	    s * 0.5f,
+	    (from.y * to.z - from.z * to.y) * (1.0f / s),
+	    (from.z * to.x - from.x * to.z) * (1.0f / s),
+	    (from.x * to.y - from.y * to.x) * (1.0f / s),
+	};
+    }
+
+    // rows of Q * bind
+    void rotateRows (glm::mat4& out, const glm::vec4& q, const glm::mat4& bind) {
+	const glm::mat3 rows = puppetQuatRows (q);
+
+	for (int j = 0; j < 3; j++) {
+	    out[j] = rows[j].x * bind[0] + rows[j].y * bind[1] + rows[j].z * bind[2];
+	}
+    }
+
+    glm::vec4 quatFromRows (const glm::mat4& m) {
+	const glm::quat q = glm::quat_cast (glm::mat3 (glm::vec3 (m[0]), glm::vec3 (m[1]), glm::vec3 (m[2])));
+	return { q.w, q.x, q.y, q.z };
+    }
+
+    const glm::vec3* childDirection (const PuppetIKRig& rig, int bone, int child) {
+	if (bone < 0 || static_cast<size_t> (bone) >= rig.childDirections.size ()) {
+	    return nullptr;
+	}
+
+	const auto& map = rig.childDirections[bone];
+	const auto it = map.find (static_cast<uint32_t> (child));
+	return it == map.end () ? nullptr : &it->second;
+    }
+
+    float length (const PuppetIKRig& rig, int bone) {
+	return bone >= 0 && static_cast<size_t> (bone) < rig.lengths.size () ? rig.lengths[bone] : 0.0f;
+    }
+
+    glm::vec3 transformPoint (const glm::mat4& m, const glm::vec3& p) { return glm::vec3 (m * glm::vec4 (p, 1.0f)); }
+
+    const PuppetBoneIK& endSettings (const std::vector<PuppetBoneIK>& ik, uint32_t bone) {
+	static const PuppetBoneIK none;
+	return bone < ik.size () ? ik[bone] : none;
+    }
+
+    // sub_14026E340: one length constraint sweep over a rope; "ikse" stretches every bone alike
+    void constrainRope (
+	const PuppetIKRig& rig, const PuppetIKEntry& entry, const PuppetBoneIK& end, const glm::mat4& world,
+	const glm::mat4& inverse, std::vector<PuppetRopeJoint>& joints, bool forward
+    ) {
+	const auto& bones = entry.bones;
+	const glm::vec3 span = joints[entry.endBone].current - joints[bones[0]].current;
+	const float distance = std::sqrt ((span.x * span.x + span.y * span.y) + span.z * span.z);
+	float scale = 1.0f;
+
+	if (distance > entry.length && (end.flags & PuppetBoneIK::SolveEnd)) {
+	    scale = distance / entry.length;
+	}
+
+	const bool freeEnd = (end.flags & PuppetBoneIK::FollowParent) != 0;
+	const int count = static_cast<int> (bones.size ()) - (freeEnd ? 0 : 1);
+
+	for (int i = 1; i < count; i++) {
+	    int child;
+	    int parent;
+
+	    if (forward) {
+		child = bones[i];
+		parent = bones[i - 1];
+	    } else {
+		const int k = count - i;
+		child = bones[freeEnd ? k : k + 1];
+		parent = bones[freeEnd ? k - 1 : k];
+	    }
+
+	    const float rest = scale * length (rig, child);
+	    const glm::vec3 from = transformPoint (inverse, joints[parent].current);
+	    const glm::vec3 to = transformPoint (inverse, joints[child].current);
+	    const glm::vec3 offset = to - from;
+	    const float current = std::sqrt ((offset.y * offset.y + offset.x * offset.x) + offset.z * offset.z);
+	    const float miss = rest - current;
+
+	    if (std::fabs (miss) <= 0.001f) {
+		continue;
+	    }
+
+	    const glm::vec3 direction = current <= 0.0099999998f ? glm::vec3 (0.707f, 0.707f, 0.0f) : offset / current;
+
+	    if (forward && i == 1) {
+		joints[child].current = transformPoint (world, to + direction * miss);
+	    } else if (!forward && i == 1) {
+		joints[parent].current = transformPoint (world, from - direction * miss);
+	    } else {
+		const float half = miss * 0.5f;
+		joints[child].current = transformPoint (world, to + direction * half);
+		joints[parent].current = transformPoint (world, from - direction * half);
+	    }
+	}
+    }
+    // WE's row major helpers
+    struct Euler {
+	float a, b, c;
+    };
+
+    // sub_1401E23D0
+    Euler eulerOf (const glm::mat4& matrix) {
+	const float* m = glm::value_ptr (matrix);
+	const float a = std::atan2 (m[1], m[0]);
+	const float b = std::atan2 (-m[2], std::sqrt (m[6] * m[6] + m[10] * m[10]));
+	const float s = std::sin (a);
+	const float c = std::cos (a);
+	return { a, b, std::atan2 (s * m[8] - c * m[9], c * m[5] - s * m[4]) };
+    }
+
+    // sub_140215020, rows only
+    glm::mat4 rotationOf (const Euler& e) {
+	const float ca = std::cos (e.a), sa = std::sin (e.a);
+	const float cb = std::cos (e.b), sb = std::sin (e.b);
+	const float cc = std::cos (e.c), sc = std::sin (e.c);
+	glm::mat4 out (0.0f);
+	float* m = glm::value_ptr (out);
+	m[0] = cb * ca;
+	m[1] = cb * sa;
+	m[2] = -sb;
+	m[4] = sb * ca * sc - cc * sa;
+	m[5] = sb * sa * sc + cc * ca;
+	m[6] = sc * cb;
+	m[8] = cc * ca * sb + sc * sa;
+	m[9] = cc * sa * sb - sc * ca;
+	m[10] = cc * cb;
+	m[15] = 1.0f;
+	return out;
+    }
+
+    // sub_1401E24B0
+    float rowLength (const glm::vec4& r) { return std::sqrt ((r.w * r.w + r.z * r.z) + (r.y * r.y + r.x * r.x)); }
+
+    glm::mat4 withPosition (glm::mat4 m, const glm::vec3& p) {
+	m[3] = glm::vec4 (p, 1.0f);
+	return m;
+    }
+
+    // sub_14026DCE0, false when parallel
+    bool closestPoints (
+	const glm::vec3& p1, const glm::vec3& d1, const glm::vec3& p2, const glm::vec3& d2, glm::vec3& onSecond
+    ) {
+	const float a = (d1.x * d1.x + d1.y * d1.y) + d1.z * d1.z;
+	const float b = (d1.x * d2.x + d1.y * d2.y) + d1.z * d2.z;
+	const float c = (d2.x * d2.x + d2.y * d2.y) + d2.z * d2.z;
+	const float det = a * c - b * b;
+
+	if (det == 0.0f) {
+	    return false;
+	}
+
+	const glm::vec3 r = p1 - p2;
+	const float d = (d1.x * r.x + d1.y * r.y) + d1.z * r.z;
+	const float e = (d2.y * r.y + d2.x * r.x) + d2.z * r.z;
+	onSecond = p2 + d2 * ((e * a - d * b) / det);
+	return true;
+    }
+} // namespace
+
+glm::mat4 blendPuppetTransform (const glm::mat4& from, const glm::mat4& to, float weight) {
+    constexpr float twoPi = 6.2831855f;
+    constexpr float pi = 3.1415927f;
+    Euler e = eulerOf (from);
+    Euler t = eulerOf (to);
+
+    for (float* angle : { &e.a, &e.b, &e.c, &t.a, &t.b, &t.c }) {
+	*angle = std::fmod (*angle, twoPi);
+    }
+
+    // WE only subtracts pi
+    if (t.c - e.c > pi) {
+	t.c -= pi;
+    }
+    if (t.b - e.b > pi) {
+	t.b -= pi;
+    }
+    if (t.a - e.a > pi) {
+	t.a -= pi;
+    }
+
+    const float keep = 1.0f - weight;
+    const glm::mat4 rotation = rotationOf (
+	{
+	    e.a * keep + t.a * weight,
+	    e.b * keep + t.b * weight,
+	    e.c * keep + t.c * weight,
+	}
+    );
+    glm::mat4 out (1.0f);
+
+    for (int i = 0; i < 3; i++) {
+	out[i] = rotation[i] * (rowLength (from[i]) * keep + rowLength (to[i]) * weight);
+    }
+
+    out[3] = glm::vec4 (position (from) * keep + position (to) * weight, 1.0f);
+    return out;
+}
+
+void applyPuppetChainConstraints (
+    const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<float>& weights,
+    std::vector<glm::mat4>& model, std::vector<glm::mat4>& extras
+) {
+    const auto validBone = [&model] (int bone) { return bone >= 0 && static_cast<size_t> (bone) < model.size (); };
+
+    for (const uint32_t extra : chain.extras) {
+	if (extra >= extras.size () || extra >= rig.extraRules.size () || extra >= rig.extraBones.size ()) {
+	    continue;
+	}
+
+	for (const auto& rule : rig.extraRules[extra]) {
+	    if (!validBone (static_cast<int> (rule.target))) {
+		continue;
+	    }
+
+	    const float weight = rule.weight < weights.size () ? weights[rule.weight] : 0.0f;
+	    const glm::mat4& target = model[rule.target];
+	    glm::mat4& controller = extras[extra];
+
+	    if ((rule.flags & 0x10000) == 0 && (rule.flags & 2) == 0) {
+		if (rule.flags & 1) {
+		    setPosition (controller, position (controller) * (1.0f - weight) + position (target) * weight);
+		} else {
+		    controller = blendPuppetTransform (controller, target, weight);
+		}
+
+		continue;
+	    }
+
+	    // once per entry ending at the extra's bone
+	    const glm::vec3 axis = glm::vec3 (target[0]) * (1.0f / rowLength (target[0]));
+	    const glm::vec3 origin = position (target);
+
+	    for (const auto& link : chain.links) {
+		for (const auto& entry : link.entries) {
+		    if (entry.endBone != rig.extraBones[extra] || entry.bones.empty ()
+			|| std::ranges::any_of (entry.bones, [&validBone] (int bone) { return !validBone (bone); })) {
+			continue;
+		    }
+
+		    const glm::vec3 offset = position (controller) - origin;
+		    const float along = (offset.y * axis.y + offset.x * axis.x) + offset.z * axis.z;
+
+		    if (rule.flags & 0x10000) {
+			// "chainalignaxis"
+			const glm::vec3 fromRoot = origin - position (model[entry.bones[0]]);
+			const float reach
+			    = std::sqrt ((fromRoot.x * fromRoot.x + fromRoot.y * fromRoot.y) + fromRoot.z * fromRoot.z);
+
+			if (reach >= entry.length || along < 0.0f) {
+			    controller = blendPuppetTransform (controller, withPosition (controller, origin), weight);
+			    continue;
+			}
+
+			float distance = std::min (entry.length - reach, along);
+			controller = blendPuppetTransform (
+			    controller, withPosition (target, origin + axis * distance), weight
+			);
+			float remaining = along;
+
+			for (int i = static_cast<int> (entry.bones.size ()) - 2; i > 0; i--) {
+			    const float next = length (rig, entry.bones[i + 1]);
+			    remaining -= next;
+
+			    if (remaining < 0.0f) {
+				break;
+			    }
+
+			    const float past = std::max (remaining - rule.start, 0.0f);
+			    const float ramp = past / rule.range >= 1.0f ? 1.0f : past / rule.range;
+
+			    if (ramp <= 0.0f) {
+				break;
+			    }
+
+			    distance -= next;
+
+			    if (distance < 0.0f) {
+				break;
+			    }
+
+			    glm::mat4& joint = model[entry.bones[i]];
+			    joint = blendPuppetTransform (
+				joint, withPosition (target, origin + axis * distance), ramp * weight
+			    );
+			}
+		    } else {
+			// "axis"
+			const glm::vec3 across = offset - axis * along;
+			const glm::vec3 direction = across
+			    * (1.0f / std::sqrt ((across.x * across.x + across.y * across.y) + across.z * across.z));
+			glm::vec3 onAxis;
+
+			if (closestPoints (position (controller), direction, origin, axis, onAxis)) {
+			    controller = blendPuppetTransform (controller, withPosition (controller, onAxis), weight);
+			}
+		    }
+		}
+	    }
+	}
+    }
+}
+
+void limitPuppetJointDirection (
+    const PuppetBoneIK& settings, const glm::vec3& joint, const glm::vec3& parent, glm::vec3& direction
+) {
+    const glm::vec3 fromParent = joint - parent;
+    const float parentLength
+	= std::sqrt ((fromParent.y * fromParent.y + fromParent.x * fromParent.x) + fromParent.z * fromParent.z);
+    glm::mat4 frame (1.0f);
+    const glm::mat3 rows
+	= puppetQuatRows (puppetRotationArc (glm::vec3 (1.0f, 0.0f, 0.0f), fromParent * (1.0f / parentLength)));
+
+    for (int i = 0; i < 3; i++) {
+	frame[i] = glm::vec4 (rows[i], 0.0f);
+    }
+
+    const float flat = std::sqrt ((direction.x * direction.x + direction.y * direction.y) + 0.0f);
+    const glm::vec3 local
+	= glm::vec3 (glm::inverse (frame) * glm::vec4 (direction.x / flat, direction.y / flat, 0.0f / flat, 1.0f));
+    const float angle = std::atan2 (local.y, local.x);
+    float turn = settings.minAngle > angle ? -(angle - settings.minAngle) : 0.0f;
+
+    if (angle > settings.maxAngle) {
+	const float back = settings.maxAngle - angle;
+
+	if (turn == 0.0f || std::fabs (turn) > std::fabs (back)) {
+	    turn = back;
+	}
+    }
+
+    if (turn == 0.0f) {
+	return;
+    }
+
+    const float c = std::cos (turn);
+    const float s = std::sin (turn);
+    const glm::vec3 turned (c * local.x - s * local.y, s * local.x + c * local.y, local.z);
+    const glm::vec3 world = glm::vec3 (frame * glm::vec4 (turned, 1.0f)) * flat;
+    direction.x = world.x;
+    direction.y = world.y;
+}
+
+bool PuppetRopeEnvironment::windAt (const glm::vec3& position, glm::vec3& force) const {
+    if (!this->wind) {
+	return false;
+    }
+
+    // zero width gives NaN noise in WE, which maxes to 0
+    float noise = 0.0f;
+
+    if (this->width > 0.0f) {
+	noise = std::max (0.0f, Utils::simplexNoise2D (this->clock, position.x / this->width * 10.0f));
+    }
+
+    force = noise * this->windDirection * this->windStrength;
+    return true;
+}
+
+void stepPuppetRopeChain (
+    const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<PuppetBoneIK>& ik,
+    std::vector<glm::mat4>& model, const std::vector<glm::mat4>& extras, const glm::mat4& world,
+    std::vector<PuppetRopeJoint>& joints, const PuppetRopeEnvironment& environment, float dt
+) {
+    const auto valid = [&model, &joints] (int bone) {
+	return bone >= 0 && static_cast<size_t> (bone) < model.size () && static_cast<size_t> (bone) < joints.size ();
+    };
+    const glm::mat4 inverse = glm::inverse (world);
+    const float dt2 = dt * dt;
+
+    for (auto link = chain.links.rbegin (); link != chain.links.rend (); ++link) {
+	for (const auto& entry : link->entries) {
+	    if ((entry.flags & 4) == 0 || entry.bones.empty () || !valid (static_cast<int> (link->bone))
+		|| !valid (static_cast<int> (entry.endBone))
+		|| std::ranges::any_of (entry.bones, [&valid] (int bone) { return !valid (bone); })) {
+		continue;
+	    }
+
+	    const PuppetBoneIK& end = endSettings (ik, entry.endBone);
+	    const glm::vec3 root = position (model[link->bone]);
+	    glm::vec3 target = position (model[entry.endBone]);
+
+	    if (entry.flags & 1) {
+		if (const auto it = rig.targets.find (entry.endBone);
+		    it != rig.targets.end () && it->second < extras.size ()) {
+		    target = position (extras[it->second]);
+		}
+	    }
+
+	    // without "ikse" the rope can't stretch
+	    if ((end.flags & PuppetBoneIK::SolveEnd) == 0) {
+		const glm::vec3 offset = target - root;
+		const float distance = std::sqrt ((offset.x * offset.x + offset.y * offset.y) + offset.z * offset.z);
+
+		if (distance > entry.length) {
+		    target = offset / distance * entry.length + root;
+		}
+	    }
+
+	    joints[link->bone].current = transformPoint (world, root);
+	    int count = static_cast<int> (entry.bones.size ());
+
+	    if ((end.flags & PuppetBoneIK::FollowParent) == 0) {
+		setPosition (model[entry.endBone], target);
+		joints[entry.endBone].current = transformPoint (world, target);
+		count--;
+	    }
+
+	    if (!joints[link->bone].started) {
+		joints[link->bone].started = true;
+
+		for (int i = 1; i < count; i++) {
+		    auto& joint = joints[entry.bones[i]];
+		    joint.current = transformPoint (world, position (model[entry.bones[i]]));
+		    joint.previous = joint.current;
+		}
+	    }
+
+	    for (int i = 1; i < count; i++) {
+		const int bone = entry.bones[i];
+		auto& joint = joints[bone];
+		const glm::vec3 current = joint.current;
+		const glm::vec3 back = joint.previous - current;
+		glm::vec3 next = (current + current) - joint.previous;
+
+		// "tf" damping
+		if (dt2 > 0.00000011920929f && end.friction > 0.0099999998f
+		    && (back.x * back.x + back.y * back.y) + back.z * back.z > 0.000099999997f) {
+		    next += back * dt2 * (1.0f / dt2) * end.friction;
+		}
+
+		glm::vec3 force (0.0f);
+
+		if (end.flags & PuppetBoneIK::Gravity) {
+		    force = end.mass * environment.gravity;
+		}
+
+		if (glm::vec3 wind; environment.windAt (next, wind)) {
+		    force += wind;
+		}
+
+		next += force * dt2;
+		joint.previous = current;
+		joint.current = next;
+		setPosition (model[bone], transformPoint (inverse, next));
+	    }
+	}
+    }
+}
+
+PuppetBoneIK PuppetBoneIK::parse (const std::string& text) {
+    PuppetBoneIK result;
+    const JSON json = JSON::parse (text, nullptr, false);
+
+    if (!json.is_object ()) {
+	return result;
+    }
+
+    const auto isTrue = [&json] (const char* key) {
+	const auto it = json.find (key);
+	return it != json.end () && it->is_boolean () && it->get<bool> ();
+    };
+
+    // only "ik" bones, except the "ikce" flag
+    if (isTrue ("ikce")) {
+	result.flags |= Constrained;
+    }
+
+    if (!isTrue ("ik")) {
+	// no limits for simulated bones
+	if ((result.flags & Constrained) && !((isTrue ("se") || isTrue ("re")) && (isTrue ("r") || isTrue ("t")))) {
+	    if (const auto it = json.find ("ikrminl"); it != json.end () && it->is_number ()) {
+		result.minAngle = it->get<float> ();
+	    }
+
+	    if (const auto it = json.find ("ikrmaxl"); it != json.end () && it->is_number ()) {
+		result.maxAngle = it->get<float> ();
+	    }
+	}
+
+	return result;
+    }
+
+    result.flags |= Enabled;
+    result.flags |= isTrue ("ge") ? Gravity : 0;
+
+    if (const auto it = json.find ("m"); it != json.end () && it->is_number ()) {
+	result.mass = it->get<float> ();
+    }
+
+    if (const auto it = json.find ("tf"); it != json.end () && it->is_number ()) {
+	result.friction = it->get<float> ();
+    }
+
+    // non-simulated bones use (tf / 100)^2
+    if (!((isTrue ("se") || isTrue ("re")) && (isTrue ("r") || isTrue ("t")))) {
+	const float scaled = (result.friction / 100.0f) * (result.friction / 100.0f);
+	result.friction = scaled >= 0.0f ? std::min (scaled, 1.0f) : 0.0f;
+    }
+
+    if (const auto it = json.find ("ikd"); it != json.end () && it->is_number ()) {
+	result.depth = std::max (it->get<int> (), 1);
+    }
+
+    result.flags |= isTrue ("ikg") ? Grounded : 0;
+
+    if (isTrue ("ikr")) {
+	result.flags |= RotateToTarget;
+
+	if (const auto it = json.find ("ikrd"); it != json.end () && it->is_number ()) {
+	    result.rotateDistance = std::max (it->get<float> (), 1.0f);
+	}
+    }
+
+    result.flags |= isTrue ("ikse") ? SolveEnd : 0;
+    result.flags |= isTrue ("ikfe") ? FollowParent : 0;
+
+    return result;
+}
+
+void solvePuppetIKChain (
+    const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<int>& parents,
+    const std::vector<PuppetBoneIK>& ik, std::vector<glm::mat4>& model, const std::vector<glm::mat4>& extras,
+    const std::vector<glm::mat4>& bindModel, const glm::mat4& world, std::vector<PuppetRopeJoint>& joints
+) {
+    const auto valid = [&model, &joints] (int bone) {
+	return bone >= 0 && static_cast<size_t> (bone) < model.size () && static_cast<size_t> (bone) < joints.size ();
+    };
+
+    const auto extraOf = [&extras] (const std::unordered_map<uint32_t, uint32_t>& map, uint32_t bone) {
+	const auto it = map.find (bone);
+	return it != map.end () && it->second < extras.size () ? &extras[it->second] : nullptr;
+    };
+
+    for (const auto& link : chain.links) {
+	for (const auto& entry : link.entries) {
+	    if (!valid (static_cast<int> (link.bone)) || !valid (static_cast<int> (entry.endBone))
+		|| std::ranges::any_of (entry.bones, [&valid] (int bone) { return !valid (bone); })) {
+		return;
+	    }
+	}
+    }
+
+    if (!valid (static_cast<int> (chain.root))) {
+	return;
+    }
+
+    const glm::vec3 root = position (model[chain.root]);
+    const glm::mat4 inverse = glm::inverse (world);
+
+    for (int iteration = 0; iteration < 10; iteration++) {
+	// forward pass
+	for (auto link = chain.links.rbegin (); link != chain.links.rend (); ++link) {
+	    glm::vec3 sum (0.0f);
+	    float count = 0.0f;
+
+	    for (auto entry = link->entries.rbegin (); entry != link->entries.rend (); ++entry) {
+		if (entry->flags & 4) {
+		    constrainRope (rig, *entry, endSettings (ik, entry->endBone), world, inverse, joints, false);
+		    continue;
+		}
+
+		const glm::vec3 start = position (model[link->bone]);
+		const glm::mat4* targetExtra = (entry->flags & 1) ? extraOf (rig.targets, entry->endBone) : nullptr;
+		glm::vec3 target = targetExtra != nullptr ? position (*targetExtra) : position (model[entry->endBone]);
+		const glm::vec3 offset = target - start;
+		float distance = std::sqrt (glm::dot (offset, offset));
+		const glm::vec3 direction = offset / distance;
+
+		if (entry->minReach > 0.0f && entry->minReach > distance) {
+		    target += (entry->minReach - distance) * direction;
+		    distance = entry->minReach;
+		}
+
+		glm::vec3 pole (0.0f);
+
+		if (const auto* poleExtra = extraOf (rig.poles, entry->endBone); poleExtra != nullptr) {
+		    const glm::vec3 toPole = position (*poleExtra) - target;
+		    pole = toPole - direction * glm::dot (toPole, direction);
+		}
+
+		setPosition (model[entry->endBone], target);
+		const int last = static_cast<int> (entry->bones.size ()) - 1;
+
+		if (distance < entry->length || (entry->flags & 2)) {
+		    // bend in the plane of the target and the pole
+		    const float poleSquared = glm::dot (pole, pole);
+		    const glm::vec3 normal (
+			direction.y * pole.z - direction.z * pole.y, direction.z * pole.x - direction.x * pole.z,
+			direction.x * pole.y - direction.y * pole.x
+		    );
+		    const float normalLength = std::sqrt (glm::dot (normal, normal));
+		    float walked = 0.0f;
+
+		    for (int i = last; i > 0; i--) {
+			const int bone = entry->bones[i];
+			const int joint = entry->bones[i - 1];
+			const glm::vec3 base = position (model[bone]);
+			glm::vec3 toJoint = position (model[joint]) - base;
+
+			if (i > 1 && static_cast<size_t> (joint) < ik.size ()
+			    && (ik[joint].flags & PuppetBoneIK::Constrained) && valid (parents[joint])) {
+			    const float squared
+				= (toJoint.x * toJoint.x + toJoint.y * toJoint.y) + toJoint.z * toJoint.z;
+			    glm::vec3 forward = -(toJoint * (1.0f / std::sqrt (squared)));
+			    limitPuppetJointDirection (
+				ik[joint], position (model[joint]), position (model[parents[joint]]), forward
+			    );
+			    toJoint = -forward;
+			}
+
+			if (i == last || entry->length * 0.5f > walked + length (rig, bone)) {
+			    if (poleSquared > 0.0099999998f) {
+				const glm::vec3 axis = normal * (1.0f / normalLength);
+				toJoint -= glm::dot (toJoint, axis) * axis;
+			    }
+
+			    const float side = glm::dot (toJoint, pole);
+
+			    if (side < 0.0f) {
+				toJoint -= (pole + pole) * side;
+			    }
+			}
+
+			const float jointLength = std::sqrt (glm::dot (toJoint, toJoint));
+			setPosition (model[joint], toJoint * (1.0f / jointLength) * length (rig, bone) + base);
+			walked += length (rig, bone);
+		    }
+		} else {
+		    // out of reach
+		    for (int i = last; i > 0; i--) {
+			const int bone = entry->bones[i];
+			setPosition (
+			    model[entry->bones[i - 1]], position (model[bone]) - length (rig, bone) * direction
+			);
+		    }
+		}
+
+		count += 1.0f;
+		sum += position (model[link->bone]);
+	    }
+
+	    if (count > 0.0f) {
+		setPosition (model[link->bone], sum / count);
+	    }
+	}
+
+	// first pass: "chainalignaxis" mirrors joints on the wrong side of the axis plane, 32 steps max
+	if (iteration == 0) {
+	    for (const uint32_t extra : chain.extras) {
+		if (extra >= rig.extraRules.size () || extra >= rig.extraBones.size ()) {
+		    continue;
+		}
+
+		for (const auto& rule : rig.extraRules[extra]) {
+		    if ((rule.flags & 0x10000) == 0 || !valid (static_cast<int> (rule.target))) {
+			continue;
+		    }
+
+		    const glm::mat4& target = model[rule.target];
+		    const float inverse = 1.0f
+			/ std::sqrt ((target[0].w * target[0].w + target[0].z * target[0].z)
+				     + (target[0].y * target[0].y + target[0].x * target[0].x));
+		    const glm::vec3 axis = glm::vec3 (target[0]) * inverse;
+
+		    for (const auto& link : chain.links) {
+			for (const auto& entry : link.entries) {
+			    const int n = static_cast<int> (entry.bones.size ());
+
+			    if (entry.endBone != rig.extraBones[extra] || n <= 2) {
+				continue;
+			    }
+
+			    const glm::vec3 fromRoot = position (target) - position (model[entry.bones[0]]);
+			    const float full = std::sqrt (
+				(fromRoot.x * fromRoot.x + fromRoot.y * fromRoot.y) + fromRoot.z * fromRoot.z
+			    );
+			    float distance = full;
+
+			    for (int k = 1, budget = 32; budget > 0; budget--) {
+				distance -= length (rig, entry.bones[k]);
+
+				if (distance < 0.0f) {
+				    break;
+				}
+
+				const glm::vec3 previous = position (model[entry.bones[k - 1]]);
+				const glm::vec3 span = position (model[entry.bones[k + 1]]) - previous;
+				const glm::vec3 side (
+				    axis.z * span.y - axis.y * span.z, axis.x * span.z - axis.z * span.x,
+				    axis.y * span.x - axis.x * span.y
+				);
+				const glm::vec3 normal (
+				    side.y * span.z - side.z * span.y, side.z * span.x - side.x * span.z,
+				    side.x * span.y - side.y * span.x
+				);
+				const float squared = normal.z * normal.z + (normal.x * normal.x + normal.y * normal.y);
+
+				if (squared >= 0.0099999998f) {
+				    const glm::vec3 unit = normal * (1.0f / std::sqrt (squared));
+				    const glm::vec3 point = position (model[entry.bones[k]]);
+				    const glm::vec3 offset = point - previous;
+				    const float depth = (unit.x * offset.x + unit.y * offset.y) + offset.z * unit.z;
+
+				    if (depth > 0.00000011920929f) {
+					setPosition (model[entry.bones[k]], point - (unit * depth + unit * depth));
+					distance = full;
+					k = 1;
+				    }
+				}
+
+				if (k++ + 2 >= n) {
+				    break;
+				}
+			    }
+			}
+		    }
+		}
+	    }
+	}
+
+	// backward pass, done within sqrt (0.1)
+	bool reached = true;
+
+	for (const auto& link : chain.links) {
+	    for (const auto& entry : link.entries) {
+		if (entry.flags & 4) {
+		    constrainRope (rig, entry, endSettings (ik, entry.endBone), world, inverse, joints, true);
+		    continue;
+		}
+
+		const bool fixedRoot = link.bone == chain.root && parents[chain.root] != -1;
+		setPosition (model[link.bone], fixedRoot ? root : position (model[link.bone]));
+
+		for (size_t i = 0; i + 1 < entry.bones.size (); i++) {
+		    const glm::vec3 base = position (model[entry.bones[i]]);
+		    const glm::vec3 toNext = position (model[entry.bones[i + 1]]) - base;
+		    glm::vec3 direction = toNext * (1.0f / std::sqrt (glm::dot (toNext, toNext)));
+		    const int bone = entry.bones[i];
+
+		    // sub_14026DF30
+		    if (i > 0 && static_cast<size_t> (bone) < ik.size () && (ik[bone].flags & PuppetBoneIK::Constrained)
+			&& valid (parents[bone])) {
+			limitPuppetJointDirection (ik[bone], base, position (model[parents[bone]]), direction);
+		    }
+
+		    setPosition (model[entry.bones[i + 1]], length (rig, entry.bones[i + 1]) * direction + base);
+		}
+
+		if (entry.flags & 1) {
+		    if (const auto* target = extraOf (rig.targets, entry.endBone); target != nullptr) {
+			const glm::vec3 miss = position (model[entry.endBone]) - position (*target);
+
+			if (glm::dot (miss, miss) > 0.1f) {
+			    reached = false;
+			}
+		    }
+		}
+	    }
+	}
+
+	if (reached) {
+	    break;
+	}
+    }
+
+    // rotate joints from bind pose onto the solved directions
+    for (const auto& link : chain.links) {
+	const bool shared = link.entries.size () != 1;
+
+	for (const auto& entry : link.entries) {
+	    for (size_t i = shared ? 1 : 0; i + 1 < entry.bones.size (); i++) {
+		const int bone = entry.bones[i];
+		const int child = entry.bones[i + 1];
+		const glm::vec3* rest = childDirection (rig, bone, child);
+
+		if (rest == nullptr) {
+		    continue;
+		}
+
+		const glm::vec3 toChild = position (model[child]) - position (model[bone]);
+		const glm::vec3 direction = toChild * (1.0f / std::sqrt (glm::dot (toChild, toChild)));
+		rotateRows (model[bone], arc (*rest, direction), bindModel[bone]);
+	    }
+
+	    if ((entry.flags & 1) == 0) {
+		continue;
+	    }
+
+	    const uint32_t end = entry.endBone;
+	    const uint32_t endFlags = end < ik.size () ? ik[end].flags : 0;
+
+	    if (endFlags & PuppetBoneIK::FollowParent) {
+		if (entry.bones.size () > 2) {
+		    const glm::mat4& before = model[entry.bones[entry.bones.size () - 2]];
+		    model[end][0] = before[0];
+		    model[end][1] = before[1];
+		    model[end][2] = before[2];
+		}
+		continue;
+	    }
+
+	    const glm::mat4* target = extraOf (rig.targets, end);
+
+	    if (target == nullptr) {
+		continue;
+	    }
+
+	    glm::mat4 rows (1.0f);
+	    rows[0] = fastNormalize ((*target)[0]);
+	    rows[1] = fastNormalize ((*target)[1]);
+	    rows[2] = fastNormalize ((*target)[2]);
+
+	    // "ikr": turn short ends towards the target
+	    if (endFlags & PuppetBoneIK::RotateToTarget) {
+		const glm::vec3 miss = position (*target) - position (model[end]);
+		const float squared = glm::dot (miss, miss);
+
+		if (squared > 1.0f) {
+		    const float distance = std::sqrt (squared);
+		    const float t = std::min ((distance - 1.0f) / ik[end].rotateDistance, 1.0f);
+		    const glm::vec4 towards = puppetRotationArc (glm::vec3 (1.0f, 0.0f, 0.0f), miss / distance);
+		    const glm::mat3 turned = puppetQuatRows (puppetSlerp (quatFromRows (rows), towards, t));
+
+		    rows[0] = glm::vec4 (turned[0], 0.0f);
+		    rows[1] = glm::vec4 (turned[1], 0.0f);
+		    rows[2] = glm::vec4 (turned[2], 0.0f);
+		}
+	    }
+
+	    model[end][0] = rows[0];
+	    model[end][1] = rows[1];
+	    model[end][2] = rows[2];
+	}
+
+	// average the arcs of several entries
+	if (!shared || link.entries.empty ()) {
+	    continue;
+	}
+
+	glm::vec4 average (1.0f, 0.0f, 0.0f, 0.0f);
+	const float weight = 1.0f / static_cast<float> (link.entries.size ());
+
+	for (const auto& entry : link.entries) {
+	    if (entry.bones.size () < 2) {
+		continue;
+	    }
+
+	    const glm::vec3* rest = childDirection (rig, static_cast<int> (link.bone), entry.bones[1]);
+
+	    if (rest == nullptr) {
+		continue;
+	    }
+
+	    const glm::vec3 toChild = position (model[entry.bones[1]]) - position (model[link.bone]);
+	    const glm::vec3 direction = toChild * (1.0f / std::sqrt (glm::dot (toChild, toChild)));
+	    average = puppetSlerp (average, puppetRotationArc (*rest, direction), weight);
+	}
+
+	rotateRows (model[link.bone], average, bindModel[link.bone]);
+    }
+}
+} // namespace WallpaperEngine::Render::Objects

+ 129 - 0
src/WallpaperEngine/Render/Objects/PuppetIK.h

@@ -0,0 +1,129 @@
+#pragma once
+
+#include <cstdint>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <glm/glm.hpp>
+
+namespace WallpaperEngine::Render::Objects {
+/** A bone's IK JSON settings (2.8.42 sub_140265C30) */
+struct PuppetBoneIK {
+    enum Flags : uint32_t {
+	Gravity = 0x4,
+	Grounded = 0x20,
+	RotateToTarget = 0x40,
+	SolveEnd = 0x80,
+	FollowParent = 0x100,
+	Enabled = 0x4000,
+	Constrained = 0x8000,
+    };
+
+    uint32_t flags = 0;
+    int depth = 2;
+    float rotateDistance = 50.0f;
+    /** "ikrminl"/"ikrmaxl" in radians, "ikce" joints only */
+    float minAngle = 0.0f;
+    float maxAngle = 0.0f;
+    /** "m" gravity scale, "tf" friction */
+    float mass = 1000.0f;
+    float friction = 0.0f;
+
+    static PuppetBoneIK parse (const std::string& json);
+};
+
+/** Scene gravity and wind (sub_1401988E0, sub_140198910) */
+struct PuppetRopeEnvironment {
+    glm::vec3 gravity = glm::vec3 (0.0f, -1.0f, 0.0f);
+    bool wind = false;
+    glm::vec3 windDirection = glm::vec3 (0.0f);
+    float windStrength = 0.0f;
+    /** wind noise runs over (clock, x / width * 10) */
+    float clock = 0.0f;
+    float width = 0.0f;
+
+    [[nodiscard]] bool windAt (const glm::vec3& position, glm::vec3& force) const;
+};
+
+/** P+952, per bone rope joint in world space */
+struct PuppetRopeJoint {
+    glm::vec3 current = glm::vec3 (0.0f);
+    glm::vec3 previous = glm::vec3 (0.0f);
+    bool started = false;
+};
+
+/** MDLS v4 chain entry: the bones from the link bone to the end bone */
+struct PuppetIKEntry {
+    uint32_t endBone = 0;
+    /** 1 targeted, 2 always bend, 4 rope */
+    uint32_t flags = 0;
+    float length = 0.0f;
+    float minReach = 0.0f;
+    std::vector<int> bones;
+};
+
+struct PuppetIKLink {
+    uint32_t bone = 0;
+    std::vector<PuppetIKEntry> entries;
+};
+
+/** puppet +272 */
+struct PuppetIKChain {
+    uint32_t root = 0;
+    /** chain +32 */
+    std::vector<uint32_t> extras;
+    std::vector<PuppetIKLink> links;
+};
+
+/** MDLS constraint. Flags: 1 "origin", 2 "axis", 0x10000 "chainalignaxis" */
+struct PuppetConstraintRule {
+    uint32_t flags = 0;
+    uint32_t weight = 0;
+    uint32_t target = 0;
+    /** flags & 2 only */
+    float start = 0.0f;
+    float range = 0.00000011920929f;
+};
+
+/** MDLS v4 IK data */
+struct PuppetIKRig {
+    std::vector<float> lengths;
+    /** per bone: child -> rest direction */
+    std::vector<std::unordered_map<uint32_t, glm::vec3>> childDirections;
+    std::unordered_map<uint32_t, uint32_t> targets;
+    std::unordered_map<uint32_t, uint32_t> poles;
+    std::vector<PuppetIKChain> chains;
+    /** extra +96, +104 */
+    std::vector<uint32_t> extraBones;
+    std::vector<std::vector<PuppetConstraintRule>> extraRules;
+};
+
+/** Blends via WE's euler angles, row lengths and position */
+glm::mat4 blendPuppetTransform (const glm::mat4& from, const glm::mat4& to, float weight);
+
+/** sub_14026F4C0 */
+void applyPuppetChainConstraints (
+    const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<float>& weights,
+    std::vector<glm::mat4>& model, std::vector<glm::mat4>& extras
+);
+
+/** sub_14026DF30: clamps an "ikce" joint's x/y direction to its limits */
+void limitPuppetJointDirection (
+    const PuppetBoneIK& settings, const glm::vec3& joint, const glm::vec3& parent, glm::vec3& direction
+);
+
+/** sub_14026EB60: Verlet rope step in world space, end pinned unless "ikfe" */
+void stepPuppetRopeChain (
+    const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<PuppetBoneIK>& ik,
+    std::vector<glm::mat4>& model, const std::vector<glm::mat4>& extras, const glm::mat4& world,
+    std::vector<PuppetRopeJoint>& joints, const PuppetRopeEnvironment& environment, float dt
+);
+
+/** sub_140271910: up to 10 FABRIK passes, then joints rotate from bind pose onto the solved directions */
+void solvePuppetIKChain (
+    const PuppetIKRig& rig, const PuppetIKChain& chain, const std::vector<int>& parents,
+    const std::vector<PuppetBoneIK>& ik, std::vector<glm::mat4>& model, const std::vector<glm::mat4>& extras,
+    const std::vector<glm::mat4>& bindModel, const glm::mat4& world, std::vector<PuppetRopeJoint>& joints
+);
+} // namespace WallpaperEngine::Render::Objects

+ 44 - 16
src/WallpaperEngine/Render/Objects/PuppetPhysics.cpp

@@ -199,11 +199,9 @@ PuppetBonePhysics PuppetBonePhysics::parse (const std::string& text) {
     flags |= isTrue ("r") ? Rotation : 0;
     flags |= isTrue ("t") ? Translation : 0;
     flags |= isTrue ("se") ? Simulate : 0;
-    flags |= isTrue ("re") ? SimulateRelative : 0;
+    flags |= isTrue ("re") ? SimulateRigid : 0;
 
-    // only "se" bones are ported: WE takes its "re" branch first when that is set, and IK chains are separate. No
-    // installed wallpaper uses either
-    if ((flags & Simulate) == 0 || (flags & SimulateRelative) != 0 || (flags & (Rotation | Translation)) == 0) {
+    if ((flags & (Simulate | SimulateRigid)) == 0 || (flags & (Rotation | Translation)) == 0) {
 	return result;
     }
 
@@ -295,16 +293,24 @@ glm::mat4 stepPuppetBonePhysics (
     const float distance = std::min (glm::length (predicted - previousTarget), dt * 900.0f);
     const Quat arc = rotationArc (glm::normalize (predicted), previousDirection);
 
-    if ((flags & PuppetBonePhysics::Simulate) && (flags & PuppetBonePhysics::Rotation)) {
+    // rigid "re" bones (0x140201a24): no stiffness, no angle wrapping, axis locks after the angle limits
+    const bool rigid = flags & PuppetBonePhysics::SimulateRigid;
+
+    if ((flags & (PuppetBonePhysics::Simulate | PuppetBonePhysics::SimulateRigid))
+	&& (flags & PuppetBonePhysics::Rotation)) {
 	Quat& velocity = state.angularVelocity;
 
 	velocity = multiply (
 	    velocity, slerp (kIdentity, arc, std::min (distance * physics.rotationInertia * kDegToRad, 1.0f))
 	);
-	velocity = multiply (
-	    velocity,
-	    slerp (kIdentity, fromEuler (-state.angles), std::min (physics.rotationStiffness * kDegToRad * dt, 1.0f))
-	);
+	if (!rigid) {
+	    velocity = multiply (
+		velocity,
+		slerp (
+		    kIdentity, fromEuler (-state.angles), std::min (physics.rotationStiffness * kDegToRad * dt, 1.0f)
+		)
+	    );
+	}
 
 	if (flags & PuppetBonePhysics::TotalAngleLimit) {
 	    const float w = velocity.x;
@@ -327,11 +333,15 @@ glm::mat4 stepPuppetBonePhysics (
 				mulRow (angles.r[2], rotation) } };
 	const glm::vec3 next = eulerFromRows (combined);
 
-	state.angles = {
-	    wrapAngle (next.x, flags & PuppetBonePhysics::LockRotationX),
-	    wrapAngle (next.y, flags & PuppetBonePhysics::LockRotationY),
-	    wrapAngle (next.z, flags & PuppetBonePhysics::LockRotationZ),
-	};
+	if (rigid) {
+	    state.angles = next;
+	} else {
+	    state.angles = {
+		wrapAngle (next.x, flags & PuppetBonePhysics::LockRotationX),
+		wrapAngle (next.y, flags & PuppetBonePhysics::LockRotationY),
+		wrapAngle (next.z, flags & PuppetBonePhysics::LockRotationZ),
+	    };
+	}
 
 	if (flags & PuppetBonePhysics::AngleLimits) {
 	    const glm::vec3 clamped = glm::min (glm::max (state.angles, physics.angleMin), physics.angleMax);
@@ -341,13 +351,22 @@ glm::mat4 stepPuppetBonePhysics (
 	    velocity = multiply ({ overshoot.x, -overshoot.y, -overshoot.z, -overshoot.w }, velocity);
 	}
 
+	if (rigid) {
+	    for (int axis = 0; axis < 3; axis++) {
+		if (flags & (PuppetBonePhysics::LockRotationX << axis)) {
+		    state.angles[axis] = 0.0f;
+		}
+	    }
+	}
+
 	velocity = slerp (velocity, kIdentity, std::min (dt * physics.rotationFriction, 1.0f));
     }
 
-    if ((flags & PuppetBonePhysics::Simulate) && (flags & PuppetBonePhysics::Translation)) {
+    if ((flags & (PuppetBonePhysics::Simulate | PuppetBonePhysics::SimulateRigid))
+	&& (flags & PuppetBonePhysics::Translation)) {
 	const glm::vec3 pulled
 	    = state.offset - (state.offset + currentOrigin - previousOrigin) * physics.translationInertia;
-	glm::vec3 velocity = state.velocity - (dt * physics.translationStiffness) * pulled;
+	glm::vec3 velocity = rigid ? state.velocity : state.velocity - (dt * physics.translationStiffness) * pulled;
 	glm::vec3 offset = pulled + dt * velocity;
 
 	for (int axis = 0; axis < 3; axis++) {
@@ -380,6 +399,15 @@ glm::mat4 stepPuppetBonePhysics (
     };
 }
 
+glm::vec4 puppetSlerp (const glm::vec4& a, const glm::vec4& b, float t) { return slerp (a, b, t); }
+
+glm::vec4 puppetRotationArc (const glm::vec3& from, const glm::vec3& to) { return rotationArc (from, to); }
+
+glm::mat3 puppetQuatRows (const glm::vec4& q) {
+    const Rows rows = quatRows (q);
+    return { rows.r[0], rows.r[1], rows.r[2] };
+}
+
 void applyPuppetBoneImpulse (
     PuppetBonePhysicsState& state, const glm::vec3& directional, const glm::vec3& angularDegrees
 ) {

+ 6 - 1
src/WallpaperEngine/Render/Objects/PuppetPhysics.h

@@ -13,7 +13,7 @@ namespace WallpaperEngine::Render::Objects {
 struct PuppetBonePhysics {
     enum Flags : uint32_t {
 	Simulate = 0x1,
-	SimulateRelative = 0x2,
+	SimulateRigid = 0x2,
 	Gravity = 0x4,
 	AngleLimits = 0x8,
 	TotalAngleLimit = 0x10,
@@ -67,6 +67,11 @@ glm::mat4 stepPuppetBonePhysics (
     const glm::mat4& previousWorld, float dt, float objectScale
 );
 
+/** Quaternion (w, x, y, z) helpers shared with the IK solver: sub_140216070, sub_1402167C0, sub_140216280 */
+glm::vec4 puppetSlerp (const glm::vec4& a, const glm::vec4& b, float t);
+glm::vec4 puppetRotationArc (const glm::vec3& from, const glm::vec3& to);
+glm::mat3 puppetQuatRows (const glm::vec4& q);
+
 /**
  * Script `applyBonePhysicsImpulse` (sub_140210990): the directional impulse is added to the translation velocity,
  * the angular one (degrees) is turned into a quaternion and multiplied onto the angular velocity.

+ 479 - 48
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -7,6 +7,7 @@
 #include <limits>
 #include <set>
 #include <strings.h>
+#include <utility>
 
 #include <glm/gtc/matrix_transform.hpp>
 
@@ -35,7 +36,9 @@ 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) {
+void stepPuppetClock (
+    PuppetActiveAnimation& clock, float duration, float delta, std::vector<std::string>* fired = nullptr
+) {
     if ((clock.flags & (PuppetClockPaused | PuppetClockStopped)) != 0
 	|| ((clock.flags & PuppetClockSingle) != 0 && clock.time >= duration) || duration <= 0.0f) {
 	return;
@@ -46,6 +49,25 @@ void stepPuppetClock (PuppetActiveAnimation& clock, float duration, float delta)
     }
 
     const float time = clock.time + delta;
+    const auto fire = [&clock, fired] (const auto& passed) {
+	if (fired == nullptr) {
+	    return;
+	}
+
+	for (const auto& event : clock.clip.events) {
+	    if (passed (event.time)) {
+		fired->push_back (event.payload);
+	    }
+	}
+    };
+
+    // events passed since the last time, including across a loop wrap (0x1401aa0b9)
+    if (delta > 0.0f) {
+	fire ([&clock, time] (float at) { return at >= clock.time && time > at; });
+    } else {
+	fire ([&clock, time] (float at) { return at > time && clock.time >= at; });
+    }
+
     clock.time = time;
 
     if ((clock.flags & PuppetClockSingle) != 0) {
@@ -59,9 +81,17 @@ void stepPuppetClock (PuppetActiveAnimation& clock, float duration, float delta)
     if ((clock.flags & PuppetClockMirror) == 0) {
 	if (time < 0.0f) {
 	    clock.time = std::fmod (time + duration, duration);
+
+	    if (clock.time >= 0.0f) {
+		fire ([&clock, duration] (float at) { return at > clock.time && duration >= at; });
+	    }
 	}
 	if (clock.time >= duration) {
 	    clock.time = std::fmod (clock.time, duration);
+
+	    if (duration > clock.time) {
+		fire ([&clock] (float at) { return at >= 0.0f && clock.time > at; });
+	    }
 	}
 	return;
     }
@@ -114,6 +144,8 @@ struct PuppetBoneSet {
     uint32_t extraCount = 0;
     uint32_t constraintCount = 0;
     std::vector<int> drawOrder;
+    std::vector<PuppetExtra> extras;
+    PuppetIKRig ik;
 };
 
 void parsePuppetCapsules (const BinaryReader& reader, PuppetBoneSet& result, size_t nextSectionOffset);
@@ -145,7 +177,7 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     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 uint32_t type = reader.nextUInt32 ();
 	const int parent = reader.nextInt ();
 	const uint32_t matrixBytes = reader.nextUInt32 ();
 
@@ -183,7 +215,9 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
 			 .parent = parent,
 			 .bindLocal = bindLocal,
 			 .restLocal = bindLocal,
-			 .physics = PuppetBonePhysics::parse (physics) }
+			 .physics = PuppetBonePhysics::parse (physics),
+			 .type = type,
+			 .ik = PuppetBoneIK::parse (physics) }
 	);
     }
 
@@ -197,9 +231,24 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     uint16_t extraCount = 0;
     reader.next (reinterpret_cast<char*> (&extraCount), sizeof (extraCount));
 
+    // name, bone, type (float, 0 target 1 pole), model space matrix
+    const auto readMatrix = [&reader] () {
+	float m[16];
+	for (float& value : m) {
+	    value = reader.nextFloat ();
+	}
+	return 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]
+	);
+    };
+
     for (uint16_t i = 0; i < extraCount; i++) {
 	(void)reader.nextNullTerminatedString ();
-	reader.base ().seekg (sizeof (uint32_t) * 2 + sizeof (float) * 16, std::ios::cur);
+	PuppetExtra extra;
+	extra.bone = reader.nextUInt32 ();
+	extra.type = reader.nextUInt32 ();
+	extra.restLocal = readMatrix ();
+	result.extras.push_back (extra);
     }
 
     // a flag byte and then a matrix per bone and per extra record: the rest pose. The vertices and the inverse bind
@@ -216,17 +265,40 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
 	    );
 	}
 
-	reader.base ().seekg (static_cast<std::streamoff> (extraCount * sizeof (float) * 16), std::ios::cur);
+	for (auto& extra : result.extras) {
+	    extra.restLocal = readMatrix ();
+	}
     }
 
     const uint32_t constraintCount = reader.nextUInt32 ();
+    result.ik.extraRules.resize (result.extras.size ());
 
+    // blend rules go on an IK joint's target extra, otherwise on the bone
     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;
+	const uint32_t bone = reader.nextUInt32 ();
+	PuppetConstraintRule rule;
+	rule.weight = reader.nextUInt32 ();
+	rule.target = reader.nextUInt32 ();
+	rule.flags = version >= 4 ? reader.nextUInt32 () : 0;
+
+	if (rule.flags & 2) {
+	    rule.start = reader.nextFloat ();
+	    rule.range = std::max (reader.nextFloat (), 0.00000011920929f);
+	}
 
-	if (flags & 2) {
-	    reader.base ().seekg (sizeof (uint32_t) + sizeof (float), std::ios::cur);
+	if (bone >= result.bones.size ()) {
+	    continue;
+	}
+
+	if (result.bones[bone].type & 2) {
+	    for (size_t extra = 0; extra < result.extras.size (); extra++) {
+		if (result.extras[extra].bone == bone && result.extras[extra].type == 0) {
+		    result.ik.extraRules[extra].push_back (rule);
+		    break;
+		}
+	    }
+	} else {
+	    result.bones[bone].rules.push_back (rule);
 	}
     }
 
@@ -247,25 +319,84 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
 	return value;
     };
 
+    // bone lengths and child rest directions (P+224, P+248)
+    auto& ik = result.ik;
     const uint16_t groups = nextUInt16 ();
-    skip (sizeof (uint32_t) * groups);
+    ik.lengths.resize (groups);
+    for (float& length : ik.lengths) {
+	length = reader.nextFloat ();
+    }
+    ik.childDirections.resize (groups);
     for (uint16_t i = 0; i < groups && reader.base ().good (); i++) {
-	skip ((sizeof (uint32_t) + sizeof (float) * 3) * nextUInt16 ());
+	const uint16_t children = nextUInt16 ();
+	for (uint16_t j = 0; j < children && reader.base ().good (); j++) {
+	    const uint32_t child = reader.nextUInt32 ();
+	    const float x = reader.nextFloat ();
+	    const float y = reader.nextFloat ();
+	    const float z = reader.nextFloat ();
+	    ik.childDirections[i][child] = glm::vec3 (x, y, z);
+	}
     }
 
+    // IK chains (P+272)
     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 ());
+	PuppetIKChain chain;
+	chain.root = reader.nextUInt32 ();
+	chain.extras.resize (reader.nextUInt32 ());
+	for (uint32_t& extra : chain.extras) {
+	    extra = reader.nextUInt32 ();
+	}
 	const uint16_t links = nextUInt16 ();
 	for (uint16_t j = 0; j < links && reader.base ().good (); j++) {
-	    (void)reader.nextUInt32 ();
+	    PuppetIKLink link;
+	    link.bone = 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 ());
+		PuppetIKEntry entry;
+		entry.endBone = reader.nextUInt32 ();
+		entry.flags = reader.nextUInt32 ();
+		entry.length = reader.nextFloat ();
+		entry.minReach = reader.nextFloat ();
+		entry.bones.resize (nextUInt16 ());
+		for (int& bone : entry.bones) {
+		    bone = reader.nextInt ();
+		}
+		link.entries.push_back (std::move (entry));
 	    }
+	    chain.links.push_back (std::move (link));
 	}
+	ik.chains.push_back (std::move (chain));
+    }
+
+    // WE fastfails on bad bone indices, drop the chain instead
+    const auto boneIndex
+	= [&result] (int bone) { return bone >= 0 && static_cast<size_t> (bone) < result.bones.size (); };
+    std::erase_if (ik.chains, [&boneIndex] (const PuppetIKChain& chain) {
+	return !boneIndex (static_cast<int> (chain.root))
+	    || std::ranges::any_of (chain.links, [&boneIndex] (const PuppetIKLink& link) {
+		   return !boneIndex (static_cast<int> (link.bone))
+		       || std::ranges::any_of (link.entries, [&boneIndex] (const PuppetIKEntry& entry) {
+			      return !boneIndex (static_cast<int> (entry.endBone))
+				  || !std::ranges::all_of (entry.bones, boneIndex);
+			  });
+	       });
+    });
+
+    if (reader.base ().good ()) {
+	for (size_t i = 0; i < ik.chains.size (); i++) {
+	    result.bones[ik.chains[i].root].chain = static_cast<int> (i);
+	}
+
+	for (uint32_t i = 0; i < result.extras.size (); i++) {
+	    ik.extraBones.push_back (result.extras[i].bone);
+	    auto& map = result.extras[i].type == 0 ? ik.targets : ik.poles;
+	    if (result.extras[i].type <= 1) {
+		map[result.extras[i].bone] = i;
+	    }
+	}
+    } else {
+	ik = {};
     }
 
     if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset) {
@@ -477,22 +608,6 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	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);
 	clip.boneFlags.assign (boneCount, 0);
@@ -525,15 +640,95 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	}
 
 	if (version >= 2) {
-	    skipFlaggedTracks (rig.extraCount, 9 * sizeof (float));
-	    skipFlaggedTracks (rig.constraintCount, sizeof (float));
+	    clip.extraTracks.resize (rig.extraCount);
+	    clip.extraAnimated.assign (rig.extraCount, true);
+
+	    for (uint32_t extra = 0; extra < rig.extraCount && valid; extra++) {
+		clip.extraAnimated[extra] = (reader.nextUInt32 () & 1) == 0;
+
+		if (reader.nextUInt32 () != sampleCount * 9 * sizeof (float)) {
+		    valid = false;
+		    break;
+		}
+
+		auto& track = clip.extraTracks[extra];
+		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 () };
+		    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);
+		}
+	    }
+
+	    clip.constraintTracks.resize (rig.constraintCount);
+	    clip.constraintFlags.assign (rig.constraintCount, 0);
+
+	    for (uint32_t constraint = 0; constraint < rig.constraintCount && valid; constraint++) {
+		clip.constraintFlags[constraint] = reader.nextUInt32 ();
+
+		if (reader.nextUInt32 () != sampleCount * sizeof (float)) {
+		    valid = false;
+		    break;
+		}
+
+		clip.constraintTracks[constraint].resize (sampleCount);
+
+		for (float& sample : clip.constraintTracks[constraint]) {
+		    sample = reader.nextFloat ();
+		}
+	    }
 	}
 
 	if (version >= 3 && valid) {
-	    skipFlaggedTracks (reader.nextUInt32 (), sizeof (float));
+	    // g_BlendMap tracks (clip +216)
+	    const uint32_t blendTracks = reader.nextUInt32 ();
+	    clip.blendTracks.resize (blendTracks);
+
+	    for (uint32_t track = 0; track < blendTracks && valid; track++) {
+		(void)reader.nextUInt32 ();
+
+		if (reader.nextUInt32 () != sampleCount * sizeof (float)) {
+		    valid = false;
+		    break;
+		}
+
+		clip.blendTracks[track].resize (sampleCount);
 
+		for (float& sample : clip.blendTracks[track]) {
+		    sample = reader.nextFloat ();
+		}
+	    }
+
+	    // bone alpha tracks (clip +240)
 	    if (valid && reader.next () != 0) {
-		skipFlaggedTracks (boneCount, sizeof (float));
+		clip.boneAlphaTracks.resize (boneCount);
+
+		for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
+		    (void)reader.nextUInt32 ();
+		    const uint32_t trackBytes = reader.nextUInt32 ();
+
+		    if (trackBytes != sampleCount * sizeof (float)) {
+			valid = false;
+			break;
+		    }
+
+		    auto& track = clip.boneAlphaTracks[boneIndex];
+		    track.resize (sampleCount);
+
+		    for (float& sample : track) {
+			sample = reader.nextFloat ();
+		    }
+		}
+
+		if (!valid) {
+		    clip.boneAlphaTracks.clear ();
+		}
 	    }
 	}
 
@@ -638,8 +833,10 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	    const uint32_t eventCount = reader.nextUInt32 ();
 
 	    for (uint32_t i = 0; i < eventCount && reader.base ().good (); i++) {
-		(void)reader.nextUInt32 (); // frame
-		(void)reader.nextNullTerminatedString ();
+		PuppetClipEvent event;
+		event.time = reader.nextFloat ();
+		event.payload = reader.nextNullTerminatedString ();
+		clip.events.push_back (std::move (event));
 	    }
 	}
 
@@ -738,7 +935,17 @@ void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t
     this->bones = std::move (boneSet.bones);
     this->boneDrawOrder = std::move (boneSet.drawOrder);
     this->boneModel = worldBind;
+    this->bindModel = worldBind;
+    this->extras = boneSet.extras;
+    this->ik = std::move (boneSet.ik);
+    this->hasIK = !this->ik.chains.empty ();
+    this->extraModel.resize (this->extras.size ());
+    for (size_t i = 0; i < this->extras.size (); i++) {
+	this->extraModel[i] = this->extras[i].restLocal;
+    }
     this->physicsState.assign (this->bones.size (), {});
+    this->ropeJoints.assign (this->bones.size (), {});
+    this->constraintWeights.assign (boneSet.constraintCount, 0.0f);
     this->hasPhysics
 	= std::ranges::any_of (this->bones, [] (const PuppetBone& bone) { return bone.physics.simulated (); });
     this->hasRestPose
@@ -985,6 +1192,8 @@ bool PuppetRig::destroyLayer (size_t serial) {
 }
 
 // sub_1401FDF90, after the pose: a layer that ended runs its ended callbacks, a playSingleAnimation() one is removed
+std::vector<std::string> PuppetRig::takeFiredEvents () { return std::exchange (this->firedEvents, {}); }
+
 void PuppetRig::finishEndedLayers (const std::function<void (size_t)>& dispatch) {
     std::vector<size_t> ended;
 
@@ -1066,7 +1275,11 @@ void PuppetRig::updateMorphWeights (const std::vector<PuppetLayerSample>& sample
 			state.active |= bit;
 		    }
 
-		    weight = std::clamp ((1.0f - sample.weight) * weight + sample.weight * value, 0.0f, 1.0f);
+		    weight = (1.0f - sample.weight) * weight + sample.weight * value;
+
+		    if (this->morphBlendClamped) {
+			weight = std::clamp (weight, 0.0f, 1.0f);
+		    }
 		}
 	    }
 	}
@@ -1109,6 +1322,30 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost*
 	orientations[i] = restOrientations[i];
     }
 
+    // extras (P+576/P+584)
+    const size_t extraCount = this->extras.size ();
+    std::vector<glm::vec3> extraPositions (extraCount);
+    std::vector<glm::vec3> extraScales (extraCount);
+    std::vector<glm::quat> extraOrientations (extraCount);
+    std::vector<glm::quat> extraRestOrientations (extraCount);
+
+    for (size_t i = 0; i < extraCount; i++) {
+	const glm::mat4& rest = this->extras[i].restLocal;
+	extraPositions[i] = glm::vec3 (rest[3]);
+	extraScales[i] = glm::vec3 (
+	    glm::length (glm::vec3 (rest[0])), glm::length (glm::vec3 (rest[1])), glm::length (glm::vec3 (rest[2]))
+	);
+	extraRestOrientations[i] = glm::normalize (
+	    glm::quat_cast (
+		glm::mat3 (
+		    glm::vec3 (rest[0]) / extraScales[i].x, glm::vec3 (rest[1]) / extraScales[i].y,
+		    glm::vec3 (rest[2]) / extraScales[i].z
+		)
+	    )
+	);
+	extraOrientations[i] = extraRestOrientations[i];
+    }
+
     // 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) {
@@ -1150,6 +1387,37 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost*
 		orientations[i] = nlerp (orientations[i], sampleOrientation, weight);
 	    }
 	}
+
+	for (size_t i = 0; i < extraCount; i++) {
+	    if (i >= clip.extraTracks.size () || clip.extraTracks[i].size () <= sample.frame1
+		|| (i < clip.extraAnimated.size () && !clip.extraAnimated[i])) {
+		continue;
+	    }
+
+	    const auto& from = clip.extraTracks[i][sample.frame0];
+	    const auto& to = clip.extraTracks[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) {
+		const glm::mat4& rest = this->extras[i].restLocal;
+		extraPositions[i] += (samplePosition - glm::vec3 (rest[3])) * weight;
+		extraScales[i] += (sampleScale
+				   - glm::vec3 (
+				       glm::length (glm::vec3 (rest[0])), glm::length (glm::vec3 (rest[1])),
+				       glm::length (glm::vec3 (rest[2]))
+				   ))
+		    * weight;
+		const glm::quat delta = glm::conjugate (extraRestOrientations[i]) * sampleOrientation;
+		extraOrientations[i] = extraOrientations[i] * nlerp (glm::quat (1.0f, 0.0f, 0.0f, 0.0f), delta, weight);
+	    } else {
+		extraPositions[i] = extraPositions[i] * (1.0f - weight) + samplePosition * weight;
+		extraScales[i] = extraScales[i] * (1.0f - weight) + sampleScale * weight;
+		extraOrientations[i] = nlerp (extraOrientations[i], sampleOrientation, weight);
+	    }
+	}
     };
 
     std::vector<PuppetLayerSample> samples;
@@ -1172,7 +1440,7 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost*
 
 	const uint32_t previousFlags = candidate.flags;
 	const float previousTime = candidate.time;
-	stepPuppetClock (candidate, duration, dt * candidate.layer->rate->value->getFloat ());
+	stepPuppetClock (candidate, duration, dt * candidate.layer->rate->value->getFloat (), &this->firedEvents);
 
 	// 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
@@ -1246,7 +1514,14 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost*
 	candidate.rootMotion.time = candidate.time;
     }
 
-    this->poseAnimated = !samples.empty () || this->hasPhysics || this->poseScripted || this->hasRestPose;
+    this->poseAnimated
+	= !samples.empty () || this->hasPhysics || this->poseScripted || this->hasRestPose || this->hasIK;
+
+    // no scale (~0x1402012a0)
+    for (size_t i = 0; i < extraCount; i++) {
+	this->extraModel[i]
+	    = glm::translate (glm::mat4 (1.0f), extraPositions[i]) * glm::mat4_cast (extraOrientations[i]);
+    }
 
     std::vector<int> animatedParents (count);
     std::vector<glm::mat4> animatedLocals (count);
@@ -1268,6 +1543,105 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost*
     this->composePose (animatedParents, animatedLocals, host != nullptr ? host->rootMotionWorld () : objectWorld);
     this->updateMorphWeights (samples);
     this->updateDrawOrder (samples);
+    this->updateBoneAlpha (samples);
+    this->updateBlendMap (samples);
+    this->updateConstraintWeights (samples);
+}
+
+void PuppetRig::updateConstraintWeights (const std::vector<PuppetLayerSample>& samples) {
+    // puppet +592 persists across frames, zeroed only by a first layer that isn't a full weight set
+    // (0x1401fee2e..0x1401fee87)
+    for (size_t layer = 0; layer < samples.size (); layer++) {
+	const auto& sample = samples[layer];
+	const auto& tracks = sample.clip->constraintTracks;
+	const bool direct = sample.weight == 1.0f && !sample.additive;
+
+	if (layer == 0 && !direct) {
+	    std::ranges::fill (this->constraintWeights, 0.0f);
+	}
+
+	for (size_t track = 0; track < tracks.size () && track < this->constraintWeights.size (); track++) {
+	    if ((sample.clip->constraintFlags[track] & 1) != 0 || sample.frame1 >= tracks[track].size ()) {
+		continue;
+	    }
+
+	    const float value
+		= (1.0f - sample.alpha) * tracks[track][sample.frame0] + sample.alpha * tracks[track][sample.frame1];
+	    float& current = this->constraintWeights[track];
+
+	    if (direct) {
+		current = value;
+	    } else if (!sample.additive) {
+		current = (1.0f - sample.weight) * current + sample.weight * value;
+	    } else {
+		current += value * sample.weight;
+	    }
+	}
+    }
+}
+
+void PuppetRig::updateBlendMap (const std::vector<PuppetLayerSample>& samples) {
+    // instance +848 persists across frames: set, lerp or add per layer (0x1401ff041..0x1401ffa18)
+    for (const auto& sample : samples) {
+	const auto& tracks = sample.clip->blendTracks;
+	const bool direct = sample.weight == 1.0f && !sample.additive;
+
+	for (size_t track = 0; track < tracks.size () && track < this->blendMap.size (); track++) {
+	    if (sample.frame1 >= tracks[track].size ()) {
+		continue;
+	    }
+
+	    const float value
+		= (1.0f - sample.alpha) * tracks[track][sample.frame0] + sample.alpha * tracks[track][sample.frame1];
+	    float& current = this->blendMap[track];
+
+	    if (direct) {
+		current = value;
+	    } else if (!sample.additive) {
+		current = (1.0f - sample.weight) * current + sample.weight * value;
+	    } else {
+		current += value * sample.weight;
+	    }
+	}
+    }
+}
+
+void PuppetRig::updateBoneAlpha (const std::vector<PuppetLayerSample>& samples) {
+    if (!this->boneAlphaEnabled) {
+	return;
+    }
+
+    // starts at 1 every frame; additive layers move by (value - 1) * weight, bones with (flags & 3) == 1 are skipped
+    this->boneAlpha.assign (this->bones.size (), 1.0f);
+
+    for (const auto& sample : samples) {
+	const auto& tracks = sample.clip->boneAlphaTracks;
+	const bool direct = sample.weight == 1.0f && !sample.additive;
+
+	for (size_t bone = 0; bone < tracks.size () && bone < this->boneAlpha.size (); bone++) {
+	    if (bone < sample.clip->boneFlags.size () && (sample.clip->boneFlags[bone] & 3) == 1) {
+		continue;
+	    }
+
+	    if (sample.frame1 >= tracks[bone].size ()) {
+		continue;
+	    }
+
+	    const float value
+		= (1.0f - sample.alpha) * tracks[bone][sample.frame0] + sample.alpha * tracks[bone][sample.frame1];
+	    float& alpha = this->boneAlpha[bone];
+
+	    if (direct) {
+		alpha = value;
+	    } else if (!sample.additive) {
+		alpha = (1.0f - sample.weight) * alpha + sample.weight * value;
+	    } else {
+		alpha = std::clamp (
+		    alpha + (value - 1.0f) * sample.weight, std::min (alpha, value), std::max (alpha, value)
+		);
+	    }
+	}
+    }
 }
 
 void PuppetRig::updateDrawOrder (const std::vector<PuppetLayerSample>& samples) {
@@ -1375,9 +1749,19 @@ void PuppetRig::composePose (
 			       + glm::length (glm::vec3 (object[2])))
 	/ 3.0f;
 
-    std::vector<glm::mat4> model (count);
+    // model matrices (P+712) persist across frames like WE, the solver starts from last frame
+    std::vector<glm::mat4> model = this->boneModel.size () == count ? this->boneModel : this->bindModel;
+    model.resize (count, glm::mat4 (1.0f));
     std::vector<glm::mat4> scene (count);
+    std::vector<glm::mat4> local = locals;
     std::vector<uint8_t> resolved (count, 0);
+    std::vector<int> ikParents (count);
+    std::vector<PuppetBoneIK> ikSettings (count);
+
+    for (size_t i = 0; i < count; i++) {
+	ikParents[i] = this->bones[i].parent;
+	ikSettings[i] = this->bones[i].ik;
+    }
 
     // parents first, a simulated parent moves its children
     const auto resolve = [&] (const auto& self, size_t index) -> void {
@@ -1387,12 +1771,29 @@ void PuppetRig::composePose (
 
 	resolved[index] = 1;
 	const int parent = parents[index];
+	const bool parented = parent >= 0 && static_cast<size_t> (parent) < count;
 
-	if (parent >= 0 && static_cast<size_t> (parent) < count && resolved[parent] != 1) {
+	if (parented && resolved[parent] != 1) {
 	    self (self, static_cast<size_t> (parent));
-	    model[index] = model[parent] * locals[index];
-	} else {
-	    model[index] = locals[index];
+	}
+
+	// posed by the solver (~0x140201300)
+	if ((this->bones[index].type & 2) && this->bones[index].chain < 0) {
+	    scene[index] = object * model[index];
+	    local[index] = parented ? glm::inverse (model[parent]) * model[index] : model[index];
+	    resolved[index] = 2;
+	    return;
+	}
+
+	model[index] = parented ? model[parent] * locals[index] : locals[index];
+
+	// the bone's blend rules, before physics
+	for (const auto& rule : this->bones[index].rules) {
+	    if (rule.target < count) {
+		const float weight
+		    = rule.weight < this->constraintWeights.size () ? this->constraintWeights[rule.weight] : 0.0f;
+		model[index] = blendPuppetTransform (model[index], model[rule.target], weight);
+	    }
 	}
 
 	scene[index] = object * model[index];
@@ -1408,6 +1809,32 @@ void PuppetRig::composePose (
 	    scene[index] = object * model[index];
 	}
 
+	// solve the chain this bone starts, its scene matrix keeps the unsolved pose
+	if (const int chain = this->bones[index].chain;
+	    chain >= 0 && static_cast<size_t> (chain) < this->ik.chains.size ()) {
+	    const auto& solved = this->ik.chains[chain];
+	    const bool rope = std::ranges::any_of (solved.links, [] (const PuppetIKLink& link) {
+		return std::ranges::any_of (link.entries, [] (const PuppetIKEntry& entry) {
+		    return (entry.flags & 4) != 0;
+		});
+	    });
+
+	    // sub_14026F4C0
+	    applyPuppetChainConstraints (this->ik, solved, this->constraintWeights, model, this->extraModel);
+
+	    if (rope) {
+		stepPuppetRopeChain (
+		    this->ik, solved, ikSettings, model, this->extraModel, object, this->ropeJoints,
+		    this->ropeEnvironment, dt
+		);
+	    }
+
+	    solvePuppetIKChain (
+		this->ik, solved, ikParents, ikSettings, model, this->extraModel, this->bindModel, object,
+		this->ropeJoints
+	    );
+	}
+
 	resolved[index] = 2;
     };
 
@@ -1415,7 +1842,7 @@ void PuppetRig::composePose (
 	resolve (resolve, i);
     }
 
-    this->boneLocal = locals;
+    this->boneLocal = std::move (local);
     this->boneModel = std::move (model);
     this->boneScene = std::move (scene);
 }
@@ -1497,8 +1924,12 @@ void PuppetRig::applyBonePhysicsImpulse (int bone, const glm::vec3& directional,
 }
 
 void PuppetRig::resetBonePhysics (int bone) {
-    // sub_140210E10
+    // sub_140210E10, rope joints included
     if (bone >= 0 && static_cast<size_t> (bone) < this->physicsState.size ()) {
 	this->physicsState[bone] = {};
     }
+
+    if (bone >= 0 && static_cast<size_t> (bone) < this->ropeJoints.size ()) {
+	this->ropeJoints[bone] = {};
+    }
 }

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

@@ -1,11 +1,13 @@
 #pragma once
 
+#include "PuppetIK.h"
 #include "PuppetPhysics.h"
 #include "PuppetRootMotion.h"
 
 #include "WallpaperEngine/Data/JSON.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 
+#include <array>
 #include <functional>
 #include <optional>
 #include <string>
@@ -30,12 +32,26 @@ struct PuppetBone {
     /** Inverse of the bone's bind-pose world transform, derived by walking the parent chain */
     glm::mat4 inverseBindWorld { 1.0f };
     PuppetBonePhysics physics {};
+    /** MDLS type, bit 2: posed by the IK solver */
+    uint32_t type = 0;
+    PuppetBoneIK ik {};
+    /** blend rules (bone +216) */
+    std::vector<PuppetConstraintRule> rules;
+    /** IK chain this bone starts (bone +212) */
+    int chain = -1;
     /** 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 };
 };
 
+/** MDLS v2+ extra: type 0 IK target, 1 pole */
+struct PuppetExtra {
+    uint32_t bone = 0;
+    uint32_t type = 0;
+    glm::mat4 restLocal { 1.0f };
+};
+
 /** A single sampled TRS pose for one bone at one point in time, from the MDLA section */
 struct PuppetKeyframe {
     glm::vec3 position {};
@@ -45,6 +61,12 @@ struct PuppetKeyframe {
     glm::quat orientation { 1.0f, 0.0f, 0.0f, 0.0f };
 };
 
+/** MDLA clip event, time in seconds (sub_1401A9F60) */
+struct PuppetClipEvent {
+    float time = 0.0f;
+    std::string payload;
+};
+
 /** A baked animation clip: one keyframe track per bone, sampled at a fixed rate */
 struct PuppetAnimationClip {
     /** what animationlayers[].animation refers to */
@@ -59,8 +81,20 @@ struct PuppetAnimationClip {
     std::vector<bool> boneAnimated;
     /** per bone, the raw track flags; the float tracks below skip a bone when (flags & 3) == 1 */
     std::vector<uint32_t> boneFlags;
+    /** MDLA v2, [extra][sample] */
+    std::vector<std::vector<PuppetKeyframe>> extraTracks;
+    std::vector<bool> extraAnimated;
     /** MDLA v6, [bone][sample]: what gets added to the parts' draw order of that bone (mesh flag 8) */
     std::vector<std::vector<float>> drawOrderTracks;
+    /** MDLA v3, [bone][sample]: g_BonesAlpha */
+    std::vector<std::vector<float>> boneAlphaTracks;
+    /** MDLA v2, [constraint][sample]: blend rule weights, flags bit 0 skips */
+    std::vector<std::vector<float>> constraintTracks;
+    std::vector<uint32_t> constraintFlags;
+    /** MDLA v3, [track][sample]: g_BlendMap */
+    std::vector<std::vector<float>> blendTracks;
+    /** clip +288 */
+    std::vector<PuppetClipEvent> events;
 
     /** a morph target's weight over the clip, one sample per frame like the bone tracks */
     struct MorphTrack {
@@ -187,6 +221,8 @@ public:
     );
     bool destroyLayersByName (const std::string& name);
     bool destroyLayer (size_t serial);
+    /** Clip events fired this frame, in layer order */
+    [[nodiscard]] std::vector<std::string> takeFiredEvents ();
     /** After the pose: every layer that ended runs dispatch (its ended callbacks), playSingleAnimation() ones go */
     void finishEndedLayers (const std::function<void (size_t)>& dispatch);
 
@@ -198,6 +234,12 @@ public:
     void updateMorphWeights (const std::vector<PuppetLayerSample>& samples);
     /** sub_1401FDF90 for meshes with flag 8: every bone's draw order from MDLS, moved by the layers' v6 tracks */
     void updateDrawOrder (const std::vector<PuppetLayerSample>& samples);
+    /** sub_1401FDF90, mesh flag 4 */
+    void updateBoneAlpha (const std::vector<PuppetLayerSample>& samples);
+    /** sub_1401FDF90, mesh flag 2 */
+    void updateBlendMap (const std::vector<PuppetLayerSample>& samples);
+    /** sub_1401FDF90 */
+    void updateConstraintWeights (const std::vector<PuppetLayerSample>& samples);
     /** sub_140225900 for one model layer after its blend, rest is what the layers above leave of it */
     void applyRootMotion (
 	PuppetActiveAnimation& layer, const PuppetLayerSample& sample, std::vector<glm::vec3>& positions,
@@ -230,6 +272,13 @@ public:
     std::vector<PuppetActiveAnimation> layers = {};
     /** per mesh, rebuilt by every updatePose () (sub_14021C480) */
     std::vector<PuppetMorphWeights> morphWeights = {};
+    /** models clamp blended layer weights to 0..1, images don't */
+    bool morphBlendClamped = true;
+    /** mesh flag 4, instance +616 */
+    bool boneAlphaEnabled = false;
+    std::vector<float> boneAlpha = {};
+    /** instance +848, four g_BlendMap rows */
+    std::array<float, 16> blendMap = {};
     size_t morphSection = 0;
     /** MDLS v3+ per bone order (instance +496), added to the order of every part of that bone */
     std::vector<int> boneDrawOrder = {};
@@ -238,6 +287,13 @@ public:
     std::vector<float> drawOrder = {};
     /** a layer wrote drawOrder this frame, the parts get sorted again */
     bool drawOrderTouched = false;
+    std::vector<PuppetExtra> extras = {};
+    PuppetIKRig ik = {};
+    /** bind pose in model space (P+808) */
+    std::vector<glm::mat4> bindModel = {};
+    /** P+736 */
+    std::vector<glm::mat4> extraModel = {};
+    bool hasIK = false;
     /** 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 */
@@ -246,10 +302,16 @@ public:
     /** Bone physics state and last frame's scene transforms, empty until the first frame */
     std::vector<PuppetBonePhysicsState> physicsState = {};
     std::vector<glm::mat4> physicsPreviousScene = {};
+    /** P+952 */
+    std::vector<PuppetRopeJoint> ropeJoints = {};
+    /** puppet +592 */
+    std::vector<float> constraintWeights = {};
+    PuppetRopeEnvironment ropeEnvironment = {};
     bool hasPhysics = false;
     /** The rest pose isn't the bind pose, the mesh needs skinning even when nothing moves */
     bool hasRestPose = false;
     size_t nextLayerSerial = 0;
+    std::vector<std::string> firedEvents = {};
     /** 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 */

+ 7 - 0
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -604,6 +604,13 @@ void ShaderUnit::preprocessScalarSwizzles () {
 
 	const std::regex swizzle ("\\b" + name + "\\.[xyzwrgba](?![A-Za-z0-9_])");
 	this->m_preprocessed = std::regex_replace (this->m_preprocessed, swizzle, name);
+
+	// scalar .xx/.xxx/.xxxx (or .rr...) replication, e.g. 3035844290 bokeh_blur
+	for (const char* width : { "4", "3", "2" }) {
+	    const std::regex replicate ("\\b" + name + "\\.(?:[x]{" + width + "}|[r]{" + width + "})(?![A-Za-z0-9_])");
+	    this->m_preprocessed
+		= std::regex_replace (this->m_preprocessed, replicate, std::string ("vec") + width + " (" + name + ")");
+	}
     }
 }
 

+ 19 - 3
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -6,6 +6,7 @@
 #include "WallpaperEngine/Render/Objects/CParticle.h"
 #include "WallpaperEngine/Render/Objects/CSound.h"
 #include "WallpaperEngine/Render/Objects/CText.h"
+#include "WallpaperEngine/Render/Objects/PuppetIK.h"
 
 #include "WallpaperEngine/Render/WallpaperState.h"
 
@@ -442,7 +443,8 @@ void CScene::renderFrame (const glm::ivec4& viewport) {
 }
 
 void CScene::renderFrameSteps (const glm::ivec4& viewport) {
-    this->m_outputSize = { viewport.z, viewport.w };
+    // --ssaa only scales the buffers, cursor/visible region/scripts stay in output pixels
+    this->m_outputSize = glm::ivec2 (viewport.z, viewport.w) * this->getSupersampling ();
     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
@@ -465,9 +467,10 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
 
     // 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
+    // WE: init () while loading, then the static camera (sub_140186C90), then the first update ()
+    this->getScriptEngine ().initializePending ();
     this->loadStaticCamera ();
+    timeStep ("script tick", [&] { this->getScriptEngine ().tick (); });
     // WE runs the object updates first, then the camera, then the parallax camera
     this->updateCamera ();
     this->updateParallax ();
@@ -1917,6 +1920,19 @@ float CScene::getTime () const { return g_Time; }
 
 float CScene::getDeltaTime () const { return g_Time - g_TimeLast; }
 
+Objects::PuppetRopeEnvironment CScene::getRopeEnvironment () const {
+    const auto& physics = this->getScene ().physics;
+
+    return {
+	.gravity = physics.gravityDirection->value->getVec3 () * physics.gravityStrength->value->getFloat (),
+	.wind = physics.windEnabled->value->getBool (),
+	.windDirection = physics.windDirection->value->getVec3 (),
+	.windStrength = physics.windStrength->value->getFloat (),
+	.clock = this->getSceneClock (),
+	.width = static_cast<float> (this->getWidth ()),
+    };
+}
+
 float CScene::getSceneClock () const {
     // wallpaper64.exe sub_14017FA70 starts over at 0 once it passes 432000 (the frame crossing it is dropped there)
     return std::fmod (std::max (g_Time - this->m_startTime, 0.0f), 432000.0f);

+ 3 - 0
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -16,6 +16,7 @@ namespace WallpaperEngine::Render {
 class Camera;
 class CObject;
 namespace Objects {
+    struct PuppetRopeEnvironment;
     class CLight;
 }
 }
@@ -73,6 +74,8 @@ 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;
+    /** Puppet rope gravity and wind */
+    [[nodiscard]] Objects::PuppetRopeEnvironment getRopeEnvironment () const;
     /** Frames rendered since the scene was loaded, the first one is 1 */
     [[nodiscard]] uint32_t getFrameCounter () const;
 

+ 33 - 0
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -650,8 +650,40 @@ void animation_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info, int
 	    return;
     }
 }
+// getAnimation (sub_18162BBE0) on an animation layer's own properties, by animation or property name
+void animation_layer_get_animation (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    auto& engine = engineOf (info);
+    const auto context = engine.getContext ();
+    auto* object = layerObject (JS::get (context, info.Data (), 0u));
+    const auto serial = static_cast<size_t> (JS::get (context, info.Data (), 1u)->IntegerValue (context).FromMaybe (0));
+    std::string name;
+
+    info.GetReturnValue ().SetNull ();
+
+    if (object == nullptr) {
+	return;
+    }
+
+    if (info.Length () > 0 && info[0]->IsString ()) {
+	name = JS::toString (info.GetIsolate (), info[0]);
+    } else if (engine.getRunningModule () != nullptr) {
+	name = engine.getRunningModule ()->propertyName;
+    }
+
+    v8::Local<v8::Value> animation;
+
+    if (engine
+	    .findAnimation (name, WallpaperEngine::Scripting::Adapters::animationLayerGroup (object->getId (), serial))
+	    .ToLocal (&animation)) {
+	info.GetReturnValue ().Set (animation);
+    }
+}
 } // namespace
 
+std::string WallpaperEngine::Scripting::Adapters::animationLayerGroup (int objectId, size_t serial) {
+    return "animationlayer" + std::to_string (objectId) + "[" + std::to_string (serial) + "]";
+}
+
 v8::Local<v8::Value> WallpaperEngine::Scripting::Adapters::makeAnimationLayerHandle (
     ScriptEngine& engine, ScriptableObject& object, size_t serial
 ) {
@@ -690,6 +722,7 @@ v8::Local<v8::Value> WallpaperEngine::Scripting::Adapters::makeAnimationLayerHan
     );
     accessor ("rate", JS::bind<animation_layer_call, LayerGetRate>, JS::bind<animation_layer_call, LayerSetRate>);
     accessor ("blend", JS::bind<animation_layer_call, LayerGetBlend>, JS::bind<animation_layer_call, LayerSetBlend>);
+    method ("getAnimation", animation_layer_get_animation, 0);
 
     // lets destroyAnimationLayer() take the object back
     handle

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

@@ -54,6 +54,9 @@ struct Layer {
 /** IAnimationLayer (wallpaper64 2.8.42 sub_14026C980) for the puppet animation layer with that serial */
 v8::Local<v8::Value> makeAnimationLayerHandle (ScriptEngine& engine, ScriptableObject& object, size_t serial);
 
+/** Animation group of an animation layer's own properties, which WE keys by the layer's own id (sub_14018DB00) */
+std::string animationLayerGroup (int objectId, size_t serial);
+
 class ScriptableObjectAdapter {
 public:
     explicit ScriptableObjectAdapter (ScriptEngine& engine);

+ 4 - 0
src/WallpaperEngine/Scripting/AnimationSystem.cpp

@@ -11,8 +11,10 @@ namespace {
 int NextSystemId = 0;
 std::map<int, AnimationSystem*> Systems;
 
+// "value": 1 parses as an int but animates as a float
 int componentCount (DynamicValue::UnderlyingType type) {
     switch (type) {
+	case DynamicValue::Int:
 	case DynamicValue::Float:
 	    return 1;
 	case DynamicValue::Vec2:
@@ -28,6 +30,7 @@ int componentCount (DynamicValue::UnderlyingType type) {
 
 glm::vec4 readComponents (const DynamicValue& value) {
     switch (value.getType ()) {
+	case DynamicValue::Int:
 	case DynamicValue::Float:
 	    return { value.getFloat (), 0.0f, 0.0f, 0.0f };
 	case DynamicValue::Vec2:
@@ -45,6 +48,7 @@ void writeComponents (DynamicValue& value, const glm::vec4& components) {
     const auto source = DynamicValue::UpdateSource::Script;
 
     switch (value.getType ()) {
+	case DynamicValue::Int:
 	case DynamicValue::Float:
 	    value.update (components.x, source);
 	    break;

+ 93 - 0
src/WallpaperEngine/Scripting/JS.cpp

@@ -1,10 +1,43 @@
 #include "JS.h"
 
+#include "WallpaperEngine/Logging/Log.h"
+
 #include <libplatform/libplatform.h>
 
 #include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <string>
+
+// embedders skip node's ICU setup, without it Fedora's libnode has no time zone data. Weak for nodes without Intl
+namespace node::i18n {
+[[gnu::weak]] bool InitializeICUDirectory (const std::string& path, std::string* error);
+}
 
 namespace WallpaperEngine::Scripting::JS {
+namespace {
+    // node's lookup: NODE_ICU_DATA, then the build's default directory if installed
+    std::string icuDataDirectory () {
+	if (const char* env = std::getenv ("NODE_ICU_DATA"); env != nullptr) {
+	    return env;
+	}
+
+#ifdef V8_ICU_DEFAULT_DATA_DIR
+	std::error_code ec;
+
+	for (const auto& entry : std::filesystem::directory_iterator (V8_ICU_DEFAULT_DATA_DIR, ec)) {
+	    const auto name = entry.path ().filename ().string ();
+
+	    if (name.starts_with ("icudt") && name.ends_with (".dat")) {
+		return V8_ICU_DEFAULT_DATA_DIR;
+	    }
+	}
+#endif
+
+	return {};
+    }
+} // namespace
+
 v8::Platform& platform () {
     // V8 initializes once per process and can't come back after V8::Dispose (), so it stays up until exit; every
     // scene's isolate shares it like WE's scenescript64 (sub_180030400 under a once guard)
@@ -16,6 +49,14 @@ v8::Platform& platform () {
 	    v8::V8::SetFlagsFromString ("--random-seed=1");
 	}
 
+	if (node::i18n::InitializeICUDirectory != nullptr) {
+	    std::string error;
+
+	    if (!node::i18n::InitializeICUDirectory (icuDataDirectory (), &error)) {
+		sLog.error ("Could not initialize ICU: ", error);
+	    }
+	}
+
 	v8::V8::InitializeICU ();
 	v8::V8::InitializePlatform (created);
 	v8::V8::Initialize ();
@@ -25,4 +66,56 @@ v8::Platform& platform () {
 
     return *instance;
 }
+
+namespace {
+    std::string zoneNameFromPath (const std::string& path) {
+	std::error_code ec;
+	std::string target = path;
+
+	if (std::filesystem::is_symlink (path, ec)) {
+	    target = std::filesystem::read_symlink (path, ec).string ();
+	}
+
+	const auto at = target.find ("zoneinfo/");
+
+	if (at == std::string::npos) {
+	    return {};
+	}
+
+	std::string name = target.substr (at + 9);
+
+	for (const char* prefix : { "posix/", "right/" }) {
+	    if (name.starts_with (prefix)) {
+		name.erase (0, std::char_traits<char>::length (prefix));
+	    }
+	}
+
+	return name;
+    }
+} // namespace
+
+void useNamedTimeZone () {
+    const char* current = std::getenv ("TZ");
+    std::string value = current != nullptr ? current : "";
+
+    if (value.starts_with (':')) {
+	value.erase (0, 1);
+    }
+
+    // zone names and POSIX rules work in ICU as they are
+    if (!value.empty () && !value.starts_with ('/')) {
+	return;
+    }
+
+    std::string name = zoneNameFromPath (value.empty () ? "/etc/localtime" : value);
+
+    if (name.empty () && value.empty ()) {
+	std::ifstream file ("/etc/timezone");
+	std::getline (file, name);
+    }
+
+    if (!name.empty () && std::filesystem::exists ("/usr/share/zoneinfo/" + name)) {
+	setenv ("TZ", name.c_str (), 1);
+    }
+}
 } // namespace WallpaperEngine::Scripting::JS

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

@@ -14,6 +14,11 @@ namespace WallpaperEngine::Scripting::JS {
 /** Creates the process wide V8 platform once, every isolate shares it */
 v8::Platform& platform ();
 
+/**
+ * Sets TZ to the local IANA zone name when unset or a path, ICU loses DST otherwise. Call before other threads start
+ */
+void useNamedTimeZone ();
+
 inline v8::Local<v8::String> string (v8::Isolate* isolate, std::string_view text) {
     return v8::String::NewFromUtf8 (isolate, text.data (), v8::NewStringType::kNormal, static_cast<int> (text.size ()))
 	.ToLocalChecked ();

+ 96 - 0
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -983,6 +983,16 @@ v8::MaybeLocal<v8::Value> ScriptEngine::findAnimation (const std::string& name,
     return this->m_adapters.object->animation (this->m_animations.getId (), clock->getId ());
 }
 
+v8::MaybeLocal<v8::Value> ScriptEngine::findAnimation (const std::string& name, const std::string& group) {
+    auto* clock = this->m_animations.findByName (name, group);
+
+    if (clock == nullptr) {
+	return {};
+    }
+
+    return this->m_adapters.object->animation (this->m_animations.getId (), clock->getId ());
+}
+
 v8::Local<v8::Value> ScriptEngine::makeThisObject (DynamicValue& value, const std::string& propertyName) {
     const auto context = this->getContext ();
     const v8::Local<v8::Object> handle = v8::Object::New (this->m_isolate);
@@ -1265,6 +1275,53 @@ void ScriptEngine::dispatchAnimationLayerEnded (const ScriptableObject& owner, s
     }
 }
 
+void ScriptEngine::dispatchClipEvent (const ScriptableObject& owner, const std::string& payload) {
+    const Scope scope (*this);
+    const auto context = this->getContext ();
+
+    for (auto& [key, module] : this->m_scriptModules) {
+	if (module.object != &owner || !module.initialized || module.dropped || module.module.IsEmpty ()) {
+	    continue;
+	}
+
+	const v8::HandleScope handleScope (this->m_isolate);
+	v8::Local<v8::Value> function;
+
+	if (!module.module.Get (this->m_isolate)
+		 ->Get (context, JS::name (this->m_isolate, "animationEvent"))
+		 .ToLocal (&function)
+	    || !function->IsFunction ()) {
+	    continue;
+	}
+
+	v8::Local<v8::Value> event = v8::Null (this->m_isolate);
+	{
+	    const v8::TryCatch parseCatch (this->m_isolate);
+	    v8::Local<v8::Value> parsed;
+
+	    if (v8::JSON::Parse (context, JS::string (this->m_isolate, payload)).ToLocal (&parsed)) {
+		event = parsed;
+	    }
+	}
+
+	const v8::TryCatch tryCatch (this->m_isolate);
+	LoadedModule* previous = this->m_runningModule;
+	this->m_runningModule = &module;
+	this->bindThisLayer (*module.object, &module);
+
+	v8::Local<v8::Value> args[] = { event, this->propertyToJs (module.value, module.propertyName) };
+	v8::Local<v8::Value> result;
+
+	if (!this->call (module, "animationEvent", 2, args).ToLocal (&result)) {
+	    logJSException (this->m_isolate, tryCatch, key.c_str (), module.value.getScriptSource ());
+	} else {
+	    this->assignPropertyJsValue (result, module.value, module.propertyName);
+	}
+
+	this->m_runningModule = previous;
+    }
+}
+
 v8::MaybeLocal<v8::Value> ScriptEngine::callAsModule (const std::string& key, v8::Local<v8::Function> callback) {
     const auto it = this->m_scriptModules.find (key);
     LoadedModule* module = it == this->m_scriptModules.end () || it->second.dropped ? nullptr : &it->second;
@@ -1297,6 +1354,45 @@ void ScriptEngine::setThisObjectFactory (
     it->second.thisObject.Reset ();
 }
 
+void ScriptEngine::initializePending () {
+    const Scope scope (*this);
+    LoadedModule* previous = this->m_runningModule;
+
+    // init () can create layers with scripts of their own
+    for (bool again = true; again;) {
+	again = false;
+
+	std::vector<std::pair<uint64_t, std::string>> order;
+	for (const auto& [key, module] : this->m_scriptModules) {
+	    if (!module.initialized && !module.dropped) {
+		order.emplace_back (module.order, key);
+	    }
+	}
+	std::ranges::sort (order);
+
+	for (const auto& [unused, key] : order) {
+	    const auto entry = this->m_scriptModules.find (key);
+	    if (entry == this->m_scriptModules.end () || entry->second.dropped || entry->second.initialized) {
+		continue;
+	    }
+	    auto& module = entry->second;
+
+	    const v8::HandleScope handleScope (this->m_isolate);
+
+	    this->m_runningModule = &module;
+
+	    if (module.object != nullptr) {
+		this->bindThisLayer (*module.object, &module);
+	    }
+
+	    this->initializeModule (key, module);
+	    again = true;
+	}
+    }
+
+    this->m_runningModule = previous;
+}
+
 void ScriptEngine::tick () {
     const Scope scope (*this);
     const auto context = this->getContext ();

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

@@ -161,6 +161,9 @@ public:
      */
     void tick ();
 
+    /** Runs pending init () calls in scene order, before the camera is set like WE */
+    void initializePending ();
+
     // Layer-script API: WE text-object scripts follow a lifecycle that
     // doesn't fit the simple `update(value) -> value` contract above. They typically look like:
     //
@@ -225,6 +228,8 @@ public:
     void addAnimationLayerEndedCallback (const ScriptableObject& owner, size_t serial, v8::Local<v8::Value> 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);
+    /** Puppet clip event -> animationEvent (sub_140177AD0) with the payload JSON parsed, null if invalid */
+    void dispatchClipEvent (const ScriptableObject& owner, const std::string& payload);
     /** The script queued under key gets thisObject from factory instead of the property handle */
     void setThisObjectFactory (const std::string& key, std::function<v8::Local<v8::Value> (ScriptEngine&)> factory);
 
@@ -268,6 +273,8 @@ public:
     /** IAnimation of the animation getAnimation (name) finds on objectId's layer, or any layer without one; empty
      *  when there is none */
     v8::MaybeLocal<v8::Value> findAnimation (const std::string& name, std::optional<int> objectId);
+    /** Same, within one animation group */
+    v8::MaybeLocal<v8::Value> findAnimation (const std::string& name, const std::string& group);
 
 private:
     void dispatchAnimationEvents ();

+ 17 - 6
src/WallpaperEngine/WebBrowser/CEF/WPSchemeHandler.cpp

@@ -106,9 +106,19 @@ bool WPSchemeHandler::Open (CefRefPtr<CefRequest> request, bool& handle_request,
 
 	    std::cout << "--web-host: serving " << local.string () << " to the page" << std::endl;
 	    this->m_contents = std::make_shared<std::ifstream> (local, std::ios::binary);
-	    this->m_isLocalFile = true;
-	    this->m_totalSize = static_cast<int64_t> (std::filesystem::file_size (local));
-	    this->m_remaining = this->m_totalSize;
+	} else {
+	    this->m_contents = this->m_assetLoader.read (file);
+	}
+
+	// Chromium can't demux WebM (Cues at the end) without a length and Range support
+	this->m_contents->seekg (0, std::ios::end);
+	const int64_t size = this->m_contents->tellg ();
+	this->m_contents->seekg (0, std::ios::beg);
+
+	if (size >= 0 && !this->m_contents->fail ()) {
+	    this->m_knownSize = true;
+	    this->m_totalSize = size;
+	    this->m_remaining = size;
 
 	    // "bytes=<start>-[<end>]", the only form media elements send
 	    if (const std::string range = request->GetHeaderByName ("Range").ToString ();
@@ -123,11 +133,12 @@ bool WPSchemeHandler::Open (CefRefPtr<CefRequest> request, bool& handle_request,
 		    this->m_partial = true;
 		    this->m_rangeStart = start;
 		    this->m_remaining = std::min (last, this->m_totalSize - 1) - start + 1;
-		    this->m_contents->seekg (start);
+		    // MemoryStream only implements seekoff
+		    this->m_contents->seekg (start, std::ios::beg);
 		}
 	    }
 	} else {
-	    this->m_contents = this->m_assetLoader.read (file);
+	    this->m_contents->clear ();
 	}
 
 	callback->Continue ();
@@ -154,7 +165,7 @@ void WPSchemeHandler::GetResponseHeaders (
 
     response->SetMimeType (this->m_mimeType);
 
-    if (this->m_isLocalFile) {
+    if (this->m_knownSize) {
 	response->SetHeaderByName ("Accept-Ranges", "bytes", true);
 
 	if (this->m_partial) {

+ 2 - 2
src/WallpaperEngine/WebBrowser/CEF/WPSchemeHandler.h

@@ -41,8 +41,8 @@ private:
     ReadStreamSharedPtr m_contents = nullptr;
     std::string m_mimeType;
 
-    // Only set for local files (see LOCAL_FILE_PREFIX), which media elements need Range support for to seek at all
-    bool m_isLocalFile = false;
+    // without a size there is no length or Range support
+    bool m_knownSize = false;
     bool m_partial = false;
     int64_t m_totalSize = 0;
     int64_t m_rangeStart = 0;

+ 3 - 0
src/main.cpp

@@ -4,6 +4,7 @@
 #include "WallpaperEngine/Application/ApplicationContext.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Scripting/JS.h"
 
 WallpaperEngine::Application::WallpaperApplication* app;
 
@@ -21,6 +22,8 @@ void initLogging () {
 }
 
 int main (int argc, char* argv[]) {
+    WallpaperEngine::Scripting::JS::useNamedTimeZone ();
+
     try {
 	// --type=* args mean this is a CEF subprocess re-exec; skip logging here
 	bool enableLogging = true;

BIN
tools/__pycache__/mdl_scan.cpython-313.pyc


+ 85 - 0
tools/mdl_chains.py

@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+"""Lists the MDLS IK chains of puppet .mdl files, read like wallpaper64.exe 2.8.42 (sub_140261880).
+
+Usage:
+    mdl_chains.py <item id>... [--dir workshop dir]
+
+Per puppet: MDLS version, bone count, which bone JSON keys are set (and how many bones have ik/se/re on), the
+extra/constraint/chain counts and each chain entry. Entries with flags & 4 are physics (kinematic rope) chains.
+"""
+import struct, sys, glob, json, collections
+
+def pkg_entries(pkg):
+    with open(pkg, 'rb') as f:
+        n = struct.unpack('<I', f.read(4))[0]; f.read(n)
+        c = struct.unpack('<I', f.read(4))[0]; ents = []
+        for _ in range(c):
+            n = struct.unpack('<I', f.read(4))[0]; name = f.read(n).decode('utf-8', 'replace')
+            o, l = struct.unpack('<II', f.read(8)); ents.append((name, o, l))
+        base = f.tell()
+        for name, o, l in ents:
+            if name.endswith('.mdl'):
+                f.seek(base + o); yield name, f.read(l)
+
+class R:
+    def __init__(self, d, o): self.d = d; self.o = o
+    # `r.o += r.f()` would load r.o before f() advances it
+    def f(self, fmt):
+        v = struct.unpack_from('<' + fmt, self.d, self.o); self.o += struct.calcsize(fmt)
+        return v if len(v) > 1 else v[0]
+    def s(self):
+        e = self.d.index(b'\0', self.o); v = self.d[self.o:e].decode('utf-8', 'replace'); self.o = e + 1; return v
+
+def scan(name, d):
+    o = d.find(b'MDLS')
+    if o < 0:
+        return
+    r = R(d, o + 9); ver = int(d[o + 4:o + 8]); end = r.f('I'); nb = r.f('I')
+    keys = collections.Counter(); on = collections.Counter()
+    for _ in range(nb):
+        r.s(); r.f('I'); r.f('i'); mb = r.f('I'); r.o += mb; js = r.s()
+        if js:
+            j = json.loads(js)
+            keys.update(j.keys())
+            on.update(k for k in ('ik', 'ikce', 'se', 're') if j.get(k) is True)
+    print(f'  {name} MDLS v{ver} bones={nb} on={dict(on)} keys={sorted(keys)}')
+    if ver < 2:
+        return
+    extras = r.f('H')
+    for _ in range(extras):
+        r.s(); r.o += 8 + 64
+    if r.f('B'):
+        r.o += 64 * (nb + extras)
+    constraints = r.f('I')
+    for _ in range(constraints):
+        r.o += 12
+        if (r.f('I') if ver >= 4 else 0) & 2:
+            r.o += 8
+    groups = r.f('H'); r.o += 4 * groups
+    for _ in range(groups):
+        children = r.f('H'); r.o += 16 * children
+    chains = r.f('H'); entries = []
+    for _ in range(chains):
+        root = r.f('I'); n = r.f('I'); r.o += 4 * n
+        for _ in range(r.f('H')):
+            r.f('I')
+            for _ in range(r.f('H')):
+                endBone, flags, _, _ = r.f('IIff')
+                bones = [r.f('i') for _ in range(r.f('H'))]
+                entries.append((root, endBone, flags, bones))
+    physics = sum(1 for e in entries if e[2] & 4)
+    print(f'    extras={extras} constraints={constraints} chains={chains} physics entries={physics} ({r.o}/{end})')
+    for root, endBone, flags, bones in entries:
+        print(f'      root {root} end {endBone} flags {flags:#x} bones {bones}')
+
+args = sys.argv[1:]
+root = '/workspace/SteamLibrary/steamapps/workshop/content/431960'
+if '--dir' in args:
+    i = args.index('--dir'); root = args[i + 1]; del args[i:i + 2]
+for item in args:
+    print('=====', item)
+    for pkg in glob.glob(f'{root}/{item}/*.pkg'):
+        for name, data in pkg_entries(pkg):
+            scan(name, data)
+    for p in glob.glob(f'{root}/{item}/**/*.mdl', recursive=True):
+        scan(p, open(p, 'rb').read())

+ 1 - 1
tools/wecompare/render_ours.sh

@@ -23,7 +23,7 @@ print(' '.join(sorted(i for i, v in items.items() if keep or v['info'].get('type
 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 \
+  HEADLESS_RENDER_SIZE=1920x1058 HEADLESS_RENDER_DELAY=${DELAY:-600} HEADLESS_RENDER_TIMEOUT=90 LD_LIBRARY_PATH=$LWE${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} \
     $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)"
 }