From b9d23fbc8c14a4e643af2ad3a9f4e6b0fac9749c Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sat, 22 Aug 2026 17:14:36 -0500 Subject: [PATCH] feat(texture): add Texture:SetMask(path) alpha-mask backport Backports the modern Texture:SetMask, clipping a texture to a mask's alpha shape - round portraits, round minimap buttons, and other shaped art. Vanilla 1.12 has no general masking (only the special-cased minimap disc). Mirrors the engine's own masked-quad draw (the minimap blip mask FUN_004eae10): a co-hook on the vertex-stream primitive FUN_0058a2a0 recovers the owning CSimpleTexture from the batch positions pointer (region = positions - OFF_SIMPLETEXTURE_CORNERS), and for a region with a mask set binds the mask on texture unit 1 with a MODULATE combiner, then re-runs the engine's own submit with uv1 = uv0 so unit 1 samples the mask at the texture's own coordinates. The unit is enabled/disabled around the draw so the mask never leaks onto other textures. A cold co-hook on the region ctor clears a region's mask on pooled reuse; a kill switch and SEH latch guard the draw path. The recipe was pinned by an in-game probe on the live GL backend and matched against FUN_004eae10; the full RE is in the "Texture masking" block in Offsets.h and the Mask.cpp header. Masks must be BLP or uncompressed 32-bit TGA with the shape in the alpha channel; two round masks ship in the client, other shapes are addon-supplied content. --- README.md | 2 +- docs/API.md | 40 +++++++ src/DllMain.cpp | 5 + src/Offsets.h | 69 ++++++++++++ src/texture/Mask.cpp | 244 +++++++++++++++++++++++++++++++++++++++++++ src/texture/Mask.h | 26 +++++ 6 files changed, 385 insertions(+), 1 deletion(-) create mode 100644 src/texture/Mask.cpp create mode 100644 src/texture/Mask.h diff --git a/README.md b/README.md index a34ae0b9..51a63d89 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Full per-function reference: **[docs/API.md](docs/API.md)**. | [Expansion](docs/API.md#expansion) | `ClassicExpansionAtLeast`, `ClassicExpansionAtMost`, `GetClassicExpansionLevel` | | [Faction](docs/API.md#faction) | `C_Reputation.GetFactionDataByIndex`, `C_Reputation.GetFactionStandings`, `C_Reputation.GetLastStandingChange`, `C_Reputation.GetWatchedFactionData`, `C_Reputation.SetWatchedFactionByID`, `GetFactionIDByIndex`, `GetFactionInfoByID`, `GetFactionParentID` | | [Focus](docs/API.md#focus) | `ClearFocus`, `FocusUnit` | -| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `fontstring:SetRotation`, `fontstring:GetRotation`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs` | +| [Frame](docs/API.md#frame) | `region:SetPoint("point")` (one-arg form), `region:SetSize`, `region:GetSize`, `region:IsMouseOver`, `region:GetRect`, `region:IsDragging`, `GetMouseFoci`, `frame:SetShown`, `fontstring:GetStringHeight`, `fontstring:GetUnboundedStringWidth`, `fontstring:GetWrappedWidth`, `fontstring:GetNumLines`, `fontstring:GetLineHeight`, `fontstring:IsTruncated`, `fontstring:SetMaxLines`, `fontstring:GetMaxLines`, `fontstring:SetFormattedText`, `texture:SetRotation`, `texture:GetRotation`, `texture:SetVertexOffset`, `texture:GetVertexOffset`, `texture:SetColorTexture`, `texture:SetMask`, `fontstring:SetRotation`, `fontstring:GetRotation`, `frame:SetResizeBounds`, `frame:HookScript`, `frame:IsEventRegistered`, `frame:GetEffectiveAlpha`, `frame:SetAttribute`, `frame:SetAttributeNoHandler`, `frame:ClearAttribute`, `frame:GetAttribute`, `OnAttributeChanged` (script), `SetModernScriptArgs`, `GetModernScriptArgs` | | [FriendList](docs/API.md#friendlist) | `C_FriendList.GetFriendInfo`, `C_FriendList.GetFriendInfoByIndex`, `C_FriendList.GetNumFriends`, `C_FriendList.GetNumOnlineFriends`, `C_FriendList.GetNumWhoResults`, `C_FriendList.GetWhoInfo`, `C_FriendList.IsFriend`, `C_FriendList.IsIgnored`, `C_FriendList.IsIgnoredByGuid`, `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName`, `C_FriendList.SetFriendNotes`, `C_FriendList.SetFriendNotesByIndex` | | [GameObject](docs/API.md#gameobject) | `C_GameObjectInfo.GetGameObjectInfoByID`, `C_GameObjectInfo.RequestLoadGameObjectByID`, `ClosestGameObjectPosition` | | [Glue](docs/API.md#glue) | `C_Glue.IsOnGlueScreen` | diff --git a/docs/API.md b/docs/API.md index 6806f097..37a65e16 100644 --- a/docs/API.md +++ b/docs/API.md @@ -178,6 +178,7 @@ build instructions. - [`fontstring:SetFormattedText(format [, ...])`](#fontstringsetformattedtextformat--) - [`texture:SetRotation(angle [, cx, cy])`](#texturesetrotationangle--cx-cy) - [`texture:SetVertexOffset(vertexIndex, offsetX, offsetY)`](#texturesetvertexoffsetvertexindex-offsetx-offsety) + - [`texture:SetMask(path)`](#texturesetmaskpath) - [`texture:SetColorTexture(colorR, colorG, colorB [, a])`](#texturesetcolortexturecolorr-colorg-colorb--a) - [`fontstring:SetRotation(angle [, cx, cy])`](#fontstringsetrotationangle--cx-cy) - [`frame:SetResizeBounds(minWidth, minHeight [, maxWidth, maxHeight])`](#framesetresizeboundsminwidth-minheight--maxwidth-maxheight) @@ -4379,6 +4380,45 @@ t:SetAllPoints(frame) t:SetColorTexture(0.1, 0.6, 1.0, 0.8) -- semi-transparent blue fill ``` +### `texture:SetMask(path)` + +Clips a texture to the shape of a mask. Later clients added this for round +portraits, round minimap buttons, and other shaped art. Vanilla has no general +masking — only the special-cased minimap. + +`path` is a mask texture. The mask's ALPHA channel is the shape: where the mask +is opaque the texture shows, where the mask is transparent the texture is +hidden. The mask is sampled across the texture's own texture coordinates, so it +lines up with the texture. Pass `nil` or `""` to remove the mask; the texture +returns to its full rectangle. + +A mask file must be one the client can load and must hold its shape in the alpha +channel: + +- A BLP, or an UNCOMPRESSED 32-bit TGA. The client cannot decode an + RLE-compressed TGA. +- The shape must be in the alpha channel, with white color. A mask that is fully + opaque does nothing; a mask whose shape is only in its color does not clip. +- Bottom-origin. A top-origin TGA loads upside down. + +Two masks ship in the client and need no file of your own: `Textures\MinimapMask` +(round) and `Interface\CharacterFrame\TempPortraitAlphaMask` (round portrait). +For any other shape, put your own mask texture in your addon folder and pass its +path, the same way you ship any custom texture. + +```lua +local t = frame:CreateTexture(nil, "ARTWORK") +t:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark") +t:SetMask("Textures\\MinimapMask") -- clip the icon to a circle +t:SetMask("Interface\\AddOns\\MyAddon\\round") -- or your own mask texture +t:SetMask(nil) -- remove the mask +``` + +> One difference from later clients: the mask follows the texture's own +> coordinates. If you crop the texture with `SetTexCoord`, the mask follows the +> cropped region rather than the full display area. For a normal, uncropped +> texture the two are the same. + ### `fontstring:SetRotation(angle [, cx, cy])` Rotates a FontString's text by `angle` radians. A positive angle turns the text diff --git a/src/DllMain.cpp b/src/DllMain.cpp index db97e0ab..84f2fb7f 100644 --- a/src/DllMain.cpp +++ b/src/DllMain.cpp @@ -22,6 +22,7 @@ #include "player/NameCache.h" #include "text/InlineTexture.h" #include "text/InlineTexturePool.h" +#include "texture/Mask.h" #include "texture/Transform.h" static Game::FrameScript_Initialize_t FrameScript_Initialize_o = nullptr; @@ -62,6 +63,9 @@ static bool __fastcall FrameScript_Initialize_h() { // reload destroys every addon texture and the region pool reuses their pointers. Texture::Transform::PrepareForReload(); + // Drop per-region texture masks for the same reason (SetMask). + Texture::Mask::PrepareForReload(); + // Drop pending character-dress jobs and their engine compositors — the // reload destroys every Model frame the jobs point at. Model::DisplayInfo::PrepareForReload(); @@ -103,6 +107,7 @@ static void __stdcall LoadGlueScriptFunctions_h() { Text::InlineTexture::PrepareForReload(); Text::InlineTexturePool::PrepareForReload(); Texture::Transform::PrepareForReload(); + Texture::Mask::PrepareForReload(); } // Every Lua-side `frame:RegisterEvent(...)` is a chance to claim a slot diff --git a/src/Offsets.h b/src/Offsets.h index 8206ccef..163c8dab 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -6909,6 +6909,75 @@ enum Offsets { // Script_Texture_SetTexture's own call site does. VAR_TEXTURE_BLEND_DEFAULT = 0x00878CF0, + // --- Texture masking (`Texture:SetMask` backport) --------------------------- + // Mirrors the engine's own canonical masked-quad draw: the minimap BLIP mask + // FUN_004eae10 (a sibling of the disc FUN_004ec440; both fed by the mask that + // Minimap:SetMaskTexture at 0x004EE4A0 loads into DAT_00bc7968). FUN_004eae10 + // is the exact template — bind base on unit 0, mask on unit 1, force each + // unit's combiner to MODULATE, submit with SEPARATE uv0/uv1, then unbind + // unit 1: + // GxRs(0x17, base); GxRs(0x1F, 1); // unit 0: bind + MODULATE preset + // GxRs(0x18, mask); GxRs(0x20, 1); // unit 1: bind + MODULATE preset + // FUN_0058a2a0(4, corners, …, uv0, uv1); // explicit second UV stream + // GxRs(0x18, 0); // unbind unit 1 + // Unit 1's MODULATE combiner multiplies the mask's alpha into the base's + // alpha, so a white-with-alpha mask clips the base to the mask's shape. + // + // The recipe was also pinned by an in-game probe (git history's + // MaskProbe.cpp) on the live GL backend — findings, load-bearing: + // * The COMBINER PRESET selectors are 0x1F+unit (GXRS_COMBINER0), value 1 = + // MODULATE/MODULATE (the .rdata preset tables at 0x0080a25c/0x0080a274). + // Binding a texture on unit 1 alone happens to give MODULATE by default + // on this GL backend, but FUN_004eae10 sets it EXPLICITLY — we mirror + // that (robust, not default-dependent). Do NOT confuse these with + // 0x2F/0x30/0x37/0x38 (texture-TRANSFORM/texgen): the probe wrote those + // and forced a texgen mode with no planes, so unit 1 sampled a single + // texel (the mask's alpha-0 corner) and the base vanished. + // * The SECOND vertex UV stream (uv1) DOES feed unit 1 on GL (FUN_004eae10 + // passes a distinct uv1 = this+0x50), so uv1 = uv0 makes unit 1 sample + // the mask at the base's own texcoords — exactly SetMask semantics. + // * The unit MUST be bracketed FUN_GX_TEXUNIT_ENABLE(1) ... FUN_GX_TEXUNIT + // _DISABLE(1); the disable is what stops the mask leaking onto every + // later textured draw (there is no Gx state push/pop around the region + // layer render's binds — units are managed explicitly). + GXRS_TEXTURE0 = 0x17, // texture bind, +unit (via FUN_GX_RS_SET_PTR) + GXRS_COMBINER0 = 0x1F, // combiner preset, +unit (via FUN_GX_RS_SET int form) + GXRS_COMBINE_MODULATE = 1, // preset value: COLOROP=MODULATE, ALPHAOP=MODULATE + // GxRs setters — `__fastcall(selector, value)`. The int form (0x00589E60) + // writes combiner presets and the like; the pointer form (0x00589E80) writes + // texture binds. + FUN_GX_RS_SET = 0x00589E60, + FUN_GX_RS_SET_PTR = 0x00589E80, + // Per-texture-unit enable/disable — `__fastcall(int unit)`. + FUN_GX_TEXUNIT_ENABLE = 0x0058B200, + FUN_GX_TEXUNIT_DISABLE = 0x0058B220, + // The vertex-stream primitive every textured region draws through + // (FUN_0076fb00 calls it per region). Decompiler signature (13 params): + // (count, positions, posStride, s3, s3Stride, colors, colorStride, drop8, + // drop9, uv0, uv0Stride, uv1, uv1Stride); RET 0x2C. The inner FUN_0058a3d0 + // builds an interleaved vertex from whichever of {s3, colors, uv0, uv1} are + // non-null — so uv1 is a real, buildable second UV slot no engine caller + // populates. `positions` for a region draw is the region's corner array + // (region + OFF_SIMPLETEXTURE_CORNERS), which is how the mask co-hook + // recovers the owning region: region = positions - OFF_SIMPLETEXTURE_CORNERS + // (verified: FUN_00772fd0 appends the batch entry with positions = + // region+0xD4, and FUN_0076fb00 forwards that pointer here). + FUN_GX_PRIM_STREAMS = 0x0058A2A0, + // Path → HTEXTURE loader trio (re-adds of the quad-era offsets removed in + // 56c2670, with the same derivations — see docs/InlineTextureEscapes.md): + // FUN_TEXTURE_LOAD_BY_PATH(path, &desc, flags, 0, 1) __fastcall, desc = + // the 5-dword {PTR_TEXLOAD_DESC_VTBL, 8, &self8, (&self8)|1, 0} on-stack + // node FUN_00770200 builds; flags via FUN_GX_TEXFLAGS_INIT(&flags, blend, + // 0,0, 0,0,0, 1, 0) __thiscall. Never returns null (engine substitutes a + // fallback texture). FUN_TEXTURE_GET_RENDERABLE(hTex, 1, 0) __fastcall + // returns the bindable CGxTex at [hTex+0x140] and drives the streaming + // load — calling it each frame IS the residency reference (what the + // minimap's masked draw does for its mask at 0x004ec65c). + FUN_TEXTURE_LOAD_BY_PATH = 0x00449D90, + PTR_TEXLOAD_DESC_VTBL = 0x007FFA10, + FUN_GX_TEXFLAGS_INIT = 0x0058A980, + FUN_TEXTURE_GET_RENDERABLE = 0x0044ACF0, + // --- Inline-texture positioning (slice 1: measure/emit integration) -------- // The 1.12 text pipeline builds a layout as a list of render "nodes" (one // per wrapped line); each node owns per-font-page glyph vertex batches and a diff --git a/src/texture/Mask.cpp b/src/texture/Mask.cpp new file mode 100644 index 00000000..856a71aa --- /dev/null +++ b/src/texture/Mask.cpp @@ -0,0 +1,244 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `Texture:SetMask(path)` — apply an alpha-mask texture to a Texture region, the +// way the modern client does (a white-with-alpha mask clips the texture to the +// mask's shape). 1.12 has no generic masking, only the special-cased minimap +// disc (Minimap:SetMaskTexture). This backports it to any Texture. +// +// Mechanism (pinned by an in-game probe on the live GL backend — see the +// Offsets.h "Texture masking" block for the full findings): every textured +// region draws through the vertex-stream primitive FUN_0058a2a0, which is +// passed the region's corner array as its `positions`. We co-hook it; when the +// positions belong to a region that has a mask set, we bind the mask on texture +// UNIT 1 (its default MODULATE combiner multiplies the mask's alpha into the +// base's alpha) and re-run the engine's own submit with the second UV stream +// set to the base's UVs, so unit 1 samples the mask at the texture's own +// coordinates. The unit is enabled/disabled around the draw so the mask never +// leaks onto other textures. No projection, vertex, or state setup of our own — +// we ride the engine's real draw and add only unit 1. +// +// A single fs-level Lua method (`SetMask`) stores the mask per region. A cold +// co-hook on the region ctor clears a region's mask when its pooled memory is +// reused, so a recycled region can never inherit a stale mask. Kill switch +// `_classicapi_TextureMaskEnable`; an SEH latch trips it on a draw fault. + +#include "Game.h" +#include "Offsets.h" + +#include + +#include +#include +#include + +namespace Texture::Mask { + +namespace { + +bool g_enabled = true; + +// A region's mask: the loaded HTEXTURE plus the path (so a re-SetMask with the +// same path is a cheap no-op and the value is inspectable). Keyed by the +// CSimpleTexture object pointer — the same pointer the Lua object resolves to +// AND the base of the corner array the draw hook recovers. +struct MaskEntry { + void *handle = nullptr; // HTEXTURE from the path loader (never null once set) + std::string path; +}; +std::unordered_map g_regionMask; + +// --- path -> HTEXTURE loader (mirrors FUN_00770200's SetTexture load) -------- + +using TexFlagsInit_t = void *(__thiscall *)(void *self, uint32_t blend, int, int, int, int, int, + uint32_t, int); +using TextureLoad_t = uint32_t(__fastcall *)(const char *path, void *desc, uint32_t flags, int, + int); +using GetRenderable_t = void *(__fastcall *)(void *hTex, int force, void *); + +struct TexLoadDesc { + void *vtbl; + int32_t field4; + void *self8; + uint32_t fieldC; + int32_t field10; +}; + +void *LoadByPath(const char *path) { + TexLoadDesc desc; + desc.vtbl = reinterpret_cast(Offsets::PTR_TEXLOAD_DESC_VTBL); + desc.field4 = 8; + desc.self8 = &desc.self8; + desc.fieldC = reinterpret_cast(&desc.self8) | 1u; + desc.field10 = 0; + uint32_t flags = 0; + const uint32_t blend = Game::Read(Offsets::VAR_TEXTURE_BLEND_DEFAULT); + reinterpret_cast(Offsets::FUN_GX_TEXFLAGS_INIT)(&flags, blend, 0, 0, 0, 0, 0, + 1, 0); + return reinterpret_cast(reinterpret_cast( + Offsets::FUN_TEXTURE_LOAD_BY_PATH)(path, &desc, flags, 0, 1)); +} + +// --- stream-primitive co-hook: apply the mask on unit 1 ---------------------- + +using GxRsSet_t = void(__fastcall *)(int selector, int value); +using GxRsSetPtr_t = void(__fastcall *)(int selector, const void *value); +using GxTexUnit_t = void(__fastcall *)(int unit); +using PrimStreams_t = void(__fastcall *)(int count, const void *pos, int posStride, const void *s3, + int s3Stride, const void *colors, int colorStride, + int drop8, int drop9, const void *uv0, int uv0Stride, + const void *uv1, int uv1Stride); + +PrimStreams_t g_primStreamsOriginal = nullptr; + +// Runs the engine's own submit with the mask bound on unit 1 and uv1 = uv0. +// Returns true if it drew; false if the mask isn't resident yet (caller draws +// the base unmasked this frame and retries next). POD-only body for the SEH +// wrapper. +bool MaskedDrawImpl(void *maskH, int count, const void *pos, int posStride, const void *s3, + int s3Stride, const void *colors, int colorStride, int drop8, int drop9, + const void *uv0, int uv0Stride) { + // Per-frame residency reference (force=1), exactly like the minimap's mask. + void *maskCGx = + reinterpret_cast(Offsets::FUN_TEXTURE_GET_RENDERABLE)(maskH, 1, nullptr); + if (maskCGx == nullptr) + return false; + auto rs = reinterpret_cast(Offsets::FUN_GX_RS_SET); + auto rsPtr = reinterpret_cast(Offsets::FUN_GX_RS_SET_PTR); + reinterpret_cast(Offsets::FUN_GX_TEXUNIT_ENABLE)(1); + rsPtr(Offsets::GXRS_TEXTURE0 + 1, maskCGx); // bind mask on unit 1 + // Force unit 1's combiner to MODULATE, exactly as the engine's own masked + // draw FUN_004eae10 does (GxRs(0x20, 1)) — robust vs. relying on the + // backend default. + rs(Offsets::GXRS_COMBINER0 + 1, Offsets::GXRS_COMBINE_MODULATE); + // uv1 = uv0 → unit 1 samples the mask at the base's texcoords. + g_primStreamsOriginal(count, pos, posStride, s3, s3Stride, colors, colorStride, drop8, drop9, + uv0, uv0Stride, uv0, uv0Stride); + reinterpret_cast(Offsets::FUN_GX_TEXUNIT_DISABLE)(1); // no leak onto later draws + return true; +} + +bool SafeMaskedDraw(void *maskH, int count, const void *pos, int posStride, const void *s3, + int s3Stride, const void *colors, int colorStride, int drop8, int drop9, + const void *uv0, int uv0Stride) { + __try { + return MaskedDrawImpl(maskH, count, pos, posStride, s3, s3Stride, colors, colorStride, + drop8, drop9, uv0, uv0Stride); + } __except (EXCEPTION_EXECUTE_HANDLER) { + g_enabled = false; // disable the feature for the session + return true; // may have partly drawn — don't double-draw + } +} + +void __fastcall PrimStreams_h(int count, const void *pos, int posStride, const void *s3, + int s3Stride, const void *colors, int colorStride, int drop8, + int drop9, const void *uv0, int uv0Stride, const void *uv1, + int uv1Stride) { + // Fast path: nothing masked, feature off, or not a plain textured quad. + if (g_enabled && !g_regionMask.empty() && count == 4 && uv0 != nullptr && uv1 == nullptr && + pos != nullptr) { + // The region draw passes the region's corner array as `positions`, so + // the owning region is positions - OFF_SIMPLETEXTURE_CORNERS. A false + // match needs a non-region draw whose positions pointer numerically + // equals a masked region's corner array — an exact-pointer collision, + // effectively impossible. + void *region = reinterpret_cast(reinterpret_cast(pos) - + Offsets::OFF_SIMPLETEXTURE_CORNERS); + auto it = g_regionMask.find(region); + if (it != g_regionMask.end() && it->second.handle != nullptr) { + if (SafeMaskedDraw(it->second.handle, count, pos, posStride, s3, s3Stride, colors, + colorStride, drop8, drop9, uv0, uv0Stride)) + return; + } + } + g_primStreamsOriginal(count, pos, posStride, s3, s3Stride, colors, colorStride, drop8, drop9, + uv0, uv0Stride, uv1, uv1Stride); +} + +static const Game::HookAutoRegister _primHook{Offsets::FUN_GX_PRIM_STREAMS, + reinterpret_cast(&PrimStreams_h), + reinterpret_cast(&g_primStreamsOriginal)}; + +// --- region ctor co-hook: drop a stale mask on pooled reuse ------------------ + +// __thiscall(mem, parent, layer, sublayer) -> region; dummy-EDX __fastcall. +using Ctor_t = void *(__fastcall *)(void *mem, void *edx, void *parent, int layer, int sublayer); +Ctor_t g_ctorOriginal = nullptr; + +void *__fastcall Ctor_h(void *mem, void *edx, void *parent, int layer, int sublayer) { + if (mem != nullptr) + g_regionMask.erase(mem); // a (re)constructed region owns no mask + return g_ctorOriginal(mem, edx, parent, layer, sublayer); +} + +static const Game::HookAutoRegister _ctorHook{Offsets::FUN_SIMPLETEXTURE_CTOR, + reinterpret_cast(&Ctor_h), + reinterpret_cast(&g_ctorOriginal)}; + +// --- Lua surface ------------------------------------------------------------- + +// texture:SetMask("path") sets the mask; SetMask(nil) / SetMask("") clears it. +int __fastcall Script_SetMask(void *L) { + void *region = Game::Lua::ResolveObject(L, 1); + if (region == nullptr) + return 0; + const char *path = (Game::Lua::GetTop(L) >= 2 && Game::Lua::Type(L, 2) == Game::Lua::TYPE_STRING) + ? Game::Lua::ToString(L, 2) + : nullptr; + if (path == nullptr || path[0] == '\0') { + g_regionMask.erase(region); + return 0; + } + auto it = g_regionMask.find(region); + if (it != g_regionMask.end() && it->second.path == path) + return 0; // unchanged + MaskEntry e; + e.handle = LoadByPath(path); // never null (engine substitutes a fallback) + e.path = path; + g_regionMask[region] = std::move(e); + return 0; +} + +// _classicapi_TextureMaskEnable([on]) -> enabled. Kill switch (also what the +// SEH latch trips on a draw fault). +int __fastcall Script_TextureMaskEnable(void *L) { + if (Game::Lua::GetTop(L) == 0) + g_enabled = true; + else + g_enabled = Game::Lua::ToBoolean(L, 1) != 0; + Game::Lua::PushBool(L, g_enabled); + return 1; +} + +const Game::Lua::FrameMethodEntry g_methods[] = { + {"SetMask", &Script_SetMask}, +}; + +void RegisterLuaFunctions() { + Game::Lua::RegisterFrameMethods( + reinterpret_cast(Offsets::VAR_TEXTURE_METHOD_REGISTRY), g_methods, + static_cast(sizeof(g_methods) / sizeof(g_methods[0]))); + Game::Lua::RegisterGlobalFunction("_classicapi_TextureMaskEnable", &Script_TextureMaskEnable); +} + +static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace + +void PrepareForReload() { + // /reload frees every region; forget the mask map so a recycled address + // can't be mistaken for a still-masked region before its ctor re-clears it. + g_regionMask.clear(); +} + +} // namespace Texture::Mask diff --git a/src/texture/Mask.h b/src/texture/Mask.h new file mode 100644 index 00000000..b1f3b82d --- /dev/null +++ b/src/texture/Mask.h @@ -0,0 +1,26 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +// Texture:SetMask backport — see texture/Mask.cpp. + +namespace Texture::Mask { + +// Called from the reload/teardown hooks (FrameScript_Initialize + world->glue): +// the reload destroys every addon Texture and the region pool reuses their +// pointers, so forget the per-region mask map. (The region ctor co-hook also +// clears an individual entry on reuse; this drops them all in one shot.) +void PrepareForReload(); + +} // namespace Texture::Mask