Quellcode durchsuchen

WE 2.8.42 parity pass, live properties, video parts, faster loading

  Rendering / layout
  - image quads are WE's centered int-size quad in object space, the world matrix goes into the MVP; the old 2D
    parent chain resolve, ancestor tilt correction and the puppet scene-position bake are gone
  - scene quads sample 0.15 texel in from every edge like WE (plain draw unless fullscreen/nopadding/passthrough/
    solid, last effect pass unless fullscreen/passthrough/solid), text too
  - puppet attachment points are part of the parent chain, so particles and text attached to a puppet follow its bones
  - blend alpha factors are the colour factors, no alpha writes onto the scene target unless the material's
    alphawriting says so (copybackground compose layers no longer go hazy)
  - WE's layer buffer pooling: only flag 0x10 layers get a named _a buffer, the rest share pooled buffers, nested
    passthrough layers share their parent's (fixes the black square)
  - passthrough layers with children composite through effectpassthrough with the layer colour
  - unresolved _rt_imageLayerComposite_ names and missing texture files bind WE's yellow/black checker texture
  - overrides of slots the pass already binds are skipped (no more _rt_FullCompoBuffer resolve errors)
  - lit layers drawn straight to the scene use the plain material without PRELIGHTING, 3D lighting uses the object's
    world matrix
  - g_TexelSize / g_TexelSizeHalf follow the output size every frame
  - model frustum culling with MDLA v5 clip boxes and .mdl bounds (+-131072 fallback for old models)
  - cursor position uses WE's top-left origin, parallax was mirrored on vflipped outputs

  Post processing
  - bloom, HDR bloom, HDR combine, camera fade and color adjustments (ccsimple) run through WE's own util materials
    (new FrameMaterial), the fake bloom layer and its virtual effect files are gone
  - HDR combine writes linear scRGB, the output pass encodes it for SDR or BT.2020 for --hdr
  - videos get the color adjustments too, the back buffer lives in CWallpaper
  - new --post-processing disabled (no bloom)

  Effects / FBOs / textures
  - effect.json fbos: width/height/fit, uvs repeat, conditions against combos, instance combos, per pass overrides
    by pass index; buffers clamped unless repeat
  - FBO format names follow WE's table, backbuffer formats switch to half float in HDR scenes, more formats mapped
  - textures upload their raw format like WE (RGB888/565 as RGBA8, RGB161616f as RGBA16F), short mips zero padded,
    mips decoded on worker threads
  - TEXV0005 tagged sections with versions, TEXB0004 conditional textures repaint when a property changes
  - MP4 guess for TEXB0004 raw textures removed

  Text
  - without flag 0x10 the last effect pass draws onto the scene, effectpassthrough only for flag 0x10
  - measured text size for scripts, buffered only for visible effects or flag 0x10

  Particles
  - simulated in WE's world space, all y flips removed, the scene matrix only applies at draw; 3D particles were
    mirrored before
  - simulation runs in the object update before scripts
  - one rasterizer state for all objects (cull mode normal no longer culls every sprite)
  - lifetimerandom exponent, rope uvscrolling as in 2.8.42, alpha to coverage under MSAA, spritesheetrefreshsync
  - layerimage emitters read the layer's buffer (effects included) with puppet bone assignment
  - collision sphere/quad defaults are WE's

  Puppets
  - MORPHING_MODIFIERS, clipping record flag 8, blend map only on the lit/albedo path, otherwise drawn into the
    layer buffer
  - WE's prelighting draw for lit puppets (skinning, packed bones, MDLV aux block / PRELIGHTINGDUALVERTEX)
  - CPU morphs only when the vertex shader uses MORPHING
  - hit boxes and hit order from MDLS for cursor events
  - animation layers created by scripts get their config property scripts, removed ones retire their scripts first

  Scripting
  - ILayer.setParent, thisScene.destroyLayer, getLayer returns null for unknown layers
  - IEffect.getMaterial / setMaterialProperty and IMaterial (degree constants, material state)
  - blend shape calls, transformAttachmentToTexture, event.hitBox and event.button
  - resizeScreen, destroy and applyUserProperties events, media metadata albumArtist and genres
  - general settings (ambient/skylight colour etc) run their scripts and animations, fixes over-bright lit scenes
  - light, renderable and object members, camera queuemode property
  - first frame runs script init, then the static camera, then the update

  Live changes / hotswap
  - user properties apply live without a reload (scenes, scripts, web pages, splats); a null slider value keeps the
    scene's bound value instead of aborting
  - control file: effects=1 with disable-effect=/enable-effect=, disable-animations=on/off, xray=disabled

  Video
  - --video-segments "2:00-3:00,4:00-5:00" plays several parts and skips the gaps, video-start/end edit one part,
    control file video-segments=
  - the video FBO follows mpv's size (screenshots were a 16x16 corner)

  Web
  - linux-wallpaperengine-web-helper as Chromium's subprocess exe (faster start), main() hands --type= processes
    straight to CEF
  - previous wallpaper stays on screen until the new web page has painted
  - fixed the page staying 16x17 when a resize landed during browser creation
  - web FBO resizes with the frame (whole screen was the top-left pixel colour)
  - audio goes to pages as raw [L64|R64] bands every 33 ms like WE, SpectrumNormalizer removed

  Loading speed
  - cached regex traits in ShaderUnit (most of a model scene's load time), memoized rewrites
  - shader cache in ~/.cache/linux-wallpaperengine/shaders (translations + program binaries), --no-shader-cache
  - .mdl files read once per scene

  Fixes
  - screenshot resampling dropped/doubled columns
  - SIGTERM handler no longer logs (deadlock when the signal hit inside malloc)
UwU vor 1 Monat
Ursprung
Commit
09cdf36347
100 geänderte Dateien mit 6202 neuen und 2148 gelöschten Zeilen
  1. 26 4
      CMakeLists.txt
  2. 4 2
      README.md
  3. 49 22
      src/WallpaperEngine/Application/ApplicationContext.cpp
  4. 6 5
      src/WallpaperEngine/Application/ApplicationContext.h
  5. 7 3
      src/WallpaperEngine/Application/ApplicationState.h
  6. 265 147
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  7. 8 12
      src/WallpaperEngine/Application/WallpaperApplication.h
  8. 2 2
      src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.cpp
  9. 3 3
      src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h
  10. 5 45
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp
  11. 0 14
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h
  12. 0 56
      src/WallpaperEngine/Audio/SpectrumNormalizer.cpp
  13. 0 24
      src/WallpaperEngine/Audio/SpectrumNormalizer.h
  14. 10 17
      src/WallpaperEngine/Data/Assets/Texture.h
  15. 4 2
      src/WallpaperEngine/Data/Model/DynamicValue.cpp
  16. 55 0
      src/WallpaperEngine/Data/Model/Effect.cpp
  17. 32 0
      src/WallpaperEngine/Data/Model/Effect.h
  18. 2 0
      src/WallpaperEngine/Data/Model/Material.h
  19. 37 17
      src/WallpaperEngine/Data/Model/Object.h
  20. 13 2
      src/WallpaperEngine/Data/Model/Property.h
  21. 1 0
      src/WallpaperEngine/Data/Model/Types.h
  22. 1 0
      src/WallpaperEngine/Data/Model/Wallpaper.h
  23. 135 3
      src/WallpaperEngine/Data/Parsers/EffectParser.cpp
  24. 1 0
      src/WallpaperEngine/Data/Parsers/EffectParser.h
  25. 1 0
      src/WallpaperEngine/Data/Parsers/MaterialParser.cpp
  26. 58 20
      src/WallpaperEngine/Data/Parsers/ObjectParser.cpp
  27. 1 0
      src/WallpaperEngine/Data/Parsers/ObjectParser.h
  28. 3 1
      src/WallpaperEngine/Data/Parsers/PropertyParser.cpp
  29. 72 123
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  30. 3 3
      src/WallpaperEngine/Data/Parsers/TextureParser.h
  31. 4 1
      src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp
  32. 17 0
      src/WallpaperEngine/Media/DBusMediaSource.cpp
  33. 3 0
      src/WallpaperEngine/Media/MediaSource.h
  34. 8 0
      src/WallpaperEngine/Render/CFBO.cpp
  35. 151 42
      src/WallpaperEngine/Render/CTexture.cpp
  36. 12 1
      src/WallpaperEngine/Render/CTexture.h
  37. 106 6
      src/WallpaperEngine/Render/CWallpaper.cpp
  38. 39 0
      src/WallpaperEngine/Render/CWallpaper.h
  39. 1 2
      src/WallpaperEngine/Render/Camera.h
  40. 31 0
      src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp
  41. 15 4
      src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.h
  42. 36 12
      src/WallpaperEngine/Render/FBOProvider.cpp
  43. 2 1
      src/WallpaperEngine/Render/FBOProvider.h
  44. 328 0
      src/WallpaperEngine/Render/FrameMaterial.cpp
  45. 79 0
      src/WallpaperEngine/Render/FrameMaterial.h
  46. 46 0
      src/WallpaperEngine/Render/MissingTexture.cpp
  47. 35 0
      src/WallpaperEngine/Render/MissingTexture.h
  48. 11 1
      src/WallpaperEngine/Render/Objects/CCamera.cpp
  49. 591 248
      src/WallpaperEngine/Render/Objects/CImage.cpp
  50. 101 45
      src/WallpaperEngine/Render/Objects/CImage.h
  51. 22 0
      src/WallpaperEngine/Render/Objects/CLight.cpp
  52. 65 50
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  53. 8 1
      src/WallpaperEngine/Render/Objects/CMesh.h
  54. 382 183
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  55. 32 11
      src/WallpaperEngine/Render/Objects/CParticle.h
  56. 53 7
      src/WallpaperEngine/Render/Objects/CRenderable.cpp
  57. 11 3
      src/WallpaperEngine/Render/Objects/CRenderable.h
  58. 19 7
      src/WallpaperEngine/Render/Objects/CSound.cpp
  59. 5 0
      src/WallpaperEngine/Render/Objects/CSound.h
  60. 75 28
      src/WallpaperEngine/Render/Objects/CText.cpp
  61. 6 1
      src/WallpaperEngine/Render/Objects/CText.h
  62. 293 78
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  63. 37 5
      src/WallpaperEngine/Render/Objects/Effects/CPass.h
  64. 57 33
      src/WallpaperEngine/Render/Objects/PuppetClipping.cpp
  65. 1 3
      src/WallpaperEngine/Render/Objects/PuppetClipping.h
  66. 1 1
      src/WallpaperEngine/Render/Objects/PuppetIK.cpp
  67. 154 14
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  68. 22 0
      src/WallpaperEngine/Render/Objects/PuppetRig.h
  69. 109 1
      src/WallpaperEngine/Render/RenderContext.cpp
  70. 16 1
      src/WallpaperEngine/Render/RenderContext.h
  71. 13 0
      src/WallpaperEngine/Render/Shaders/GLSLContext.cpp
  72. 372 0
      src/WallpaperEngine/Render/Shaders/ShaderCache.cpp
  73. 53 0
      src/WallpaperEngine/Render/Shaders/ShaderCache.h
  74. 211 126
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  75. 2 0
      src/WallpaperEngine/Render/Shaders/ShaderUnit.h
  76. 4 0
      src/WallpaperEngine/Render/Shaders/Variables/ShaderVariable.h
  77. 115 21
      src/WallpaperEngine/Render/TextureCache.cpp
  78. 27 0
      src/WallpaperEngine/Render/TextureCache.h
  79. 3 3
      src/WallpaperEngine/Render/Volumetrics.cpp
  80. 363 439
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  81. 87 27
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  82. 8 0
      src/WallpaperEngine/Render/Wallpapers/CSplat.cpp
  83. 108 9
      src/WallpaperEngine/Render/Wallpapers/CVideo.cpp
  84. 9 2
      src/WallpaperEngine/Render/Wallpapers/CVideo.h
  85. 116 18
      src/WallpaperEngine/Render/Wallpapers/CWeb.cpp
  86. 7 0
      src/WallpaperEngine/Render/Wallpapers/CWeb.h
  87. 509 25
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp
  88. 7 0
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h
  89. 34 5
      src/WallpaperEngine/Scripting/SceneObject.cpp
  90. 127 11
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  91. 12 4
      src/WallpaperEngine/Scripting/ScriptEngine.h
  92. 12 0
      src/WallpaperEngine/Scripting/ScriptPropertiesObject.cpp
  93. 2 0
      src/WallpaperEngine/Scripting/ScriptPropertiesObject.h
  94. 56 0
      src/WallpaperEngine/Scripting/ScriptableObject.cpp
  95. 8 0
      src/WallpaperEngine/Scripting/ScriptableObject.h
  96. 4 4
      src/WallpaperEngine/Testing/Cases/SpectrumListeners.cpp
  97. 0 95
      src/WallpaperEngine/Testing/Cases/SpectrumNormalizer.cpp
  98. 113 35
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp
  99. 15 7
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h
  100. 17 0
      src/WallpaperEngine/VideoPlayback/VideoSegment.h

+ 26 - 4
CMakeLists.txt

@@ -372,8 +372,6 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp
     src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h
     src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.cpp
-    src/WallpaperEngine/Audio/SpectrumNormalizer.cpp
-    src/WallpaperEngine/Audio/SpectrumNormalizer.h
     src/WallpaperEngine/Desktop/IconTheme.cpp
     src/WallpaperEngine/Desktop/IconTheme.h
     src/WallpaperEngine/Desktop/UserShortcut.cpp
@@ -430,6 +428,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Shaders/ShaderUnit.h
     src/WallpaperEngine/Render/Shaders/GLSLContext.cpp
     src/WallpaperEngine/Render/Shaders/GLSLContext.h
+    src/WallpaperEngine/Render/Shaders/ShaderCache.cpp
+    src/WallpaperEngine/Render/Shaders/ShaderCache.h
 
     src/WallpaperEngine/Render/Helpers/ContextAware.cpp
     src/WallpaperEngine/Render/Helpers/ContextAware.h
@@ -489,6 +489,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/CTexture.h
     src/WallpaperEngine/Render/AlbumTexture.h
     src/WallpaperEngine/Render/AlbumTexture.cpp
+    src/WallpaperEngine/Render/MissingTexture.h
+    src/WallpaperEngine/Render/MissingTexture.cpp
     src/WallpaperEngine/Render/TextureProvider.h
 
     src/WallpaperEngine/Render/Objects/CRenderable.cpp
@@ -519,6 +521,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Objects/CCamera.cpp
     src/WallpaperEngine/Render/Volumetrics.h
     src/WallpaperEngine/Render/Volumetrics.cpp
+    src/WallpaperEngine/Render/FrameMaterial.h
+    src/WallpaperEngine/Render/FrameMaterial.cpp
     src/WallpaperEngine/Render/ShadowMapping.h
     src/WallpaperEngine/Render/ShadowMapping.cpp
     src/WallpaperEngine/Render/ModelData.h
@@ -564,6 +568,7 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Data/Model/UserSetting.h
     src/WallpaperEngine/Data/Model/DynamicValue.h
     src/WallpaperEngine/Data/Model/DynamicValue.cpp
+    src/WallpaperEngine/Data/Model/Effect.cpp
     src/WallpaperEngine/Data/Model/PropertyAnimation.h
     src/WallpaperEngine/Data/Model/Property.h
     src/WallpaperEngine/Data/Utils/TypeCaster.h
@@ -654,7 +659,6 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/MouseCoordinates.cpp
         src/WallpaperEngine/Testing/Cases/PropertyParser.cpp
         src/WallpaperEngine/Testing/Cases/SpectrumListeners.cpp
-        src/WallpaperEngine/Testing/Cases/SpectrumNormalizer.cpp
         src/WallpaperEngine/Testing/Cases/SpectrumPipeline.cpp
         src/WallpaperEngine/Testing/Cases/ParticleNoise.cpp
         src/WallpaperEngine/Testing/Cases/UserShortcut.cpp
@@ -800,9 +804,26 @@ add_executable(linux-wallpaperengine
 
 target_link_libraries (linux-wallpaperengine PUBLIC linux-wallpaperengine-lib)
 
+# Chromium child processes of the web host, only libcef and the page shim
+add_executable(linux-wallpaperengine-web-helper
+    src/web_helper.cpp
+    src/WallpaperEngine/WebBrowser/CEF/SubprocessApp.cpp)
+
+target_include_directories(linux-wallpaperengine-web-helper PRIVATE
+    src
+    ${CEF_INCLUDE_PATH}
+    ${CMAKE_SOURCE_DIR})
+
+target_link_libraries(linux-wallpaperengine-web-helper PRIVATE
+    libcef_lib
+    libcef_dll_wrapper)
+
+add_dependencies(linux-wallpaperengine-web-helper libcef_dll_wrapper)
+REPLACED_SET_EXECUTABLE_TARGET_PROPERTIES(linux-wallpaperengine-web-helper)
+
 # Install the main executable and shared library via install(TARGETS)
 # so that CMake automatically strips/replaces the build-time RPATH.
-install(TARGETS linux-wallpaperengine
+install(TARGETS linux-wallpaperengine linux-wallpaperengine-web-helper
     RUNTIME DESTINATION .
 )
 install(TARGETS linux-wallpaperengine-lib
@@ -813,5 +834,6 @@ install(TARGETS linux-wallpaperengine-lib
 # but exclude the files already handled by install(TARGETS) above.
 install(DIRECTORY ${TARGET_OUTPUT_DIRECTORY}/ DESTINATION .
     PATTERN "linux-wallpaperengine" EXCLUDE
+    PATTERN "linux-wallpaperengine-web-helper" EXCLUDE
     PATTERN "liblinux-wallpaperengine-lib.so" EXCLUDE
 )

+ 4 - 2
README.md

@@ -39,7 +39,7 @@ Control:
 - Multi-monitor handling: per-screen backgrounds (`--screen-root`), one wallpaper spanning several monitors (`--screen-span`), per-screen scaling/zoom/alignment/corner color, and Workshop playlists (`--playlist`).
 - Live hotswap of the running wallpaper and its settings via `SIGUSR1`, separately per engine with `--control-file`, no process restart.
 - A global playback speed multiplier (`--speed`), separate from the FPS cap.
-- Video wallpapers can loop just part of the video (`--video-start`/`--video-end`), e.g. only minute 3 to 4 of a 5 minute clip.
+- Video wallpapers can loop just part of the video (`--video-start`/`--video-end`), e.g. only minute 3 to 4 of a 5 minute clip, or several parts one after the other while skipping the rest (`--video-segments "2:00-3:00,4:00-5:00"`).
 - More granular audio: restrict sound to a single screen (`--audio-screen`), a separate ambient volume for non-video backgrounds (`--ambient-volume`), per-object sound volume (`--sound-volume`), and a tunable multiplier on audio-reactive properties (`--audio-sensitivity`, with `--list-audio-objects` to see what's wired up).
 - Layer and effect introspection/toggling (`--list-objects`, `--disable-object`, `--list-effects`, `--disable-effect`, ...) for things the wallpaper author didn't expose as a property.
 
@@ -177,8 +177,9 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--layer <layer>` | Wayland only: `wlr-layer-shell` layer (`background`, `bottom`, `top`, `overlay`). Default `bottom`, on KDE `background` can end up under plasmashell's desktop window |
 | `--speed <factor>` | Global playback speed multiplier |
 | `--video-start <time>`, `--video-end <time>` | Video wallpapers only: loop just this part of the video, in seconds, `m:ss` or `h:mm:ss` (either one alone leaves that side at the video's start/end) |
+| `--video-segments <start-end,...>` | Video wallpapers only: play these parts one after the other and skip everything between them, e.g. `"2:00-3:00,4:00-5:00"`; an empty side is the video's start/end (`"4:00-"`) |
 | `--control-file <path>` | File the `SIGUSR1` hotswap request is read from, one per engine when several run. Default `$XDG_RUNTIME_DIR/lwe-control` |
-| `--post-processing <mode>` | `enabled` (default), `ultra` (HDR rendering and HDR bloom for scenes with bloom + hdr) or `displayhdr` (highlights up to the HDR output's peak, with `--hdr`) |
+| `--post-processing <mode>` | `disabled` (no bloom), `enabled` (default), `ultra` (HDR rendering and HDR bloom for scenes with bloom + hdr) or `displayhdr` (highlights up to the HDR output's peak, with `--hdr`) |
 | `--shadows <quality>`, `--volumetrics <quality>` | `disabled`, `low`, `medium` (default), `high`, `ultra` |
 | `--msaa <none/x2/x4/x8>` | Wallpaper Engine's anti-aliasing, only for scenes with 3D models like in Wallpaper Engine |
 | `--ssaa <none/x2/x3/x4>` | Supersampling: render the scene that many times larger per axis and average it down |
@@ -207,6 +208,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--audio-sensitivity <id/name>=<mult>` | Scale an object's audio-reactive swing; `0` disables it, `1` is default; repeatable, `*` for unmatched objects |
 | `--list-audio-objects` | List objects whose script reacts to music |
 | `--dump-structure`, `--render-debug <mode>` | Debugging output, see `--help` |
+| `--no-shader-cache` | Translate and link every shader from scratch instead of using `~/.cache/linux-wallpaperengine/shaders` |
 
 ### Examples
 

+ 49 - 22
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -367,18 +367,6 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    }
 	});
 
-    // Internal, hidden: appended to CEF subprocess re-execs so they see the current (possibly
-    // hotswapped) background instead of the launch-time "background id" positional. Registered
-    // last so it takes precedence.
-    backgroundGroup.add_argument ("--current-background")
-	.default_value ("")
-	.hidden ()
-	.action ([this] (const std::string& value) -> void {
-	    if (!value.empty ()) {
-		this->settings.general.defaultBackground = translateBackground (value);
-	    }
-	});
-
     // Internal, hidden: marks a self-re-exec as a disposable CEF host for one Web wallpaper.
     backgroundGroup.add_argument ("--web-host").flag ().hidden ().store_into (this->settings.general.webHost);
 
@@ -1031,13 +1019,23 @@ void ApplicationContext::loadSettingsFromArgv () {
 	return *seconds;
     };
 
+    const auto singleSegment = [this] () -> WallpaperEngine::VideoPlayback::VideoSegment& {
+	auto& segments = this->settings.render.videoSegments;
+
+	if (segments.size () != 1) {
+	    segments.assign (1, {});
+	}
+
+	return segments.front ();
+    };
+
     configurationGroup.add_argument ("--video-start")
 	.help (
 	    "Video wallpapers only: where the part of the video that loops starts, in seconds, m:ss or h:mm:ss (e.g. "
 	    "\"3:00\"). Without --video-end it loops from here to the end of the video"
 	)
-	.action ([this, parseVideoTime] (const std::string& value) -> void {
-	    this->settings.render.videoStart = parseVideoTime ("--video-start", value);
+	.action ([parseVideoTime, singleSegment] (const std::string& value) -> void {
+	    singleSegment ().start = parseVideoTime ("--video-start", value);
 	});
 
     configurationGroup.add_argument ("--video-end")
@@ -1045,8 +1043,24 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    "Video wallpapers only: where the part of the video that loops ends, in seconds, m:ss or h:mm:ss (e.g. "
 	    "\"4:00\"). Without --video-start it loops from the beginning up to here"
 	)
-	.action ([this, parseVideoTime] (const std::string& value) -> void {
-	    this->settings.render.videoEnd = parseVideoTime ("--video-end", value);
+	.action ([parseVideoTime, singleSegment] (const std::string& value) -> void {
+	    singleSegment ().end = parseVideoTime ("--video-end", value);
+	});
+
+    configurationGroup.add_argument ("--video-segments")
+	.help (
+	    "Video wallpapers only: plays just these parts one after the other and skips the rest, as a comma "
+	    "separated list of start-end times in seconds, m:ss or h:mm:ss (e.g. \"2:00-3:00,4:00-5:00\"). An empty "
+	    "side means the start or end of the video (\"4:00-\")"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    const auto segments = WallpaperEngine::Render::Wallpapers::CVideo::parseSegments (value);
+
+	    if (!segments.has_value ()) {
+		sLog.exception ("Invalid --video-segments value (start-end,start-end,...): ", value);
+	    }
+
+	    this->settings.render.videoSegments = *segments;
 	});
 
     configurationGroup.add_argument ("--control-file")
@@ -1077,12 +1091,14 @@ void ApplicationContext::loadSettingsFromArgv () {
 
     configurationGroup.add_argument ("--post-processing")
 	.help (
-	    "Wallpaper Engine's post processing quality: \"enabled\" (default), \"ultra\" or \"displayhdr\". With "
-	    "ultra, scenes that turn on both bloom and hdr render in HDR with Wallpaper Engine's HDR bloom; displayhdr "
+	    "Wallpaper Engine's post processing quality: \"disabled\" (no bloom), \"enabled\" (default), \"ultra\" or "
+	    "\"displayhdr\". With ultra, scenes that turn on both bloom and hdr render in HDR with Wallpaper Engine's "
+	    "HDR bloom; displayhdr "
 	    "also lets their highlights go up to an HDR output's peak brightness (with --hdr)"
 	)
-	.choices ("enabled", "ultra", "displayhdr")
+	.choices ("disabled", "enabled", "ultra", "displayhdr")
 	.action ([this] (const std::string& value) -> void {
+	    this->settings.general.postProcessingDisabled = value == "disabled";
 	    this->settings.general.ultraPostProcessing = value == "ultra" || value == "displayhdr";
 	    this->settings.general.displayHDR = value == "displayhdr";
 	});
@@ -1129,7 +1145,10 @@ void ApplicationContext::loadSettingsFromArgv () {
 	});
 
     configurationGroup.add_argument ("--disable-animations")
-	.help ("Freezes all scene animation (scripts, particles, effects and puppet meshes) at its current frame")
+	.help (
+	    "Freezes all scene animation (scripts, particles, effects and puppet meshes) at its current frame. "
+	    "Control file: disable-animations=on/off"
+	)
 	.flag ()
 	.action ([this] (const std::string& value) -> void { this->settings.render.freezeAnimations = true; });
 
@@ -1201,7 +1220,7 @@ void ApplicationContext::loadSettingsFromArgv () {
     configurationGroup.add_argument ("--disable-effect")
 	.help (
 	    "Disables an object's visual effect (bloom, blur, glow, etc), matched by effect id or editor name. "
-	    "Can be repeated"
+	    "Can be repeated. Control file: effects=1 plus disable-effect=<id> lines"
 	)
 	.action ([this] (const std::string& value) -> void {
 	    this->settings.general.disabledEffects.push_back (value);
@@ -1211,7 +1230,7 @@ void ApplicationContext::loadSettingsFromArgv () {
     configurationGroup.add_argument ("--enable-effect")
 	.help (
 	    "Forces an effect to show even if the scene hides it by default, matched by effect id or editor name. "
-	    "Can be repeated"
+	    "Can be repeated. Control file: effects=1 plus enable-effect=<id> lines"
 	)
 	.action ([this] (const std::string& value) -> void { this->settings.general.enabledEffects.push_back (value); })
 	.append ();
@@ -1281,6 +1300,14 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.flag ()
 	.store_into (this->settings.general.dumpStructure);
 
+    debuggingGroup.add_argument ("--no-shader-cache")
+	.help (
+	    "Translates and links every shader from scratch instead of reusing the ones cached in "
+	    "~/.cache/linux-wallpaperengine/shaders (nothing is written there either)"
+	)
+	.flag ()
+	.store_into (this->settings.general.noShaderCache);
+
     debuggingGroup.add_argument ("--render-debug")
 	.help (
 	    "Scene render debug mode: base-only, no-solid-final, pass-log, brightness-log, no-puppet-animation, "

+ 6 - 5
src/WallpaperEngine/Application/ApplicationContext.h

@@ -15,6 +15,7 @@
 
 #include "../Render/TextureProvider.h"
 #include "WallpaperEngine/Render/WallpaperState.h"
+#include "WallpaperEngine/VideoPlayback/VideoSegment.h"
 
 #include "WallpaperEngine/Data/Model/Project.h"
 
@@ -114,9 +115,11 @@ public:
 	    bool onlyListAudioObjects;
 	    bool onlyListEffects;
 	    bool dumpStructure;
+	    bool noShaderCache;
 	    bool disableParticles;
 	    /** Grows a scene's render canvas to fit every image layer that extends past it, see --expand-canvas */
 	    bool expandCanvas;
+	    bool postProcessingDisabled = false;
 	    /** WE's "ultra" post processing quality: scenes with bloom and hdr render in HDR, see --post-processing */
 	    bool ultraPostProcessing = false;
 	    /** WE's "displayhdr" post processing: ultra plus highlights brightened towards an HDR output's peak */
@@ -180,9 +183,7 @@ public:
 	    int maximumFPS;
 	    /** Global playback speed multiplier for animations, particles and effects, see --speed */
 	    float playbackSpeed;
-	    /** Video wallpapers loop only this part (seconds, either side open), see --video-start/--video-end */
-	    std::optional<double> videoStart;
-	    std::optional<double> videoEnd;
+	    WallpaperEngine::VideoPlayback::VideoSegments videoSegments;
 	    /** Freezes scene time entirely (scripts, particles, effects and puppet meshes all stop advancing), see
 	     * --disable-animations */
 	    bool freezeAnimations;
@@ -265,6 +266,7 @@ public:
             .onlyListAudioObjects = false,
             .onlyListEffects = false,
             .dumpStructure = false,
+            .noShaderCache = false,
             .disabledObjects = {},
             .enabledObjects = {},
             .disabledEffects = {},
@@ -295,8 +297,7 @@ public:
             .mode = NORMAL_WINDOW,
             .maximumFPS = 60,
             .playbackSpeed = 1.0f,
-            .videoStart = std::nullopt,
-            .videoEnd = std::nullopt,
+            .videoSegments = {},
             .freezeAnimations = false,
             .pauseOnFullscreen = true,
             .pauseOnFullscreenOnlyWhenActive = false,

+ 7 - 3
src/WallpaperEngine/Application/ApplicationState.h

@@ -3,6 +3,12 @@
 #include "ApplicationContext.h"
 
 namespace WallpaperEngine::Application {
+enum class XrayMode {
+    Normal,
+    Full,
+    Disabled,
+};
+
 class ApplicationState {
 public:
     struct {
@@ -19,9 +25,7 @@ public:
     } mouse {};
 
     struct {
-	/** If true, xray-style effects (Wallpaper Engine's built-in "effects/xray") render fully revealed
-	 * everywhere instead of following the mouse pointer */
-	bool fullReveal;
+	XrayMode mode;
     } xray {};
 };
 } // namespace WallpaperEngine::Application

+ 265 - 147
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -10,7 +10,11 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
 #include "WallpaperEngine/Render/RenderContext.h"
+#include "WallpaperEngine/Render/Shaders/ShaderCache.h"
+#include "WallpaperEngine/Render/Wallpapers/CScene.h"
+#include "WallpaperEngine/Render/Wallpapers/CSplat.h"
 #include "WallpaperEngine/Render/Wallpapers/CVideo.h"
+#include "WallpaperEngine/Render/Wallpapers/CWeb.h"
 
 #include "WallpaperEngine/Data/Dumpers/StringPrinter.h"
 #include "WallpaperEngine/Data/Parsers/ProjectParser.h"
@@ -86,33 +90,11 @@ void CustomGLDebugCallback (
     }
 }
 
-bool WallpaperApplication::isCefSubprocess () const {
-    for (int i = 1; i < this->m_context.getArgc (); i++) {
-	if (std::string_view (this->m_context.getArgv ()[i]).starts_with ("--type=")) {
-	    return true;
-	}
-    }
-
-    return false;
-}
-
 WallpaperApplication::WallpaperApplication (ApplicationContext& context) : m_context (context) {
+    Render::Shaders::ShaderCache::get ().setEnabled (!this->m_context.settings.general.noShaderCache);
     this->initializeSubsystems ();
 
-    try {
-	this->loadBackgrounds ();
-    } catch (const std::exception& e) {
-	if (!this->isCefSubprocess ()) {
-	    throw;
-	}
-
-	// CEF re-execs this binary for its own subprocesses with a reconstructed argv that doesn't
-	// always resolve to a loadable background. Must still reach setupBrowser() below regardless
-	// - that's what calls CefExecuteProcess() to hand off into Chromium's subprocess entrypoint;
-	// skipping it here leaves CEF's IPC handshake incomplete, which reads as a crashed subprocess
-	// and gets retried, turning one web wallpaper into several stray processes.
-	sLog.error ("Skipping background load for CEF subprocess re-exec: ", e.what ());
-    }
+    this->loadBackgrounds ();
 
     this->setupProperties ();
     this->setupAudioSensitivity ();
@@ -162,54 +144,6 @@ WallpaperApplication::setupAssetLocator (const std::string& bg, const std::files
 
     auto& vfs = container->getVFS ();
 
-    // Had to get a little creative with the effects to achieve the same bloom effect without any custom code:
-    // these virtual files are loaded by an image in the scene that takes the current _rt_FullFrameBuffer and
-    // applies the bloom effect to render it out to the screen.
-    vfs.add (
-	"effects/wpenginelinux/bloomeffect.json",
-	{ { "name", "camerabloom_wpengine_linux" },
-	  { "group", "wpengine_linux_camera" },
-	  { "dependencies", JSON::array () },
-	  {
-	      "passes",
-	      JSON::array (
-		  { { { "material", "materials/util/downsample_quarter_bloom.json" },
-		      { "target", "_rt_4FrameBuffer" },
-		      { "bind", JSON::array ({ { { "name", "_rt_FullFrameBuffer" }, { "index", 0 } } }) } },
-		    { { "material", "materials/util/downsample_eighth_blur_v.json" },
-		      { "target", "_rt_8FrameBuffer" },
-		      { "bind", JSON::array ({ { { "name", "_rt_4FrameBuffer" }, { "index", 0 } } }) } },
-		    { { "material", "materials/util/blur_h_bloom.json" },
-		      { "target", "_rt_Bloom" },
-		      { "bind", JSON::array ({ { { "name", "_rt_8FrameBuffer" }, { "index", 0 } } }) } },
-		    { { "material", "materials/util/combine.json" },
-		      { "target", "_rt_FullFrameBuffer" },
-		      { "bind",
-			JSON::array (
-			    { { { "name", "_rt_imageLayerComposite_-1_a" }, { "index", 0 } },
-			      { { "name", "_rt_Bloom" }, { "index", 1 } } }
-			) } } }
-	      ),
-	  } }
-    );
-
-    // Wastes a render pass on an image element that exists only to host the bloom material above
-    // fullscreen, so it covers the whole scene buffer whatever part of the scene the output shows
-    vfs.add ("models/wpenginelinux.json", { { "material", "materials/wpenginelinux.json" }, { "fullscreen", true } });
-
-    vfs.add (
-	"materials/wpenginelinux.json",
-	{ { "passes",
-	    JSON::array (
-		{ { { "blending", "normal" },
-		    { "cullmode", "nocull" },
-		    { "depthtest", "disabled" },
-		    { "depthwrite", "disabled" },
-		    { "shader", "genericimage2" },
-		    { "textures", JSON::array ({ "_rt_FullFrameBuffer" }) } } }
-	    ) } }
-    );
-
     vfs.add (
 	"shaders/commands/copy.frag",
 	"uniform sampler2D g_Texture0;\n"
@@ -657,7 +591,7 @@ void WallpaperApplication::advancePlaylist (
 		wallpaper->setImageAdjustments (
 		    this->resolveScreenImageAdjustments (screen, *this->m_backgrounds[screen])
 		);
-		this->m_renderContext->setWallpaper (screen, std::move (wallpaper));
+		this->m_renderContext->setWallpaper (screen, std::move (wallpaper), true);
 		this->applyAudioPolicy ();
 	    }
 	} catch (...) {
@@ -722,13 +656,17 @@ struct HotswapRequest {
     bool layersProvided = false;
     std::vector<std::string> disabledObjects;
     std::vector<std::string> enabledObjects;
+    /** effects=1 seen, the effect lists replace the current ones */
+    bool effectsProvided = false;
+    std::vector<std::string> disabledEffects;
+    std::vector<std::string> enabledEffects;
+    std::optional<std::string> disableAnimations;
     /** True once at least one "property=name=value" line was seen */
     bool propertiesProvided = false;
     std::map<std::string, std::string> properties;
     std::optional<int> volume;
     /** frame rate limit, see --fps */
     std::optional<int> fps;
-    /** "on"/"off"/"toggle" (also "1"/"0"/"true"/"false" for on/off) */
     std::optional<std::string> xray;
     /** "stretch"/"fit"/"fill"/"center"/"default" */
     std::optional<std::string> scaling;
@@ -751,6 +689,8 @@ struct HotswapRequest {
     /** seconds, m:ss or h:mm:ss, "" or "none" clears it, see --video-start/--video-end */
     std::optional<std::string> videoStart;
     std::optional<std::string> videoEnd;
+    /** "" or "none" clears it */
+    std::optional<std::string> videoSegments;
     /** position to jump video wallpapers to, same format */
     std::optional<std::string> videoSeek;
     /** screen name to restrict audio to, or "" to clear the restriction, see --audio-screen */
@@ -780,15 +720,7 @@ std::string trimHotswapToken (const std::string& value) {
     return value.substr (begin, end - begin);
 }
 
-/**
- * Parses the control file. Supports the original bare-path-on-one-line format for backwards
- * compatibility, plus key=value lines (path/layers/disable-object/enable-object/volume/xray/scaling/zoom/
- * offset/disable-parallax/corner-color/image-filter/image-filter-strength/brightness/contrast/saturation/hue/
- * color-options/flip/speed/video-start/video-end/video-seek/audio-screen/ambient-volume/property) so a single
- * request can
- * carry more than just the background path. "property=name=value" (repeatable) carries
- * --set-property-equivalent overrides.
- */
+/** Control file: the old bare path line, or key=value lines (see below). property=name=value can repeat */
 HotswapRequest parseHotswapRequest (std::istream& file) {
     HotswapRequest request;
     std::string rawLine;
@@ -824,6 +756,16 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	} else if (key == "enable-object") {
 	    request.layersProvided = true;
 	    request.enabledObjects.push_back (value);
+	} else if (key == "effects") {
+	    request.effectsProvided = true;
+	} else if (key == "disable-effect") {
+	    request.effectsProvided = true;
+	    request.disabledEffects.push_back (value);
+	} else if (key == "enable-effect") {
+	    request.effectsProvided = true;
+	    request.enabledEffects.push_back (value);
+	} else if (key == "disable-animations") {
+	    request.disableAnimations = value;
 	} else if (key == "volume") {
 	    try {
 		request.volume = std::stoi (value);
@@ -899,6 +841,8 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.videoStart = value;
 	} else if (key == "video-end") {
 	    request.videoEnd = value;
+	} else if (key == "video-segments") {
+	    request.videoSegments = value;
 	} else if (key == "video-seek") {
 	    request.videoSeek = value;
 	} else if (key == "audio-screen") {
@@ -965,8 +909,9 @@ void WallpaperApplication::checkHotswapRequest () {
 	&& !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
 	&& !request.expandCanvas.has_value () && !request.cornerColor.has_value () && !request.imageAdjustmentsProvided
 	&& !request.speed.has_value () && !request.videoStart.has_value () && !request.videoEnd.has_value ()
-	&& !request.videoSeek.has_value () && !request.audioScreen.has_value () && !request.ambientVolume.has_value ()
-	&& !request.propertiesProvided && !request.audioSensitivityProvided && !request.soundVolumeProvided) {
+	&& !request.videoSegments.has_value () && !request.videoSeek.has_value () && !request.audioScreen.has_value ()
+	&& !request.ambientVolume.has_value () && !request.propertiesProvided && !request.audioSensitivityProvided
+	&& !request.soundVolumeProvided && !request.effectsProvided && !request.disableAnimations.has_value ()) {
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
     }
@@ -987,8 +932,7 @@ void WallpaperApplication::checkHotswapRequest () {
 
 	// Wallpaper Engine keeps these per wallpaper too
 	this->m_context.settings.render.window.imageAdjustments = {};
-	this->m_context.settings.render.videoStart.reset ();
-	this->m_context.settings.render.videoEnd.reset ();
+	this->m_context.settings.render.videoSegments.clear ();
 	general.screenImageAdjustments.clear ();
 
 	for (auto& spanGroup : general.spanGroups) {
@@ -1040,8 +984,8 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->applySpeedHotswap (*request.speed);
     }
 
-    if (request.videoStart.has_value () || request.videoEnd.has_value ()) {
-	this->applyVideoRangeHotswap (request.videoStart, request.videoEnd);
+    if (request.videoStart.has_value () || request.videoEnd.has_value () || request.videoSegments.has_value ()) {
+	this->applyVideoSegmentsHotswap (request.videoStart, request.videoEnd, request.videoSegments);
     }
 
     if (request.videoSeek.has_value ()) {
@@ -1079,9 +1023,35 @@ void WallpaperApplication::checkHotswapRequest () {
 	this->m_context.settings.general.enabledObjects = request.enabledObjects;
     }
 
+    // effect passes are built at scene load
+    if (request.effectsProvided) {
+	this->m_context.settings.general.disabledEffects = request.disabledEffects;
+	this->m_context.settings.general.enabledEffects = request.enabledEffects;
+    }
+
+    if (request.disableAnimations.has_value ()) {
+	const auto& value = *request.disableAnimations;
+	const bool freeze = value == "on" || value == "1" || value == "true";
+
+	if (!freeze && value != "off" && value != "0" && value != "false") {
+	    sLog.error ("Hotswap: ignoring invalid disable-animations value: ", value);
+	} else {
+	    this->m_context.settings.render.freezeAnimations = freeze;
+	}
+    }
+
+    std::vector<std::string> changedProperties;
+
     if (request.propertiesProvided) {
+	auto& properties = this->m_context.settings.general.properties;
+
 	for (const auto& [name, value] : request.properties) {
-	    this->m_context.settings.general.properties[name] = value;
+	    if (const auto previous = properties.find (name);
+		previous == properties.end () || previous->second != value) {
+		changedProperties.push_back (name);
+	    }
+
+	    properties[name] = value;
 	}
     }
 
@@ -1095,10 +1065,15 @@ void WallpaperApplication::checkHotswapRequest () {
 	}
     }
 
+    if (request.propertiesProvided && !request.path.has_value () && !request.layersProvided && !request.effectsProvided
+	&& !request.audioSensitivityProvided && !expandCanvasChanged && this->applyPropertiesLive (changedProperties)) {
+	return;
+    }
+
     // volume/xray/speed-only requests are pure live setters with nothing to reload. Properties
     // and audio sensitivity, like layers, are baked into the scene graph at parse time, so they
     // need the same reload, as does the expanded canvas (it sizes the scene's framebuffers).
-    if (!request.path.has_value () && !request.layersProvided && !request.propertiesProvided
+    if (!request.path.has_value () && !request.layersProvided && !request.effectsProvided && !request.propertiesProvided
 	&& !request.audioSensitivityProvided && !expandCanvasChanged) {
 	return;
     }
@@ -1155,7 +1130,7 @@ void WallpaperApplication::checkHotswapRequest () {
 		    wallpaper->setAlignment (this->resolveScreenAlignment (screen));
 		    wallpaper->setCornerColor (this->resolveScreenCornerColor (screen));
 		    wallpaper->setImageAdjustments (this->resolveScreenImageAdjustments (screen, *background));
-		    this->m_renderContext->setWallpaper (screen, std::move (wallpaper));
+		    this->m_renderContext->setWallpaper (screen, std::move (wallpaper), true);
 		}
 	    } catch (...) {
 		project = std::move (background);
@@ -1306,22 +1281,24 @@ void WallpaperApplication::applyFpsHotswap (int fps) {
 }
 
 void WallpaperApplication::applyXrayHotswap (const std::string& value) {
-    bool newState;
+    auto& mode = this->m_context.state.xray.mode;
 
+    // on/off/toggle predate "disabled" and only switch between full and normal
     if (value == "toggle") {
-	newState = !this->m_context.state.xray.fullReveal;
-    } else if (value == "on" || value == "1" || value == "true") {
-	newState = true;
-    } else if (value == "off" || value == "0" || value == "false") {
-	newState = false;
+	mode = mode == XrayMode::Full ? XrayMode::Normal : XrayMode::Full;
+    } else if (value == "full" || value == "on" || value == "1" || value == "true") {
+	mode = XrayMode::Full;
+    } else if (value == "normal" || value == "off" || value == "0" || value == "false") {
+	mode = XrayMode::Normal;
+    } else if (value == "disabled") {
+	mode = XrayMode::Disabled;
     } else {
 	sLog.error ("Hotswap: ignoring invalid xray value: ", value);
 	return;
     }
 
-    this->m_context.state.xray.fullReveal = newState;
-
-    sLog.out ("Hotswap: full xray ", newState ? "enabled" : "disabled", " live");
+    const char* name = mode == XrayMode::Full ? "full" : mode == XrayMode::Disabled ? "disabled" : "normal";
+    sLog.out ("Hotswap: xray ", name, " live");
 }
 
 void WallpaperApplication::applyScalingHotswap (const std::string& value) {
@@ -1563,48 +1540,72 @@ void WallpaperApplication::applySpeedHotswap (const std::string& value) {
     sLog.out ("Hotswap: applied speed ", speed, " live");
 }
 
-void WallpaperApplication::applyVideoRangeHotswap (
-    const std::optional<std::string>& start, const std::optional<std::string>& end
+void WallpaperApplication::applyVideoSegmentsHotswap (
+    const std::optional<std::string>& start, const std::optional<std::string>& end,
+    const std::optional<std::string>& segments
 ) {
-    auto& render = this->m_context.settings.render;
-
-    const auto update = [] (const char* key, const std::optional<std::string>& value, std::optional<double>& target) {
-	if (!value.has_value ()) {
-	    return;
+    using WallpaperEngine::Render::Wallpapers::CVideo;
+    auto& current = this->m_context.settings.render.videoSegments;
+    const auto clears = [] (const std::string& value) { return value.empty () || value == "none"; };
+
+    if (segments.has_value ()) {
+	if (clears (*segments)) {
+	    current.clear ();
+	} else if (const auto parsed = CVideo::parseSegments (*segments)) {
+	    current = *parsed;
+	} else {
+	    sLog.error ("Hotswap: ignoring invalid video-segments value: ", *segments);
 	}
+    }
 
-	if (value->empty () || *value == "none") {
-	    target.reset ();
-	    return;
+    if (start.has_value () || end.has_value ()) {
+	WallpaperEngine::VideoPlayback::VideoSegment segment;
+
+	if (!current.empty ()) {
+	    segment = { current.front ().start, current.back ().end };
 	}
 
-	const auto seconds = WallpaperEngine::Render::Wallpapers::CVideo::parseTime (*value);
+	if (start.has_value ()) {
+	    if (clears (*start)) {
+		segment.start = 0.0;
+	    } else if (const auto seconds = CVideo::parseTime (*start)) {
+		segment.start = *seconds;
+	    } else {
+		sLog.error ("Hotswap: ignoring invalid video-start value: ", *start);
+	    }
+	}
 
-	if (!seconds.has_value ()) {
-	    sLog.error ("Hotswap: ignoring invalid ", key, " value: ", *value);
-	    return;
+	if (end.has_value ()) {
+	    if (clears (*end)) {
+		segment.end.reset ();
+	    } else if (const auto seconds = CVideo::parseTime (*end)) {
+		segment.end = seconds;
+	    } else {
+		sLog.error ("Hotswap: ignoring invalid video-end value: ", *end);
+	    }
 	}
 
-	target = seconds;
-    };
+	current = { segment };
+    }
 
-    update ("video-start", start, render.videoStart);
-    update ("video-end", end, render.videoEnd);
+    current = CVideo::normalizeSegments (current);
 
     if (this->m_renderContext) {
 	for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
-	    if (wallpaper->is<WallpaperEngine::Render::Wallpapers::CVideo> ()) {
-		wallpaper->as<WallpaperEngine::Render::Wallpapers::CVideo> ()->setLoopRange (
-		    render.videoStart, render.videoEnd
-		);
+	    if (wallpaper->is<CVideo> ()) {
+		wallpaper->as<CVideo> ()->setSegments (current);
 	    }
 	}
     }
 
-    sLog.out (
-	"Hotswap: applied video range ", render.videoStart.has_value () ? std::to_string (*render.videoStart) : "start",
-	" - ", render.videoEnd.has_value () ? std::to_string (*render.videoEnd) : "end", " live"
-    );
+    std::string description = current.empty () ? "whole video" : "";
+
+    for (const auto& segment : current) {
+	description += (description.empty () ? "" : ", ") + std::to_string (segment.start) + " - "
+	    + (segment.end.has_value () ? std::to_string (*segment.end) : "end");
+    }
+
+    sLog.out ("Hotswap: applied video parts ", description, " live");
 }
 
 void WallpaperApplication::applyVideoSeekHotswap (const std::string& value) {
@@ -1964,14 +1965,75 @@ void WallpaperApplication::applySoundVolumeHotswap (const std::map<std::string,
     sLog.out ("Hotswap: applied sound volume live");
 }
 
+bool WallpaperApplication::applyPropertiesLive (const std::vector<std::string>& names) {
+    using WallpaperEngine::Render::Wallpapers::CScene;
+    using WallpaperEngine::Render::Wallpapers::CWeb;
+
+    const auto wallpaperOf = [this] (const std::string& screen) -> WallpaperEngine::Render::CWallpaper* {
+	if (!this->m_renderContext) {
+	    return nullptr;
+	}
+
+	const auto& wallpapers = this->m_renderContext->getWallpapers ();
+	const auto it = wallpapers.find (screen);
+	return it != wallpapers.end () ? it->second.get () : nullptr;
+    };
+
+    for (const auto& name : names) {
+	for (const auto& [screen, info] : this->m_backgrounds) {
+	    const auto property = info->properties.find (name);
+
+	    if (property == info->properties.end ()) {
+		continue;
+	    }
+
+	    static const bool force = std::getenv ("LWE_FORCE_LIVE_PROPERTIES") != nullptr;
+	    const auto* wallpaper = wallpaperOf (screen);
+
+	    // scenes follow via bindings and scripts, web pages via applyUserProperties, splats read theirs per frame
+	    const bool scene = info->wallpaper->is<Scene> () && wallpaper != nullptr && wallpaper->is<CScene> ();
+	    const bool web = info->wallpaper->is<Web> () && wallpaper != nullptr
+		&& (wallpaper->is<CWeb> () || wallpaper->is<WallpaperEngine::Render::Wallpapers::CSplat> ());
+
+	    if (!(scene || web) || (!force && !property->second->appliesLive ())) {
+		return false;
+	    }
+	}
+    }
+
+    for (const auto& name : names) {
+	const auto& value = this->m_context.settings.general.properties.at (name);
+
+	for (const auto& [background, info] : this->m_backgrounds) {
+	    if (const auto property = info->properties.find (name); property != info->properties.end ()) {
+		try {
+		    property->second->update (value, DynamicValue::UpdateSource::User);
+		} catch (const std::exception& e) {
+		    sLog.error ("Hotswap: ignoring invalid value for property ", name, ": ", e.what ());
+		}
+	    }
+	}
+
+	sLog.out ("Hotswap: applied property ", name, " live");
+    }
+
+    if (this->m_renderContext && !names.empty ()) {
+	for (const auto& wallpaper : this->m_renderContext->getWallpapers () | std::views::values) {
+	    if (wallpaper->is<CScene> ()) {
+		wallpaper->as<CScene> ()->getScriptEngine ().notifyUserPropertiesChanged (names);
+	    } else if (wallpaper->is<CWeb> ()) {
+		wallpaper->as<CWeb> ()->setPropertyOverrides (this->m_context.settings.general.properties);
+	    }
+	}
+    }
+
+    return true;
+}
+
 void WallpaperApplication::setupBrowser () {
-    // The main engine process never hosts CEF directly - CEF only supports one
-    // CefInitialize()/CefShutdown() pair per process, so a process that might later need to stop
-    // and restart hosting a web wallpaper can't safely do it in place. Only two roles reach here:
-    // CEF's own subprocess re-execs (--type=zygote/gpu-process/renderer/utility), which must
-    // always reach WebBrowserContext even if loadBackgrounds() found nothing to load, and this
-    // process's own --web-host role.
-    if ((!this->isCefSubprocess () && !this->m_context.settings.general.webHost) || this->m_browserContext) {
+    // CEF allows one CefInitialize/CefShutdown per process, so only the --web-host process hosts it. Chromium's own
+    // children go to WebBrowserContext::runSubprocess from main ()
+    if (!this->m_context.settings.general.webHost || this->m_browserContext) {
 	return;
     }
 
@@ -2053,6 +2115,7 @@ void WallpaperApplication::runWebHost () {
     uint32_t lastDesiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
     uint32_t lastDesiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
     bool lastAudioMuted = shm->audioMuted.load (std::memory_order_relaxed);
+    bool resizeRequested = false;
     browser->GetHost ()->SetAudioMuted (lastAudioMuted);
     CEF::PageBridge bridge (browser, *shm, project.properties, *client);
 
@@ -2073,7 +2136,17 @@ void WallpaperApplication::runWebHost () {
 	const uint32_t desiredWidth = shm->desiredWidth.load (std::memory_order_relaxed);
 	const uint32_t desiredHeight = shm->desiredHeight.load (std::memory_order_relaxed);
 
-	if (desiredWidth != lastDesiredWidth || desiredHeight != lastDesiredHeight) {
+	// also compare with what CEF was last told, else a resize during CreateBrowserSync is lost (16x17 page)
+	const bool viewDiffers = std::clamp (desiredWidth, 1u, shm->maxWidth) != renderHandler->viewWidth ()
+	    || std::clamp (desiredHeight, 1u, shm->maxHeight) != renderHandler->viewHeight ();
+
+	if (!viewDiffers) {
+	    resizeRequested = false;
+	}
+
+	if (desiredWidth != lastDesiredWidth || desiredHeight != lastDesiredHeight
+	    || (viewDiffers && !resizeRequested)) {
+	    resizeRequested = viewDiffers;
 	    lastDesiredWidth = desiredWidth;
 	    lastDesiredHeight = desiredHeight;
 	    browser->GetHost ()->WasResized ();
@@ -2218,26 +2291,27 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	    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 from the output pixel's center, its left edge truncated 250/1920*1920 to 249
+	    const auto firstSample = [] (const int pixel, const int size, const float start, const float end,
+					 const int readSize, const int samples) {
+		const double center = start + (pixel + 0.5) / size * (end - start);
+		return static_cast<int> (std::floor (center * readSize - samples * 0.5 + 0.5));
+	    };
 
 	    // 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++) {
-		    const float u
-			= capture.ustart + (static_cast<float> (x) / capture.vpWidth) * (capture.uend - capture.ustart);
-		    const float v = capture.vstart
-			+ (static_cast<float> (y) / capture.vpHeight) * (capture.vend - capture.vstart);
-
-		    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);
+		    const int srcX
+			= firstSample (x, capture.vpWidth, capture.ustart, capture.uend, capture.readWidth, samplesX);
+		    const int srcY
+			= firstSample (y, capture.vpHeight, capture.vstart, capture.vend, capture.readHeight, samplesY);
 		    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);
+			const int row = std::clamp (srcY + sy, 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 column = std::clamp (srcX + sx, 0, capture.readWidth - 1);
 			    const int srcIdx = (row * capture.readWidth + column) * 3;
 
 			    sum[0] += capture.buffer[srcIdx];
@@ -2547,8 +2621,50 @@ void WallpaperApplication::render () {
 	m_audioDriver->update (rawDelta * this->m_context.settings.render.playbackSpeed);
 	m_mediaSource->update ();
 	m_videoDriver->getInputContext ().update ();
+
+	// LWE_HOTSWAP_AT_FRAME=<n>: read the control file before frame n as if SIGUSR1 came in (regression tests)
+	static const int64_t hotswapFrame = [] {
+	    const char* value = std::getenv ("LWE_HOTSWAP_AT_FRAME");
+	    return value != nullptr ? std::strtoll (value, nullptr, 10) : -1;
+	}();
+
+	if (hotswapFrame >= 0 && m_videoDriver->getFrameCounter () == static_cast<uint64_t> (hotswapFrame)) {
+	    this->m_hotswapRequested = true;
+	    this->checkHotswapRequest ();
+	}
+
 	m_videoDriver->dispatchEventQueue ();
 
+	// spritesheetrefreshsync: sleep until the first image's next sprite frame (sub_140110630)
+	if (fixedTimestep <= 0.0f && !this->m_context.settings.render.freezeAnimations) {
+	    std::optional<float> syncDelay;
+
+	    for (const auto& [screen, wallpaper] : this->m_renderContext->getWallpapers ()) {
+		if (!wallpaper->is<WallpaperEngine::Render::Wallpapers::CScene> ()) {
+		    continue;
+		}
+
+		if (const auto delay
+		    = wallpaper->as<WallpaperEngine::Render::Wallpapers::CScene> ()->spriteSheetSyncDelay ();
+		    delay.has_value ()) {
+		    syncDelay = std::min (syncDelay.value_or (*delay), *delay);
+		}
+	    }
+
+	    if (syncDelay.has_value ()) {
+		float wait = *syncDelay;
+		const float speed = this->m_context.settings.render.playbackSpeed;
+
+		if (speed > 0.001f) {
+		    wait /= speed;
+		}
+
+		std::this_thread::sleep_for (
+		    std::chrono::milliseconds (static_cast<int> (std::min (wait, 0.25f) * 1000.0f))
+		);
+	    }
+	}
+
 	// read every frame, --fps can change with a hotswap
 	const float minimumTime = 1.0f / std::max (1, this->m_context.settings.render.maximumFPS);
 	const float frameTime = m_videoDriver->getRenderTime () - rawTimeNow;
@@ -2640,7 +2756,9 @@ void WallpaperApplication::signal (int signal) {
 	return;
     }
 
-    sLog.out ("Stop requested by signal ", signal);
+    // no logger here, it allocates and a signal mid-malloc would deadlock
+    static constexpr char message[] = "Stop requested by signal\n";
+    std::ignore = write (STDOUT_FILENO, message, sizeof (message) - 1);
     this->m_context.state.general.keepRunning = false;
 }
 

+ 8 - 12
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -125,9 +125,6 @@ private:
     std::vector<std::size_t> buildPlaylistOrder (const ApplicationContext::PlaylistDefinition& definition);
     bool makeAnyViewportCurrent () const;
 
-    /** True if this process was re-exec'd by CEF as a subprocess helper (--type=renderer/gpu-process/...) */
-    bool isCefSubprocess () const;
-
     /**
      * Pushes a volume change live to already-running video players and the SDL audio mixer,
      * without touching the loaded projects. volume is 0-128, matching --volume.
@@ -135,10 +132,7 @@ private:
     void applyVolumeHotswap (int volume);
     void applyFpsHotswap (int fps);
 
-    /**
-     * Pushes a full-xray toggle live to the renderer, without touching the loaded projects.
-     * value is "on"/"off"/"toggle" (also accepts "1"/"0"/"true"/"false" for on/off).
-     */
+    /** "full"/"normal"/"disabled", or the older "on"/"off"/"toggle" */
     void applyXrayHotswap (const std::string& value);
 
     /**
@@ -179,11 +173,11 @@ private:
      */
     void applySpeedHotswap (const std::string& value);
 
-    /**
-     * Pushes a new --video-start/--video-end live to video wallpapers (empty or "none" clears that side), they
-     * restart from the new start
-     */
-    void applyVideoRangeHotswap (const std::optional<std::string>& start, const std::optional<std::string>& end);
+    /** Video wallpapers restart from the first part, video-start/video-end make it one part */
+    void applyVideoSegmentsHotswap (
+	const std::optional<std::string>& start, const std::optional<std::string>& end,
+	const std::optional<std::string>& segments
+    );
 
     /** Jumps video wallpapers to a position (seconds, m:ss or h:mm:ss), e.g. a few seconds before the loop end */
     void applyVideoSeekHotswap (const std::string& value);
@@ -205,6 +199,8 @@ private:
      * is a pure live setter.
      */
     void applySoundVolumeHotswap (const std::map<std::string, std::string>& targets);
+    /** false when one of them needs a reload */
+    bool applyPropertiesLive (const std::vector<std::string>& names);
 
     /**
      * Recomputes and pushes CWallpaper::setAudioPolicy() to every currently rendered wallpaper

+ 2 - 2
src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.cpp

@@ -29,11 +29,11 @@ void PlaybackRecorder::removeSpectrumListener (int id) {
     this->m_listeners.erase (id);
 }
 
-void PlaybackRecorder::notifySpectrumListeners (const float* audio64) {
+void PlaybackRecorder::notifySpectrumListeners (const float* bands) {
     std::lock_guard guard (this->m_listenersMutex);
 
     for (const auto& listener : this->m_listeners | std::views::values) {
-	listener (audio64);
+	listener (bands);
     }
 }
 

+ 3 - 3
src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h

@@ -12,8 +12,8 @@ class PlaybackRecorder {
     Audio::SpectrumProcessor m_processor;
 
 public:
-    /** Called with the 64 band spectrum every time a fresh one has been computed, from the recorder's capture thread */
-    using SpectrumListener = std::function<void (const float* audio64)>;
+    /** [left 64 | right 64] bands per analyzed block (zeros once quiet), called on the capture thread */
+    using SpectrumListener = std::function<void (const float* bands)>;
 
     virtual ~PlaybackRecorder () = default;
 
@@ -43,7 +43,7 @@ public:
     const float* audio64 = m_processor.audio64;
 
 protected:
-    void notifySpectrumListeners (const float* audio64);
+    void notifySpectrumListeners (const float* bands);
 
     /** [left 64 | right 64] linear band levels from the capture thread, guarded by lock()/unlock() */
     float m_captured[128] = { 0 };

+ 5 - 45
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp

@@ -221,8 +221,7 @@ void pa_context_notify_cb (pa_context* ctx, void* userdata) {
 }
 
 PulseAudioPlaybackRecorder::PulseAudioPlaybackRecorder () :
-    m_captureData ({ .owner = this, .captureStream = nullptr, .captureLost = false }), m_analyzer (CAPTURE_RATE),
-    m_webFFT (kiss_fftr_alloc (WAVE_BUFFER_SIZE, 0, nullptr, nullptr)) {
+    m_captureData ({ .owner = this, .captureStream = nullptr, .captureLost = false }), m_analyzer (CAPTURE_RATE) {
     this->m_dataMutex = SDL_CreateMutex ();
     this->m_mainloop = pa_mainloop_new ();
     this->m_mainloopApi = pa_mainloop_get_api (this->m_mainloop);
@@ -270,8 +269,6 @@ PulseAudioPlaybackRecorder::~PulseAudioPlaybackRecorder () {
 	pa_stream_unref (m_captureData.captureStream);
     }
 
-    free (this->m_webFFT);
-
     pa_context_disconnect (this->m_context);
     pa_context_unref (this->m_context);
     pa_mainloop_free (this->m_mainloop);
@@ -311,9 +308,12 @@ void PulseAudioPlaybackRecorder::captureLoop () {
 }
 
 void PulseAudioPlaybackRecorder::clearCaptured () {
+    constexpr float silence[128] = {};
+
     this->lock ();
     std::fill_n (this->m_captured, 128, 0.0f);
     this->unlock ();
+    this->notifySpectrumListeners (silence);
 }
 
 void PulseAudioPlaybackRecorder::dropBlock () { this->m_analyzer.reset (); }
@@ -327,48 +327,8 @@ void PulseAudioPlaybackRecorder::consumeSamples (const float* samples, std::size
 	this->lock ();
 	std::copy_n (bands, 128, this->m_captured);
 	this->unlock ();
+	this->notifySpectrumListeners (bands);
     }
-
-    for (std::size_t i = 0; i < frames; i++) {
-	this->m_webSamples[this->m_webSampleCount++]
-	    = (samples[i * CAPTURE_CHANNELS] + samples[i * CAPTURE_CHANNELS + 1]) * 0.5f;
-
-	if (this->m_webSampleCount == WAVE_BUFFER_SIZE) {
-	    this->m_webSampleCount = 0;
-	    this->processWebFrame ();
-	}
-    }
-}
-
-void PulseAudioPlaybackRecorder::processWebFrame () {
-    kiss_fftr (this->m_webFFT, this->m_webSamples, this->m_FFTinfo);
-
-    float bands64[64];
-
-    for (int band = 0; band < 64; band++) {
-	const int index = band * 2;
-	const float power
-	    = this->m_FFTinfo[index].r * this->m_FFTinfo[index].r + this->m_FFTinfo[index].i * this->m_FFTinfo[index].i;
-	float level = 0.0f;
-
-	if (power > 0.0f) {
-	    level = 0.35f * log10 (power) + 1.0f;
-	}
-
-	bands64[band] = fmax (0.0f, level * static_cast<float> (2.0f - pow (M_E, (1.0f - band / 63.0f) * 1.0f - 0.5f)));
-    }
-
-    const auto now = std::chrono::steady_clock::now ();
-    const float dt = std::chrono::duration<float> (now - this->m_lastWebFrame).count ();
-    this->m_lastWebFrame = now;
-
-    this->m_normalizer.update (bands64, 64, dt);
-
-    for (float& band : bands64) {
-	band = this->m_normalizer.apply (band);
-    }
-
-    this->notifySpectrumListeners (bands64);
 }
 
 } // namespace WallpaperEngine::Audio::Drivers::Recorders

+ 0 - 14
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h

@@ -2,16 +2,12 @@
 
 #include "PlaybackRecorder.h"
 #include "WallpaperEngine/Audio/SpectrumAnalyzer.h"
-#include "WallpaperEngine/Audio/SpectrumNormalizer.h"
-#include "kiss_fftr.h"
 #include <SDL.h>
 #include <atomic>
 #include <chrono>
 #include <pulse/pulseaudio.h>
 #include <string>
 
-#define WAVE_BUFFER_SIZE 1024
-
 namespace WallpaperEngine::Audio::Drivers::Recorders {
 class PlaybackRecorder;
 
@@ -37,7 +33,6 @@ public:
 private:
     static int captureThreadEntry (void* userdata);
     void captureLoop ();
-    void processWebFrame ();
     void clearCaptured ();
 
     pa_mainloop* m_mainloop;
@@ -49,15 +44,6 @@ private:
     WallpaperEngine::Audio::SpectrumAnalyzer m_analyzer;
     std::chrono::steady_clock::time_point m_lastSamples = std::chrono::steady_clock::now ();
 
-    // web wallpapers get their own spectrum through the listeners, WE computes that one in its web process with
-    // different rules, so it keeps the older mono FFT and normalizer
-    kiss_fftr_cfg m_webFFT;
-    WallpaperEngine::Audio::SpectrumNormalizer m_normalizer;
-    std::chrono::steady_clock::time_point m_lastWebFrame = std::chrono::steady_clock::now ();
-    float m_webSamples[WAVE_BUFFER_SIZE] = { 0.0f };
-    std::size_t m_webSampleCount = 0;
-    kiss_fft_cpx m_FFTinfo[WAVE_BUFFER_SIZE / 2 + 1] = { { .r = 0.0f, .i = 0.0f } };
-
     // Capture runs on its own thread (see the constructor) so it keeps draining PulseAudio
     // regardless of how long a render frame takes
     SDL_Thread* m_captureThread = nullptr;

+ 0 - 56
src/WallpaperEngine/Audio/SpectrumNormalizer.cpp

@@ -1,56 +0,0 @@
-#include "SpectrumNormalizer.h"
-
-#include <algorithm>
-#include <array>
-#include <cmath>
-#include <functional>
-
-using namespace WallpaperEngine::Audio;
-
-namespace {
-// levels are 0.35 * log10(power) scaled, so one unit is a bit under 30dB
-constexpr float WINDOW = 1.2f;
-// below this a band is never shown, capture noise and dither sit around here
-constexpr float GATE = 0.2f;
-// the smallest span that still gets stretched to fill the range, so faint sounds fill it without noise blowing up
-constexpr float MIN_SPAN = 0.35f;
-// how quickly the reference rises to a louder peak, per second (as an exponential rate)
-constexpr float ATTACK_RATE = 25.0f;
-constexpr float RELEASE_SECONDS = 3.0f;
-} // namespace
-
-void SpectrumNormalizer::update (const float* levels, std::size_t count, float dt) {
-    dt = std::clamp (dt, 0.0f, 0.25f);
-    count = std::min<std::size_t> (count, 64);
-
-    if (count == 0) {
-	return;
-    }
-
-    std::array<float, 64> sorted {};
-    std::copy_n (levels, count, sorted.begin ());
-
-    // average of the loudest fifth of the bands
-    const std::size_t top = std::max<std::size_t> (1, count / 5);
-    std::partial_sort (sorted.begin (), sorted.begin () + top, sorted.begin () + count, std::greater<> ());
-
-    float peak = 0.0f;
-    for (std::size_t i = 0; i < top; i++) {
-	peak += sorted[i];
-    }
-    peak /= static_cast<float> (top);
-
-    if (peak > this->m_reference) {
-	this->m_reference += (peak - this->m_reference) * (1.0f - std::exp (-ATTACK_RATE * dt));
-    } else {
-	// falls back to the current peak rather than to zero, so a steady level settles right at it
-	this->m_reference = peak + (this->m_reference - peak) * std::exp (-dt / RELEASE_SECONDS);
-    }
-}
-
-float SpectrumNormalizer::apply (float level) const {
-    const float high = std::max (this->m_reference, GATE + MIN_SPAN);
-    const float low = std::max (high - WINDOW, GATE);
-
-    return std::clamp ((level - low) / (high - low), 0.0f, 1.0f);
-}

+ 0 - 24
src/WallpaperEngine/Audio/SpectrumNormalizer.h

@@ -1,24 +0,0 @@
-#pragma once
-
-#include <cstddef>
-
-namespace WallpaperEngine::Audio {
-/**
- * Turns the recorder's unbounded log scaled band levels into 0-1 values that keep the shape of the spectrum at any
- * volume. The top of the range follows the loudest fifth of the bands (rising quickly, falling back over a few
- * seconds), and levels below a gate are never shown so silence and capture noise stay flat.
- */
-class SpectrumNormalizer {
-public:
-    /** Feeds the band levels of a frame (at most 64), dt being the time since the previous one */
-    void update (const float* levels, std::size_t count, float dt);
-
-    /** Maps one band level of the frame last given to update() into 0-1 */
-    [[nodiscard]] float apply (float level) const;
-
-    [[nodiscard]] float getReference () const { return this->m_reference; }
-
-private:
-    float m_reference = 0.0f;
-};
-} // namespace WallpaperEngine::Audio

+ 10 - 17
src/WallpaperEngine/Data/Assets/Texture.h

@@ -9,21 +9,6 @@
 #include "Types.h"
 
 namespace WallpaperEngine::Data::Assets {
-enum ContainerVersion {
-    ContainerVersion_UNKNOWN = 0,
-    ContainerVersion_TEXB0001 = 1,
-    ContainerVersion_TEXB0002 = 2,
-    ContainerVersion_TEXB0003 = 3,
-    ContainerVersion_TEXB0004 = 4,
-};
-
-enum AnimatedVersion {
-    AnimatedVersion_UNKNOWN = 0,
-    AnimatedVersion_TEXS0001 = 1,
-    AnimatedVersion_TEXS0002 = 2,
-    AnimatedVersion_TEXS0003 = 3,
-};
-
 enum FIF {
     FIF_UNKNOWN = -1,
     FIF_BMP = 0,
@@ -83,6 +68,13 @@ enum TextureFormat {
     TextureFormat_RGBa1010102 = 13,
     TextureFormat_RGBA16161616f = 14,
     TextureFormat_RGB161616f = 15,
+    /** The rest only have an FBO format name (sub_1401E53A0) */
+    TextureFormat_R32f = 16,
+    TextureFormat_RGBA16161616 = 17,
+    TextureFormat_RGB161616 = 18,
+    TextureFormat_RGBA16161616S = 19,
+    TextureFormat_RGB161616S = 20,
+    TextureFormat_RGBA8888S = 21,
     /** Not a .tex format: a depth only render target with 32 bit float depth (WE's shadow atlas, R32_TYPELESS) */
     TextureFormat_D32f = 100,
 };
@@ -158,8 +150,9 @@ struct Frame {
 };
 
 struct Texture {
-    ContainerVersion containerVersion = ContainerVersion_UNKNOWN;
-    AnimatedVersion animatedVersion = AnimatedVersion_UNKNOWN;
+    /** The number after TEXB / TEXS (sub_14015E580) */
+    uint32_t containerVersion = 0;
+    uint32_t animatedVersion = 0;
     /** Bitmask of TextureFlags, stored as raw uint32_t */
     uint32_t flags = TextureFlags_NoFlags;
     uint32_t width = 0;

+ 4 - 2
src/WallpaperEngine/Data/Model/DynamicValue.cpp

@@ -273,8 +273,10 @@ void DynamicValue::connect (DynamicValue* other) {
 
     const auto deregisterFunction = other->listen (lambda);
 
-    // trigger the same update cycle immediately for the initial value
-    lambda (*other, UpdateSource::Initialization);
+    // a null source (slider with a null value) keeps the parsed value like WE
+    if (other->getType () != UnderlyingType::Null) {
+	lambda (*other, UpdateSource::Initialization);
+    }
 
     this->m_connections.push_back (deregisterFunction);
 }

+ 55 - 0
src/WallpaperEngine/Data/Model/Effect.cpp

@@ -0,0 +1,55 @@
+#include "Effect.h"
+
+#include <algorithm>
+
+using namespace WallpaperEngine::Data::Model;
+
+bool EffectConditions::holds (const ComboMap& combos) const {
+    return std::ranges::all_of (this->tests, [&combos] (const EffectCondition& test) {
+	const auto it = combos.find (test.combo);
+	const int combo = it != combos.end () ? it->second : 0;
+
+	switch (test.op) {
+	    case EffectCondition::GreaterEqual:
+		return combo >= test.value;
+	    case EffectCondition::Greater:
+		return combo > test.value;
+	    case EffectCondition::LessEqual:
+		return combo <= test.value;
+	    case EffectCondition::Less:
+		return combo < test.value;
+	    default:
+		return combo == test.value;
+	}
+    });
+}
+
+// sub_1401EA500 picks the size, sub_1400D2C60 divides it by the scale
+glm::uvec2 FBO::bufferSize (const glm::vec2 objectSize) const {
+    int width
+	= this->width.has_value () ? static_cast<int> (*this->width) : std::max (static_cast<int> (objectSize.x), 4);
+    int height
+	= this->height.has_value () ? static_cast<int> (*this->height) : std::max (static_cast<int> (objectSize.y), 4);
+
+    if (this->fit.has_value () && width > 0 && height > 0) {
+	const int fit = static_cast<int> (*this->fit);
+
+	if (width < height) {
+	    const int side = std::min (fit, height);
+	    width = static_cast<int> (
+		static_cast<float> (width) / static_cast<float> (height) * static_cast<float> (side)
+	    );
+	    height = side;
+	} else {
+	    const int side = std::min (fit, width);
+	    height = static_cast<int> (
+		static_cast<float> (height) / static_cast<float> (width) * static_cast<float> (side)
+	    );
+	    width = side;
+	}
+    }
+
+    const int scale = std::max (static_cast<int> (this->scale), 1);
+
+    return { std::max (width / scale, 2), std::max (height / scale, 2) };
+}

+ 32 - 0
src/WallpaperEngine/Data/Model/Effect.h

@@ -1,23 +1,51 @@
 #pragma once
 
+#include <glm/vec2.hpp>
 #include <glm/vec4.hpp>
 #include <optional>
 #include <string>
+#include <vector>
 
 #include "Types.h"
 
 namespace WallpaperEngine::Data::Model {
 enum PassCommandType { Command_Copy = 0, Command_Swap = 1 };
 
+/** effect.json "conditions" entry (sub_1401E63B0): a combo against a number or {"value", "op"} */
+struct EffectCondition {
+    enum Operator { Equal, GreaterEqual, Greater, LessEqual, Less };
+
+    std::string combo;
+    int value = 0;
+    Operator op = Equal;
+};
+
+struct EffectConditions {
+    std::vector<EffectCondition> tests;
+
+    [[nodiscard]] bool holds (const ComboMap& combos) const;
+};
+
 struct FBO {
     std::string name;
     std::string format;
+    /** an int from 1 to 255, anything else is 1 */
     float scale;
     bool unique;
     /** "clear": up to four numbers, what the buffer is cleared to when made and by a clear function */
     glm::vec4 clearColor = {};
     /** "clear" was empty or had all four numbers (wallpaper64.exe 2.8.42 sub_1401E7170, FBO flag 2) */
     bool clearOnCreate = false;
+    /** width/height replace the object's size, fit shrinks the longer side to it (sub_1401EA500) */
+    std::optional<uint32_t> width = std::nullopt;
+    std::optional<uint32_t> height = std::nullopt;
+    std::optional<uint32_t> fit = std::nullopt;
+    /** "uvs": "repeat" */
+    bool repeat = false;
+    EffectConditions conditions = {};
+
+    /** width/height/fit, divided by the scale, at least 2 */
+    [[nodiscard]] glm::uvec2 bufferSize (glm::vec2 objectSize) const;
 };
 
 /**
@@ -31,11 +59,15 @@ struct EffectFunction {
 };
 
 struct EffectPass {
+    /** a pass failing its conditions keeps its index for pass overrides */
+    EffectConditions conditions;
     std::optional<MaterialUniquePtr> material;
     TextureMap binds;
     std::optional<PassCommandType> command;
     std::optional<std::string> source;
     std::optional<std::string> target;
+    /** counted into the layer's buffer passes (sub_1401E7170) */
+    bool compose = false;
 };
 
 struct Effect {

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

@@ -43,6 +43,8 @@ struct MaterialPass {
     ComboMap combos;
     /** e.g. overbright, bloom settings */
     ShaderConstantMap constants;
+    /** Only read by scripts */
+    std::string alphawriting = "default";
 };
 
 struct Material {

+ 37 - 17
src/WallpaperEngine/Data/Model/Object.h

@@ -29,6 +29,8 @@ struct ObjectComponentDependency {
     std::string type;
     /** Which of the particle's components of that type uses it, in file order */
     int index;
+    /** emitterimage: its red channel scales the layer's alpha before pixels are picked */
+    std::string mask;
 };
 
 struct ObjectData {
@@ -36,12 +38,15 @@ struct ObjectData {
     std::string name;
     std::vector<int> dependencies;
     std::vector<ObjectComponentDependency> componentDependencies;
-    std::optional<int> parent;
+    /** mutable for setParent */
+    mutable std::optional<int> parent;
     /** Name of a named attachment point on the parent's puppet rig to follow, if any */
-    std::optional<std::string> attachment;
+    mutable std::optional<std::string> attachment;
     /** Explicit paint-order override (scene.json's "sortorder") - lower draws first (further back).
      *  Falls back to this object's array position when absent. */
     std::optional<int> sortOrder;
+    /** object +292, 0 unless set (sub_1401E0530) */
+    UserSettingUniquePtr sortOrderValue;
     UserSettingUniquePtr origin;
     /** Transform fields for generic scene/group objects. Typed objects keep their own transform fields. */
     UserSettingUniquePtr groupScale;
@@ -82,6 +87,8 @@ struct ImageEffect {
     /** Effect's name for the editor */
     std::string name;
     UserSettingUniquePtr visible;
+    /** what the effect.json "conditions" test (sub_1401E7170) */
+    ComboMap combos;
     std::vector<ImageEffectPassOverrideUniquePtr> passOverrides;
     EffectUniquePtr effect;
 };
@@ -114,6 +121,14 @@ enum ImageAlignment {
     ImageAlignment_Right = 8,
 };
 
+/** Only read by scripts (property table sub_1401EE520) */
+struct RenderableSettings {
+    UserSettingUniquePtr ledSource;
+    UserSettingUniquePtr noInterpolation;
+    UserSettingUniquePtr clampUVs;
+    UserSettingUniquePtr castShadow;
+};
+
 struct ImageData {
     UserSettingUniquePtr scale;
     UserSettingUniquePtr angles;
@@ -132,6 +147,7 @@ struct ImageData {
     bool clampUVs;
     /** Passthrough layers only: start from a copy of the scene behind them, otherwise from a transparent buffer */
     UserSettingUniquePtr copyBackground;
+    RenderableSettings renderable;
     ModelUniquePtr model;
     /** Applied after the material is rendered */
     std::vector<ImageEffectUniquePtr> effects;
@@ -157,14 +173,14 @@ struct SoundData {
      *  Sound objects (e.g. alternate music tracks) mute all but one via --set-property */
     UserSettingUniquePtr volume;
     /** Sound stays muted until a script calls play() on its layer */
-    std::optional<bool> startsilent;
+    UserSettingUniquePtr startsilent;
     /** random mode: seconds of silence after a sound, picked between these */
-    float mintime;
-    float maxtime;
+    UserSettingUniquePtr mintime;
+    UserSettingUniquePtr maxtime;
     /** AL_ROLLOFF_FACTOR / AL_REFERENCE_DISTANCE of spatialized sounds */
-    float attenuation;
-    float mindistance;
-    bool spatialization;
+    UserSettingUniquePtr attenuation;
+    UserSettingUniquePtr mindistance;
+    UserSettingUniquePtr spatialization;
 };
 
 class Sound : public Object, public SoundData {
@@ -252,10 +268,11 @@ public:
 
 class LifetimeRandomInitializer : public ParticleInitializerBase {
 public:
-    LifetimeRandomInitializer (UserSettingUniquePtr min, UserSettingUniquePtr max) :
-	min (std::move (min)), max (std::move (max)) { }
+    LifetimeRandomInitializer (UserSettingUniquePtr min, UserSettingUniquePtr max, UserSettingUniquePtr exponent) :
+	min (std::move (min)), max (std::move (max)), exponent (std::move (exponent)) { }
     UserSettingUniquePtr min;
     UserSettingUniquePtr max;
+    UserSettingUniquePtr exponent;
 };
 
 class VelocityRandomInitializer : public ParticleInitializerBase {
@@ -866,7 +883,6 @@ struct ParticleRenderer {
     float segments; // ropetrail: number of history segments per particle
     float uvScale;
     bool uvScrolling;
-    bool uvSmoothing; // rope only: reduces flickering when lifetimes are identical
     bool fadeAlpha; // ropetrail: fade alpha along trail
     bool fadeSize; // ropetrail: fade size along trail
     /** "orientation" (sub_1401C22E0): screen 0, upright 1, fixed 2 */
@@ -1032,6 +1048,9 @@ struct TextData {
     UserSettingUniquePtr dropShadowColor;
     /** "enabled" draws with the depth tested font materials in 3D scenes, any other value is "disabled" */
     UserSettingUniquePtr depthTest;
+    /** Only read by scripts */
+    UserSettingUniquePtr copyBackground;
+    RenderableSettings renderable;
 };
 
 class Text : public Object, public TextData {
@@ -1048,13 +1067,15 @@ enum class LightType { Legacy, Point, Spot, Tube, Directional };
 
 struct LightData {
     LightType type;
+    /** "light" for scripts */
+    UserSettingUniquePtr typeName;
     UserSettingUniquePtr color;
     UserSettingUniquePtr intensity;
     UserSettingUniquePtr radius;
     UserSettingUniquePtr visible;
     /** Light volumes glowing in the air around the light (LightingV1 lights) */
-    bool castVolumetrics = false;
-    bool castShadow = false;
+    UserSettingUniquePtr castVolumetrics;
+    UserSettingUniquePtr castShadow;
     UserSettingUniquePtr density;
     UserSettingUniquePtr volumetricsExponent;
     /** Spot lights: half angles of the cone in degrees, full brightness inside the inner one */
@@ -1065,7 +1086,7 @@ struct LightData {
     /** Tube lights: the far end of the tube in the light's own space */
     UserSettingUniquePtr controlPoint;
     /** Spot lights projecting a texture ("cookie", WE falls back to cookie/flashlight1) */
-    bool useCookie = false;
+    UserSettingUniquePtr useCookie;
     std::string cookie;
     /** Directional light shadow cascades: how far each one reaches (light +768/+772/+776) */
     UserSettingUniquePtr cascadeDistance[3];
@@ -1098,14 +1119,13 @@ struct CameraTimeline {
     std::vector<AnimationKeyframe> fov;
 };
 
-enum class CameraQueueMode { Random = 0, Sequential = 1 };
-
 /** A "camera" object, the last visible one drives the scene's view (fov only in 3D scenes) */
 struct SceneCameraData {
     UserSettingUniquePtr fov;
     UserSettingUniquePtr zoom;
     std::vector<CameraTimeline> timelines;
-    CameraQueueMode queueMode = CameraQueueMode::Random;
+    /** "random" or "sequential" */
+    DynamicValueUniquePtr queueMode;
 };
 
 class SceneCamera : public Object, public SceneCameraData {

+ 13 - 2
src/WallpaperEngine/Data/Model/Property.h

@@ -7,6 +7,7 @@
 
 #include <functional>
 #include <map>
+#include <optional>
 #include <ranges>
 #include <string>
 #include <utility>
@@ -37,13 +38,23 @@ public:
     using DynamicValue::update;
     virtual void update (const std::string& value, UpdateSource source) = 0;
     [[nodiscard]] virtual std::string dump () const = 0;
+
+    /** Marks the property as read only at setup, a change then needs a reload */
+    void pin () const { this->m_pinned = true; }
+    [[nodiscard]] bool appliesLive () const { return !this->m_pinned; }
+
+private:
+    mutable bool m_pinned = false;
 };
 
 class PropertySlider final : public Property, SliderData {
 public:
-    PropertySlider (PropertyData data, SliderData sliderData, const float value) :
+    // a null "value" leaves it unset, bindings keep the scene's own (2667316345)
+    PropertySlider (PropertyData data, SliderData sliderData, const std::optional<float> value) :
 	Property (std::move (data)), SliderData (sliderData) {
-	this->Property::update (value, UpdateSource::Initialization);
+	if (value.has_value ()) {
+	    this->Property::update (value.value (), UpdateSource::Initialization);
+	}
     }
 
     using Property::update;

+ 1 - 0
src/WallpaperEngine/Data/Model/Types.h

@@ -13,6 +13,7 @@ class Web;
 class Video;
 struct UserSetting;
 struct ImageAnimationLayer;
+struct RenderableSettings;
 class Object;
 class Sound;
 class Image;

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

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

+ 135 - 3
src/WallpaperEngine/Data/Parsers/EffectParser.cpp

@@ -2,6 +2,8 @@
 #include "MaterialParser.h"
 
 #include <algorithm>
+#include <climits>
+#include <cmath>
 #include <cstdlib>
 
 #include "WallpaperEngine/Data/Model/DynamicValue.h"
@@ -87,6 +89,111 @@ std::vector<EffectFunction> EffectParser::parseFunctions (const JSON& it, const
     return result;
 }
 
+namespace {
+// WE's int check (sub_1400886E0): fits an int32 without a fraction
+std::optional<int> jsonInt (const JSON& value) {
+    if (value.is_number_unsigned ()) {
+	const auto number = value.get<uint64_t> ();
+	return number <= INT_MAX ? std::optional (static_cast<int> (number)) : std::nullopt;
+    }
+
+    if (value.is_number_integer ()) {
+	const auto number = value.get<int64_t> ();
+	return number >= INT_MIN && number <= INT_MAX ? std::optional (static_cast<int> (number)) : std::nullopt;
+    }
+
+    if (value.is_number_float ()) {
+	const auto number = value.get<double> ();
+
+	if (number >= INT_MIN && number <= INT_MAX && std::trunc (number) == number) {
+	    return static_cast<int> (number);
+	}
+    }
+
+    return std::nullopt;
+}
+
+// WE's asInt (sub_140085EE0)
+int jsonAsInt (const JSON& value) {
+    if (value.is_number_integer ()) {
+	return static_cast<int> (value.get<int64_t> ());
+    }
+
+    if (value.is_number_float ()) {
+	return static_cast<int> (value.get<double> ());
+    }
+
+    return 0;
+}
+
+// 16 bit, only used up to 4096 (sub_1401EA500)
+std::optional<uint32_t> fboSize (const JSON& it, const char* key) {
+    const auto found = it.find (key);
+
+    if (found == it.end ()) {
+	return std::nullopt;
+    }
+
+    const auto number = jsonInt (*found);
+
+    if (!number.has_value () || static_cast<uint16_t> (*number) > 0x1000) {
+	return std::nullopt;
+    }
+
+    return static_cast<uint16_t> (*number);
+}
+} // namespace
+
+// sub_1401E63B0: each member names a combo, a number must equal it, an object compares "value" by "op"
+EffectConditions EffectParser::parseConditions (const JSON& it) {
+    EffectConditions result;
+
+    if (!it.is_array ()) {
+	return result;
+    }
+
+    for (const auto& entry : it) {
+	if (!entry.is_object ()) {
+	    continue;
+	}
+
+	for (const auto& [combo, test] : entry.items ()) {
+	    if (test.is_number ()) {
+		result.tests.push_back ({ .combo = combo, .value = jsonAsInt (test) });
+		continue;
+	    }
+
+	    if (!test.is_object ()) {
+		continue;
+	    }
+
+	    EffectCondition condition { .combo = combo };
+
+	    if (const auto value = test.find ("value"); value != test.end ()) {
+		condition.value = jsonAsInt (*value);
+	    }
+
+	    if (const auto op = test.find ("op"); op != test.end () && op->is_string ()) {
+		const auto name = op->get<std::string> ();
+
+		if (name == "ge") {
+		    condition.op = EffectCondition::GreaterEqual;
+		} else if (name == "gt") {
+		    condition.op = EffectCondition::Greater;
+		} else if (name == "le") {
+		    condition.op = EffectCondition::LessEqual;
+		} else if (name == "lt") {
+		    condition.op = EffectCondition::Less;
+		}
+	    }
+
+	    result.tests.push_back (std::move (condition));
+	}
+    }
+
+    return result;
+}
+
 std::vector<std::string> EffectParser::parseDependencies (const JSON& it) {
     std::vector<std::string> result = {};
 
@@ -112,9 +219,11 @@ std::vector<EffectPassUniquePtr> EffectParser::parseEffectPasses (const JSON& it
 	const auto binds = cur.optional ("bind");
 	const auto command = cur.optional ("command");
 	const auto material = cur.optional ("material");
+	const auto conditions = cur.optional ("conditions");
 
 	result.push_back (
 	    std::make_unique<EffectPass> (EffectPass {
+		.conditions = conditions.has_value () ? parseConditions (*conditions) : EffectConditions {},
 		.material = material.has_value () ? MaterialParser::load (project, *material)
 						  : std::optional<MaterialUniquePtr> {},
 		.binds = binds.has_value () ? parseBinds (binds.value ()) : std::map<int, std::string> {},
@@ -126,6 +235,7 @@ std::vector<EffectPassUniquePtr> EffectParser::parseEffectPasses (const JSON& it
 		.target = command.has_value ()
 		    ? cur.require<std::string> ("target", "Effect command must have a target")
 		    : cur.optional<std::string> ("target"),
+		.compose = cur.optional<bool> ("compose").value_or (false),
 	    })
 	);
     }
@@ -158,11 +268,33 @@ std::vector<FBOUniquePtr> EffectParser::parseFBOs (const JSON& it) {
     }
 
     for (const auto& cur : it) {
+	const auto name = cur.find ("name");
+	const auto format = cur.find ("format");
+
+	if (name == cur.end () || !name->is_string () || format == cur.end () || !format->is_string ()) {
+	    continue;
+	}
+
+	// stored in a byte, a non-int is 1
+	int scale = 1;
+
+	if (const auto scaleIt = cur.find ("scale"); scaleIt != cur.end ()) {
+	    scale = jsonInt (*scaleIt).value_or (1);
+	}
+
+	const auto uvs = cur.find ("uvs");
+	const auto conditions = cur.find ("conditions");
+
 	auto fbo = std::make_unique<FBO> (FBO {
-	    .name = cur.require<std::string> ("name", "FBO must have a name"),
-	    .format = cur.optional<std::string> ("format", "rgba8888"),
-	    .scale = cur.optional ("scale", 1.0f),
+	    .name = name->get<std::string> (),
+	    .format = format->get<std::string> (),
+	    .scale = static_cast<float> (static_cast<uint8_t> (scale)),
 	    .unique = cur.optional ("unique", false),
+	    .width = fboSize (cur, "width"),
+	    .height = fboSize (cur, "height"),
+	    .fit = fboSize (cur, "fit"),
+	    .repeat = uvs != cur.end () && uvs->is_string () && uvs->get<std::string> () == "repeat",
+	    .conditions = conditions != cur.end () ? parseConditions (*conditions) : EffectConditions {},
 	});
 
 	// sub_1401E7170 reads "clear" with atof, one number per run of spaces; an empty string or all four numbers

+ 1 - 0
src/WallpaperEngine/Data/Parsers/EffectParser.h

@@ -18,6 +18,7 @@ private:
     static std::vector<EffectPassUniquePtr> parseEffectPasses (const JSON& it, const Project& project);
     static std::map<int, std::string> parseBinds (const JSON& it);
     static std::vector<FBOUniquePtr> parseFBOs (const JSON& it);
+    static EffectConditions parseConditions (const JSON& it);
     static std::vector<EffectFunction> parseFunctions (const JSON& it, const std::vector<FBOUniquePtr>& fbos);
 };
 } // namespace WallpaperEngine::Data::Parsers

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

@@ -77,6 +77,7 @@ MaterialPassUniquePtr MaterialParser::parsePass (const JSON& it, const Project&
 	.usertextures = usertextures.has_value () ? TextureParser::parseTextureMap (*usertextures) : TextureMap {},
 	.combos = combos.has_value () ? parseCombos (*combos) : ComboMap {},
 	.constants = constants.has_value () ? ShaderConstantParser::parse (*constants, project) : ShaderConstantMap {},
+	.alphawriting = it.optional ("alphawriting", std::string ("default")),
     });
 }
 

+ 58 - 20
src/WallpaperEngine/Data/Parsers/ObjectParser.cpp

@@ -11,6 +11,7 @@
 #include "WallpaperEngine/Data/Builders/UserSettingBuilder.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Model/Project.h"
+#include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Maths.h"
 
@@ -300,6 +301,7 @@ ObjectUniquePtr ObjectParser::parseObject (const JSON& it, const Project& projec
 	    .parent = it.optional<int> ("parent"),
 	    .attachment = it.optional<std::string> ("attachment"),
 	    .sortOrder = it.optional<int> ("sortorder"),
+	    .sortOrderValue = it.user ("sortorder", project.properties, 0),
 	    .origin = it.user ("origin", project.properties, glm::vec3 (0.0f)),
 	    .groupScale = it.user ("scale", project.properties, glm::vec3 (1.0f)),
 	    .groupAngles = it.user ("angles", project.properties, glm::vec3 (0.0f)),
@@ -331,6 +333,7 @@ ObjectUniquePtr ObjectParser::parseObject (const JSON& it, const Project& projec
 	    .parent = it.optional<int> ("parent"),
 	    .attachment = it.optional<std::string> ("attachment"),
 	    .sortOrder = it.optional<int> ("sortorder"),
+	    .sortOrderValue = it.user ("sortorder", project.properties, 0),
 	    .origin = it.user ("origin", project.properties, glm::vec3 (0.0f)),
 	    .groupScale = it.user ("scale", project.properties, glm::vec3 (1.0f)),
 	    .groupAngles = it.user ("angles", project.properties, glm::vec3 (0.0f)),
@@ -487,8 +490,9 @@ SceneCameraUniquePtr ObjectParser::parseCamera (const JSON& it, const Project& p
 	.fov = it.user ("fov", project.properties, 50.0f),
 	.zoom = it.user ("zoom", project.properties, 1.0f),
 	.timelines = {},
-	.queueMode = it.optional ("queuemode", std::string ("random")) == "sequential" ? CameraQueueMode::Sequential
-										       : CameraQueueMode::Random,
+	.queueMode = std::make_unique<DynamicValue> (
+	    std::string (it.optional ("queuemode", std::string ("random")) == "sequential" ? "sequential" : "random")
+	),
     };
 
     if (const auto path = it.optional<std::string> ("path"); path.has_value ()) {
@@ -498,6 +502,15 @@ SceneCameraUniquePtr ObjectParser::parseCamera (const JSON& it, const Project& p
     return std::make_unique<SceneCamera> (std::move (base), std::move (data));
 }
 
+RenderableSettings ObjectParser::parseRenderable (const JSON& it, const Project& project) {
+    return {
+	.ledSource = it.user ("ledsource", project.properties, false),
+	.noInterpolation = it.user ("nointerpolation", project.properties, false),
+	.clampUVs = it.user ("clampuvs", project.properties, true),
+	.castShadow = it.user ("castshadow", project.properties, false),
+    };
+}
+
 LightUniquePtr ObjectParser::parseLight (const JSON& it, const Project& project, ObjectData base) {
     const auto name = it.require<std::string> ("light", "Light must have a type");
     const std::map<std::string, LightType> types = {
@@ -517,20 +530,21 @@ LightUniquePtr ObjectParser::parseLight (const JSON& it, const Project& project,
 	std::move (base),
 	LightData {
 	    .type = type != types.end () ? type->second : LightType::Legacy,
+	    .typeName = Builders::UserSettingBuilder::fromValue (name),
 	    .color = it.color ("color", project.properties, Builders::ColorBuilder::White),
 	    .intensity = it.user ("intensity", project.properties, 1.0f),
 	    .radius = it.user ("radius", project.properties, 1.0f),
 	    .visible = it.user ("visible", project.properties, true),
 	    // defaults from the light's constructor (sub_14018FF60) and property table (sub_14025DA80)
-	    .castVolumetrics = it.optional ("castvolumetrics", false),
-	    .castShadow = it.optional ("castshadow", false),
+	    .castVolumetrics = it.user ("castvolumetrics", project.properties, false),
+	    .castShadow = it.user ("castshadow", project.properties, false),
 	    .density = it.user ("density", project.properties, 2.0f),
 	    .volumetricsExponent = it.user ("volumetricsexponent", project.properties, 1.0f),
 	    .innerCone = it.user ("innercone", project.properties, 20.0f),
 	    .outerCone = it.user ("outercone", project.properties, 30.0f),
 	    .exponent = it.user ("exponent", project.properties, 2.0f),
 	    .controlPoint = it.user ("controlpoint", project.properties, glm::vec3 (2.0f, 0.0f, 0.0f)),
-	    .useCookie = it.optional ("usecookie", false),
+	    .useCookie = it.user ("usecookie", project.properties, false),
 	    .cookie = it.optional ("cookie", std::string ()),
 	    .cascadeDistance = {
 		it.user ("cascadedistance0", project.properties, 3.0f),
@@ -595,8 +609,12 @@ std::vector<ObjectComponentDependency> ObjectParser::parseComponentDependencies
 	    || !cur["index"].is_number () || !cur.contains ("type") || !cur["type"].is_string ()) {
 	    continue;
 	}
+	const auto mask = cur.find ("mask");
 	result.push_back (
-	    { .id = cur["id"].get<int> (), .type = cur["type"].get<std::string> (), .index = cur["index"].get<int> () }
+	    { .id = cur["id"].get<int> (),
+	      .type = cur["type"].get<std::string> (),
+	      .index = cur["index"].get<int> (),
+	      .mask = mask != cur.end () && mask->is_string () ? mask->get<std::string> () : "" }
 	);
     }
 
@@ -614,19 +632,25 @@ SoundUniquePtr ObjectParser::parseSound (const JSON& it, const Project& project,
 	}
     }
 
+    // not user bindable, a non-string is "" which means loop (sub_1401F7D00)
+    const auto playbackmode = it.optional ("playbackmode");
+    const std::string mode
+	= playbackmode.has_value () && playbackmode->is_string () ? playbackmode->get<std::string> () : "";
+
     // defaults from the sound object's constructor in sub_14018FF60
     return std::make_unique<Sound> (
 	std::move (base),
 	SoundData {
-	    .playbackmode = parsePlaybackMode (it.optional ("playbackmode", std::string ("loop"))),
+	    .playbackmode = parsePlaybackMode (mode),
 	    .sounds = sounds,
 	    .volume = it.user<float> ("volume", project.properties, 1.0f),
-	    .startsilent = it.optional<bool> ("startsilent"),
-	    .mintime = it.optional ("mintime", 1.0f),
-	    .maxtime = it.optional ("maxtime", 5.0f),
-	    .attenuation = it.optional ("attenuation", 1.0f),
-	    .mindistance = it.optional ("mindistance", 1.0f),
-	    .spatialization = it.optional ("spatialization", false),
+	    // all user bindable (2937687740 binds maxtime to a slider)
+	    .startsilent = it.user ("startsilent", project.properties, false),
+	    .mintime = it.user ("mintime", project.properties, 1.0f),
+	    .maxtime = it.user ("maxtime", project.properties, 5.0f),
+	    .attenuation = it.user ("attenuation", project.properties, 1.0f),
+	    .mindistance = it.user ("mindistance", project.properties, 1.0f),
+	    .spatialization = it.user ("spatialization", project.properties, false),
 	}
     );
 }
@@ -702,7 +726,7 @@ TextUniquePtr ObjectParser::parseText (const JSON& it, const Project& project, O
 	    .spacing = it.user ("spacing", properties, glm::vec2 (0.0f)),
 	    .effects = effects.has_value () ? parseEffects (*effects, project) : std::vector<ImageEffectUniquePtr> {},
 	    .limitWidth = it.user ("limitwidth", properties, false),
-	    .maxWidth = it.user ("maxwidth", properties, 512.0f),
+	    .maxWidth = it.user ("maxwidth", properties, 500.0f),
 	    .limitRows = it.user ("limitrows", properties, false),
 	    .maxRows = it.user ("maxrows", properties, 1),
 	    .limitUseEllipsis = it.user ("limituseellipsis", properties, false),
@@ -723,6 +747,8 @@ TextUniquePtr ObjectParser::parseText (const JSON& it, const Project& project, O
 	    .dropShadowOffset = it.user ("dropshadowoffset", properties, glm::vec2 (4.0f)),
 	    .dropShadowColor = it.color ("dropshadowcolor", properties, Builders::ColorBuilder::Black),
 	    .depthTest = it.user ("depthtest", properties, std::string ("enabled")),
+	    .copyBackground = it.user ("copybackground", properties, true),
+	    .renderable = parseRenderable (it, project),
 	}
     );
 }
@@ -752,6 +778,7 @@ ObjectParser::parseImage (const JSON& it, const Project& project, ObjectData bas
 	    .brightness = it.user ("brightness", properties, 1.0f),
 	    .clampUVs = it.optional ("clampuvs", false),
 	    .copyBackground = it.user ("copybackground", properties, true),
+	    .renderable = parseRenderable (it, project),
 	    .model = ModelParser::load (project, image),
 	    .effects = effects.has_value () ? parseEffects (*effects, project) : std::vector<ImageEffectUniquePtr> {},
 	    .animationLayers = animationLayers.has_value () ? parseAnimationLayers (*animationLayers, project)
@@ -826,10 +853,24 @@ std::vector<ImageEffectUniquePtr> ObjectParser::parseEffects (const JSON& it, co
 
 ImageEffectUniquePtr ObjectParser::parseEffect (const JSON& it, const Project& project) {
     const auto& passsOverrides = it.optional ("passes");
+    ComboMap combos;
+
+    // non-numbers count as 0 (sub_1401E63B0)
+    if (const auto found = it.find ("combos"); found != it.end () && found->is_object ()) {
+	for (const auto& [name, value] : found->items ()) {
+	    combos.emplace (
+		name,
+		value.is_number_float () ? static_cast<int> (value.get<double> ())
+					 : (value.is_number () ? static_cast<int> (value.get<int64_t> ()) : 0)
+	    );
+	}
+    }
+
     return std::make_unique<ImageEffect> (ImageEffect {
 	.id = it.optional<int> ("id", -1),
 	.name = it.optional<std::string> ("name", "Effect without name"),
 	.visible = it.user ("visible", project.properties, true),
+	.combos = std::move (combos),
 	.passOverrides = passsOverrides.has_value () ? parseEffectPassOverrides (passsOverrides.value (), project)
 						     : std::vector<ImageEffectPassOverrideUniquePtr> {},
 	.effect = EffectParser::load (project, it.require ("file", "Image effect must have an effect")) });
@@ -1054,7 +1095,6 @@ ParticleUniquePtr ObjectParser::parseParticle (const JSON& it, const Project& pr
 		    .segments = 4.0f,
 		    .uvScale = 1.0f,
 		    .uvScrolling = false,
-		    .uvSmoothing = true,
 		    .fadeAlpha = false,
 		    .fadeSize = false,
 		}
@@ -1296,7 +1336,7 @@ ParticleInitializerUniquePtr ObjectParser::parseParticleInitializer (const JSON&
 	);
     } else if (name == "lifetimerandom") {
 	return std::make_unique<LifetimeRandomInitializer> (
-	    it.user ("min", properties, 0.0f), it.user ("max", properties, 1.0f)
+	    it.user ("min", properties, 0.0f), it.user ("max", properties, 1.0f), it.user ("exponent", properties, 1.0f)
 	);
     } else if (name == "velocityrandom") {
 	// defaults (sub_1401BAC50) differ between 2D and 3D scenes, CParticle picks them
@@ -1588,7 +1628,6 @@ ParticleRenderer ObjectParser::parseParticleRenderer (const JSON& it) {
 	.segments = it.optional ("segments", 4.0f),
 	.uvScale = it.optional ("uvscale", 1.0f),
 	.uvScrolling = it.optional ("uvscrolling", false),
-	.uvSmoothing = it.optional ("uvsmoothing", true),
 	.fadeAlpha = it.optional ("fadealpha", false),
 	.fadeSize = it.optional ("fadesize", false),
 	.orientation = orientation == "upright" ? 1
@@ -1712,8 +1751,6 @@ ParticleChild ObjectParser::parseParticleChild (
 	glm::vec4 (row0 * scale.x, 0.0f), glm::vec4 (row1 * scale.y, 0.0f), glm::vec4 (row2 * scale.z, 0.0f),
 	glm::vec4 (origin, 1.0f)
     );
-    // particle space here is WE's with y flipped, same as emitter origins and velocities
-    const glm::mat4 flipY = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
 
     // the child is loaded like a particle object of its own that shares the owner's instance override
     JSON childObject = JSON::object ();
@@ -1738,6 +1775,7 @@ ParticleChild ObjectParser::parseParticleChild (
 		    .parent = std::nullopt,
 		    .attachment = std::nullopt,
 		    .sortOrder = std::nullopt,
+		    .sortOrderValue = Builders::UserSettingBuilder::fromValue (0),
 		    .origin = Builders::UserSettingBuilder::fromValue (glm::vec3 (0.0f)),
 		    .groupScale = Builders::UserSettingBuilder::fromValue (glm::vec3 (1.0f)),
 		    .groupAngles = Builders::UserSettingBuilder::fromValue (glm::vec3 (0.0f)),
@@ -1766,7 +1804,7 @@ ParticleChild ObjectParser::parseParticleChild (
 	.probability = it.optional ("probability", 1.0f),
 	.flags = it.optional ("flags", 0u),
 	.controlPointStartIndex = it.optional ("controlpointstartindex", 0),
-	.transform = flipY * weTransform * flipY,
+	.transform = weTransform,
 	.particle = std::move (particle),
     };
 }

+ 1 - 0
src/WallpaperEngine/Data/Parsers/ObjectParser.h

@@ -25,6 +25,7 @@ private:
     static ObjectUniquePtr parseObject (const JSON& it, const Project& project);
     static std::vector<int> parseDependencies (const JSON& it);
     static std::vector<ObjectComponentDependency> parseComponentDependencies (const JSON& it);
+    static RenderableSettings parseRenderable (const JSON& it, const Project& project);
     static SoundUniquePtr parseSound (const JSON& it, const Project& project, ObjectData base);
     static SoundPlaybackMode parsePlaybackMode (const std::string& mode);
     static ImageUniquePtr

+ 3 - 1
src/WallpaperEngine/Data/Parsers/PropertyParser.cpp

@@ -100,6 +100,8 @@ PropertySharedPtr PropertyParser::parseBoolean (const JSON& it, const std::strin
 }
 
 PropertySharedPtr PropertyParser::parseSlider (const JSON& it, const std::string& name) {
+    const auto value = it.optional ("value");
+
     return std::make_shared<PropertySlider> (
 	PropertyData {
 	    .name = name,
@@ -110,7 +112,7 @@ PropertySharedPtr PropertyParser::parseSlider (const JSON& it, const std::string
 	    .max = it.optional ("max", 0.0f),
 	    .step = it.optional ("step", 0.0f),
 	},
-	it.require ("value", "Property must have a value")
+	value.has_value () && !value->is_null () ? std::optional<float> (value->get<float> ()) : std::nullopt
     );
 }
 

+ 72 - 123
src/WallpaperEngine/Data/Parsers/TextureParser.cpp

@@ -1,4 +1,5 @@
 #include <cmath>
+#include <cstdlib>
 #include <cstring>
 
 #include <lz4.h>
@@ -13,39 +14,35 @@ using namespace WallpaperEngine::Data::Parsers;
 
 TextureUniquePtr TextureParser::parse (const BinaryReader& file) {
     auto result = std::make_unique<Texture> ();
+    const std::string magic = file.nextNullTerminatedString ();
 
-    // wallpaper64.exe sub_14015E580: TEXV0004 is a version 0 TEXI header followed by a version 0 TEXB body (one
-    // image, mips like TEXB0001) with no section tags and no TEXS
-    const bool legacy = parseTextureHeader (*result, file);
-
-    if (legacy) {
-	result->containerVersion = ContainerVersion_TEXB0001;
-	result->imageCount = 1;
-    } else {
-	parseContainer (*result, file);
+    // sub_14015E580: TEXV0004 is an untagged v0 TEXI + v0 TEXB, TEXV0005 tagged sections whose last four
+    // digits are the version, stopping at the first unknown tag
+    if (magic == "TEXV0004") {
+	parseTextureHeader (*result, file, 0);
+	parseContainer (*result, file, 0);
+	return result;
     }
 
-    for (uint32_t image = 0; image < result->imageCount; image++) {
-	const uint32_t mipmapCount = file.nextUInt32 ();
-	MipmapList mipmaps;
+    if (magic != "TEXV0005") {
+	sLog.exception ("unexpected texture container type: ", magic);
+    }
 
-	for (uint32_t mipmap = 0; mipmap < mipmapCount; mipmap++) {
-	    mipmaps.emplace_back (parseMipmap (file, *result));
+    while (file.base ().peek () != std::char_traits<char>::eof ()) {
+	const std::string tag = file.nextNullTerminatedString ();
+	const uint32_t version = tag.size () > 4 ? static_cast<uint32_t> (std::atoi (tag.c_str () + 4)) : 0;
 
-	    if (!result->conditions.empty ()) {
-		parseMipmapPatches (*mipmaps.back (), file);
-	    }
+	if (tag.starts_with ("TEXI")) {
+	    parseTextureHeader (*result, file, version);
+	} else if (tag.starts_with ("TEXB")) {
+	    parseContainer (*result, file, version);
+	} else if (tag.starts_with ("TEXS")) {
+	    parseAnimations (*result, file, version);
+	} else {
+	    break;
 	}
-
-	result->images.emplace (image, mipmaps);
-    }
-
-    if (legacy || !result->isAnimated ()) {
-	return result;
     }
 
-    parseAnimations (*result, file);
-
     return result;
 }
 
@@ -60,21 +57,21 @@ MipmapSharedPtr TextureParser::parseMipmap (const BinaryReader& file, const Text
 	result->depth = file.nextUInt32 ();
     }
 
-    if (header.containerVersion == ContainerVersion_TEXB0003 || header.containerVersion == ContainerVersion_TEXB0002) {
+    if (header.containerVersion >= 2) {
 	result->compression = file.nextUInt32 ();
 	result->uncompressedSize = file.nextInt ();
     }
 
     result->compressedSize = file.nextInt ();
 
-    if (result->compression == 0) {
+    if ((result->compression & 1) == 0) {
 	// misnamed: in uncompressed files compressedSize actually holds the file length
 	result->uncompressedSize = result->compressedSize;
     }
 
     result->uncompressedData = std::unique_ptr<char[]> (new char[result->uncompressedSize]);
 
-    if (result->compression == 1) {
+    if (result->compression & 1) {
 	result->compressedData = std::unique_ptr<char[]> (new char[result->compressedSize]);
 	file.next (result->compressedData.get (), result->compressedSize);
 	int bytes = LZ4_decompress_safe (
@@ -176,49 +173,11 @@ TextureMap TextureParser::parseTextureMap (const JSON& it) {
     return result;
 }
 
-TextureFormat TextureParser::parseTextureFormat (uint32_t value) {
-    switch (value) {
-	case TextureFormat_UNKNOWN:
-	case TextureFormat_ARGB8888:
-	case TextureFormat_RGB888:
-	case TextureFormat_RGB565:
-	case TextureFormat_DXT5:
-	case TextureFormat_DXT3:
-	case TextureFormat_DXT1:
-	case TextureFormat_RG88:
-	case TextureFormat_R8:
-	case TextureFormat_RG1616f:
-	case TextureFormat_R16f:
-	case TextureFormat_BC7:
-	case TextureFormat_RGBa1010102:
-	case TextureFormat_RGBA16161616f:
-	case TextureFormat_RGB161616f:
-	    return static_cast<TextureFormat> (value);
-
-	default:
-	    sLog.exception ("unknown texture format: ", value);
-    }
-}
-
-bool TextureParser::parseTextureHeader (Texture& header, const BinaryReader& file) {
-    char magic[9] = { 0 };
-
-    file.next (magic, 9);
-
-    const bool legacy = strncmp (magic, "TEXV0004", 9) == 0;
-
-    if (!legacy && strncmp (magic, "TEXV0005", 9) != 0) {
-	sLog.exception ("unexpected texture container type: ", std::string_view (magic, 9));
-    }
-
-    if (!legacy) {
-	file.next (magic, 9);
-
-	if (strncmp (magic, "TEXI0001", 9) != 0) {
-	    sLog.exception ("unexpected texture sub-container type: ", std::string_view (magic, 9));
-	}
-    }
+// unknown formats are RGBA8 at upload (sub_1400D2A20)
+TextureFormat TextureParser::parseTextureFormat (uint32_t value) { return static_cast<TextureFormat> (value); }
 
+// sub_14015C760
+void TextureParser::parseTextureHeader (Texture& header, const BinaryReader& file, const uint32_t version) {
     header.format = parseTextureFormat (file.nextUInt32 ());
     header.flags = parseTextureFlags (file.nextUInt32 ());
     header.textureWidth = file.nextUInt32 ();
@@ -226,90 +185,80 @@ bool TextureParser::parseTextureHeader (Texture& header, const BinaryReader& fil
     header.width = file.nextUInt32 ();
     header.height = file.nextUInt32 ();
 
-    // wallpaper64.exe sub_14015C760
     if (header.flags & TextureFlags_Volume) {
 	header.depth = file.nextUInt32 ();
     }
 
-    // only TEXI version 1 and up has this field
-    if (!legacy) {
+    if (version >= 1) {
 	std::ignore = file.nextUInt32 ();
     }
-
-    return legacy;
 }
 
-void TextureParser::parseContainer (Texture& header, const BinaryReader& file) {
-    char magic[9] = { 0 };
-
-    file.next (magic, 9);
-
-    header.imageCount = file.nextUInt32 ();
+// sub_14015C8D0: v1 adds the image count, v2 per mip compression, v3 FreeImage format, v4 conditions
+void TextureParser::parseContainer (Texture& header, const BinaryReader& file, const uint32_t version) {
+    header.containerVersion = version;
+    header.imageCount = version >= 1 ? file.nextUInt32 () : 1;
 
-    if (strncmp (magic, "TEXB0004", 9) == 0) {
-	// 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;
+    if (version >= 3) {
 	header.freeImageFormat = parseFIF (file.nextUInt32 ());
 
-	const uint32_t conditionCount = file.nextUInt32 ();
+	// no power of two padding for encoded images
+	if (header.freeImageFormat != FIF_UNKNOWN) {
+	    header.textureWidth = header.width;
+	    header.textureHeight = header.height;
+	}
+    }
 
-	for (uint32_t index = 0; index < conditionCount; index++) {
-	    TextureCondition condition;
+    const uint32_t conditionCount = version >= 4 ? file.nextUInt32 () : 0;
 
-	    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;
-	header.freeImageFormat = parseFIF (file.nextUInt32 ());
-    } else if (strncmp (magic, "TEXB0002", 9) == 0) {
-	header.containerVersion = ContainerVersion_TEXB0002;
-    } else if (strncmp (magic, "TEXB0001", 9) == 0) {
-	header.containerVersion = ContainerVersion_TEXB0001;
-    } else {
-	sLog.exception ("unknown texture format type: ", std::string_view (magic, 9));
+    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));
     }
-}
 
-void TextureParser::parseAnimations (Texture& header, const BinaryReader& file) {
-    char magic[9] = { 0 };
+    for (uint32_t image = 0; image < header.imageCount; image++) {
+	const uint32_t mipmapCount = file.nextUInt32 ();
+	MipmapList mipmaps;
+
+	for (uint32_t mipmap = 0; mipmap < mipmapCount; mipmap++) {
+	    mipmaps.emplace_back (parseMipmap (file, header));
 
-    file.next (magic, 9);
+	    // present whenever there are conditions, even empty
+	    if (conditionCount > 0) {
+		parseMipmapPatches (*mipmaps.back (), file);
+	    }
+	}
 
-    if (strncmp (magic, "TEXS0001", 9) == 0) {
-	header.animatedVersion = AnimatedVersion_TEXS0001;
-    } else if (strncmp (magic, "TEXS0002", 9) == 0) {
-	header.animatedVersion = AnimatedVersion_TEXS0002;
-    } else if (strncmp (magic, "TEXS0003", 9) == 0) {
-	header.animatedVersion = AnimatedVersion_TEXS0003;
-    } else {
-	sLog.exception ("found animation information of unknown type: ", std::string_view (magic, 9));
+	header.images.emplace (image, mipmaps);
     }
+}
+
+// sub_14015E1D0: v1 has integer frame rects, v3+ stores the frame size after the count
+void TextureParser::parseAnimations (Texture& header, const BinaryReader& file, const uint32_t version) {
+    header.animatedVersion = version;
 
     uint32_t frameCount = file.nextUInt32 ();
 
-    if (header.animatedVersion == AnimatedVersion_TEXS0003) {
+    if (version >= 3) {
 	header.gifWidth = file.nextUInt32 ();
 	header.gifHeight = file.nextUInt32 ();
+    } else {
+	header.gifWidth = header.width;
+	header.gifHeight = header.height;
     }
 
     while (frameCount-- > 0) {
-	if (header.animatedVersion == AnimatedVersion_TEXS0001) {
+	if (version == 1) {
 	    header.frames.push_back (parseFrameV1 (file));
 	} else {
 	    header.frames.push_back (parseFrame (file));
 	}
     }
-
-    // wallpaper64.exe 2.8.42 sub_14015E1D0: before TEXS0003 the frame size is the TEXI image size
-    if (header.animatedVersion == AnimatedVersion_TEXS0001 || header.animatedVersion == AnimatedVersion_TEXS0002) {
-	header.gifWidth = header.width;
-	header.gifHeight = header.height;
-    }
 }
 
 uint32_t TextureParser::parseTextureFlags (uint32_t value) { return value & TextureFlags_All; }

+ 3 - 3
src/WallpaperEngine/Data/Parsers/TextureParser.h

@@ -24,9 +24,9 @@ public:
     static TextureMap parseTextureMap (const JSON& it);
 
 private:
-    static bool parseTextureHeader (Texture& header, const BinaryReader& file);
-    static void parseContainer (Texture& header, const BinaryReader& file);
-    static void parseAnimations (Texture& header, const BinaryReader& file);
+    static void parseTextureHeader (Texture& header, const BinaryReader& file, uint32_t version);
+    static void parseContainer (Texture& header, const BinaryReader& file, uint32_t version);
+    static void parseAnimations (Texture& header, const BinaryReader& file, uint32_t version);
     static void parseMipmapPatches (Mipmap& mipmap, const BinaryReader& file);
     static TextureFormat parseTextureFormat (uint32_t value);
     static uint32_t parseTextureFlags (uint32_t value);

+ 4 - 1
src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp

@@ -291,7 +291,9 @@ SceneUniquePtr WallpaperParser::parseScene (const JSON& file, Project& project)
     const auto& properties = project.properties;
     // particles read it while the objects get parsed below
     project.sceneVersion = scene.optional ("version", 0);
-    // missing keys fall back to the scene constructor's defaults in wallpaper64.exe 2.8.42 (sub_140186C90)
+    // missing keys use the scene constructor's defaults (sub_140186C90); spritesheetrefreshsync is a plain bool
+    const auto syncIt = general.find ("spritesheetrefreshsync");
+    const bool spriteSheetRefreshSync = syncIt != general.end () && syncIt->is_boolean () && syncIt->get<bool> ();
 
     return std::make_unique <Scene> (
         WallpaperData {
@@ -364,6 +366,7 @@ SceneUniquePtr WallpaperParser::parseScene (const JSON& file, Project& project)
                 }
             },
             .transparentSorting = general.user ("transparentsorting", properties, false),
+            .spriteSheetRefreshSync = spriteSheetRefreshSync,
             .physics = {
                 .gravityDirection = general.user ("gravitydirection", properties, glm::vec3 (0.0f, -1.0f, 0.0f)),
                 .gravityStrength = general.user ("gravitystrength", properties, 1.0f),

+ 17 - 0
src/WallpaperEngine/Media/DBusMediaSource.cpp

@@ -162,6 +162,23 @@ void DBusMediaSource::parseMetadata (DBusMessageIter& variant) {
 		    metadataUpdate = true;
 		}
 	    }
+	} else if (keyStr == "xesam:albumArtist" || keyStr == "xesam:genre") {
+	    DBusMessageIter arr;
+
+	    dbus_message_iter_recurse (&value, &arr);
+
+	    if (dbus_message_iter_get_arg_type (&arr) == DBUS_TYPE_STRING) {
+		const char* text = nullptr;
+		dbus_message_iter_get_basic (&arr, &text);
+
+		std::string& target
+		    = keyStr == "xesam:albumArtist" ? this->m_mediaInfo.albumArtist : this->m_mediaInfo.genres;
+
+		if (target != (text ?: "")) {
+		    target = text ?: "";
+		    metadataUpdate = true;
+		}
+	    }
 	} else if (keyStr == "xesam:album") {
 	    const char* album = nullptr;
 	    dbus_message_iter_get_basic (&value, &album);

+ 3 - 0
src/WallpaperEngine/Media/MediaSource.h

@@ -21,6 +21,9 @@ public:
 	std::string title;
 	std::string artist;
 	std::string album;
+	/** first of MPRIS's list */
+	std::string albumArtist;
+	std::string genres;
 	std::optional<std::string> url;
 	double duration;
 	double position;

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

@@ -23,6 +23,14 @@ GLint internalFormat (const TextureFormat format) {
 	    return GL_RGBA16F;
 	case TextureFormat_RGBa1010102:
 	    return GL_RGB10_A2;
+	case TextureFormat_R32f:
+	    return GL_R32F;
+	case TextureFormat_RGBA16161616:
+	case TextureFormat_RGB161616:
+	    return GL_RGBA16;
+	case TextureFormat_RGBA16161616S:
+	case TextureFormat_RGB161616S:
+	    return GL_RGBA16_SNORM;
 	default:
 	    return GL_RGBA8;
     }

+ 151 - 42
src/WallpaperEngine/Render/CTexture.cpp

@@ -1,7 +1,12 @@
 #include "CTexture.h"
 #include "WallpaperEngine/Logging/Log.h"
 
+#include <algorithm>
+#include <atomic>
+#include <cstring>
 #include <lz4.h>
+#include <thread>
+#include <vector>
 
 #include "ImageDecoder.h"
 
@@ -18,7 +23,7 @@ extern float g_TimeLast;
 CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
     Helpers::ContextAware (context), m_header (std::move (header)) {
     this->setupResolution ();
-    const GLint internalFormat = this->setupInternalFormat ();
+    const UploadFormat upload = this->uploadFormat ();
 
     GLint maxTextureSize = 0;
     glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTextureSize);
@@ -76,6 +81,67 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
 	this->m_gif.reset ();
     }
 
+    this->uploadImages (upload);
+}
+
+void CTexture::uploadImages (const UploadFormat& upload) const {
+    struct Decoded {
+	const Mipmap* mipmap;
+	stbi_uc* pixels = nullptr;
+	int width = 0;
+	int height = 0;
+    };
+
+    // decode on worker threads, upload here
+    std::vector<Decoded> decoded;
+
+    if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
+	for (const auto& [index, mipmaps] : this->m_header->images) {
+	    for (const auto& mipmap : mipmaps) {
+		if (mipmap->composedPixels.empty ()) {
+		    decoded.push_back ({ .mipmap = mipmap.get (), .width = mipmap->width, .height = mipmap->height });
+		}
+	    }
+	}
+    }
+
+    const auto decode = [] (Decoded& job) {
+	job.pixels = decodeImageRGBA (
+	    job.mipmap->uncompressedData.get (), job.mipmap->uncompressedSize, job.width, job.height
+	);
+    };
+
+    if (decoded.size () == 1) {
+	decode (decoded.front ());
+    } else if (decoded.size () > 1) {
+	std::atomic<size_t> next = 0;
+	const auto worker = [&decoded, &next, &decode] () {
+	    for (size_t i = next++; i < decoded.size (); i = next++) {
+		decode (decoded[i]);
+	    }
+	};
+	const size_t threadCount
+	    = std::min<size_t> (decoded.size (), std::max (1u, std::thread::hardware_concurrency ()));
+	std::vector<std::thread> threads;
+
+	for (size_t i = 1; i < threadCount; i++) {
+	    threads.emplace_back (worker);
+	}
+
+	worker ();
+
+	for (auto& thread : threads) {
+	    thread.join ();
+	}
+    }
+
+    auto nextDecoded = decoded.begin ();
+    GLint previousAlignment = 4;
+
+    // tightly packed rows like WE's D3D pitch (sub_1400EC220)
+    glGetIntegerv (GL_UNPACK_ALIGNMENT, &previousAlignment);
+    glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
+
     for (const auto& [index, mipmaps] : this->m_header->images) {
 	this->setupOpenGLParameters (index);
 
@@ -84,45 +150,44 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
 	for (const auto& mipmap : mipmaps) {
 	    stbi_uc* handle = nullptr;
 	    const void* dataptr = mipmap->uncompressedData.get ();
+	    size_t dataSize = std::max (mipmap->uncompressedSize, 0);
 	    int width = mipmap->width;
 	    int height = mipmap->height;
-	    const uint32_t bufferSize = mipmap->uncompressedSize;
-	    GLenum textureFormat = GL_RGBA;
 
 	    if (!mipmap->composedPixels.empty ()) {
 		dataptr = mipmap->composedPixels.data ();
+		dataSize = mipmap->composedPixels.size ();
 	    } else if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
-		dataptr = handle
-		    = decodeImageRGBA (mipmap->uncompressedData.get (), mipmap->uncompressedSize, width, height);
+		dataptr = handle = nextDecoded->pixels;
+		width = nextDecoded->width;
+		height = nextDecoded->height;
+		dataSize = handle != nullptr ? static_cast<size_t> (width) * height * 4 : 0;
+		++nextDecoded;
+	    }
+
+	    if (upload.compressed) {
+		glCompressedTexImage2D (
+		    GL_TEXTURE_2D, level, upload.internalFormat, width, height, 0, static_cast<GLsizei> (dataSize),
+		    dataptr
+		);
 	    } else {
-		if (this->m_header->format == TextureFormat_R8) {
-		    // 1 byte per pixel, so alignment must be set manually
-		    glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
-		    textureFormat = GL_RED;
-		} else if (this->m_header->format == TextureFormat_RG88) {
-		    // 2 bytes per pixel, so odd widths are not 4-byte aligned
-		    glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
-		    textureFormat = GL_RG;
+		// pad a short mipmap with zeros instead of reading past it
+		const size_t expected = static_cast<size_t> (width) * height * upload.bytesPerPixel;
+		std::vector<unsigned char> padded;
+
+		if (dataSize < expected) {
+		    padded.resize (expected, 0);
+
+		    if (dataptr != nullptr && dataSize > 0) {
+			memcpy (padded.data (), dataptr, dataSize);
+		    }
+
+		    dataptr = padded.data ();
 		}
-	    }
 
-	    switch (internalFormat) {
-		case GL_RGBA8:
-		case GL_RG8:
-		case GL_R8:
-		    glTexImage2D (
-			GL_TEXTURE_2D, level, internalFormat, width, height, 0, textureFormat, GL_UNSIGNED_BYTE, dataptr
-		    );
-		    break;
-		case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
-		case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
-		case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
-		    glCompressedTexImage2D (
-			GL_TEXTURE_2D, level, internalFormat, width, height, 0, bufferSize, dataptr
-		    );
-		    break;
-		default:
-		    sLog.exception ("Cannot load texture, unknown format", this->m_header->format);
+		glTexImage2D (
+		    GL_TEXTURE_2D, level, upload.internalFormat, width, height, 0, upload.format, upload.type, dataptr
+		);
 	    }
 
 	    if (handle != nullptr) {
@@ -134,6 +199,22 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
 	    level++;
 	}
     }
+
+    glPixelStorei (GL_UNPACK_ALIGNMENT, previousAlignment);
+}
+
+bool CTexture::repaint (TextureUniquePtr header) {
+    const auto& current = *this->m_header;
+
+    if (this->m_player || this->m_gif || header->imageCount != current.imageCount || header->format != current.format
+	|| header->textureWidth != current.textureWidth || header->textureHeight != current.textureHeight
+	|| header->freeImageFormat != current.freeImageFormat) {
+	return false;
+    }
+
+    this->m_header = std::move (header);
+    this->uploadImages (this->uploadFormat ());
+    return true;
 }
 
 void CTexture::label (const std::string& name) const {
@@ -173,27 +254,55 @@ void CTexture::setupResolution () {
     }
 }
 
-GLint CTexture::setupInternalFormat () const {
+// WE uploads the raw mips as their DXGI format (sub_1400D2A20, sub_1400EB090): RGB888/RGB565 are RGBA8, RGB161616f
+// RGBA16F, unknown RGBA8
+CTexture::UploadFormat CTexture::uploadFormat () const {
     if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
-	return GL_RGBA8;
+	return { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, 4, false };
     }
 
     switch (this->m_header->format) {
 	case TextureFormat_DXT5:
-	    return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
+	    return { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_NONE, GL_NONE, 0, true };
 	case TextureFormat_DXT3:
-	    return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
+	    return { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_NONE, GL_NONE, 0, true };
 	case TextureFormat_DXT1:
-	    return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
-	case TextureFormat_ARGB8888:
-	    return GL_RGBA8;
-	case TextureFormat_R8:
-	    return GL_R8;
+	    return { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_NONE, GL_NONE, 0, true };
+	case TextureFormat_BC7:
+	    return { GL_COMPRESSED_RGBA_BPTC_UNORM, GL_NONE, GL_NONE, 0, true };
 	case TextureFormat_RG88:
-	    return GL_RG8;
+	    return { GL_RG8, GL_RG, GL_UNSIGNED_BYTE, 2, false };
+	case TextureFormat_R8:
+	    return { GL_R8, GL_RED, GL_UNSIGNED_BYTE, 1, false };
+	case TextureFormat_RG1616f:
+	    return { GL_RG16F, GL_RG, GL_HALF_FLOAT, 4, false };
+	case TextureFormat_R16f:
+	    return { GL_R16F, GL_RED, GL_HALF_FLOAT, 2, false };
+	case TextureFormat_RGBa1010102:
+	    return { GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, 4, false };
+	case TextureFormat_RGBA16161616f:
+	case TextureFormat_RGB161616f:
+	    return { GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 8, false };
+	case TextureFormat_R32f:
+	    return { GL_R32F, GL_RED, GL_FLOAT, 4, false };
+	case TextureFormat_RGBA16161616:
+	case TextureFormat_RGB161616:
+	    return { GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT, 8, false };
+	case TextureFormat_RGBA16161616S:
+	case TextureFormat_RGB161616S:
+	    return { GL_RGBA16_SNORM, GL_RGBA, GL_SHORT, 8, false };
 	default:
-	    sLog.exception ("Cannot determine texture format");
+	    break;
     }
+
+    // depth, typeless R32 and unknown formats can't be sampled in D3D
+    if (this->m_header->format >= 22 && this->m_header->format <= 27) {
+	sLog.exception (
+	    "Cannot load texture, format ", static_cast<uint32_t> (this->m_header->format), " is not sampleable"
+	);
+    }
+
+    return { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, 4, false };
 }
 
 void CTexture::setupOpenGLParameters (const uint32_t textureID) const {

+ 12 - 1
src/WallpaperEngine/Render/CTexture.h

@@ -47,13 +47,24 @@ public:
     [[nodiscard]] GLPlayer* getPlayer () const override { return this->m_player.get (); }
     /** Debug label for every image of the texture, shows up in renderdoc/apitrace */
     void label (const std::string& name) const;
+    /** Uploads a new parse of the same file (TEXB0004 patches), false if it doesn't fit the existing textures */
+    bool repaint (TextureUniquePtr header);
 
 private:
+    struct UploadFormat {
+	GLint internalFormat;
+	GLenum format;
+	GLenum type;
+	uint32_t bytesPerPixel;
+	bool compressed;
+    };
+
     [[nodiscard]] const Texture& getHeader () const;
 
     void setupResolution ();
-    GLint setupInternalFormat () const;
+    [[nodiscard]] UploadFormat uploadFormat () const;
     void setupOpenGLParameters (uint32_t textureID) const;
+    void uploadImages (const UploadFormat& upload) const;
 
     TextureUniquePtr m_header;
     GLuint* m_textureID = nullptr;

+ 106 - 6
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -6,6 +6,7 @@
 #include "ImageDecoder.h"
 
 #include "CWallpaper.h"
+#include "FrameMaterial.h"
 #include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Data/Parsers/TextureParser.h"
 #include "WallpaperEngine/Data/Utils/BinaryReader.h"
@@ -56,6 +57,11 @@ CWallpaper::CWallpaper (
 }
 
 CWallpaper::~CWallpaper () {
+    if (this->m_backBuffer.texture != GL_NONE) {
+	glDeleteFramebuffers (1, &this->m_backBuffer.framebuffer);
+	glDeleteTextures (1, &this->m_backBuffer.texture);
+    }
+
     // programs here only ever have 2 shaders attached (vertex + fragment)
     GLuint attachedShaders[2];
     GLsizei attachedCount = 0;
@@ -85,9 +91,88 @@ const AssetLocator& CWallpaper::getAssetLocator () const { return *this->m_wallp
 
 const Wallpaper& CWallpaper::getWallpaperData () const { return this->m_wallpaperData; }
 
-GLuint CWallpaper::getWallpaperFramebuffer () const { return this->m_sceneFBO->getFramebuffer (); }
+GLuint CWallpaper::getWallpaperFramebuffer () const {
+    return this->m_presentBackBuffer ? this->m_backBuffer.framebuffer : this->m_sceneFBO->getFramebuffer ();
+}
+
+GLuint CWallpaper::getWallpaperTexture () const {
+    return this->m_presentBackBuffer ? this->m_backBuffer.texture : this->m_sceneFBO->getTextureID (0);
+}
+
+void CWallpaper::prepareBackBuffer (const glm::ivec2& size, const GLenum format) {
+    auto& back = this->m_backBuffer;
+
+    if (back.size == size && back.format == format) {
+	return;
+    }
+
+    if (back.texture == GL_NONE) {
+	glGenTextures (1, &back.texture);
+	glGenFramebuffers (1, &back.framebuffer);
+    }
+
+    glBindTexture (GL_TEXTURE_2D, back.texture);
+    glTexImage2D (GL_TEXTURE_2D, 0, format, size.x, size.y, 0, GL_RGBA, GL_FLOAT, nullptr);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+    glBindFramebuffer (GL_FRAMEBUFFER, back.framebuffer);
+    glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, back.texture, 0);
+#if !NDEBUG
+    glObjectLabel (GL_TEXTURE, back.texture, -1, "back buffer");
+#endif
+    back.size = size;
+    back.format = format;
+}
+
+void CWallpaper::renderImageAdjustments (const glm::ivec2& size, const GLenum format) {
+    // sub_140181F30: COL when the color options moved, LUT for a filter above 0, otherwise no material
+    const bool color = this->m_colorEnabled;
+    const bool lut = this->m_lutTexture != GL_NONE && this->m_lutStrength > 0.0f;
 
-GLuint CWallpaper::getWallpaperTexture () const { return this->m_sceneFBO->getTextureID (0); }
+    if (!color && !lut) {
+	this->m_imageAdjustmentsMaterial = nullptr;
+	return;
+    }
+
+    if (this->m_imageAdjustmentsMaterial == nullptr || this->m_imageAdjustmentsCombos != std::pair (color, lut)) {
+	ComboMap combos;
+
+	if (color) {
+	    combos.emplace ("COL", 1);
+	}
+
+	combos.emplace ("LUT", lut ? 1 : 0);
+	this->m_imageAdjustmentsMaterial = std::make_unique<FrameMaterial> (
+	    *this, this->m_wallpaperData.project, "materials/util/ccsimple.json", combos
+	);
+	this->m_imageAdjustmentsCombos = { color, lut };
+    }
+
+    FrameMaterial& material = *this->m_imageAdjustmentsMaterial;
+
+    if (color) {
+	material.setConstant ("params", this->m_colorParams);
+    }
+
+    if (lut) {
+	material.setTexture (1, this->m_lutTexture, GL_TEXTURE_3D);
+	material.setConstant ("lutparams", this->m_lutStrength);
+    }
+
+    // sub_14017FA70 copies the back buffer into _rt_FullFrameBuffer first
+    this->prepareBackBuffer (size, format);
+
+    if (this->m_presentBackBuffer) {
+	glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_backBuffer.framebuffer);
+	glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
+	glBlitFramebuffer (0, 0, size.x, size.y, 0, 0, size.x, size.y, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+    }
+
+    material.draw (this->m_backBuffer.framebuffer, this->m_backBuffer.size);
+    this->m_presentBackBuffer = true;
+}
 
 void CWallpaper::setupShaders () {
     const GLuint vertexShaderID = glCreateShader (GL_VERTEX_SHADER);
@@ -133,6 +218,7 @@ void CWallpaper::setupShaders () {
 	  "uniform bool u_ColorEnabled;\n"
 	  "uniform bool u_LutEnabled;\n"
 	  "uniform bool u_InputLinear;\n"
+	  "uniform bool u_InputScRGB;\n"
 	  "uniform bool u_OutputPQ;\n"
 	  "uniform int u_Supersample;\n"
 	  "in vec2 v_TexCoord;\n"
@@ -188,6 +274,10 @@ void CWallpaper::setupShaders () {
 	  "} else {\n"
 	  "albedo = texture (g_Texture0, v_TexCoord);\n"
 	  "}\n"
+	  // HDR outputs take it linear, SDR gets it clipped and encoded
+	  "if (u_InputScRGB) {\n"
+	  "albedo.rgb = u_OutputPQ ? bt709to2020 * albedo.rgb : linearToSrgb (clamp (albedo.rgb, 0.0, 1.0));\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
@@ -268,6 +358,7 @@ void CWallpaper::setupShaders () {
     this->u_ColorEnabled = glGetUniformLocation (this->m_shader, "u_ColorEnabled");
     this->u_LutEnabled = glGetUniformLocation (this->m_shader, "u_LutEnabled");
     this->u_InputLinear = glGetUniformLocation (this->m_shader, "u_InputLinear");
+    this->u_InputScRGB = glGetUniformLocation (this->m_shader, "u_InputScRGB");
     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");
@@ -331,6 +422,13 @@ void CWallpaper::render (
     }
 #if !NDEBUG
     glPopDebugGroup ();
+#endif /* !NDEBUG */
+
+    this->present (viewport, globalPosition, logicalSize);
+}
+
+void CWallpaper::present (const glm::ivec4& viewport, const glm::ivec2& globalPosition, const glm::ivec2& logicalSize) {
+#if !NDEBUG
     glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, "Rendering scene to output");
 #endif /* !NDEBUG */
 
@@ -494,11 +592,13 @@ void CWallpaper::drawOutputQuad (const int supersample) {
     // a sampler2D and a sampler3D on the same unit is an invalid draw even when the LUT is never read
     glUniform1i (this->g_Texture1, 1);
 
-    const bool lutEnabled = this->m_lutTexture != GL_NONE && this->m_lutStrength > 0.0f;
+    const bool adjusted = !this->drawsImageAdjustments ();
+    const bool lutEnabled = adjusted && this->m_lutTexture != GL_NONE && this->m_lutStrength > 0.0f;
 
-    glUniform1i (this->u_ColorEnabled, this->m_colorEnabled);
+    glUniform1i (this->u_ColorEnabled, adjusted && this->m_colorEnabled);
     glUniform1i (this->u_LutEnabled, lutEnabled);
-    glUniform1i (this->u_InputLinear, this->m_linearInput);
+    glUniform1i (this->u_InputLinear, this->m_linearInput || (this->m_scRGBInput && this->m_outputHDR));
+    glUniform1i (this->u_InputScRGB, this->m_scRGBInput);
     glUniform1i (this->u_OutputPQ, this->m_outputHDR);
     glUniform1i (this->u_Supersample, supersample);
     glUniform4fv (this->g_Params, 1, &this->m_colorParams.x);
@@ -580,7 +680,7 @@ bool CWallpaper::hasImageAdjustments () const {
 
 GLuint CWallpaper::renderAdjustedFramebuffer () {
     // a linear (HDR video) framebuffer needs encoding to sRGB even without adjustments
-    if (!this->hasImageAdjustments () && !this->m_linearInput) {
+    if (!this->hasImageAdjustments () && !this->m_linearInput && !this->m_scRGBInput) {
 	return this->getWallpaperFramebuffer ();
     }
 

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

@@ -24,6 +24,8 @@ class WallpaperApplication;
 }
 
 namespace WallpaperEngine::Render {
+class FrameMaterial;
+
 namespace Helpers {
     class ContextAware;
 }
@@ -50,6 +52,15 @@ public:
 	const glm::ivec2& logicalSize = { 0, 0 }
     );
 
+    /** Draws the last frame again */
+    void present (
+	const glm::ivec4& viewport, const glm::ivec2& globalPosition = { 0, 0 },
+	const glm::ivec2& logicalSize = { 0, 0 }
+    );
+
+    /** False until a web page painted, the previous wallpaper stays on screen meanwhile */
+    [[nodiscard]] virtual bool hasContent () const { return true; }
+
     virtual void setPause (bool newState);
 
     /**
@@ -151,6 +162,30 @@ protected:
     void setupFramebuffers (bool depth = false, TextureFormat format = TextureFormat_ARGB8888);
     /** The framebuffer holds linear light with BT.2020 primaries, 1.0 being reference white (HDR video) */
     void setLinearInput (bool linear) { this->m_linearInput = linear; }
+    /** FP16 scRGB like WE's HDR swapchain, clipped and sRGB encoded on SDR outputs */
+    void setScRGBInput (bool scRGB) { this->m_scRGBInput = scRGB; }
+    /** Draws the image adjustments itself with ccsimple.json */
+    [[nodiscard]] virtual bool drawsImageAdjustments () const { return false; }
+    /** RGBA8 or RGBA16F like WE's swapchain (sub_14012AC60) */
+    void prepareBackBuffer (const glm::ivec2& size, GLenum format);
+    /** ccsimple.json color options and image filter (sub_140181F30) */
+    void renderImageAdjustments (const glm::ivec2& size, GLenum format);
+
+    struct BackBuffer {
+	GLuint texture = GL_NONE;
+	GLuint framebuffer = GL_NONE;
+	glm::ivec2 size {};
+	GLenum format = GL_NONE;
+    };
+    BackBuffer m_backBuffer;
+    bool m_presentBackBuffer = false;
+    /** WE's COL combo (sub_140181F30) */
+    [[nodiscard]] bool isColorEnabled () const { return this->m_colorEnabled; }
+    /** brightness, contrast, saturation, hue */
+    [[nodiscard]] const glm::vec4& getColorParams () const { return this->m_colorParams; }
+    [[nodiscard]] GLuint getLutTexture () const { return this->m_lutTexture; }
+    /** wcc_amt / 100 */
+    [[nodiscard]] float getLutStrength () const { return this->m_lutStrength; }
 
     const Wallpaper& m_wallpaperData;
 
@@ -190,6 +225,8 @@ private:
     float m_lutStrength = 0.0f;
     std::string m_lutName;
     GLuint m_lutTexture = GL_NONE;
+    std::unique_ptr<FrameMaterial> m_imageAdjustmentsMaterial;
+    std::pair<bool, bool> m_imageAdjustmentsCombos { false, false };
     /** --clamp and --corner-color, only for drawing the frame to the output */
     GLuint m_outputSampler = GL_NONE;
     std::unique_ptr<CFBO> m_adjustedFBO;
@@ -197,7 +234,9 @@ private:
     bool m_outputHDR = false;
     glm::vec2 m_outputLuminance = glm::vec2 (0.0f);
     bool m_linearInput = false;
+    bool m_scRGBInput = false;
     GLint u_InputLinear = GL_NONE;
+    GLint u_InputScRGB = GL_NONE;
     GLint u_OutputPQ = GL_NONE;
     GLint u_Supersample = GL_NONE;
     void loadLut (const std::string& name);

+ 1 - 2
src/WallpaperEngine/Render/Camera.h

@@ -27,8 +27,7 @@ public:
      */
     void setOrthogonalProjection (float width, float height, float canvasWidth = 0.0f, float canvasHeight = 0.0f);
     /**
-     * 3D scenes: the scene camera becomes a perspective one (getPerspective/getView), getProjection and
-     * getLookAt turn into a plain screen space camera for the 2D layers (fullscreen post processing, bloom)
+     * 3D scenes: the scene camera becomes perspective, getProjection/getLookAt stay a screen space camera for 2D layers
      */
     void setPerspectiveProjection (float width, float height);
 

+ 31 - 0
src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp

@@ -10,6 +10,7 @@
 #include <cstring>
 #include <filesystem>
 #include <fstream>
+#include <sstream>
 #include <string>
 #include <vector>
 
@@ -77,6 +78,36 @@ HeadlessOpenGLDriver::FixedMouse::FixedMouse (const HeadlessOpenGLDriver& driver
     if (cursor != nullptr && std::sscanf (cursor, "%lf,%lf", &m_fraction.x, &m_fraction.y) != 2) {
 	m_fraction = glm::dvec2 (0.5);
     }
+
+    const char* path = std::getenv ("LWE_HEADLESS_CURSOR_PATH");
+    std::istringstream steps (path != nullptr ? path : "");
+    std::string text;
+
+    while (std::getline (steps, text, ';')) {
+	Step step {};
+	char button = 0;
+	const int fields
+	    = std::sscanf (text.c_str (), "%lf:%lf,%lf,%c", &step.time, &step.fraction.x, &step.fraction.y, &button);
+
+	if (fields >= 3) {
+	    step.down = fields == 4 && button == 'd';
+	    m_path.push_back (step);
+	}
+    }
+}
+
+void HeadlessOpenGLDriver::FixedMouse::update () {
+    const double elapsed
+	= std::chrono::duration<double> (std::chrono::steady_clock::now () - m_driver.m_started).count ();
+
+    for (const auto& step : m_path) {
+	if (step.time > elapsed) {
+	    break;
+	}
+
+	m_fraction = step.fraction;
+	m_down = step.down;
+    }
 }
 
 HeadlessOpenGLDriver::HeadlessOpenGLDriver (ApplicationContext& context, WallpaperApplication& app) :

+ 15 - 4
src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.h

@@ -8,6 +8,7 @@
 #include <EGL/egl.h>
 #include <GL/glew.h>
 #include <chrono>
+#include <vector>
 
 namespace WallpaperEngine::Render::Drivers {
 using namespace WallpaperEngine::Application;
@@ -40,16 +41,26 @@ private:
     public:
 	explicit FixedMouse (const HeadlessOpenGLDriver& driver);
 
-	void update () override { }
-	// the middle of the output (where the pointer of a fresh Xvfb display sits too), or LWE_HEADLESS_CURSOR=x,y
-	// as fractions of the output
+	void update () override;
+	// output center, or LWE_HEADLESS_CURSOR=x,y as fractions. LWE_HEADLESS_CURSOR_PATH="seconds:x,y[,d];..." moves
+	// it over time, d holds the left button
 	[[nodiscard]] glm::dvec2 position () const override { return glm::dvec2 (m_driver.m_size) * m_fraction; }
-	[[nodiscard]] Input::MouseClickStatus leftClick () const override { return Input::Released; }
+	[[nodiscard]] Input::MouseClickStatus leftClick () const override {
+	    return m_down ? Input::Clicked : Input::Released;
+	}
 	[[nodiscard]] Input::MouseClickStatus rightClick () const override { return Input::Released; }
 
     private:
+	struct Step {
+	    double time;
+	    glm::dvec2 fraction;
+	    bool down;
+	};
+
 	const HeadlessOpenGLDriver& m_driver;
 	glm::dvec2 m_fraction = glm::dvec2 (0.5);
+	bool m_down = false;
+	std::vector<Step> m_path;
     };
 
     void createSurface ();

+ 36 - 12
src/WallpaperEngine/Render/FBOProvider.cpp

@@ -8,24 +8,44 @@ using namespace WallpaperEngine::Render;
 using namespace WallpaperEngine::Data::Model;
 
 namespace {
-// same names and fallback as wallpaper64.exe's lookup table (sub_140172ED0). the backbuffer formats
-// only switch to half floats in HDR scenes, which aren't supported here, so they stay 8-bit
-TextureFormat parseFormat (std::string name) {
+// sub_1401E7170: backbuffer names (any case) are the scene's format, the rest go through sub_1401E53A0's table,
+// unknown names are RGBA8
+TextureFormat parseFormat (const std::string& name, const bool hdr) {
     static const std::map<std::string, TextureFormat> formats = {
 	{ "rgba8888", TextureFormat_ARGB8888 },
-	{ "rgba_backbuffer", TextureFormat_ARGB8888 },
 	{ "rgb888", TextureFormat_RGB888 },
-	{ "rgb_backbuffer", TextureFormat_RGB888 },
-	{ "rgb565", TextureFormat_RGB565 },
 	{ "rg88", TextureFormat_RG88 },
 	{ "r8", TextureFormat_R8 },
-	{ "rg1616f", TextureFormat_RG1616f },
-	{ "r16f", TextureFormat_R16f },
+	{ "rgb565", TextureFormat_RGB565 },
+	{ "bc7", TextureFormat_BC7 },
+	{ "dxt5", TextureFormat_DXT5 },
+	{ "dxt3", TextureFormat_DXT3 },
+	{ "dxt1", TextureFormat_DXT1 },
 	{ "rgba16161616f", TextureFormat_RGBA16161616f },
 	{ "rgb161616f", TextureFormat_RGB161616f },
+	{ "rg1616f", TextureFormat_RG1616f },
+	{ "r16f", TextureFormat_R16f },
+	{ "rgba16161616", TextureFormat_RGBA16161616 },
+	{ "rgb161616", TextureFormat_RGB161616 },
+	{ "rgba16161616S", TextureFormat_RGBA16161616S },
+	{ "rgb161616S", TextureFormat_RGB161616S },
+	{ "rgba8888s", TextureFormat_RGBA8888S },
+	{ "rgba1010102", TextureFormat_RGBa1010102 },
     };
 
-    std::ranges::transform (name, name.begin (), [] (const unsigned char c) { return std::tolower (c); });
+    const auto equalsIgnoringCase = [&name] (const std::string_view other) {
+	return std::ranges::equal (name, other, [] (const unsigned char a, const unsigned char b) {
+	    return std::tolower (a) == std::tolower (b);
+	});
+    };
+
+    if (equalsIgnoringCase ("rgba_backbuffer")) {
+	return hdr ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
+    }
+
+    if (equalsIgnoringCase ("rgb_backbuffer")) {
+	return hdr ? TextureFormat_RGB161616f : TextureFormat_RGB888;
+    }
 
     const auto it = formats.find (name);
     return it != formats.end () ? it->second : TextureFormat_ARGB8888;
@@ -34,10 +54,14 @@ TextureFormat parseFormat (std::string name) {
 
 FBOProvider::FBOProvider (const FBOProvider* parent) : m_parent (parent) { }
 
-std::shared_ptr<CFBO> FBOProvider::create (const FBO& base, uint32_t flags, const glm::vec2 size) {
+std::shared_ptr<CFBO> FBOProvider::create (const FBO& base, const glm::vec2 objectSize, const bool hdr) {
+    // clamped unless uvs is "repeat" (sub_1401EA500)
+    const uint32_t flags = base.repeat ? TextureFlags_NoFlags : TextureFlags_ClampUVs;
+    const glm::uvec2 size = base.bufferSize (objectSize);
+
     return this->m_fbos[base.name] = std::make_shared<CFBO> (
-	       base.name, parseFormat (base.format), flags, base.scale, size.x / base.scale, size.y / base.scale,
-	       size.x / base.scale, size.y / base.scale
+	       base.name, parseFormat (base.format, hdr), flags, std::max (base.scale, 1.0f), size.x, size.y, size.x,
+	       size.y
 	   );
 }
 

+ 2 - 1
src/WallpaperEngine/Render/FBOProvider.h

@@ -13,7 +13,8 @@ class FBOProvider {
 public:
     explicit FBOProvider (const FBOProvider* parent);
 
-    std::shared_ptr<CFBO> create (const FBO& base, uint32_t flags, glm::vec2 size);
+    /** An effect.json buffer for an object of the given size (sub_1401EA500) */
+    std::shared_ptr<CFBO> create (const FBO& base, glm::vec2 objectSize, bool hdr);
     std::shared_ptr<CFBO> create (
 	const std::string& name, TextureFormat format, uint32_t flags, float scale, glm::vec2 realSize,
 	glm::vec2 textureSize, const glm::vec4& borderColor = { 0.0f, 0.0f, 0.0f, 1.0f }, uint32_t mipLevels = 1

+ 328 - 0
src/WallpaperEngine/Render/FrameMaterial.cpp

@@ -0,0 +1,328 @@
+#include "FrameMaterial.h"
+
+#include "WallpaperEngine/Data/Parsers/MaterialParser.h"
+#include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/CFBO.h"
+#include "WallpaperEngine/Render/Shaders/GLSLContext.h"
+#include "WallpaperEngine/Render/Wallpapers/CScene.h"
+
+using namespace WallpaperEngine::Render;
+using namespace WallpaperEngine::Data::Model;
+
+namespace {
+// x, y, z, u, v strip of WE's fullscreen quad, v up
+constexpr float kQuad[] = {
+    -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,
+};
+
+GLuint compile (const std::string& source, const GLenum type, const std::string& name) {
+    const GLuint shader = glCreateShader (type);
+    const char* text = source.c_str ();
+    glShaderSource (shader, 1, &text, nullptr);
+    glCompileShader (shader);
+
+    GLint compiled = GL_FALSE;
+    glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled);
+
+    if (compiled == GL_FALSE) {
+	char log[2048] = {};
+	glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
+	sLog.error ("Frame material ", name, " failed to compile: ", log);
+    }
+
+    return shader;
+}
+} // namespace
+
+FrameMaterial::FrameMaterial (
+    const CWallpaper& owner, const Project& project, const std::string& file, const ComboMap& combos
+) : m_owner (owner), m_file (file) {
+    this->m_material = Data::Parsers::MaterialParser::load (project, file);
+
+    if (this->m_material == nullptr || this->m_material->passes.empty ()) {
+	sLog.error ("Frame material ", file, " could not be loaded");
+	return;
+    }
+
+    this->m_pass = this->m_material->passes.front ().get ();
+    this->m_combos = this->m_pass->combos;
+
+    for (const auto& [name, value] : combos) {
+	this->m_combos.insert_or_assign (name, value);
+    }
+
+    // scene wide defines (sub_1401A5C40)
+    if (const auto* scene = owner.is<Wallpapers::CScene> () ? owner.as<Wallpapers::CScene> () : nullptr) {
+	if (scene->getCamera ().isOrthogonal ()) {
+	    this->m_combos.insert_or_assign ("SCENE_ORTHO", 1);
+	}
+
+	if (scene->isHDR ()) {
+	    this->m_combos.insert_or_assign ("HDR", 1);
+	}
+    }
+
+    static const ShaderConstantMap noConstants;
+
+    try {
+	this->m_shader = std::make_unique<Shaders::Shader> (
+	    *project.assetLocator, this->m_pass->shader, this->m_combos, this->m_overrideCombos, this->m_pass->textures,
+	    this->m_noTextures, noConstants
+	);
+	const auto sources = Shaders::GLSLContext::get ().toGlsl (
+	    this->m_shader->vertex (), this->m_shader->fragment (), this->m_pass->shader
+	);
+	this->link (sources.vertex, sources.fragment, this->m_pass->shader);
+    } catch (const std::exception& e) {
+	sLog.error ("Frame material ", file, " has no usable shader: ", e.what ());
+	this->m_shader = nullptr;
+	return;
+    }
+
+    for (const auto* unit : { &this->m_shader->getVertex (), &this->m_shader->getFragment () }) {
+	for (const auto* parameter : unit->getParameters ()) {
+	    switch (parameter->getType ()) {
+		case DynamicValue::Float:
+		    this->setValue (parameter->getName (), glm::vec4 (parameter->getFloat ()), 1);
+		    break;
+		case DynamicValue::Vec2:
+		    this->setValue (parameter->getName (), glm::vec4 (parameter->getVec2 (), 0.0f, 0.0f), 2);
+		    break;
+		case DynamicValue::Vec3:
+		    this->setValue (parameter->getName (), glm::vec4 (parameter->getVec3 (), 0.0f), 3);
+		    break;
+		case DynamicValue::Vec4:
+		    this->setValue (parameter->getName (), parameter->getVec4 (), 4);
+		    break;
+		default:
+		    break;
+	    }
+	}
+    }
+
+    for (const auto& [name, setting] : this->m_pass->constants) {
+	const auto& value = *setting->value;
+
+	switch (value.getType ()) {
+	    case DynamicValue::Float:
+		this->setConstant (name, value.getFloat ());
+		break;
+	    case DynamicValue::Vec3:
+		this->setConstant (name, value.getVec3 ());
+		break;
+	    case DynamicValue::Vec4:
+		this->setConstant (name, value.getVec4 ());
+		break;
+	    default:
+		break;
+	}
+    }
+
+    GLint previousVao = 0;
+    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVao);
+    glGenVertexArrays (1, &this->m_vao);
+    glBindVertexArray (this->m_vao);
+    glGenBuffers (1, &this->m_vertices);
+    glBindBuffer (GL_ARRAY_BUFFER, this->m_vertices);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (kQuad), kQuad, GL_STATIC_DRAW);
+
+    if (this->a_Position != -1) {
+	glEnableVertexAttribArray (this->a_Position);
+	glVertexAttribPointer (this->a_Position, 3, GL_FLOAT, GL_FALSE, 5 * sizeof (float), nullptr);
+    }
+
+    if (this->a_TexCoord != -1) {
+	glEnableVertexAttribArray (this->a_TexCoord);
+	glVertexAttribPointer (
+	    this->a_TexCoord, 2, GL_FLOAT, GL_FALSE, 5 * sizeof (float), reinterpret_cast<void*> (3 * sizeof (float))
+	);
+    }
+
+    glBindVertexArray (previousVao);
+}
+
+FrameMaterial::~FrameMaterial () {
+    if (this->m_program != GL_NONE) {
+	glDeleteProgram (this->m_program);
+    }
+
+    if (this->m_vertices != GL_NONE) {
+	glDeleteBuffers (1, &this->m_vertices);
+    }
+
+    if (this->m_vao != GL_NONE) {
+	glDeleteVertexArrays (1, &this->m_vao);
+    }
+}
+
+void FrameMaterial::link (const std::string& vertex, const std::string& fragment, const std::string& name) {
+    const GLuint vertexShader = compile (vertex, GL_VERTEX_SHADER, name);
+    const GLuint fragmentShader = compile (fragment, GL_FRAGMENT_SHADER, name);
+    this->m_program = glCreateProgram ();
+    glAttachShader (this->m_program, vertexShader);
+    glAttachShader (this->m_program, fragmentShader);
+    glLinkProgram (this->m_program);
+    glDeleteShader (vertexShader);
+    glDeleteShader (fragmentShader);
+
+    GLint linked = GL_FALSE;
+    glGetProgramiv (this->m_program, GL_LINK_STATUS, &linked);
+
+    if (linked == GL_FALSE) {
+	char log[2048] = {};
+	glGetProgramInfoLog (this->m_program, sizeof (log) - 1, nullptr, log);
+	sLog.error ("Frame material ", name, " failed to link: ", log);
+	glDeleteProgram (this->m_program);
+	this->m_program = GL_NONE;
+	return;
+    }
+
+#if !NDEBUG
+    glObjectLabel (GL_PROGRAM, this->m_program, -1, this->m_file.c_str ());
+#endif
+
+    this->a_Position = glGetAttribLocation (this->m_program, "a_Position");
+    this->a_TexCoord = glGetAttribLocation (this->m_program, "a_TexCoord");
+
+    // translated GLSL collapses sampler bindings to 0
+    glUseProgram (this->m_program);
+
+    for (int index = 0; index <= 9; index++) {
+	const std::string sampler = "g_Texture" + std::to_string (index);
+
+	if (const GLint location = glGetUniformLocation (this->m_program, sampler.c_str ()); location != -1) {
+	    glUniform1i (location, index);
+	}
+    }
+}
+
+std::string FrameMaterial::uniformOf (const std::string& constant) const {
+    if (this->m_shader == nullptr) {
+	return {};
+    }
+
+    for (const auto* unit : { &this->m_shader->getFragment (), &this->m_shader->getVertex () }) {
+	for (const auto* parameter : unit->getParameters ()) {
+	    if (parameter->getIdentifierName () == constant) {
+		return parameter->getName ();
+	    }
+	}
+    }
+
+    return {};
+}
+
+void FrameMaterial::setValue (const std::string& uniform, const glm::vec4& value, const int components) {
+    if (uniform.empty ()) {
+	return;
+    }
+
+    this->m_values.insert_or_assign (uniform, Value { .value = value, .components = components });
+}
+
+void FrameMaterial::setTexture (const int index, const GLuint texture, const GLenum target) {
+    this->m_textures.insert_or_assign (index, Texture { .texture = texture, .target = target });
+}
+
+void FrameMaterial::setConstant (const std::string& name, const float value) {
+    this->setValue (this->uniformOf (name), glm::vec4 (value), 1);
+}
+
+void FrameMaterial::setConstant (const std::string& name, const glm::vec3& value) {
+    this->setValue (this->uniformOf (name), glm::vec4 (value, 0.0f), 3);
+}
+
+void FrameMaterial::setConstant (const std::string& name, const glm::vec4& value) {
+    this->setValue (this->uniformOf (name), value, 4);
+}
+
+void FrameMaterial::setUniform (const std::string& name, const float value) {
+    this->setValue (name, glm::vec4 (value), 1);
+}
+
+void FrameMaterial::setUniform (const std::string& name, const glm::vec2& value) {
+    this->setValue (name, glm::vec4 (value, 0.0f, 0.0f), 2);
+}
+
+void FrameMaterial::setUniform (const std::string& name, const glm::vec4& value) { this->setValue (name, value, 4); }
+
+void FrameMaterial::draw (const CFBO& target) const {
+    this->draw (target.getFramebuffer (), { target.getRealWidth (), target.getRealHeight () });
+}
+
+void FrameMaterial::draw (const GLuint framebuffer, const glm::ivec2& size) const {
+    if (this->m_program == GL_NONE) {
+	return;
+    }
+
+    glBindFramebuffer (GL_FRAMEBUFFER, framebuffer);
+    glViewport (0, 0, size.x, size.y);
+    glUseProgram (this->m_program);
+
+    // util materials: no cull, no depth; additive (bloom), translucent (fade), else replace
+    glDisable (GL_DEPTH_TEST);
+    glDepthMask (GL_FALSE);
+    glDisable (GL_CULL_FACE);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+
+    if (this->m_pass->blending == BlendingMode_Additive) {
+	glEnable (GL_BLEND);
+	glBlendFunc (GL_ONE, GL_ONE);
+    } else if (this->m_pass->blending == BlendingMode_Translucent) {
+	glEnable (GL_BLEND);
+	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+    } else {
+	glDisable (GL_BLEND);
+    }
+
+    for (const auto& [uniform, value] : this->m_values) {
+	const GLint location = glGetUniformLocation (this->m_program, uniform.c_str ());
+
+	if (location == -1) {
+	    continue;
+	}
+
+	switch (value.components) {
+	    case 1:
+		glUniform1f (location, value.value.x);
+		break;
+	    case 2:
+		glUniform2fv (location, 1, &value.value.x);
+		break;
+	    case 3:
+		glUniform3fv (location, 1, &value.value.x);
+		break;
+	    default:
+		glUniform4fv (location, 1, &value.value.x);
+		break;
+	}
+    }
+
+    // slot overrides first, then the render target the material names
+    std::map<int, Texture> textures = this->m_textures;
+
+    for (const auto& [index, name] : this->m_pass->textures) {
+	if (textures.contains (index)) {
+	    continue;
+	}
+
+	if (const auto fbo = this->m_owner.find (name); fbo != nullptr) {
+	    textures.emplace (index, Texture { .texture = fbo->getTextureID (0) });
+	}
+    }
+
+    for (const auto& [index, texture] : textures) {
+	glActiveTexture (GL_TEXTURE0 + index);
+	glBindTexture (texture.target, texture.texture);
+    }
+
+    glActiveTexture (GL_TEXTURE0);
+
+    GLint previousVao = 0;
+    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVao);
+    glBindVertexArray (this->m_vao);
+    glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
+    glBindVertexArray (previousVao);
+    glDisable (GL_BLEND);
+}

+ 79 - 0
src/WallpaperEngine/Render/FrameMaterial.h

@@ -0,0 +1,79 @@
+#pragma once
+
+#include <GL/glew.h>
+#include <glm/glm.hpp>
+#include <map>
+#include <memory>
+#include <string>
+
+#include "WallpaperEngine/Data/Model/Material.h"
+#include "WallpaperEngine/Render/Shaders/Shader.h"
+
+namespace WallpaperEngine::Data::Model {
+struct Project;
+}
+
+namespace WallpaperEngine::Render {
+class CFBO;
+class CWallpaper;
+
+/** A util material drawn over a whole target (bloom, combine; sub_14017FA70, sub_140183610), first pass only */
+class FrameMaterial {
+public:
+    /** on top of the material's own (sub_140150110) */
+    FrameMaterial (
+	const CWallpaper& owner, const Data::Model::Project& project, const std::string& file,
+	const Data::Model::ComboMap& combos = {}
+    );
+    ~FrameMaterial ();
+
+    FrameMaterial (const FrameMaterial&) = delete;
+    FrameMaterial& operator= (const FrameMaterial&) = delete;
+
+    /** material +208/+216 overrides */
+    void setTexture (int index, GLuint texture, GLenum target = GL_TEXTURE_2D);
+    /** by material name (sub_14017E920) */
+    void setConstant (const std::string& name, float value);
+    void setConstant (const std::string& name, const glm::vec3& value);
+    void setConstant (const std::string& name, const glm::vec4& value);
+    /** by shader name */
+    void setUniform (const std::string& name, float value);
+    void setUniform (const std::string& name, const glm::vec2& value);
+    void setUniform (const std::string& name, const glm::vec4& value);
+
+    void draw (GLuint framebuffer, const glm::ivec2& size) const;
+    void draw (const CFBO& target) const;
+
+private:
+    struct Value {
+	glm::vec4 value { 0.0f };
+	int components = 1;
+	bool integer = false;
+    };
+
+    void link (const std::string& vertex, const std::string& fragment, const std::string& name);
+    void setValue (const std::string& uniform, const glm::vec4& value, int components);
+    [[nodiscard]] std::string uniformOf (const std::string& constant) const;
+
+    const CWallpaper& m_owner;
+    std::string m_file;
+    Data::Model::MaterialUniquePtr m_material;
+    const Data::Model::MaterialPass* m_pass = nullptr;
+    Data::Model::ComboMap m_combos;
+    Data::Model::ComboMap m_overrideCombos;
+    Data::Model::TextureMap m_noTextures;
+    std::unique_ptr<Shaders::Shader> m_shader;
+    GLuint m_program = GL_NONE;
+    GLuint m_vertices = GL_NONE;
+    /** the scene's VAO carries the output quad's attributes */
+    GLuint m_vao = GL_NONE;
+    GLint a_Position = -1;
+    GLint a_TexCoord = -1;
+    struct Texture {
+	GLuint texture = GL_NONE;
+	GLenum target = GL_TEXTURE_2D;
+    };
+    std::map<int, Texture> m_textures;
+    std::map<std::string, Value> m_values;
+};
+} // namespace WallpaperEngine::Render

+ 46 - 0
src/WallpaperEngine/Render/MissingTexture.cpp

@@ -0,0 +1,46 @@
+#include "MissingTexture.h"
+
+#include <array>
+
+using namespace WallpaperEngine::Render;
+
+MissingTexture::MissingTexture () {
+    std::array<uint8_t, SIZE * SIZE * 4> pixels {};
+
+    for (uint32_t i = 0; i < SIZE * SIZE; i++) {
+	const uint8_t yellow = ((i / SIZE) & 1) != (i & 1) ? 255 : 0;
+
+	pixels[i * 4 + 0] = yellow;
+	pixels[i * 4 + 1] = yellow;
+	pixels[i * 4 + 2] = 0;
+	pixels[i * 4 + 3] = 255;
+    }
+
+    glGenTextures (1, &this->m_textureID);
+    glBindTexture (GL_TEXTURE_2D, this->m_textureID);
+    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, SIZE, SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data ());
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+}
+
+MissingTexture::~MissingTexture () { glDeleteTextures (1, &this->m_textureID); }
+
+GLuint MissingTexture::getTextureID (uint32_t imageIndex) const { return this->m_textureID; }
+uint32_t MissingTexture::getTextureWidth (uint32_t imageIndex) const { return SIZE; }
+uint32_t MissingTexture::getTextureHeight (uint32_t imageIndex) const { return SIZE; }
+uint32_t MissingTexture::getRealWidth () const { return SIZE; }
+uint32_t MissingTexture::getRealHeight () const { return SIZE; }
+TextureFormat MissingTexture::getFormat () const { return TextureFormat_ARGB8888; }
+uint32_t MissingTexture::getFlags () const { return TextureFlags_NoInterpolation; }
+const std::vector<FrameSharedPtr>& MissingTexture::getFrames () const { return this->m_frames; }
+const glm::vec4* MissingTexture::getResolution () const { return &this->m_resolution; }
+bool MissingTexture::isAnimated () const { return false; }
+bool MissingTexture::isReady () const { return true; }
+
+void MissingTexture::incrementUsageCount () const { }
+void MissingTexture::decrementUsageCount () const { }
+void MissingTexture::update () const { }

+ 35 - 0
src/WallpaperEngine/Render/MissingTexture.h

@@ -0,0 +1,35 @@
+#pragma once
+
+#include "TextureProvider.h"
+
+namespace WallpaperEngine::Render {
+/** WE's texture for anything it can't load (sub_1400EEF70): 6x6 yellow/black checker, point sampled */
+class MissingTexture final : public TextureProvider {
+public:
+    MissingTexture ();
+    ~MissingTexture () override;
+
+    [[nodiscard]] GLuint getTextureID (uint32_t imageIndex) const override;
+    [[nodiscard]] uint32_t getTextureWidth (uint32_t imageIndex) const override;
+    [[nodiscard]] uint32_t getTextureHeight (uint32_t imageIndex) const override;
+    [[nodiscard]] uint32_t getRealWidth () const override;
+    [[nodiscard]] uint32_t getRealHeight () const override;
+    [[nodiscard]] TextureFormat getFormat () const override;
+    [[nodiscard]] uint32_t getFlags () const override;
+    [[nodiscard]] const std::vector<FrameSharedPtr>& getFrames () const override;
+    [[nodiscard]] const glm::vec4* getResolution () const override;
+    [[nodiscard]] bool isAnimated () const override;
+    [[nodiscard]] bool isReady () const override;
+
+    void incrementUsageCount () const override;
+    void decrementUsageCount () const override;
+    void update () const override;
+
+private:
+    static constexpr uint32_t SIZE = 6;
+
+    std::vector<FrameSharedPtr> m_frames;
+    glm::vec4 m_resolution { SIZE, SIZE, SIZE, SIZE };
+    GLuint m_textureID = GL_NONE;
+};
+} // namespace WallpaperEngine::Render

+ 11 - 1
src/WallpaperEngine/Render/Objects/CCamera.cpp

@@ -14,6 +14,16 @@ CCamera::CCamera (Wallpapers::CScene& scene, const SceneCamera& camera) :
     m_random (static_cast<unsigned> (camera.id)) {
     this->registerProperty ("fov", *camera.fov->value);
     this->registerProperty ("zoom", *camera.zoom->value);
+    this->registerProperty ("queuemode", *camera.queueMode);
+
+    // an unknown name is the table's first entry (sub_1401F38C0)
+    camera.queueMode->listen (
+	[mode = camera.queueMode.get ()] (const DynamicValue&, const DynamicValue::UpdateSource source) {
+	    if (mode->getString () != "random" && mode->getString () != "sequential") {
+		mode->update (std::string ("random"), source);
+	    }
+	}
+    );
 }
 
 const SceneCamera& CCamera::getCamera () const { return this->m_camera; }
@@ -22,7 +32,7 @@ int CCamera::nextTimeline () {
     const auto& timelines = this->m_camera.timelines;
     const int count = static_cast<int> (timelines.size ());
 
-    if (this->m_camera.queueMode == CameraQueueMode::Sequential) {
+    if (this->m_camera.queueMode->getString () == "sequential") {
 	for (int tries = 0; tries < count; tries++) {
 	    this->m_cursor = (this->m_cursor + 1) % count;
 

Datei-Diff unterdrückt, da er zu groß ist
+ 591 - 248
src/WallpaperEngine/Render/Objects/CImage.cpp


+ 101 - 45
src/WallpaperEngine/Render/Objects/CImage.h

@@ -49,6 +49,16 @@ struct PuppetMorphTargets {
     std::vector<glm::vec4> texels;
     /** some target alpha is below 1 */
     bool alpha = false;
+    /** mesh flag 0x2000 (MORPHING_MODIFIERS): bone, 1 for an axis rule, smoothstep edges */
+    struct BoneRule {
+	uint32_t bone = 0;
+	float axis = 0.0f;
+	float edge0 = 0.0f;
+	float edge1 = 0.0f;
+    };
+    std::vector<BoneRule> boneRules;
+    /** for script blend shape lookups */
+    std::vector<std::string> names;
 };
 
 class CImage final : public CRenderable, public ScriptableObject {
@@ -69,17 +79,30 @@ public:
     /** A cursor event's localPosition: (u * width, (1 - v) * height) of the unscaled layer, from its top left, where
      *  the cursor meets the quad's plane (sub_14019DBB0), off the quad too. Zero when it doesn't meet the plane */
     [[nodiscard]] glm::vec2 cursorLocalPosition (const glm::vec2& ndc);
+    /** hitBox: puppet bone box under the cursor (sub_1401FD690) */
+    [[nodiscard]] std::optional<std::string> cursorHitBox (const glm::vec2& ndc) const;
     void renderPassthroughChildren (const std::shared_ptr<const CFBO>& buffer);
+    /** sub_1401EA500: only layers with renderable flag 0x10 get a named _a buffer, the rest and every _b are pooled */
+    [[nodiscard]] bool usesPooledBuffer () const;
+    /** renderable +800 (sub_1401E7170): 1 per visible effect (0 for shapes) plus its compose passes */
+    [[nodiscard]] int effectBufferPasses () const;
+    /** sub_1401EA500's buffer name for index, empty when WE has no such buffer */
+    [[nodiscard]] std::string layerBufferName (int index) const;
     [[nodiscard]] const Image& getImage () const;
     [[nodiscard]] glm::vec2 getSize () const;
     /** Another object samples this layer's composite FBO, so its passes run even while it's hidden */
     void markAsDependency ();
+    [[nodiscard]] bool copiesForReaders () const;
+    /** had children when it was set up */
+    [[nodiscard]] bool drawsPassthroughChildren () const { return this->m_hasPassthroughChildren; }
 
     [[nodiscard]] GLuint getSceneSpacePosition () const;
     [[nodiscard]] GLuint getCopySpacePosition () const;
     [[nodiscard]] GLuint getPassSpacePosition () const;
     [[nodiscard]] GLuint getTexCoordCopy () const;
     [[nodiscard]] GLuint getTexCoordPass () const;
+    /** copy is x, y, right, bottom */
+    void uploadSceneTexCoords (const glm::vec4& copy);
 
     [[nodiscard]] const float& getBrightness () const override;
     [[nodiscard]] const float& getUserAlpha () const override;
@@ -92,21 +115,8 @@ public:
 
     void pinpongFramebuffer (std::shared_ptr<const CFBO>* drawTo, std::shared_ptr<const TextureProvider>* asInput);
 
-    /** A puppet attachment point's current animated position, rotation and scale, in this puppet's own
-     * local mesh space (same space as PuppetAttachmentPoint's position/localTransform). A negative
-     * scale component means the bone's transform includes a reflection (a mirrored bone). */
-    struct AttachmentPointTransform {
-	glm::vec3 position;
-	float angle;
-	glm::vec2 scale;
-    };
-
-    /**
-     * @param name A named attachment point on this puppet's rig (see PuppetAttachmentPoint)
-     * @return The point's current animated transform, or nullopt if there's no such point (or no puppet mesh)
-     */
-    [[nodiscard]] std::optional<AttachmentPointTransform>
-    getAttachmentPointMeshTransform (const std::string& name) const;
+    /** Bone matrix times the attachment point's matrix in puppet space (sub_1401FD5C0) */
+    [[nodiscard]] std::optional<glm::mat4> getAttachmentMatrix (const std::string& name) const;
 
     /** Per frame puppet update (WE's image update, sub_1401FDF90): animation, physics and the bone matrices, before
      *  the scripts run so they read and change this frame's pose */
@@ -118,6 +128,12 @@ public:
      * local ones relative to the parent bone. Only valid while hasPuppetPose(), for bones below the bone count.
      */
     [[nodiscard]] bool hasPuppetPose () const;
+    /** sub_140210400: first target of that name, -1 for none */
+    [[nodiscard]] int getBlendShapeIndex (const std::string& name) const;
+    /** sub_1402104B0: 0 out of range */
+    [[nodiscard]] float getBlendShapeWeight (int target) const;
+    /** sub_1402105C0: holds until the next update resets the weights (sub_14021C480) */
+    void setBlendShapeWeight (int target, float weight);
     [[nodiscard]] const std::vector<PuppetBone>& getPuppetBones () const { return this->m_rig.bones; }
     [[nodiscard]] PuppetRig& getRig () { return this->m_rig; }
     [[nodiscard]] const PuppetRig& getRig () const { return this->m_rig; }
@@ -183,17 +199,13 @@ protected:
     [[nodiscard]] bool effectVisibilityChanged () const;
 
     void updateScreenSpacePosition ();
-    [[nodiscard]] glm::mat4 ancestorTiltCorrection () const;
     void updateEffectTextureProjection ();
-    void updateLightingTransform (const glm::mat4& sceneTransform);
-
-    struct ResolvedTransform {
-	glm::vec3 origin;
-	glm::vec3 scale;
-	float angle;
-    };
+    /** objectTransform is the world matrix and view projection in 3D scenes, screen the draw's MVP */
+    void updateLightingTransform (
+	const glm::mat4& sceneTransform, const std::optional<std::pair<glm::mat4, glm::mat4>>& objectTransform,
+	const glm::mat4& screen
+    );
 
-    [[nodiscard]] ResolvedTransform resolveTransform (const WallpaperEngine::Data::Model::Object& object) const;
     /** Scene camera of this layer, the perspective layer camera when "perspective" is set */
     [[nodiscard]] glm::mat4 getViewProjection () const;
 
@@ -201,13 +213,6 @@ private:
     /** Composite pass that applies the scene's fog, when there is fog */
     Effects::CPass* m_fogPass = nullptr;
 
-public:
-    /**
-     * Computes the object's own transform (origin/scale/angle) without walking the
-     * parent chain. Used as the per-node step of resolveTransform.
-     */
-    [[nodiscard]] static ResolvedTransform localTransform (const WallpaperEngine::Data::Model::Object& object);
-
 private:
     bool loadPuppetMesh (const glm::vec2& size);
     void updatePuppetPositionBuffer (const glm::vec2& size);
@@ -217,6 +222,11 @@ private:
     [[nodiscard]] ComboMap puppetVertexAlphaCombos () const;
     void updatePuppetVertexAlpha (const std::vector<float>& morphAlpha);
     void setupPuppetGeometryCallback (Effects::CPass* pass) const;
+    /** No other pass, prelight, blend map or clipping */
+    [[nodiscard]] bool litDrawsDirect () const;
+    void setupDirectLitPass ();
+    void setupPuppetPrelight ();
+    void uploadPuppetPrelightBuffers ();
     /** The mask and clipping target passes of a puppet with clipping records, once the mesh pass exists */
     void setupPuppetClipping ();
     /** sub_1401FDF90 end: sorts the parts by order + their bone's animated draw order, rebuilds the indices */
@@ -228,12 +238,12 @@ private:
     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 (
-	const glm::vec3& origin, const glm::vec2& size, const glm::vec3& scale, float sceneWidth, float sceneHeight
-    );
+    void setupPuppetBlendMap (bool offscreen);
+    /** LIGHTING / REFLECTION on the first pass */
+    [[nodiscard]] bool hasLitMaterial () const;
+    void updateGeometryBuffers ();
+    [[nodiscard]] glm::vec2 resolveGeometrySize () const;
+    void updateScenePosition (const glm::vec2& size);
     void uploadGeometryBuffers (const glm::vec2& size);
     [[nodiscard]] bool shouldRenderFinalPass (bool isLastPass) const;
     bool configurePassTarget (
@@ -247,6 +257,8 @@ private:
     GLuint m_passSpacePosition;
     GLuint m_texcoordCopy;
     GLuint m_texcoordPass;
+    GLuint m_texcoordDirect = GL_NONE;
+    GLuint m_texcoordFinal = GL_NONE;
     GLuint m_puppetSpacePosition = GL_NONE;
     GLuint m_puppetTexCoord = GL_NONE;
     GLuint m_puppetIndices = GL_NONE;
@@ -295,15 +307,34 @@ private:
 	Effects::CPass* copyPass = nullptr;
 	Effects::CPass* pass = nullptr;
     } m_blendMap;
+    /** WE's prelighting draw (sub_140209540) for lit puppets whose mesh a later pass draws */
+    struct {
+	Effects::CPass* pass = nullptr;
+	GLuint bindPositions = GL_NONE;
+	/** bind positions plus morph targets */
+	GLuint morphedPositions = GL_NONE;
+	GLuint flatPositions = GL_NONE;
+	GLuint normals = GL_NONE;
+	GLuint tangents = GL_NONE;
+	GLuint blendIndices = GL_NONE;
+	GLuint blendWeights = GL_NONE;
+	/** MDLV 21+ auxiliary block, empty without one */
+	std::vector<GLfloat> auxPositions = {};
+	std::vector<GLfloat> normalData = {};
+	std::vector<GLfloat> tangentData = {};
+	std::vector<GLfloat> morphedData = {};
+	/** float4x3 per bone */
+	std::vector<GLfloat> bones = {};
+	glm::mat4 model { 1.0f };
+	glm::mat3 normal { 1.0f };
+	glm::mat4 projection { 1.0f };
+    } m_puppetPrelight;
+    /** WE's model material draw for lit layers that need no buffer (sub_140209540), nullptr otherwise */
+    Effects::CPass* m_directLitPass = nullptr;
     mutable bool m_puppetDrawDiagnosticLogged = false;
     mutable bool m_puppetDrawErrorChecked = false;
     bool m_puppetPositionDiagnosticLogged = false;
-    mutable std::set<int> m_attachmentDiagnosticLogged = {};
     std::vector<GLfloat> m_puppetRawPositions = {};
-    /** This object's current resolved scale, mirrored here so updatePuppetSkinning() (called after
-     *  updateGeometryBuffers() each frame, see render()) can fold it into puppet vertex positions
-     *  without needing resolveTransform() run twice */
-    glm::vec3 m_puppetScale { 1.0f };
     std::vector<glm::uvec4> m_puppetBlendIndices = {};
     std::vector<glm::vec4> m_puppetBlendWeights = {};
 
@@ -312,6 +343,8 @@ private:
     uint32_t m_puppetMeshFlags = 0;
     uint32_t m_puppetMeshFormat = 0;
     std::optional<PuppetMorphTargets> m_puppetMorph = std::nullopt;
+    /** genericimage4 has it, genericimage2 doesn't */
+    bool m_puppetMorphShader = false;
     /** per vertex morph texel, nullopt if not morphed */
     std::vector<std::optional<uint32_t>> m_puppetMorphIndices = {};
     /** vertex alpha through SKINNING_ALPHA, see setupPuppetGeometryCallback */
@@ -341,6 +374,16 @@ private:
 
     std::shared_ptr<const CFBO> m_mainFBO = nullptr;
     std::shared_ptr<const CFBO> m_subFBO = nullptr;
+    std::shared_ptr<const CFBO> m_namedMainFBO = nullptr;
+    std::shared_ptr<const CFBO> m_namedSubFBO = nullptr;
+    /** pooled buffers of the same name are shared between layers */
+    struct LayerBufferConfig {
+	glm::vec2 size {};
+	TextureFormat format = TextureFormat_ARGB8888;
+	uint32_t flags = 0;
+    } m_layerBufferConfig;
+    /** like sub_1401EA500, redone on every pass rebuild */
+    void assignLayerBuffers ();
     std::shared_ptr<const CFBO> m_currentMainFBO = nullptr;
     std::shared_ptr<const CFBO> m_currentSubFBO = nullptr;
 
@@ -358,6 +401,17 @@ private:
 	bool fromEffect;
     };
     std::vector<PassState> m_allPassStates = {};
+    /** Inputs setup () depends on, a change sets the passes up again */
+    struct SetupInputs {
+	std::vector<bool> puppetEffects;
+	int colorBlendMode = 0;
+	bool copyForReaders = false;
+
+	bool operator== (const SetupInputs&) const = default;
+    };
+    [[nodiscard]] SetupInputs currentSetupInputs () const;
+    void releasePasses ();
+    SetupInputs m_setupInputs = {};
     std::vector<bool> m_activePassMask = {};
     bool m_hasActiveEffectPass = false;
     bool m_passesDrawToScreen = false;
@@ -366,9 +420,6 @@ private:
     glm::vec4 m_pos = {};
     /** The quad's size before the layer's scale, what m_pos spans */
     glm::vec2 m_displaySize = {};
-    /** The object's origin in m_pos's space, what the rotation turns around: WE puts the alignment offset inside
-     *  the rotated and scaled frame (sub_1401FD3F0), not around it */
-    glm::vec3 m_scenePivot = {};
     std::optional<TextureAnimation> m_textureAnimation = std::nullopt;
     float m_textureAnimationClock = -1.0f;
     /** Lit passes: scene/copy space vertices -> WE world (y up, bottom left origin), see CPass::setLightingTransform */
@@ -385,6 +436,8 @@ private:
     bool m_initialized = false;
     bool m_isDependency = false;
     bool m_readByOtherLayer = false;
+    /** read by a particle layerimage emitter */
+    bool m_emitterImageSource = false;
     /** A passthrough layer with objects under it, it draws them into its buffer after the base pass */
     bool m_hasPassthroughChildren = false;
 
@@ -393,12 +446,15 @@ private:
 	    MaterialUniquePtr material;
 	    ImageEffectPassOverrideUniquePtr override;
 	} colorBlending;
+	Effects::CPass* colorBlendingPass = nullptr;
 	std::vector<MaterialUniquePtr> compatibilityMaterials = {};
 	std::vector<ImageEffectPassOverrideUniquePtr> compatibilityOverrides = {};
 	MaterialUniquePtr clippingMask;
 	MaterialUniquePtr clippingCompose;
 	std::vector<ImageEffectPassOverrideUniquePtr> clippingOverrides = {};
 	ImageEffectPassOverrideUniquePtr puppetVertexAlpha;
+	ImageEffectPassOverrideUniquePtr puppetPrelight;
+	ImageEffectPassOverrideUniquePtr directLit;
 	MaterialUniquePtr blendMap;
 	ImageEffectPassOverrideUniquePtr blendMapOverride;
     } m_materials;

+ 22 - 0
src/WallpaperEngine/Render/Objects/CLight.cpp

@@ -10,6 +10,28 @@ CLight::CLight (Wallpapers::CScene& scene, const Light& light, int slot) :
     this->registerProperty ("intensity", *light.intensity->value);
     this->registerProperty ("radius", *light.radius->value);
     this->registerProperty ("visible", *light.visible->value);
+
+    // sub_14025DA80
+    const std::pair<const char*, const UserSettingUniquePtr&> properties[] = {
+	{ "light", light.typeName },
+	{ "castvolumetrics", light.castVolumetrics },
+	{ "usecookie", light.useCookie },
+	{ "castshadow", light.castShadow },
+	{ "controlpoint", light.controlPoint },
+	{ "cascadedistance0", light.cascadeDistance[0] },
+	{ "cascadedistance1", light.cascadeDistance[1] },
+	{ "cascadedistance2", light.cascadeDistance[2] },
+	{ "volumetricsexponent", light.volumetricsExponent },
+	{ "outercone", light.outerCone },
+	{ "innercone", light.innerCone },
+	{ "exponent", light.exponent },
+	{ "lightsourcesize", light.lightSourceSize },
+	{ "density", light.density },
+    };
+
+    for (const auto& [name, setting] : properties) {
+	this->registerProperty (name, *setting->value);
+    }
 }
 
 const Light& CLight::getLight () const { return this->m_light; }

+ 65 - 50
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -189,8 +189,7 @@ private:
     std::vector<FrameSharedPtr> m_frames = {};
 };
 
-// bounds is the union of every mesh's box (sub_1402617C0), what the cursor hit test uses; files before version 17 have
-// no boxes and leave it empty (min > max)
+// bounds = union of the mesh boxes (sub_1402617C0), before v17 boxes are zero; no width gives +-131072
 std::vector<MdlMesh> readMdlMeshes (
     const std::vector<char>& data, glm::vec3& boundsMin, glm::vec3& boundsMax, size_t& end, uint32_t& meshCount,
     std::vector<uint32_t>& meshFlags
@@ -299,6 +298,11 @@ std::vector<MdlMesh> readMdlMeshes (
 	}
     }
 
+    if (!(boundsMax.x > boundsMin.x)) {
+	boundsMin = glm::vec3 (-131072.0f);
+	boundsMax = glm::vec3 (131072.0f);
+    }
+
     end = reader.offset ();
     return meshes;
 }
@@ -782,29 +786,11 @@ CMesh::CMesh (Wallpapers::CScene& scene, const Mesh& mesh) :
     CObject (scene, mesh), ScriptableObject (scene, mesh), m_mesh (mesh) {
     this->registerProperty ("castshadow", *mesh.castShadow->value);
     this->registerProperty ("rootmotion", *mesh.rootMotion->value);
+    this->registerProperty ("perspective", *mesh.perspective->value);
 
     // animation layer property scripts run with the layer as thisObject, like an image's (sub_1402230C0)
     for (size_t layerIndex = 0; layerIndex < mesh.animationLayers.size (); layerIndex++) {
-	const auto& layer = mesh.animationLayers[layerIndex];
-	const std::string prefix = "animationlayers[" + std::to_string (layerIndex) + "].";
-
-	for (const auto& [name, setting] :
-	     { std::pair { "visible", &layer->visible }, std::pair { "rate", &layer->rate },
-	       std::pair { "blend", &layer->blend } }) {
-	    if (*setting == nullptr) {
-		continue;
-	    }
-
-	    this->registerProperty (
-		prefix + name, *(*setting)->value,
-		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);
-		}
-	    );
-	}
+	this->registerAnimationLayerProperties (layerIndex, *mesh.animationLayers[layerIndex]);
     }
 }
 
@@ -835,14 +821,15 @@ void CMesh::setup () {
 	return;
     }
 
-    const auto& project = this->getScene ().getScene ().project;
-    const auto stream = project.assetLocator->read (this->m_mesh.model);
-    const std::vector<char> data { std::istreambuf_iterator<char> (*stream), std::istreambuf_iterator<char> () };
+    const auto file = this->getScene ().readModelFile (this->m_mesh.model);
+    const std::vector<char>& data = *file;
 
     size_t end = 0;
     uint32_t meshCount = 0;
     std::vector<uint32_t> meshFlags;
     auto meshes = readMdlMeshes (data, this->m_boundsMin, this->m_boundsMax, end, meshCount, meshFlags);
+    this->m_cullMin = this->m_boundsMin;
+    this->m_cullMax = this->m_boundsMax;
 
     // version 13+ files name the next section after the last mesh, a skeleton (MDLS) and its clips are loaded the same
     // way as a puppet's (sub_140261880)
@@ -897,6 +884,8 @@ void CMesh::buildModelDataParts () {
     this->m_modelStructure = this->m_modelData->structure;
     this->m_boundsMin = this->m_modelData->boundsMin;
     this->m_boundsMax = this->m_modelData->boundsMax;
+    this->m_cullMin = this->m_boundsMin;
+    this->m_cullMax = this->m_boundsMax;
 
     for (const auto& source : this->m_modelData->meshes) {
 	if (source.stride == 0 || source.vertices.empty ()) {
@@ -974,7 +963,15 @@ void CMesh::updateAnimation () {
     this->m_rig.finishEndedLayers ([this] (size_t serial) {
 	this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
     });
+    for (const auto& removed : this->m_rig.takeRemovedLayers ()) {
+	this->unregisterAnimationLayerProperties (removed.serial);
+    }
     this->updateBones ();
+
+    if (!this->m_rig.clipBounds (this->m_cullMin, this->m_cullMax)) {
+	this->m_cullMin = this->m_boundsMin;
+	this->m_cullMax = this->m_boundsMax;
+    }
 }
 
 bool CMesh::rootMotionEnabled () const { return this->m_mesh.rootMotion->value->getBool (); }
@@ -1021,11 +1018,42 @@ void CMesh::render () {
 
     this->updateMatrices ();
 
+    // renderer +284 bit 0, set for every scene (sub_140186C90)
+    if (this->outsideFrustum (this->getScene ().getCullViewProjection ())) {
+	return;
+    }
+
     for (const auto& part : this->m_parts) {
 	part->render ();
     }
 }
 
+bool CMesh::outsideFrustum (const glm::mat4& direct3D) const {
+    const glm::vec3 low (this->m_modelMatrix * glm::vec4 (this->m_cullMin, 1.0f));
+    const glm::vec3 high (this->m_modelMatrix * glm::vec4 (this->m_cullMax, 1.0f));
+    const glm::vec3 half = (high - low) * 0.5f;
+    const glm::vec3 center = low + half;
+    const float radius = glm::length (half);
+    const glm::mat4& m = direct3D;
+    const glm::vec4 rows[4] = {
+	{ m[0][0], m[1][0], m[2][0], m[3][0] },
+	{ m[0][1], m[1][1], m[2][1], m[3][1] },
+	{ m[0][2], m[1][2], m[2][2], m[3][2] },
+	{ m[0][3], m[1][3], m[2][3], m[3][3] },
+    };
+
+    for (const glm::vec4& plane : { rows[3] + rows[0], rows[3] - rows[0], rows[3] + rows[1], rows[3] - rows[1],
+				    rows[3] + rows[2], rows[3] - rows[2] }) {
+	const glm::vec4 normalized = plane / glm::length (glm::vec3 (plane));
+
+	if (-radius > glm::dot (glm::vec3 (normalized), center) + normalized.w) {
+	    return true;
+	}
+    }
+
+    return false;
+}
+
 void CMesh::updateMatrices () {
     const auto& scene = this->getScene ();
     const auto& camera = scene.getCamera ();
@@ -1070,31 +1098,9 @@ void CMesh::renderShadowCaster (
 ) {
     this->updateMatrices ();
 
-    // perspective scenes (renderer +284 & 1) skip a shadow viewport whose frustum (sub_1401849E0: x, y and z against
-    // w, planes normalized) has the model's bounding sphere fully outside one plane. The sphere spans the world
-    // corners of the .mdl bounds (sub_1402222A0)
-    if (this->getScene ().getCamera ().isPerspective () && this->m_boundsMax.x > this->m_boundsMin.x) {
-	const glm::vec3 low (this->m_modelMatrix * glm::vec4 (this->m_boundsMin, 1.0f));
-	const glm::vec3 high (this->m_modelMatrix * glm::vec4 (this->m_boundsMax, 1.0f));
-	const glm::vec3 half = (high - low) * 0.5f;
-	const glm::vec3 center = low + half;
-	const float radius = glm::length (half);
-	const glm::mat4& m = cullViewProjection;
-	const glm::vec4 rows[4] = {
-	    { m[0][0], m[1][0], m[2][0], m[3][0] },
-	    { m[0][1], m[1][1], m[2][1], m[3][1] },
-	    { m[0][2], m[1][2], m[2][2], m[3][2] },
-	    { m[0][3], m[1][3], m[2][3], m[3][3] },
-	};
-
-	for (const glm::vec4& plane : { rows[3] + rows[0], rows[3] - rows[0], rows[3] + rows[1], rows[3] - rows[1],
-					rows[3] + rows[2], rows[3] - rows[2] }) {
-	    const glm::vec4 normalized = plane / glm::length (glm::vec3 (plane));
-
-	    if (-radius > glm::dot (glm::vec3 (normalized), center) + normalized.w) {
-		return;
-	    }
-	}
+    // skip shadow viewports whose frustum has the bounding sphere fully outside a plane (sub_1402222A0)
+    if (this->outsideFrustum (cullViewProjection)) {
+	return;
     }
 
     const glm::mat4 matrix = viewProjection * this->m_modelMatrix;
@@ -1147,6 +1153,15 @@ std::optional<glm::vec3> CMesh::boxEntry (const glm::vec2& ndc) const {
     return origin + direction * enter;
 }
 
+std::optional<std::string> CMesh::cursorHitBox (const glm::vec2& ndc, glm::vec3& local) const {
+    const auto& scene = this->getScene ();
+    glm::vec3 origin;
+    glm::vec3 direction;
+    scene.cursorLine (ndc, this->m_mesh.perspective->value->getBool (), origin, direction);
+
+    return this->m_rig.modelHitBox (origin, direction, scene.objectWorldMatrix (this->m_mesh), local);
+}
+
 std::optional<glm::mat4> CMesh::getAttachmentMatrix (const std::string& name) const {
     return this->m_rig.attachmentMatrix (this->m_rig.findAttachment (name));
 }

+ 8 - 1
src/WallpaperEngine/Render/Objects/CMesh.h

@@ -52,7 +52,7 @@ public:
     [[nodiscard]] const glm::mat4& getModelViewProjectionMatrix () const;
     [[nodiscard]] const glm::mat4& getModelViewProjectionMatrixInverse () const;
     [[nodiscard]] const glm::vec3& getEyePosition () const;
-    /** The .mdl's bounds in model space (MDLV 17+), max not above min when the file has none */
+    /** Union of the MDLV 17+ mesh boxes, +-131072 when it has no width */
     [[nodiscard]] const glm::vec3& getBoundsMin () const { return this->m_boundsMin; }
     [[nodiscard]] const glm::vec3& getBoundsMax () const { return this->m_boundsMax; }
     /** Cursor hit test (sub_140185520): the line through the cursor against the model's bounds in model space, a box
@@ -60,6 +60,8 @@ public:
     [[nodiscard]] bool hitTest (const glm::vec2& ndc) const;
     /** A cursor event's localPosition: where the line enters that box, relative to the box's center, zero on a miss */
     [[nodiscard]] glm::vec3 cursorLocalPosition (const glm::vec2& ndc) const;
+    /** hitBox: first bone box the cursor line enters (sub_140223810), local becomes the entry point in its space */
+    [[nodiscard]] std::optional<std::string> cursorHitBox (const glm::vec2& ndc, glm::vec3& local) const;
     /**
      * Draws the meshes whose material blends "normal" or "alphatocoverage" into the bound shadow map through
      * viewProjection (GL clip space) with the caster program, the others don't cast (sub_1402222A0 in mode 0).
@@ -86,6 +88,8 @@ private:
 
     /** The model space point where the line through ndc enters the hit box, see hitTest */
     [[nodiscard]] std::optional<glm::vec3> boxEntry (const glm::vec2& ndc) const;
+    /** sub_1402222A0, planes from sub_1401849E0 */
+    [[nodiscard]] bool outsideFrustum (const glm::mat4& direct3D) const;
     void updateMatrices ();
     void updateBones ();
 
@@ -101,6 +105,9 @@ private:
     glm::vec3 m_eyePosition = glm::vec3 (0.0f);
     glm::vec3 m_boundsMin = glm::vec3 (0.0f);
     glm::vec3 m_boundsMax = glm::vec3 (0.0f);
+    /** model +760/+772 (sub_140226A10): visible animation layers' MDLA v5 boxes, else the .mdl bounds */
+    glm::vec3 m_cullMin = glm::vec3 (0.0f);
+    glm::vec3 m_cullMax = glm::vec3 (0.0f);
     std::shared_ptr<ModelData::Model> m_modelData = nullptr;
     PuppetRig m_rig;
     int m_boneCount = 0;

Datei-Diff unterdrückt, da er zu groß ist
+ 382 - 183
src/WallpaperEngine/Render/Objects/CParticle.cpp


+ 32 - 11
src/WallpaperEngine/Render/Objects/CParticle.h

@@ -23,6 +23,7 @@ using namespace WallpaperEngine::Data::Model;
 
 namespace WallpaperEngine::Render::Objects {
 class CImage;
+class PuppetRig;
 
 constexpr uint32_t DEFAULT_MAX_PARTICLES = 1000;
 
@@ -120,6 +121,8 @@ public:
 
     void setup () override;
     void render () override;
+    /** sub_140230650, before scripts */
+    void simulate ();
     void update (float dt);
 
     [[nodiscard]] const Particle& getParticle () const;
@@ -211,12 +214,8 @@ protected:
     [[nodiscard]] glm::vec3 remapOperatorInput (const ParticleRemap& remap, const ParticleInstance& p) const;
     /** The same for remapinitialvalue (sub_14023B340 case 15), which reads the particle's base values */
     [[nodiscard]] glm::vec3 remapInitialInput (const ParticleRemap& remap, ParticleInstance& p);
-    /** Layer transform translation in wallpaper64.exe's scene coordinates (remap input layerorigin) */
+    /** remap input layerorigin */
     [[nodiscard]] glm::vec3 remapLayerOrigin () const;
-    /** Control point position in wallpaper64.exe's y-up particle space */
-    [[nodiscard]] glm::vec3 controlPointWE (int index) const;
-    /** A position or direction as the vertex buffer takes it, see m_drawFlipY */
-    [[nodiscard]] glm::vec3 drawVector (const glm::vec3& value) const;
     /** A control point's matrix before the system's transform: its offset, or the instance override's point/angles */
     [[nodiscard]] glm::mat4 localControlPointMatrix (size_t index) const;
     /** Operators scale some forces by how long frames take (sub_140236CD0): dt * min(1, 0.025 / frame time)^0.7 */
@@ -248,19 +247,37 @@ protected:
     struct ImagePixel {
 	uint8_t r, g, b;
 	int16_t x, y;
+	/** puppet layers, 0xFF none */
+	uint8_t bone = 0xFF;
     };
+    /** sub_1401D3AE0 */
     struct ImageEmitter {
 	/** Which emitterimage dependency record it reads */
 	int index;
 	std::vector<ImagePixel> pixels;
-	bool built { false };
-	float refreshTimer { 0.0f };
+	/** first call only sets layer flags 0x1010 */
+	bool flagged { false };
+	bool requested { false };
+	uint32_t requestFrame { 0 };
+	/** 0 nothing, 1 downsampled into staging, 2 pixels ready */
+	int stage { 0 };
+	std::vector<ImagePixel> staged;
 	glm::ivec2 size { 0 };
+	glm::ivec2 stagedSize { 0 };
+	float refreshTimer { 0.0f };
+	/** layer world at the last read with pixels */
+	glm::mat4 world { 1.0f };
 	glm::mat4 previousWorld { 1.0f };
+	/** only if already loaded at setup */
+	std::shared_ptr<const TextureProvider> mask;
+	std::vector<glm::mat4> boneInverseBind;
     };
     std::vector<ImageEmitter> m_imageEmitters;
     EmitterFunc createImageEmitter (const ParticleEmitter& emitter);
-    void buildImagePixels (ImageEmitter& state, const CImage& image);
+    /** true once there are pixels to spawn from */
+    bool readImagePixels (ImageEmitter& state, const CObject& layer);
+    void downsampleLayerBuffer (ImageEmitter& state, const CFBO& buffer);
+    static void assignImagePixelBones (ImageEmitter& state, const PuppetRig& rig);
     OperatorFunc createCollisionModelOperator (const CollisionOperator& op);
     /** collisionmodel components set up so far, each one reads the dependency record with its index */
     int m_collisionModels { 0 };
@@ -280,6 +297,9 @@ protected:
 
     /** The object's transform (origin, parallax, angles, scale), what WE keeps at +928 for top level systems */
     [[nodiscard]] glm::mat4 objectMatrix () const;
+    /** WE's world to the camera's space: the 2D scene space, identity in 3D */
+    [[nodiscard]] glm::mat4 sceneMatrix () const;
+    [[nodiscard]] bool isShown () const;
     /** The matrix stack top WE simulates this system with (sub_140229760 / sub_140229810) */
     void updateFrame ();
     /** wallpaper64.exe sub_14022E3E0 */
@@ -346,10 +366,9 @@ private:
     GLint m_prevVAO { 0 };
 
     // Particle-specific uniform data (stored here, pointed to by CPass)
+    /** m_worldModelMatrix in sceneMatrix () space */
     glm::mat4 m_modelMatrix { 1.0f };
-    /** 2D scenes: vertices are uploaded in WE's y-up particle frame, m_modelMatrix carries the flip */
-    bool m_drawFlipY = false;
-    /** g_ModelMatrix: m_modelMatrix in WE's world space, see updateMatrices () */
+    /** WE's world, identity for world space systems */
     glm::mat4 m_worldModelMatrix { 1.0f };
     glm::mat4 m_modelMatrixInverse { 1.0f };
     glm::mat4 m_mvpMatrix { 1.0f };
@@ -379,6 +398,8 @@ private:
     int m_ropeSegments { 4 }; // ropetrail: historical position snapshots per particle
     float m_ropeUVScale { 1.0f };
     bool m_ropeUVScrolling { false };
+    /** since the last restart, for rope uvscrolling */
+    uint32_t m_ropeDeaths { 0 };
     bool m_trailFadeAlpha { false };
     bool m_trailFadeSize { false };
     /** ropetrail: m_ropeSegments past positions per particle slot, newest first, compacted with the particles */

+ 53 - 7
src/WallpaperEngine/Render/Objects/CRenderable.cpp

@@ -60,16 +60,56 @@ void clearBuffer (const CFBO& buffer, const glm::vec4& color) {
 }
 } // namespace
 
-void CRenderable::registerEffectBuffers (const ImageEffect& effect, std::vector<std::shared_ptr<CFBO>> buffers) {
-    for (size_t index = 0; index < buffers.size () && index < effect.effect->fbos.size (); index++) {
-	if (effect.effect->fbos[index]->clearOnCreate) {
-	    clearBuffer (*buffers[index], effect.effect->fbos[index]->clearColor);
+void CRenderable::registerEffectBuffers (const ImageEffect& effect, EffectBuffers buffers) {
+    for (const auto& [base, buffer] : buffers) {
+	if (base->clearOnCreate) {
+	    clearBuffer (*buffer, base->clearColor);
 	}
     }
 
     this->m_effectBuffers.insert_or_assign (&effect, std::move (buffers));
 }
 
+void CRenderable::registerEffectMaterial (const ImageEffect& effect, size_t passIndex, Effects::CPass* pass) {
+    auto& passes = this->m_effectMaterials[&effect];
+
+    if (passes.size () <= passIndex) {
+	passes.resize (passIndex + 1, nullptr);
+    }
+
+    if (passes[passIndex] != nullptr) {
+	return;
+    }
+
+    passes[passIndex] = pass;
+
+    if (const auto it = this->m_releasedScriptStates.find ({ &effect, passIndex });
+	it != this->m_releasedScriptStates.end ()) {
+	pass->restoreScriptState (it->second);
+	this->m_releasedScriptStates.erase (it);
+    }
+}
+
+void CRenderable::releaseEffectMaterials () {
+    for (const auto& [effect, passes] : this->m_effectMaterials) {
+	for (size_t passIndex = 0; passIndex < passes.size (); passIndex++) {
+	    if (passes[passIndex] != nullptr) {
+		this->m_releasedScriptStates.insert_or_assign (
+		    { effect, passIndex }, passes[passIndex]->getScriptState ()
+		);
+	    }
+	}
+    }
+
+    this->m_effectMaterials.clear ();
+}
+
+Effects::CPass* CRenderable::getEffectMaterial (const ImageEffect& effect, size_t passIndex) const {
+    const auto it = this->m_effectMaterials.find (&effect);
+
+    return it == this->m_effectMaterials.end () || passIndex >= it->second.size () ? nullptr : it->second[passIndex];
+}
+
 bool CRenderable::executeEffectFunction (const ImageEffect& effect, const std::string& name) const {
     const auto buffers = this->m_effectBuffers.find (&effect);
 
@@ -85,9 +125,15 @@ bool CRenderable::executeEffectFunction (const ImageEffect& effect, const std::s
 	return true;
     }
 
-    // WE's own slip: the loop counter picks the buffer, not the index the name resolved to
-    for (size_t index = 0; index < function->fbos.size () && index < buffers->second.size (); index++) {
-	clearBuffer (*buffers->second[index], effect.effect->fbos[index]->clearColor);
+    // WE's slip: the loop counter picks the buffer, not the index the name resolved to
+    const auto made = std::ranges::count_if (function->fbos, [&effect, &buffers] (const int index) {
+	return std::ranges::any_of (buffers->second, [&effect, index] (const auto& buffer) {
+	    return buffer.first == effect.effect->fbos[index].get ();
+	});
+    });
+
+    for (size_t index = 0; index < static_cast<size_t> (made) && index < buffers->second.size (); index++) {
+	clearBuffer (*buffers->second[index].second, buffers->second[index].first->clearColor);
     }
 
     return true;

+ 11 - 3
src/WallpaperEngine/Render/Objects/CRenderable.h

@@ -34,14 +34,20 @@ public:
      *  shared clock (renderer +4908, sub_14015F0D0) */
     [[nodiscard]] virtual std::optional<int> getTextureFrameOverride () const { return std::nullopt; }
 
-    /** The buffers made for an effect's fbos, in their order; ones with a complete "clear" are cleared now */
-    void registerEffectBuffers (const ImageEffect& effect, std::vector<std::shared_ptr<CFBO>> buffers);
+    /** The effect's buffers whose conditions held, with their effect.json entries */
+    using EffectBuffers = std::vector<std::pair<const FBO*, std::shared_ptr<CFBO>>>;
+    void registerEffectBuffers (const ImageEffect& effect, EffectBuffers buffers);
     /**
      * IEffect.executeMaterialFunction (wallpaper64.exe 2.8.42 sub_1401EE3A0): a "clear" function clears as many of
      * the effect's buffers as it names, but always the first ones, each to its own clear color. False when the effect
      * isn't one of this object's
      */
     bool executeEffectFunction (const ImageEffect& effect, const std::string& name) const;
+    /** WE only keeps a material's first pass (sub_1401515B0), what IEffect.getMaterial hands out */
+    void registerEffectMaterial (const ImageEffect& effect, size_t passIndex, Effects::CPass* pass);
+    [[nodiscard]] Effects::CPass* getEffectMaterial (const ImageEffect& effect, size_t passIndex) const;
+    /** Called before the passes are deleted, what scripts set on them goes to the next passes registered */
+    void releaseEffectMaterials ();
 
 protected:
     void detectTexture ();
@@ -50,6 +56,8 @@ protected:
 
     std::shared_ptr<const TextureProvider> m_texture = nullptr;
     const Material& m_material;
-    std::map<const ImageEffect*, std::vector<std::shared_ptr<CFBO>>> m_effectBuffers = {};
+    std::map<const ImageEffect*, EffectBuffers> m_effectBuffers = {};
+    std::map<const ImageEffect*, std::vector<Effects::CPass*>> m_effectMaterials = {};
+    std::map<std::pair<const ImageEffect*, size_t>, Effects::CPass::ScriptState> m_releasedScriptStates = {};
 };
 }

+ 19 - 7
src/WallpaperEngine/Render/Objects/CSound.cpp

@@ -61,7 +61,8 @@ glm::vec2 stereoPan (const glm::vec3& direction, float distance) {
 } // namespace
 
 CSound::CSound (Wallpapers::CScene& scene, const Sound& sound) :
-    CObject (scene, sound), m_sound (sound), m_startSilent (sound.startsilent.value_or (false)) {
+    CObject (scene, sound), m_sound (sound), m_startSilent (sound.startsilent->value->getBool ()) {
+    this->m_lastStartSilent = this->m_startSilent;
     this->m_lastVolume
 	= this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
     this->m_lastMaster = this->masterVolume ();
@@ -188,8 +189,10 @@ void CSound::play () {
 	this->loadVoices ();
     }
 
-    if (this->m_sound.spatialization) {
+    if (this->m_sound.spatialization->value->getBool ()) {
 	this->m_position = this->spatialPosition ();
+	this->m_rolloff = this->m_sound.attenuation->value->getFloat ();
+	this->m_reference = this->m_sound.mindistance->value->getFloat ();
     }
 
     const bool loop = this->m_voices.size () <= 1 && this->m_sound.playbackmode == PlaybackMode_Loop;
@@ -222,8 +225,12 @@ void CSound::play () {
 		    this->playVoice (voice, false);
 		    this->m_remaining = voice.duration;
 		}
-		this->m_timer = uniform01 () * (this->m_sound.maxtime - this->m_sound.mintime) + this->m_sound.mintime
-		    + this->m_remaining;
+		{
+		    const float mintime = this->m_sound.mintime->value->getFloat ();
+		    const float maxtime = this->m_sound.maxtime->value->getFloat ();
+
+		    this->m_timer = uniform01 () * (maxtime - mintime) + mintime + this->m_remaining;
+		}
 		break;
 	    case PlaybackMode_Single:
 		{
@@ -333,6 +340,11 @@ void CSound::update (float dt) {
 	= this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
     const float master = this->masterVolume ();
 
+    if (const bool startSilent = this->m_sound.startsilent->value->getBool (); startSilent != this->m_lastStartSilent) {
+	this->m_lastStartSilent = startSilent;
+	this->m_startSilent = startSilent;
+    }
+
     if (volume != this->m_lastVolume || master != this->m_lastMaster) {
 	this->m_lastVolume = volume;
 	this->m_lastMaster = master;
@@ -354,7 +366,7 @@ void CSound::update (float dt) {
 	    this->m_remaining -= dt;
 	}
 
-	if (this->m_sound.spatialization) {
+	if (this->m_sound.spatialization->value->getBool ()) {
 	    this->m_position = this->spatialPosition ();
 	}
     }
@@ -420,8 +432,8 @@ glm::vec2 CSound::outputGains (const Voice& voice) const {
     if (voice.mono && this->getScene ().getAudioContext ().getChannels () == 2) {
 	// WE only sets the reference distance and rolloff on spatialized sounds, the others keep OpenAL's 1 and 1 and
 	// sit on the listener
-	const float reference = this->m_sound.spatialization ? this->m_sound.mindistance : 1.0f;
-	const float rolloff = this->m_sound.spatialization ? this->m_sound.attenuation : 1.0f;
+	const float reference = this->m_reference;
+	const float rolloff = this->m_rolloff;
 	const float limit = std::max (reference / 1024.0f, FLT_EPSILON);
 	glm::vec3 direction = this->m_position;
 	float distance = 0.0f;

+ 5 - 0
src/WallpaperEngine/Render/Objects/CSound.h

@@ -92,7 +92,12 @@ private:
 
     float m_lastVolume = 0.0f;
     float m_lastMaster = 0.0f;
+    /** startsilent changes rewrite the flag even after play () cleared it (sub_14019B6B0) */
+    bool m_lastStartSilent = false;
     /** OpenAL source position, the origin (the listener) until spatialization moves it */
     glm::vec3 m_position = glm::vec3 (0.0f);
+    /** only set by play () on spatialized sounds */
+    float m_reference = 1.0f;
+    float m_rolloff = 1.0f;
 };
 } // namespace WallpaperEngine::Render::Objects

+ 75 - 28
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -347,6 +347,8 @@ CText::CText (Wallpapers::CScene& scene, const Text& text) :
     for (const auto& [name, setting] : properties) {
 	this->registerProperty (name, *setting->value);
     }
+    this->registerProperty ("copybackground", *text.copyBackground->value);
+    this->registerRenderableProperties (text.renderable, *text.colorBlendMode, *text.brightness);
     this->registerEffectConstants (text.effects);
 }
 
@@ -360,7 +362,7 @@ CText::~CText () {
 
     for (GLuint* buffer :
 	 { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords, &m_backgroundPositions,
-	   &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords }) {
+	   &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords, &m_finalTexcoords }) {
 	if (*buffer != 0) {
 	    glDeleteBuffers (1, buffer);
 	}
@@ -368,6 +370,8 @@ CText::~CText () {
 }
 
 void CText::destroyPasses () {
+    this->releaseEffectMaterials ();
+
     for (auto* pass : m_passes) {
 	delete pass;
     }
@@ -406,7 +410,7 @@ void CText::setup () {
 
     for (GLuint* buffer :
 	 { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords, &m_backgroundPositions,
-	   &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords }) {
+	   &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords, &m_finalTexcoords }) {
 	glGenBuffers (1, buffer);
     }
 
@@ -516,6 +520,15 @@ TextLayoutParams CText::currentParams () const {
     };
 }
 
+glm::vec2 CText::measuredSize () const {
+    if (!m_result.valid) {
+	return { 2.0f, 2.0f };
+    }
+
+    const glm::vec2 padding = m_passLayout.buffered ? this->currentPadding () : glm::vec2 (0.0f);
+    return { m_result.maxX - m_result.minX + padding.x * 2.0f, m_result.top - m_result.bottom + padding.y * 2.0f };
+}
+
 glm::vec2 CText::currentPadding () const {
     const glm::vec2 padding = m_text.padding->value->getVec2 ();
     return { std::min (padding.x, 512.0f), std::min (padding.y, 512.0f) };
@@ -577,8 +590,11 @@ CText::PassLayout CText::currentPassLayout () const {
     // and 0x8000, sub_140186440). Its other trigger, image flag 0x100, is never set in 2.8.42. The scene loader adds
     // 0x1010 to a text another object lists in its dependencies (sub_140186C90), the buffer is what it reads
     const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
+    layout.passthrough = (layout.blendMode != 0 && layout.blendMode != 31) || fog || m_isDependency;
+    // sub_140258900: buffered for visible effects or flag 0x10
     layout.buffered
-	= (!m_text.effects.empty () || (layout.blendMode != 0 && layout.blendMode != 31) || fog || m_isDependency)
+	= (std::ranges::any_of (m_text.effects, [] (const auto& effect) { return effect->visible->value->getBool (); })
+	   || layout.passthrough)
 	&& !debug.baseOnly;
 
     // sub_140258900: text with effects renders into a buffer of its box plus padding on every side
@@ -666,7 +682,7 @@ void CText::uploadGeometry () {
     glBindBuffer (GL_ARRAY_BUFFER, m_backgroundPositions);
     glBufferData (GL_ARRAY_BUFFER, sizeof (background), background, GL_DYNAMIC_DRAW);
 
-    // the effect buffer's composite quad, centered like the text box it holds
+    // composite quad: centered, the buffer's truncated size (sub_140258900)
     const float hx = std::max (1.0f, static_cast<float> (m_passLayout.bufferSize.x)) * 0.5f;
     const float hy = std::max (1.0f, static_cast<float> (m_passLayout.bufferSize.y)) * 0.5f;
     const GLfloat composite[]
@@ -674,6 +690,15 @@ void CText::uploadGeometry () {
 
     glBindBuffer (GL_ARRAY_BUFFER, m_compositePosition);
     glBufferData (GL_ARRAY_BUFFER, sizeof (composite), composite, GL_DYNAMIC_DRAW);
+
+    // 0.15 texel in from every edge (sub_1401EA310)
+    const glm::vec2 inset = 0.15000001f / glm::max (glm::vec2 (m_passLayout.bufferSize), glm::vec2 (1.0f));
+    const GLfloat finalTexcoords[]
+	= { inset.x,        inset.y, inset.x, 1.0f - inset.y, 1.0f - inset.x, inset.y,
+	    1.0f - inset.x, inset.y, inset.x, 1.0f - inset.y, 1.0f - inset.x, 1.0f - inset.y };
+
+    glBindBuffer (GL_ARRAY_BUFFER, m_finalTexcoords);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (finalTexcoords), finalTexcoords, GL_DYNAMIC_DRAW);
 }
 
 // sub_1401B3B60: g_RenderVar0..3 of materials/fonts/font.frag in atlas pixels (32 per em), clamped like WE
@@ -762,10 +787,8 @@ void CText::buildPasses () {
 	m_clearAlphaMaterial = layout.buffered && !layout.background
 	    ? MaterialParser::load (project, "materials/util/composelayer_clearalpha.json")
 	    : nullptr;
-	// scenes from version 3 on composite with genericimage4, the one with fog (sub_140257840)
-	m_passthroughMaterial = layout.buffered
-		&& ((layout.blendMode != 0 && layout.blendMode != 31) || this->getScene ().hasDistanceFog ()
-		    || this->getScene ().hasHeightFog ())
+	// genericimage4 for scene version 3+ (sub_140257840)
+	m_passthroughMaterial = layout.buffered && layout.passthrough
 	    ? MaterialParser::load (
 		  project,
 		  project.sceneVersion >= 3 ? "materials/util/effectpassthrough_4.json"
@@ -908,6 +931,8 @@ void CText::buildPasses () {
     }
 
     std::shared_ptr<const TextureProvider> asInput = m_currentMainFBO;
+    CPass* lastEffectPass = nullptr;
+    bool lastWritesToTarget = false;
 
     for (const auto& effect : m_text.effects) {
 	if (!effect->visible->value->getBool ()) {
@@ -915,31 +940,35 @@ void CText::buildPasses () {
 	}
 
 	const auto fboProvider = std::make_shared<FBOProvider> (this);
-	std::vector<std::shared_ptr<CFBO>> buffers;
+	EffectBuffers buffers;
 
 	for (const auto& fbo : effect->effect->fbos) {
-	    buffers.push_back (fboProvider->create (*fbo, TextureFlags_ClampUVs, fboSize));
+	    if (fbo->conditions.holds (effect->combos)) {
+		buffers.emplace_back (fbo.get (), fboProvider->create (*fbo, fboSize, this->getScene ().isHDR ()));
+	    }
 	}
 
 	this->registerEffectBuffers (*effect, std::move (buffers));
 
-	auto curOverride = effect->passOverrides.begin ();
-	const auto endOverride = effect->passOverrides.end ();
-
 	// same target/previous bookkeeping as CImage::setupPasses
 	bool inTargetSequence = false;
 	std::shared_ptr<const TextureProvider> sequenceInput = nullptr;
 
-	for (const auto& effectPass : effect->effect->passes) {
-	    if (!effectPass->material.has_value ()) {
-		// command-only passes (e.g. plain FBO copies) aren't supported for text
+	for (size_t passIndex = 0; passIndex < effect->effect->passes.size (); passIndex++) {
+	    const auto& effectPass = effect->effect->passes[passIndex];
+
+	    // command-only passes aren't supported for text, overrides go by pass index
+	    if (!effectPass->material.has_value () || !effectPass->conditions.holds (effect->combos)) {
 		continue;
 	    }
 
+	    const auto override = passIndex < effect->passOverrides.size ()
+		? std::optional<std::reference_wrapper<const ImageEffectPassOverride>> (
+		      *effect->passOverrides[passIndex]
+		  )
+		: std::nullopt;
+
 	    for (auto& matPass : effectPass->material.value ()->passes) {
-		const auto override = curOverride != endOverride
-		    ? **curOverride
-		    : std::optional<std::reference_wrapper<const ImageEffectPassOverride>> (std::nullopt);
 		const auto target = effectPass->target.has_value ()
 		    ? *effectPass->target
 		    : std::optional<std::reference_wrapper<std::string>> (std::nullopt);
@@ -980,6 +1009,9 @@ void CText::buildPasses () {
 		cpass->setModelViewProjectionMatrix (&m_modelViewProjectionPass);
 		cpass->setModelViewProjectionMatrixInverse (&m_modelViewProjectionPass);
 		m_passes.push_back (cpass);
+		this->registerEffectMaterial (*effect, passIndex, cpass);
+		lastEffectPass = cpass;
+		lastWritesToTarget = writesToTarget;
 
 		asInput = drawTo;
 
@@ -989,16 +1021,27 @@ void CText::buildPasses () {
 		    sequenceInput = nullptr;
 		}
 	    }
-
-	    if (curOverride != endOverride) {
-		++curOverride;
-	    }
 	}
     }
 
-    // final pass: composite the accumulated result onto the actual scene. With a blend mode that is WE's
-    // effectpassthrough material with BLENDMODE (sub_140257840), drawn translucent in white at full alpha
-    // (sub_1401E8AA0); colorBlendMode 31 is a plain additive composite
+    // without flag 0x10 the last effect pass draws onto the scene (sub_1401EBF60), depth tested only for 3D text
+    if (m_passthroughMaterial == nullptr && lastEffectPass != nullptr && !lastWritesToTarget) {
+	lastEffectPass->setDestination (this->getScene ().getFBO ());
+	lastEffectPass->setPosition (m_compositePosition);
+	lastEffectPass->setTexCoord (m_finalTexcoords);
+	lastEffectPass->setModelViewProjectionMatrix (&m_compositeMatrix);
+	lastEffectPass->setModelViewProjectionMatrixInverse (&m_compositeMatrixInverse);
+	lastEffectPass->setBlendingMode (BlendingMode_Translucent);
+	lastEffectPass->setDepthState (
+	    std::make_pair (
+		layout.depth ? DepthtestMode_Enabled : DepthtestMode_Disabled, lastEffectPass->getPass ().depthwrite
+	    )
+	);
+	m_compositePassCount = 1;
+	return;
+    }
+
+    // flag 0x10: effectpassthrough with BLENDMODE (sub_140257840) in white, translucent or additive for mode 31
     m_passthroughOverride.combos.clear ();
 
     if (m_passthroughMaterial != nullptr) {
@@ -1016,7 +1059,7 @@ void CText::buildPasses () {
 	    : new CPass (*this, std::make_shared<FBOProvider> (this), *pass, std::nullopt, std::nullopt, std::nullopt);
 
 	if (m_passthroughMaterial != nullptr) {
-	    cpass->setBlendingMode (BlendingMode_Translucent);
+	    cpass->setBlendingMode (layout.blendMode == 31 ? BlendingMode_Additive : BlendingMode_Translucent);
 	    cpass->addUniform ("g_Color4", &m_white);
 	    cpass->addUniform ("g_EyePosition", &this->getScene ().getFog ().eyeLocal);
 	} else if (layout.blendMode == 31) {
@@ -1026,7 +1069,7 @@ void CText::buildPasses () {
 	cpass->setDestination (this->getScene ().getFBO ());
 	cpass->setInput (asInput);
 	cpass->setPosition (m_compositePosition);
-	cpass->setTexCoord (m_compositeTexcoords);
+	cpass->setTexCoord (m_finalTexcoords);
 	// the fog of the composite measures where the text is in the scene
 	cpass->setModelMatrix (m_passthroughMaterial != nullptr ? &m_compositeModel : &m_modelMatrix);
 	cpass->setViewProjectionMatrix (&m_viewProjectionMatrix);
@@ -1118,10 +1161,14 @@ void CText::render () {
     const size_t passCount
 	= visible ? m_passes.size () : m_passes.size () - std::min (m_passes.size (), m_compositePassCount);
 
+    // no alpha writes into the scene target (sub_1401E8AA0)
     for (size_t i = 0; i < passCount; i++) {
+	glColorMask (true, true, true, m_passes[i]->getDestination () != this->getScene ().getFBO ());
 	m_passes[i]->render ();
     }
 
+    glColorMask (true, true, true, true);
+
 #if !NDEBUG
     glPopDebugGroup ();
 #endif /* DEBUG */

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

@@ -53,6 +53,8 @@ public:
     [[nodiscard]] bool hitTest (const glm::vec2& ndc);
     /** A cursor event's localPosition: from the top left of the box hitTest uses, where the cursor meets its plane */
     [[nodiscard]] glm::vec2 cursorLocalPosition (const glm::vec2& ndc);
+    /** sub_140258900: the layout box, plus padding when buffered, 2 x 2 before layout */
+    [[nodiscard]] glm::vec2 measuredSize () const;
     /** WE's text world (vtable slot 16, sub_140256E10): the object's world moved by the alignment anchor */
     [[nodiscard]] glm::mat4 worldMatrix () const;
 
@@ -68,8 +70,9 @@ private:
 	bool color = false;
 	/** the depth tested materials (3D scenes, depthtest "enabled") */
 	bool depth = false;
-	/** effects or a blend mode: the text goes through a buffer of its box plus padding first */
 	bool buffered = false;
+	/** flag 0x10: blend mode, fog or a dependent object */
+	bool passthrough = false;
 	int blendMode = 0;
 	glm::ivec2 bufferSize = { 0, 0 };
 
@@ -131,6 +134,8 @@ private:
     GLuint m_compositePosition = 0;
     GLuint m_quadTexcoords = 0;
     GLuint m_compositeTexcoords = 0;
+    /** 0.15 texel in from every edge */
+    GLuint m_finalTexcoords = 0;
 
     std::vector<Effects::CPass*> m_passes = {};
     /** the last passes, the ones putting the buffer onto the scene */

+ 293 - 78
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -1,7 +1,10 @@
 #include "CPass.h"
+
 #include <algorithm>
 #include <cctype>
 #include <cmath>
+#include <cstdlib>
+#include <ranges>
 #include <sstream>
 #include <type_traits>
 #include <utility>
@@ -18,6 +21,7 @@
 #include "WallpaperEngine/Render/CFBO.h"
 #include "WallpaperEngine/Render/Objects/CImage.h"
 
+#include "WallpaperEngine/Render/Shaders/ShaderCache.h"
 #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariable.h"
 #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableFloat.h"
 #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableInteger.h"
@@ -88,21 +92,16 @@ std::string textureSizeLabel (const std::shared_ptr<const TextureProvider>& text
 // shader used by Wallpaper Engine's built-in "X-Ray" interactive effect (effects/xray/effect.json)
 const std::string XRAY_EFFECT_SHADER = "effects/xray";
 
-// The xray fragment shader gates its reveal on a projector-style sample of a small halo sprite
-// (g_Texture2, e.g. "particle/halo_6") taken around the pointer; g_PointerScale only controls how
-// far that sample zooms into the sprite, not any on-screen radius, so there's no uniform value that
-// makes it cover the whole screen. Instead this patches the compiled fragment source to add a
-// g_XrayFullReveal uniform that bypasses the halo sample entirely, forcing the hidden layer
-// (g_Texture1) to blend in everywhere once toggled - see patchXrayFullRevealBypass() below.
+// The xray shader gates its reveal on a halo sprite sample around the pointer, so no uniform can make it cover
+// the screen. g_XrayReveal replaces that sample when >= 0: 1 everywhere (full), 0 never (disabled)
 const std::string XRAY_MULTIPLY_UNIFORM = "uniform float g_Multiply;";
-const std::string XRAY_FULL_REVEAL_UNIFORM_DECL = "uniform float g_Multiply;\nuniform float g_XrayFullReveal;";
+const std::string XRAY_REVEAL_UNIFORM_DECL = "uniform float g_Multiply;\nuniform float g_XrayReveal;";
 const std::string XRAY_BLEND_LINE = "blend *= (blendSample.x * blendSample.y);";
-const std::string XRAY_BLEND_LINE_PATCHED = "blend *= mix (blendSample.x * blendSample.y, 1.0, g_XrayFullReveal);";
+const std::string XRAY_BLEND_LINE_PATCHED
+    = "blend *= (g_XrayReveal < 0.0 ? blendSample.x * blendSample.y : g_XrayReveal);";
 
-// Returns false (leaving fragmentSource untouched) if the anchors weren't found, e.g. because a
-// different spirv-cross/glslang version formats the compiled output differently - callers should
-// treat that as "full xray toggle becomes a no-op" rather than fail the whole shader compile.
-bool patchXrayFullRevealBypass (std::string& fragmentSource) {
+// false (source untouched) if the anchors weren't found, xray modes then do nothing
+bool patchXrayRevealOverride (std::string& fragmentSource) {
     const auto blendPos = fragmentSource.find (XRAY_BLEND_LINE);
     const auto uniformPos = fragmentSource.find (XRAY_MULTIPLY_UNIFORM);
 
@@ -112,7 +111,7 @@ bool patchXrayFullRevealBypass (std::string& fragmentSource) {
 
     // replace the later occurrence first so the earlier one's position stays valid
     fragmentSource.replace (blendPos, XRAY_BLEND_LINE.size (), XRAY_BLEND_LINE_PATCHED);
-    fragmentSource.replace (uniformPos, XRAY_MULTIPLY_UNIFORM.size (), XRAY_FULL_REVEAL_UNIFORM_DECL);
+    fragmentSource.replace (uniformPos, XRAY_MULTIPLY_UNIFORM.size (), XRAY_REVEAL_UNIFORM_DECL);
     return true;
 }
 }
@@ -230,6 +229,10 @@ std::optional<std::string> CPass::resolveUserTextureName (const std::string& pro
     const auto& properties = this->m_renderable.getScene ().getScene ().project.properties;
     const auto it = properties.find (propertyName);
 
+    if (it != properties.end ()) {
+	it->second->pin ();
+    }
+
     if (it == properties.end ()) {
 	// not actually a property reference, treat it as a literal texture name like before
 	return propertyName;
@@ -260,6 +263,27 @@ std::shared_ptr<const TextureProvider> CPass::resolveNamedTexture (const std::st
 	return this->m_renderable.getScene ().getLightCookie ();
     }
 
+    // WE finds only _a of a named layer buffer by name (sub_1401EA500), anything else binds the checker
+    // (sub_1400EEF70). A layer's own buffers stay reachable
+    constexpr std::string_view compositePrefix = "_rt_imageLayerComposite_";
+
+    if (name.starts_with (compositePrefix)) {
+	const auto separator = name.rfind ('_');
+	const std::string id = name.substr (compositePrefix.size (), separator - compositePrefix.size ());
+	char* end = nullptr;
+	const long value = std::strtol (id.c_str (), &end, 10);
+	const bool numeric = !id.empty () && end != nullptr && *end == '\0';
+
+	if (numeric && value == this->m_renderable.getId ()) {
+	    return this->resolveFBO (name);
+	}
+
+	if (!numeric || name.substr (separator + 1) != "a"
+	    || !this->m_renderable.getScene ().hasNamedLayerBuffer (static_cast<int> (value))) {
+	    return this->m_renderable.getScene ().getMissingTexture ();
+	}
+    }
+
     if (name.starts_with ("_rt_") || name.starts_with ("_alias_")) {
 	return this->resolveFBO (name);
     }
@@ -267,6 +291,15 @@ std::shared_ptr<const TextureProvider> CPass::resolveNamedTexture (const std::st
     return this->getContext ().resolveTexture (name, this->m_renderable.getScene ().getScene ().project);
 }
 
+void CPass::bindMissingTexture (int index) {
+    // WE's missing texture (sub_1400EEF70)
+    const auto it = this->m_textures.find (index);
+    this->m_textures[index] = std::make_shared<TextureChainEntry> (TextureChainEntry {
+	.texture = this->m_renderable.getScene ().getMissingTexture (),
+	.next = it != this->m_textures.end () ? it->second : nullptr,
+    });
+}
+
 std::shared_ptr<const CFBO> CPass::resolveFBO (const std::string& name) const {
     std::shared_ptr<const CFBO> fbo = this->m_fboProvider->find (name);
 
@@ -309,22 +342,32 @@ void CPass::setupRenderFramebuffer () const {
 	} else {
 	    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
 	}
+	glColorMask (true, true, true, true);
 	glClear (GL_COLOR_BUFFER_BIT);
 	glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
     }
 
     glViewport (0, 0, target->getRealWidth (), target->getRealHeight ());
 
-    // the alpha source factor must be GL_ONE, GL_SRC_ALPHA squares every blended pass's alpha and compounds through
-    // chained effects
-    switch (this->getBlendingMode ()) {
+    // D3D11 unbinds a resource that is also the render target, WE reads 0 there (pooled buffer shared with the target).
+    // Not for the scene buffer, WE samples a copy
+    this->m_boundTargetTexture
+	= target == this->m_renderable.getScene ().getFBO () ? GL_NONE : target->getTextureID (0);
+
+    const BlendingMode blending = this->m_scriptBlending.value_or (this->m_blendingmode);
+    const auto depth = this->m_scriptDepth.value_or (
+	this->m_depthState.value_or (std::make_pair (this->m_pass.depthtest, this->m_pass.depthwrite))
+    );
+
+    // WE's blend desc uses the colour factors for alpha too, so translucent leaves alpha squared (sub_140099F60)
+    switch (blending) {
 	case BlendingMode_Translucent:
 	    glEnable (GL_BLEND);
-	    glBlendFuncSeparate (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+	    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
 	    break;
 	case BlendingMode_Additive:
 	    glEnable (GL_BLEND);
-	    glBlendFuncSeparate (GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE);
+	    glBlendFunc (GL_SRC_ALPHA, GL_ONE);
 	    break;
 	// WE's blend state builder (sub_140099F60) turns blending off for normal on every target, the scene's
 	// alpha is masked off anyway, so the pass's RGB replaces what's below regardless of its alpha
@@ -334,13 +377,26 @@ void CPass::setupRenderFramebuffer () const {
 	    break;
     }
 
+    // AlphaToCoverageEnable only matters on the multisampled scene target (sub_140099F60)
+    if (blending == BlendingMode_AlphaToCoverage) {
+	glEnable (GL_SAMPLE_ALPHA_TO_COVERAGE);
+    }
+
+    // no alpha writes onto the scene target unless the material's alphawriting overrides it (sub_140155FC0)
+    const auto& alphaWriting = this->m_pass.alphawriting;
+    glColorMask (
+	true, true, true,
+	alphaWriting == "enabled"
+	    || (alphaWriting != "disabled" && this->m_drawTo != this->m_renderable.getScene ().getFBO ())
+    );
+
     // sub_140099F60 with renderer state flag 0x10: alpha op MAX and all four channels written, the color blend stays
     if (layerTarget != nullptr && layerTarget->alphaMax) {
 	glBlendEquationSeparate (GL_FUNC_ADD, GL_MAX);
 	glColorMask (true, true, true, true);
     }
 
-    switch (this->m_depthState.has_value () ? this->m_depthState->first : this->m_pass.depthtest) {
+    switch (depth.first) {
 	case DepthtestMode_Enabled:
 	    glEnable (GL_DEPTH_TEST);
 	    glDepthFunc (GL_LEQUAL);
@@ -351,7 +407,7 @@ void CPass::setupRenderFramebuffer () const {
 	    break;
     }
 
-    switch (this->m_pass.cullmode) {
+    switch (this->m_scriptCulling.value_or (this->m_pass.cullmode)) {
 	case CullingMode_Normal:
 	    glEnable (GL_CULL_FACE);
 	    // the mirrored reflection pass flips every triangle's winding
@@ -364,7 +420,7 @@ void CPass::setupRenderFramebuffer () const {
 	    break;
     }
 
-    switch (this->m_depthState.has_value () ? this->m_depthState->second : this->m_pass.depthwrite) {
+    switch (depth.second) {
 	case DepthwriteMode_Enabled:
 	    glDepthMask (true);
 	    break;
@@ -377,7 +433,7 @@ void CPass::setupRenderFramebuffer () const {
 
     // WE picks the no-write depth state for translucent and additive blending whatever the material says
     // (sub_140099F60: state index | 1 when the blend mode isn't normal or alphatocoverage)
-    if (this->getBlendingMode () == BlendingMode_Translucent || this->getBlendingMode () == BlendingMode_Additive) {
+    if (blending == BlendingMode_Translucent || blending == BlendingMode_Additive) {
 	glDepthMask (false);
     }
 }
@@ -500,8 +556,13 @@ void CPass::bindTextureUnit (int index, const std::shared_ptr<const TextureProvi
 	this->m_renderable.getScene ().resolveMultisample ();
     }
 
+    const GLuint id = texture->getTextureID (frame);
+
     glActiveTexture (GL_TEXTURE0 + index);
-    glBindTexture (GL_TEXTURE_2D, texture->getTextureID (frame));
+    glBindTexture (
+	GL_TEXTURE_2D,
+	id != GL_NONE && id == this->m_boundTargetTexture ? this->m_renderable.getScene ().getNullTexture () : id
+    );
 }
 
 void CPass::bindTextureOverrides (uint32_t currentTexture, std::shared_ptr<const TextureProvider>& texture0) const {
@@ -645,6 +706,8 @@ void CPass::renderGeometry () const {
 }
 
 void CPass::cleanupRenderSetup () {
+    glDisable (GL_SAMPLE_ALPHA_TO_COVERAGE);
+
     if (this->m_cleanupAttribsCallback) {
 	this->m_cleanupAttribsCallback ();
     } else {
@@ -684,8 +747,10 @@ void CPass::render () {
     this->refreshRenderableUniforms ();
 
     if (this->m_pass.shader == XRAY_EFFECT_SHADER) {
-	const bool fullReveal = this->getContext ().getApp ().getContext ().state.xray.fullReveal;
-	this->m_xrayFullReveal = fullReveal ? 1.0f : 0.0f;
+	const auto mode = this->getContext ().getApp ().getContext ().state.xray.mode;
+	this->m_xrayReveal = mode == Application::XrayMode::Full ? 1.0f
+	    : mode == Application::XrayMode::Disabled            ? 0.0f
+								 : -1.0f;
     }
 
     const auto& debug = this->getContext ().getApp ().getContext ().settings.render.debug;
@@ -796,6 +861,7 @@ void CPass::clearDestination () const {
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_drawTo->getFramebuffer ());
     glViewport (0, 0, this->m_drawTo->getRealWidth (), this->m_drawTo->getRealHeight ());
     glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
+    glColorMask (true, true, true, true);
     glClear (GL_COLOR_BUFFER_BIT);
     glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
 }
@@ -928,56 +994,56 @@ void CPass::setGeometryCallback (
     this->m_cleanupAttribsCallback = std::move (cleanupAttribs);
 }
 
-GLuint CPass::compileShader (const char* shader, GLuint type) {
-    const GLuint shaderID = glCreateShader (type);
+namespace {
+// Mesa mis-reads a vec3 uniform followed by a float used as vec4(vec3, float), use g_Color4
+std::string patchColorAlpha (const std::string& shader) {
+    std::string patched = shader;
 
-    // Mesa mis-reads a vec3 uniform followed by a float used as vec4(vec3, float), use the g_Color4 the engine already
-    // exposes
-    std::string patched;
-
-    if (type == GL_FRAGMENT_SHADER) {
-	patched = shader;
-
-	const std::string declarations = "uniform vec3 g_Color;\nuniform float g_Alpha;";
-	const std::string construction = "vec4(g_Color, g_Alpha)";
-	const auto declarationsAt = patched.find (declarations);
-	const auto constructionAt = patched.find (construction);
-
-	if (declarationsAt != std::string::npos && constructionAt != std::string::npos) {
-	    patched.replace (constructionAt, construction.size (), "g_Color4");
-	    patched.replace (declarationsAt, declarations.size (), "uniform vec4 g_Color4;");
-
-	    // only safe when that was the sole use of both
-	    // the generated source keeps the original as an "#if 0" block at the end, that doesn't count
-	    const size_t codeEnd = std::min (patched.size (), patched.find ("#if 0"));
-	    const auto stillUsed = [&patched, codeEnd] (const std::string& name) {
-		size_t pos = 0;
-
-		while ((pos = patched.find (name, pos)) != std::string::npos && pos < codeEnd) {
-		    const bool wordStart = pos == 0
-			|| !(std::isalnum (static_cast<unsigned char> (patched[pos - 1])) || patched[pos - 1] == '_');
-		    const size_t end = pos + name.size ();
-		    const bool wordEnd = end >= patched.size ()
-			|| !(std::isalnum (static_cast<unsigned char> (patched[end])) || patched[end] == '_');
-
-		    if (wordStart && wordEnd) {
-			return true;
-		    }
+    const std::string declarations = "uniform vec3 g_Color;\nuniform float g_Alpha;";
+    const std::string construction = "vec4(g_Color, g_Alpha)";
+    const auto declarationsAt = patched.find (declarations);
+    const auto constructionAt = patched.find (construction);
 
-		    pos = end;
-		}
+    if (declarationsAt == std::string::npos || constructionAt == std::string::npos) {
+	return patched;
+    }
+
+    patched.replace (constructionAt, construction.size (), "g_Color4");
+    patched.replace (declarationsAt, declarations.size (), "uniform vec4 g_Color4;");
+
+    // only safe when that was the sole use of both, the trailing "#if 0" copy doesn't count
+    const size_t codeEnd = std::min (patched.size (), patched.find ("#if 0"));
+    const auto stillUsed = [&patched, codeEnd] (const std::string& name) {
+	size_t pos = 0;
 
-		return false;
-	    };
+	while ((pos = patched.find (name, pos)) != std::string::npos && pos < codeEnd) {
+	    const bool wordStart = pos == 0
+		|| !(std::isalnum (static_cast<unsigned char> (patched[pos - 1])) || patched[pos - 1] == '_');
+	    const size_t end = pos + name.size ();
+	    const bool wordEnd = end >= patched.size ()
+		|| !(std::isalnum (static_cast<unsigned char> (patched[end])) || patched[end] == '_');
 
-	    if (stillUsed ("g_Color") || stillUsed ("g_Alpha")) {
-		patched = shader;
+	    if (wordStart && wordEnd) {
+		return true;
 	    }
+
+	    pos = end;
 	}
 
-	shader = patched.c_str ();
+	return false;
+    };
+
+    if (stillUsed ("g_Color") || stillUsed ("g_Alpha")) {
+	return shader;
     }
 
+    return patched;
+}
+} // namespace
+
+GLuint CPass::compileShader (const char* shader, GLuint type) {
+    const GLuint shaderID = glCreateShader (type);
+
     glShaderSource (shaderID, 1, &shader, nullptr);
     glCompileShader (shaderID);
 
@@ -1019,7 +1085,9 @@ void CPass::setupShaders () {
 	return combo != this->m_combos.end () && combo->second != 0;
     };
 
-    if (comboEnabled ("LIGHTING") || comboEnabled ("REFLECTION")) {
+    // a lit layer drawn straight onto the scene overrides this off
+    if ((comboEnabled ("LIGHTING") || comboEnabled ("REFLECTION"))
+	&& !this->m_override.combos.contains ("PRELIGHTING")) {
 	this->m_combos.insert_or_assign ("PRELIGHTING", 1);
     }
 
@@ -1149,11 +1217,11 @@ void CPass::setupShaders () {
     std::string fragment = this->m_compiled->fragment;
 
     if (shaderName == XRAY_EFFECT_SHADER) {
-	this->m_xrayFullRevealPatched = patchXrayFullRevealBypass (fragment);
+	this->m_xrayRevealPatched = patchXrayRevealOverride (fragment);
 
-	if (!this->m_xrayFullRevealPatched) {
+	if (!this->m_xrayRevealPatched) {
 	    sLog.error (
-		"Full xray toggle unavailable: couldn't find the expected reveal blend line in the "
+		"Full/disabled xray unavailable: couldn't find the expected reveal blend line in the "
 		"compiled effects/xray shader (spirv-cross output format may have changed)"
 	    );
 	}
@@ -1275,8 +1343,20 @@ bool CPass::releaseSharedProgram () {
 }
 
 GLuint CPass::linkProgram (
-    const std::string& vertex, const std::string& fragment, const std::string& geometry, const std::string& shaderName
+    const std::string& vertex, const std::string& unpatchedFragment, const std::string& geometry,
+    const std::string& shaderName
 ) {
+    const std::string fragment = patchColorAlpha (unpatchedFragment);
+    auto& cache = Shaders::ShaderCache::get ();
+    const std::string cacheKey = vertex + '\0' + fragment + '\0' + geometry;
+
+    if (const GLuint cached = cache.loadProgram (cacheKey); cached != 0) {
+#if !NDEBUG
+	glObjectLabel (GL_PROGRAM, cached, -1, shaderName.c_str ());
+#endif /* DEBUG */
+	return cached;
+    }
+
     const GLuint vertexShaderID = compileShader (vertex.c_str (), GL_VERTEX_SHADER);
     const GLuint fragmentShaderID = compileShader (fragment.c_str (), GL_FRAGMENT_SHADER);
     const GLuint geometryShaderID = geometry.empty () ? 0 : compileShader (geometry.c_str (), GL_GEOMETRY_SHADER);
@@ -1286,6 +1366,9 @@ GLuint CPass::linkProgram (
     if (geometryShaderID != 0) {
 	glAttachShader (program, geometryShaderID);
     }
+    if (cache.programsSupported ()) {
+	glProgramParameteri (program, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
+    }
     glLinkProgram (program);
     GLint result = GL_FALSE;
     int infoLogLength = 0;
@@ -1323,6 +1406,8 @@ GLuint CPass::linkProgram (
 	glDeleteShader (geometryShaderID);
     }
 
+    cache.storeProgram (cacheKey, program);
+
     return program;
 }
 
@@ -1439,6 +1524,7 @@ void CPass::setupTextureUniforms () {
 		"Cannot resolve texture '", textureName, "' (index=", index,
 		", object id=", this->m_renderable.getId (), ") for fragment shader ", ex.what ()
 	    );
+	    this->bindMissingTexture (index);
 	}
     }
 
@@ -1462,6 +1548,7 @@ void CPass::setupTextureUniforms () {
 		"Cannot resolve texture '", textureName, "' (index=", index,
 		", object id=", this->m_renderable.getId (), ") for pass ", ex.what ()
 	    );
+	    this->bindMissingTexture (index);
 	}
     }
 
@@ -1498,6 +1585,16 @@ void CPass::setupTextureUniforms () {
 
     // override any texture
     for (const auto& [index, textureName] : this->m_override.textures) {
+	// WE writes every bound FBO into its slot on each draw (sub_1401EBF60), so overrides there are never sampled
+	if (const auto bind = this->m_binds.find (index); bind != this->m_binds.end () && bind->second != "previous") {
+	    continue;
+	}
+
+	// same for slot 0 of a pass without binds (3736099508)
+	if (index == 0 && this->m_binds.empty ()) {
+	    continue;
+	}
+
 	try {
 	    auto texture = this->resolveNamedTexture (textureName);
 
@@ -1640,8 +1737,8 @@ void CPass::setupUniforms () {
     const auto& recorder = this->m_renderable.getScene ().getAudioContext ().getRecorder ();
 
     // lighting variables
-    this->addUniform ("g_LightAmbientColor", sceneData.colors.ambient->value->getVec3 ());
-    this->addUniform ("g_LightSkylightColor", sceneData.colors.skylight->value->getVec3 ());
+    this->addUniform ("g_LightAmbientColor", &sceneData.colors.ambient->value->getVec3 ());
+    this->addUniform ("g_LightSkylightColor", &sceneData.colors.skylight->value->getVec3 ());
     this->addUniform ("g_LightsPosition", UniformType::Vector3, scene.getLightsPosition (), 4);
     this->addUniform ("g_LightsColorPremultiplied", UniformType::Vector4, scene.getLightsColorPremultiplied (), 3);
     this->addUniform ("g_LightsColorRadius", UniformType::Vector4, scene.getLightsColorRadius (), 4);
@@ -1722,8 +1819,8 @@ void CPass::setupUniforms () {
     this->addUniform ("g_ParallaxPosition", scene.getParallaxPosition ());
     this->addUniform ("g_EffectTextureProjectionMatrix", &this->m_effectTextureProjectionMatrix);
     this->addUniform ("g_EffectTextureProjectionMatrixInverse", &this->m_effectTextureProjectionMatrixInverse);
-    this->addUniform ("g_TexelSize", glm::vec2 (1.0 / scene.getWidth (), 1.0 / scene.getHeight ()));
-    this->addUniform ("g_TexelSizeHalf", glm::vec2 (0.5 / scene.getWidth (), 0.5 / scene.getHeight ()));
+    this->addUniform ("g_TexelSize", scene.getTexelSize ());
+    this->addUniform ("g_TexelSizeHalf", scene.getTexelSizeHalf ());
     this->addUniform ("g_AudioSpectrum16Left", recorder.audio16, 16);
     this->addUniform ("g_AudioSpectrum16Right", recorder.audio16 + 16, 16);
     this->addUniform ("g_AudioSpectrum32Left", recorder.audio32, 32);
@@ -1821,6 +1918,18 @@ int componentCount (GLenum type) {
 }
 } // namespace
 
+int CPass::getMaterialConstantSize (const std::string& name) const {
+    const ShaderVariable* var = this->m_materialConstants.contains (name) ? this->findActiveParameter (name) : nullptr;
+
+    return var == nullptr ? 0 : componentCount (*var);
+}
+
+bool CPass::isMaterialConstantInDegrees (const std::string& name) const {
+    const ShaderVariable* var = this->m_materialConstants.contains (name) ? this->findActiveParameter (name) : nullptr;
+
+    return var != nullptr && var->isInDegrees ();
+}
+
 void CPass::setupShaderVariables () {
     // a uniform declared differently per stage takes the linked program's type
     for (const auto& cur : this->m_shader->getVertex ().getParameters ()) {
@@ -1847,6 +1956,15 @@ void CPass::setupShaderVariables () {
 	}
     }
 
+    // shader defaults as scripts see them
+    for (const auto* unit : { &this->m_shader->getVertex (), &this->m_shader->getFragment () }) {
+	for (const auto* cur : unit->getParameters ()) {
+	    if (!cur->getIdentifierName ().empty () && this->m_uniforms.contains (cur->getName ())) {
+		this->m_materialConstants.try_emplace (cur->getIdentifierName (), cur);
+	    }
+	}
+    }
+
     // 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) {
@@ -1858,13 +1976,110 @@ void CPass::setupShaderVariables () {
 
 	    this->addConstantUniform (var, *value);
 	    this->m_constantUniforms.insert (var->getName ());
+
+	    if (this->m_materialConstants.contains (name)) {
+		this->m_materialConstants[name] = value->value.get ();
+	    }
 	}
     }
 
-    // bind the full-reveal bypass uniform injected by patchXrayFullRevealBypass() (see setupShaders());
-    // a no-op if the patch didn't find its anchors, since the uniform then doesn't exist in the shader
+    // no-op when patchXrayRevealOverride() didn't find its anchors
     if (this->m_pass.shader == XRAY_EFFECT_SHADER) {
-	this->addUniform ("g_XrayFullReveal", &this->m_xrayFullReveal);
+	this->addUniform ("g_XrayReveal", &this->m_xrayReveal);
+    }
+}
+
+std::vector<std::string> CPass::getMaterialConstantNames () const {
+    std::vector<std::pair<std::string, std::string>> byUniform;
+
+    for (const auto& name : this->m_materialConstants | std::views::keys) {
+	if (const auto* var = this->findActiveParameter (name)) {
+	    byUniform.emplace_back (var->getName (), name);
+	}
+    }
+
+    std::ranges::sort (byUniform, std::greater {});
+    std::vector<std::string> names;
+
+    for (const auto& name : byUniform | std::views::values) {
+	names.push_back (name);
+    }
+
+    return names;
+}
+
+const DynamicValue* CPass::getMaterialConstant (const std::string& name) const {
+    const auto it = this->m_materialConstants.find (name);
+
+    return it == this->m_materialConstants.end () ? nullptr : it->second;
+}
+
+DynamicValue* CPass::getScriptConstant (const std::string& name) {
+    if (const auto it = this->m_scriptConstants.find (name); it != this->m_scriptConstants.end ()) {
+	return it->second.get ();
+    }
+
+    ShaderVariable* var = this->findActiveParameter (name);
+    const DynamicValue* current = this->getMaterialConstant (name);
+
+    if (var == nullptr || current == nullptr) {
+	return nullptr;
+    }
+
+    // typed like the uniform (sub_140154480), vectors get padded
+    const bool scalar = current->getType () == DynamicValue::Float || current->getType () == DynamicValue::Int;
+    const glm::vec4 value = scalar ? glm::vec4 (current->getFloat (), 0.0f, 0.0f, 0.0f) : current->getVec4 ();
+    std::unique_ptr<DynamicValue> copy;
+
+    if (var->is<ShaderVariableVector2> ()) {
+	copy = std::make_unique<DynamicValue> (glm::vec2 (value));
+    } else if (var->is<ShaderVariableVector3> ()) {
+	copy = std::make_unique<DynamicValue> (glm::vec3 (value));
+    } else if (var->is<ShaderVariableVector4> ()) {
+	copy = std::make_unique<DynamicValue> (value);
+    } else {
+	copy = std::make_unique<DynamicValue> (current->getFloat ());
+    }
+
+    auto* result = copy.get ();
+    this->addUniform (var, result);
+    this->m_constantUniforms.insert (var->getName ());
+    this->m_materialConstants[name] = result;
+    this->m_scriptConstants.emplace (name, std::move (copy));
+    return result;
+}
+
+void CPass::setScriptMaterialState (
+    const BlendingMode blending, const std::pair<DepthtestMode, DepthwriteMode> depth, const CullingMode culling
+) {
+    this->m_scriptBlending = blending;
+    this->m_scriptDepth = depth;
+    this->m_scriptCulling = culling;
+}
+
+CPass::ScriptState CPass::getScriptState () const {
+    ScriptState state {
+	.blending = this->m_scriptBlending,
+	.depth = this->m_scriptDepth,
+	.culling = this->m_scriptCulling,
+    };
+
+    for (const auto& [name, value] : this->m_scriptConstants) {
+	state.constants.emplace (name, *value);
+    }
+
+    return state;
+}
+
+void CPass::restoreScriptState (const ScriptState& state) {
+    this->m_scriptBlending = state.blending;
+    this->m_scriptDepth = state.depth;
+    this->m_scriptCulling = state.culling;
+
+    for (const auto& [name, value] : state.constants) {
+	if (auto* target = this->getScriptConstant (name)) {
+	    target->update (value, DynamicValue::UpdateSource::Script);
+	}
     }
 }
 

+ 37 - 5
src/WallpaperEngine/Render/Objects/Effects/CPass.h

@@ -1,6 +1,7 @@
 #pragma once
 
 #include <deque>
+#include <map>
 #include <set>
 #include <unordered_map>
 
@@ -80,7 +81,32 @@ public:
     [[nodiscard]] BlendingMode getBlendingMode () const;
     /** Depth test and write taken from another material instead of this pass's own, nullopt to drop it */
     void setDepthState (std::optional<std::pair<DepthtestMode, DepthwriteMode>> state);
+
+    /** What IMaterial writes put on the pass, above the layer's own blending/depth setup */
+    struct ScriptState {
+	std::optional<BlendingMode> blending;
+	std::optional<std::pair<DepthtestMode, DepthwriteMode>> depth;
+	std::optional<CullingMode> culling;
+	std::map<std::string, DynamicValue> constants;
+    };
+    void
+    setScriptMaterialState (BlendingMode blending, std::pair<DepthtestMode, DepthwriteMode> depth, CullingMode culling);
+    [[nodiscard]] ScriptState getScriptState () const;
+    /** Carries a previous pass's script writes over to this one, after the layer set its passes up again */
+    void restoreScriptState (const ScriptState& state);
+
+    /** Uniforms with a "material" name (sub_140154480), last to first like WE lists them */
+    [[nodiscard]] std::vector<std::string> getMaterialConstantNames () const;
+    /** script, effect override, material or shader default; nullptr without one */
+    [[nodiscard]] const DynamicValue* getMaterialConstant (const std::string& name) const;
+    /** 1 float, 2 to 4 vectors */
+    [[nodiscard]] int getMaterialConstantSize (const std::string& name) const;
+    /** rad2deg: scripts use degrees (sub_140154480) */
+    [[nodiscard]] bool isMaterialConstantInDegrees (const std::string& name) const;
+    /** The pass gets its own copy on the first script write */
+    [[nodiscard]] DynamicValue* getScriptConstant (const std::string& name);
     [[nodiscard]] std::shared_ptr<const CFBO> resolveFBO (const std::string& name) const;
+    void bindMissingTexture (int index);
     [[nodiscard]] std::shared_ptr<const TextureProvider> resolveNamedTexture (const std::string& name) const;
 
     [[nodiscard]] std::shared_ptr<const FBOProvider> getFBOProvider () const;
@@ -283,8 +309,16 @@ private:
     bool m_keepDestination = false;
     bool m_followLayerTarget = false;
     bool m_neutralColor = false;
+    /** treated as unbound by bindTextureUnit */
+    mutable GLuint m_boundTargetTexture = GL_NONE;
     // uniforms the pass sets as material or override constants, the renderable values leave these alone
     std::set<std::string> m_constantUniforms;
+    // plus the copies scripts wrote
+    std::map<std::string, const DynamicValue*> m_materialConstants;
+    std::map<std::string, std::unique_ptr<DynamicValue>> m_scriptConstants;
+    std::optional<BlendingMode> m_scriptBlending = std::nullopt;
+    std::optional<std::pair<DepthtestMode, DepthwriteMode>> m_scriptDepth = std::nullopt;
+    std::optional<CullingMode> m_scriptCulling = std::nullopt;
     // zero-padded constants, a deque so the uniform pointers stay valid
     std::deque<glm::vec4> m_paddedConstants;
     std::map<std::string, ReferenceUniformEntry*> m_referenceUniforms = {};
@@ -309,11 +343,9 @@ private:
     glm::mat4 m_layerModelViewProjectionInverse = glm::mat4 (1.0f);
     glm::mat4 m_layerViewProjection = glm::mat4 (1.0f);
 
-    // full xray support: 0.0/1.0 fed to the g_XrayFullReveal uniform injected by patchXrayFullRevealBypass(),
-    // updated each frame from state.xray.fullReveal (see render()); m_xrayFullRevealPatched records whether
-    // that injection actually found its anchors in the compiled shader, for diagnostics
-    float m_xrayFullReveal = 0.0f;
-    bool m_xrayFullRevealPatched = false;
+    // g_XrayReveal: -1 follow mouse, 1 full, 0 disabled
+    float m_xrayReveal = -1.0f;
+    bool m_xrayRevealPatched = false;
 
     std::map<int, std::shared_ptr<TextureChainEntry>> m_textures = {};
     /** Textures that got their usage count bumped by this pass (starts video playback), released on destruction */

+ 57 - 33
src/WallpaperEngine/Render/Objects/PuppetClipping.cpp

@@ -181,13 +181,9 @@ PuppetClipping::read (const std::vector<char>& data, size_t offset, int version,
     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;
-    }
-
+void PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
     constexpr uint32_t Target = 0x1;
+    constexpr uint32_t AtTargetsTarget = 0x4;
     constexpr uint32_t Source = 0x8;
 
     const auto partCount = static_cast<int> (this->parts.size ());
@@ -228,8 +224,17 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	for (const auto part : record.sources) {
 	    partFlags[part] |= Source;
 	}
+
+	if (record.flags & AtTargets) {
+	    for (const auto part : record.targets) {
+		partFlags[part] |= AtTargetsTarget;
+	    }
+	}
     }
 
+    // last record naming a part as a target
+    std::map<uint32_t, uint32_t> targetRecord;
+
     struct Entry {
 	uint32_t record = 0;
 	int firstTarget = INT_MAX;
@@ -251,6 +256,7 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	    if ((partFlags[part] & Target) && contains (record.targets, part)) {
 		entry.targets.push_back (part);
 		entry.firstTarget = std::min (entry.firstTarget, part);
+		targetRecord[part] = static_cast<uint32_t> (index);
 	    }
 
 	    if (contains (record.sources, part)) {
@@ -316,6 +322,31 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	pending.clear ();
     };
 
+    // sub_14020CAB0
+    const auto drawMasked = [&] (const Entry& entry, const std::vector<uint32_t>& targets) {
+	std::vector<int> chain;
+	for (int parent = records[entry.record].parent; parent != -1; parent = records[parent].parent) {
+	    chain.push_back (parent);
+	}
+
+	maskDraws[entry.record] = addDraw (entry.maskParts);
+	addDraw (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));
+    };
+
     for (int part = 0; part < partCount; part++) {
 	const uint32_t flags = partFlags[part];
 
@@ -323,46 +354,39 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	    if (!hiddenSources.contains (part)) {
 		pending.push_back (part);
 	    }
-	} else if (!(flags & Source)) {
+	} else if (!(flags & (Source | AtTargetsTarget))) {
 	    // drawn with its record
 	    continue;
 	}
 
-	if (!(flags & Source)) {
-	    continue;
-	}
+	if (flags & Source) {
+	    for (const auto& entry : entries) {
+		if ((records[entry.record].flags & AtTargets) || entry.lastSource != part) {
+		    continue;
+		}
 
-	for (const auto& entry : entries) {
-	    if (entry.lastSource != part) {
+		flush ();
+		drawMasked (entry, entry.targets);
+	    }
+	} else if (flags & AtTargetsTarget) {
+	    // WE's loop (0x14020c2a0) looks up the first part every step, so every later part joins and draws again
+	    const auto found = targetRecord.find (part);
+	    if (found == targetRecord.end ()) {
 		continue;
 	    }
 
-	    flush ();
-
-	    std::vector<int> chain;
-	    for (int parent = records[entry.record].parent; parent != -1; parent = records[parent].parent) {
-		chain.push_back (parent);
+	    std::vector<uint32_t> targets;
+	    for (int later = part; later < partCount; later++) {
+		targets.push_back (later);
 	    }
 
-	    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]);
-		}
+	    const auto entry = std::ranges::find (entries, found->second, &Entry::record);
+	    if (entry != entries.end ()) {
+		flush ();
+		drawMasked (*entry, targets);
 	    }
-
-	    this->commands.push_back (static_cast<int> (entry.record));
 	}
     }
 
     flush ();
-    return true;
 }

+ 1 - 3
src/WallpaperEngine/Render/Objects/PuppetClipping.h

@@ -19,7 +19,6 @@ struct PuppetClipping {
 	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,
     };
 
@@ -66,8 +65,7 @@ struct PuppetClipping {
     /** Only the part ranges (MDLV 21+), what the animated draw order sorts */
     static std::vector<Part> readParts (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);
+    void build (const std::vector<uint16_t>& meshIndices);
 
     std::vector<Part> parts;
     /** parts in drawing order (indices into parts), file order unless the draw order animates; build () walks it */

+ 1 - 1
src/WallpaperEngine/Render/Objects/PuppetIK.cpp

@@ -393,7 +393,7 @@ bool PuppetRopeEnvironment::windAt (const glm::vec3& position, glm::vec3& force)
 	return false;
     }
 
-    // zero width gives NaN noise in WE, which maxes to 0
+    // zero width: every simplex corner fails in WE (sub_140198910)
     float noise = 0.0f;
 
     if (this->width > 0.0f) {

+ 154 - 14
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -6,6 +6,7 @@
 #include <cstring>
 #include <limits>
 #include <set>
+#include <string_view>
 #include <strings.h>
 #include <utility>
 
@@ -144,6 +145,7 @@ struct PuppetBoneSet {
     uint32_t extraCount = 0;
     uint32_t constraintCount = 0;
     std::vector<int> drawOrder;
+    std::vector<int> hitOrder;
     std::vector<PuppetExtra> extras;
     PuppetIKRig ik;
 };
@@ -312,7 +314,6 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     result.constraintCount = constraintCount;
 
     // sub_140261880 goes on with two more blocks before the per bone collision capsules
-    const auto skip = [&reader] (std::streamoff bytes) { reader.base ().seekg (bytes, std::ios::cur); };
     const auto nextUInt16 = [&reader] () {
 	uint16_t value = 0;
 	reader.next (reinterpret_cast<char*> (&value), sizeof (value));
@@ -408,14 +409,17 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
 	parsePuppetCapsules (reader, result, nextSectionOffset);
     }
 
-    // then a flag byte and a per bone int (kept below the bone count, consumer not traced) and from MDLS v3 another
-    // flag byte and the bones' draw order
+    // flag byte + cursor box test order (sub_1401FD690), MDLS v3+ another flag byte + bone draw order
     const auto atEnd = [&reader, nextSectionOffset] () {
 	return !reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset;
     };
 
     if (!atEnd () && reader.next () != 0) {
-	skip (static_cast<std::streamoff> (sizeof (uint32_t) * result.bones.size ()));
+	result.hitOrder.resize (result.bones.size ());
+
+	for (int& bone : result.hitOrder) {
+	    bone = static_cast<int> (std::min<uint32_t> (reader.nextUInt32 (), result.bones.size () - 1));
+	}
     }
 
     if (version >= 3 && !atEnd () && reader.next () != 0) {
@@ -429,6 +433,7 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
 	reader.base ().clear ();
 	result.drawOrder.clear ();
+	result.hitOrder.clear ();
     }
 
     return result;
@@ -769,7 +774,12 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	}
 
 	if (version >= 5 && valid) {
-	    reader.base ().seekg (sizeof (uint32_t) * 6, std::ios::cur);
+	    for (int axis = 0; axis < 3; axis++) {
+		clip.boundsMin[axis] = reader.nextFloat ();
+	    }
+	    for (int axis = 0; axis < 3; axis++) {
+		clip.boundsMax[axis] = reader.nextFloat ();
+	    }
 	}
 
 	// a flag byte and one float track per bone, the bones' draw order offsets (clip +264)
@@ -934,6 +944,7 @@ 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->boneHitOrder = std::move (boneSet.hitOrder);
     this->boneModel = worldBind;
     this->bindModel = worldBind;
     this->extras = boneSet.extras;
@@ -968,6 +979,20 @@ void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t
 	    this->attachmentPoints = std::move (attachmentSet.points);
 	} else if (tag == "MDMP") {
 	    this->morphSection = offset;
+	} else if (tag == "MDLE" && std::string_view (data.data () + offset, 8) == "MDLE0002") {
+	    // skipped byte size, then a row-major matrix per bone
+	    const size_t matrices = offset + 17;
+	    if (matrices + this->bones.size () * 64 <= data.size ()) {
+		this->layerImageBindLocal.resize (this->bones.size ());
+		for (size_t bone = 0; bone < this->bones.size (); bone++) {
+		    float m[16];
+		    std::memcpy (m, data.data () + matrices + bone * 64, sizeof (m));
+		    this->layerImageBindLocal[bone] = glm::mat4 (
+			m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14],
+			m[15]
+		    );
+		}
+	    }
 	} else if (tag == "MDLA") {
 	    this->clips = parsePuppetAnimationClips (
 		reader, offset, static_cast<uint32_t> (this->bones.size ()), boneSet, meshCount
@@ -1019,6 +1044,29 @@ std::vector<glm::mat4> PuppetRig::skinMatrices () const {
     return skin;
 }
 
+bool PuppetRig::clipBounds (glm::vec3& min, glm::vec3& max) const {
+    glm::vec3 lower (std::numeric_limits<float>::max ());
+    glm::vec3 upper (-std::numeric_limits<float>::max ());
+    bool found = false;
+
+    for (const auto& layer : this->layers) {
+	if (layer.layer == nullptr || !layer.layer->visible->value->getBool ()) {
+	    continue;
+	}
+
+	found = found || layer.clip.boundsMax.x > layer.clip.boundsMin.x;
+	lower = glm::min (lower, layer.clip.boundsMin);
+	upper = glm::max (upper, layer.clip.boundsMax);
+    }
+
+    if (found) {
+	min = lower;
+	max = upper;
+    }
+
+    return found;
+}
+
 PuppetActiveAnimation* PuppetRig::findLayer (size_t serial) {
     const auto it = std::ranges::find (this->layers, serial, &PuppetActiveAnimation::serial);
 
@@ -1178,17 +1226,11 @@ bool PuppetRig::destroyLayersByName (const std::string& name) {
 	return false;
     }
 
-    return std::erase_if (
-	       this->layers, [&name] (const PuppetActiveAnimation& layer) { return layer.layer->name == name; }
-	   )
-	> 0;
+    return this->removeLayers ([&name] (const PuppetActiveAnimation& layer) { return layer.layer->name == name; }) > 0;
 }
 
 bool PuppetRig::destroyLayer (size_t serial) {
-    return std::erase_if (
-	       this->layers, [serial] (const PuppetActiveAnimation& layer) { return layer.serial == serial; }
-	   )
-	> 0;
+    return this->removeLayers ([serial] (const PuppetActiveAnimation& layer) { return layer.serial == serial; }) > 0;
 }
 
 // sub_1401FDF90, after the pose: a layer that ended runs its ended callbacks, a playSingleAnimation() one is removed
@@ -1208,11 +1250,41 @@ void PuppetRig::finishEndedLayers (const std::function<void (size_t)>& dispatch)
 	dispatch (serial);
     }
 
-    std::erase_if (this->layers, [&ended] (const PuppetActiveAnimation& layer) {
+    this->removeLayers ([&ended] (const PuppetActiveAnimation& layer) {
 	return layer.autoRemove && std::ranges::find (ended, layer.serial) != ended.end ();
     });
 }
 
+size_t PuppetRig::removeLayers (const std::function<bool (const PuppetActiveAnimation&)>& predicate) {
+    const auto removed = std::ranges::stable_partition (this->layers, std::not_fn (predicate));
+    const auto count = static_cast<size_t> (std::ranges::distance (removed));
+
+    for (auto& layer : removed) {
+	if (layer.ownedLayer != nullptr) {
+	    this->removedLayers.push_back (std::move (layer));
+	}
+    }
+
+    this->layers.erase (removed.begin (), removed.end ());
+    return count;
+}
+
+std::vector<glm::mat4> PuppetRig::layerImageBindModel () const {
+    const bool own = this->layerImageBindLocal.size () == this->bones.size ();
+    std::vector<glm::mat4> result (this->bones.size (), glm::mat4 (1.0f));
+
+    // a parent listed later is still unset, WE reads it uninitialised
+    for (size_t i = 0; i < this->bones.size (); i++) {
+	const glm::mat4& local = own ? this->layerImageBindLocal[i] : this->bones[i].bindLocal;
+	const int parent = this->bones[i].parent;
+	result[i] = parent >= 0 && static_cast<size_t> (parent) < result.size () ? result[parent] * local : local;
+    }
+
+    return result;
+}
+
+std::vector<PuppetActiveAnimation> PuppetRig::takeRemovedLayers () { return std::exchange (this->removedLayers, {}); }
+
 void PuppetRig::updateMorphWeights (const std::vector<PuppetLayerSample>& samples) {
     // sub_14021C480: every mesh's weights start at zero each frame, then the layers apply theirs in order. A layer at
     // full weight sets them (a weight of about 0 switches the target off), additive ones add theirs kept between
@@ -1881,6 +1953,74 @@ std::optional<glm::mat4> PuppetRig::attachmentMatrix (int index) const {
 
 const glm::mat4& PuppetRig::getBoneTransform (int bone) const { return this->boneScene[bone]; }
 
+namespace {
+// sub_1401853C0, no t >= 0 check
+bool lineHitsBox (const glm::vec3& origin, const glm::vec3& direction, const glm::vec3& extents, float& enter) {
+    float leave = std::numeric_limits<float>::max ();
+    enter = std::numeric_limits<float>::lowest ();
+
+    for (int axis = 0; axis < 3; axis++) {
+	const float a = (extents[axis] - origin[axis]) / direction[axis];
+	const float b = (-extents[axis] - origin[axis]) / direction[axis];
+
+	enter = std::max (enter, std::min (a, b));
+	leave = std::min (leave, std::max (a, b));
+    }
+
+    return leave >= enter;
+}
+} // namespace
+
+std::string PuppetRig::hitBoxName (int bone) const {
+    return this->bones[bone].name.empty () ? std::to_string (bone) : this->bones[bone].name;
+}
+
+std::optional<std::string> PuppetRig::imageHitBox (const glm::vec3& origin, const glm::vec3& direction) const {
+    if (!this->hasPose () || this->boneHitOrder.empty () || !this->bones.front ().hasCapsule) {
+	return std::nullopt;
+    }
+
+    for (auto it = this->boneHitOrder.rbegin (); it != this->boneHitOrder.rend (); ++it) {
+	const int bone = *it;
+	const glm::mat4 toBox = glm::inverse (this->boneScene[bone] * this->bones[bone].capsule);
+	const glm::vec3 localOrigin = toBox * glm::vec4 (origin, 1.0f);
+	const glm::vec3 localDirection = glm::normalize (glm::vec3 (toBox * glm::vec4 (direction, 0.0f)));
+	float enter;
+
+	if (lineHitsBox (localOrigin, localDirection, this->bones[bone].capsuleExtents, enter)) {
+	    return this->hitBoxName (bone);
+	}
+    }
+
+    return std::nullopt;
+}
+
+std::optional<std::string> PuppetRig::modelHitBox (
+    const glm::vec3& origin, const glm::vec3& direction, const glm::mat4& objectWorld, glm::vec3& local
+) const {
+    if (this->bones.empty () || !this->bones.front ().hasCapsule || this->boneModel.size () != this->bones.size ()) {
+	return std::nullopt;
+    }
+
+    std::optional<std::string> name;
+    float nearest = std::numeric_limits<float>::max ();
+
+    for (size_t bone = 0; bone < this->bones.size (); bone++) {
+	const glm::mat4 toBox = glm::inverse (objectWorld * this->boneModel[bone] * this->bones[bone].capsule);
+	const glm::vec3 localOrigin = toBox * glm::vec4 (origin, 1.0f);
+	const glm::vec3 localDirection = glm::normalize (glm::vec3 (toBox * glm::vec4 (direction, 0.0f)));
+	float enter;
+
+	if (lineHitsBox (localOrigin, localDirection, this->bones[bone].capsuleExtents, enter) && enter < nearest) {
+	    nearest = enter;
+	    local = localOrigin + localDirection * enter;
+	    name = this->hitBoxName (static_cast<int> (bone));
+	}
+    }
+
+    return name;
+}
+
 void PuppetRig::setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld) {
     // sub_14020F350: only this bone, its children keep their matrices until the next update
     this->boneScene[bone] = transform;

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

@@ -95,6 +95,9 @@ struct PuppetAnimationClip {
     std::vector<std::vector<float>> blendTracks;
     /** clip +288 */
     std::vector<PuppetClipEvent> events;
+    /** MDLA v5 clip box */
+    glm::vec3 boundsMin = glm::vec3 (0.0f);
+    glm::vec3 boundsMax = glm::vec3 (0.0f);
 
     /** a morph target's weight over the clip, one sample per frame like the bone tracks */
     struct MorphTrack {
@@ -221,6 +224,8 @@ public:
     );
     bool destroyLayersByName (const std::string& name);
     bool destroyLayer (size_t serial);
+    /** Created layers removed since the last call, alive until their property scripts are dropped */
+    std::vector<PuppetActiveAnimation> takeRemovedLayers ();
     /** 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 */
@@ -256,6 +261,13 @@ public:
      *  sub_140224970); nothing for an index out of range or before the bones exist */
     [[nodiscard]] std::optional<glm::mat4> attachmentMatrix (int index) const;
     [[nodiscard]] const glm::mat4& getBoneTransform (int bone) const;
+    /** sub_1401FD690: first bone box in reverse hit order, name or index */
+    [[nodiscard]] std::optional<std::string> imageHitBox (const glm::vec3& origin, const glm::vec3& direction) const;
+    /** sub_140223810: the box the line enters first, local gets the entry point in its space */
+    [[nodiscard]] std::optional<std::string> modelHitBox (
+	const glm::vec3& origin, const glm::vec3& direction, const glm::mat4& objectWorld, glm::vec3& local
+    ) const;
+    [[nodiscard]] std::string hitBoxName (int bone) const;
     void setBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
     [[nodiscard]] const glm::mat4& getLocalBoneTransform (int bone) const;
     void setLocalBoneTransform (int bone, const glm::mat4& transform, const glm::mat4& objectWorld);
@@ -263,6 +275,8 @@ public:
     void resetBonePhysics (int bone);
     /** model space bone matrices times the inverse bind ones, what the vertices are skinned with */
     [[nodiscard]] std::vector<glm::mat4> skinMatrices () const;
+    /** sub_140226A10: union of the visible layers' MDLA v5 boxes, false when none has one */
+    [[nodiscard]] bool clipBounds (glm::vec3& min, glm::vec3& max) const;
     /** Where the file's MDMP section (morph targets) starts, 0 without one */
     [[nodiscard]] size_t getMorphSection () const { return this->morphSection; }
 
@@ -282,6 +296,8 @@ public:
     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 = {};
+    /** walked from the end */
+    std::vector<int> boneHitOrder = {};
     /** set by the image for a mesh with flag 8: the pose update then keeps drawOrder (instance +640) */
     bool drawOrderEnabled = false;
     std::vector<float> drawOrder = {};
@@ -291,6 +307,10 @@ public:
     PuppetIKRig ik = {};
     /** bind pose in model space (P+808) */
     std::vector<glm::mat4> bindModel = {};
+    /** MDLE0002 local bind matrices */
+    std::vector<glm::mat4> layerImageBindLocal = {};
+    /** sub_1401D6D30: MDLE0002 locals if any, else MDLS's */
+    [[nodiscard]] std::vector<glm::mat4> layerImageBindModel () const;
     /** P+736 */
     std::vector<glm::mat4> extraModel = {};
     bool hasIK = false;
@@ -311,6 +331,8 @@ public:
     /** The rest pose isn't the bind pose, the mesh needs skinning even when nothing moves */
     bool hasRestPose = false;
     size_t nextLayerSerial = 0;
+    size_t removeLayers (const std::function<bool (const PuppetActiveAnimation&)>& predicate);
+    std::vector<PuppetActiveAnimation> removedLayers = {};
     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;

+ 109 - 1
src/WallpaperEngine/Render/RenderContext.cpp

@@ -54,6 +54,7 @@ void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
     }
 
     viewport->makeCurrent ();
+    this->m_textureCache->repaintConditionalTextures ();
 
 #if !NDEBUG
     const std::string str = "Rendering to output " + viewport->name;
@@ -66,6 +67,7 @@ void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
 	ref->second->render (
 	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
 	);
+	this->drawHeldFrame (*viewport, *ref->second);
     }
 
 #if !NDEBUG
@@ -88,6 +90,7 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     stats.lastFrame = frameStart;
 
     viewport->makeCurrent ();
+    this->m_textureCache->repaintConditionalTextures ();
     glFinish ();
     VideoPlayback::MPV::GLPlayer::s_statsMillis = 0.0;
 
@@ -98,6 +101,7 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
 	ref->second->render (
 	    viewport->viewport, this->getOutput ().renderVFlip (), viewport->globalPosition, viewport->logicalSize
 	);
+	this->drawHeldFrame (*viewport, *ref->second);
     }
 
     glFinish ();
@@ -135,12 +139,111 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     stats = FrameStats { .lastFrame = stats.lastFrame };
 }
 
-void RenderContext::setWallpaper (const std::string& display, std::shared_ptr<CWallpaper> wallpaper) {
+void RenderContext::setWallpaper (
+    const std::string& display, std::shared_ptr<CWallpaper> wallpaper, const bool holdPrevious
+) {
+    if (holdPrevious) {
+	this->holdFrame (display);
+    } else {
+	this->releaseHeldFrame (display);
+    }
+
     wallpaper->setDestinationFramebuffer (this->m_app.getDestinationFramebuffer ());
     this->m_wallpapers.insert_or_assign (display, wallpaper);
     this->pruneTextures ();
 }
 
+void RenderContext::holdFrame (const std::string& display) {
+    const auto current = this->m_wallpapers.find (display);
+    const auto& viewports = this->getOutput ().getViewports ();
+    const auto viewport = viewports.find (display);
+
+    if (current == this->m_wallpapers.end () || viewport == viewports.end ()) {
+	this->releaseHeldFrame (display);
+	return;
+    }
+
+    // keep the older frame when switching again before content arrived
+    if (this->m_heldFrames.contains (display) && !current->second->hasContent ()) {
+	return;
+    }
+
+    this->releaseHeldFrame (display);
+
+    const glm::ivec4 rect = viewport->second->viewport;
+
+    if (rect.z <= 0 || rect.w <= 0) {
+	return;
+    }
+
+    viewport->second->makeCurrent ();
+
+    HeldFrame held { .viewport = rect };
+
+    glGenTextures (1, &held.texture);
+    glBindTexture (GL_TEXTURE_2D, held.texture);
+    // keep HDR values above 1
+    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA16F, rect.z, rect.w, 0, GL_RGBA, GL_HALF_FLOAT, nullptr);
+    glBindTexture (GL_TEXTURE_2D, 0);
+    glGenFramebuffers (1, &held.framebuffer);
+    glBindFramebuffer (GL_FRAMEBUFFER, held.framebuffer);
+    glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, held.texture, 0);
+
+    if (glCheckFramebufferStatus (GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
+	sLog.error ("Cannot keep the previous wallpaper on ", display, " while the new one loads");
+	glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
+	glDeleteFramebuffers (1, &held.framebuffer);
+	glDeleteTextures (1, &held.texture);
+	return;
+    }
+
+    glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
+    glClear (GL_COLOR_BUFFER_BIT);
+
+    current->second->setDestinationFramebuffer (held.framebuffer);
+    current->second->present (
+	{ 0, 0, rect.z, rect.w }, viewport->second->globalPosition, viewport->second->logicalSize
+    );
+    current->second->setDestinationFramebuffer (this->m_app.getDestinationFramebuffer ());
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
+
+    this->m_heldFrames.insert_or_assign (display, held);
+}
+
+void RenderContext::releaseHeldFrame (const std::string& display) {
+    const auto held = this->m_heldFrames.find (display);
+
+    if (held == this->m_heldFrames.end ()) {
+	return;
+    }
+
+    glDeleteFramebuffers (1, &held->second.framebuffer);
+    glDeleteTextures (1, &held->second.texture);
+    this->m_heldFrames.erase (held);
+}
+
+void RenderContext::drawHeldFrame (const Drivers::Output::OutputViewport& viewport, const CWallpaper& wallpaper) {
+    const auto held = this->m_heldFrames.find (viewport.name);
+
+    if (held == this->m_heldFrames.end ()) {
+	return;
+    }
+
+    const glm::ivec4 rect = viewport.viewport;
+
+    if (wallpaper.hasContent () || held->second.viewport != rect) {
+	this->releaseHeldFrame (viewport.name);
+	return;
+    }
+
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, held->second.framebuffer);
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
+    glBlitFramebuffer (
+	0, 0, rect.z, rect.w, rect.x, rect.y, rect.x + rect.z, rect.y + rect.w, GL_COLOR_BUFFER_BIT, GL_NEAREST
+    );
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
+}
+
 void RenderContext::pruneTextures () const { this->m_textureCache->prune (); }
 
 void RenderContext::setPause (const bool newState) const {
@@ -162,6 +265,11 @@ RenderContext::resolveTexture (const std::string& name, const Data::Model::Proje
     return this->m_textureCache->resolve (name, project);
 }
 
+std::shared_ptr<const TextureProvider>
+RenderContext::findLoadedTexture (const std::string& name, const Data::Model::Project& project) const {
+    return this->m_textureCache->findLoaded (name, project);
+}
+
 const std::map<std::string, std::shared_ptr<CWallpaper>>& RenderContext::getWallpapers () const {
     return this->m_wallpapers;
 }

+ 16 - 1
src/WallpaperEngine/Render/RenderContext.h

@@ -38,7 +38,9 @@ namespace Render {
 	RenderContext (Drivers::VideoDriver& driver, WallpaperApplication& app, Media::MediaSource& mediaSource);
 
 	void render (Drivers::Output::OutputViewport* viewport);
-	void setWallpaper (const std::string& display, std::shared_ptr<CWallpaper> wallpaper);
+	/** holdPrevious keeps the old wallpaper's last frame on screen until the new one has content */
+	void
+	setWallpaper (const std::string& display, std::shared_ptr<CWallpaper> wallpaper, bool holdPrevious = false);
 	void setPause (bool newState) const;
 	void pruneTextures () const;
 	[[nodiscard]] Input::InputContext& getInputContext () const;
@@ -47,17 +49,30 @@ namespace Render {
 	[[nodiscard]] const Drivers::Output::Output& getOutput () const;
 	[[nodiscard]] std::shared_ptr<const TextureProvider>
 	resolveTexture (const std::string& name, const Data::Model::Project& project) const;
+	/** see TextureCache::findLoaded */
+	[[nodiscard]] std::shared_ptr<const TextureProvider>
+	findLoadedTexture (const std::string& name, const Data::Model::Project& project) const;
 	[[nodiscard]] const std::map<std::string, std::shared_ptr<CWallpaper>>& getWallpapers () const;
 	[[nodiscard]] Media::MediaSource& getMediaSource () const;
 
     private:
 	void renderWithStats (Drivers::Output::OutputViewport* viewport);
+	void holdFrame (const std::string& display);
+	void releaseHeldFrame (const std::string& display);
+	void drawHeldFrame (const Drivers::Output::OutputViewport& viewport, const CWallpaper& wallpaper);
+
+	struct HeldFrame {
+	    GLuint framebuffer = GL_NONE;
+	    GLuint texture = GL_NONE;
+	    glm::ivec4 viewport {};
+	};
 
 	Drivers::VideoDriver& m_driver;
 	std::map<std::string, std::shared_ptr<CWallpaper>> m_wallpapers = {};
 	WallpaperApplication& m_app;
 	Media::MediaSource& m_mediaSource;
 	std::unique_ptr<TextureCache> m_textureCache = nullptr;
+	std::map<std::string, HeldFrame> m_heldFrames = {};
     };
 } // namespace Render
 } // namespace WallpaperEngine

+ 13 - 0
src/WallpaperEngine/Render/Shaders/GLSLContext.cpp

@@ -14,6 +14,8 @@
 #include <stdexcept>
 #include <unordered_map>
 
+#include "ShaderCache.h"
+
 #include "SPIRV/GlslangToSpv.h"
 #include "glslang/Include/ResourceLimits.h"
 #include "glslang/Public/ShaderLang.h"
@@ -254,6 +256,15 @@ GLSLContext::Sources GLSLContext::toGlsl (
 	}
     }
 
+    // glslang/SPIRV-Cross and the options below only change with a rebuild
+    const std::string diskKey = std::string ("glsl " __DATE__ " " __TIME__ "\0") + cacheKey;
+
+    if (auto stored = ShaderCache::get ().loadTranslation (diskKey); stored.has_value ()) {
+	std::lock_guard lock (cacheMutex);
+	cache.emplace (std::move (cacheKey), *stored);
+	return *stored;
+    }
+
     const auto vertexShader = parseStage (EShLangVertex, vertex, name, "vertex");
     const auto fragmentShader = parseStage (EShLangFragment, fragment, name, "fragment");
     std::unique_ptr<glslang::TShader> geometryShader;
@@ -281,6 +292,8 @@ GLSLContext::Sources GLSLContext::toGlsl (
 	.geometry = geometryShader ? crossCompile (program, EShLangGeometry) + "#if 0\n" + geometry + "\n#endif" : "",
     };
 
+    ShaderCache::get ().storeTranslation (diskKey, result);
+
     {
 	std::lock_guard lock (cacheMutex);
 	cache.emplace (std::move (cacheKey), result);

+ 372 - 0
src/WallpaperEngine/Render/Shaders/ShaderCache.cpp

@@ -0,0 +1,372 @@
+#include "ShaderCache.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <unistd.h>
+#include <vector>
+
+#include "WallpaperEngine/Logging/Log.h"
+
+using namespace WallpaperEngine::Render::Shaders;
+
+namespace {
+constexpr char MAGIC[8] = { 'L', 'W', 'E', 'S', 'H', 'C', '0', '1' };
+// pruned to 3/4 of this on a run's first write and again every 1/16 of it written
+constexpr uint64_t SIZE_LIMIT = 256ull * 1024 * 1024;
+
+uint64_t fnv1a (const std::string& data) {
+    uint64_t hash = 0xcbf29ce484222325ull;
+
+    for (const unsigned char c : data) {
+	hash = (hash ^ c) * 0x100000001b3ull;
+    }
+
+    return hash;
+}
+
+/** guards against file name collisions */
+uint64_t mix64 (const std::string& data) {
+    uint64_t hash = 0x9e3779b97f4a7c15ull ^ data.size ();
+    size_t i = 0;
+
+    const auto round = [&hash] (uint64_t value) {
+	value *= 0xbf58476d1ce4e5b9ull;
+	value ^= value >> 31;
+	hash = (hash ^ value) * 0x94d049bb133111ebull;
+	hash ^= hash >> 29;
+    };
+
+    for (; i + 8 <= data.size (); i += 8) {
+	uint64_t value;
+	memcpy (&value, data.data () + i, 8);
+	round (value);
+    }
+
+    uint64_t tail = 0;
+    memcpy (&tail, data.data () + i, data.size () - i);
+    round (tail);
+
+    return hash;
+}
+
+void appendU32 (std::string& out, uint32_t value) { out.append (reinterpret_cast<const char*> (&value), 4); }
+
+void appendString (std::string& out, const std::string& value) {
+    appendU32 (out, static_cast<uint32_t> (value.size ()));
+    out += value;
+}
+
+bool readU32 (const std::string& in, size_t& offset, uint32_t& value) {
+    if (offset + 4 > in.size ()) {
+	return false;
+    }
+
+    memcpy (&value, in.data () + offset, 4);
+    offset += 4;
+    return true;
+}
+
+bool readString (const std::string& in, size_t& offset, std::string& value) {
+    uint32_t size;
+
+    if (!readU32 (in, offset, size) || offset + size > in.size ()) {
+	return false;
+    }
+
+    value.assign (in, offset, size);
+    offset += size;
+    return true;
+}
+
+std::filesystem::path cacheDirectory () {
+    if (const char* home = std::getenv ("XDG_CACHE_HOME"); home != nullptr && home[0] == '/') {
+	return std::filesystem::path (home) / "linux-wallpaperengine" / "shaders";
+    }
+
+    if (const char* home = std::getenv ("HOME"); home != nullptr && home[0] != '\0') {
+	return std::filesystem::path (home) / ".cache" / "linux-wallpaperengine" / "shaders";
+    }
+
+    return {};
+}
+} // namespace
+
+ShaderCache& ShaderCache::get () {
+    static ShaderCache instance;
+    return instance;
+}
+
+ShaderCache::ShaderCache () : m_directory (cacheDirectory ()) { this->m_enabled = !this->m_directory.empty (); }
+
+void ShaderCache::setEnabled (bool enabled) {
+    std::lock_guard lock (this->m_mutex);
+    this->m_enabled = enabled && !this->m_directory.empty ();
+}
+
+std::optional<ShaderCache::Entry> ShaderCache::entry (const std::string& kind, const std::string& key) const {
+    if (!this->m_enabled) {
+	return std::nullopt;
+    }
+
+    char name[17];
+    snprintf (name, sizeof (name), "%016llx", static_cast<unsigned long long> (fnv1a (key)));
+
+    return Entry { .path = this->m_directory / kind / name, .check = mix64 (key) };
+}
+
+std::optional<std::string> ShaderCache::read (const Entry& entry) const {
+    std::ifstream file (entry.path, std::ios::binary);
+
+    if (!file) {
+	return std::nullopt;
+    }
+
+    std::string data ((std::istreambuf_iterator<char> (file)), std::istreambuf_iterator<char> ());
+    uint64_t check;
+
+    if (data.size () < sizeof (MAGIC) + 8 || memcmp (data.data (), MAGIC, sizeof (MAGIC)) != 0) {
+	return std::nullopt;
+    }
+
+    memcpy (&check, data.data () + sizeof (MAGIC), 8);
+
+    if (check != entry.check) {
+	return std::nullopt;
+    }
+
+    std::error_code error;
+    std::filesystem::last_write_time (entry.path, std::filesystem::file_time_type::clock::now (), error);
+
+    return data.substr (sizeof (MAGIC) + 8);
+}
+
+void ShaderCache::write (const Entry& entry, const std::string& payload) {
+    std::error_code error;
+    std::filesystem::create_directories (entry.path.parent_path (), error);
+
+    if (error) {
+	return;
+    }
+
+    const auto temporary = entry.path.string () + "." + std::to_string (getpid ()) + ".tmp";
+
+    {
+	std::ofstream file (temporary, std::ios::binary | std::ios::trunc);
+
+	if (!file) {
+	    return;
+	}
+
+	file.write (MAGIC, sizeof (MAGIC));
+	file.write (reinterpret_cast<const char*> (&entry.check), 8);
+	file.write (payload.data (), static_cast<std::streamsize> (payload.size ()));
+
+	if (!file) {
+	    file.close ();
+	    std::filesystem::remove (temporary, error);
+	    return;
+	}
+    }
+
+    std::filesystem::rename (temporary, entry.path, error);
+
+    if (error) {
+	std::filesystem::remove (temporary, error);
+	return;
+    }
+
+    this->m_bytesWritten += payload.size ();
+
+    if (!this->m_pruned || this->m_bytesWritten > SIZE_LIMIT / 16) {
+	this->prune ();
+    }
+}
+
+void ShaderCache::prune () {
+    this->m_pruned = true;
+    this->m_bytesWritten = 0;
+
+    struct File {
+	std::filesystem::path path;
+	std::filesystem::file_time_type time;
+	uintmax_t size;
+    };
+
+    std::vector<File> files;
+    uintmax_t total = 0;
+    std::error_code error;
+
+    for (auto it = std::filesystem::recursive_directory_iterator (this->m_directory, error);
+	 !error && it != std::filesystem::recursive_directory_iterator (); it.increment (error)) {
+	if (!it->is_regular_file (error)) {
+	    continue;
+	}
+
+	const auto size = it->file_size (error);
+	const auto time = it->last_write_time (error);
+
+	if (!error) {
+	    files.push_back ({ it->path (), time, size });
+	    total += size;
+	}
+    }
+
+    if (total <= SIZE_LIMIT) {
+	return;
+    }
+
+    std::ranges::sort (files, {}, &File::time);
+
+    for (const auto& file : files) {
+	if (total <= SIZE_LIMIT / 4 * 3) {
+	    break;
+	}
+
+	if (std::filesystem::remove (file.path, error)) {
+	    total -= file.size;
+	}
+    }
+}
+
+std::optional<GLSLContext::Sources> ShaderCache::loadTranslation (const std::string& key) {
+    std::lock_guard lock (this->m_mutex);
+    const auto entry = this->entry ("translations", key);
+
+    if (!entry.has_value ()) {
+	return std::nullopt;
+    }
+
+    const auto data = this->read (*entry);
+
+    if (!data.has_value ()) {
+	return std::nullopt;
+    }
+
+    GLSLContext::Sources sources;
+    size_t offset = 0;
+
+    if (!readString (*data, offset, sources.vertex) || !readString (*data, offset, sources.fragment)
+	|| !readString (*data, offset, sources.geometry) || offset != data->size ()) {
+	return std::nullopt;
+    }
+
+    return sources;
+}
+
+void ShaderCache::storeTranslation (const std::string& key, const GLSLContext::Sources& sources) {
+    std::lock_guard lock (this->m_mutex);
+    const auto entry = this->entry ("translations", key);
+
+    if (!entry.has_value ()) {
+	return;
+    }
+
+    std::string payload;
+    payload.reserve (sources.vertex.size () + sources.fragment.size () + sources.geometry.size () + 12);
+    appendString (payload, sources.vertex);
+    appendString (payload, sources.fragment);
+    appendString (payload, sources.geometry);
+
+    this->write (*entry, payload);
+}
+
+bool ShaderCache::programsSupported () {
+    std::lock_guard lock (this->m_mutex);
+
+    if (!this->m_enabled) {
+	return false;
+    }
+
+    if (!this->m_programsSupported.has_value ()) {
+	GLint formats = 0;
+
+	if (GLEW_VERSION_4_1 || GLEW_ARB_get_program_binary) {
+	    glGetIntegerv (GL_NUM_PROGRAM_BINARY_FORMATS, &formats);
+	}
+
+	this->m_programsSupported = formats > 0;
+
+	// binaries only load into the driver that made them
+	for (const GLenum name : { GL_VENDOR, GL_RENDERER, GL_VERSION, GL_SHADING_LANGUAGE_VERSION }) {
+	    const auto* value = reinterpret_cast<const char*> (glGetString (name));
+	    this->m_driver += value != nullptr ? value : "";
+	    this->m_driver += '\0';
+	}
+    }
+
+    return *this->m_programsSupported;
+}
+
+GLuint ShaderCache::loadProgram (const std::string& key) {
+    if (!this->programsSupported ()) {
+	return 0;
+    }
+
+    std::lock_guard lock (this->m_mutex);
+    const auto entry = this->entry ("programs", this->m_driver + key);
+
+    if (!entry.has_value ()) {
+	return 0;
+    }
+
+    const auto data = this->read (*entry);
+    uint32_t format;
+    size_t offset = 0;
+
+    if (!data.has_value () || !readU32 (*data, offset, format) || offset == data->size ()) {
+	return 0;
+    }
+
+    const GLuint program = glCreateProgram ();
+    glProgramBinary (program, format, data->data () + offset, static_cast<GLsizei> (data->size () - offset));
+
+    GLint linked = GL_FALSE;
+    glGetProgramiv (program, GL_LINK_STATUS, &linked);
+
+    if (linked != GL_TRUE) {
+	// some driver updates break binaries without a version change
+	glDeleteProgram (program);
+	std::error_code error;
+	std::filesystem::remove (entry->path, error);
+	return 0;
+    }
+
+    return program;
+}
+
+void ShaderCache::storeProgram (const std::string& key, GLuint program) {
+    if (!this->programsSupported ()) {
+	return;
+    }
+
+    std::lock_guard lock (this->m_mutex);
+    const auto entry = this->entry ("programs", this->m_driver + key);
+    GLint length = 0;
+
+    if (!entry.has_value ()) {
+	return;
+    }
+
+    glGetProgramiv (program, GL_PROGRAM_BINARY_LENGTH, &length);
+
+    if (length <= 0) {
+	return;
+    }
+
+    std::string payload (4 + length, '\0');
+    GLenum format = 0;
+    GLsizei written = 0;
+    glGetProgramBinary (program, length, &written, &format, payload.data () + 4);
+
+    if (written <= 0) {
+	return;
+    }
+
+    memcpy (payload.data (), &format, 4);
+    payload.resize (4 + written);
+
+    this->write (*entry, payload);
+}

+ 53 - 0
src/WallpaperEngine/Render/Shaders/ShaderCache.h

@@ -0,0 +1,53 @@
+#pragma once
+
+#include <GL/glew.h>
+#include <cstdint>
+#include <filesystem>
+#include <mutex>
+#include <optional>
+#include <string>
+
+#include "GLSLContext.h"
+
+namespace WallpaperEngine::Render::Shaders {
+/**
+ * glslang/SPIRV-Cross translations and program binaries keyed by the full source, in
+ * $XDG_CACHE_HOME/linux-wallpaperengine/shaders, written via rename so engines can share it
+ */
+class ShaderCache {
+public:
+    [[nodiscard]] static ShaderCache& get ();
+
+    void setEnabled (bool enabled);
+
+    [[nodiscard]] std::optional<GLSLContext::Sources> loadTranslation (const std::string& key);
+    void storeTranslation (const std::string& key, const GLSLContext::Sources& sources);
+
+    /** 0 when missing or rejected */
+    [[nodiscard]] GLuint loadProgram (const std::string& key);
+    /** needs GL_PROGRAM_BINARY_RETRIEVABLE_HINT */
+    void storeProgram (const std::string& key, GLuint program);
+    [[nodiscard]] bool programsSupported ();
+
+private:
+    ShaderCache ();
+
+    struct Entry {
+	std::filesystem::path path;
+	uint64_t check;
+    };
+
+    [[nodiscard]] std::optional<Entry> entry (const std::string& kind, const std::string& key) const;
+    [[nodiscard]] std::optional<std::string> read (const Entry& entry) const;
+    void write (const Entry& entry, const std::string& payload);
+    void prune ();
+
+    std::filesystem::path m_directory;
+    bool m_enabled = true;
+    std::optional<bool> m_programsSupported;
+    std::string m_driver;
+    uint64_t m_bytesWritten = 0;
+    bool m_pruned = false;
+    std::mutex m_mutex;
+};
+} // namespace WallpaperEngine::Render::Shaders

+ 211 - 126
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -1,6 +1,7 @@
 #include "ShaderUnit.h"
 
 #include "WallpaperEngine/Logging/Log.h"
+#include <array>
 #include <cctype>
 #include <charconv>
 #include <cmath>
@@ -27,6 +28,59 @@
 #include "WallpaperEngine/Data/Builders/VectorBuilder.h"
 #include "WallpaperEngine/FileSystem/Container.h"
 
+namespace {
+// libstdc++ looks the "w" class up by name for every \b and refetches the ctype facet per test (most of a model scene's
+// load time), done once here
+struct ShaderRegexTraits : std::regex_traits<char> {
+    struct ClassTable {
+	char_class_type mask;
+	std::array<bool, 256> members;
+
+	explicit ClassTable (char name) {
+	    const std::regex_traits<char> traits;
+	    this->mask = traits.lookup_classname (&name, &name + 1);
+
+	    for (int c = 0; c < 256; c++) {
+		this->members[c] = traits.isctype (static_cast<char> (c), this->mask);
+	    }
+	}
+    };
+
+    static const ClassTable& word () {
+	static const ClassTable table ('w');
+	return table;
+    }
+
+    static const ClassTable& space () {
+	static const ClassTable table ('s');
+	return table;
+    }
+
+    template <typename Iterator>
+    char_class_type lookup_classname (Iterator first, Iterator last, bool icase = false) const {
+	if (!icase && std::distance (first, last) == 1 && *first == 'w') {
+	    return word ().mask;
+	}
+
+	return std::regex_traits<char>::lookup_classname (first, last, icase);
+    }
+
+    bool isctype (char c, char_class_type mask) const {
+	for (const ClassTable* table : { &word (), &space () }) {
+	    if (mask == table->mask) {
+		return table->members[static_cast<unsigned char> (c)];
+	    }
+	}
+
+	return std::regex_traits<char>::isctype (c, mask);
+    }
+};
+
+using Regex = std::basic_regex<char, ShaderRegexTraits>;
+constexpr size_t MEMO_LIMIT = 512;
+using RegexIterator = std::regex_iterator<std::string::const_iterator, char, ShaderRegexTraits>;
+} // namespace
+
 // the wpe_ defines rename words GLSL reserves that are plain identifiers in HLSL (3681571511's fxaa has a
 // "float common")
 #define SHADER_HEADER(filename)                                                                                        \
@@ -58,6 +112,7 @@
 	  "#define saturate(x) (clamp(x, 0.0, 1.0))\n"                                                                 \
 	  "#define texSample2D texture\n"                                                                              \
 	  "#define texSample2DLod textureLod\n"                                                                        \
+	  "#define texSample3D texture\n"                                                                              \
 	  "#define sampler2DComparison sampler2DShadow\n"                                                              \
 	  "#define texSample2DCompare(s, u, d) vec4 (texture (s, vec3 (u, d)))\n"                                      \
 	  "#define atan2 atan\n"                                                                                       \
@@ -104,11 +159,10 @@ using namespace WallpaperEngine::Render::Shaders;
 namespace {
 // "name|name|..." of every uniform, varying and attribute the source declares, for regex alternations
 std::string declaredInputNames (const std::string& source) {
-    static const std::regex inputDecl (R"(\b(?:uniform|varying|attribute)\s+\w+\s+([A-Za-z_]\w*))");
+    static const Regex inputDecl (R"(\b(?:uniform|varying|attribute)\s+\w+\s+([A-Za-z_]\w*))");
 
     std::string names;
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), inputDecl); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), inputDecl); it != RegexIterator (); ++it) {
 	names += (names.empty () ? "" : "|") + (*it)[1].str ();
     }
 
@@ -118,7 +172,7 @@ std::string declaredInputNames (const std::string& source) {
 // the #if/#elif/#else lines leading to the branch that contains pos, one list per open level, so code
 // moved somewhere else can be put back under the same condition
 std::vector<std::vector<std::string>> conditionalBranch (const std::string& source, const size_t pos) {
-    static const std::regex directive (R"(^[ \t]*#[ \t]*(if|ifdef|ifndef|elif|else|endif)\b)");
+    static const Regex directive (R"(^[ \t]*#[ \t]*(if|ifdef|ifndef|elif|else|endif)\b)");
 
     std::vector<std::vector<std::string>> levels;
     size_t start = 0;
@@ -183,9 +237,35 @@ void ShaderUnit::preprocess () {
     this->preprocessIncludes ();
     this->preprocessRequires ();
     this->preprocessVariables ();
-    this->preprocessBalanceConditionals ();
-    this->preprocessSwizzledDeclarations ();
-    this->preprocessScalarSwizzles ();
+
+    // every combo permutation brings the same source again
+    static std::mutex cacheMutex;
+    static std::unordered_map<std::string, std::string> rewritten;
+    std::string input = this->m_preprocessed;
+    bool cached = false;
+
+    {
+	std::lock_guard lock (cacheMutex);
+
+	if (const auto found = rewritten.find (input); found != rewritten.end ()) {
+	    this->m_preprocessed = found->second;
+	    cached = true;
+	}
+    }
+
+    if (!cached) {
+	this->preprocessBalanceConditionals ();
+	this->preprocessSwizzledDeclarations ();
+	this->preprocessScalarSwizzles ();
+
+	std::lock_guard lock (cacheMutex);
+
+	if (rewritten.size () >= MEMO_LIMIT) {
+	    rewritten.clear ();
+	}
+
+	rewritten.emplace (std::move (input), this->m_preprocessed);
+    }
 
     const std::string from = "gl_FragColor";
     const std::string to = "out_FragColor";
@@ -538,13 +618,13 @@ std::string ShaderUnit::generateLightingV1 () const {
 }
 
 void ShaderUnit::preprocessBalanceConditionals () {
-    static const std::regex directive (R"((?:^|\n)[ \t]*#(ifndef|ifdef|if|endif)\b)");
+    static const Regex directive (R"((?:^|\n)[ \t]*#(ifndef|ifdef|if|endif)\b)");
 
     int depth = 0;
     std::vector<size_t> extraEndifs;
 
-    auto begin = std::sregex_iterator (this->m_preprocessed.cbegin (), this->m_preprocessed.cend (), directive);
-    auto end = std::sregex_iterator ();
+    auto begin = RegexIterator (this->m_preprocessed.cbegin (), this->m_preprocessed.cend (), directive);
+    auto end = RegexIterator ();
 
     for (auto it = begin; it != end; ++it) {
 	const std::string& keyword = (*it)[1].str ();
@@ -569,7 +649,7 @@ void ShaderUnit::preprocessBalanceConditionals () {
 }
 
 void ShaderUnit::preprocessSwizzledDeclarations () {
-    static const std::regex swizzledDecl (
+    static const Regex swizzledDecl (
 	R"(\b(varying|uniform|attribute)(\s+[A-Za-z0-9_]+\s+[A-Za-z_][A-Za-z0-9_]*)\.[xyzwrgba]+(\s*;))"
     );
 
@@ -585,29 +665,29 @@ void ShaderUnit::preprocessScalarSwizzles () {
     // genericropeparticle's non geometry shader TRAILSCROLLALPHA + TRAILFADESIZE branch writes sizeStart.w on a
     // float, WE never compiles that branch (it draws ropes with a geometry shader) and GLSL rejects it. A single
     // component swizzle of a variable that is only ever declared as float is the variable itself
-    static const std::regex declaration (
+    static const Regex declaration (
 	R"(\b(float|int|bool|u?int|[biu]?vec[234]|mat[234](?:x[234])?)\s+([A-Za-z_][A-Za-z0-9_]*)\b)"
     );
 
     std::set<std::string> scalars;
     std::set<std::string> others;
-    for (auto it = std::sregex_iterator (this->m_preprocessed.begin (), this->m_preprocessed.end (), declaration);
-	 it != std::sregex_iterator (); ++it) {
+    for (auto it = RegexIterator (this->m_preprocessed.begin (), this->m_preprocessed.end (), declaration);
+	 it != RegexIterator (); ++it) {
 	((*it)[1] == "float" ? scalars : others).insert ((*it)[2]);
     }
 
     for (const auto& name : scalars) {
-	// std::regex is slow, most names never show up with a dot after them
+	// regex is slow, most names never have a dot after them
 	if (others.contains (name) || this->m_preprocessed.find (name + ".") == std::string::npos) {
 	    continue;
 	}
 
-	const std::regex swizzle ("\\b" + name + "\\.[xyzwrgba](?![A-Za-z0-9_])");
+	const 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_])");
+	    const 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 + ")");
 	}
@@ -615,13 +695,12 @@ void ShaderUnit::preprocessScalarSwizzles () {
 }
 
 std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source) const {
-    static const std::regex vectorDecl (R"(\b(vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
-    static const std::regex narrowAssign (R"(\b(vec[23])\s+[A-Za-z_][A-Za-z0-9_]*\s*=\s*([^;{}]+);)");
+    static const Regex vectorDecl (R"(\b(vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
+    static const Regex narrowAssign (R"(\b(vec[23])\s+[A-Za-z_][A-Za-z0-9_]*\s*=\s*([^;{}]+);)");
 
     // name -> width, 0 when the same name is declared with different widths in different scopes
     std::unordered_map<std::string, int> widths;
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), vectorDecl); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), vectorDecl); it != RegexIterator (); ++it) {
 	const int width = (*it)[1].str ().back () - '0';
 	const std::string name = (*it)[2].str ();
 	const auto found = widths.find (name);
@@ -730,8 +809,7 @@ std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source)
     std::string result;
     size_t last = 0;
 
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), narrowAssign); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), narrowAssign); it != RegexIterator (); ++it) {
 	const size_t exprStart = it->position (2);
 
 	result.append (source, last, exprStart - last);
@@ -742,12 +820,11 @@ std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source)
     result.append (source, last, std::string::npos);
 
     // the coordinates of a 2D sample are a float2 in HLSL, "texSample2D(s, uv.xy - (k * v4))" truncates v4
-    static const std::regex sampleCall (R"(\btexSample2D(?:Lod)?\s*\()");
+    static const Regex sampleCall (R"(\btexSample2D(?:Lod)?\s*\()");
     std::string sampled;
     last = 0;
 
-    for (auto it = std::sregex_iterator (result.cbegin (), result.cend (), sampleCall); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (result.cbegin (), result.cend (), sampleCall); it != RegexIterator (); ++it) {
 	const size_t open = it->position () + it->length () - 1;
 	size_t argStart = std::string::npos;
 	size_t argEnd = std::string::npos;
@@ -796,14 +873,13 @@ std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source)
 }
 
 std::string ShaderUnit::applyFloatConditionCompatibility (std::string source) const {
-    static const std::regex floatDecl (R"(\b(float|vec[234]|int|bool|mat[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
-    static const std::regex ternaryCond (R"(\b([A-Za-z_][A-Za-z0-9_]*)\s*\?)");
-    static const std::regex ifCond (R"(\bif\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\))");
+    static const Regex floatDecl (R"(\b(float|vec[234]|int|bool|mat[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
+    static const Regex ternaryCond (R"(\b([A-Za-z_][A-Za-z0-9_]*)\s*\?)");
+    static const Regex ifCond (R"(\bif\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\))");
 
     // names that are only ever declared as float
     std::unordered_map<std::string, bool> onlyFloat;
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), floatDecl); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), floatDecl); it != RegexIterator (); ++it) {
 	const bool isFloat = (*it)[1].str () == "float";
 	const std::string name = (*it)[2].str ();
 	const auto found = onlyFloat.find (name);
@@ -819,12 +895,11 @@ std::string ShaderUnit::applyFloatConditionCompatibility (std::string source) co
     size_t last = 0;
     bool changed = false;
 
-    auto rewrite = [&] (const std::regex& pattern, bool ternary) {
+    auto rewrite = [&] (const Regex& pattern, bool ternary) {
 	result.clear ();
 	last = 0;
 
-	for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), pattern); it != std::sregex_iterator ();
-	     ++it) {
+	for (auto it = RegexIterator (source.cbegin (), source.cend (), pattern); it != RegexIterator (); ++it) {
 	    const std::string name = (*it)[1].str ();
 	    const auto found = onlyFloat.find (name);
 	    if (found == onlyFloat.end () || !found->second) {
@@ -874,12 +949,12 @@ std::string ShaderUnit::applyFloatConditionCompatibility (std::string source) co
 }
 
 std::string ShaderUnit::applyBoolArithmeticCompatibility (std::string source) const {
-    static const std::regex decl (R"(\b(float|int|uint|bool|[biu]?vec[234]|mat[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
-    static const std::regex assign (R"(\b([A-Za-z_][A-Za-z0-9_]*)\s*([-+*/]?=)\s*([A-Za-z_][A-Za-z0-9_]*)\s*;)");
+    static const Regex decl (R"(\b(float|int|uint|bool|[biu]?vec[234]|mat[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
+    static const Regex assign (R"(\b([A-Za-z_][A-Za-z0-9_]*)\s*([-+*/]?=)\s*([A-Za-z_][A-Za-z0-9_]*)\s*;)");
 
     // every type each name is declared with (#if branches may declare it differently)
     std::unordered_map<std::string, std::set<std::string>> types;
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), decl); it != std::sregex_iterator (); ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), decl); it != RegexIterator (); ++it) {
 	types[(*it)[2].str ()].insert ((*it)[1].str ());
     }
 
@@ -892,8 +967,7 @@ std::string ShaderUnit::applyBoolArithmeticCompatibility (std::string source) co
     std::string result;
     size_t last = 0;
 
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), assign); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), assign); it != RegexIterator (); ++it) {
 	const auto target = types.find ((*it)[1].str ());
 	const auto value = types.find ((*it)[3].str ());
 	if (target == types.end () || value == types.end () || value->second != std::set<std::string> { "bool" }
@@ -922,7 +996,7 @@ std::string ShaderUnit::applyLinkedVaryingCompatibility (std::string source) con
 	return source;
     }
 
-    std::regex fragmentVec4Varying (R"(\bvarying\s+vec4\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
+    Regex fragmentVec4Varying (R"(\bvarying\s+vec4\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
     std::smatch varyingMatch;
     std::string linked = this->m_link->m_preprocessed;
     size_t linkedOffset = 0;
@@ -931,24 +1005,21 @@ std::string ShaderUnit::applyLinkedVaryingCompatibility (std::string source) con
 	const std::string name = varyingMatch[1].str ();
 	linkedOffset += varyingMatch.position () + varyingMatch.length ();
 
-	const std::regex vertexVec2Decl ("\\bvarying\\s+vec2\\s+" + name + "\\s*;");
+	const Regex vertexVec2Decl ("\\bvarying\\s+vec2\\s+" + name + "\\s*;");
 	if (!std::regex_search (source, vertexVec2Decl)) {
 	    continue;
 	}
 
 	// m_preprocessed still has the #if branches: a varying declared once per branch (generic's v_TexCoord, vec4
 	// with LIGHTMAP, vec2 without) already matches the fragment side in every combination
-	const std::regex anyVertexDecl ("\\bvarying\\s+\\w+\\s+" + name + "\\s*;");
-	if (std::distance (
-		std::sregex_iterator (source.cbegin (), source.cend (), anyVertexDecl), std::sregex_iterator ()
-	    )
-	    != 1) {
+	const Regex anyVertexDecl ("\\bvarying\\s+\\w+\\s+" + name + "\\s*;");
+	if (std::distance (RegexIterator (source.cbegin (), source.cend (), anyVertexDecl), RegexIterator ()) != 1) {
 	    continue;
 	}
 
 	source = std::regex_replace (source, vertexVec2Decl, "varying vec4 " + name + ";");
 
-	const std::regex assignment ("(^|\\n)([ \\t]*)" + name + "\\s*=\\s*([^;\\n]+);");
+	const Regex assignment ("(^|\\n)([ \\t]*)" + name + "\\s*=\\s*([^;\\n]+);");
 	std::smatch assignmentMatch;
 	size_t offset = 0;
 	while (std::regex_search (source.cbegin () + offset, source.cend (), assignmentMatch, assignment)) {
@@ -970,8 +1041,8 @@ std::string ShaderUnit::applyNarrowFragmentVaryingCompatibility (std::string sou
 	return source;
     }
 
-    static const std::regex vertexVarying (R"(\bvarying\s+vec([34])\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
-    static const std::regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
+    static const Regex vertexVarying (R"(\bvarying\s+vec([34])\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
+    static const Regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
     static const char* swizzles[] = { "", "", ".xy", ".xyz" };
 
     if (!std::regex_search (source, mainOpen)) {
@@ -982,20 +1053,17 @@ std::string ShaderUnit::applyNarrowFragmentVaryingCompatibility (std::string sou
     std::string copyCode;
     std::string names;
 
-    for (auto it = std::sregex_iterator (linked.cbegin (), linked.cend (), vertexVarying);
-	 it != std::sregex_iterator (); ++it) {
+    for (auto it = RegexIterator (linked.cbegin (), linked.cend (), vertexVarying); it != RegexIterator (); ++it) {
 	const int vertexWidth = (*it)[1].str ()[0] - '0';
 	const std::string name = (*it)[2].str ();
-	const std::regex anyDecl ("\\bvarying\\s+\\w+\\s+" + name + "\\s*;");
-	const std::regex narrowDecl ("\\bvarying\\s+vec([23])\\s+" + name + "\\s*;");
+	const Regex anyDecl ("\\bvarying\\s+\\w+\\s+" + name + "\\s*;");
+	const Regex narrowDecl ("\\bvarying\\s+vec([23])\\s+" + name + "\\s*;");
 	std::smatch declMatch;
 
 	// conditionals are still in the source here, a varying declared once per #if branch
 	// (the stock generic shaders) can't be told apart from a real mismatch, leave those alone
 	const auto declarations = [&anyDecl] (const std::string& text) {
-	    return std::distance (
-		std::sregex_iterator (text.cbegin (), text.cend (), anyDecl), std::sregex_iterator ()
-	    );
+	    return std::distance (RegexIterator (text.cbegin (), text.cend (), anyDecl), RegexIterator ());
 	};
 
 	if (declarations (linked) != 1 || declarations (source) != 1
@@ -1007,9 +1075,9 @@ std::string ShaderUnit::applyNarrowFragmentVaryingCompatibility (std::string sou
 	const std::string type = "vec" + std::to_string (width);
 	const std::string copy = "wpeVar_" + name;
 
-	source = std::regex_replace (source, std::regex ("(^|[^.\\w])" + name + "\\b"), "$1" + copy);
+	source = std::regex_replace (source, Regex ("(^|[^.\\w])" + name + "\\b"), "$1" + copy);
 	source = std::regex_replace (
-	    source, std::regex ("\\bvarying\\s+" + type + "\\s+" + copy + "\\s*;"),
+	    source, Regex ("\\bvarying\\s+" + type + "\\s+" + copy + "\\s*;"),
 	    "varying vec" + std::to_string (vertexWidth) + " " + name + "; " + type + " " + copy + ";"
 	);
 	copyCode += " " + copy + " = " + name + swizzles[width] + ";";
@@ -1034,10 +1102,10 @@ std::string ShaderUnit::applyFragmentTexCoordCompatibility (std::string source)
 	return source;
     }
 
-    const std::regex texCoordBeforeCast2 (R"(\bv_TexCoord\b(\s*[-+*/]\s*CAST2\s*\())");
-    const std::regex cast2BeforeTexCoord (R"((CAST2\s*\([^)]+\)\s*[-+*/]\s*)\bv_TexCoord\b)");
+    const Regex texCoordBeforeCast2 (R"(\bv_TexCoord\b(\s*[-+*/]\s*CAST2\s*\())");
+    const Regex cast2BeforeTexCoord (R"((CAST2\s*\([^)]+\)\s*[-+*/]\s*)\bv_TexCoord\b)");
 
-    const std::regex wideTexCoordDecl (R"(\bvarying\s+vec[34]\s+v_TexCoord\s*;)");
+    const Regex wideTexCoordDecl (R"(\bvarying\s+vec[34]\s+v_TexCoord\s*;)");
     if (!std::regex_search (source, wideTexCoordDecl)
 	|| (!std::regex_search (source, texCoordBeforeCast2) && !std::regex_search (source, cast2BeforeTexCoord))) {
 	return source;
@@ -1059,22 +1127,21 @@ std::string ShaderUnit::applyFragmentVaryingShadowCompatibility (std::string sou
 	return source;
     }
 
-    static const std::regex varyingDecl (R"(\bvarying\s+(vec[234]|float)\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
+    static const Regex varyingDecl (R"(\bvarying\s+(vec[234]|float)\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
 
     std::vector<std::pair<std::string, std::string>> shadowed;
 
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), varyingDecl); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), varyingDecl); it != RegexIterator (); ++it) {
 	const std::string type = (*it)[1].str ();
 	const std::string name = (*it)[2].str ();
 
 	// only shadow varyings the shader actually reassigns - a plain read-only "in" is fine as-is,
 	// and touching the declaration unnecessarily risks breaking a shader that works today.
 	// writes to a typed local of the same name don't count, that local already shadows the varying
-	const std::regex localDecl ("\\b(?:vec[234]|float|int|bool)\\s+" + name + "\\b");
+	const Regex localDecl ("\\b(?:vec[234]|float|int|bool)\\s+" + name + "\\b");
 	const std::string withoutLocals = std::regex_replace (source, localDecl, " ");
 
-	const std::regex assignmentUse (
+	const Regex assignmentUse (
 	    "(?:\\b" + name + "\\b(?:\\.[xyzwrgba]+)?\\s*(?:=(?!=)|\\+=|-=|\\*=|/=|\\+\\+|--))|(?:(?:\\+\\+|--)\\s*"
 	    + name + "\\b)"
 	);
@@ -1089,7 +1156,7 @@ std::string ShaderUnit::applyFragmentVaryingShadowCompatibility (std::string sou
 	return source;
     }
 
-    static const std::regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
+    static const Regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
     if (!std::regex_search (source, mainOpen)) {
 	return source;
     }
@@ -1100,8 +1167,8 @@ std::string ShaderUnit::applyFragmentVaryingShadowCompatibility (std::string sou
     std::string copyCode;
     for (const auto& [type, name] : shadowed) {
 	const std::string copy = "wpeVar_" + name;
-	const std::regex use ("(^|[^.\\w])" + name + "\\b");
-	const std::regex decl ("\\bvarying\\s+" + type + "\\s+" + copy + "\\s*;");
+	const Regex use ("(^|[^.\\w])" + name + "\\b");
+	const Regex decl ("\\bvarying\\s+" + type + "\\s+" + copy + "\\s*;");
 
 	source = std::regex_replace (source, use, "$1" + copy);
 	source = std::regex_replace (source, decl, "varying " + type + " " + name + "; " + type + " " + copy + ";");
@@ -1122,7 +1189,7 @@ std::string ShaderUnit::applyFragmentVaryingShadowCompatibility (std::string sou
 }
 
 std::string ShaderUnit::applyDirectiveSemicolonCompatibility (std::string source) const {
-    static const std::regex directive (R"((^|\n)([ \t]*#[ \t]*(?:if|elif)\b[^\n;]*?)[ \t]*;[ \t]*(?=\r?\n|$))");
+    static const Regex directive (R"((^|\n)([ \t]*#[ \t]*(?:if|elif)\b[^\n;]*?)[ \t]*;[ \t]*(?=\r?\n|$))");
 
     std::string result = std::regex_replace (source, directive, "$1$2");
     if (result != source) {
@@ -1133,7 +1200,7 @@ std::string ShaderUnit::applyDirectiveSemicolonCompatibility (std::string source
 }
 
 std::string ShaderUnit::applyHlslAttributeCompatibility (std::string source) const {
-    static const std::regex attribute (
+    static const Regex attribute (
 	R"(([;{}]|^|\n)([ \t]*)\[\s*(?:loop|unroll|branch|flatten|fastopt|allow_uav_condition|forcecase|call)\s*(?:\(\s*\w*\s*\))?\s*\](?=\s*(?:for|while|do|if|switch)\b))"
     );
 
@@ -1149,7 +1216,7 @@ std::string ShaderUnit::applyPackedFloatArrayCompatibility (std::string source)
     // WE packs a uniform float array into vec4 registers (every cached g_AudioSpectrum64Left is float4[16] in its
     // compiled shader's RDEF), so "name[a][b]" reads register a, component b (3605510527's video effect). GLSL
     // can't index a float, the same element is name[a * 4 + b]. HLSL's % on floats is fmod
-    static const std::regex declaration (R"(\buniform\s+float\s+([A-Za-z_]\w*)\s*\[\s*(\d+)\s*\]\s*;)");
+    static const Regex declaration (R"(\buniform\s+float\s+([A-Za-z_]\w*)\s*\[\s*(\d+)\s*\]\s*;)");
 
     const auto closing = [&source] (size_t open) -> size_t {
 	int depth = 0;
@@ -1180,8 +1247,7 @@ std::string ShaderUnit::applyPackedFloatArrayCompatibility (std::string source)
     };
 
     std::set<std::string> names;
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), declaration); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), declaration); it != RegexIterator (); ++it) {
 	if (std::stoi ((*it)[2].str ()) % 4 == 0) {
 	    names.insert ((*it)[1].str ());
 	}
@@ -1190,7 +1256,7 @@ std::string ShaderUnit::applyPackedFloatArrayCompatibility (std::string source)
     bool changed = false;
 
     for (const auto& name : names) {
-	const std::regex use ("\\b" + name + "\\s*\\[");
+	const Regex use ("\\b" + name + "\\s*\\[");
 	size_t offset = 0;
 	std::smatch match;
 
@@ -1237,19 +1303,18 @@ std::string ShaderUnit::applyPackedFloatArrayCompatibility (std::string source)
 
 std::string ShaderUnit::applyNonConstantConstCompatibility (std::string source) const {
     // locals only, globals sit at column 0
-    static const std::regex constLocal (R"((^|\n)([ \t]+)const\s+([^;=]+=([^;]*);))");
+    static const Regex constLocal (R"((^|\n)([ \t]+)const\s+([^;=]+=([^;]*);))");
     // plain variables and function parameters, anything declared const is skipped below
-    static const std::regex variableDecl (
+    static const Regex variableDecl (
 	R"((\bconst\s+)?\b(?:float|int|uint|bool|[biu]?vec[234]|mat[234](?:x[234])?)\s+([A-Za-z_]\w*)\s*(?=[=;,)\[]))"
     );
-    static const std::regex declaredName (R"(^[^=]*?([A-Za-z_]\w*)\s*(?:\[[^\]]*\]\s*)?=)");
+    static const Regex declaredName (R"(^[^=]*?([A-Za-z_]\w*)\s*(?:\[[^\]]*\]\s*)?=)");
 
     std::string names = R"(texSample2D\w*|texture\w*|g_\w+|v_\w+|wpeVar_\w+)";
     if (const std::string inputs = declaredInputNames (source); !inputs.empty ()) {
 	names += "|" + inputs;
     }
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), variableDecl); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), variableDecl); it != RegexIterator (); ++it) {
 	if (!(*it)[1].matched) {
 	    names += "|" + (*it)[2].str ();
 	}
@@ -1259,10 +1324,9 @@ std::string ShaderUnit::applyNonConstantConstCompatibility (std::string source)
     size_t count = 0;
     auto last = source.cbegin ();
 
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), constLocal); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), constLocal); it != RegexIterator (); ++it) {
 	const auto& match = *it;
-	const std::regex nonConstant (R"(\b(?:)" + names + R"()\b)");
+	const Regex nonConstant (R"(\b(?:)" + names + R"()\b)");
 
 	if (!std::regex_search (match[4].first, match[4].second, nonConstant)) {
 	    continue;
@@ -1290,10 +1354,10 @@ std::string ShaderUnit::applyNonConstantConstCompatibility (std::string source)
 }
 
 std::string ShaderUnit::applyNonConstantGlobalConstCompatibility (std::string source) const {
-    static const std::regex constGlobal (
+    static const Regex constGlobal (
 	R"((^|\n)[ \t]*const\s+((?:float|int|uint|bool|[biu]?vec[234]|mat[234](?:x[234])?)\s+([A-Za-z_]\w*))\s*=([^;]*);)"
     );
-    static const std::regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
+    static const Regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
 
     // only statements outside any function body count as globals
     std::vector<bool> topLevel (source.size () + 1, false);
@@ -1323,8 +1387,7 @@ std::string ShaderUnit::applyNonConstantGlobalConstCompatibility (std::string so
     std::vector<std::string> moved;
     auto last = source.cbegin ();
 
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), constGlobal); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), constGlobal); it != RegexIterator (); ++it) {
 	const auto& match = *it;
 	const std::string name = match[3].str ();
 	const std::string init = match[4].str ();
@@ -1334,7 +1397,7 @@ std::string ShaderUnit::applyNonConstantGlobalConstCompatibility (std::string so
 	}
 
 	// a const that reads an earlier moved one isn't constant anymore either
-	const std::regex uses (R"(\b(?:)" + nonConstant + R"()\b)");
+	const Regex uses (R"(\b(?:)" + nonConstant + R"()\b)");
 	if (!std::regex_search (init, uses)) {
 	    continue;
 	}
@@ -1369,8 +1432,7 @@ std::string ShaderUnit::applyNonConstantGlobalConstCompatibility (std::string so
 
     result.append (last, source.cend ());
 
-    const auto mains
-	= std::distance (std::sregex_iterator (result.cbegin (), result.cend (), mainOpen), std::sregex_iterator ());
+    const auto mains = std::distance (RegexIterator (result.cbegin (), result.cend (), mainOpen), RegexIterator ());
     if (mains != 1) {
 	return source;
     }
@@ -1401,7 +1463,7 @@ int ShaderUnit::defineValue (const std::string& name, const std::string& source)
 
     // the shader's own fallback, like "#ifndef TRAILSUBDIVISION #define TRAILSUBDIVISION 0"
     std::smatch match;
-    if (std::regex_search (source, match, std::regex ("#define\\s+" + name + "\\s+(-?\\d+)"))) {
+    if (std::regex_search (source, match, Regex ("#define\\s+" + name + "\\s+(-?\\d+)"))) {
 	return std::stoi (match[1].str ());
     }
 
@@ -1463,14 +1525,13 @@ std::string ShaderUnit::applyGeometryOutputNames (std::string source) const {
 	return source;
     }
 
-    static const std::regex varyingDecl (R"(\bvarying\s+\w+\s+([A-Za-z_]\w*)\s*;)");
+    static const Regex varyingDecl (R"(\bvarying\s+\w+\s+([A-Za-z_]\w*)\s*;)");
     std::set<std::string> names;
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), varyingDecl); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), varyingDecl); it != RegexIterator (); ++it) {
 	names.insert ((*it)[1].str ());
     }
     for (const auto& name : names) {
-	source = std::regex_replace (source, std::regex ("\\b" + name + "\\b"), GEOMETRY_INPUT_PREFIX + name);
+	source = std::regex_replace (source, Regex ("\\b" + name + "\\b"), GEOMETRY_INPUT_PREFIX + name);
     }
 
     return source;
@@ -1478,15 +1539,15 @@ std::string ShaderUnit::applyGeometryOutputNames (std::string source) const {
 
 std::string ShaderUnit::applyGeometryDialect (std::string source) const {
     // [maxvertexcount(N)] -> the input and output layouts, N worked out with the combos this unit gets
-    static const std::regex maxVertexCount (R"(\[\s*maxvertexcount\s*\(([^\]]*)\)\s*\])");
+    static const Regex maxVertexCount (R"(\[\s*maxvertexcount\s*\(([^\]]*)\)\s*\])");
     std::smatch match;
     if (std::regex_search (source, match, maxVertexCount)) {
 	std::string expression = match[1].str ();
-	static const std::regex identifier (R"([A-Za-z_]\w*)");
+	static const Regex identifier (R"([A-Za-z_]\w*)");
 	std::string resolved;
 	auto last = expression.cbegin ();
-	for (auto it = std::sregex_iterator (expression.cbegin (), expression.cend (), identifier);
-	     it != std::sregex_iterator (); ++it) {
+	for (auto it = RegexIterator (expression.cbegin (), expression.cend (), identifier); it != RegexIterator ();
+	     ++it) {
 	    resolved.append (last, (*it)[0].first);
 	    resolved += std::to_string (this->defineValue ((*it)[0].str (), source));
 	    last = (*it)[0].second;
@@ -1503,45 +1564,41 @@ std::string ShaderUnit::applyGeometryDialect (std::string source) const {
 
     // the vertex stage's outputs arrive as arrays under the names applyGeometryOutputNames gave them (the same
     // names are often outputs here too, v_Color), gl_Position is a builtin on both sides
-    source = std::regex_replace (source, std::regex (R"(\b(in|out)\s+vec4\s+gl_Position\s*;)"), "");
+    source = std::regex_replace (source, Regex (R"(\b(in|out)\s+vec4\s+gl_Position\s*;)"), "");
     source = std::regex_replace (
-	source, std::regex (R"((^|\n)(\s*)in\s+(\w+)\s+(\w+)\s*;)"), "$1$2in $3 " GEOMETRY_INPUT_PREFIX "$4[];"
+	source, Regex (R"((^|\n)(\s*)in\s+(\w+)\s+(\w+)\s*;)"), "$1$2in $3 " GEOMETRY_INPUT_PREFIX "$4[];"
     );
 
-    source = std::regex_replace (
-	source, std::regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*gl_Position\b)"), "gl_in[$1].gl_Position"
-    );
-    source = std::regex_replace (
-	source, std::regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*(\w+))"), GEOMETRY_INPUT_PREFIX "$2[$1]"
-    );
+    source
+	= std::regex_replace (source, Regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*gl_Position\b)"), "gl_in[$1].gl_Position");
+    source = std::regex_replace (source, Regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*(\w+))"), GEOMETRY_INPUT_PREFIX "$2[$1]");
 
     // "PS_INPUT v;" is the vertex being written: its fields are the outputs themselves
-    static const std::regex vertexDecl (R"(\bPS_INPUT\s+(\w+)\s*;)");
+    static const Regex vertexDecl (R"(\bPS_INPUT\s+(\w+)\s*;)");
     if (std::regex_search (source, match, vertexDecl)) {
 	const std::string name = match[1].str ();
 	source = std::regex_replace (source, vertexDecl, "");
-	source = std::regex_replace (source, std::regex ("(^|[^\\w.])" + name + "\\s*\\.\\s*(\\w+)"), "$1$2");
+	source = std::regex_replace (source, Regex ("(^|[^\\w.])" + name + "\\s*\\.\\s*(\\w+)"), "$1$2");
 	source = std::regex_replace (
-	    source, std::regex ("\\bOUT\\s*\\.\\s*Append\\s*\\(\\s*" + name + "\\s*\\)\\s*;"), "EmitVertex();"
+	    source, Regex ("\\bOUT\\s*\\.\\s*Append\\s*\\(\\s*" + name + "\\s*\\)\\s*;"), "EmitVertex();"
 	);
     }
-    source = std::regex_replace (source, std::regex (R"(\bOUT\s*\.\s*RestartStrip\s*\(\s*\)\s*;)"), "EndPrimitive();");
+    source = std::regex_replace (source, Regex (R"(\bOUT\s*\.\s*RestartStrip\s*\(\s*\)\s*;)"), "EndPrimitive();");
 
     // HLSL lets a loop body redeclare its counter ("for (int s ...) { float s = ...") and use the new one from then
     // on, GLSL doesn't: the counter gets another name in the loop header
-    static const std::regex loopHeader (R"(for\s*\(\s*int\s+(\w+)\s*=[^;]*;[^;]*;[^)]*\))");
+    static const Regex loopHeader (R"(for\s*\(\s*int\s+(\w+)\s*=[^;]*;[^;]*;[^)]*\))");
     std::string result;
     auto last = source.cbegin ();
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), loopHeader); it != std::sregex_iterator ();
-	 ++it) {
+    for (auto it = RegexIterator (source.cbegin (), source.cend (), loopHeader); it != RegexIterator (); ++it) {
 	const std::string counter = (*it)[1].str ();
 	const size_t bodyStart = static_cast<size_t> ((*it)[0].second - source.cbegin ());
 	const size_t bodyEnd = std::min (source.size (), source.find ('}', bodyStart));
 	const std::string body = source.substr (bodyStart, bodyEnd - bodyStart);
 	std::string header = (*it)[0].str ();
 
-	if (std::regex_search (body, std::regex ("\\b(?:float|int|uint|vec[234])\\s+" + counter + "\\s*="))) {
-	    header = std::regex_replace (header, std::regex ("\\b" + counter + "\\b"), "wpeLoop_" + counter);
+	if (std::regex_search (body, Regex ("\\b(?:float|int|uint|vec[234])\\s+" + counter + "\\s*="))) {
+	    header = std::regex_replace (header, Regex ("\\b" + counter + "\\b"), "wpeLoop_" + counter);
 	}
 
 	result.append (last, (*it)[0].first);
@@ -1760,6 +1817,7 @@ void ShaderUnit::parseParameterConfiguration (
     if (material.has_value () && parameter != nullptr) {
 	parameter->setIdentifierName (*material);
 	parameter->setName (name);
+	parameter->setInDegrees (data.optional ("conversion", std::string ()) == "rad2deg");
 
 	this->m_parameters.push_back (parameter);
     }
@@ -1769,6 +1827,22 @@ const ComboMap& ShaderUnit::getCombos () const { return this->m_combos; }
 
 const ComboMap& ShaderUnit::getDiscoveredCombos () const { return this->m_discoveredCombos; }
 
+bool ShaderUnit::refersTo (const std::string& identifier) const {
+    const auto isWordChar = [] (const char c) { return std::isalnum (static_cast<unsigned char> (c)) || c == '_'; };
+
+    for (size_t at = this->m_preprocessed.find (identifier); at != std::string::npos;
+	 at = this->m_preprocessed.find (identifier, at + 1)) {
+	const size_t end = at + identifier.size ();
+
+	if ((at == 0 || !isWordChar (this->m_preprocessed[at - 1]))
+	    && (end == this->m_preprocessed.size () || !isWordChar (this->m_preprocessed[end]))) {
+	    return true;
+	}
+    }
+
+    return false;
+}
+
 void ShaderUnit::linkToUnit (const ShaderUnit* unit) { this->m_link = unit; }
 
 void ShaderUnit::feedGeometryStage () { this->m_feedsGeometry = true; }
@@ -1786,7 +1860,7 @@ const std::string& ShaderUnit::compile () {
     // (which is always true here). Adding a blanket compatibility macro would get expanded right
     // over such a shader's own function definition and mangle it, so only add it when the shader
     // doesn't already define log10 itself.
-    static const std::regex log10Definition (
+    static const Regex log10Definition (
 	R"(\b(?:void|float|int|uint|bool|vec[234]|ivec[234]|uvec[234]|bvec[234]|mat[234](?:x[234])?)\s+log10\s*\()"
     );
     // memoized per source, compile() runs again for every pass a text layer rebuilds
@@ -1876,8 +1950,21 @@ const std::string& ShaderUnit::compile () {
 	}
     }
 
-    // the header above already encodes the unit type and every define, so it works as the key
-    std::string cacheKey = this->m_final;
+    // these passes only read what's in the key (plus defines for geometry), so permutations share results
+    std::string cacheKey = std::to_string (this->m_type) + (this->m_feedsGeometry ? "g" : "");
+
+    if (this->m_type == GLSLContext::UnitType_Geometry) {
+	cacheKey += '\x1f';
+	cacheKey += this->m_final;
+
+	for (const auto& [name, value] : this->m_combos) {
+	    cacheKey += '\x1f';
+	    cacheKey += name;
+	    cacheKey += '=';
+	    cacheKey += std::to_string (value);
+	}
+    }
+
     cacheKey += '\x1f';
     cacheKey += this->m_preprocessed;
     cacheKey += '\x1f';
@@ -1886,13 +1973,6 @@ const std::string& ShaderUnit::compile () {
 	cacheKey += this->m_link->m_preprocessed;
     }
 
-    for (const auto& [name, value] : this->m_combos) {
-	cacheKey += '\x1f';
-	cacheKey += name;
-	cacheKey += '=';
-	cacheKey += std::to_string (value);
-    }
-
     {
 	std::lock_guard lock (cacheMutex);
 
@@ -1921,6 +2001,11 @@ const std::string& ShaderUnit::compile () {
 
     {
 	std::lock_guard lock (cacheMutex);
+
+	if (compatCache.size () >= MEMO_LIMIT) {
+	    compatCache.clear ();
+	}
+
 	compatCache.emplace (std::move (cacheKey), compat);
     }
 

+ 2 - 0
src/WallpaperEngine/Render/Shaders/ShaderUnit.h

@@ -44,6 +44,8 @@ public:
     [[nodiscard]] const ComboMap& getCombos () const;
     /** Combos discovered during preprocessing that weren't in the configured combo list */
     [[nodiscard]] const ComboMap& getDiscoveredCombos () const;
+    /** whole word match in the preprocessed source */
+    [[nodiscard]] bool refersTo (const std::string& identifier) const;
 
 protected:
     void preprocess ();

+ 4 - 0
src/WallpaperEngine/Render/Shaders/Variables/ShaderVariable.h

@@ -18,8 +18,12 @@ public:
 
     void setIdentifierName (std::string identifierName);
     void setName (const std::string& name);
+    /** "conversion":"rad2deg", scripts use degrees (sub_1401636A0) */
+    [[nodiscard]] bool isInDegrees () const { return this->m_inDegrees; }
+    void setInDegrees (bool inDegrees) { this->m_inDegrees = inDegrees; }
 
 private:
+    bool m_inDegrees = false;
     std::string m_identifierName;
     std::string m_name;
 };

+ 115 - 21
src/WallpaperEngine/Render/TextureCache.cpp

@@ -183,7 +183,7 @@ TextureUniquePtr buildRawTexture (const std::string& filename, const std::string
 
     auto result = std::make_unique<Texture> ();
 
-    result->containerVersion = ContainerVersion_TEXB0003;
+    result->containerVersion = 3;
     result->format = TextureFormat_ARGB8888;
     result->flags = animatedGif ? TextureFlags_ClampUVs | TextureFlags_NoInterpolation : TextureFlags_ClampUVs;
     result->width = width;
@@ -244,7 +244,7 @@ TextureUniquePtr buildIconTexture (const std::filesystem::path& path) {
 
     auto result = std::make_unique<Texture> ();
 
-    result->containerVersion = ContainerVersion_TEXB0003;
+    result->containerVersion = 3;
     result->format = TextureFormat_ARGB8888;
     result->flags = TextureFlags_ClampUVs;
     result->width = width;
@@ -258,42 +258,52 @@ TextureUniquePtr buildIconTexture (const std::filesystem::path& path) {
     return result;
 }
 
-// wallpaper64.exe 2.8.42 sub_140174A60: a plain name needs a boolean property that is true, the object form a string
-// property equal to its condition
-bool textureConditionHolds (const std::string& json, const Project& project) {
+struct TextureCondition {
+    std::string name;
+    std::optional<std::string> wanted;
+};
+
+std::optional<TextureCondition> parseTextureCondition (const std::string& json) {
     const auto parsed = JSON::parse (json, nullptr, false);
 
     if (!parsed.is_object () || !parsed.contains ("condition")) {
-	return false;
+	return std::nullopt;
     }
 
     const auto& condition = parsed["condition"];
-    std::string name;
-    const std::string* wanted = nullptr;
 
     if (condition.is_string ()) {
-	name = condition.get<std::string> ();
-    } else if (
-	condition.is_object () && condition.contains ("name") && condition["name"].is_string ()
-	&& condition.contains ("condition") && condition["condition"].is_string ()
-    ) {
-	name = condition["name"].get<std::string> ();
-	wanted = condition["condition"].get_ptr<const std::string*> ();
-    } else {
+	return TextureCondition { .name = condition.get<std::string> () };
+    }
+
+    if (condition.is_object () && condition.contains ("name") && condition["name"].is_string ()
+	&& condition.contains ("condition") && condition["condition"].is_string ()) {
+	return TextureCondition { .name = condition["name"].get<std::string> (),
+				  .wanted = condition["condition"].get<std::string> () };
+    }
+
+    return std::nullopt;
+}
+
+// sub_140174A60: a plain name needs a true bool property, the object form a string property equal to it
+bool textureConditionHolds (const std::string& json, const Project& project) {
+    const auto condition = parseTextureCondition (json);
+
+    if (!condition.has_value ()) {
 	return false;
     }
 
-    const auto property = project.properties.find (name);
+    const auto property = project.properties.find (condition->name);
 
     if (property == project.properties.end ()) {
 	return false;
     }
 
-    if (wanted == nullptr) {
+    if (!condition->wanted.has_value ()) {
 	return property->second->getType () == DynamicValue::Boolean && property->second->getBool ();
     }
 
-    return property->second->getType () == DynamicValue::String && property->second->getString () == *wanted;
+    return property->second->getType () == DynamicValue::String && property->second->getString () == *condition->wanted;
 }
 
 // how many bytes of patch pixels blitTexturePatch reads, WE doesn't check it
@@ -559,6 +569,16 @@ TextureCache::TextureCache (RenderContext& context) : Helpers::ContextAware (con
 
 TextureCache::~TextureCache () { this->m_mediaCallback (); }
 
+std::shared_ptr<const TextureProvider>
+TextureCache::findLoaded (const std::string& filename, const Project& project) const {
+    if (const auto shared = this->m_sharedTextures.find (filename); shared != this->m_sharedTextures.end ()) {
+	return shared->second;
+    }
+
+    const auto found = this->m_textureCache.find (std::make_pair (&project, filename));
+    return found != this->m_textureCache.end () ? found->second : nullptr;
+}
+
 std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string& filename, const Project& requester) {
     if (const auto shared = this->m_sharedTextures.find (filename); shared != this->m_sharedTextures.end ()) {
 	return shared->second;
@@ -592,8 +612,7 @@ std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string&
 	} catch (AssetLoadException&) {
 	    // WE picks the image decoder from the file contents (resourceutil64 FreeImage_GetFileTypeU), so
 	    // e.g. a user-picked .jfif loads just like a .jpg
-	    const auto raw = project.assetLocator->read (filename);
-	    const std::string contents ((std::istreambuf_iterator<char> (*raw)), std::istreambuf_iterator<char> ());
+	    const std::string contents = project.assetLocator->readString (filename);
 	    int width;
 	    int height;
 
@@ -604,10 +623,19 @@ std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string&
 
 	    parsedTexture = buildRawTexture (filename, contents);
 	}
+	std::vector<std::string> conditionProperties;
+
+	for (const auto& condition : parsedTexture->conditions) {
+	    if (const auto parsed = parseTextureCondition (condition.json); parsed.has_value ()) {
+		conditionProperties.push_back (parsed->name);
+	    }
+	}
+
 	auto texture = std::make_shared<CTexture> (this->getContext (), std::move (parsedTexture));
 	texture->label (filename);
 
 	this->m_textureCache.insert_or_assign (key, texture);
+	this->followConditions (texture, project, filename, conditionProperties);
 
 	return texture;
     };
@@ -634,6 +662,64 @@ std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string&
     throw AssetLoadException ("Cannot find file", filename, std::error_code ());
 }
 
+void TextureCache::followConditions (
+    const std::shared_ptr<CTexture>& texture, const Project& project, const std::string& filename,
+    const std::vector<std::string>& properties
+) {
+    auto entry = std::make_unique<ConditionalTexture> (ConditionalTexture {
+	.texture = texture,
+	.project = &project,
+	.filename = filename,
+    });
+
+    for (const auto& name : properties) {
+	if (const auto property = project.properties.find (name); property != project.properties.end ()) {
+	    entry->listeners.push_back (property->second->listen ([dirty = &entry->dirty] (const DynamicValue&, auto) {
+		*dirty = true;
+	    }));
+	}
+    }
+
+    if (!entry->listeners.empty ()) {
+	this->m_conditionalTextures.push_back (std::move (entry));
+    }
+}
+
+void TextureCache::repaintConditionalTextures () {
+    const auto& backgrounds = this->getContext ().getApp ().getBackgrounds ();
+
+    for (const auto& entry : this->m_conditionalTextures) {
+	if (!entry->dirty) {
+	    continue;
+	}
+
+	entry->dirty = false;
+	const auto texture = entry->texture.lock ();
+	const bool alive = std::ranges::any_of (backgrounds, [&entry] (const auto& background) {
+	    return background.second.get () == entry->project;
+	});
+
+	if (texture == nullptr || !alive) {
+	    continue;
+	}
+
+	// patches are picked while parsing (sub_14015C8D0), so parse again
+	try {
+	    const auto contents = entry->project->assetLocator->texture (entry->filename);
+	    auto stream = BinaryReader (contents);
+	    auto parsed = TextureParser::parse (stream);
+
+	    applyTexturePatches (*parsed, *entry->project);
+
+	    if (!texture->repaint (std::move (parsed))) {
+		sLog.error ("Cannot repaint ", entry->filename, " for a property change, the texture layout differs");
+	    }
+	} catch (const std::exception& e) {
+	    sLog.error ("Cannot repaint ", entry->filename, " for a property change: ", e.what ());
+	}
+    }
+}
+
 void TextureCache::store (const std::string& name, std::shared_ptr<const TextureProvider> texture) {
     this->m_sharedTextures.insert_or_assign (name, texture);
 }
@@ -649,4 +735,12 @@ void TextureCache::prune () {
 
 	return !alive || entry.second.use_count () == 1;
     });
+
+    std::erase_if (this->m_conditionalTextures, [&backgrounds] (const auto& entry) {
+	const bool alive = std::ranges::any_of (backgrounds, [&entry] (const auto& background) {
+	    return background.second.get () == entry->project;
+	});
+
+	return !alive || entry->texture.expired ();
+    });
 }

+ 27 - 0
src/WallpaperEngine/Render/TextureCache.h

@@ -15,6 +15,7 @@ using namespace WallpaperEngine::Render;
 
 namespace WallpaperEngine::Render {
 class AlbumTexture;
+class CTexture;
 namespace Helpers {
     class ContextAware;
 }
@@ -29,6 +30,9 @@ public:
     /** Returns the texture for filename as seen by the given project, cached per project since wallpapers reuse file
      * names */
     std::shared_ptr<const TextureProvider> resolve (const std::string& filename, const Data::Model::Project& project);
+    /** nullptr unless already loaded for that project */
+    [[nodiscard]] std::shared_ptr<const TextureProvider>
+    findLoaded (const std::string& filename, const Data::Model::Project& project) const;
 
     /** Registers a texture that is shared by every project (media thumbnails and such) */
     void store (const std::string& name, std::shared_ptr<const TextureProvider> texture);
@@ -36,7 +40,30 @@ public:
     /** Drops every cached texture that no wallpaper is using anymore */
     void prune ();
 
+    /** TEXB0004 textures whose conditions changed */
+    void repaintConditionalTextures ();
+
 private:
+    struct ConditionalTexture {
+	std::weak_ptr<CTexture> texture;
+	const Data::Model::Project* project;
+	std::string filename;
+	std::vector<std::function<void ()>> listeners = {};
+	bool dirty = false;
+
+	~ConditionalTexture () {
+	    for (const auto& deregister : this->listeners) {
+		deregister ();
+	    }
+	}
+    };
+
+    void followConditions (
+	const std::shared_ptr<CTexture>& texture, const Data::Model::Project& project, const std::string& filename,
+	const std::vector<std::string>& properties
+    );
+
+    std::vector<std::unique_ptr<ConditionalTexture>> m_conditionalTextures = {};
     std::shared_ptr<const AlbumTexture> m_previousThumbnail = nullptr;
     std::shared_ptr<const AlbumTexture> m_currentThumbnail = nullptr;
     std::map<std::string, std::shared_ptr<const TextureProvider>> m_sharedTextures = {};

+ 3 - 3
src/WallpaperEngine/Render/Volumetrics.cpp

@@ -732,7 +732,7 @@ void Volumetrics::renderLight (
     this->copySceneDepth (previousFramebuffer);
 
     const bool spot = light.type == Data::Model::LightType::Spot;
-    const bool cookie = spot && light.useCookie;
+    const bool cookie = spot && light.useCookie->value->getBool ();
     const float radius = light.radius->value->getFloat ();
     const glm::vec3 origin (world[3]);
     const auto& fog = this->m_scene.getFog ();
@@ -741,8 +741,8 @@ void Volumetrics::renderLight (
 	? glm::vec3 (0.0f, 0.0f, -1.0f)
 	: -glm::vec3 (camera.getView ()[0][2], camera.getView ()[1][2], camera.getView ()[2][2]);
     const glm::vec3 probe = fog.eyeWorld + forward * 0.2f - origin;
-    const bool shadowed
-	= light.castShadow && this->m_scene.getContext ().getApp ().getContext ().settings.general.shadowQuality > 0;
+    const bool shadowed = light.castShadow->value->getBool ()
+	&& this->m_scene.getContext ().getApp ().getContext ().settings.general.shadowQuality > 0;
     glm::mat4 volume;
     bool inside;
 

Datei-Diff unterdrückt, da er zu groß ist
+ 363 - 439
src/WallpaperEngine/Render/Wallpapers/CScene.cpp


+ 87 - 27
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -5,6 +5,7 @@
 #include "WallpaperEngine/Render/ModelData.h"
 
 #include "WallpaperEngine/Render/CWallpaper.h"
+#include "WallpaperEngine/Render/FrameMaterial.h"
 #include "WallpaperEngine/Render/ShadowMapping.h"
 #include "WallpaperEngine/Render/Volumetrics.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
@@ -18,6 +19,9 @@ class CObject;
 namespace Objects {
     struct PuppetRopeEnvironment;
     class CLight;
+    namespace Effects {
+	class CPass;
+    }
 }
 }
 
@@ -62,6 +66,7 @@ public:
     [[nodiscard]] bool isRenderingReflection () const { return this->m_renderingReflection; }
     /** Keeps fbo at the output's size / divisor, like the buffers WE makes from the window client size */
     void followOutputSize (const std::shared_ptr<CFBO>& fbo, float divisor);
+    void followOutputSize (const std::shared_ptr<CFBO>& fbo, const FBO& base);
 
     [[nodiscard]] int getWidth () const override;
     [[nodiscard]] int getHeight () const override;
@@ -105,6 +110,9 @@ public:
     [[nodiscard]] bool rendersAtOutputSize () const override { return true; }
     /** Pixel size of the output being drawn, what WE's window client area (and _rt_FullFrameBuffer) would be */
     [[nodiscard]] glm::ivec2 getOutputSize () const { return this->m_outputSize; }
+    /** 1 and 0.5 over the client size (sub_14017F1B0), refreshed every frame */
+    [[nodiscard]] const glm::vec2* getTexelSize () const { return &this->m_texelSize; }
+    [[nodiscard]] const glm::vec2* getTexelSizeHalf () const { return &this->m_texelSizeHalf; }
     [[nodiscard]] bool isCursorLeftDown () const { return this->m_cursorLeftDown; }
     /** Position fed to shaders as g_ParallaxPosition: 0.5 +- the smoothed, influence-scaled mouse offset */
     const glm::vec2* getParallaxPosition () const;
@@ -118,8 +126,21 @@ public:
     [[nodiscard]] static glm::mat4 objectLocalMatrix (const Data::Model::Object& object);
     /** T * Rz * Ry * Rx * S down the parent chain, WE's object world matrix (sub_1401850A0) */
     [[nodiscard]] glm::mat4 objectWorldMatrix (const Data::Model::Object& object) const;
+    /** Without scale (sub_1401DD7D0) */
+    [[nodiscard]] glm::mat4 objectFrameMatrix (const Data::Model::Object& object) const;
+    /** ILayer.setParent (sub_1401DE750). False is WE's "Invalid parent configuration.", the object loses its parent */
+    bool setObjectParent (CObject& object, const CObject* parent, int attachment, bool adjustTransforms);
+    /** WE's children list order (object +408) */
+    [[nodiscard]] std::vector<CObject*> childrenOf (int id) const;
+    /** sub_14018B730: removed after this frame's scripts, lookups skip it until then */
+    bool queueDestroyLayer (CObject& object);
+    [[nodiscard]] bool isPendingDestroy (const CObject& object) const;
+    [[nodiscard]] size_t getPendingDestroyCount () const { return this->m_pendingDestroy.size (); }
+    [[nodiscard]] bool scriptsMayReparent () const;
 
     [[nodiscard]] const std::vector<CObject*>& getObjectsByRenderOrder () const;
+    /** Seconds until the first image layer's next sprite frame (sub_140110630), nullopt without the flag */
+    [[nodiscard]] std::optional<float> spriteSheetSyncDelay () const;
     /** g_Fog* uniforms (sub_140186440). Height params come in two versions: WE's world (y up from the bottom) and
      *  the space 2D objects are laid out in here (y down from the center), the same in 3D scenes */
     struct FogUniforms {
@@ -142,6 +163,10 @@ public:
     [[nodiscard]] glm::ivec2 getOutputResolution () const;
     /** WE's world (scene units, y up from the bottom left in 2D) to clip space of the scene buffer */
     [[nodiscard]] glm::mat4 getWorldViewProjection (bool perspectiveLayer = false) const;
+    /** Near plane point and direction for ndc */
+    void cursorLine (const glm::vec2& ndc, bool perspectiveLayer, glm::vec3& origin, glm::vec3& direction) const;
+    /** With WE's depth range (renderer +0x930), for model culling */
+    [[nodiscard]] glm::mat4 getCullViewProjection () const;
     [[nodiscard]] const CObject* getObject (int id) const;
     [[nodiscard]] CObject* getObject (int id);
     /** Whether the quad (-half..half, z 0) drawn through mvp covers the clip space point ndc. A planar quad stays
@@ -174,6 +199,7 @@ public:
     void resolveMultisample () const;
     /** IEffect.executeMaterialFunction on whichever object owns the effect */
     void executeEffectFunction (const ImageEffect& effect, const std::string& name) const;
+    [[nodiscard]] Objects::Effects::CPass* findEffectMaterial (const ImageEffect& effect, size_t passIndex) const;
     /** Under a passthrough layer, which draws the object into its own buffer instead of the scene (object flag 2) */
     [[nodiscard]] bool isDrawnByPassthroughLayer (const CObject& object) const;
     /** Draws the objects under a passthrough layer into target, WE's order and visibility rules (sub_1401ECB20) */
@@ -232,7 +258,13 @@ public:
     [[nodiscard]] bool isShadowCasterVisible (const CObject& object) const;
     /** The texture lit materials sample for cookie spots ("_alias_lightCookie"), null without a cookie spot */
     [[nodiscard]] std::shared_ptr<const TextureProvider> getLightCookie () const;
-    /** The render order as scripts see it: without the synthesized bloom layer */
+    /** made on first use */
+    [[nodiscard]] std::shared_ptr<const TextureProvider> getMissingTexture () const;
+    /** what D3D11 reads from an unbound resource */
+    [[nodiscard]] GLuint getNullTexture () const;
+    /** see CImage::usesPooledBuffer, uncreated objects are judged by their scene data */
+    [[nodiscard]] bool hasNamedLayerBuffer (int id) const;
+    /** render order as scripts see it */
     [[nodiscard]] std::vector<CObject*> getLayers () const;
     [[nodiscard]] int getObjectIndex (const CObject* object) const;
 
@@ -277,6 +309,8 @@ public:
     /** A model layer's reference (sub_14021AD10), released with releaseModelData */
     std::shared_ptr<ModelData::Model> acquireModelData (int token);
     void releaseModelData (uint32_t token);
+    /** Read once per scene load and shared, like WE's model map (sub_1401D5A40) */
+    [[nodiscard]] std::shared_ptr<const std::vector<char>> readModelFile (const std::string& filename);
 
 protected:
     void appendLayer (CObject* object);
@@ -312,11 +346,16 @@ private:
     void updateCamera ();
     /** Scene camera paths without a camera object, advances them by dt and writes this frame's camera */
     void updateCameraPath (float dt, glm::vec3& eye, glm::vec3& center, glm::vec3& up, float& zoom);
-    /** camerafade overlay over the finished scene */
+    /** sub_14017FA70: bloom and combine */
+    void renderPostProcessing ();
+    [[nodiscard]] glm::ivec2 backBufferSize () const;
+    /** at the start and end of a camera path */
     void renderCameraFade ();
-    /** WE's HDR bloom (sub_140183610) and combine_hdr_upsample into the scene buffer */
+    [[nodiscard]] bool drawsImageAdjustments () const override { return true; }
+    void renderBloom ();
     void renderHDRBloom ();
-    void releaseHDRBloom ();
+    /** (white, peak - white) / 80, (1, 1) on SDR */
+    [[nodiscard]] glm::vec2 combineRenderVar () const;
     /** Copies the finished scene into _rt_MipMappedFrameBuffer and rebuilds its mips, WE does it before bloom */
     void updateMipMappedFrameBuffer () const;
     /** The scene mirrored on the world's y = 0 plane into _rt_Reflection, before the main pass */
@@ -335,7 +374,10 @@ private:
     /** Draw call of an object under a passthrough layer, sub_1401ECA70 walks the rest of the subtree depth first */
     void renderPassthroughSubtree (int parentId, int depth);
     void renderPassthroughChild (CObject* object);
-    [[nodiscard]] std::vector<CObject*> childrenOf (int id) const;
+    /** includes the attachment point */
+    [[nodiscard]] glm::mat4 parentChainMatrix (const Data::Model::Object& object, bool scaled) const;
+    /** sub_1401DDB50 */
+    [[nodiscard]] int passthroughDepth (const CObject& object) const;
     /** Back to front along the camera's view direction, WE's transparent sort (sub_1401865C0) */
     [[nodiscard]] std::vector<CObject*> sortedByDepth (std::vector<CObject*> objects) const;
     /** transparentsorting list membership, decided when the object is created (object flag 0x100, sub_14018FF60) */
@@ -347,14 +389,18 @@ private:
     void addObjectToRenderOrder (const Object& object);
 
     std::unique_ptr<Scripting::ScriptEngine> m_scriptEngine;
+    /** general settings' scripts and animations */
+    ObjectUniquePtr m_settingsScriptsData;
+    std::unique_ptr<Scripting::ScriptableObject> m_settingsScripts;
     std::unique_ptr<Camera> m_camera;
-    ObjectUniquePtr m_bloomObjectData;
-    CObject* m_bloomObject = nullptr;
     std::map<int, CObject*> m_objects = {};
     std::set<int> m_objectsInCreation = {};
     std::set<int> m_objectsInRenderOrderWalk = {};
     std::map<int, bool> m_soundPlayRequests = {};
     ModelData::Store m_modelData;
+    /** cleared once the constructor is done */
+    std::map<std::string, std::shared_ptr<const std::vector<char>>> m_modelFiles = {};
+    bool m_loading = true;
     StaticCamera m_staticCamera;
     bool m_staticCameraLoaded = false;
     /** checkModelDataMaterial results, compiling the material's shader every time would be slow */
@@ -373,26 +419,27 @@ private:
     bool m_fogDistance = false;
     bool m_fogHeight = false;
     bool m_hdr = false;
-    /** HDR bloom: mip chain at half the output resolution and down, see renderHDRBloom () */
-    struct BloomLevel {
-	GLuint texture = GL_NONE;
-	GLuint framebuffer = GL_NONE;
-	glm::ivec2 size {};
-    };
-    std::vector<BloomLevel> m_bloomLevels;
-    BloomLevel m_hdrCopy;
-    glm::ivec2 m_bloomResolution {};
-    GLuint m_bloomDownsample = GL_NONE;
-    GLuint m_bloomDownsampleThreshold = GL_NONE;
-    GLuint m_bloomUpsample = GL_NONE;
-    GLuint m_bloomUpsampleCubic = GL_NONE;
     /** "displayhdr" post processing: combine_dhdr_upsample */
     bool m_displayHDR = false;
-    GLuint m_bloomCombine = GL_NONE;
-    GLuint m_fadeProgram = GL_NONE;
+    /** sub_14017FA70, loaded on the first frame */
+    struct FrameMaterials {
+	std::unique_ptr<FrameMaterial> combine;
+	/** HDR without bloom */
+	std::unique_ptr<FrameMaterial> combineWithoutBloom;
+	std::unique_ptr<FrameMaterial> downsampleQuarterBloom;
+	std::unique_ptr<FrameMaterial> downsampleEighthBlurV;
+	std::unique_ptr<FrameMaterial> blurHBloom;
+	std::unique_ptr<FrameMaterial> hdrDownsampleBloom;
+	std::unique_ptr<FrameMaterial> hdrDownsample;
+	std::unique_ptr<FrameMaterial> hdrUpsample;
+	std::unique_ptr<FrameMaterial> hdrUpsampleCubic;
+	std::unique_ptr<FrameMaterial> fade;
+    };
+    std::unique_ptr<FrameMaterials> m_frameMaterials;
+    /** sub_14017F1B0 */
+    std::vector<std::shared_ptr<CFBO>> m_hdrBloomLevels;
     std::vector<DynamicValue*> m_scriptedValues = {};
-    // owns the synthesized model data backing createLayer()'d objects; must outlive the CObject
-    // built from it (same pattern as m_bloomObjectData)
+    // backs createLayer() objects, must outlive them
     std::vector<ObjectUniquePtr> m_dynamicObjectData = {};
     int m_nextDynamicLayerId = 2000000000;
     std::map<std::string, std::string> m_createLayerAliases = {};
@@ -404,6 +451,8 @@ private:
     /** Cursor in output pixels from the viewport's top left, unclamped and unflipped (WE's ScreenToClient point) */
     glm::vec2 m_mousePositionViewport = {};
     glm::ivec2 m_outputSize = {};
+    glm::vec2 m_texelSize = { 1.0f, 1.0f };
+    glm::vec2 m_texelSizeHalf = { 0.5f, 0.5f };
     /** Smoothed camera offset from the scene center as a fraction of the scene size, in mouse coordinates */
     glm::vec2 m_cameraParallax = {};
     glm::vec2 m_parallaxPosition = { 0.5f, 0.5f };
@@ -427,9 +476,6 @@ private:
     std::set<int> m_cursorPressed = {};
     std::vector<LayerTarget> m_layerTargets = {};
     std::map<const CObject*, bool> m_transparentSorted = {};
-    std::shared_ptr<const CFBO> _rt_4FrameBuffer = nullptr;
-    std::shared_ptr<const CFBO> _rt_8FrameBuffer = nullptr;
-    std::shared_ptr<const CFBO> _rt_Bloom = nullptr;
     std::shared_ptr<const CFBO> _rt_shadowAtlas = nullptr;
     std::shared_ptr<const CFBO> _rt_MipMappedFrameBuffer = nullptr;
     std::shared_ptr<CFBO> _rt_Reflection = nullptr;
@@ -447,9 +493,23 @@ private:
     struct OutputSizedBuffer {
 	std::weak_ptr<CFBO> fbo;
 	float divisor;
+	const FBO* base = nullptr;
+
+	[[nodiscard]] glm::uvec2 sizeFor (glm::ivec2 output) const;
     };
     std::vector<OutputSizedBuffer> m_outputSizedBuffers = {};
     glm::ivec2 m_outputBufferSize = {};
     void resizeOutputBuffers (glm::ivec2 size);
+    mutable std::optional<bool> m_scriptsMayReparent = std::nullopt;
+    /** WE's order (object +408) */
+    std::unordered_map<int, std::vector<int>> m_children = {};
+    void attachChild (const CObject& child);
+    void detachChild (const CObject& child);
+    std::set<CObject*> m_pendingDestroy = {};
+    /** deleted with the scene */
+    std::vector<CObject*> m_destroyedObjects = {};
+    void destroyPendingLayers ();
+    mutable std::shared_ptr<const TextureProvider> m_missingTexture = nullptr;
+    mutable GLuint m_nullTexture = GL_NONE;
 };
 } // namespace WallpaperEngine::Render::Wallpaper

+ 8 - 0
src/WallpaperEngine/Render/Wallpapers/CSplat.cpp

@@ -421,6 +421,14 @@ CSplat::CSplat (
 ) : CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) {
     this->setupFramebuffers ();
     this->loadCloud ();
+
+    // pick the data loadCloud () reads, the rest is read every frame
+    for (const char* name : { "sogPreset", "sogmeta", "sogdirectory" }) {
+	if (const auto property = this->getWallpaperData ().project.properties.find (name);
+	    property != this->getWallpaperData ().project.properties.end ()) {
+	    property->second->pin ();
+	}
+    }
 }
 
 CSplat::~CSplat () {

+ 108 - 9
src/WallpaperEngine/Render/Wallpapers/CVideo.cpp

@@ -5,6 +5,7 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
 
+#include <algorithm>
 #include <cmath>
 
 using namespace WallpaperEngine;
@@ -18,6 +19,7 @@ CVideo::CVideo (
 ) : CWallpaper (wallpaper, context, audioContext, scalingMode, clampMode) {
     // with --hdr the video keeps its highlights, the output shader turns it into PQ or sRGB per monitor
     const bool hdr = this->getContext ().getDriver ().isHDRAvailable ();
+    this->m_hdr = hdr;
 
     this->setupFramebuffers (false, hdr ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888);
     this->setLinearInput (hdr);
@@ -36,7 +38,7 @@ CVideo::CVideo (
     this->m_player->setVolume (audioSettings.enabled ? audioSettings.volume * 100.0 / 128.0 : 0.0);
     const auto& renderSettings = this->getContext ().getApp ().getContext ().settings.render;
     this->m_player->setSpeed (renderSettings.playbackSpeed);
-    this->setLoopRange (renderSettings.videoStart, renderSettings.videoEnd);
+    this->setSegments (renderSettings.videoSegments);
 
     if (hdr) {
 	this->m_player->setLinearOutput ();
@@ -50,7 +52,21 @@ CVideo::~CVideo () { this->m_player->decrementUsageCount (); }
 void CVideo::renderFrame (const glm::ivec4& viewport) {
     this->updateMuteState ();
 
+    this->m_presentBackBuffer = false;
     this->m_player->render ();
+
+    // mpv reallocates the texture at the video's size later, the CFBO was made at 16x16
+    if (const auto fbo = this->find ("_rt_FullFrameBuffer"); fbo != nullptr
+	&& (static_cast<int> (fbo->getRealWidth ()) != this->getWidth ()
+	    || static_cast<int> (fbo->getRealHeight ()) != this->getHeight ())) {
+	fbo->resize (this->getWidth (), this->getHeight ());
+	this->m_player->requestRedraw ();
+	this->m_player->render ();
+    }
+
+    if (!this->m_hdr) {
+	this->renderImageAdjustments ({ this->getWidth (), this->getHeight () }, GL_RGBA8);
+    }
 }
 
 void CVideo::updateMuteState () {
@@ -85,14 +101,8 @@ void CVideo::setVolume (double volume) { this->m_player->setVolume (volume); }
 
 void CVideo::setSpeed (double speed) { this->m_player->setSpeed (speed); }
 
-void CVideo::setLoopRange (const std::optional<double> start, const std::optional<double> end) {
-    if (start.has_value () && end.has_value () && *end <= *start) {
-	sLog.error ("Video end (", *end, "s) must come after its start (", *start, "s), playing all of it");
-	this->m_player->setLoopRange (std::nullopt, std::nullopt);
-	return;
-    }
-
-    this->m_player->setLoopRange (start, end);
+void CVideo::setSegments (const VideoPlayback::VideoSegments& segments) {
+    this->m_player->setSegments (normalizeSegments (segments));
 }
 
 void CVideo::seek (const double seconds) { this->m_player->seek (seconds); }
@@ -129,6 +139,95 @@ std::optional<double> CVideo::parseTime (const std::string& value) {
     return std::nullopt;
 }
 
+std::optional<VideoPlayback::VideoSegments> CVideo::parseSegments (const std::string& value) {
+    VideoPlayback::VideoSegments segments;
+    std::size_t begin = 0;
+
+    const auto trim = [] (std::string text) {
+	const auto first = text.find_first_not_of (" \t");
+	const auto last = text.find_last_not_of (" \t");
+	return first == std::string::npos ? std::string () : text.substr (first, last - first + 1);
+    };
+
+    while (begin <= value.size ()) {
+	const auto comma = value.find (',', begin);
+	const std::string part = trim (value.substr (begin, comma == std::string::npos ? comma : comma - begin));
+	begin = comma == std::string::npos ? value.size () + 1 : comma + 1;
+
+	if (part.empty ()) {
+	    continue;
+	}
+
+	const auto dash = part.find ('-');
+
+	if (dash == std::string::npos) {
+	    return std::nullopt;
+	}
+
+	const std::string startText = trim (part.substr (0, dash));
+	const std::string endText = trim (part.substr (dash + 1));
+	VideoPlayback::VideoSegment segment;
+
+	if (!startText.empty ()) {
+	    const auto start = parseTime (startText);
+
+	    if (!start.has_value ()) {
+		return std::nullopt;
+	    }
+
+	    segment.start = *start;
+	}
+
+	if (!endText.empty ()) {
+	    segment.end = parseTime (endText);
+
+	    if (!segment.end.has_value ()) {
+		return std::nullopt;
+	    }
+	}
+
+	segments.push_back (segment);
+    }
+
+    return segments;
+}
+
+VideoPlayback::VideoSegments CVideo::normalizeSegments (VideoPlayback::VideoSegments segments) {
+    std::erase_if (segments, [] (const VideoPlayback::VideoSegment& segment) {
+	if (!segment.end.has_value () || *segment.end > segment.start) {
+	    return false;
+	}
+
+	sLog.error ("Video part ", segment.start, "s - ", *segment.end, "s ends before it starts, skipping it");
+	return true;
+    });
+
+    std::sort (segments.begin (), segments.end (), [] (const auto& a, const auto& b) { return a.start < b.start; });
+
+    VideoPlayback::VideoSegments merged;
+
+    for (const auto& segment : segments) {
+	if (merged.empty () || (merged.back ().end.has_value () && segment.start > *merged.back ().end)) {
+	    merged.push_back (segment);
+	    continue;
+	}
+
+	auto& last = merged.back ();
+
+	if (!segment.end.has_value ()) {
+	    last.end.reset ();
+	} else if (last.end.has_value ()) {
+	    last.end = std::max (*last.end, *segment.end);
+	}
+    }
+
+    if (merged.size () == 1 && merged.front ().start <= 0.0 && !merged.front ().end.has_value ()) {
+	merged.clear ();
+    }
+
+    return merged;
+}
+
 void CVideo::setPause (bool newState) {
     if (newState) {
 	this->m_player->setPaused ();

+ 9 - 2
src/WallpaperEngine/Render/Wallpapers/CVideo.h

@@ -29,18 +29,24 @@ public:
     /** Pushes a new playback speed multiplier to the underlying mpv player without a reload, see --speed */
     void setSpeed (double speed);
 
-    /** Loops only the part between start and end (seconds, either one open), see --video-start/--video-end */
-    void setLoopRange (std::optional<double> start, std::optional<double> end);
+    void setSegments (const VideoPlayback::VideoSegments& segments);
 
     /** Jumps to a position in seconds without changing the loop range */
     void seek (double seconds);
 
     /** Seconds from "90", "1:30" or "0:01:30.5", nullopt if the text is none of those */
     static std::optional<double> parseTime (const std::string& value);
+    /** "2:00-3:00,4:00-5:00", empty sides are open, nullopt on a bad part */
+    static std::optional<VideoPlayback::VideoSegments> parseSegments (const std::string& value);
+    /** Sorted and merged, an open end swallows the rest, the whole video gives no segments */
+    static VideoPlayback::VideoSegments normalizeSegments (VideoPlayback::VideoSegments segments);
 
     /** ambientVolume is ignored - video wallpapers always use --volume, only muted matters here */
     void setAudioPolicy (bool muted, std::optional<int> ambientVolume) override;
 
+    /** WE 2.8 plays videos in its scene renderer (sub_140120050), --hdr has no WE counterpart */
+    [[nodiscard]] bool drawsImageAdjustments () const override { return !this->m_hdr; }
+
 protected:
     void renderFrame (const glm::ivec4& viewport) override;
 
@@ -51,6 +57,7 @@ private:
 
     GLPlayerUniquePtr m_player;
 
+    bool m_hdr = false;
     bool m_muted = false;
     /** Forced mute from --audio-screen (this screen isn't the designated audio screen) */
     bool m_forceMuted = false;

+ 116 - 18
src/WallpaperEngine/Render/Wallpapers/CWeb.cpp

@@ -17,6 +17,7 @@
 #include <csignal>
 #include <cstdlib>
 #include <cstring>
+#include <string_view>
 #include <sys/prctl.h>
 #include <sys/syscall.h>
 #include <sys/wait.h>
@@ -38,6 +39,31 @@ void closeInheritedFds () {
 #endif
 }
 
+// a page paints its background long before its content, so a flat color doesn't count. Samples a grid
+bool frameHasContent (const uint8_t* pixels, uint32_t width, uint32_t height) {
+    constexpr uint32_t columns = 48;
+    constexpr uint32_t rows = 27;
+    constexpr int tolerance = 2;
+    const uint8_t* first = pixels;
+
+    for (uint32_t row = 0; row < rows; row++) {
+	const uint32_t y = (height - 1) * row / (rows - 1);
+
+	for (uint32_t column = 0; column < columns; column++) {
+	    const uint32_t x = (width - 1) * column / (columns - 1);
+	    const uint8_t* pixel = pixels + (static_cast<size_t> (y) * width + x) * 4;
+
+	    for (int channel = 0; channel < 4; channel++) {
+		if (std::abs (pixel[channel] - first[channel]) > tolerance) {
+		    return true;
+		}
+	    }
+	}
+    }
+
+    return false;
+}
+
 // When the engine binary gets reinstalled while we're running, /proc/self/exe points at
 // "<path> (deleted)". exec'ing /proc/self/exe still works, but CEF resolves its own executable
 // through that link to start the zygote and aborts on the nonexistent path. The shared libs are
@@ -83,6 +109,9 @@ CWeb::CWeb (
 	sLog.exception ("CWeb: failed to create shared memory for the web host process");
     }
 
+    // lay out at the real size right away
+    this->m_width = static_cast<int> (this->m_shmMaxWidth);
+    this->m_height = static_cast<int> (this->m_shmMaxHeight);
     this->m_shm->desiredWidth.store (static_cast<uint32_t> (this->m_width), std::memory_order_relaxed);
     this->m_shm->desiredHeight.store (static_cast<uint32_t> (this->m_height), std::memory_order_relaxed);
 
@@ -90,12 +119,10 @@ CWeb::CWeb (
     auto* shm = this->m_shm;
 
     this->m_spectrumRecorder = &this->getAudioContext ().getRecorder ();
-    this->m_spectrumListenerId = this->m_spectrumRecorder->addSpectrumListener ([shm] (const float* audio64) {
+    this->m_spectrumListenerId = this->m_spectrumRecorder->addSpectrumListener ([shm] (const float* bands) {
 	for (std::size_t i = 0; i < WebHostSharedMemory::AUDIO_BANDS; i++) {
-	    shm->audioBands[i].store (audio64[i], std::memory_order_relaxed);
+	    shm->audioBands[i].store (bands[i], std::memory_order_relaxed);
 	}
-
-	shm->audioSeq.fetch_add (1, std::memory_order_release);
     });
 
     this->m_statsEnabled = std::getenv ("LWE_WEB_STATS") != nullptr;
@@ -107,6 +134,26 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
     auto& appContext = this->getContext ().getApp ().getContext ();
     const std::string executable = hostExecutable ();
 
+    // tests only (HEADLESS_RENDER_WEB=1): LD_PRELOAD for the host alone, libcef.so before libc for its close() wrapper
+    std::vector<std::string> environment;
+    std::vector<char*> envp;
+
+    if (const char* preload = std::getenv ("LWE_WEB_HOST_PRELOAD"); preload != nullptr && preload[0] != '\0') {
+	for (char** entry = environ; *entry != nullptr; entry++) {
+	    if (!std::string_view (*entry).starts_with ("LD_PRELOAD=")) {
+		environment.emplace_back (*entry);
+	    }
+	}
+
+	environment.emplace_back (std::string ("LD_PRELOAD=") + preload);
+
+	for (auto& entry : environment) {
+	    envp.push_back (entry.data ());
+	}
+
+	envp.push_back (nullptr);
+    }
+
     const pid_t pid = fork ();
 
     if (pid < 0) {
@@ -157,7 +204,11 @@ void CWeb::spawnHost (const std::filesystem::path& resolvedBackgroundPath) {
 
 	argv.push_back (nullptr);
 
-	execv (executable.c_str (), argv.data ());
+	if (envp.empty ()) {
+	    execv (executable.c_str (), argv.data ());
+	} else {
+	    execve (executable.c_str (), argv.data (), envp.data ());
+	}
 
 	// only reached if execv() itself failed
 	_exit (127);
@@ -226,31 +277,50 @@ void CWeb::renderFrame (const glm::ivec4& viewport) {
 	return;
     }
 
-    glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture ());
-
-    // only reallocate when the size changed, glTexSubImage2D avoids a driver-side realloc/sync every frame
-    if (frameWidth == this->m_uploadedTextureWidth && frameHeight == this->m_uploadedTextureHeight) {
-	glTexSubImage2D (
-	    GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei> (frameWidth), static_cast<GLsizei> (frameHeight), GL_BGRA_EXT,
-	    GL_UNSIGNED_BYTE, this->m_shm->frameBuffer (this->m_frontSlot)
-	);
-    } else {
-	glTexImage2D (
-	    GL_TEXTURE_2D, 0, GL_RGBA, static_cast<GLsizei> (frameWidth), static_cast<GLsizei> (frameHeight), 0,
-	    GL_BGRA_EXT, GL_UNSIGNED_BYTE, this->m_shm->frameBuffer (this->m_frontSlot)
-	);
+    // resize the FBO with the frame, the output pass filters by its size; only reallocate on a change
+    if (frameWidth != this->m_uploadedTextureWidth || frameHeight != this->m_uploadedTextureHeight) {
+	this->find ("_rt_FullFrameBuffer")->resize (frameWidth, frameHeight);
 	this->m_uploadedTextureWidth = frameWidth;
 	this->m_uploadedTextureHeight = frameHeight;
     }
 
+    glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture ());
+    glTexSubImage2D (
+	GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei> (frameWidth), static_cast<GLsizei> (frameHeight), GL_BGRA_EXT,
+	GL_UNSIGNED_BYTE, this->m_shm->frameBuffer (this->m_frontSlot)
+    );
     glBindTexture (GL_TEXTURE_2D, 0);
 
+    if (!this->m_pageHasContent
+	&& frameHasContent (this->m_shm->frameBuffer (this->m_frontSlot), frameWidth, frameHeight)) {
+	this->m_pageHasContent = true;
+
+	if (this->m_statsEnabled) {
+	    sLog.out (
+		"CWeb host ", this->m_hostPid, ": first page content after ",
+		std::chrono::duration_cast<std::chrono::milliseconds> (
+		    std::chrono::steady_clock::now () - this->m_created
+		)
+		    .count (),
+		"ms"
+	    );
+	}
+    }
+
     this->m_statsFrames++;
 
     // ask for the next frame only after taking this one, so what gets painted is always what the next render shows
     this->requestPageFrame ();
 }
 
+bool CWeb::hasContent () const {
+    // show flat or blank pages anyway after that
+    constexpr auto patience = std::chrono::seconds (10);
+
+    return this->m_pageHasContent || this->m_shm->helperFailed.load (std::memory_order_relaxed)
+	|| std::chrono::steady_clock::now () - this->m_created > patience;
+}
+
 void CWeb::requestPageFrame () {
     const auto now = std::chrono::steady_clock::now ();
 
@@ -453,3 +523,31 @@ CWeb::~CWeb () {
 
     closeSharedMemory (this->m_shm, this->m_shmName, this->m_shmMaxWidth, this->m_shmMaxHeight, true);
 }
+
+void CWeb::setPropertyOverrides (const std::map<std::string, std::string>& overrides) {
+    if (this->m_shm == nullptr) {
+	return;
+    }
+
+    std::string text;
+
+    for (const auto& [name, value] : overrides) {
+	text += name + "=" + value + "\n";
+    }
+
+    if (text.size () >= WebHostSharedMemory::PROPERTIES_TEXT) {
+	sLog.error (
+	    "Property overrides too long for the web host (", text.size (), " bytes), the page keeps its values"
+	);
+	return;
+    }
+
+    auto& shm = *this->m_shm;
+    const uint32_t seq = shm.propertiesSeq.load (std::memory_order_relaxed);
+
+    shm.propertiesSeq.store (seq + 1, std::memory_order_release);
+    std::atomic_thread_fence (std::memory_order_seq_cst);
+    copyText (shm.propertiesText, WebHostSharedMemory::PROPERTIES_TEXT, text);
+    std::atomic_thread_fence (std::memory_order_seq_cst);
+    shm.propertiesSeq.store (seq + 2, std::memory_order_release);
+}

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

@@ -44,6 +44,11 @@ public:
     /** ambientVolume==0 (or muted) mutes the host's CEF browser; CEF exposes no analog volume control */
     void setAudioPolicy (bool muted, std::optional<int> ambientVolume) override;
 
+    /** The host passes changes to the page's applyUserProperties */
+    void setPropertyOverrides (const std::map<std::string, std::string>& overrides);
+    /** Painted something not flat, the host failed, or it took too long */
+    [[nodiscard]] bool hasContent () const override;
+
 protected:
     void renderFrame (const glm::ivec4& viewport) override;
     void updateMouse (const glm::ivec4& viewport);
@@ -91,6 +96,8 @@ private:
     bool m_mediaPublished = false;
     uint32_t m_coverVersion = 0;
     bool m_helperFailureLogged = false;
+    std::chrono::steady_clock::time_point m_created = std::chrono::steady_clock::now ();
+    bool m_pageHasContent = false;
 
     int m_width = 16;
     int m_height = 17;

+ 509 - 25
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -7,6 +7,7 @@
 #include <array>
 #include <cmath>
 #include <cstdint>
+#include <cstdlib>
 #include <cstring>
 #include <optional>
 #include <ranges>
@@ -36,6 +37,7 @@ using namespace WallpaperEngine::Scripting::Adapters;
 using WallpaperEngine::Render::Objects::CImage;
 using WallpaperEngine::Render::Objects::CMesh;
 using WallpaperEngine::Render::Objects::CParticle;
+using WallpaperEngine::Render::Objects::CText;
 
 namespace {
 ScriptEngine& engineOf (const v8::FunctionCallbackInfo<v8::Value>& info) {
@@ -84,6 +86,25 @@ v8::Local<v8::Object> makeMat4 (const ScriptEngine& engine, const glm::mat4& mat
     return result;
 }
 
+// m[i] is float i of the native 3x3
+v8::Local<v8::Object> makeMat3 (const ScriptEngine& engine, const std::array<float, 9>& matrix) {
+    auto* isolate = engine.getIsolate ();
+    const auto context = engine.getContext ();
+    const v8::Local<v8::Object> result = v8::Object::New (isolate);
+
+    if (const auto prototype = JS::get (context, engine.getGlobalThis (), "_Mat3"); prototype->IsObject ()) {
+	JS::setPrototype (context, result, prototype);
+    }
+
+    const v8::Local<v8::Array> values = v8::Array::New (isolate, 9);
+    for (uint32_t i = 0; i < 9; i++) {
+	values->Set (context, i, v8::Number::New (isolate, matrix[i])).Check ();
+    }
+    JS::set (context, result, "m", values);
+
+    return result;
+}
+
 // elements that aren't numbers keep the identity's value, like sub_1816214A0
 glm::mat4 readMat4 (v8::Local<v8::Context> context, v8::Local<v8::Value> value) {
     glm::mat4 result (1.0f);
@@ -197,11 +218,8 @@ void hierarchy_call (const v8::FunctionCallbackInfo<v8::Value>& info, int childr
     const v8::Local<v8::Array> result = v8::Array::New (info.GetIsolate ());
     uint32_t index = 0;
 
-    for (const auto* candidate : scene.getObjectsByRenderOrder ()) {
-	const auto& candidateParent = candidate->getObject ().parent;
-
-	if (!candidateParent.has_value () || *candidateParent != object->getObject ().id
-	    || !candidate->is<ScriptableObject> ()) {
+    for (const auto* candidate : scene.childrenOf (object->getObject ().id)) {
+	if (!candidate->is<ScriptableObject> ()) {
 	    continue;
 	}
 
@@ -441,23 +459,183 @@ enum EffectCall {
     EffectGetMaterialCount,
     EffectGetAnimation,
     EffectExecuteMaterialFunction,
+    EffectGetMaterial,
+    EffectSetMaterialProperty,
 };
 
-// IEffect methods; getMaterialCount (sub_1401EE1A0) counts the effect's materials, one per pass
+// IEffect (sub_1401EFCA0): one entry per pass. getMaterial takes an index or file name (last match, empty matches all),
+// setMaterialProperty writes every material with that constant
 void effect_method (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
-    const auto* effect = JS::unwrap<ImageEffect> (info.Data ());
+    auto* effect = JS::unwrap<ImageEffect> (info.Data ());
+    auto& engine = engineOf (info);
+    auto* isolate = info.GetIsolate ();
+    const size_t count = effect->effect != nullptr ? effect->effect->passes.size () : 0;
 
     if (call == EffectGetMaterialCount) {
-	info.GetReturnValue ().Set (
-	    effect->effect != nullptr ? static_cast<int32_t> (effect->effect->passes.size ()) : 0
-	);
+	info.GetReturnValue ().Set (static_cast<int32_t> (count));
     } else if (call == EffectExecuteMaterialFunction && effect->effect != nullptr) {
+	const std::string name = info[0]->IsString () ? JS::toString (isolate, info[0]) : std::string ();
+
+	engine.getScene ().executeEffectFunction (*effect, name);
+    } else if (call == EffectGetMaterial) {
+	info.GetReturnValue ().SetNull ();
+
+	// int or name, anything else is an empty name
+	if (info[0]->IsInt32 () && !info[0]->IsString ()) {
+	    const int index = info[0].As<v8::Int32> ()->Value ();
+
+	    if (index >= 0 && static_cast<size_t> (index) < count) {
+		info.GetReturnValue ().Set (engine.getAdapters ().object->material (*effect, index));
+	    }
+	    return;
+	}
+
+	const std::string name = info[0]->IsString () ? JS::toString (isolate, info[0]) : std::string ();
+	std::optional<size_t> found;
+
+	for (size_t index = 0; index < count; index++) {
+	    const auto& material = effect->effect->passes[index]->material;
+
+	    if (material.has_value () && (name.empty () || (*material)->filename == name)
+		&& engine.getScene ().findEffectMaterial (*effect, index) != nullptr) {
+		found = index;
+	    }
+	}
+
+	if (found.has_value ()) {
+	    info.GetReturnValue ().Set (engine.getAdapters ().object->material (*effect, *found));
+	}
+    } else if (call == EffectSetMaterialProperty) {
+	// scenescript's dispatcher (sub_1816214A0): int32 is an int, other numbers floats, objects a vec2 of x/y, so a
+	// Vec3 never changes a vec3 constant (live WE)
+	const std::string name = info[0]->IsString () ? JS::toString (isolate, info[0]) : std::string ();
+	const auto context = engine.getContext ();
+	const v8::Local<v8::Value> value = info[1];
+	std::optional<float> number;
+	std::optional<glm::vec2> vector;
+
+	if (value->IsNumber ()) {
+	    number = value->IsInt32 () ? static_cast<float> (value.As<v8::Int32> ()->Value ())
+				       : static_cast<float> (value.As<v8::Number> ()->Value ());
+	} else if (value->IsObject ()) {
+	    glm::vec2 read (0.0f);
+	    const auto object = value.As<v8::Object> ();
+
+	    for (int axis = 0; axis < 2; axis++) {
+		const auto component = JS::get (context, object, axis == 0 ? "x" : "y");
+
+		if (component->IsNumber ()) {
+		    read[axis] = static_cast<float> (component.As<v8::Number> ()->Value ());
+		}
+	    }
+
+	    vector = read;
+	}
+
+	for (size_t index = 0; index < count && (number.has_value () || vector.has_value ()); index++) {
+	    auto* pass = engine.getScene ().findEffectMaterial (*effect, index);
+	    const int size = pass != nullptr ? pass->getMaterialConstantSize (name) : 0;
+
+	    auto* target = size == 1 || size == 2 ? pass->getScriptConstant (name) : nullptr;
+
+	    // rad2deg constants take degrees
+	    if (target != nullptr && size == 1 && number.has_value ()) {
+		const float factor = pass->isMaterialConstantInDegrees (name) ? 0.017453292f : 1.0f;
+		target->update (*number * factor, DynamicValue::UpdateSource::Script);
+	    } else if (target != nullptr && size == 2 && vector.has_value ()) {
+		target->update (*vector, DynamicValue::UpdateSource::Script);
+	    }
+	}
+    }
+}
+
+enum BlendShapeCall { GetBlendShapeIndex, GetBlendShapeWeight, SetBlendShapeWeight };
+
+// sub_140210400 / sub_1402104B0 / sub_1402105C0, non-puppets read -1 / 0 and ignore writes
+void blend_shape_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
+    auto* object = layerObject (info.Data ());
+    auto* image = object != nullptr && object->is<CImage> () ? object->as<CImage> () : nullptr;
+
+    if (call == GetBlendShapeIndex) {
 	const std::string name = info[0]->IsString () ? JS::toString (info.GetIsolate (), info[0]) : std::string ();
+	info.GetReturnValue ().Set (image != nullptr ? image->getBlendShapeIndex (name) : -1);
+	return;
+    }
 
-	engineOf (info).getScene ().executeEffectFunction (*effect, name);
+    const auto [index, name] = indexOrNameArgument (info.GetIsolate (), info[0]);
+    const int target = image == nullptr ? -1 : index.has_value () ? *index : image->getBlendShapeIndex (name);
+
+    if (call == GetBlendShapeWeight) {
+	info.GetReturnValue ().Set (
+	    static_cast<double> (image != nullptr ? image->getBlendShapeWeight (target) : 0.0f)
+	);
+    } else if (image != nullptr) {
+	const float weight = info[1]->IsNumber () ? static_cast<float> (info[1].As<v8::Number> ()->Value ()) : 0.0f;
+	image->setBlendShapeWeight (target, weight);
+    }
+}
+
+// data is the constants' group (registerEffectConstants)
+void material_get_animation (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    auto& engine = engineOf (info);
+    const std::string group = JS::toString (info.GetIsolate (), info.Data ());
+    std::string name = info[0]->IsString () ? JS::toString (info.GetIsolate (), info[0]) : std::string ();
+
+    if (name.empty () && engine.getRunningModule () != nullptr) {
+	name = engine.getRunningModule ()->propertyName;
+    }
+
+    v8::Local<v8::Value> animation;
+
+    if (engine.findAnimation (name, group).ToLocal (&animation)) {
+	info.GetReturnValue ().Set (animation);
     }
 }
 
+// sub_1401577E0, each a byte with its own name table
+struct MaterialEnum {
+    const char* name;
+    size_t byte;
+    std::vector<std::pair<const char*, uint8_t>> values;
+};
+
+const std::array<MaterialEnum, 5> MaterialEnums = { {
+    { "depthwrite", 3, { { "disabled", 1 }, { "enabled", 0 } } },
+    { "depthtest", 2, { { "disabled", 1 }, { "enabled", 0 } } },
+    { "cullmode", 4, { { "normal", 0 }, { "nocull", 1 } } },
+    { "alphawriting", 1, { { "default", 0 }, { "disabled", 2 }, { "enabled", 1 } } },
+    { "blending", 0, { { "normal", 0 }, { "translucent", 1 }, { "additive", 2 }, { "alphatocoverage", 3 } } },
+} };
+
+// what the first pass sets on load (sub_140154480), missing keys stay 0
+std::array<uint8_t, 5> materialState (const WallpaperEngine::Data::Model::MaterialPass& pass) {
+    std::array<uint8_t, 5> state {};
+
+    state[0] = pass.blending == BlendingMode_Translucent ? 1
+	: pass.blending == BlendingMode_Additive         ? 2
+	: pass.blending == BlendingMode_AlphaToCoverage  ? 3
+							 : 0;
+    state[1] = pass.alphawriting == "enabled" ? 1 : pass.alphawriting == "disabled" ? 2 : 0;
+    state[2] = pass.depthtest == DepthtestMode_Disabled ? 1 : 0;
+    state[3] = pass.depthwrite == DepthwriteMode_Disabled ? 1 : 0;
+    state[4] = pass.cullmode == CullingMode_Disable ? 1 : 0;
+    return state;
+}
+
+void applyMaterialState (WallpaperEngine::Render::Objects::Effects::CPass& pass, const std::array<uint8_t, 5>& state) {
+    static constexpr BlendingMode blending[]
+	= { BlendingMode_Normal, BlendingMode_Translucent, BlendingMode_Additive, BlendingMode_AlphaToCoverage };
+
+    pass.setScriptMaterialState (
+	blending[std::min<uint8_t> (state[0], 3)],
+	std::make_pair (
+	    state[2] == 1 ? DepthtestMode_Disabled : DepthtestMode_Enabled,
+	    state[3] == 1 ? DepthwriteMode_Disabled : DepthwriteMode_Enabled
+	),
+	state[4] == 1 ? CullingMode_Disable : CullingMode_Normal
+    );
+}
+
 // emitParticles (an int argument, flag 8, the dispatcher's 0 otherwise) and getAnimation on IParticleSystemInstance
 void particle_call (const v8::FunctionCallbackInfo<v8::Value>& info, int emit) {
     auto* object = layerObject (info.Data ());
@@ -814,9 +992,16 @@ void layer_animation_layer_call (const v8::FunctionCallbackInfo<v8::Value>& info
 		const auto config = info.Length () > 1 ? animationLayerArgument (isolate, info[1], true)
 						       : WallpaperEngine::Data::JSON::JSON ();
 
-		info.GetReturnValue ().Set (handleFor (rig->createLayer (
+		const auto serial = rig->createLayer (
 		    animation, config, call == PlaySingleAnimation, object->getScene ().getScene ().project
-		)));
+		);
+
+		// through the scene loader's property handler (sub_1401730D0), scripts included
+		if (const auto* layer = serial.has_value () ? rig->findLayer (*serial) : nullptr; layer != nullptr) {
+		    object->registerAnimationLayerProperties (*serial, *layer->layer);
+		}
+
+		info.GetReturnValue ().Set (handleFor (serial));
 		return;
 	    }
 	case DestroyAnimationLayer:
@@ -1121,6 +1306,25 @@ glm::mat4 layerWorld (const ScriptableObject& object) {
     return object.getScene ().objectWorldMatrix (object.getObject ());
 }
 
+// renderable +752. Uses the data model since scripted properties can update from the ScriptableObject constructor
+std::optional<glm::vec2> renderableSize (const ScriptableObject& object) {
+    const auto& model = object.getObject ();
+
+    if (model.is<Image> ()) {
+	return model.as<Image> ()->size;
+    }
+
+    if (const auto* text = dynamic_cast<const CText*> (&object); text != nullptr) {
+	return text->measuredSize ();
+    }
+
+    if (model.is<Text> ()) {
+	return glm::vec2 (2.0f);
+    }
+
+    return std::nullopt;
+}
+
 // puppet images and models have attachment points (slots 14/15), every other object has none
 const WallpaperEngine::Render::Objects::PuppetRig* layerRig (const ScriptableObject& object) {
     if (object.is<CImage> ()) {
@@ -1172,6 +1376,67 @@ std::optional<glm::vec3> lookAtAngles (
     return localBoneAngles (glm::transpose (glm::lookAtRH (origin, target, up)));
 }
 
+// sub_140196AC0: a layer object, list index or name; an unknown name is read as an id
+const CObject* layerArgument (ScriptEngine& engine, v8::Local<v8::Value> value) {
+    auto& scene = engine.getScene ();
+    const CObject* layer = engine.getAdapters ().object->getObject (value);
+
+    if (value->IsInt32 ()) {
+	const auto layers = scene.getLayers ();
+	const int index = value.As<v8::Int32> ()->Value ();
+
+	if (index >= 0 && index < static_cast<int> (layers.size ())) {
+	    layer = layers[index];
+	}
+    } else if (value->IsString ()) {
+	const std::string name = JS::toString (engine.getIsolate (), value);
+
+	for (const auto* candidate : scene.getObjectsByRenderOrder ()) {
+	    if (candidate->getObject ().name == name && candidate->is<ScriptableObject> ()) {
+		layer = candidate;
+		break;
+	    }
+	}
+
+	if (layer == nullptr) {
+	    const auto* byId = scene.getObject (static_cast<int> (std::strtol (name.c_str (), nullptr, 10)));
+	    layer = byId != nullptr && byId->is<ScriptableObject> () ? byId : nullptr;
+	}
+    }
+
+    return layer;
+}
+
+void set_parent_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    auto& engine = engineOf (info);
+    auto* object = layerObject (info.Data ());
+
+    if (object == nullptr) {
+	return;
+    }
+
+    auto* isolate = info.GetIsolate ();
+    auto& scene = engine.getScene ();
+    const CObject* parent = layerArgument (engine, info[0]);
+
+    const bool adjust = (info[1]->IsBoolean () && info[1]->IsTrue ()) || (info[2]->IsBoolean () && info[2]->IsTrue ());
+    int attachment = -1;
+
+    if (parent != nullptr && info[1]->IsInt32 ()) {
+	attachment = info[1].As<v8::Int32> ()->Value ();
+    } else if (parent != nullptr && info[1]->IsString ()) {
+	const auto* scriptable = dynamic_cast<const ScriptableObject*> (parent);
+	const auto* rig = scriptable != nullptr ? layerRig (*scriptable) : nullptr;
+
+	attachment = rig != nullptr ? rig->findAttachment (JS::toString (isolate, info[1])) : -1;
+    }
+
+    // WE throws a plain Error
+    if (!scene.setObjectParent (*object, parent, attachment, adjust)) {
+	isolate->ThrowException (v8::Exception::Error (JS::string (isolate, "Invalid parent configuration.")));
+    }
+}
+
 // thisLayer transform and attachment calls (wallpaper64 2.8.42 object methods, sub_1401E0530). Matrices follow
 // the bone calls: glm column-vector, the same 16 floats as WE's row-vector ones
 void transform_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
@@ -1286,6 +1551,75 @@ void transform_call (const v8::FunctionCallbackInfo<v8::Value>& info, int call)
     }
 }
 
+// in WE's y up world, with the perspective layer camera or camera parallax (sub_14018AAC0)
+glm::mat4 layerViewProjection (const ScriptableObject& object) {
+    const auto& scene = object.getScene ();
+    const auto& perspective = object.getObject ().perspective;
+    glm::mat4 viewProjection = scene.getWorldViewProjection (perspective != nullptr && perspective->value->getBool ());
+
+    if (!scene.getCamera ().isPerspective () && scene.getScene ().camera.parallax.enabled->value->getBool ()) {
+	const glm::vec2 offset = scene.getParallaxOffset (object.getObject ());
+	viewProjection = glm::translate (viewProjection, glm::vec3 (offset.x, -offset.y, 0.0f));
+    }
+
+    return viewProjection;
+}
+
+// sub_1401ED0D0: the other layer's attachment point and a point 100 units along its x go to the screen and back onto
+// this layer's plane. Returns a Mat3 of texture direction and position
+void transform_attachment_to_texture_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    auto& engine = engineOf (info);
+    auto* object = layerObject (info.Data ());
+    const auto* other = dynamic_cast<const ScriptableObject*> (layerArgument (engine, info[0]));
+    std::array<float, 9> result = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f };
+
+    // WE crashes on a missing layer, return the identity
+    if (object == nullptr || other == nullptr) {
+	info.GetReturnValue ().Set (makeMat3 (engine, result));
+	return;
+    }
+
+    const auto [index, name] = indexOrNameArgument (info.GetIsolate (), info[1]);
+    glm::mat4 attachment (1.0f);
+
+    if (const auto* rig = layerRig (*other)) {
+	if (const auto point = rig->attachmentMatrix (index.has_value () ? *index : rig->findAttachment (name))) {
+	    attachment = *point;
+	}
+    }
+
+    const glm::mat4 toScreen = layerViewProjection (*other) * layerWorld (*other) * attachment;
+    const glm::mat4 fromScreen = glm::inverse (layerViewProjection (*object));
+    const glm::mat4 toLocal = glm::inverse (layerWorld (*object));
+    const glm::vec2 size = renderableSize (*object).value_or (glm::vec2 (0.0f));
+
+    // sub_1401E5DD0: barycentrics of the line against (0,0,0) (1,0,0) (0,1,0) are local x/y, then into texture space
+    const auto texturePoint = [&] (const glm::vec4& local) {
+	const glm::vec4 clip = toScreen * local;
+	const glm::vec2 ndc = glm::vec2 (clip) / clip.w;
+	const glm::vec4 nearPoint = fromScreen * glm::vec4 (ndc, -1.0f, 1.0f);
+	const glm::vec4 farPoint = fromScreen * glm::vec4 (ndc, 1.0f, 1.0f);
+	const glm::vec3 origin = toLocal * (nearPoint / nearPoint.w);
+	const glm::vec3 direction = glm::vec3 (toLocal * (farPoint / farPoint.w)) - origin;
+	glm::vec2 uv (0.0f);
+
+	if (std::abs (direction.z) > 1.1920929e-7f) {
+	    const float t = -origin.z / direction.z;
+	    uv = glm::vec2 (origin) + glm::vec2 (direction) * t;
+	}
+
+	return glm::vec2 ((uv.x - 0.5f) / size.x + 0.5f, 0.5f - (uv.y - 0.5f) / size.y);
+    };
+
+    const glm::vec2 position = texturePoint (glm::vec4 (0.0f, 0.0f, 0.0f, 1.0f));
+    const glm::vec2 along = texturePoint (glm::vec4 (100.0f, 0.0f, 0.0f, 1.0f));
+    const float length = glm::length (along - position);
+    const glm::vec2 direction = length <= 1.1920929e-7f ? glm::vec2 (0.0f) : (along - position) / length;
+
+    result = { direction.x, direction.y, 0.0f, direction.y, -direction.x, 0.0f, position.x, position.y, 1.0f };
+    info.GetReturnValue ().Set (makeMat3 (engine, result));
+}
+
 // The members WE's layer objects have: scenescript64 builds each layer object from the object's property and method
 // lists, parents included, plus getAnimation (sub_181652380). The lists are wallpaper64 2.8.42's static tables,
 // object (sub_1401E0530) under renderable (sub_1401EE520) under image (sub_140211070) and text (sub_140258CA0);
@@ -1428,8 +1762,7 @@ std::vector<LayerMember> layerMembers (const ScriptableObject& object) {
     return members;
 }
 
-// the natives behind the methods; a member without one (setParent, transformAttachmentToTexture, the blend shape
-// calls) is there but undefined
+// a member without a native is there but undefined
 struct LayerMethod {
     std::string_view name;
     v8::FunctionCallback callback;
@@ -1441,9 +1774,14 @@ constexpr LayerMethod LayerMethods[] = {
     { "stop", JS::bind<playback_call, 3> },
     { "isPlaying", JS::bind<playback_call, 2> },
     { "getParent", JS::bind<hierarchy_call, 0> },
+    { "setParent", set_parent_call },
+    { "getBlendShapeIndex", JS::bind<blend_shape_call, GetBlendShapeIndex> },
+    { "getBlendShapeWeight", JS::bind<blend_shape_call, GetBlendShapeWeight> },
+    { "setBlendShapeWeight", JS::bind<blend_shape_call, SetBlendShapeWeight> },
     { "getChildren", JS::bind<hierarchy_call, 1> },
     { "getEffectCount", JS::bind<effect_call, 0> },
     { "getEffect", JS::bind<effect_call, 1> },
+    { "transformAttachmentToTexture", transform_attachment_to_texture_call },
     { "getAnimationLayerCount", JS::bind<layer_animation_layer_call, GetAnimationLayerCount> },
     { "getAnimationLayer", JS::bind<layer_animation_layer_call, GetAnimationLayer> },
     { "createAnimationLayer", JS::bind<layer_animation_layer_call, CreateAnimationLayer> },
@@ -1490,6 +1828,15 @@ void layer_get (v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8:
     const std::string name = JS::toString (isolate, property);
 
     if (auto* value = object.tryGetProperty (name); value != nullptr) {
+	// vec2 descriptors filled by a JSON number (sub_1401E0530)
+	const bool scalar = value->getType () == DynamicValue::Float || value->getType () == DynamicValue::Int;
+
+	if (scalar
+	    && (name == "padding" || name == "spacing" || name == "dropshadowoffset" || name == "parallaxDepth")) {
+	    info.GetReturnValue ().Set (engine.getAdapters ().vec2->create (glm::vec2 (value->getFloat ())));
+	    return;
+	}
+
 	info.GetReturnValue ().Set (engine.propertyToJs (*value, name));
 	return;
     }
@@ -1501,14 +1848,8 @@ void layer_get (v8::Local<v8::Name> property, const v8::PropertyCallbackInfo<v8:
     } else if (name == "instance" && object.is<CParticle> ()) {
 	info.GetReturnValue ().Set (engine.getAdapters ().object->particleInstance (*layer));
     } else if (name == "size") {
-	// checked against the data model (Image/Text) rather than the render object (CImage/CText) because scripted
-	// properties can run their first update() from inside the base ScriptableObject constructor
-	const auto& model = object.getObject ();
-
-	if (model.is<Image> ()) {
-	    info.GetReturnValue ().Set (engine.getAdapters ().vec2->create (model.as<Image> ()->size));
-	} else if (model.is<Text> ()) {
-	    info.GetReturnValue ().Set (engine.getAdapters ().vec2->create (model.as<Text> ()->size));
+	if (const auto size = renderableSize (object)) {
+	    info.GetReturnValue ().Set (engine.getAdapters ().vec2->create (*size));
 	}
     }
 }
@@ -1846,8 +2187,7 @@ v8::Local<v8::Value> ScriptableObjectAdapter::effect (ImageEffect& effect) {
 	return it->second.Get (isolate);
     }
 
-    // IEffect (wallpaper64 2.8.42 sub_1401EFCA0) in the order live WE lists it. getMaterial and setMaterialProperty
-    // aren't there yet
+    // IEffect (sub_1401EFCA0) in live WE's order
     auto& engine = this->m_engine;
     std::vector<NativeProperty> properties = {
 	{ .name = "name",
@@ -1871,9 +2211,11 @@ v8::Local<v8::Value> ScriptableObjectAdapter::effect (ImageEffect& effect) {
 
     const auto data = JS::external (isolate, &effect);
     const std::vector<std::pair<std::string, v8::Local<v8::Function>>> methods = {
+	{ "getMaterial", JS::function (context, JS::bind<effect_method, EffectGetMaterial>, data) },
 	{ "executeMaterialFunction",
 	  JS::function (context, JS::bind<effect_method, EffectExecuteMaterialFunction>, data) },
 	{ "getMaterialCount", JS::function (context, JS::bind<effect_method, EffectGetMaterialCount>, data) },
+	{ "setMaterialProperty", JS::function (context, JS::bind<effect_method, EffectSetMaterialProperty>, data) },
 	{ "getAnimation", JS::function (context, JS::bind<effect_method, EffectGetAnimation>, data) },
     };
 
@@ -1882,6 +2224,148 @@ v8::Local<v8::Value> ScriptableObjectAdapter::effect (ImageEffect& effect) {
     return result;
 }
 
+v8::Local<v8::Value> ScriptableObjectAdapter::material (ImageEffect& effect, size_t passIndex) {
+    auto* isolate = this->m_engine.getIsolate ();
+    const auto context = this->m_engine.getContext ();
+    const auto key = std::make_pair (static_cast<const ImageEffect*> (&effect), passIndex);
+    auto& engine = this->m_engine;
+    const auto passOf
+	= [&engine, &effect, passIndex] { return engine.getScene ().findEffectMaterial (effect, passIndex); };
+    auto* pass = passOf ();
+
+    if (pass == nullptr) {
+	return v8::Null (isolate);
+    }
+
+    if (const auto it = this->m_materials.find (key); it != this->m_materials.end ()) {
+	return it->second.Get (isolate);
+    }
+
+    auto& state = this->m_materialStates.try_emplace (key, materialState (pass->getPass ())).first->second;
+    std::vector<NativeProperty> properties;
+
+    // own constants first, then the static IMaterial members
+    for (const auto& name : pass->getMaterialConstantNames ()) {
+	properties.push_back (
+	    { .name = name,
+	      .get = [isolate, &engine, passOf, name] () -> v8::Local<v8::Value> {
+		  auto* current = passOf ();
+		  const auto* value = current != nullptr ? current->getMaterialConstant (name) : nullptr;
+		  const int size = current != nullptr ? current->getMaterialConstantSize (name) : 0;
+
+		  if (value == nullptr || size == 0) {
+		      return v8::Undefined (isolate);
+		  }
+
+		  const bool scalar
+		      = value->getType () == DynamicValue::Float || value->getType () == DynamicValue::Int;
+		  const glm::vec4 vector
+		      = scalar ? glm::vec4 (value->getFloat (), 0.0f, 0.0f, 0.0f) : value->getVec4 ();
+		  // flag 4 floats and vec3s in degrees (sub_1816208E0)
+		  const float factor = current->isMaterialConstantInDegrees (name) ? 57.29578f : 1.0f;
+
+		  switch (size) {
+		      case 2:
+			  return engine.getAdapters ().vec2->create (glm::vec2 (vector));
+		      case 3:
+			  return engine.getAdapters ().vec3->create (glm::vec3 (vector) * factor);
+		      case 4:
+			  return engine.getAdapters ().vec4->create (vector);
+		      default:
+			  return v8::Number::New (isolate, value->getFloat () * factor);
+		  }
+	      },
+	      .set =
+		  [&engine, passOf, name] (v8::Local<v8::Value> value) {
+		      auto* current = passOf ();
+
+		      auto* target = current != nullptr ? current->getScriptConstant (name) : nullptr;
+
+		      if (target == nullptr) {
+			  return;
+		      }
+
+		      engine.assignPropertyJsValue (value, *target, "");
+
+		      // sub_181620E10
+		      if (current->isMaterialConstantInDegrees (name)) {
+			  if (target->getType () == DynamicValue::Float) {
+			      target->update (target->getFloat () * 0.017453292f, DynamicValue::UpdateSource::Script);
+			  } else if (target->getType () == DynamicValue::Vec3) {
+			      target->update (target->getVec3 () * 0.017453292f, DynamicValue::UpdateSource::Script);
+			  }
+		      }
+		  } }
+	);
+    }
+
+    for (const auto& member : MaterialEnums) {
+	properties.push_back (
+	    { .name = member.name,
+	      // sub_140158490
+	      .get = [isolate, &state, &member] () -> v8::Local<v8::Value> {
+		  v8::Local<v8::Value> result = v8::Undefined (isolate);
+
+		  for (const auto& [text, value] : member.values) {
+		      if (value == state[member.byte]) {
+			  result = JS::string (isolate, text);
+		      }
+		  }
+
+		  return result;
+	      },
+	      // sub_1401583B0: unknown names are the first entry
+	      .set =
+		  [isolate, &state, &member, passOf] (v8::Local<v8::Value> value) {
+		      const std::string text = JS::toString (isolate, value);
+		      const auto entry = std::ranges::find_if (member.values, [&text] (const auto& cur) {
+			  return text == cur.first;
+		      });
+
+		      state[member.byte]
+			  = entry != member.values.end () ? entry->second : member.values.front ().second;
+
+		      if (auto* current = passOf ()) {
+			  applyMaterialState (*current, state);
+		      }
+		  } }
+	);
+    }
+
+    // the group registerEffectConstants used
+    std::string group;
+
+    for (const auto* object : engine.getScene ().getObjectsByRenderOrder ()) {
+	const auto* effects = effectsOf (object->getObject ());
+
+	if (effects == nullptr) {
+	    continue;
+	}
+
+	for (size_t index = 0; index < effects->size (); index++) {
+	    if ((*effects)[index].get () != &effect) {
+		continue;
+	    }
+
+	    const auto& passes = effect.effect->passes;
+	    const auto materialIndex
+		= std::count_if (passes.begin (), passes.begin () + passIndex, [] (const auto& cur) {
+		      return cur->material.has_value ();
+		  });
+	    group = "obj" + std::to_string (object->getId ()) + "/fx" + std::to_string (index) + ".p"
+		+ std::to_string (materialIndex) + ".";
+	}
+    }
+
+    const std::vector<std::pair<std::string, v8::Local<v8::Function>>> methods = {
+	{ "getAnimation", JS::function (context, material_get_animation, JS::string (isolate, group)) },
+    };
+
+    const auto result = this->makeNativeObject (std::move (properties), methods);
+    this->m_materials[key].Reset (isolate, result);
+    return result;
+}
+
 v8::Local<v8::Value> ScriptableObjectAdapter::particleInstance (Layer& layer) {
     auto* isolate = this->m_engine.getIsolate ();
     const auto context = this->m_engine.getContext ();

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

@@ -3,7 +3,9 @@
 #include <v8-local-handle.h>
 #include <v8-persistent-handle.h>
 
+#include <array>
 #include <functional>
+#include <map>
 #include <memory>
 #include <string>
 #include <unordered_map>
@@ -73,6 +75,8 @@ public:
     v8::Local<v8::Value> particleInstance (Layer& layer);
     /** IEffect of one of an image's effects, one JS object per effect */
     v8::Local<v8::Value> effect (Data::Model::ImageEffect& effect);
+    /** one JS object per material, null without one */
+    v8::Local<v8::Value> material (Data::Model::ImageEffect& effect, size_t passIndex);
     /** IAnimation of an animated property's timeline, one JS object per timeline (sub_14018DB00 keeps it at +248) */
     v8::Local<v8::Value> animation (int systemId, int clockId);
     /**
@@ -94,6 +98,9 @@ private:
     std::vector<std::unique_ptr<Layer>> m_forgotten;
     std::unordered_map<int, v8::Global<v8::Object>> m_animations;
     std::unordered_map<const Data::Model::ImageEffect*, v8::Global<v8::Object>> m_effects;
+    std::map<std::pair<const Data::Model::ImageEffect*, size_t>, v8::Global<v8::Object>> m_materials;
+    // blending, alphawriting, depthtest, depthwrite, cullmode (material +496..+500)
+    std::map<std::pair<const Data::Model::ImageEffect*, size_t>, std::array<uint8_t, 5>> m_materialStates;
     // the native objects' members, their accessors point into these
     std::vector<std::unique_ptr<std::vector<NativeProperty>>> m_nativeMembers;
     v8::Global<v8::Private> m_layerKey;

+ 34 - 5
src/WallpaperEngine/Scripting/SceneObject.cpp

@@ -167,7 +167,7 @@ v8::Local<v8::Value> instantiate_sound_layer (ScriptEngine& engine, const Sound&
     const v8::Local<v8::Object> handle = v8::Object::New (isolate);
     const auto data = JS::data (
 	isolate,
-	{ v8::Integer::New (isolate, sound.id), v8::Boolean::New (isolate, sound.startsilent.value_or (false)) }
+	{ v8::Integer::New (isolate, sound.id), v8::Boolean::New (isolate, sound.startsilent->value->getBool ()) }
     );
 
     JS::set (context, handle, "play", JS::function (context, JS::bind<sound_layer_call, 0>, data));
@@ -193,6 +193,8 @@ v8::Local<v8::Value> get_layer_by_id (SceneObject& container, int id) {
 // real WE: a number is a render-order index, a string is a name and falls back to an id,
 // a layer is handed back as is, anything else is undefined
 void get_layer (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    info.GetReturnValue ().SetNull ();
+
     if (info.Length () < 1) {
 	return;
     }
@@ -205,7 +207,8 @@ void get_layer (const v8::FunctionCallbackInfo<v8::Value>& info) {
 	const int index = layer->Int32Value (engine.getContext ()).FromMaybe (0);
 	const auto layers = container.getScene ().getLayers ();
 
-	if (index < 0 || index >= static_cast<int> (layers.size ())) {
+	if (index < 0 || index >= static_cast<int> (layers.size ())
+	    || container.getScene ().isPendingDestroy (*layers[index])) {
 	    return;
 	}
 
@@ -224,7 +227,8 @@ void get_layer (const v8::FunctionCallbackInfo<v8::Value>& info) {
 	}
 
 	for (auto* object : container.getScene ().getObjectsByRenderOrder ()) {
-	    if (object->getObject ().name == name && object->is<ScriptableObject> ()) {
+	    if (object->getObject ().name == name && object->is<ScriptableObject> ()
+		&& !container.getScene ().isPendingDestroy (*object)) {
 		info.GetReturnValue ().Set (instantiate_layer (engine, object));
 		return;
 	    }
@@ -260,7 +264,9 @@ void get_layer_by_id_call (const v8::FunctionCallbackInfo<v8::Value>& info) {
 }
 
 void get_layer_count (const v8::FunctionCallbackInfo<v8::Value>& info) {
-    info.GetReturnValue ().Set (static_cast<int32_t> (sceneOf (info).getScene ().getLayers ().size ()));
+    // pending ones are already off the count (sub_14018B730)
+    const auto& scene = sceneOf (info).getScene ();
+    info.GetReturnValue ().Set (static_cast<int32_t> (scene.getLayers ().size () - scene.getPendingDestroyCount ()));
 }
 
 void enumerate_layers (const v8::FunctionCallbackInfo<v8::Value>& info) {
@@ -493,7 +499,7 @@ namespace ModelDataScript {
 
 // scenescript64 sub_1816372D0: a string is a name (the first layer with it), falling back to strtol as an id, a
 // number is an index, a layer object is itself
-WallpaperEngine::Render::CObject* resolve_layer_object (SceneObject& container, v8::Local<v8::Value> value) {
+WallpaperEngine::Render::CObject* resolve_layer_object_any (SceneObject& container, v8::Local<v8::Value> value) {
     auto* isolate = container.getEngine ().getIsolate ();
     const auto layers = container.getScene ().getLayers ();
 
@@ -526,6 +532,28 @@ WallpaperEngine::Render::CObject* resolve_layer_object (SceneObject& container,
     return container.getEngine ().getAdapters ().object->getObject (value);
 }
 
+// skips layers destroyed this frame (sub_1401966D0)
+WallpaperEngine::Render::CObject* resolve_layer_object (SceneObject& container, v8::Local<v8::Value> value) {
+    auto* object = resolve_layer_object_any (container, value);
+
+    return object != nullptr && container.getScene ().isPendingDestroy (*object) ? nullptr : object;
+}
+
+// sub_181632FC0: removed after this frame's scripts, not from a module's top level
+void destroy_layer (const v8::FunctionCallbackInfo<v8::Value>& info) {
+    auto* isolate = info.GetIsolate ();
+    auto& container = sceneOf (info);
+
+    if (container.getEngine ().isEvaluatingModuleBody ()) {
+	JS::throwSyntaxError (isolate, "destroyLayer cannot be called from global scope.");
+	return;
+    }
+
+    auto* object = info.Length () < 1 ? nullptr : resolve_layer_object (container, info[0]);
+
+    info.GetReturnValue ().Set (object != nullptr && container.getScene ().queueDestroyLayer (*object));
+}
+
 // sub_181634980: the object's creation JSON without its id, parsed again. The global scope message really names
 // destroyLayer in WE
 void get_initial_layer_config (const v8::FunctionCallbackInfo<v8::Value>& info) {
@@ -763,6 +791,7 @@ SceneObject::SceneObject (ScriptEngine& engine, Render::Wallpapers::CScene& scen
     method ("createLayer", create_layer, 1);
     method ("sortLayer", sort_layer, 2);
     method ("getInitialLayerConfig", get_initial_layer_config, 1);
+    method ("destroyLayer", destroy_layer, 1);
     method ("getCameraTransforms", get_camera_transforms, 0);
     method ("setCameraTransforms", set_camera_transforms, 1);
     method ("getAnimation", get_animation, 0);

+ 127 - 11
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -788,6 +788,26 @@ ScriptEngine::call (const LoadedModule& module, const char* name, int argc, v8::
 
 void ScriptEngine::retireScript (const std::string& key) { this->m_retiredScriptKeys.push_back (key); }
 
+void ScriptEngine::destroyObjectScripts (const ScriptableObject& object) {
+    {
+	const Scope scope (*this);
+
+	for (auto& module : this->m_scriptModules | std::views::values) {
+	    if (module.object != &object || !module.initialized || module.dropped) {
+		continue;
+	    }
+
+	    const v8::TryCatch tryCatch (this->m_isolate);
+
+	    if (this->callEvent (module, "destroy", 0, nullptr).IsEmpty ()) {
+		logJSException (this->m_isolate, tryCatch, "destroy", module.value.getScriptSource ());
+	    }
+	}
+    }
+
+    this->dropObjectScripts (object);
+}
+
 void ScriptEngine::dropObjectScripts (const ScriptableObject& object) {
     const Scope scope (*this);
     const auto context = this->getContext ();
@@ -1134,9 +1154,7 @@ void ScriptEngine::initializeModule (const std::string& key, LoadedModule& modul
 	}
     }
 
-    if (this->m_mediaSource.getMediaInfo ().available) {
-	this->notifyMediaUpdate (this->m_mediaSource.getMediaInfo (), &module);
-    }
+    this->notifyMediaUpdate (this->m_mediaSource.getMediaInfo (), &module);
 }
 
 namespace {
@@ -1174,7 +1192,8 @@ bool ScriptEngine::hasCursorHandlers (const ScriptableObject& object) {
 }
 
 void ScriptEngine::dispatchCursorEvent (
-    const char* handler, ScriptableObject& object, const glm::vec2& worldPosition, const glm::vec3& localPosition
+    const char* handler, ScriptableObject& object, const glm::vec2& worldPosition, const glm::vec3& localPosition,
+    const std::optional<std::string>& hitBox
 ) {
     const Scope scope (*this);
     const auto context = this->getContext ();
@@ -1198,9 +1217,14 @@ void ScriptEngine::dispatchCursorEvent (
 	this->bindThisLayer (*module.object, &module);
 
 	const v8::Local<v8::Object> event = v8::Object::New (this->m_isolate);
+	JS::set (context, event, "button", v8::Integer::New (this->m_isolate, 0));
 	JS::set (context, event, "worldPosition", makePosition (glm::vec3 (worldPosition, 0.0f)));
 	JS::set (context, event, "localPosition", makePosition (localPosition));
 
+	if (hitBox.has_value ()) {
+	    JS::set (context, event, "hitBox", JS::string (this->m_isolate, *hitBox));
+	}
+
 	v8::Local<v8::Value> args[] = { event };
 
 	if (this->call (module, handler, 1, args).IsEmpty ()) {
@@ -1542,6 +1566,68 @@ Media::ThumbnailPalette ScriptEngine::thumbnailPaletteFor (const Media::MediaSou
     return this->m_palette;
 }
 
+v8::MaybeLocal<v8::Value>
+ScriptEngine::callEvent (LoadedModule& module, const char* name, int argc, v8::Local<v8::Value> argv[]) {
+    // with its own layer as thisLayer
+    LoadedModule* previous = this->m_runningModule;
+    this->m_runningModule = &module;
+
+    if (module.object != nullptr) {
+	this->bindThisLayer (*module.object, &module);
+    }
+
+    const auto result = this->call (module, name, argc, argv);
+    this->m_runningModule = previous;
+    return result;
+}
+
+void ScriptEngine::notifyResizeScreen (const glm::vec2& size) {
+    const Scope scope (*this);
+    auto* isolate = this->m_isolate;
+
+    for (auto& module : this->m_scriptModules | std::views::values) {
+	if (!module.initialized || module.dropped) {
+	    continue;
+	}
+
+	const v8::TryCatch tryCatch (isolate);
+	v8::Local<v8::Value> args[] = { this->m_adapters.vec2->create (size) };
+
+	if (this->callEvent (module, "resizeScreen", 1, args).IsEmpty ()) {
+	    logJSException (isolate, tryCatch, "resizeScreen", module.value.getScriptSource ());
+	}
+    }
+}
+
+void ScriptEngine::notifyUserPropertiesChanged (const std::vector<std::string>& names) {
+    const Scope scope (*this);
+    this->m_scriptPropertiesObject->userPropertiesChanged (names);
+    const auto context = this->getContext ();
+    auto* isolate = this->m_isolate;
+    const auto& properties = this->m_engineObject->getScene ().getUserProperties ();
+
+    for (auto& module : this->m_scriptModules | std::views::values) {
+	if (!module.initialized || module.dropped) {
+	    continue;
+	}
+
+	const v8::TryCatch tryCatch (isolate);
+	const v8::Local<v8::Object> userProps = v8::Object::New (isolate);
+
+	for (const auto& name : names) {
+	    if (const auto it = properties.find (name); it != properties.end ()) {
+		JS::set (context, userProps, name, this->userPropertyToJs (*it->second));
+	    }
+	}
+
+	v8::Local<v8::Value> args[] = { userProps };
+
+	if (this->callEvent (module, "applyUserProperties", 1, args).IsEmpty ()) {
+	    logJSException (isolate, tryCatch, "applyUserProperties", module.value.getScriptSource ());
+	}
+    }
+}
+
 void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media, LoadedModule* only) {
     const Scope scope (*this);
     const auto context = this->getContext ();
@@ -1554,11 +1640,21 @@ void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media
 	return this->m_adapters.vec3->instantiate (dynamic);
     };
 
+    // sub_18164E4D0 cases 14 to 18
+    const v8::Local<v8::Object> statusEvent = v8::Object::New (isolate);
+
+    JS::set (context, statusEvent, "enabled", v8::Boolean::New (isolate, true));
+
     const v8::Local<v8::Object> propertiesEvent = v8::Object::New (isolate);
 
+    // SMTC subtitle and content type have no MPRIS counterpart
     JS::set (context, propertiesEvent, "title", JS::string (isolate, media.title));
     JS::set (context, propertiesEvent, "artist", JS::string (isolate, media.artist));
+    JS::set (context, propertiesEvent, "albumArtist", JS::string (isolate, media.albumArtist));
     JS::set (context, propertiesEvent, "albumTitle", JS::string (isolate, media.album));
+    JS::set (context, propertiesEvent, "subTitle", JS::string (isolate, ""));
+    JS::set (context, propertiesEvent, "genres", JS::string (isolate, media.genres));
+    JS::set (context, propertiesEvent, "contentType", JS::string (isolate, ""));
 
     const v8::Local<v8::Object> playbackEvent = v8::Object::New (isolate);
 
@@ -1578,12 +1674,32 @@ void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media
     JS::set (context, mediaThumbnailEvent, "textColor", color (palette.text));
     JS::set (context, mediaThumbnailEvent, "highContrastColor", color (palette.highContrast));
 
-    const std::pair<const char*, v8::Local<v8::Value>> events[] = {
-	{ "mediaPropertiesChanged", propertiesEvent },
-	{ "mediaPlaybackChanged", playbackEvent },
-	{ "mediaTimelineChanged", mediaTimelineEvent },
-	{ "mediaThumbnailChanged", mediaThumbnailEvent },
-    };
+    std::vector<std::pair<const char*, v8::Local<v8::Value>>> events;
+
+    if (only != nullptr) {
+	// on load (sub_140172830): status, then playback state, properties, thumbnail and timeline
+	events.emplace_back ("mediaStatusChanged", statusEvent);
+
+	if (media.available && media.playbackState != Media::MediaSource::Stopped) {
+	    events.emplace_back ("mediaPlaybackChanged", playbackEvent);
+	}
+	if (media.available && !media.title.empty ()) {
+	    events.emplace_back ("mediaPropertiesChanged", propertiesEvent);
+	}
+	if (media.available && media.url.has_value ()) {
+	    events.emplace_back ("mediaThumbnailChanged", mediaThumbnailEvent);
+	}
+	if (media.available && media.duration != 0.0) {
+	    events.emplace_back ("mediaTimelineChanged", mediaTimelineEvent);
+	}
+    } else {
+	events = {
+	    { "mediaPropertiesChanged", propertiesEvent },
+	    { "mediaPlaybackChanged", playbackEvent },
+	    { "mediaTimelineChanged", mediaTimelineEvent },
+	    { "mediaThumbnailChanged", mediaThumbnailEvent },
+	};
+    }
 
     for (auto& module : this->m_scriptModules | std::views::values) {
 	// modules that haven't run init() yet get the current media state replayed once they do
@@ -1595,7 +1711,7 @@ void ScriptEngine::notifyMediaUpdate (const Media::MediaSource::MediaInfo& media
 	    const v8::TryCatch tryCatch (isolate);
 	    v8::Local<v8::Value> args[] = { event };
 
-	    if (this->call (module, handler, 1, args).IsEmpty ()) {
+	    if (this->callEvent (module, handler, 1, args).IsEmpty ()) {
 		logJSException (isolate, tryCatch, handler, module.value.getScriptSource ());
 	    }
 	}

+ 12 - 4
src/WallpaperEngine/Scripting/ScriptEngine.h

@@ -150,6 +150,8 @@ public:
     /** Detaches and retires every module attached to object, for an object destroyed while the script context lives on
      * (setup failed after its properties queued their scripts) */
     void dropObjectScripts (const ScriptableObject& object);
+    /** destroy () (export 3) where present, then dropObjectScripts () */
+    void destroyObjectScripts (const ScriptableObject& object);
 
     /** Rebinds an already-running module under key to newValue in place when its script source is identical, so init()
      * does not run twice. Returns false if nothing was rebound */
@@ -213,12 +215,12 @@ public:
     /** Whether any running script on the object exports a cursor handler (cursorEnter, cursorClick, ...) */
     [[nodiscard]] bool hasCursorHandlers (const ScriptableObject& object);
     /**
-     * Calls `handler` (cursorEnter/cursorLeave/cursorMove/cursorDown/cursorUp/cursorClick) on every script running on
-     * the object with an event carrying worldPosition (scene coordinates) and localPosition (where the object was hit,
-     * see CScene::dispatchCursorEvents)
+     * Calls handler (cursorEnter/Leave/Move/Down/Up/Click) on the object's scripts with button (always 0),
+     * worldPosition, localPosition and hitBox (sub_18164E4D0)
      */
     void dispatchCursorEvent (
-	const char* handler, ScriptableObject& object, const glm::vec2& worldPosition, const glm::vec3& localPosition
+	const char* handler, ScriptableObject& object, const glm::vec2& worldPosition, const glm::vec3& localPosition,
+	const std::optional<std::string>& hitBox
     );
 
     /** Calls callback (once per playthrough) when player reaches the end of a non-looping video, for
@@ -241,6 +243,11 @@ public:
     [[nodiscard]] bool hasScript (const DynamicValue& value) const;
     const JSObjectAdapters& getAdapters () const { return m_adapters; }
     const Render::Wallpapers::CScene& getScene () const { return m_scene; }
+    Render::Wallpapers::CScene& getScene () { return m_scene; }
+    /** export 2 with the new render size (sub_14017F1B0) */
+    void notifyResizeScreen (const glm::vec2& size);
+    /** export 4 with the changed properties (sub_1401731D0) */
+    void notifyUserPropertiesChanged (const std::vector<std::string>& names);
     /** Reads a file through the wallpaper's asset locator (project first, then the assets dir), nullopt if it is
      * missing */
     std::optional<std::string> readScriptAsset (const std::string& path) const;
@@ -264,6 +271,7 @@ private:
     void installBuiltins ();
 
     Media::ThumbnailPalette thumbnailPaletteFor (const Media::MediaSource::MediaInfo& media);
+    v8::MaybeLocal<v8::Value> callEvent (LoadedModule& module, const char* name, int argc, v8::Local<v8::Value> argv[]);
     void notifyMediaUpdate (const Media::MediaSource::MediaInfo& media, LoadedModule* only = nullptr);
     void initializeModule (const std::string& key, LoadedModule& module);
     void bindThisLayer (ScriptableObject& object, LoadedModule* module = nullptr);

+ 12 - 0
src/WallpaperEngine/Scripting/ScriptPropertiesObject.cpp

@@ -2,6 +2,7 @@
 
 #include "JS.h"
 #include "ScriptEngine.h"
+#include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 
@@ -126,6 +127,17 @@ void ScriptPropertiesObject::deliverValues (Data::Model::DynamicValue& value) {
     });
 }
 
+void ScriptPropertiesObject::userPropertiesChanged (const std::vector<std::string>& names) {
+    for (const auto& instance : this->m_instances) {
+	for (const auto& [name, setting] : instance->value.getProperties ()) {
+	    if (setting != nullptr && setting->property != nullptr
+		&& std::ranges::find (names, setting->property->name) != names.end ()) {
+		instance->assigned.erase (name);
+	    }
+	}
+    }
+}
+
 ScriptPropertiesObject::ScriptPropertiesObject (ScriptEngine& engine, Render::Wallpapers::CScene& scene) :
     m_scene (scene), m_engine (engine) {
     auto* isolate = engine.getIsolate ();

+ 2 - 0
src/WallpaperEngine/Scripting/ScriptPropertiesObject.h

@@ -47,6 +47,8 @@ public:
      * script its scene values right after evaluating the module, so top-level code still sees the add*() defaults
      */
     void deliverValues (Data::Model::DynamicValue& value);
+    /** sub_1401731D0: bound scriptproperties get the new values, replacing what the script assigned */
+    void userPropertiesChanged (const std::vector<std::string>& names);
 
     v8::Local<v8::Object> newCreator ();
     /** The creator a JS object stands for, nullptr for anything else */

+ 56 - 0
src/WallpaperEngine/Scripting/ScriptableObject.cpp

@@ -4,6 +4,7 @@
 #include "WallpaperEngine/Data/Model/Effect.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Utils/ScopeGuard.h"
+#include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 
 #include <cstdint>
 #include <ranges>
@@ -18,6 +19,22 @@ ScriptableObject::ScriptableObject (Wallpapers::CScene& scene, const Object& obj
     this->registerProperty ("visible", *object.groupVisible->value);
     this->registerProperty ("solid", *object.solid->value);
     this->registerProperty ("disablepropagation", *object.disablePropagation->value);
+    // sub_1401E0530, typed objects register their own parallaxDepth
+    this->registerProperty ("parallaxDepth", *object.groupParallaxDepth->value);
+    this->registerProperty ("sortorder", *object.sortOrderValue->value);
+}
+
+void ScriptableObject::registerRenderableProperties (
+    const RenderableSettings& renderable, const UserSetting& colorBlendMode, const UserSetting& brightness
+) {
+    // sub_1401EE520
+    this->registerProperty ("colorBlendMode", *colorBlendMode.value);
+    this->registerProperty ("brightness", *brightness.value);
+    this->registerProperty ("perspective", *this->getObject ().perspective->value);
+    this->registerProperty ("ledsource", *renderable.ledSource->value);
+    this->registerProperty ("nointerpolation", *renderable.noInterpolation->value);
+    this->registerProperty ("clampuvs", *renderable.clampUVs->value);
+    this->registerProperty ("castshadow", *renderable.castShadow->value);
 }
 
 DynamicValue& ScriptableObject::getProperty (const std::string& name) {
@@ -106,3 +123,42 @@ void ScriptableObject::registerProperty (
 	animationKey.empty () ? name : animationKey, value
     );
 }
+
+namespace {
+std::string animationLayerPrefix (size_t serial) { return "animationlayers[" + std::to_string (serial) + "]."; }
+}
+
+void ScriptableObject::registerAnimationLayerProperties (size_t serial, const ImageAnimationLayer& layer) {
+    const std::string prefix = animationLayerPrefix (serial);
+
+    for (const auto& [name, setting] : { std::pair { "visible", &layer.visible }, std::pair { "rate", &layer.rate },
+					 std::pair { "blend", &layer.blend } }) {
+	if (*setting == nullptr) {
+	    continue;
+	}
+
+	this->registerProperty (
+	    prefix + name, *(*setting)->value, Adapters::animationLayerGroup (this->getId (), serial), name
+	);
+	this->getScene ().getScriptEngine ().setThisObjectFactory (
+	    this->m_properties.at (prefix + name).key,
+	    [this, serial] (ScriptEngine& engine) { return Adapters::makeAnimationLayerHandle (engine, *this, serial); }
+	);
+    }
+}
+
+void ScriptableObject::unregisterAnimationLayerProperties (size_t serial) {
+    const std::string prefix = animationLayerPrefix (serial);
+
+    for (const char* name : { "visible", "rate", "blend" }) {
+	const auto entry = this->m_properties.find (prefix + name);
+
+	if (entry == this->m_properties.end ()) {
+	    continue;
+	}
+
+	this->getScene ().getScriptEngine ().getAnimations ().remove (entry->second.value);
+	this->getScene ().getScriptEngine ().retireScript (entry->second.key);
+	this->m_properties.erase (entry);
+    }
+}

+ 8 - 0
src/WallpaperEngine/Scripting/ScriptableObject.h

@@ -35,11 +35,19 @@ public:
     [[nodiscard]] Playback getPlayback () const { return this->m_playback; }
     [[nodiscard]] virtual bool isPlaying () const { return this->m_playback == Playback::Playing; }
 
+    /** thisObject is the IAnimationLayer (sub_1401730D0, sub_14026C980) */
+    void registerAnimationLayerProperties (size_t serial, const ImageAnimationLayer& layer);
+    /** before its settings go away */
+    void unregisterAnimationLayerProperties (size_t serial);
+
 protected:
     void registerProperty (
 	const std::string& name, DynamicValue& value, const std::string& animationGroup = {},
 	const std::string& animationKey = {}
     );
+    void registerRenderableProperties (
+	const RenderableSettings& renderable, const UserSetting& colorBlendMode, const UserSetting& brightness
+    );
     /** Effect pass constants (Radius, Area, ...) only matter to the script engine when they carry a script or animation
      */
     void registerEffectConstants (const std::vector<ImageEffectUniquePtr>& effects);

+ 4 - 4
src/WallpaperEngine/Testing/Cases/SpectrumListeners.cpp

@@ -14,13 +14,13 @@ public:
 
 TEST_CASE ("Spectrum listeners are pushed every new spectrum until removed") {
     PushingRecorder recorder;
-    float bands[64] = { 0.5f };
+    float bands[128] = { 0.5f };
     int calls = 0;
     float first = 0.0f;
 
-    const int id = recorder.addSpectrumListener ([&] (const float* audio64) {
+    const int id = recorder.addSpectrumListener ([&] (const float* captured) {
 	calls++;
-	first = audio64[0];
+	first = captured[0];
     });
 
     recorder.push (bands);
@@ -38,7 +38,7 @@ TEST_CASE ("Spectrum listeners are pushed every new spectrum until removed") {
 
 TEST_CASE ("Several spectrum listeners each get the spectrum") {
     PushingRecorder recorder;
-    float bands[64] = {};
+    float bands[128] = {};
     int a = 0;
     int b = 0;
 

+ 0 - 95
src/WallpaperEngine/Testing/Cases/SpectrumNormalizer.cpp

@@ -1,95 +0,0 @@
-#include <catch2/catch_approx.hpp>
-#include <catch2/catch_test_macros.hpp>
-
-#include "WallpaperEngine/Audio/SpectrumNormalizer.h"
-
-using Catch::Approx;
-using WallpaperEngine::Audio::SpectrumNormalizer;
-
-namespace {
-// a frame whose loudest fifth of the bands sit at the given level, and the rest well below it
-void settle (SpectrumNormalizer& normalizer, float peak, float seconds) {
-    constexpr float frame = 0.023f;
-    float levels[64] = {};
-
-    for (int i = 0; i < 13; i++) {
-	levels[i] = peak;
-    }
-
-    for (float t = 0.0f; t < seconds; t += frame) {
-	normalizer.update (levels, 64, frame);
-    }
-}
-} // namespace
-
-TEST_CASE ("Silence and capture noise stay flat") {
-    SpectrumNormalizer normalizer;
-
-    settle (normalizer, 0.0f, 2.0f);
-
-    CHECK (normalizer.apply (0.0f) == 0.0f);
-    CHECK (normalizer.apply (0.1f) == 0.0f);
-}
-
-TEST_CASE ("Loud music does not push every band to the top") {
-    SpectrumNormalizer normalizer;
-
-    settle (normalizer, 2.5f, 3.0f);
-
-    CHECK (normalizer.apply (2.5f) == Approx (1.0f).margin (0.02f));
-    // a band a little below the peak is clearly below the top, not locked to it
-    CHECK (normalizer.apply (2.1f) < 0.7f);
-    CHECK (normalizer.apply (2.1f) > 0.2f);
-    CHECK (normalizer.apply (1.0f) == 0.0f);
-}
-
-TEST_CASE ("The same shape looks the same at any volume") {
-    SpectrumNormalizer loud;
-    SpectrumNormalizer louder;
-
-    settle (loud, 2.0f, 3.0f);
-    settle (louder, 3.0f, 3.0f);
-
-    // 0.3 below the peak in both
-    CHECK (loud.apply (1.7f) == Approx (louder.apply (2.7f)).margin (0.02f));
-}
-
-TEST_CASE ("Faint sounds are stretched to fill the range but not below the gate") {
-    SpectrumNormalizer normalizer;
-
-    settle (normalizer, 0.6f, 3.0f);
-
-    CHECK (normalizer.apply (0.6f) == Approx (1.0f).margin (0.02f));
-    CHECK (normalizer.apply (0.15f) == 0.0f);
-}
-
-TEST_CASE ("The reference follows the music back down over a few seconds") {
-    SpectrumNormalizer normalizer;
-
-    settle (normalizer, 3.0f, 2.0f);
-    CHECK (normalizer.getReference () == Approx (3.0f).margin (0.05f));
-
-    settle (normalizer, 1.0f, 0.5f);
-    CHECK (normalizer.getReference () > 2.0f);
-
-    settle (normalizer, 1.0f, 10.0f);
-    CHECK (normalizer.getReference () < 1.2f);
-}
-
-TEST_CASE ("One outlier band does not flatten the rest of the spectrum") {
-    SpectrumNormalizer normalizer;
-    float levels[64];
-
-    for (float& level : levels) {
-	level = 1.5f;
-    }
-
-    levels[10] = 4.0f;
-
-    for (int i = 0; i < 200; i++) {
-	normalizer.update (levels, 64, 0.023f);
-    }
-
-    CHECK (normalizer.getReference () < 2.2f);
-    CHECK (normalizer.apply (1.5f) > 0.5f);
-}

+ 113 - 35
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp

@@ -10,6 +10,7 @@
 #include <utility>
 #include <vector>
 
+using namespace WallpaperEngine::VideoPlayback;
 using namespace WallpaperEngine::VideoPlayback::MPV;
 
 std::unordered_map<std::filesystem::path, GLPlayer*> GLPlayer::s_activePlayers;
@@ -157,58 +158,98 @@ void GLPlayer::setLoop (bool loop) {
     }
 }
 
+// eof-reached uses 0
+static constexpr uint64_t TIME_POS_OBSERVER = 1;
+static constexpr uint64_t FPS_OBSERVER = 2;
+
 // with ab-loop-b unset mpv's own loop restarts the file from 0 instead of going back to A, so an open end is a B
 // past the end of any video
-static std::pair<std::string, std::string>
-abLoopPoints (const std::optional<double>& start, const std::optional<double>& end) {
-    if (!start.has_value () && !end.has_value ()) {
+static std::pair<std::string, std::string> abLoopPoints (const VideoSegments& segments) {
+    if (segments.empty ()) {
 	return { "no", "no" };
     }
 
-    return { std::to_string (start.value_or (0.0)), end.has_value () ? std::to_string (*end) : "1e9" };
+    const auto& end = segments.back ().end;
+
+    return { std::to_string (segments.front ().start), end.has_value () ? std::to_string (*end) : "1e9" };
 }
 
-void GLPlayer::setLoopRange (const std::optional<double> start, const std::optional<double> end) {
-    // a request repeating the range (we_manager saving what it just previewed) must not interrupt playback
-    if (this->m_handle != nullptr && start == this->m_loopStart && end == this->m_loopEnd) {
+void GLPlayer::setSegments (const VideoSegments& segments) {
+    // re-sending the same parts must not interrupt playback
+    if (this->m_handle != nullptr && segments == this->m_segments) {
 	return;
     }
 
-    this->m_loopStart = start;
-    this->m_loopEnd = end;
+    this->m_segments = segments;
 
     if (this->m_handle == nullptr) {
 	return;
     }
 
     if (this->m_fileLoaded) {
-	this->dropLoopRangePastEnd ();
+	this->dropSegmentsPastEnd ();
     }
 
-    const auto [a, b] = abLoopPoints (this->m_loopStart, this->m_loopEnd);
+    const auto [a, b] = abLoopPoints (this->m_segments);
 
     setPropertyAsync (this->m_handle, "ab-loop-a", a.c_str ());
     setPropertyAsync (this->m_handle, "ab-loop-b", b.c_str ());
-    this->seek (this->m_loopStart.value_or (0.0));
+    this->observePosition ();
+    this->seek (this->m_segments.empty () ? 0.0 : this->m_segments.front ().start);
 }
 
-bool GLPlayer::dropLoopRangePastEnd () const {
-    if (!this->m_loopStart.has_value ()) {
+bool GLPlayer::dropSegmentsPastEnd () const {
+    const double duration = this->getDuration ();
+
+    if (duration <= 0.0) {
 	return false;
     }
 
-    const double duration = this->getDuration ();
+    const auto dropped = std::erase_if (this->m_segments, [duration] (const VideoSegment& segment) {
+	if (segment.start < duration) {
+	    return false;
+	}
 
-    if (duration <= 0.0 || *this->m_loopStart < duration) {
-	return false;
+	sLog.error (
+	    "Video part from ", segment.start, "s starts past the end of the video (", duration, "s), skipping it"
+	);
+	return true;
+    });
+
+    if (dropped > 0 && this->m_segments.empty ()) {
+	sLog.error ("No video part left, playing all of it");
     }
 
-    sLog.error (
-	"Video loop start ", *this->m_loopStart, "s is past the end of the video (", duration, "s), playing all of it"
-    );
-    this->m_loopStart.reset ();
-    this->m_loopEnd.reset ();
-    return true;
+    return dropped > 0;
+}
+
+void GLPlayer::observePosition () const {
+    mpv_unobserve_property (this->m_handle, TIME_POS_OBSERVER);
+    mpv_unobserve_property (this->m_handle, FPS_OBSERVER);
+    this->m_skipping = false;
+
+    if (this->m_segments.size () > 1) {
+	mpv_observe_property (this->m_handle, TIME_POS_OBSERVER, "time-pos", MPV_FORMAT_DOUBLE);
+	mpv_observe_property (this->m_handle, FPS_OBSERVER, "container-fps", MPV_FORMAT_DOUBLE);
+    }
+}
+
+std::optional<double> GLPlayer::skipTarget (const double position) const {
+    // jump when the next frame would be past the end
+    const double next = position + this->m_frameDuration * 0.99;
+
+    for (const auto& segment : this->m_segments) {
+	if (position < segment.start) {
+	    return segment.start;
+	}
+
+	if (!segment.end.has_value () || next < *segment.end) {
+	    return std::nullopt;
+	}
+    }
+
+    // past the last part the A-B loop goes back to the first
+    return std::nullopt;
 }
 
 void GLPlayer::seek (const double seconds) {
@@ -248,9 +289,38 @@ void GLPlayer::render () const {
 	    break;
 	}
 
+	if (event->event_id == MPV_EVENT_PLAYBACK_RESTART) {
+	    this->m_skipping = false;
+	    continue;
+	}
+
 	if (event->event_id == MPV_EVENT_PROPERTY_CHANGE) {
 	    const auto* property = static_cast<const mpv_event_property*> (event->data);
 
+	    if (event->reply_userdata == FPS_OBSERVER) {
+		const double fps
+		    = property->format == MPV_FORMAT_DOUBLE ? *static_cast<const double*> (property->data) : 0.0;
+
+		this->m_frameDuration = fps > 0.0 ? 1.0 / fps : 0.0;
+		continue;
+	    }
+
+	    if (event->reply_userdata == TIME_POS_OBSERVER) {
+		if (property->format != MPV_FORMAT_DOUBLE || this->m_skipping || !this->m_fileLoaded) {
+		    continue;
+		}
+
+		if (const auto target = this->skipTarget (*static_cast<const double*> (property->data))) {
+		    const std::string position = std::to_string (*target);
+		    const char* command[] = { "seek", position.c_str (), "absolute+exact", nullptr };
+
+		    this->m_skipping = true;
+		    mpv_command_async (this->m_handle, 0, command);
+		}
+
+		continue;
+	    }
+
 	    if (property->format == MPV_FORMAT_FLAG && std::string_view (property->name) == "eof-reached"
 		&& *static_cast<const int*> (property->data) && !this->m_loop) {
 		this->m_ended = true;
@@ -262,10 +332,13 @@ void GLPlayer::render () const {
 	if (event->event_id == MPV_EVENT_FILE_LOADED) {
 	    this->m_fileLoaded = true;
 
-	    if (this->dropLoopRangePastEnd ()) {
-		setPropertyAsync (this->m_handle, "ab-loop-a", "no");
-		setPropertyAsync (this->m_handle, "ab-loop-b", "no");
-		this->m_pendingSeek = 0.0;
+	    if (this->dropSegmentsPastEnd ()) {
+		const auto [a, b] = abLoopPoints (this->m_segments);
+
+		setPropertyAsync (this->m_handle, "ab-loop-a", a.c_str ());
+		setPropertyAsync (this->m_handle, "ab-loop-b", b.c_str ());
+		this->observePosition ();
+		this->m_pendingSeek = this->m_segments.empty () ? 0.0 : this->m_segments.front ().start;
 	    }
 
 	    if (this->m_pendingSeek.has_value ()) {
@@ -387,6 +460,7 @@ void GLPlayer::prepareGL () {
 void GLPlayer::init () {
     this->m_fileLoaded = false;
     this->m_ended = false;
+    this->m_skipping = false;
     this->m_handle = mpv_create ();
 
     if (this->m_handle == nullptr) {
@@ -434,11 +508,12 @@ void GLPlayer::init () {
     mpv_set_property_string (this->m_handle, "hwdec", "auto");
     mpv_set_property_string (this->m_handle, "loop", this->m_loop ? "inf" : "no");
     mpv_set_property_string (this->m_handle, "keep-open", "yes");
-    const auto [loopA, loopB] = abLoopPoints (this->m_loopStart, this->m_loopEnd);
+    const auto [loopA, loopB] = abLoopPoints (this->m_segments);
     mpv_set_property_string (this->m_handle, "ab-loop-a", loopA.c_str ());
     mpv_set_property_string (this->m_handle, "ab-loop-b", loopB.c_str ());
     mpv_set_property (this->m_handle, "volume", MPV_FORMAT_DOUBLE, &this->m_volume);
     mpv_set_property (this->m_handle, "speed", MPV_FORMAT_DOUBLE, &this->m_speed);
+    this->observePosition ();
 
     mpv_opengl_init_params gl_init_params { get_proc_address, this };
     // without the native display mpv can't import decoded frames into our GL context (VA-API dmabuf interop)
@@ -485,21 +560,24 @@ void GLPlayer::play () {
 
 	// if another player is already showing the same video (e.g. mirrored on another
 	// monitor), start around the same position instead of always restarting from zero
-	std::optional<double> start = this->m_loopStart;
+	std::optional<double> start;
+
+	if (!this->m_segments.empty ()) {
+	    start = this->m_segments.front ().start;
+	}
 
 	if (const auto it = s_activePlayers.find (path); it != s_activePlayers.end ()) {
 	    const double position = it->second->getPlaybackPosition ();
-	    const bool inRange = position >= this->m_loopStart.value_or (0.0)
-		&& (!this->m_loopEnd.has_value () || position < *this->m_loopEnd);
+	    const bool inPart = this->m_segments.empty ()
+		|| (position >= this->m_segments.front ().start && !this->skipTarget (position).has_value ()
+		    && (!this->m_segments.back ().end.has_value () || position < *this->m_segments.back ().end));
 
-	    if (position > 0.0 && inRange) {
+	    if (position > 0.0 && inPart) {
 		start = position;
 	    }
 	}
 
-	// a trimmed video has to begin at A, the first pass would play everything before it otherwise. Set as an
-	// option, not through loadfile's options argument: mpv 0.38 put a playlist index in front of it and
-	// rejects the old form
+	// start at the first part. An option, not a loadfile argument: mpv 0.38 changed that form
 	if (start.has_value ()) {
 	    mpv_set_property_string (this->m_handle, "start", std::to_string (*start).c_str ());
 	}

+ 15 - 7
src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.h

@@ -2,6 +2,7 @@
 
 #include "MemoryStreamProtocol.h"
 #include "WallpaperEngine/Render/RenderContext.h"
+#include "WallpaperEngine/VideoPlayback/VideoSegment.h"
 
 #include <GL/glew.h>
 #include <mpv/client.h>
@@ -48,10 +49,9 @@ public:
     void clearPaused ();
     void setLoop (bool loop);
     /**
-     * Plays only the part between start and end (seconds, either side open) over and over, through mpv's A-B loop.
-     * A change while playing restarts from start, the same range again changes nothing
+     * Loops only these sorted parts: mpv's A-B loop wraps, gaps are seeked over. A change restarts from the first part
      */
-    void setLoopRange (std::optional<double> start, std::optional<double> end);
+    void setSegments (const VideoSegments& segments);
     /** Jumps to a position in seconds, remembered and applied once the file has loaded if playback hasn't got that far
      */
     void seek (double seconds);
@@ -63,6 +63,7 @@ public:
     double getDuration () const;
 
     void render () const;
+    void requestRedraw () const { this->m_needsRedraw = true; }
 
     int getWidth () const;
     int getHeight () const;
@@ -75,8 +76,12 @@ public:
 
 private:
     void prepareGL ();
-    /** mpv seeks back to an A past the end over and over, so such a range is dropped once the length is known */
-    bool dropLoopRangePastEnd () const;
+    /** mpv keeps seeking back to an A past the end, so those parts are dropped once the length is known */
+    bool dropSegmentsPastEnd () const;
+    /** only while there are gaps */
+    void observePosition () const;
+    /** nullopt inside a part or past the last */
+    std::optional<double> skipTarget (double position) const;
     void init ();
     void play ();
     void setSource (MemoryStreamProtocolUniquePtr source);
@@ -104,8 +109,11 @@ protected:
     mutable bool m_fileLoaded = false;
     mutable bool m_ended = false;
     mutable std::optional<double> m_pendingSeek;
-    mutable std::optional<double> m_loopStart;
-    mutable std::optional<double> m_loopEnd;
+    mutable VideoSegments m_segments;
+    /** positions reported until it lands are stale */
+    mutable bool m_skipping = false;
+    /** 0 while unknown */
+    mutable double m_frameDuration = 0.0;
     std::optional<std::filesystem::path> m_file;
     std::optional<MemoryStreamProtocolUniquePtr> m_stream;
     uint32_t m_usageCount = 0;

+ 17 - 0
src/WallpaperEngine/VideoPlayback/VideoSegment.h

@@ -0,0 +1,17 @@
+#pragma once
+
+#include <optional>
+#include <vector>
+
+namespace WallpaperEngine::VideoPlayback {
+/** In seconds, no end means up to the end of the video */
+struct VideoSegment {
+    double start = 0.0;
+    std::optional<double> end;
+
+    bool operator== (const VideoSegment& other) const = default;
+};
+
+/** Sorted and non-overlapping, empty plays it all */
+using VideoSegments = std::vector<VideoSegment>;
+} // namespace WallpaperEngine::VideoPlayback

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.