Bladeren bron

implemented clipping masks

updated readme
UwU 1 maand geleden
bovenliggende
commit
ca7f03f78c

+ 11 - 5
.github/workflows/cmake.yml

@@ -1,8 +1,8 @@
 name: CMake
 
 on:
-  push:
-    tags: [ 'v*' ]
+  release:
+    types: [ published ]
   workflow_dispatch:
 
 jobs:
@@ -166,7 +166,7 @@ jobs:
 
   release:
     needs: [build, distro-build]
-    if: startsWith(github.ref, 'refs/tags/v')
+    if: startsWith(github.ref, 'refs/tags/')
     runs-on: ubuntu-latest
     permissions:
       contents: write
@@ -178,10 +178,16 @@ jobs:
           path: release
           merge-multiple: true
 
-      - name: Create release
+      - name: Upload to the release
         env:
           GH_TOKEN: ${{ github.token }}
-        run: gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --generate-notes release/*.tar.gz
+        run: |
+          # a release made on GitHub already exists, a manual run on a bare tag has none yet
+          if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
+            gh release upload "$GITHUB_REF_NAME" --clobber release/*.tar.gz
+          else
+            gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --generate-notes release/*.tar.gz
+          fi
 
   clang-build:
     needs: tests

+ 2 - 0
CMakeLists.txt

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

+ 38 - 3
README.md

@@ -241,12 +241,47 @@ linux-wallpaperengine --disable-object Clock --disable-object 3 2370927443
 
 ## Limitations
 
-- Light and VolumeLight scene objects are parsed but not rendered - wallpapers that depend on them for lighting will look different from the Windows original.
-- Passthrough image effects aren't implemented.
-- Text objects can't sample the background behind them (no copybackground-style effects on `Text`).
+The scene renderer follows Wallpaper Engine 2.8 closely, but not everything is there yet. The full list with details is in [TODO.md](TODO.md).
+
+Platform and setup:
+
 - KDE fullscreen-pause detection is experimental and requires the separate KWin Maximize Detector script.
 - On X11, a compositor or DE drawing its own background will block the wallpaper. Disabling the compositor is currently the only fix.
+- HDR output (`--hdr`) is Wayland only and needs a compositor with the color-management protocol.
 - Some NVIDIA setups hit GLFW/OpenGL init failures; try `__GL_THREADED_OPTIMIZATIONS=0 linux-wallpaperengine` if you run into this.
+- There is no MSAA setting yet (Wallpaper Engine's "anti-aliasing" option), so edges of 3D models are not smoothed.
+- Windows fonts (`systemfont_*`) are replaced by the closest installed match through fontconfig, so text can look slightly different if Arial, Segoe UI etc. or their metric-compatible clones aren't installed.
+- RGB lighting output (iCUE/Chroma `ledsource`) is ignored.
+
+Puppets (2D animated characters):
+
+- IK chains are not supported.
+- Animated bone transparency (parts fading in and out) is not supported.
+- Animated changes of the parts' draw order are not supported.
+- Morph targets (blend shapes) are only applied to 3D models, not to puppets.
+- `layerimage` particle emitters don't follow puppet layers.
+
+3D scenes:
+
+- Camera parallax is not applied in 3D scenes.
+
+Images, particles and text:
+
+- An animated GIF picked as a wallpaper's custom image only shows its first frame.
+- `layerimage` particle emitters read the layer right away, not from the GPU a frame later like Wallpaper Engine, and don't support text layers or opacity masks.
+- Particle `spritesheetrefreshsync`, `alphatocoverage` and rope `uvscrolling`/`uvsmoothing` are not supported.
+- Emoji from the bundled Twemoji font are drawn as their colour bitmap where Wallpaper Engine (without Windows' emoji font) draws nothing.
+
+Sound:
+
+- Spatialized sound objects don't switch to HRTF for headphones like OpenAL on Windows does.
+
+Scripting (SceneScript):
+
+- Not implemented: `setParent`, the effect material calls (`getMaterial`, `setMaterialProperty`, `executeMaterialFunction`), blend shape calls, `transformAttachmentToTexture`, and the `resizeScreen`, `applyGeneralSettings` and `mediaStatusChanged` events.
+- A few layer members read `undefined` (`sortorder`, `ledsource`, `colorBlendMode`, most light properties, ...).
+- Property scripts inside a `createLayer` config aren't registered.
+- Particles still update after scripts within a frame, Wallpaper Engine updates them before.
 
 ## Credits
 

+ 294 - 3
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -787,6 +787,13 @@ CImage::~CImage () {
     this->m_passes.clear ();
     this->m_allPasses.clear ();
 
+    for (auto* pass : this->m_puppetClipMaskPasses) {
+	delete pass;
+    }
+
+    delete this->m_puppetClipTargetPass;
+    delete this->m_puppetClipComposePass;
+
     glDeleteBuffers (1, &this->m_sceneSpacePosition);
     glDeleteBuffers (1, &this->m_copySpacePosition);
     glDeleteBuffers (1, &this->m_passSpacePosition);
@@ -801,6 +808,12 @@ CImage::~CImage () {
     if (this->m_puppetIndices != GL_NONE) {
 	glDeleteBuffers (1, &this->m_puppetIndices);
     }
+    for (const GLuint buffer :
+	 { this->m_puppetClipIndices, this->m_puppetClipComposePosition, this->m_puppetClipComposeTexCoord }) {
+	if (buffer != GL_NONE) {
+	    glDeleteBuffers (1, &buffer);
+	}
+    }
 }
 
 bool CImage::loadPuppetMesh (const glm::vec2& size) {
@@ -859,6 +872,40 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	);
 
 	this->m_puppetIndexCount = static_cast<GLsizei> (mesh->indices.size ());
+	this->m_puppetDrawBuffer = this->m_puppetIndices;
+	this->m_puppetDrawCount = this->m_puppetIndexCount;
+
+	// 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;
+	const size_t indexEnd = layout->block.headerOffset + meshHeaderSize + layout->block.vertexBytes
+	    + sizeof (uint32_t) + layout->block.indexBytes;
+	this->m_puppetClipping.reset ();
+
+	try {
+	    auto clipping = PuppetClipping::read (data, indexEnd, version, mesh->indices.size ());
+
+	    if (clipping.has_value () && clipping->build (mesh->indices)) {
+		glGenBuffers (1, &this->m_puppetClipIndices);
+		glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
+		glBufferData (
+		    GL_ELEMENT_ARRAY_BUFFER, clipping->indices.size () * sizeof (GLushort), clipping->indices.data (),
+		    GL_STATIC_DRAW
+		);
+		sLog.out (
+		    "Puppet ", *this->getImage ().model->puppet, " clipping: ", clipping->records.size (), " masks, ",
+		    clipping->parts.size (), " parts, ", clipping->draws.size (), " draws"
+		);
+		this->m_puppetClipping = std::move (clipping);
+	    } else if (clipping.has_value ()) {
+		sLog.error (
+		    "Puppet ", *this->getImage ().model->puppet, " has clipping masks drawn where their targets are, ",
+		    "which aren't supported, drawing it without them"
+		);
+	    }
+	} catch (const std::exception& ex) {
+	    sLog.error ("Ignoring the clipping masks of ", *this->getImage ().model->puppet, ": ", ex.what ());
+	}
 
 	sLog.out (
 	    "Loaded puppet mesh ", *this->getImage ().model->puppet, " version=", puppetVersion,
@@ -1281,7 +1328,8 @@ void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
 	[this, pass] () {
 	    // a mesh pass into the layer's own buffer starts it fresh, one meant for the scene may be going into a
 	    // passthrough layer's buffer right now, which holds its other children
-	    if (pass->getDestination () != this->getScene ().getFBO ()) {
+	    if (pass == this->m_puppetMeshPass && !this->m_puppetDrawKeep
+		&& pass->getDestination () != this->getScene ().getFBO ()) {
 		GLfloat previousClearColor[4] = {};
 		glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
 		glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
@@ -1291,8 +1339,11 @@ void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
 		);
 	    }
 
-	    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
-	    glDrawElements (GL_TRIANGLES, this->m_puppetIndexCount, GL_UNSIGNED_SHORT, nullptr);
+	    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetDrawBuffer);
+	    glDrawElements (
+		GL_TRIANGLES, this->m_puppetDrawCount, GL_UNSIGNED_SHORT,
+		reinterpret_cast<const void*> (static_cast<uintptr_t> (this->m_puppetDrawOffset) * sizeof (GLushort))
+	    );
 
 	    if (!this->m_puppetDrawErrorChecked) {
 		this->m_puppetDrawErrorChecked = true;
@@ -1343,6 +1394,242 @@ void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
     );
 }
 
+// sub_140209540 / sub_140206AE0: a puppet with clipping records gets clippingmaskimage4 for its masks and its own
+// material again with CLIPPINGUVS and CLIPPINGTARGET for what they clip
+void CImage::setupPuppetClipping () {
+    if (!this->m_puppetClipping.has_value () || this->m_puppetMeshPass == nullptr) {
+	return;
+    }
+
+    const auto& project = this->getScene ().getScene ().project;
+    const auto& records = this->m_puppetClipping->records;
+    auto& overrides = this->m_materials.clippingOverrides;
+    const auto fboProvider = std::make_shared<FBOProvider> (this);
+
+    overrides.push_back (
+	std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
+	    .id = -1,
+	    .combos = { { "CLIPPINGUVS", 1 }, { "CLIPPINGTARGET", 1 } },
+	    .constants = {},
+	    .textures = {},
+	})
+    );
+    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;
+    const auto& imagePasses = this->getImage ().model->material->passes;
+
+    if (!imagePasses.empty () && imagePasses.front ()->blending == BlendingMode_AlphaToCoverage) {
+	maskCombos.emplace ("ALPHATOCOVERAGE", 1);
+    }
+
+    this->m_materials.clippingMask = MaterialParser::load (project, "materials/util/clippingmaskimage4.json");
+
+    for (const auto& record : records) {
+	overrides.push_back (
+	    std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
+		.id = -1,
+		.combos = maskCombos,
+		.constants = {},
+		.textures = { { 1, record.mask } },
+	    })
+	);
+
+	auto* pass = new CPass (
+	    *this, fboProvider, **this->m_materials.clippingMask->passes.begin (), *overrides.back (), std::nullopt,
+	    std::nullopt
+	);
+	pass->addUniform ("g_RenderVar0", &this->m_puppetClipRenderVar0);
+	pass->setClearColor (&this->m_puppetClipClearColor);
+	this->setupPuppetGeometryCallback (pass);
+	this->m_puppetClipMaskPasses.push_back (pass);
+    }
+
+    if (std::ranges::none_of (records, [] (const PuppetClipping::Record& record) { return record.parent != -1; })) {
+	return;
+    }
+
+    // nested masks: the intermediate goes through flattexture onto _rt_FullAlphaMask with identity matrices
+    constexpr GLfloat positions[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f };
+    constexpr GLfloat texcoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
+
+    glGenBuffers (1, &this->m_puppetClipComposePosition);
+    glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (positions), positions, GL_STATIC_DRAW);
+    glGenBuffers (1, &this->m_puppetClipComposeTexCoord);
+    glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (texcoords), texcoords, GL_STATIC_DRAW);
+
+    this->m_materials.clippingCompose = MaterialParser::load (project, "materials/util/flattexture.json");
+    auto* compose = new CPass (
+	*this, fboProvider, **this->m_materials.clippingCompose->passes.begin (), std::nullopt, std::nullopt,
+	std::nullopt
+    );
+    compose->setDestination (this->getScene ().requireAlphaMaskFrameBuffer (false));
+    compose->setInput (this->getScene ().requireAlphaMaskFrameBuffer (true));
+    compose->setKeepDestination (true);
+    compose->setModelViewProjectionMatrix (&this->m_puppetClipIdentity);
+    compose->setModelViewProjectionMatrixInverse (&this->m_puppetClipIdentity);
+    compose->setModelMatrix (&this->m_puppetClipIdentity);
+    compose->setViewProjectionMatrix (&this->m_puppetClipIdentity);
+    static const glm::mat3 identityNormal (1.0f);
+    compose->setLightingTransform (&this->m_puppetClipIdentity, &identityNormal, &this->m_puppetClipIdentity);
+    compose->setEffectTextureProjectionMatrix (&this->m_puppetClipIdentity, &this->m_puppetClipIdentity);
+    // sub_14020D6A0 sets the renderer alpha to 1 for it
+    compose->addUniform ("g_Alpha", &this->m_puppetClipComposeAlpha);
+    compose->setGeometryCallback (
+	[this, compose] () {
+	    const GLint position = glGetAttribLocation (compose->getProgramID (), "a_Position");
+	    const GLint texCoord = glGetAttribLocation (compose->getProgramID (), "a_TexCoord");
+
+	    if (position >= 0) {
+		glEnableVertexAttribArray (position);
+		glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposePosition);
+		glVertexAttribPointer (position, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
+	    }
+
+	    if (texCoord >= 0) {
+		glEnableVertexAttribArray (texCoord);
+		glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetClipComposeTexCoord);
+		glVertexAttribPointer (texCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
+	    }
+	},
+	[] () {
+	    // translucent with renderer flag 0x100 (sub_140099F60): the source color becomes DEST_COLOR, alpha ONE/ONE,
+	    // rgb written only, so the intermediate multiplies into the mask
+	    GLboolean colorMask[4] = {};
+	    glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
+	    glEnable (GL_BLEND);
+	    glBlendFuncSeparate (GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
+	    glColorMask (true, true, true, false);
+	    glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
+	    glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
+	},
+	[compose] () {
+	    for (const char* name : { "a_Position", "a_TexCoord" }) {
+		const GLint location = glGetAttribLocation (compose->getProgramID (), name);
+
+		if (location >= 0) {
+		    glDisableVertexAttribArray (location);
+		}
+	    }
+	}
+    );
+    this->m_puppetClipComposePass = compose;
+}
+
+void CImage::selectPuppetDraw (const int draw) {
+    if (draw < 0 || !this->m_puppetClipping.has_value ()
+	|| static_cast<size_t> (draw) >= this->m_puppetClipping->draws.size ()) {
+	this->m_puppetDrawBuffer = this->m_puppetIndices;
+	this->m_puppetDrawOffset = 0;
+	this->m_puppetDrawCount = draw < 0 ? this->m_puppetIndexCount : 0;
+	return;
+    }
+
+    const auto& range = this->m_puppetClipping->draws[draw];
+    this->m_puppetDrawBuffer = this->m_puppetClipIndices;
+    this->m_puppetDrawOffset = static_cast<GLsizei> (range.offset);
+    this->m_puppetDrawCount = static_cast<GLsizei> (range.count);
+}
+
+void CImage::renderPuppetClipMask (
+    const Effects::CPass& meshPass, const int record, const int draw, const bool clear, const bool intermediate
+) {
+    auto& scene = this->getScene ();
+    auto* pass = this->m_puppetClipMaskPasses[record];
+    const bool inverted = this->m_puppetClipping->records[record].flags & PuppetClipping::Inverted;
+
+    pass->copyBindings (meshPass);
+    pass->setDestination (scene.requireAlphaMaskFrameBuffer (intermediate));
+    // a mesh going onto the scene may be drawn into a passthrough layer, the mask has to be laid out the same way
+    pass->setFollowLayerTarget (meshPass.getDestination () == scene.getFBO ());
+    pass->setKeepDestination (!clear && !intermediate);
+    this->m_puppetClipClearColor = glm::vec4 (inverted ? 1.0f : 0.0f);
+    this->m_puppetClipRenderVar0.x = inverted ? 1.0f : 0.0f;
+
+    this->selectPuppetDraw (draw);
+    pass->render ();
+
+    if (intermediate && this->m_puppetClipComposePass != nullptr) {
+	this->m_puppetClipComposePass->render ();
+    }
+}
+
+void CImage::renderPuppetClipped (Effects::CPass* meshPass) {
+    const auto& commands = this->m_puppetClipping->commands;
+    const auto& records = this->m_puppetClipping->records;
+    auto* target = this->m_puppetClipTargetPass;
+    int draw = 0;
+    bool drawn = false;
+
+    target->copyBindings (*meshPass);
+
+    const auto drawMesh = [&] (Effects::CPass* pass, const int index) {
+	this->selectPuppetDraw (index);
+	this->m_puppetDrawKeep = drawn;
+	pass->setKeepDestination (drawn);
+	pass->render ();
+	drawn = true;
+    };
+
+    const auto drawTargets = [&] (const int record, const int index) {
+	target->setBlendingMode (
+	    records[record].flags & PuppetClipping::Additive ? BlendingMode_Additive : BlendingMode_Translucent
+	);
+	drawMesh (target, index);
+    };
+
+    for (size_t i = 0; i < commands.size (); i++) {
+	switch (commands[i]) {
+	    case PuppetClipping::PlainDraw:
+		drawMesh (meshPass, draw++);
+		break;
+
+	    case PuppetClipping::Mask:
+		{
+		    const int record = commands[++i];
+
+		    if (static_cast<size_t> (record) < records.size ()) {
+			this->renderPuppetClipMask (*meshPass, record, draw, true, false);
+			drawTargets (record, draw + 1);
+		    }
+
+		    draw += 2;
+		    break;
+		}
+
+	    case PuppetClipping::NestedMask:
+		{
+		    const int chain = commands[++i];
+
+		    for (int link = 0; link < chain; link++) {
+			const int parent = commands[++i];
+			const int parentDraw = commands[++i];
+			this->renderPuppetClipMask (*meshPass, parent, parentDraw, link == 0, link != 0);
+		    }
+
+		    const int record = commands[++i];
+		    this->renderPuppetClipMask (*meshPass, record, draw, false, true);
+		    drawTargets (record, draw + 1);
+		    draw += 2;
+		    break;
+		}
+
+	    default:
+		break;
+	}
+    }
+
+    meshPass->setKeepDestination (false);
+    this->m_puppetDrawKeep = false;
+    this->selectPuppetDraw (-1);
+}
+
 bool CImage::followsOutputSize () const {
     // a fullscreen layer takes its texture's size (sub_1401912C0), which for the usual one is _rt_FullFrameBuffer
     return this->getImage ().model->fullscreen && this->m_texture == this->getScene ().getFBO ();
@@ -1624,6 +1911,8 @@ void CImage::setup () {
 	}
     }
 
+    this->setupPuppetClipping ();
+
     passVisibility.resize (this->m_passes.size (), nullptr);
     passFromEffect.resize (this->m_passes.size (), false);
 
@@ -1940,6 +2229,8 @@ void CImage::render () {
 
 	if (*cur == skippedBasePass && std::next (cur) != end) {
 	    (*cur)->clearDestination ();
+	} else if (*cur == this->m_puppetMeshPass && this->m_puppetClipTargetPass != nullptr) {
+	    this->renderPuppetClipped (*cur);
 	} else {
 	    (*cur)->render ();
 	}

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

@@ -9,6 +9,7 @@
 #include "WallpaperEngine/Render/Shaders/Shader.h"
 
 #include "../TextureProvider.h"
+#include "PuppetClipping.h"
 #include "PuppetRig.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 
@@ -194,6 +195,13 @@ private:
     /** Skins the puppet vertices with the current bone matrices and re-uploads them */
     void updatePuppetSkinning ();
     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 ();
