From 6a593a94b2707618f057907e54c4e6be81be9b74 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:22:52 +0100 Subject: [PATCH 1/3] Reference count material var textures like the material system --- Source.MaterialSystem/Material.cs | 11 +++- Source.MaterialSystem/MaterialVar.cs | 65 ++++++++++++++++++- .../Surface/TextureDictionary.cs | 2 + 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/Source.MaterialSystem/Material.cs b/Source.MaterialSystem/Material.cs index 57d49666..8730f5c4 100644 --- a/Source.MaterialSystem/Material.cs +++ b/Source.MaterialSystem/Material.cs @@ -1204,7 +1204,12 @@ private void CleanUpMaterialProxy() { } private void CleanUpShaderParams() { - ShaderParams = null; + if (ShaderParams != null) { + for (int i = 0; i < VarCount; ++i) + MaterialVar.Destroy(ShaderParams[i]); + + ShaderParams = null; + } VarCount = 0; } @@ -1270,8 +1275,10 @@ public void SetNeedsWhiteLightmap(bool value) { public void DeleteIfUnreferenced() { if (RefCount > 0) return; - // todo: this has more, but i'm not sure if its needed? + MaterialVar.DeleteUnreferencedTextures(true); + Uncache(); materials.MaterialDict.RemoveMaterial(this); + MaterialVar.DeleteUnreferencedTextures(false); } public IMaterialVar? FindVarFast(ReadOnlySpan varName, ref TokenCache token) { diff --git a/Source.MaterialSystem/MaterialVar.cs b/Source.MaterialSystem/MaterialVar.cs index 1cb7e1f7..04c59f10 100644 --- a/Source.MaterialSystem/MaterialVar.cs +++ b/Source.MaterialSystem/MaterialVar.cs @@ -47,6 +47,30 @@ public static void EnableThreadedMaterialVarAccess(bool enable) { } } + static bool DeleteUnreferencedTexturesEnabled = false; + + public static void DeleteUnreferencedTextures(bool enable) => DeleteUnreferencedTexturesEnabled = enable; + + public static void Destroy(IMaterialVar? var) => (var as MaterialVar)?.CleanUpData(); + + void CleanUpData() { + switch (Type) { + case MaterialVarType.String: + StringVal = ""; + break; + + case MaterialVarType.Texture: + // garymcthack + if (TextureValue != null && !ITextureInternal.IsTextureInternalEnvCubemap(TextureValue)) { + TextureValue.DecrementReferenceCount(); + if (DeleteUnreferencedTexturesEnabled) + TextureValue.DeleteIfUnreferenced(); + TextureValue = null; + } + break; + } + } + MatCallQueue? GetCallQueue() => FakeMaterialVar ? null : materials?.GetRenderCallQueue(); MaterialVar? GetThreadedTempVar() { @@ -221,6 +245,7 @@ public override void SetFloatValue(float val) { FlushIfCurrentMaterial(); + CleanUpData(); VecVal[0] = VecVal[1] = VecVal[2] = VecVal[3] = val; IntVal = (int)val; Type = MaterialVarType.Float; @@ -245,6 +270,7 @@ public override void SetIntValue(int val) { FlushIfCurrentMaterial(); + CleanUpData(); IntVal = val; VecVal[0] = VecVal[1] = VecVal[2] = VecVal[3] = val; Type = MaterialVarType.Int; @@ -265,6 +291,7 @@ public override void SetMatrixValue(in Matrix4x4 matrix) { FlushIfCurrentMaterial(); + CleanUpData(); Matrix.Matrix = matrix; Type = MaterialVarType.Matrix; Matrix.IsIdent = matrix.IsIdentity; @@ -284,16 +311,28 @@ public override void SetStringValue(ReadOnlySpan val) { FlushIfCurrentMaterial(); + CleanUpData(); StringVal = new(val.SliceNullTerminatedString()); Type = MaterialVarType.String; VarChanged(); } public override void SetTextureValue(ITexture? texture) { +#if GMOD_DLL + if (texture == null) { + Warning("CMaterialVar::SetTextureValue is being set to NULL, falling back to error texture!\n"); + texture = materials?.GetErrorTexture(); + } +#endif + MatCallQueue? callQueue = GetCallQueue(); if (callQueue != null) { AllocThreadedTempVar()?.SetTextureValue(texture); - callQueue.QueueCall(static s => s.Var.SetTextureValue(s.Val), (Var: this, Val: texture)); + + // Matches DecrementReferenceCount in SetTextureValueQueued + texture?.IncrementReferenceCount(); + + callQueue.QueueCall(static s => s.Var.SetTextureValueQueued(s.Val), (Var: this, Val: texture)); return; } @@ -303,11 +342,24 @@ public override void SetTextureValue(ITexture? texture) { FlushIfCurrentMaterial(); + if (texture != null && !ITextureInternal.IsTextureInternalEnvCubemap(texture)) + texture.IncrementReferenceCount(); + + CleanUpData(); Type = MaterialVarType.Texture; TextureValue = texture; + IntVal = 0; + VecVal = default; VarChanged(); } + void SetTextureValueQueued(ITexture? texture) { + SetTextureValue(texture); + + // Matches IncrementReferenceCount in SetTextureValue + texture?.DecrementReferenceCount(); + } + public override void SetUndefined() { MatCallQueue? callQueue = GetCallQueue(); if (callQueue != null) { @@ -321,6 +373,7 @@ public override void SetUndefined() { FlushIfCurrentMaterial(); + CleanUpData(); Type = MaterialVarType.Undefined; VarChanged(); } @@ -342,7 +395,10 @@ public override void SetVecComponentValue(float val, int component) { FlushIfCurrentMaterial(); - Type = MaterialVarType.Vector; + if (Type != MaterialVarType.Vector) { + CleanUpData(); + Type = MaterialVarType.Vector; + } Assert(component <= 3); if (NumVectorComps < component) { @@ -371,7 +427,10 @@ void SetVecValueInternal(in Vector4 vec, int comps) { FlushIfCurrentMaterial(); - Type = MaterialVarType.Vector; + if (Type != MaterialVarType.Vector) { + CleanUpData(); + Type = MaterialVarType.Vector; + } Assert(comps <= 4); NumVectorComps = (byte)comps; VecVal = vec; diff --git a/Source.MaterialSystem/Surface/TextureDictionary.cs b/Source.MaterialSystem/Surface/TextureDictionary.cs index b97ffbeb..75347f8d 100644 --- a/Source.MaterialSystem/Surface/TextureDictionary.cs +++ b/Source.MaterialSystem/Surface/TextureDictionary.cs @@ -202,6 +202,7 @@ public void SetMaterial(ReadOnlySpan filename) { if (Material!.TryFindVar("$basetexture", out IMaterialVar? var) && var.IsTexture()) { Texture = var.GetTextureValue(); if (Texture != null) { + Texture.IncrementReferenceCount(); CreateRegen(Wide, Tall, Texture.GetImageFormat()); Texture.SetTextureRegenerator(Regen); } @@ -397,6 +398,7 @@ internal void ReferenceOtherProcedural(MatSystemTexture texture, IMaterial mater if (Material!.TryFindVar("$basetexture", out IMaterialVar? var) && var.IsTexture()) { Texture = var.GetTextureValue(); if (Texture != null) { + Texture.IncrementReferenceCount(); Assert(Texture == texture.Texture); Regen = texture.Regen; From 796f89654f6e1fad9c1411f7d2aa90ca572a5dd8 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:22:52 +0100 Subject: [PATCH 2/3] Pack font glyphs like GMod --- Source.Common/GUI/ISurface.cs | 2 + .../Surface/FontTextureCache.cs | 117 +++++++++++++ .../Surface/MatSystemSurface.cs | 3 + .../Surface/TexturePacker.cs | 159 ++++++++++++++++++ 4 files changed, 281 insertions(+) create mode 100644 Source.MaterialSystem/Surface/TexturePacker.cs diff --git a/Source.Common/GUI/ISurface.cs b/Source.Common/GUI/ISurface.cs index 4f8504e9..08c5220d 100644 --- a/Source.Common/GUI/ISurface.cs +++ b/Source.Common/GUI/ISurface.cs @@ -235,6 +235,8 @@ public interface ISurface void DrawGetColor(out Color color); void DrawGetTextColor(out Color color); void DrawGetTranslate(out int x, out int y); + void GMOD_ClearFontCache(); + void GMOD_FreeFontMaterials(); #endif } diff --git a/Source.MaterialSystem/Surface/FontTextureCache.cs b/Source.MaterialSystem/Surface/FontTextureCache.cs index 0f490470..d55d90ec 100644 --- a/Source.MaterialSystem/Surface/FontTextureCache.cs +++ b/Source.MaterialSystem/Surface/FontTextureCache.cs @@ -65,6 +65,9 @@ public class Page public short Tall; public short NextX; public short NextY; +#if GMOD_DLL + public TexturePacker? PackedFontTextureCache; +#endif } public class FontTextureCache @@ -202,19 +205,123 @@ public bool GetTextureForChars(IFont font, FontDrawType drawType, ReadOnlySpan TEXTURE_PAGE_WIDTH || charTall > TEXTURE_PAGE_HEIGHT) + return false; + + pageIndex = CurrPage; + + TexturePacker.Rect rect = new() { X = 0, Y = 0, Width = charWide, Height = charTall }; + int nodeIndex = -1; + if (pageIndex >= 0) + nodeIndex = PageList[(int)pageIndex].PackedFontTextureCache!.InsertRect(rect); + + if (nodeIndex == -1) { + // allocate a new page + pageIndex = PageList.Count; + Page newPage = new(); + PageList.Add(newPage); + + for (int i = 0; i < (int)FontDrawType.Count; ++i) + newPage.TextureID[i] = surface.CreateNewTextureID(true); + + newPage.PackedFontTextureCache = new TexturePacker(TEXTURE_PAGE_WIDTH, TEXTURE_PAGE_HEIGHT, 1); + nodeIndex = newPage.PackedFontTextureCache.InsertRect(rect); + if (nodeIndex == -1) { + PageList.RemoveAt((int)pageIndex); + Warning("Failed to AllocatePageForChar!\n"); + return false; + } + + CurrPage = pageIndex; + + Span textureName = stackalloc char[64]; + Span finalName = sprintf(textureName, "%s__font_page_%d").S(FontPageName).D(fontPageId); + ++fontPageId; + + ITexture pTexture = materials.CreateProceduralTexture( + finalName, + TEXTURE_GROUP_VGUI, + TEXTURE_PAGE_WIDTH, + TEXTURE_PAGE_HEIGHT, + ImageFormat.RGBA8888, + TextureFlags.ClampS | TextureFlags.ClampT | TextureFlags.NoMip | TextureFlags.NoLOD | TextureFlags.Procedural | TextureFlags.SingleCopy + ); + + CreateFontMaterials(ref newPage, pTexture); + pTexture.DecrementReferenceCount(); + + int nByteCount = TEXTURE_PAGE_WIDTH * TEXTURE_PAGE_HEIGHT * 4; + Span rgba = stackalloc byte[nByteCount]; + for (int i = 0; i < nByteCount; i += 4) { + rgba[i + 0] = 255; + rgba[i + 1] = 255; + rgba[i + 2] = 255; + rgba[i + 3] = 0; + } + + int typePageNonAdditive = (int)FontDrawType.NonAdditive - 1; + surface.DrawSetTextureRGBA(newPage.TextureID[typePageNonAdditive], rgba, TEXTURE_PAGE_WIDTH, TEXTURE_PAGE_HEIGHT, 0, false); + } + + TexturePacker packer = PageList[(int)pageIndex].PackedFontTextureCache!; + if (nodeIndex < 0 || nodeIndex > packer.MaxElementIndex) { + Warning("CTexturePacker::GetEntry Out of bounds!\n"); + nodeIndex = 0; + } + + TexturePacker.TreeEntry entry = packer.GetEntry(nodeIndex); + drawX = entry.Rc.X; + drawY = entry.Rc.Y; + twide = TEXTURE_PAGE_WIDTH; + ttall = TEXTURE_PAGE_HEIGHT; + return true; + } +#else bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int drawX, out int drawY, out int twide, out int ttall) { int nPageType = ComputePageType(charTall); if (nPageType < 0) { @@ -286,6 +393,8 @@ bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int CreateFontMaterials(ref newPage, pTexture); + pTexture.DecrementReferenceCount(); + // clear the texture from the inital checkerboard to black // allocate for 32bpp format int nByteCount = TEXTURE_PAGE_WIDTH * TEXTURE_PAGE_HEIGHT * 4; @@ -313,6 +422,8 @@ bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int page.NextX = (short)(nNextX + 1); return true; } +#endif + void CreateFontMaterials(ref Page page, ITexture fontTexture, bool bitmapFont = false) { // The normal material KeyValues vmtKeyValues = new KeyValues("UnlitGeneric"); @@ -357,6 +468,12 @@ int ComputePageType(int charTall) { } Dictionary CharCache = []; List PageList = []; +#if GMOD_DLL + nint CurrPage = -1; + readonly List FreeTextureIDs = []; + readonly string FontPageName = ""; +#else nint[] CurrPage = new nint[(int)Surface.FontPageSize.Count]; +#endif Dictionary FontPages = []; } diff --git a/Source.MaterialSystem/Surface/MatSystemSurface.cs b/Source.MaterialSystem/Surface/MatSystemSurface.cs index 3150167f..1a95d693 100644 --- a/Source.MaterialSystem/Surface/MatSystemSurface.cs +++ b/Source.MaterialSystem/Surface/MatSystemSurface.cs @@ -2144,6 +2144,9 @@ public void DrawGetTranslate(out int x, out int y) { x = TranslateX; y = TranslateY; } + + public void GMOD_ClearFontCache() => FontTextureCache.Clear(); + public void GMOD_FreeFontMaterials() => FontTextureCache.GMOD_FreeMaterials(); #endif public void PushFullscreenViewport() { diff --git a/Source.MaterialSystem/Surface/TexturePacker.cs b/Source.MaterialSystem/Surface/TexturePacker.cs new file mode 100644 index 00000000..8821aea4 --- /dev/null +++ b/Source.MaterialSystem/Surface/TexturePacker.cs @@ -0,0 +1,159 @@ +namespace Source.MaterialSystem.Surface; + +public class TexturePacker +{ + public struct Rect + { + public int X; + public int Y; + public int Width; + public int Height; + } + + public struct TreeEntry + { + public Rect Rc; + public bool InUse; + } + + struct Node + { + public TreeEntry Entry; + public int FirstChild; + public int NextSibling; + } + + const int InvalidIndex = -1; + + readonly List Tree = []; + int Root = InvalidIndex; + readonly int PageWidth; + readonly int PageHeight; + readonly int PixelGap; + + public TexturePacker(int texWidth, int texHeight, int pixelGap = 0) { + PageWidth = texWidth; + PageHeight = texHeight; + PixelGap = pixelGap; + + Clear(); + } + + public void Clear() { + Tree.Clear(); + + Node newEntry = default; + newEntry.Entry.Rc.X = 0; + newEntry.Entry.Rc.Y = 0; + newEntry.Entry.Rc.Width = PageWidth; + newEntry.Entry.Rc.Height = PageHeight; + newEntry.Entry.InUse = false; + newEntry.FirstChild = InvalidIndex; + newEntry.NextSibling = InvalidIndex; + + Root = Tree.Count; + Tree.Add(newEntry); + } + + public int MaxElementIndex => Tree.Count; + + public bool IsValidIndex(int nodeIndex) => nodeIndex >= 0 && nodeIndex < Tree.Count; + + public TreeEntry GetEntry(int nodeIndex) => Tree[nodeIndex].Entry; + + bool IsLeaf(int nodeIndex) { + int leftChildIndex = Tree[nodeIndex].FirstChild; + if (leftChildIndex == InvalidIndex) + return true; + else if (Tree[leftChildIndex].NextSibling == InvalidIndex) + return true; + + return false; + } + + int InsertChildAfter(int parent, int after, in Rect rc) { + Node node = default; + node.Entry.Rc = rc; + node.Entry.InUse = false; + node.FirstChild = InvalidIndex; + + int index = Tree.Count; + if (after == InvalidIndex) { + node.NextSibling = Tree[parent].FirstChild; + Tree.Add(node); + Node parentNode = Tree[parent]; + parentNode.FirstChild = index; + Tree[parent] = parentNode; + } + else { + node.NextSibling = Tree[after].NextSibling; + Tree.Add(node); + Node afterNode = Tree[after]; + afterNode.NextSibling = index; + Tree[after] = afterNode; + } + + return index; + } + + public int InsertRect(in Rect texRect, int nodeIndex = InvalidIndex) { + if (nodeIndex == InvalidIndex) + nodeIndex = Root; + + while (true) { + // if we are not a leaf + if (!IsLeaf(nodeIndex)) { + int leftChildIndex = Tree[nodeIndex].FirstChild; + // try inserting under left child + int newIndex = InsertRect(texRect, leftChildIndex); + if (IsValidIndex(newIndex)) + return newIndex; + + // no room, insert under right child + nodeIndex = Tree[leftChildIndex].NextSibling; + continue; + } + + // we are a leaf + Node node = Tree[nodeIndex]; + if (node.Entry.InUse) + return InvalidIndex; + + int availableWidth = node.Entry.Rc.Width; + int availableHeight = node.Entry.Rc.Height; + + if (texRect.Width > availableWidth || texRect.Height > availableHeight) + return InvalidIndex; + + if (texRect.Width == availableWidth && texRect.Height == availableHeight) { + node.Entry.InUse = true; + Tree[nodeIndex] = node; + return nodeIndex; + } + + // otherwise, gotta split this node and create some kids + // decide which way to split + int dw = availableWidth - texRect.Width; + int dh = availableHeight - texRect.Height; + + int leftChild; + if (dw > dh) { // split vertically + Rect left = new() { X = node.Entry.Rc.X, Y = node.Entry.Rc.Y, Width = texRect.Width, Height = availableHeight }; + leftChild = InsertChildAfter(nodeIndex, InvalidIndex, in left); + + Rect right = new() { X = node.Entry.Rc.X + texRect.Width + PixelGap, Y = node.Entry.Rc.Y, Width = dw - PixelGap, Height = availableHeight }; + InsertChildAfter(nodeIndex, leftChild, in right); + } + else { // split horizontally + Rect left = new() { X = node.Entry.Rc.X, Y = node.Entry.Rc.Y, Width = availableWidth, Height = texRect.Height }; + leftChild = InsertChildAfter(nodeIndex, InvalidIndex, in left); + + Rect right = new() { X = node.Entry.Rc.X, Y = node.Entry.Rc.Y + texRect.Height + PixelGap, Width = availableWidth, Height = dh - PixelGap }; + InsertChildAfter(nodeIndex, leftChild, in right); + } + + // insert into first child we created + nodeIndex = leftChild; + } + } +} From 297d5c041736668c17b1017bb6ca8c87b8c4fa66 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:26:38 -0800 Subject: [PATCH 3/3] resolve concerns --- Source.MaterialSystem/Material.cs | 3 ++- Source.MaterialSystem/MaterialVar.cs | 6 ++++-- Source.MaterialSystem/Surface/TextureDictionary.cs | 1 + Source.MaterialSystem/Texture.cs | 4 ++-- Source.MaterialSystem/TextureManager.cs | 6 +++--- 5 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Source.MaterialSystem/Material.cs b/Source.MaterialSystem/Material.cs index 8730f5c4..f5a24285 100644 --- a/Source.MaterialSystem/Material.cs +++ b/Source.MaterialSystem/Material.cs @@ -1273,8 +1273,9 @@ public void SetNeedsWhiteLightmap(bool value) { public void DecrementReferenceCount() => --RefCount; public void DeleteIfUnreferenced() { - if (RefCount > 0) + if (RefCount > 0 || IsErrorMaterialInternal()) return; + MaterialVar.DeleteUnreferencedTextures(true); Uncache(); materials.MaterialDict.RemoveMaterial(this); diff --git a/Source.MaterialSystem/MaterialVar.cs b/Source.MaterialSystem/MaterialVar.cs index 04c59f10..e4672cc7 100644 --- a/Source.MaterialSystem/MaterialVar.cs +++ b/Source.MaterialSystem/MaterialVar.cs @@ -330,7 +330,8 @@ public override void SetTextureValue(ITexture? texture) { AllocThreadedTempVar()?.SetTextureValue(texture); // Matches DecrementReferenceCount in SetTextureValueQueued - texture?.IncrementReferenceCount(); + if (texture != null && !ITextureInternal.IsTextureInternalEnvCubemap(texture)) + texture.IncrementReferenceCount(); callQueue.QueueCall(static s => s.Var.SetTextureValueQueued(s.Val), (Var: this, Val: texture)); return; @@ -357,7 +358,8 @@ void SetTextureValueQueued(ITexture? texture) { SetTextureValue(texture); // Matches IncrementReferenceCount in SetTextureValue - texture?.DecrementReferenceCount(); + if (texture != null && !ITextureInternal.IsTextureInternalEnvCubemap(texture)) + texture.DecrementReferenceCount(); } public override void SetUndefined() { diff --git a/Source.MaterialSystem/Surface/TextureDictionary.cs b/Source.MaterialSystem/Surface/TextureDictionary.cs index 75347f8d..afc96abf 100644 --- a/Source.MaterialSystem/Surface/TextureDictionary.cs +++ b/Source.MaterialSystem/Surface/TextureDictionary.cs @@ -354,6 +354,7 @@ internal void SetTextureRGBA(Span rgba, int wide, int tall, ImageFormat fo IMaterial pMaterial = materials.CreateMaterial(textureName, vmtTKeyValues); pMaterial.Refresh(); + pTexture.DecrementReferenceCount(); SetMaterial(pMaterial); InputTall = tall; diff --git a/Source.MaterialSystem/Texture.cs b/Source.MaterialSystem/Texture.cs index 6a3d6f33..d704a750 100644 --- a/Source.MaterialSystem/Texture.cs +++ b/Source.MaterialSystem/Texture.cs @@ -115,9 +115,9 @@ void StoreResourceData(IVTFTexture vtfTexture) { } } - public void IncrementReferenceCount() => ++RefCount; + public void IncrementReferenceCount() => Interlocked.Increment(ref RefCount); - public void DecrementReferenceCount() => --RefCount; + public void DecrementReferenceCount() => Interlocked.Decrement(ref RefCount); public bool IsCubeMap() => ((TextureFlags)Flags & TextureFlags.EnvMap) != 0; public bool IsError() => ((InternalTextureFlags)InternalFlags & InternalTextureFlags.Error) != 0; diff --git a/Source.MaterialSystem/TextureManager.cs b/Source.MaterialSystem/TextureManager.cs index be3d2922..f69ee8c0 100644 --- a/Source.MaterialSystem/TextureManager.cs +++ b/Source.MaterialSystem/TextureManager.cs @@ -48,8 +48,6 @@ public void Init() { whiteTexture = CreateProceduralTexture("white", TEXTURE_GROUP_OTHER, WHITE_TEXTURE_SIZE, WHITE_TEXTURE_SIZE, 1, ImageFormat.RGB888, TextureFlags.NoMip | TextureFlags.SingleCopy)!; color.R = color.G = color.B = color.A = 255; CreateSolidTexture(whiteTexture, color); - - } private void CreateCheckerboardTexture(ITexture errorTexture, int checkerSize, Color color1, Color color2) @@ -62,9 +60,11 @@ private void CreateSolidTexture(ITexture tex, Color color) name = name.SliceNullTerminatedString(); Texture newTexture = new(MaterialSystem); newTexture.InitProceduralTexture(name, textureGroup, w, h, d, imageFormat, flags, generator); + if (newTexture == null) return null; - + + newTexture.IncrementReferenceCount(); TextureList[newTexture.GetName().Hash()] = newTexture; ((ITextureInternal)newTexture).Download();