+    /** The mesh pass's draw split up like WE's command list (sub_140208670) */
+    void renderPuppetClipped (Effects::CPass* meshPass);
+    /** 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);
     ResolvedTransform updateGeometryBuffers ();
     [[nodiscard]] glm::vec2 resolveGeometrySize (float sceneWidth, float sceneHeight, glm::vec3& origin) const;
     void updateScenePosition (
@@ -220,6 +228,26 @@ private:
     // the pass that draws the warped mesh, and whether it is the last one (straight into the scene FBO)
     Effects::CPass* m_puppetMeshPass = nullptr;
     bool m_puppetMeshLast = false;
+    /** what the puppet geometry callback draws: the whole mesh, or one of the clipping draws */
+    GLuint m_puppetDrawBuffer = GL_NONE;
+    GLsizei m_puppetDrawOffset = 0;
+    GLsizei m_puppetDrawCount = 0;
+    /** the mesh pass draws again into what it already drew this frame */
+    bool m_puppetDrawKeep = false;
+    std::optional<PuppetClipping> m_puppetClipping = std::nullopt;
+    GLuint m_puppetClipIndices = GL_NONE;
+    /** clippingmaskimage4 per record, each with its mask texture */
+    std::vector<Effects::CPass*> m_puppetClipMaskPasses = {};
+    /** the mesh pass's material with CLIPPINGUVS and CLIPPINGTARGET */
+    Effects::CPass* m_puppetClipTargetPass = nullptr;
+    /** flattexture of the intermediate mask multiplied into _rt_FullAlphaMask, for nested masks */
+    Effects::CPass* m_puppetClipComposePass = nullptr;
+    GLuint m_puppetClipComposePosition = GL_NONE;
+    GLuint m_puppetClipComposeTexCoord = GL_NONE;
+    glm::vec4 m_puppetClipRenderVar0 { 0.0f };
+    glm::vec4 m_puppetClipClearColor { 0.0f };
+    glm::mat4 m_puppetClipIdentity { 1.0f };
+    float m_puppetClipComposeAlpha = 1.0f;
     mutable bool m_puppetDrawDiagnosticLogged = false;
     mutable bool m_puppetDrawErrorChecked = false;
     bool m_puppetPositionDiagnosticLogged = false;
@@ -311,6 +339,9 @@ private:
 	} colorBlending;
 	std::vector<MaterialUniquePtr> compatibilityMaterials = {};
 	std::vector<ImageEffectPassOverrideUniquePtr> compatibilityOverrides = {};
+	MaterialUniquePtr clippingMask;
+	MaterialUniquePtr clippingCompose;
+	std::vector<ImageEffectPassOverrideUniquePtr> clippingOverrides = {};
     } m_materials;
 };
 } // namespace WallpaperEngine::Render::Objects

+ 19 - 0
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -794,6 +794,25 @@ std::shared_ptr<const FBOProvider> CPass::getFBOProvider () const { return this-
 
 const CRenderable& CPass::getRenderable () const { return this->m_renderable; }
 
+void CPass::copyBindings (const CPass& other) {
+    this->m_drawTo = other.m_drawTo;
+    this->m_input = other.m_input;
+    this->m_previousInput = other.m_previousInput;
+    this->a_Position = other.a_Position;
+    this->a_TexCoord = other.a_TexCoord;
+    this->m_modelViewProjectionMatrix = other.m_modelViewProjectionMatrix;
+    this->m_modelViewProjectionMatrixInverse = other.m_modelViewProjectionMatrixInverse;
+    this->m_effectModelViewProjectionOverride = other.m_effectModelViewProjectionOverride;
+    this->m_modelMatrix = other.m_modelMatrix;
+    this->m_layerModelMatrix = other.m_layerModelMatrix;
+    this->m_viewProjectionMatrix = other.m_viewProjectionMatrix;
+    this->m_lightingModelMatrix = other.m_lightingModelMatrix;
+    this->m_lightingNormalMatrix = other.m_lightingNormalMatrix;
+    this->m_lightingViewProjectionMatrix = other.m_lightingViewProjectionMatrix;
+    this->m_effectTextureProjectionMatrix = other.m_effectTextureProjectionMatrix;
+    this->m_effectTextureProjectionMatrixInverse = other.m_effectTextureProjectionMatrixInverse;
+}
+
 void CPass::setDestination (std::shared_ptr<const CFBO> drawTo) { this->m_drawTo = std::move (drawTo); }
 
 void CPass::setInput (std::shared_ptr<const TextureProvider> input) { this->m_input = std::move (input); }

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

@@ -41,6 +41,8 @@ public:
      * scene */
     void updatePlaybackTextures () const;
 
+    /** Takes another pass's destination, input, geometry and matrices, for passes drawing the same thing differently */
+    void copyBindings (const CPass& other);
     void setDestination (std::shared_ptr<const CFBO> drawTo);
     void setInput (std::shared_ptr<const TextureProvider> input);
     void setPreviousInput (std::shared_ptr<const TextureProvider> input);

+ 321 - 0
src/WallpaperEngine/Render/Objects/PuppetClipping.cpp

@@ -0,0 +1,321 @@
+#include "PuppetClipping.h"
+
+#include <algorithm>
+#include <climits>
+#include <cstring>
+#include <map>
+#include <set>
+#include <stdexcept>
+
+using namespace WallpaperEngine::Render::Objects;
+
+namespace {
+class Reader {
+public:
+    Reader (const std::vector<char>& data, size_t offset) : m_data (data), m_offset (offset) { }
+
+    template <typename T> T value () {
+	if (m_offset + sizeof (T) > m_data.size ()) {
+	    throw std::runtime_error ("puppet clipping data is cut short");
+	}
+
+	T result;
+	std::memcpy (&result, m_data.data () + m_offset, sizeof (T));
+	m_offset += sizeof (T);
+	return result;
+    }
+
+    std::string string () {
+	const auto* start = m_data.data () + m_offset;
+	const auto* end = static_cast<const char*> (std::memchr (start, '\0', m_data.size () - m_offset));
+
+	if (end == nullptr) {
+	    throw std::runtime_error ("puppet clipping mask name is cut short");
+	}
+
+	m_offset += end - start + 1;
+	return { start, end };
+    }
+
+    void skip (size_t bytes) {
+	if (m_offset + bytes > m_data.size ()) {
+	    throw std::runtime_error ("puppet clipping data is cut short");
+	}
+
+	m_offset += bytes;
+    }
+
+private:
+    const std::vector<char>& m_data;
+    size_t m_offset;
+};
+
+bool contains (const std::vector<uint32_t>& list, uint32_t value) {
+    return std::find (list.begin (), list.end (), value) != list.end ();
+}
+
+// sub_140261880 after the records: a record whose sources are all targets of another one is nested in it, a loop
+// in that chain drops the link
+void linkParents (std::vector<PuppetClipping::Record>& records) {
+    if (records.size () <= 1) {
+	return;
+    }
+
+    for (size_t index = 0; index < records.size (); index++) {
+	auto& record = records[index];
+
+	if (record.sources.empty ()) {
+	    continue;
+	}
+
+	for (size_t other = 0; other < records.size (); other++) {
+	    if (other == index) {
+		continue;
+	    }
+
+	    const auto found = std::ranges::count_if (record.sources, [&] (uint32_t source) {
+		return contains (records[other].targets, source);
+	    });
+
+	    if (static_cast<size_t> (found) == record.sources.size ()) {
+		record.parent = static_cast<int> (other);
+		break;
+	    }
+	}
+
+	std::set<int> seen;
+	for (int parent = record.parent; parent != -1; parent = records[parent].parent) {
+	    if (!seen.insert (parent).second) {
+		record.parent = -1;
+		break;
+	    }
+	}
+    }
+}
+} // namespace
+
+std::optional<PuppetClipping>
+PuppetClipping::read (const std::vector<char>& data, size_t offset, int version, size_t indexCount) {
+    if (version < 23) {
+	return std::nullopt;
+    }
+
+    Reader reader (data, offset);
+    PuppetClipping clipping;
+
+    if (reader.value<uint8_t> () != 0) {
+	reader.value<uint32_t> ();
+	reader.skip (reader.value<uint32_t> ());
+    }
+
+    if (reader.value<uint8_t> () != 0) {
+	const auto bytes = reader.value<uint32_t> ();
+
+	for (uint32_t index = 0; index < bytes / 16; index++) {
+	    reader.value<uint32_t> ();
+	    reader.value<uint32_t> ();
+	    const auto first = reader.value<uint32_t> ();
+	    const auto count = reader.value<uint32_t> ();
+
+	    if (first > indexCount || count > indexCount - first) {
+		throw std::runtime_error ("puppet part range is past the index buffer");
+	    }
+
+	    clipping.parts.push_back ({ .firstIndex = first, .indexCount = count });
+	}
+
+	reader.skip (bytes % 16);
+    }
+
+    const auto count = reader.value<uint32_t> ();
+
+    for (uint32_t index = 0; index < count; index++) {
+	Record record;
+	reader.value<uint64_t> ();
+	record.mask = reader.string ();
+	record.flags = reader.value<uint32_t> ();
+
+	for (auto* list : { &record.targets, &record.sources }) {
+	    const auto entries = reader.value<uint32_t> ();
+
+	    for (uint32_t entry = 0; entry < entries; entry++) {
+		const auto part = reader.value<uint32_t> ();
+
+		// WE fails fast on these
+		if (part >= clipping.parts.size ()) {
+		    throw std::runtime_error ("puppet clipping record names a part that doesn't exist");
+		}
+
+		list->push_back (part);
+	    }
+	}
+
+	clipping.records.push_back (std::move (record));
+    }
+
+    if (clipping.records.empty ()) {
+	return std::nullopt;
+    }
+
+    linkParents (clipping.records);
+    return clipping;
+}
+
+bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
+    // the AtTargets path (part flag 4 in sub_14020B720) reads like it takes every later part as a target, left out
+    if (std::ranges::any_of (this->records, [] (const Record& record) { return record.flags & AtTargets; })) {
+	return false;
+    }
+
+    constexpr uint32_t Target = 0x1;
+    constexpr uint32_t Source = 0x8;
+
+    const auto partCount = static_cast<int> (this->parts.size ());
+    std::vector<uint32_t> partFlags (this->parts.size (), 0);
+
+    for (const auto& record : this->records) {
+	for (const auto part : record.targets) {
+	    partFlags[part] |= Target;
+	}
+
+	for (const auto part : record.sources) {
+	    partFlags[part] |= Source;
+	}
+    }
+
+    struct Entry {
+	uint32_t record = 0;
+	int firstTarget = INT_MAX;
+	int firstSource = -1;
+	int lastSource = -1;
+	std::vector<uint32_t> maskParts;
+	std::vector<uint32_t> targets;
+    };
+
+    std::vector<Entry> entries (this->records.size ());
+    std::set<uint32_t> hiddenSources;
+
+    for (size_t index = 0; index < this->records.size (); index++) {
+	const auto& record = this->records[index];
+	auto& entry = entries[index];
+	entry.record = static_cast<uint32_t> (index);
+
+	for (int part = 0; part < partCount; part++) {
+	    if ((partFlags[part] & Target) && contains (record.targets, part)) {
+		entry.targets.push_back (part);
+		entry.firstTarget = std::min (entry.firstTarget, part);
+	    }
+
+	    if (contains (record.sources, part)) {
+		if (entry.firstSource < 0) {
+		    entry.firstSource = part;
+		}
+
+		entry.lastSource = part;
+
+		if (record.flags & HideSources) {
+		    hiddenSources.insert (part);
+		}
+	    }
+	}
+
+	// everything drawn between the first and the last source makes the mask, apart from the record's own targets
+	for (int part = 0; part < partCount; part++) {
+	    if (entry.firstSource <= part && entry.lastSource >= part && !contains (entry.targets, part)) {
+		entry.maskParts.push_back (part);
+	    }
+	}
+    }
+
+    // a nested mask can only be drawn once its ancestors' sources are
+    for (size_t index = 0; index < entries.size (); index++) {
+	for (int parent = this->records[index].parent; parent != -1; parent = this->records[parent].parent) {
+	    entries[index].lastSource = std::max (entries[index].lastSource, entries[parent].lastSource);
+	}
+    }
+
+    std::ranges::stable_sort (entries, [] (const Entry& a, const Entry& b) { return a.firstTarget < b.firstTarget; });
+
+    this->indices.clear ();
+    this->draws.clear ();
+    this->commands.clear ();
+
+    const auto addDraw = [this, &meshIndices] (const std::vector<uint32_t>& list) {
+	Draw draw { .offset = static_cast<uint32_t> (this->indices.size ()), .count = 0 };
+
+	for (const auto part : list) {
+	    const auto& range = this->parts[part];
+	    this->indices.insert (
+		this->indices.end (), meshIndices.begin () + range.firstIndex,
+		meshIndices.begin () + range.firstIndex + range.indexCount
+	    );
+	    draw.count += range.indexCount;
+	}
+
+	this->draws.push_back (draw);
+	return static_cast<int> (this->draws.size () - 1);
+    };
+
+    std::vector<uint32_t> pending;
+    std::map<uint32_t, int> maskDraws;
+
+    const auto flush = [&] () {
+	if (pending.empty ()) {
+	    return;
+	}
+
+	addDraw (pending);
+	this->commands.push_back (PlainDraw);
+	pending.clear ();
+    };
+
+    for (int part = 0; part < partCount; part++) {
+	const uint32_t flags = partFlags[part];
+
+	if (!(flags & Target)) {
+	    if (!hiddenSources.contains (part)) {
+		pending.push_back (part);
+	    }
+	} else if (!(flags & Source)) {
+	    // drawn with its record
+	    continue;
+	}
+
+	if (!(flags & Source)) {
+	    continue;
+	}
+
+	for (const auto& entry : entries) {
+	    if (entry.lastSource != part) {
+		continue;
+	    }
+
+	    flush ();
+
+	    std::vector<int> chain;
+	    for (int parent = this->records[entry.record].parent; parent != -1; parent = this->records[parent].parent) {
+		chain.push_back (parent);
+	    }
+
+	    maskDraws[entry.record] = addDraw (entry.maskParts);
+	    addDraw (entry.targets);
+
+	    if (chain.empty ()) {
+		this->commands.push_back (Mask);
+	    } else {
+		this->commands.push_back (NestedMask);
+		this->commands.push_back (static_cast<int> (chain.size ()));
+
+		for (const auto parent : chain) {
+		    this->commands.push_back (parent);
+		    this->commands.push_back (maskDraws[parent]);
+		}
+	    }
+
+	    this->commands.push_back (static_cast<int> (entry.record));
+	}
+    }
+
+    flush ();
+    return true;
+}

+ 73 - 0
src/WallpaperEngine/Render/Objects/PuppetClipping.h

@@ -0,0 +1,73 @@
+#pragma once
+
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace WallpaperEngine::Render::Objects {
+/**
+ * Clipping masks of a puppet mesh (MDLV 23+), read and turned into draws the way wallpaper64.exe 2.8.42 does: the
+ * loader (sub_140261880) reads the part ranges and the records, the image setup (sub_14020AE00, sub_14020B720) splits
+ * the index buffer into draws and builds the command list the final draw (sub_140208670 / sub_140208C80) walks.
+ */
+struct PuppetClipping {
+    enum RecordFlags : uint32_t {
+	/** the targets are drawn additively instead of translucent */
+	Additive = 0x1,
+	/** the mask is inverted: cleared to white, the shader flips it (g_RenderVar0.x) */
+	Inverted = 0x2,
+	/** the sources only make the mask, they aren't drawn themselves */
+	HideSources = 0x4,
+	/** the mask is drawn where its targets are instead of after its last source, not ported */
+	AtTargets = 0x8,
+    };
+
+    struct Part {
+	uint32_t firstIndex = 0;
+	uint32_t indexCount = 0;
+    };
+
+    struct Record {
+	/** texture name relative to materials/, sampled through the mesh UVs */
+	std::string mask;
+	uint32_t flags = 0;
+	/** parts drawn through the mask */
+	std::vector<uint32_t> targets;
+	/** parts that make the mask */
+	std::vector<uint32_t> sources;
+	/** the record whose targets contain every source of this one, its mask is multiplied in */
+	int parent = -1;
+    };
+
+    struct Draw {
+	uint32_t offset = 0;
+	uint32_t count = 0;
+    };
+
+    enum Command : int {
+	/** draw the next draw normally */
+	PlainDraw = 0,
+	/** record: its mask from the next draw, the targets with the one after */
+	Mask = 1,
+	/** chain length, (record, mask draw) per ancestor, record: like Mask with the ancestors' masks multiplied in */
+	NestedMask = 2,
+    };
+
+    /**
+     * Reads what follows a puppet's index buffer. offset is the end of the index data, nullopt when the file has no
+     * clipping records
+     */
+    static std::optional<PuppetClipping>
+    read (const std::vector<char>& data, size_t offset, int version, size_t indexCount);
+
+    /** Splits the mesh's indices into WE's draws and fills commands, false when the records can't be drawn here */
+    bool build (const std::vector<uint16_t>& meshIndices);
+
+    std::vector<Part> parts;
+    std::vector<Record> records;
+    std::vector<uint16_t> indices;
+    std::vector<Draw> draws;
+    std::vector<int> commands;
+};
+} // namespace WallpaperEngine::Render::Objects

+ 20 - 0
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -911,6 +911,26 @@ std::shared_ptr<const CFBO> CScene::requireReflectionFrameBuffer () {
     return this->_rt_Reflection;
 }
 
+std::shared_ptr<const CFBO> CScene::requireAlphaMaskFrameBuffer (const bool intermediate) {
+    auto& buffer = intermediate ? this->_rt_FullAlphaMaskIntermediate : this->_rt_FullAlphaMask;
+
+    if (buffer != nullptr) {
+	return buffer;
+    }
+
+    // sub_1401AADB0 with divisor 2, no depth
+    const uint32_t width = std::max (this->m_sceneFBO->getRealWidth () / 2, 2u);
+    const uint32_t height = std::max (this->m_sceneFBO->getRealHeight () / 2, 2u);
+
+    buffer = this->create (
+	intermediate ? "_rt_FullAlphaMaskIntermediate" : "_rt_FullAlphaMask", TextureFormat_R8, TextureFlags_ClampUVs,
+	1.0, { width, height }, { width, height }
+    );
+    this->followOutputSize (buffer, 2);
+
+    return buffer;
+}
+
 void CScene::addReflectionReceiver (const int id) { this->m_reflectionReceivers.insert (id); }
 
 void CScene::renderReflection () {

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

@@ -50,6 +50,11 @@ public:
      * (sub_140181AF0, scene flag 1)
      */
     std::shared_ptr<const CFBO> requireReflectionFrameBuffer ();
+    /**
+     * _rt_FullAlphaMask / _rt_FullAlphaMaskIntermediate, the puppet clipping masks: R8 at half the output size, made
+     * by the first puppet that draws one (sub_140208670)
+     */
+    std::shared_ptr<const CFBO> requireAlphaMaskFrameBuffer (bool intermediate);
     /** An object whose program samples _rt_Reflection, it stays out of the reflection pass (object flag 8) */
     void addReflectionReceiver (int id);
     /** While the mirrored reflection pass draws, culling is inverted */
@@ -413,6 +418,8 @@ private:
     std::shared_ptr<const CFBO> _rt_shadowAtlas = nullptr;
     std::shared_ptr<const CFBO> _rt_MipMappedFrameBuffer = nullptr;
     std::shared_ptr<CFBO> _rt_Reflection = nullptr;
+    std::shared_ptr<CFBO> _rt_FullAlphaMask = nullptr;
+    std::shared_ptr<CFBO> _rt_FullAlphaMaskIntermediate = nullptr;
     std::set<int> m_reflectionReceivers = {};
     bool m_renderingReflection = false;
     struct OutputSizedBuffer {

+ 134 - 0
tools/mdl_scan.py

@@ -0,0 +1,134 @@
+#!/usr/bin/env python3
+"""Counts what every installed .mdl carries, read the way wallpaper64.exe 2.8.42 reads it (sub_140261880).
+
+Usage:
+    mdl_scan.py [workshop dir]
+
+Walks every item's .pkg files and loose .mdl files plus the assets dir and prints, per feature, how many files
+have it and which items: MDLV versions, vertex formats, mesh flag bits, the MDLV 21 auxiliary vertex block and part
+ranges, MDLV 23 clipping records, and every section after the meshes (MDLS/MDLA/MDAT/MDMP/MDLE with versions).
+"""
+import struct, os, glob, collections, sys
+roots=[sys.argv[1] if len(sys.argv) > 1 else os.environ.get('LWE_WORKSHOP_DIR', '/workspace/SteamLibrary/steamapps/workshop/content/431960')]
+assets=os.environ.get('LWE_ASSETS_DIR', '/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets')
+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)
+def files():
+    for item in sorted(os.listdir(roots[0])):
+        d=os.path.join(roots[0],item)
+        for pkg in glob.glob(d+'/*.pkg'):
+            for name,data in pkg_entries(pkg): yield item,name,data
+        for p in glob.glob(d+'/**/*.mdl',recursive=True):
+            yield item,os.path.relpath(p,d),open(p,'rb').read()
+    for p in glob.glob(assets+'/**/*.mdl',recursive=True):
+        yield 'assets',os.path.relpath(p,assets),open(p,'rb').read()
+class R:
+    def __init__(s,d,o=0): s.d=d; s.o=o
+    def u32(s): v=struct.unpack_from('<I',s.d,s.o)[0]; s.o+=4; return v
+    def u8(s): v=s.d[s.o]; s.o+=1; return v
+    def skip(s,n): s.o+=n
+    def s(s):
+        e=s.d.index(b'\0',s.o); v=s.d[s.o:e].decode('utf-8','replace'); s.o=e+1; return v
+def note(stats,ex,key,item,n=1):
+    if n: stats[key]+=n; ex[key].add(item)
+
+# MDLS like PuppetRig::parsePuppetBones: bones, then (v2+) extra records, rest pose, constraints
+def mdls(d,o,ver,stats,ex,item):
+    r=R(d,o+13); bones=r.u32()
+    for _ in range(bones):
+        r.s(); r.u32(); r.u32(); r.skip(r.u32()); r.s()
+    rig={'bones':bones,'extras':0,'constraints':0}
+    if ver<2: return rig
+    extras=struct.unpack_from('<H',d,r.o)[0]; r.skip(2)
+    for _ in range(extras): r.s(); r.skip(8+64)
+    note(stats,ex,'MDLS extra records',item,extras)
+    if r.u8(): r.skip(64*(bones+extras)); note(stats,ex,'MDLS rest pose',item)
+    cons=r.u32(); note(stats,ex,'MDLS constraints',item,cons)
+    for _ in range(cons):
+        r.skip(12); fl=r.u32() if ver>=4 else 0
+        if fl&2: r.skip(8)
+    rig.update(extras=extras,constraints=cons)
+    return rig
+
+# MDLA like PuppetRig::parsePuppetAnimationClips, counting the tracks we skip
+def mdla(d,o,ver,rig,meshes,stats,ex,item):
+    r=R(d,o+13); clips=r.u32()
+    for _ in range(clips):
+        r.skip(8); r.s(); r.s(); r.skip(4); frames=r.u32(); flags=r.u32(); bones=r.u32(); n=frames+1
+        for _ in range(bones): r.u32(); r.skip(r.u32())
+        def tracks(count, key):
+            k=0
+            for _ in range(count): r.u32(); r.skip(r.u32()); k+=1
+            note(stats,ex,key,item,k)
+        if ver>=2:
+            tracks(rig['extras'],'MDLA v2 extra tracks'); tracks(rig['constraints'],'MDLA v2 constraint tracks')
+        if ver>=3:
+            tracks(r.u32(),'MDLA v3 counted float tracks')
+            if r.u8(): tracks(bones,'MDLA v3 bone alpha tracks')
+        if ver>=4 and r.u8():
+            for _ in range(meshes):
+                if r.u32()&1:
+                    r.u32(); c=struct.unpack_from('<H',d,r.o)[0]; r.skip(2)
+                    for _ in range(c): r.skip(2); r.skip(r.u32())
+                    note(stats,ex,'MDLA v4 morph tracks',item,c)
+        if ver>=5:
+            ints=struct.unpack_from('<6I',d,r.o); r.skip(24)
+            if any(ints): note(stats,ex,'MDLA v5 ints nonzero',item)
+        if ver>=6 and r.u8(): tracks(bones,'MDLA v6 draw order tracks')
+        if flags&1: r.skip(2+16); note(stats,ex,'MDLA root motion',item)
+        ev=r.u32()
+        for _ in range(ev): r.u32(); r.s()
+        note(stats,ex,'MDLA events',item,ev)
+
+stats=collections.Counter(); ex=collections.defaultdict(set)
+for item,name,d in files():
+    try:
+        r=R(d); magic=r.s()
+        if not magic.startswith('MDLV'): stats['notMDLV']+=1; continue
+        ver=int(magic[4:]); fmt=r.u32(); mpm=r.u32(); mc=r.u32()
+        stats['MDLV%04d'%ver]+=1; ex['MDLV%04d'%ver].add(item)
+        if mc>1: stats['multimesh']+=1; ex['multimesh'].add(item)
+        if mpm!=1: stats['materialsPerMesh=%d'%mpm]+=1; ex['materialsPerMesh=%d'%mpm].add(item)
+        for i in range(mc):
+            for _ in range(mpm): r.s()
+            fl=0
+            if ver>=4:
+                fl=r.u32()
+                if fl&2: r.u32(); stats['meshflag2']+=1; ex['meshflag2'].add(item)
+                if ver>=17: r.o+=24
+                if ver>=15: fmt2=r.u32(); stats['fmt=%x'%fmt2]+=1; ex['fmt=%x'%fmt2].add(item)
+            for b in range(32):
+                if fl&(1<<b): stats['meshflagbit %#x'%(1<<b)]+=1; ex['meshflagbit %#x'%(1<<b)].add(item)
+            r.skip(r.u32()); r.skip(r.u32())
+            if ver>=21:
+                if r.u8(): r.u32(); r.skip(r.u32()); stats['v21 aux block']+=1; ex['v21 aux block'].add(item)
+                if r.u8(): r.skip(r.u32()); stats['v21 ranges']+=1
+            if ver>=23:
+                n=r.u32()
+                if n: stats['clip records']+=1; ex['clip records'].add(item)
+                for _ in range(n):
+                    r.o+=8; r.s(); r.u32(); r.skip(4*r.u32()); r.skip(4*r.u32())
+        o=r.o; seen=set(); rig=None
+        while o+13<=len(d) and d[o]!=0 and o not in seen:
+            seen.add(o); tag=d[o:o+8].decode('ascii','replace'); nxt=struct.unpack_from('<I',d,o+9)[0]
+            stats[tag]+=1; ex[tag].add(item)
+            try:
+                if tag.startswith('MDLS'): rig=mdls(d,o,int(tag[4:]),stats,ex,item)
+                if tag.startswith('MDLA') and rig: mdla(d,o,int(tag[4:]),rig,mc,stats,ex,item)
+            except Exception as e:
+                stats['%s parseERR'%tag[:4]]+=1; ex['%s parseERR'%tag[:4]].add(item)
+            if nxt<=o: break
+            o=nxt
+        if o<len(d) and o not in seen: pass
+    except Exception as e:
+        stats['parseERR']+=1; ex['parseERR'].add(item+':'+name+':'+str(e)[:40])
+for k in sorted(stats): print('%-22s %5d  %s'%(k,stats[k],' '.join(sorted(ex[k]))[:150]))